@dammers/use-signalr-svelte 0.4.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
@@ -1,207 +1,229 @@
1
- # @dammers/use-signalr-svelte
2
-
3
- A typed, reusable [SignalR](https://learn.microsoft.com/aspnet/core/signalr) provider and store set for Svelte, driven by your contract.
4
-
5
- [![npm](https://img.shields.io/npm/v/@dammers/use-signalr-svelte.svg)](https://www.npmjs.com/package/@dammers/use-signalr-svelte)
6
- ![types](https://img.shields.io/badge/types-included-blue.svg)
7
- [![license](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)
8
-
9
- ```ts
10
- const { provideSignalR, hubInvoke } = createSignalRClient({
11
- hubs: {
12
- "/hubs/chat": {
13
- methods: { SendMessage: method<[roomId: string, message: string]>() },
14
- },
15
- },
16
- });
17
- ```
18
-
19
- One factory call returns a provider function and a set of stores/functions, each typed against your hub contract. Event args, method args, and return values are all inferred from the config.
20
-
21
- Shared concepts (the contract, per-hub config, invoke retry, send vs invoke vs teardown) are covered in the [root README](https://github.com/DammersCode/use-signalr#readme). This document covers Svelte-specific install and usage.
22
-
23
- ## Install
24
-
25
- ```bash
26
- npm i @dammers/use-signalr-svelte @microsoft/signalr
27
- ```
28
-
29
- Requires `svelte` ≥ 4 and `@microsoft/signalr` ≥ 8 (tested against 8–10).
30
-
31
- ## Usage
32
-
33
- ### 1. Define your contract and create the client
34
-
35
- The **keys of `config.hubs` declare the hubs**. Each hub's `events` (what the server pushes to you) and `methods` (what you invoke) are declared inline with the `event()` and `method()` markers. This is the same contract shape as the React and Solid packages — only the provider and the functions below differ.
36
-
37
- ```ts
38
- // signalr.ts
39
- import { createSignalRClient, event, method } from "@dammers/use-signalr-svelte";
40
-
41
- export const {
42
- provideSignalR,
43
- getSignalR,
44
- onHubEvent,
45
- hubInvoke,
46
- hubSend,
47
- hubTeardown,
48
- hubStatus,
49
- onReconnected,
50
- keepHubAlive,
51
- } = createSignalRClient({
52
- hubs: {
53
- "/hubs/chat": {
54
- events: {
55
- ReceiveMessage: event<[user: string, message: string]>(),
56
- },
57
- methods: {
58
- SendMessage: method<[roomId: string, message: string]>(),
59
- JoinRoom: method<[roomId: string], { success: boolean }>(),
60
- },
61
- // per-hub config also goes here (see the root README)
62
- },
63
- },
64
- // global defaults (all optional):
65
- // lazy: false, reconnect: true, maxConnectRetries: 2, logLevel: LogLevel.Information
66
- });
67
- ```
68
-
69
- `event<Args>()` takes the handler's argument tuple. `method<Args, Return>()` takes the argument tuple and the resolved return type (default `void`).
70
-
71
- ### 2. Provide the connection in your root layout
72
-
73
- `provideSignalR` is a **function**, not a component — call it once in your root component's `<script>`, before any other function from this client. In SvelteKit, that means `+layout.svelte`.
74
-
75
- ```svelte
76
- <!-- +layout.svelte -->
77
- <script lang="ts">
78
- import { provideSignalR } from "$lib/signalr";
79
- import { accessToken, isAuthenticated } from "$lib/auth";
80
-
81
- let { children } = $props();
82
-
83
- provideSignalR({
84
- baseUrl: "https://api.example.com",
85
- accessTokenFactory: () => accessToken(),
86
- enabled: isAuthenticated, // optional, default true; can be a store or a plain value
87
- onError: (hub, err) => console.error(`Connection to ${hub} failed`, err),
88
- onStatusChange: (hub, status) => {
89
- if (status === "reconnecting") console.warn(`Reconnecting to ${hub}…`);
90
- },
91
- });
92
- </script>
93
-
94
- {@render children()}
95
- ```
96
-
97
- All connection work happens client-side only — `provideSignalR` is safe to call during SSR, since it defers building any connection until the component mounts in the browser.
98
-
99
- ### 3. Use the exported stores/functions — everything below is fully typed
100
-
101
- These work the same way as the React and Solid packages' hooks, with one difference: **`hubStatus` returns a Svelte store**, not a plain value. Read it with the `$` prefix in a component.
102
-
103
- ```svelte
104
- <script lang="ts">
105
- import { onDestroy } from "svelte";
106
- import {
107
- onHubEvent,
108
- hubInvoke,
109
- hubSend,
110
- hubTeardown,
111
- hubStatus,
112
- onReconnected,
113
- keepHubAlive,
114
- getSignalR,
115
- } from "$lib/signalr";
116
-
117
- // Listen to a server event — args inferred from the contract
118
- onHubEvent("/hubs/chat", "ReceiveMessage", (user, message) => {
119
- console.log(user, message);
120
- });
121
-
122
- // Invoke a server method — args + return inferred, waits for connection
123
- const sendMessage = hubInvoke("/hubs/chat", "SendMessage");
124
- await sendMessage(roomId, "hello"); // typed params, Promise<void>
125
-
126
- // Typed fire-and-forget — does not wait for connection; drops if not connected.
127
- // Safe to capture in onDestroy.
128
- const send = hubSend("/hubs/chat", "SendMessage");
129
- await send(roomId, "bye"); // typed args; Promise<boolean> (true = dispatched)
130
-
131
- // Reliable teardown — for a method called in onDestroy. Survives disposal,
132
- // queues while the hub connects (instead of dropping), and holds a lazy hub
133
- // open until it flushes. Best-effort: Promise<boolean> (true = dispatched).
134
- const joinRoom = hubInvoke("/hubs/chat", "JoinRoomAsync");
135
- const leaveRoom = hubTeardown("/hubs/chat", "LeaveRoomAsync");
136
- joinRoom(roomId);
137
- onDestroy(() => {
138
- leaveRoom(roomId);
139
- }); // lands even mid-connect or after disposal
140
-
141
- // Live connection status, as a Svelte store
142
- const status = hubStatus("/hubs/chat");
143
-
144
- // Re-sync after a reconnect, for example to refetch a query
145
- onReconnected("/hubs/chat", () => refetchMessages());
146
-
147
- // Keep a lazy hub connected for this component's lifetime without subscribing
148
- keepHubAlive("/hubs/chat");
149
-
150
- // Last resort: the raw HubConnection (prefer the typed stores/functions above)
151
- const { getConnection } = getSignalR();
152
- getConnection("/hubs/chat")?.send("SendMessage", roomId, "bye");
153
- </script>
154
-
155
- <p>Status: {$status}</p>
156
- ```
157
-
158
- ### Reliable join/leave (session pattern)
159
-
160
- A common pattern joins a session on init and leaves it in `onDestroy`.
161
-
162
- ```svelte
163
- <script lang="ts">
164
- import { onDestroy } from "svelte";
165
-
166
- const joinRoom = hubInvoke("/hubs/chat", "JoinRoomAsync");
167
- const leaveRoom = hubTeardown("/hubs/chat", "LeaveRoomAsync");
168
-
169
- joinRoom(roomId);
170
- onDestroy(() => {
171
- leaveRoom(roomId);
172
- });
173
- </script>
174
- ```
175
-
176
- A plain `hubInvoke` or `hubSend` makes the **leave** unreliable:
177
-
178
- - `hubInvoke` aborts in-flight calls on destroy, so a leave issued in `onDestroy` can be cancelled before it reaches the server.
179
- - `hubSend` drops silently if the hub is not `Connected`, so a leave that races a still-connecting socket (a fast route change, a rapid mount/unmount) is lost.
180
-
181
- `hubTeardown` fixes both problems. It:
182
-
183
- - **survives the calling component's disposal** — it runs detached and is never aborted,
184
- - **queues while connecting** — it waits up to `timeout` (default 10s) for the hub, then sends, instead of dropping,
185
- - **holds a lazy hub open** until the flush completes, even if the disposing component was its last consumer.
186
-
187
- It is best-effort and fire-and-forget: it resolves `true` once dispatched, `false` if the hub never connected in time, and never throws.
188
-
189
- > If your leave already uses `hubInvoke` and only needs to avoid the abort on destroy, pass `{ keepAliveOnUnmount: true }`. This covers the abort case but **not** the still-connecting race. For that race, use `hubTeardown`.
190
-
191
- ## Svelte-specific behavior
192
-
193
- - **`provideSignalR` is a function, not a component.** Call it directly in a `<script>` block during component initialization — most commonly your root layout — instead of wrapping markup in a provider component.
194
- - **`hubStatus` returns a `Readable<HubConnectionStatus>`.** Read the current value with `$status` in markup, or call `.subscribe(...)` directly for more control. This works the same in Svelte 4 and Svelte 5.
195
- - **`baseUrl`, `enabled`, and `connectionKey` accept a `MaybeReadable<T>`** — either a plain value or a Svelte store (`Readable<T>`). Passing a store makes the provider react to it: the connection rebuilds whenever the store's value changes, exactly as if you had passed a new plain value.
196
- - **Hub, event, method names and the options object are read once, during component init.** They are not reactive. If you need a different hub or method for different state, call the function again for each variant rather than expecting it to react to a changed argument.
197
- - **Handlers are live closures.** `onHubEvent`'s handler and `onReconnected`'s callback are captured once, but a normal JS closure sees current values from your component's scope. Memoization is never needed.
198
- - **Join/leave uses component init + `onDestroy`**, imported directly from `"svelte"`. `onDestroy` runs once when the component is destroyed.
199
- - **All connection work is client-side only.** `provideSignalR` defers connecting until the component mounts in the browser (`onMount`, which never runs during SSR), so it is safe to call from a SvelteKit `+layout.svelte` without any SSR guard.
200
-
201
- ## More
202
-
203
- Per-hub config, invoke retry semantics, the send/invoke/teardown comparison, and notes on token rotation live in the [root README](https://github.com/DammersCode/use-signalr#readme). Contributing setup lives in [CONTRIBUTING.md](https://github.com/DammersCode/use-signalr/blob/main/CONTRIBUTING.md).
204
-
205
- ## License
206
-
207
- MIT © [DammersCode](https://github.com/DammersCode)
1
+ # @dammers/use-signalr-svelte
2
+
3
+ A typed, reusable [SignalR](https://learn.microsoft.com/aspnet/core/signalr) provider and store set for Svelte, driven by your contract.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@dammers/use-signalr-svelte.svg)](https://www.npmjs.com/package/@dammers/use-signalr-svelte)
6
+ ![types](https://img.shields.io/badge/types-included-blue.svg)
7
+ [![license](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)
8
+
9
+ ```ts
10
+ const { provideSignalR, hubInvoke } = createSignalRClient({
11
+ hubs: {
12
+ "/hubs/chat": {
13
+ methods: { SendMessage: method<[roomId: string, message: string]>() },
14
+ },
15
+ },
16
+ });
17
+ ```
18
+
19
+ One factory call returns a provider function and a set of stores/functions, each typed against your hub contract. Event args, method args, and return values are all inferred from the config.
20
+
21
+ Shared concepts (the contract, per-hub config, invoke retry, send vs invoke vs teardown) are covered in the [root README](https://github.com/DammersCode/use-signalr#readme). This document covers Svelte-specific install and usage.
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ npm i @dammers/use-signalr-svelte @microsoft/signalr
27
+ ```
28
+
29
+ Requires `svelte` ≥ 4 and `@microsoft/signalr` ≥ 8 (tested against 8–10).
30
+
31
+ ## Usage
32
+
33
+ ### 1. Define your contract and create the client
34
+
35
+ The **keys of `config.hubs` declare the hubs**. Each hub's `events` (what the server pushes to you) and `methods` (what you invoke) are declared inline with the `event()` and `method()` markers. This is the same contract shape as the React and Solid packages — only the provider and the functions below differ.
36
+
37
+ ```ts
38
+ // signalr.ts
39
+ import { createSignalRClient, event, method } from "@dammers/use-signalr-svelte";
40
+
41
+ export const {
42
+ provideSignalR,
43
+ getSignalR,
44
+ onHubEvent,
45
+ hubInvoke,
46
+ hubSend,
47
+ hubTeardown,
48
+ hubStatus,
49
+ onReconnected,
50
+ keepHubAlive,
51
+ } = createSignalRClient({
52
+ hubs: {
53
+ "/hubs/chat": {
54
+ events: {
55
+ ReceiveMessage: event<[user: string, message: string]>(),
56
+ },
57
+ methods: {
58
+ SendMessage: method<[roomId: string, message: string]>(),
59
+ JoinRoom: method<[roomId: string], { success: boolean }>(),
60
+ },
61
+ // per-hub config also goes here (see the root README)
62
+ },
63
+ },
64
+ // global defaults (all optional):
65
+ // lazy: false, reconnect: true, maxConnectRetries: 2, logLevel: LogLevel.Information
66
+ });
67
+ ```
68
+
69
+ `event<Args>()` takes the handler's argument tuple. `method<Args, Return>()` takes the argument tuple and the resolved return type (default `void`).
70
+
71
+ ### 2. Provide the connection in your root layout
72
+
73
+ `provideSignalR` is a **function**, not a component — call it once in your root component's `<script>`, before any other function from this client. In SvelteKit, that means `+layout.svelte`.
74
+
75
+ ```svelte
76
+ <!-- +layout.svelte -->
77
+ <script lang="ts">
78
+ import { provideSignalR } from "$lib/signalr";
79
+ import { accessToken, isAuthenticated } from "$lib/auth";
80
+
81
+ let { children } = $props();
82
+
83
+ provideSignalR({
84
+ baseUrl: "https://api.example.com",
85
+ accessTokenFactory: () => accessToken(),
86
+ enabled: isAuthenticated, // optional, default true; can be a store or a plain value
87
+ onError: (hub, err) => console.error(`Connection to ${hub} failed`, err),
88
+ onStatusChange: (hub, status) => {
89
+ if (status === "reconnecting") console.warn(`Reconnecting to ${hub}…`);
90
+ },
91
+ });
92
+ </script>
93
+
94
+ {@render children()}
95
+ ```
96
+
97
+ All connection work happens client-side only — `provideSignalR` is safe to call during SSR, since it defers building any connection until the component mounts in the browser.
98
+
99
+ ### 3. Use the exported stores/functions — everything below is fully typed
100
+
101
+ These work the same way as the React and Solid packages' hooks, with one difference: **`hubStatus` returns a Svelte store**, not a plain value. Read it with the `$` prefix in a component.
102
+
103
+ ```svelte
104
+ <script lang="ts">
105
+ import { onDestroy } from "svelte";
106
+ import {
107
+ onHubEvent,
108
+ hubInvoke,
109
+ hubSend,
110
+ hubTeardown,
111
+ hubStatus,
112
+ onReconnected,
113
+ keepHubAlive,
114
+ getSignalR,
115
+ } from "$lib/signalr";
116
+
117
+ // Listen to a server event — args inferred from the contract
118
+ onHubEvent("/hubs/chat", "ReceiveMessage", (user, message) => {
119
+ console.log(user, message);
120
+ });
121
+
122
+ // Invoke a server method — args + return inferred, waits for connection
123
+ const sendMessage = hubInvoke("/hubs/chat", "SendMessage");
124
+ await sendMessage(roomId, "hello"); // typed params, Promise<void>
125
+
126
+ // Typed fire-and-forget — does not wait for connection; drops if not connected.
127
+ // Safe to capture in onDestroy.
128
+ const send = hubSend("/hubs/chat", "SendMessage");
129
+ await send(roomId, "bye"); // typed args; Promise<boolean> (true = dispatched)
130
+
131
+ // Reliable teardown — for a method called in onDestroy. Survives disposal,
132
+ // queues while the hub connects (instead of dropping), and holds a lazy hub
133
+ // open until it flushes. Best-effort: Promise<boolean> (true = dispatched).
134
+ const joinRoom = hubInvoke("/hubs/chat", "JoinRoomAsync");
135
+ const leaveRoom = hubTeardown("/hubs/chat", "LeaveRoomAsync");
136
+ joinRoom(roomId);
137
+ onDestroy(() => {
138
+ leaveRoom(roomId);
139
+ }); // lands even mid-connect or after disposal
140
+
141
+ // Live connection status, as a Svelte store
142
+ const status = hubStatus("/hubs/chat");
143
+
144
+ // Re-sync after a reconnect, for example to refetch a query
145
+ onReconnected("/hubs/chat", () => refetchMessages());
146
+
147
+ // Keep a lazy hub connected for this component's lifetime without subscribing
148
+ keepHubAlive("/hubs/chat");
149
+
150
+ // Last resort: the raw HubConnection (prefer the typed stores/functions above)
151
+ const { getConnection } = getSignalR();
152
+ getConnection("/hubs/chat")?.send("SendMessage", roomId, "bye");
153
+ </script>
154
+
155
+ <p>Status: {$status}</p>
156
+ ```
157
+
158
+ ### Reliable join/leave (session pattern)
159
+
160
+ A common pattern joins a session on init and leaves it in `onDestroy`.
161
+
162
+ ```svelte
163
+ <script lang="ts">
164
+ import { onDestroy } from "svelte";
165
+
166
+ const joinRoom = hubInvoke("/hubs/chat", "JoinRoomAsync");
167
+ const leaveRoom = hubTeardown("/hubs/chat", "LeaveRoomAsync");
168
+
169
+ joinRoom(roomId);
170
+ onDestroy(() => {
171
+ leaveRoom(roomId);
172
+ });
173
+ </script>
174
+ ```
175
+
176
+ A plain `hubInvoke` or `hubSend` makes the **leave** unreliable:
177
+
178
+ - `hubInvoke` aborts in-flight calls on destroy, so a leave issued in `onDestroy` can be cancelled before it reaches the server.
179
+ - `hubSend` drops silently if the hub is not `Connected`, so a leave that races a still-connecting socket (a fast route change, a rapid mount/unmount) is lost.
180
+
181
+ `hubTeardown` fixes both problems. It:
182
+
183
+ - **survives the calling component's disposal** — it runs detached and is never aborted,
184
+ - **queues while connecting** — it waits up to `timeout` (default 10s) for the hub, then sends, instead of dropping,
185
+ - **holds a lazy hub open** until the flush completes, even if the disposing component was its last consumer.
186
+
187
+ It is best-effort and fire-and-forget: it resolves `true` once dispatched, `false` if the hub never connected in time, and never throws.
188
+
189
+ > If your leave already uses `hubInvoke` and only needs to avoid the abort on destroy, pass `{ keepAliveOnUnmount: true }`. This covers the abort case but **not** the still-connecting race. For that race, use `hubTeardown`.
190
+
191
+ ## Lazy hubs and `graceMs`
192
+
193
+ Set `lazy: true` on a hub to connect it only when the first store or function for that hub is set up. Consumers are ref-counted.
194
+
195
+ After the last consumer is destroyed, the connection stays open for `graceMs` milliseconds. If a new consumer appears inside that window, the connection stays. The default is `0`.
196
+
197
+ ```ts
198
+ createSignalRClient({
199
+ hubs: {
200
+ "/hubs/presence": { lazy: true, graceMs: 5000 },
201
+ },
202
+ });
203
+ ```
204
+
205
+ ## `InvokeError`
206
+
207
+ `hubInvoke` 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).
208
+
209
+ `InvokeError` is thrown only when you set `retries` above `0`. With the default `retries: 0`, the raw server error propagates unchanged.
210
+
211
+ The `timeout` option bounds only the wait for a connected hub before dispatch. SignalR cannot cancel an invocation after dispatch.
212
+
213
+ ## Svelte-specific behavior
214
+
215
+ - **`provideSignalR` is a function, not a component.** Call it directly in a `<script>` block during component initialization — most commonly your root layout — instead of wrapping markup in a provider component.
216
+ - **`hubStatus` returns a `Readable<HubConnectionStatus>`.** Read the current value with `$status` in markup, or call `.subscribe(...)` directly for more control. This works the same in Svelte 4 and Svelte 5.
217
+ - **`baseUrl`, `enabled`, and `connectionKey` accept a `MaybeReadable<T>`** — either a plain value or a Svelte store (`Readable<T>`). Passing a store makes the provider react to it: the connection rebuilds whenever the store's value changes, exactly as if you had passed a new plain value.
218
+ - **Hub, event, method names and the options object are read once, during component init.** They are not reactive. If you need a different hub or method for different state, call the function again for each variant rather than expecting it to react to a changed argument.
219
+ - **Handlers are live closures.** `onHubEvent`'s handler and `onReconnected`'s callback are captured once, but a normal JS closure sees current values from your component's scope. Memoization is never needed.
220
+ - **Join/leave uses component init + `onDestroy`**, imported directly from `"svelte"`. `onDestroy` runs once when the component is destroyed.
221
+ - **All connection work is client-side only.** `provideSignalR` defers connecting until the component mounts in the browser (`onMount`, which never runs during SSR), so it is safe to call from a SvelteKit `+layout.svelte` without any SSR guard.
222
+
223
+ ## More
224
+
225
+ Per-hub config, invoke retry semantics, the send/invoke/teardown comparison, and notes on token rotation live in the [root README](https://github.com/DammersCode/use-signalr#readme). Contributing setup lives in [CONTRIBUTING.md](https://github.com/DammersCode/use-signalr/blob/main/CONTRIBUTING.md).
226
+
227
+ ## License
228
+
229
+ MIT © [DammersCode](https://github.com/DammersCode)
@@ -13,13 +13,13 @@ export declare function createSignalRClient<const H extends Record<HubString, Hu
13
13
  * `accessTokenFactory`, and gate them with `enabled`. All connection work
14
14
  * happens client-side only, so this is safe to call during SSR.
15
15
  */
16
- provideSignalR: (props: import("./types").SignalRProviderProps) => void;
16
+ provideSignalR: (props: import("./types.js").SignalRProviderProps) => void;
17
17
  /**
18
18
  * Escape hatch to the raw SignalR context (`getConnection`, `getStatus`,
19
19
  * `isHubConnected`, and more). Prefer the typed stores/functions below.
20
20
  * Use this only for the underlying `HubConnection` or a point read.
21
21
  */
22
- getSignalR: () => import("./types").SignalRContextValue<InferContract<H>>;
22
+ getSignalR: () => import("./types.js").SignalRContextValue<InferContract<H>>;
23
23
  /**
24
24
  * Keeps a (possibly lazy) hub connected for the component's lifetime,
25
25
  * without subscribing to events or status. Acquires at component init,
@@ -1,6 +1,6 @@
1
1
  import { hubKeys, resolveHubConfig } from "@dammers/use-signalr-core";
2
- import { createSignalRProvider } from "./internal/create-provider";
3
- import { createSignalRHooks } from "./internal/create-hooks";
2
+ import { createSignalRProvider } from "./internal/create-provider.js";
3
+ import { createSignalRHooks } from "./internal/create-hooks.js";
4
4
  /**
5
5
  * Creates a fully-typed SignalR client. Returns a provider function and a set
6
6
  * of stores/functions, typed against the contract inferred from
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 { MaybeReadable, SignalRProviderProps, SignalRContextValue } from "./types";
5
+ export type { MaybeReadable, 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 { Readable } from "svelte/store";
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 functions bound to one client's context. */
5
5
  export declare function createSignalRHooks<T extends SignalRContract>(contextKey: symbol): {
6
6
  getSignalR: () => SignalRContextValue<T>;
@@ -1,5 +1,5 @@
1
1
  import { getContext, onDestroy } from "svelte";
2
- import { createInvoker, createSender, createTeardownSender } from "@dammers/use-signalr-core";
2
+ import { createAbortScope, createInvoker, createSender, createTeardownSender, } from "@dammers/use-signalr-core";
3
3
  /** Builds the functions bound to one client's context. */
4
4
  export function createSignalRHooks(contextKey) {
5
5
  /**
@@ -126,14 +126,12 @@ export function createSignalRHooks(contextKey) {
126
126
  function hubInvoke(hub, method, options) {
127
127
  const { waitForConnection, getConnection } = getSignalR();
128
128
  keepHubAlive(hub);
129
- let abort = null;
129
+ const scope = createAbortScope();
130
130
  onDestroy(() => {
131
131
  if (!options?.keepAliveOnUnmount)
132
- abort?.abort();
133
- });
134
- return createInvoker({ waitForConnection, getConnection }, hub, method, () => options, (ac) => {
135
- abort = ac;
132
+ scope.abortAll();
136
133
  });
134
+ return createInvoker({ waitForConnection, getConnection }, hub, method, () => options, scope.track, scope.untrack);
137
135
  }
138
136
  /**
139
137
  * Returns a stable, typed fire-and-forget sender. Unlike {@link hubInvoke},
@@ -1,4 +1,4 @@
1
1
  import type { HubString, ResolvedHubConfig, SignalRContract } from "@dammers/use-signalr-core";
2
- import type { SignalRProviderProps } from "../types";
2
+ import type { SignalRProviderProps } from "../types.js";
3
3
  /** Builds the `provideSignalR` function bound to one client's context. */
4
4
  export declare function createSignalRProvider<T extends SignalRContract>(contextKey: symbol, hubs: Array<keyof T & HubString>, resolve: (hub: keyof T & HubString) => ResolvedHubConfig): (props: SignalRProviderProps) => void;
@@ -1,6 +1,6 @@
1
1
  import { setContext, onMount } from "svelte";
2
2
  import { derived, readable } from "svelte/store";
3
- import { createStatusStore } from "../status-store";
3
+ import { createStatusStore } from "../status-store.js";
4
4
  import { createSignalRSession } from "@dammers/use-signalr-core";
5
5
  function isReadable(value) {
6
6
  return (typeof value === "object" &&
@@ -26,7 +26,7 @@ export function createSignalRProvider(contextKey, hubs, resolve) {
26
26
  const baseUrl$ = toReadable(props.baseUrl);
27
27
  const enabled$ = toReadable(props.enabled ?? true);
28
28
  const connectionKey$ = toReadable(props.connectionKey);
29
- const identity$ = derived([baseUrl$, enabled$, connectionKey$], ([baseUrl, enabled]) => [baseUrl, enabled]);
29
+ const identity$ = derived([baseUrl$, enabled$, connectionKey$], ([baseUrl, enabled, connectionKey]) => [baseUrl, enabled, connectionKey]);
30
30
  // All connection work is client-side only: onMount never runs during SSR.
31
31
  onMount(() => {
32
32
  const unsubscribe = identity$.subscribe(([baseUrl, enabled]) => {
package/dist/types.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Readable } from "svelte/store";
2
2
  import type { SignalRContract, SignalRProviderPropsBase, SignalRContextValueBase, HubString } from "@dammers/use-signalr-core";
3
- import type { StatusStore } from "./status-store";
3
+ import type { StatusStore } from "./status-store.js";
4
4
  /** A value that can also be supplied as a store, to make the provider react to it. */
5
5
  export type MaybeReadable<T> = T | Readable<T>;
6
6
  export type SignalRProviderProps = Omit<SignalRProviderPropsBase<never>, "children" | "baseUrl" | "enabled" | "connectionKey"> & {
package/package.json CHANGED
@@ -1,60 +1,61 @@
1
- {
2
- "name": "@dammers/use-signalr-svelte",
3
- "version": "0.4.0",
4
- "description": "Fully-typed multi-hub SignalR provider + stores for Svelte: auto-reconnect, invoke retry, lazy hubs, live status.",
5
- "author": "Dammers",
6
- "license": "MIT",
7
- "repository": {
8
- "type": "git",
9
- "url": "git+https://github.com/DammersCode/use-signalr.git",
10
- "directory": "packages/svelte"
11
- },
12
- "homepage": "https://github.com/DammersCode/use-signalr/tree/main/packages/svelte#readme",
13
- "bugs": "https://github.com/DammersCode/use-signalr/issues",
14
- "keywords": [
15
- "svelte",
16
- "sveltekit",
17
- "signalr",
18
- "stores",
19
- "typescript",
20
- "realtime",
21
- "websocket"
22
- ],
23
- "engines": {
24
- "node": ">=18"
25
- },
26
- "type": "module",
27
- "sideEffects": false,
28
- "main": "./dist/index.js",
29
- "types": "./dist/index.d.ts",
30
- "exports": {
31
- ".": {
32
- "types": "./dist/index.d.ts",
33
- "import": "./dist/index.js"
34
- }
35
- },
36
- "files": [
37
- "dist"
38
- ],
39
- "publishConfig": {
40
- "access": "public"
41
- },
42
- "scripts": {
43
- "build": "tsc -p tsconfig.build.json",
44
- "typecheck": "tsc --noEmit",
45
- "test": "vitest run"
46
- },
47
- "dependencies": {
48
- "@dammers/use-signalr-core": "0.4.0"
49
- },
50
- "peerDependencies": {
51
- "@microsoft/signalr": ">=8",
52
- "svelte": ">=4"
53
- },
54
- "devDependencies": {
55
- "@microsoft/signalr": ">=8",
56
- "svelte": "^5.0.0",
57
- "@sveltejs/vite-plugin-svelte": "^7.3.0",
58
- "@testing-library/svelte": "^5.4.2"
59
- }
60
- }
1
+ {
2
+ "name": "@dammers/use-signalr-svelte",
3
+ "version": "0.5.0",
4
+ "description": "Fully-typed multi-hub SignalR provider + stores for Svelte: auto-reconnect, invoke retry, lazy hubs, live status.",
5
+ "author": "Dammers",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/DammersCode/use-signalr.git",
10
+ "directory": "packages/svelte"
11
+ },
12
+ "homepage": "https://github.com/DammersCode/use-signalr/tree/main/packages/svelte#readme",
13
+ "bugs": "https://github.com/DammersCode/use-signalr/issues",
14
+ "keywords": [
15
+ "svelte",
16
+ "sveltekit",
17
+ "signalr",
18
+ "stores",
19
+ "typescript",
20
+ "realtime",
21
+ "websocket"
22
+ ],
23
+ "engines": {
24
+ "node": ">=18"
25
+ },
26
+ "type": "module",
27
+ "sideEffects": false,
28
+ "main": "./dist/index.js",
29
+ "types": "./dist/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js"
34
+ }
35
+ },
36
+ "files": [
37
+ "dist"
38
+ ],
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "scripts": {
43
+ "prebuild": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
44
+ "build": "tsc -p tsconfig.build.json",
45
+ "typecheck": "tsc --noEmit",
46
+ "test": "vitest run"
47
+ },
48
+ "dependencies": {
49
+ "@dammers/use-signalr-core": "0.5.0"
50
+ },
51
+ "peerDependencies": {
52
+ "@microsoft/signalr": ">=8",
53
+ "svelte": ">=4"
54
+ },
55
+ "devDependencies": {
56
+ "@microsoft/signalr": ">=8",
57
+ "svelte": "^5.0.0",
58
+ "@sveltejs/vite-plugin-svelte": "^7.3.0",
59
+ "@testing-library/svelte": "^5.4.2"
60
+ }
61
+ }