@dammers/use-signalr-svelte 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 +29 -201
- package/dist/create-signalr-client.d.ts +41 -31
- package/dist/create-signalr-client.js +40 -30
- package/dist/index.d.ts +3 -4
- package/dist/index.js +1 -1
- package/dist/internal/create-hooks.d.ts +5 -6
- package/dist/internal/create-hooks.js +29 -149
- package/dist/internal/create-provider.d.ts +1 -1
- package/dist/internal/create-provider.js +27 -8
- package/dist/status-store.d.ts +1 -5
- package/dist/status-store.js +4 -13
- package/dist/types.d.ts +7 -1
- package/package.json +12 -10
package/README.md
CHANGED
|
@@ -1,229 +1,57 @@
|
|
|
1
1
|
# @dammers/use-signalr-svelte
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Context and stores for typed [SignalR](https://learn.microsoft.com/aspnet/core/signalr) in Svelte. Part of [use-signalr](https://use-signalr.vercel.app).
|
|
4
4
|
|
|
5
5
|
[](https://www.npmjs.com/package/@dammers/use-signalr-svelte)
|
|
6
|
-
](./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.
|
|
6
|
+
[](https://github.com/DammersCode/use-signalr/blob/main/LICENSE)
|
|
22
7
|
|
|
23
8
|
## Install
|
|
24
9
|
|
|
25
10
|
```bash
|
|
26
|
-
npm
|
|
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
|
-
});
|
|
11
|
+
npm install @dammers/use-signalr-svelte @microsoft/signalr
|
|
67
12
|
```
|
|
68
13
|
|
|
69
|
-
|
|
14
|
+
It needs Svelte ^5.15, `@microsoft/signalr` ^8 || ^9 || ^10 || ^11, and Node 20.19 or later.
|
|
70
15
|
|
|
71
|
-
|
|
16
|
+
## Example
|
|
72
17
|
|
|
73
|
-
|
|
18
|
+
This file declares a hub, connects it, and reads a typed method result:
|
|
74
19
|
|
|
20
|
+
<!-- hero:svelte:start -->
|
|
75
21
|
```svelte
|
|
76
|
-
|
|
77
|
-
|
|
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.
|
|
22
|
+
<script module lang="ts">
|
|
23
|
+
import { createSignalRClient, method } from "@dammers/use-signalr-svelte";
|
|
102
24
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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);
|
|
25
|
+
export const { provideSignalR, hubInvoke } = createSignalRClient({
|
|
26
|
+
hubs: {
|
|
27
|
+
"/hubs/rooms": {
|
|
28
|
+
methods: { GetHistory: method<[roomId: string], { text: string }[]>() },
|
|
29
|
+
},
|
|
30
|
+
},
|
|
120
31
|
});
|
|
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
32
|
</script>
|
|
154
33
|
|
|
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
34
|
<script lang="ts">
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
const joinRoom = hubInvoke("/hubs/chat", "JoinRoomAsync");
|
|
167
|
-
const leaveRoom = hubTeardown("/hubs/chat", "LeaveRoomAsync");
|
|
35
|
+
provideSignalR({ baseUrl: "https://api.example.com", accessTokenFactory: () => "token" });
|
|
168
36
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
});
|
|
37
|
+
const getHistory = hubInvoke("/hubs/rooms", "GetHistory");
|
|
38
|
+
let count = $state(0);
|
|
39
|
+
const load = () => getHistory("general").then((m) => (count = m.length)).catch(console.error);
|
|
173
40
|
</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
41
|
|
|
187
|
-
|
|
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
|
-
});
|
|
42
|
+
<button onclick={load}>{count} messages</button>
|
|
203
43
|
```
|
|
44
|
+
<!-- hero:svelte:end -->
|
|
204
45
|
|
|
205
|
-
##
|
|
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
|
|
46
|
+
## Documentation
|
|
224
47
|
|
|
225
|
-
|
|
48
|
+
- [Quick start](https://use-signalr.vercel.app/docs/svelte/quick-start)
|
|
49
|
+
- [Provider setup](https://use-signalr.vercel.app/docs/svelte/concepts/provider)
|
|
50
|
+
- [Events](https://use-signalr.vercel.app/docs/svelte/concepts/events) and [calls](https://use-signalr.vercel.app/docs/svelte/concepts/calls)
|
|
51
|
+
- [Connection status](https://use-signalr.vercel.app/docs/svelte/concepts/connection-status) and [recovery](https://use-signalr.vercel.app/docs/svelte/concepts/recovery)
|
|
52
|
+
- [API reference](https://use-signalr.vercel.app/docs/svelte/reference/api)
|
|
53
|
+
- [Troubleshooting](https://use-signalr.vercel.app/docs/svelte/reference/troubleshooting)
|
|
226
54
|
|
|
227
55
|
## License
|
|
228
56
|
|
|
229
|
-
MIT © [DammersCode](https://github.com/DammersCode)
|
|
57
|
+
[MIT](https://github.com/DammersCode/use-signalr/blob/main/LICENSE) © [DammersCode](https://github.com/DammersCode)
|
|
@@ -1,66 +1,76 @@
|
|
|
1
1
|
import type { HubDef, HubString, InferContract, SignalRClientConfig } from "@dammers/use-signalr-core";
|
|
2
2
|
/**
|
|
3
|
-
* Creates a
|
|
3
|
+
* Creates a typed SignalR client. Returns a provider function and a set
|
|
4
4
|
* of stores/functions, typed against the contract inferred from
|
|
5
5
|
* `config.hubs`: the keys declare the hubs, and each hub's
|
|
6
6
|
* `event()`/`method()` declarations declare its events and methods.
|
|
7
7
|
*/
|
|
8
8
|
export declare function createSignalRClient<const H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>): {
|
|
9
9
|
/**
|
|
10
|
-
* Builds
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
10
|
+
* Builds the session and sets the context. Call it once in your root
|
|
11
|
+
* component's script, before any other function, for example in
|
|
12
|
+
* `+layout.svelte` in SvelteKit. Pass `baseUrl` and `accessTokenFactory`,
|
|
13
|
+
* and gate them with `enabled`. Every hub that is not lazy starts in
|
|
14
|
+
* `onMount`. On the server, the session is disabled and nothing connects,
|
|
15
|
+
* so a call in `onDestroy` fails at once.
|
|
15
16
|
*/
|
|
16
|
-
provideSignalR: (props: import("./types.js").SignalRProviderProps) => void;
|
|
17
|
+
provideSignalR: (props: import("./types.js").SignalRProviderProps<keyof H & `/${string}`>) => void;
|
|
17
18
|
/**
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
19
|
+
* Gives access to the SignalR context (`getConnection`, `getStatus`,
|
|
20
|
+
* and `waitForConnection`). Call it during component init, below
|
|
21
|
+
* `provideSignalR`. Prefer the typed functions below. Use this only for
|
|
22
|
+
* the underlying `HubConnection` or a one-time read.
|
|
21
23
|
*/
|
|
22
|
-
getSignalR: () => import("
|
|
24
|
+
getSignalR: () => import("@dammers/use-signalr-core").SignalRPublicContext<InferContract<H>>;
|
|
23
25
|
/**
|
|
24
|
-
* Keeps a
|
|
25
|
-
*
|
|
26
|
-
* releases on destroy.
|
|
26
|
+
* Keeps a hub connected until the component is destroyed, without
|
|
27
|
+
* subscribing to events or status. Call it during component init. It
|
|
28
|
+
* acquires the hub at once and releases it on destroy.
|
|
27
29
|
*/
|
|
28
30
|
keepHubAlive: (hub: keyof H & `/${string}`) => void;
|
|
29
31
|
/**
|
|
30
|
-
* Subscribes to a typed server event
|
|
31
|
-
*
|
|
32
|
-
* reconnects.
|
|
32
|
+
* Subscribes to a typed server event until the component is destroyed.
|
|
33
|
+
* Call it during component init. Handler arguments come from your
|
|
34
|
+
* contract. The subscription survives reconnects and rebuilds.
|
|
33
35
|
*/
|
|
34
36
|
onHubEvent: <H_1 extends keyof H & `/${string}`, E extends import("@dammers/use-signalr-core").EventName<InferContract<H>, H_1>>(hub: H_1, event: E, handler: (...args: import("@dammers/use-signalr-core").EventArgs<InferContract<H>, H_1, E>) => void) => void;
|
|
35
37
|
/**
|
|
36
38
|
* Typed invoker that waits for the connection and resolves with the
|
|
37
|
-
* method's return value.
|
|
38
|
-
*
|
|
39
|
+
* method's return value. Call it during component init, then call the
|
|
40
|
+
* invoker later. It fails fast by default. Opt in to retry for idempotent
|
|
41
|
+
* methods only. A pending call rejects with an `AbortError` when the
|
|
42
|
+
* component is destroyed, unless `keepAliveOnUnmount` is true. With
|
|
43
|
+
* `keepAliveOnUnmount`, the call also holds a lazy hub open until it settles.
|
|
39
44
|
*/
|
|
40
45
|
hubInvoke: <H_1 extends keyof H & `/${string}`, M extends import("@dammers/use-signalr-core").MethodName<InferContract<H>, H_1>>(hub: H_1, method: M, options?: import("@dammers/use-signalr-core").InvokeOptions) => (...args: import("@dammers/use-signalr-core").MethodArgs<InferContract<H>, H_1, M>) => Promise<import("@dammers/use-signalr-core").MethodReturn<InferContract<H>, H_1, M>>;
|
|
41
46
|
/**
|
|
42
|
-
* Typed fire-and-forget sender.
|
|
43
|
-
*
|
|
44
|
-
*
|
|
47
|
+
* Typed fire-and-forget sender. Call it during component init. It does
|
|
48
|
+
* not wait for the connection. It resolves `true` when it sends the call,
|
|
49
|
+
* and `false` when the hub is not connected and it drops the call. It also
|
|
50
|
+
* resolves `false` when the send fails. It never throws, so a cleanup can
|
|
51
|
+
* call it. For a call that must land in a cleanup, use `hubTeardown`.
|
|
45
52
|
*/
|
|
46
53
|
hubSend: <H_1 extends keyof H & `/${string}`, M extends import("@dammers/use-signalr-core").MethodName<InferContract<H>, H_1>>(hub: H_1, method: M) => (...args: import("@dammers/use-signalr-core").MethodArgs<InferContract<H>, H_1, M>) => Promise<boolean>;
|
|
47
54
|
/**
|
|
48
|
-
* Typed
|
|
49
|
-
*
|
|
50
|
-
* still connecting instead of dropping, and holds
|
|
51
|
-
* the
|
|
52
|
-
* `false` if the hub
|
|
55
|
+
* Typed teardown sender for a method that you call in `onDestroy`. Call
|
|
56
|
+
* it during component init. It survives the destroy of the component,
|
|
57
|
+
* queues while the hub is still connecting instead of dropping, and holds
|
|
58
|
+
* a lazy hub open until the send ends. It resolves `true` if the call
|
|
59
|
+
* is sent. It resolves `false` if the hub does not connect in time, the session stops while the call waits for the hub, the session is disabled, the hub failed, or the send fails or does not end in time. It never throws.
|
|
60
|
+
* If the session stops while the call is pending on a connected hub, the call is sent before the connection closes.
|
|
53
61
|
*/
|
|
54
62
|
hubTeardown: <H_1 extends keyof H & `/${string}`, M extends import("@dammers/use-signalr-core").MethodName<InferContract<H>, H_1>>(hub: H_1, method: M, options?: import("@dammers/use-signalr-core").TeardownOptions) => (...args: import("@dammers/use-signalr-core").MethodArgs<InferContract<H>, H_1, M>) => Promise<boolean>;
|
|
55
63
|
/**
|
|
56
|
-
* Live connection status of a hub, as a Svelte store.
|
|
57
|
-
*
|
|
58
|
-
* connected
|
|
64
|
+
* Live connection status of a hub, as a Svelte store. Call it during
|
|
65
|
+
* component init. Subscribe with `$` to run again only when this hub's
|
|
66
|
+
* status changes. It also keeps a lazy hub connected until the component
|
|
67
|
+
* is destroyed.
|
|
59
68
|
*/
|
|
60
69
|
hubStatus: <H_1 extends keyof H & `/${string}`>(hub: H_1) => import("svelte/store").Readable<import("@dammers/use-signalr-core").HubConnectionStatus>;
|
|
61
70
|
/**
|
|
62
71
|
* Runs a callback after each reconnect, not the first connect, to refetch
|
|
63
|
-
* state that went stale while offline.
|
|
72
|
+
* state that went stale while offline. It also runs after a rebuild, but
|
|
73
|
+
* only for a hub that was connected before. Call it during component init.
|
|
64
74
|
*/
|
|
65
75
|
onReconnected: <H_1 extends keyof H & `/${string}`>(hub: H_1, callback: () => void) => void;
|
|
66
76
|
};
|
|
@@ -2,74 +2,84 @@ import { hubKeys, resolveHubConfig } from "@dammers/use-signalr-core";
|
|
|
2
2
|
import { createSignalRProvider } from "./internal/create-provider.js";
|
|
3
3
|
import { createSignalRHooks } from "./internal/create-hooks.js";
|
|
4
4
|
/**
|
|
5
|
-
* Creates a
|
|
5
|
+
* Creates a typed SignalR client. Returns a provider function and a set
|
|
6
6
|
* of stores/functions, typed against the contract inferred from
|
|
7
7
|
* `config.hubs`: the keys declare the hubs, and each hub's
|
|
8
8
|
* `event()`/`method()` declarations declare its events and methods.
|
|
9
9
|
*/
|
|
10
10
|
export function createSignalRClient(config) {
|
|
11
11
|
const hubs = hubKeys(config);
|
|
12
|
-
const resolved = new Map(hubs.map((h) => [h, resolveHubConfig(config,
|
|
12
|
+
const resolved = new Map(hubs.map((h) => [h, resolveHubConfig(config, h)]));
|
|
13
13
|
const resolve = (hub) => resolved.get(hub);
|
|
14
14
|
const contextKey = Symbol("use-signalr");
|
|
15
15
|
const provideSignalR = createSignalRProvider(contextKey, hubs, resolve);
|
|
16
16
|
const hooks = createSignalRHooks(contextKey);
|
|
17
17
|
return {
|
|
18
18
|
/**
|
|
19
|
-
* Builds
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
19
|
+
* Builds the session and sets the context. Call it once in your root
|
|
20
|
+
* component's script, before any other function, for example in
|
|
21
|
+
* `+layout.svelte` in SvelteKit. Pass `baseUrl` and `accessTokenFactory`,
|
|
22
|
+
* and gate them with `enabled`. Every hub that is not lazy starts in
|
|
23
|
+
* `onMount`. On the server, the session is disabled and nothing connects,
|
|
24
|
+
* so a call in `onDestroy` fails at once.
|
|
24
25
|
*/
|
|
25
26
|
provideSignalR,
|
|
26
27
|
/**
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
28
|
+
* Gives access to the SignalR context (`getConnection`, `getStatus`,
|
|
29
|
+
* and `waitForConnection`). Call it during component init, below
|
|
30
|
+
* `provideSignalR`. Prefer the typed functions below. Use this only for
|
|
31
|
+
* the underlying `HubConnection` or a one-time read.
|
|
30
32
|
*/
|
|
31
33
|
getSignalR: hooks.getSignalR,
|
|
32
34
|
/**
|
|
33
|
-
* Keeps a
|
|
34
|
-
*
|
|
35
|
-
* releases on destroy.
|
|
35
|
+
* Keeps a hub connected until the component is destroyed, without
|
|
36
|
+
* subscribing to events or status. Call it during component init. It
|
|
37
|
+
* acquires the hub at once and releases it on destroy.
|
|
36
38
|
*/
|
|
37
39
|
keepHubAlive: hooks.keepHubAlive,
|
|
38
40
|
/**
|
|
39
|
-
* Subscribes to a typed server event
|
|
40
|
-
*
|
|
41
|
-
* reconnects.
|
|
41
|
+
* Subscribes to a typed server event until the component is destroyed.
|
|
42
|
+
* Call it during component init. Handler arguments come from your
|
|
43
|
+
* contract. The subscription survives reconnects and rebuilds.
|
|
42
44
|
*/
|
|
43
45
|
onHubEvent: hooks.onHubEvent,
|
|
44
46
|
/**
|
|
45
47
|
* Typed invoker that waits for the connection and resolves with the
|
|
46
|
-
* method's return value.
|
|
47
|
-
*
|
|
48
|
+
* method's return value. Call it during component init, then call the
|
|
49
|
+
* invoker later. It fails fast by default. Opt in to retry for idempotent
|
|
50
|
+
* methods only. A pending call rejects with an `AbortError` when the
|
|
51
|
+
* component is destroyed, unless `keepAliveOnUnmount` is true. With
|
|
52
|
+
* `keepAliveOnUnmount`, the call also holds a lazy hub open until it settles.
|
|
48
53
|
*/
|
|
49
54
|
hubInvoke: hooks.hubInvoke,
|
|
50
55
|
/**
|
|
51
|
-
* Typed fire-and-forget sender.
|
|
52
|
-
*
|
|
53
|
-
*
|
|
56
|
+
* Typed fire-and-forget sender. Call it during component init. It does
|
|
57
|
+
* not wait for the connection. It resolves `true` when it sends the call,
|
|
58
|
+
* and `false` when the hub is not connected and it drops the call. It also
|
|
59
|
+
* resolves `false` when the send fails. It never throws, so a cleanup can
|
|
60
|
+
* call it. For a call that must land in a cleanup, use `hubTeardown`.
|
|
54
61
|
*/
|
|
55
62
|
hubSend: hooks.hubSend,
|
|
56
63
|
/**
|
|
57
|
-
* Typed
|
|
58
|
-
*
|
|
59
|
-
* still connecting instead of dropping, and holds
|
|
60
|
-
* the
|
|
61
|
-
* `false` if the hub
|
|
64
|
+
* Typed teardown sender for a method that you call in `onDestroy`. Call
|
|
65
|
+
* it during component init. It survives the destroy of the component,
|
|
66
|
+
* queues while the hub is still connecting instead of dropping, and holds
|
|
67
|
+
* a lazy hub open until the send ends. It resolves `true` if the call
|
|
68
|
+
* is sent. It resolves `false` if the hub does not connect in time, the session stops while the call waits for the hub, the session is disabled, the hub failed, or the send fails or does not end in time. It never throws.
|
|
69
|
+
* If the session stops while the call is pending on a connected hub, the call is sent before the connection closes.
|
|
62
70
|
*/
|
|
63
71
|
hubTeardown: hooks.hubTeardown,
|
|
64
72
|
/**
|
|
65
|
-
* Live connection status of a hub, as a Svelte store.
|
|
66
|
-
*
|
|
67
|
-
* connected
|
|
73
|
+
* Live connection status of a hub, as a Svelte store. Call it during
|
|
74
|
+
* component init. Subscribe with `$` to run again only when this hub's
|
|
75
|
+
* status changes. It also keeps a lazy hub connected until the component
|
|
76
|
+
* is destroyed.
|
|
68
77
|
*/
|
|
69
78
|
hubStatus: hooks.hubStatus,
|
|
70
79
|
/**
|
|
71
80
|
* Runs a callback after each reconnect, not the first connect, to refetch
|
|
72
|
-
* state that went stale while offline.
|
|
81
|
+
* state that went stale while offline. It also runs after a rebuild, but
|
|
82
|
+
* only for a hub that was connected before. Call it during component init.
|
|
73
83
|
*/
|
|
74
84
|
onReconnected: hooks.onReconnected,
|
|
75
85
|
};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
export { createSignalRClient } from "./create-signalr-client.js";
|
|
2
|
-
export {
|
|
3
|
-
export type {
|
|
4
|
-
export type {
|
|
5
|
-
export type { MaybeReadable, SignalRProviderProps, SignalRContextValue } from "./types.js";
|
|
2
|
+
export { event, method } from "@dammers/use-signalr-core";
|
|
3
|
+
export type { HubString, HubContract, SignalRContract, SignalRClientConfig, PerHubConfig, HubProtocolConfig, ConfigureBuilder, BuilderContext, HttpOptions, HubDef, EventDef, MethodDef, InferContract, ReconnectConfig, InvokeOptions, TeardownOptions, HubConnectionStatus, SignalRErrorInfo, SignalRPublicContext, EventName, MethodName, EventArgs, MethodArgs, MethodReturn, } from "@dammers/use-signalr-core";
|
|
4
|
+
export type { MaybeReadable, SignalRProviderProps } from "./types.js";
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export { createSignalRClient } from "./create-signalr-client.js";
|
|
2
|
-
export {
|
|
2
|
+
export { event, method } from "@dammers/use-signalr-core";
|
|
@@ -1,14 +1,13 @@
|
|
|
1
1
|
import type { Readable } from "svelte/store";
|
|
2
|
-
import type { EventArgs, EventName, HubConnectionStatus, InvokeOptions, TeardownOptions,
|
|
3
|
-
import type { SignalRContextValue } from "../types.js";
|
|
2
|
+
import type { EventArgs, EventName, HubConnectionStatus, InvokeOptions, TeardownOptions, MethodName, SignalRContract, SignalRPublicContext } from "@dammers/use-signalr-core";
|
|
4
3
|
/** Builds the functions bound to one client's context. */
|
|
5
4
|
export declare function createSignalRHooks<T extends SignalRContract>(contextKey: symbol): {
|
|
6
|
-
getSignalR: () =>
|
|
5
|
+
getSignalR: () => SignalRPublicContext<T>;
|
|
7
6
|
keepHubAlive: (hub: keyof T & `/${string}`) => void;
|
|
8
7
|
hubStatus: <H extends keyof T & `/${string}`>(hub: H) => Readable<HubConnectionStatus>;
|
|
9
8
|
onReconnected: <H extends keyof T & `/${string}`>(hub: H, callback: () => void) => void;
|
|
10
9
|
onHubEvent: <H extends keyof T & `/${string}`, E extends EventName<T, H>>(hub: H, event: E, handler: (...args: EventArgs<T, H, E>) => void) => void;
|
|
11
|
-
hubInvoke: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M, options?: InvokeOptions) => (...args: MethodArgs<T, H, M>) => Promise<MethodReturn<T, H, M>>;
|
|
12
|
-
hubSend: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M) => (...args: MethodArgs<T, H, M>) => Promise<boolean>;
|
|
13
|
-
hubTeardown: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M, options?: TeardownOptions) => (...args: MethodArgs<T, H, M>) => Promise<boolean>;
|
|
10
|
+
hubInvoke: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M, options?: InvokeOptions) => (...args: import("@dammers/use-signalr-core").MethodArgs<T, H, M>) => Promise<import("@dammers/use-signalr-core").MethodReturn<T, H, M>>;
|
|
11
|
+
hubSend: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M) => (...args: import("@dammers/use-signalr-core").MethodArgs<T, H, M>) => Promise<boolean>;
|
|
12
|
+
hubTeardown: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M, options?: TeardownOptions) => (...args: import("@dammers/use-signalr-core").MethodArgs<T, H, M>) => Promise<boolean>;
|
|
14
13
|
};
|
|
@@ -2,187 +2,67 @@ import { getContext, onDestroy } from "svelte";
|
|
|
2
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
|
-
|
|
6
|
-
* Escape hatch to the raw SignalR context. Prefer the typed stores/functions
|
|
7
|
-
* below. Reach for this only when you need the underlying `HubConnection`
|
|
8
|
-
* or a point read.
|
|
9
|
-
*
|
|
10
|
-
* @returns The context value: `getConnection`, `isHubConnected`, `getStatus`,
|
|
11
|
-
* `waitForConnection`, `acquire`/`release`, `registerReconnect`, `statusStore`.
|
|
12
|
-
* @throws If called outside `provideSignalR`.
|
|
13
|
-
*/
|
|
14
|
-
function getSignalR() {
|
|
5
|
+
function getInternalContext(name) {
|
|
15
6
|
const ctx = getContext(contextKey);
|
|
16
7
|
if (!ctx)
|
|
17
|
-
throw new Error(
|
|
8
|
+
throw new Error(`${name} must be called during component init, below provideSignalR`);
|
|
18
9
|
return ctx;
|
|
19
10
|
}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
* `onDestroy`.
|
|
24
|
-
*
|
|
25
|
-
* Most functions already do this internally. Use it directly only when you
|
|
26
|
-
* want a lazy hub connected for a component that does not otherwise touch it.
|
|
27
|
-
*
|
|
28
|
-
* @param hub The hub path to keep connected.
|
|
29
|
-
*/
|
|
11
|
+
function getSignalR() {
|
|
12
|
+
return getInternalContext("getSignalR").publicContext;
|
|
13
|
+
}
|
|
30
14
|
function keepHubAlive(hub) {
|
|
31
|
-
const { acquire, release } =
|
|
15
|
+
const { acquire, release } = getInternalContext("keepHubAlive");
|
|
32
16
|
acquire(hub);
|
|
33
17
|
onDestroy(() => release(hub));
|
|
34
18
|
}
|
|
35
|
-
/**
|
|
36
|
-
* Live connection status of a hub, as a Svelte store. Subscribe with `$` in
|
|
37
|
-
* a component to re-render only when THIS hub's status changes, not when
|
|
38
|
-
* another hub changes. Also keeps the hub alive while mounted, so a lazy
|
|
39
|
-
* hub connects on first use.
|
|
40
|
-
*
|
|
41
|
-
* @param hub The hub path to watch.
|
|
42
|
-
* @returns A `Readable<"disconnected" | "connecting" | "connected" | "reconnecting" | "reconnected">`.
|
|
43
|
-
*/
|
|
44
19
|
function hubStatus(hub) {
|
|
45
|
-
const { statusStore } =
|
|
20
|
+
const { statusStore } = getInternalContext("hubStatus");
|
|
46
21
|
keepHubAlive(hub);
|
|
47
22
|
return statusStore.readable(hub);
|
|
48
23
|
}
|
|
49
|
-
/**
|
|
50
|
-
* Runs a callback every time a hub reconnects, after a dropped connection
|
|
51
|
-
* is re-established, to refetch state that may have gone stale while
|
|
52
|
-
* offline. Does NOT fire on the first connect, only on reconnects.
|
|
53
|
-
*
|
|
54
|
-
* @param hub The hub path to watch.
|
|
55
|
-
* @param callback Invoked after each successful reconnect.
|
|
56
|
-
*/
|
|
57
24
|
function onReconnected(hub, callback) {
|
|
58
|
-
const { registerReconnect } =
|
|
25
|
+
const { registerReconnect } = getInternalContext("onReconnected");
|
|
59
26
|
keepHubAlive(hub);
|
|
60
27
|
const unsub = registerReconnect(hub, () => callback());
|
|
61
28
|
onDestroy(unsub);
|
|
62
29
|
}
|
|
63
|
-
/**
|
|
64
|
-
* Subscribes to a typed server event for the lifetime of the component. The
|
|
65
|
-
* handler's args are inferred from your contract for `(hub, event)`. The
|
|
66
|
-
* subscription attaches once the hub is connected, re-attaches across
|
|
67
|
-
* reconnects, and detaches on `onDestroy`.
|
|
68
|
-
*
|
|
69
|
-
* @param hub The hub path.
|
|
70
|
-
* @param event The event name, a key of that hub's `events`.
|
|
71
|
-
* @param handler Called with the event's typed args each time the server pushes it.
|
|
72
|
-
*/
|
|
73
30
|
function onHubEvent(hub, event, handler) {
|
|
74
|
-
const {
|
|
31
|
+
const { subscribe } = getInternalContext("onHubEvent");
|
|
75
32
|
keepHubAlive(hub);
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
const detach = () => {
|
|
79
|
-
if (!attachedConn)
|
|
80
|
-
return;
|
|
81
|
-
attachedConn.off(event, listener);
|
|
82
|
-
attachedConn = null;
|
|
83
|
-
};
|
|
84
|
-
const unsubscribe = statusStore.readable(hub).subscribe((status) => {
|
|
85
|
-
if (status !== "connected") {
|
|
86
|
-
detach();
|
|
87
|
-
return;
|
|
88
|
-
}
|
|
89
|
-
if (attachedConn)
|
|
90
|
-
return; // already attached this connected phase
|
|
91
|
-
const connection = getConnection(hub);
|
|
92
|
-
if (!connection)
|
|
93
|
-
return;
|
|
94
|
-
connection.on(event, listener);
|
|
95
|
-
attachedConn = connection;
|
|
96
|
-
});
|
|
97
|
-
onDestroy(() => {
|
|
98
|
-
unsubscribe();
|
|
99
|
-
detach();
|
|
100
|
-
});
|
|
33
|
+
const unsubscribe = subscribe(hub, event, (...args) => handler(...args));
|
|
34
|
+
onDestroy(unsubscribe);
|
|
101
35
|
}
|
|
102
|
-
/**
|
|
103
|
-
* Returns a stable, typed function that invokes a hub method and resolves
|
|
104
|
-
* with its return value. It waits, up to `timeout`, for the connection
|
|
105
|
-
* before it invokes, so calling right after component init is safe.
|
|
106
|
-
*
|
|
107
|
-
* Special behavior:
|
|
108
|
-
* - **Fails fast by default** (`retries: 0`): rethrows the raw server error,
|
|
109
|
-
* so callers see the original.
|
|
110
|
-
* - **Opt-in retry** for retriable failures (transport drops, timeouts),
|
|
111
|
-
* with jittered backoff. Business errors (a `HubException` thrown while
|
|
112
|
-
* still connected) are never retried.
|
|
113
|
-
* - **At-least-once when retrying.** Enable `retries` only for IDEMPOTENT methods.
|
|
114
|
-
* - **Auto-aborts** any in-flight call or retry loop on `onDestroy`, UNLESS
|
|
115
|
-
* `keepAliveOnUnmount: true`. For a method invoked in a teardown, set that
|
|
116
|
-
* flag, or prefer {@link hubTeardown}, which also handles the
|
|
117
|
-
* hub-still-connecting race.
|
|
118
|
-
*
|
|
119
|
-
* @param hub The hub path.
|
|
120
|
-
* @param method The method name, a key of that hub's `methods`.
|
|
121
|
-
* @param options Optional `retries`, `timeout`, `backoff`, `isRetriable`, `keepAliveOnUnmount`.
|
|
122
|
-
* @returns An async fn that takes the method's typed args and resolves to its typed return.
|
|
123
|
-
* @throws The raw error when `retries === 0`. Otherwise an {@link InvokeError}
|
|
124
|
-
* that wraps the last failure once attempts are exhausted.
|
|
125
|
-
*/
|
|
126
36
|
function hubInvoke(hub, method, options) {
|
|
127
|
-
const { waitForConnection, getConnection } =
|
|
37
|
+
const { waitForConnection, getConnection, acquire, release } = getInternalContext("hubInvoke");
|
|
128
38
|
keepHubAlive(hub);
|
|
129
39
|
const scope = createAbortScope();
|
|
130
40
|
onDestroy(() => {
|
|
131
41
|
if (!options?.keepAliveOnUnmount)
|
|
132
|
-
scope.
|
|
42
|
+
scope.abort();
|
|
43
|
+
});
|
|
44
|
+
return createInvoker({
|
|
45
|
+
target: { waitForConnection, getConnection, acquire, release },
|
|
46
|
+
hub,
|
|
47
|
+
method,
|
|
48
|
+
getOptions: () => options,
|
|
49
|
+
getSignal: scope.signal,
|
|
133
50
|
});
|
|
134
|
-
return createInvoker({ waitForConnection, getConnection }, hub, method, () => options, scope.track, scope.untrack);
|
|
135
51
|
}
|
|
136
|
-
/**
|
|
137
|
-
* Returns a stable, typed fire-and-forget sender. Unlike {@link hubInvoke},
|
|
138
|
-
* it does NOT wait for the connection and does NOT return the method's
|
|
139
|
-
* result. If the hub is not Connected, the call is dropped (resolves
|
|
140
|
-
* `false`); otherwise it is dispatched (resolves `true`).
|
|
141
|
-
*
|
|
142
|
-
* Reads the connection at call time and never depends on reactive state, so
|
|
143
|
-
* it is safe to capture in a teardown.
|
|
144
|
-
*
|
|
145
|
-
* @param hub The hub path.
|
|
146
|
-
* @param method The method name, a key of that hub's `methods`.
|
|
147
|
-
* @returns An async fn that takes the method's typed args and resolves
|
|
148
|
-
* `true` if dispatched, `false` if dropped because it was not connected.
|
|
149
|
-
*/
|
|
150
52
|
function hubSend(hub, method) {
|
|
151
|
-
const { getConnection } =
|
|
53
|
+
const { getConnection } = getInternalContext("hubSend");
|
|
152
54
|
keepHubAlive(hub);
|
|
153
|
-
return createSender(getConnection, hub, method);
|
|
55
|
+
return createSender({ getConnection, hub, method });
|
|
154
56
|
}
|
|
155
|
-
/**
|
|
156
|
-
* Returns a stable, typed RELIABLE teardown sender, built for a method
|
|
157
|
-
* invoked in a teardown. Unlike {@link hubSend}, which drops a call if
|
|
158
|
-
* not yet connected, and {@link hubInvoke}, which aborts in-flight
|
|
159
|
-
* calls on `onDestroy`, the returned function:
|
|
160
|
-
*
|
|
161
|
-
* - **Survives the calling component's disposal.** It runs detached, not
|
|
162
|
-
* tied to any subscription or AbortController, so a call issued in
|
|
163
|
-
* `onDestroy` still lands.
|
|
164
|
-
* - **Queues while connecting.** It waits, up to `timeout`, for the hub to
|
|
165
|
-
* (re)connect, then sends, instead of dropping the call.
|
|
166
|
-
* - **Holds a lazy hub open** until the flush completes, even when the
|
|
167
|
-
* calling component was the last consumer — it acquires and releases
|
|
168
|
-
* independently.
|
|
169
|
-
* - **Is best-effort and fire-and-forget.** It resolves `true` once
|
|
170
|
-
* dispatched, `false` if the hub never connected within `timeout`, and
|
|
171
|
-
* never throws.
|
|
172
|
-
*
|
|
173
|
-
* Also lands when the calling component is destroyed immediately after
|
|
174
|
-
* initializing — the queued call still flushes.
|
|
175
|
-
*
|
|
176
|
-
* @param hub The hub path.
|
|
177
|
-
* @param method The teardown method name, a key of that hub's `methods`.
|
|
178
|
-
* @param options Optional `timeout` in ms to wait for a connection. Default 10_000.
|
|
179
|
-
* @returns An async fn that takes the method's typed args and resolves
|
|
180
|
-
* `true` if dispatched, `false` if the hub never connected in time.
|
|
181
|
-
*/
|
|
182
57
|
function hubTeardown(hub, method, options) {
|
|
183
|
-
const { acquire, release, waitForConnection } =
|
|
58
|
+
const { acquire, release, waitForConnection, beginSend } = getInternalContext("hubTeardown");
|
|
184
59
|
keepHubAlive(hub);
|
|
185
|
-
return createTeardownSender({
|
|
60
|
+
return createTeardownSender({
|
|
61
|
+
target: { acquire, release, waitForConnection, beginSend },
|
|
62
|
+
hub,
|
|
63
|
+
method,
|
|
64
|
+
getOptions: () => options,
|
|
65
|
+
});
|
|
186
66
|
}
|
|
187
67
|
return {
|
|
188
68
|
getSignalR,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import type { HubString, ResolvedHubConfig, SignalRContract } from "@dammers/use-signalr-core";
|
|
2
2
|
import type { SignalRProviderProps } from "../types.js";
|
|
3
3
|
/** Builds the `provideSignalR` function bound to one client's context. */
|
|
4
|
-
export declare function createSignalRProvider<T extends SignalRContract>(contextKey: symbol, hubs: Array<keyof T & HubString>, resolve: (hub: keyof T & HubString) => ResolvedHubConfig): (props: SignalRProviderProps) => void;
|
|
4
|
+
export declare function createSignalRProvider<T extends SignalRContract>(contextKey: symbol, hubs: Array<keyof T & HubString>, resolve: (hub: keyof T & HubString) => ResolvedHubConfig): (props: SignalRProviderProps<keyof T & `/${string}`>) => void;
|
|
@@ -9,7 +9,7 @@ function isReadable(value) {
|
|
|
9
9
|
typeof value.subscribe === "function");
|
|
10
10
|
}
|
|
11
11
|
function toReadable(value) {
|
|
12
|
-
return isReadable(value) ? value : readable(value
|
|
12
|
+
return isReadable(value) ? value : readable(value);
|
|
13
13
|
}
|
|
14
14
|
/** Builds the `provideSignalR` function bound to one client's context. */
|
|
15
15
|
export function createSignalRProvider(contextKey, hubs, resolve) {
|
|
@@ -21,21 +21,40 @@ export function createSignalRProvider(contextKey, hubs, resolve) {
|
|
|
21
21
|
statusStore,
|
|
22
22
|
getAccessToken: () => props.accessTokenFactory(),
|
|
23
23
|
onStatusChange: (hub, status) => props.onStatusChange?.(hub, status),
|
|
24
|
-
onError: (hub, err) => props.onError?.(hub, err),
|
|
24
|
+
onError: (hub, err, info) => props.onError?.(hub, err, info),
|
|
25
25
|
});
|
|
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, connectionKey]) =>
|
|
30
|
-
//
|
|
29
|
+
const identity$ = derived([baseUrl$, enabled$, connectionKey$], ([baseUrl, enabled, connectionKey]) => ({ baseUrl, enabled, connectionKey }));
|
|
30
|
+
// Svelte runs onDestroy but not onMount on the server, so a waiting call must fail at once.
|
|
31
|
+
if (typeof window === "undefined") {
|
|
32
|
+
session.update({ baseUrl: undefined, enabled: false, connectionKey: undefined });
|
|
33
|
+
}
|
|
31
34
|
onMount(() => {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
+
let first = true;
|
|
36
|
+
let stopped = false;
|
|
37
|
+
let pending;
|
|
38
|
+
const unsubscribe = identity$.subscribe((values) => {
|
|
39
|
+
if (first) {
|
|
40
|
+
first = false;
|
|
41
|
+
session.update(values);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
const scheduled = pending !== undefined;
|
|
45
|
+
pending = values;
|
|
46
|
+
if (scheduled)
|
|
35
47
|
return;
|
|
36
|
-
|
|
48
|
+
queueMicrotask(() => {
|
|
49
|
+
if (stopped || !pending)
|
|
50
|
+
return;
|
|
51
|
+
const latest = pending;
|
|
52
|
+
pending = undefined;
|
|
53
|
+
session.update(latest);
|
|
54
|
+
});
|
|
37
55
|
});
|
|
38
56
|
return () => {
|
|
57
|
+
stopped = true;
|
|
39
58
|
unsubscribe();
|
|
40
59
|
session.stop();
|
|
41
60
|
};
|
package/dist/status-store.d.ts
CHANGED
|
@@ -4,9 +4,5 @@ export interface StatusStore<H extends string> extends StatusStoreBase<H> {
|
|
|
4
4
|
/** Readable store for one hub's status; subscribe with `$` in components. */
|
|
5
5
|
readable: (hub: H) => Readable<HubConnectionStatus>;
|
|
6
6
|
}
|
|
7
|
-
/**
|
|
8
|
-
* Small store for hub statuses, backed by one Svelte writable per hub,
|
|
9
|
-
* created lazily on first access. `set` dedupes by hand since a Svelte
|
|
10
|
-
* writable notifies subscribers even on an equal value.
|
|
11
|
-
*/
|
|
7
|
+
/** Hub statuses, backed by one Svelte writable per hub, created on first access. */
|
|
12
8
|
export declare function createStatusStore<H extends string>(): StatusStore<H>;
|
package/dist/status-store.js
CHANGED
|
@@ -1,27 +1,18 @@
|
|
|
1
1
|
import { writable, get as readStore } from "svelte/store";
|
|
2
|
-
/**
|
|
3
|
-
* Small store for hub statuses, backed by one Svelte writable per hub,
|
|
4
|
-
* created lazily on first access. `set` dedupes by hand since a Svelte
|
|
5
|
-
* writable notifies subscribers even on an equal value.
|
|
6
|
-
*/
|
|
2
|
+
/** Hub statuses, backed by one Svelte writable per hub, created on first access. */
|
|
7
3
|
export function createStatusStore() {
|
|
8
4
|
const stores = new Map();
|
|
9
5
|
const getOrCreate = (hub) => {
|
|
10
6
|
let store = stores.get(hub);
|
|
11
7
|
if (!store) {
|
|
12
|
-
store = writable("
|
|
8
|
+
store = writable("idle");
|
|
13
9
|
stores.set(hub, store);
|
|
14
10
|
}
|
|
15
11
|
return store;
|
|
16
12
|
};
|
|
17
13
|
return {
|
|
18
14
|
get: (hub) => readStore(getOrCreate(hub)),
|
|
19
|
-
set: (hub, status) =>
|
|
20
|
-
|
|
21
|
-
if (readStore(store) === status)
|
|
22
|
-
return;
|
|
23
|
-
store.set(status);
|
|
24
|
-
},
|
|
25
|
-
readable: (hub) => getOrCreate(hub),
|
|
15
|
+
set: (hub, status) => getOrCreate(hub).set(status),
|
|
16
|
+
readable: (hub) => ({ subscribe: getOrCreate(hub).subscribe }),
|
|
26
17
|
};
|
|
27
18
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -3,9 +3,15 @@ import type { SignalRContract, SignalRProviderPropsBase, SignalRContextValueBase
|
|
|
3
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
|
-
export type SignalRProviderProps = Omit<SignalRProviderPropsBase<
|
|
6
|
+
export type SignalRProviderProps<THub extends HubString = HubString> = Omit<SignalRProviderPropsBase<THub>, "baseUrl" | "enabled" | "connectionKey"> & {
|
|
7
|
+
/** Base URL of the SignalR server. The library adds the hub paths from the contract and removes a trailing slash. A new value rebuilds all connections. `undefined` or `""` disables the session. Use `"/"` for the same origin. */
|
|
7
8
|
baseUrl: MaybeReadable<string | undefined>;
|
|
9
|
+
/**
|
|
10
|
+
* When `false`, all hubs stop and the status is `idle`. An invoke that waits for the connection rejects at once with an error named `SignalRDisabledError`.
|
|
11
|
+
* @default true
|
|
12
|
+
*/
|
|
8
13
|
enabled?: MaybeReadable<boolean>;
|
|
14
|
+
/** A new value rebuilds all connections. Use it to recover from `disconnected`. Pass a user ID or a login counter, not the token. */
|
|
9
15
|
connectionKey?: MaybeReadable<string | number | undefined>;
|
|
10
16
|
};
|
|
11
17
|
export type SignalRContextValue<T extends SignalRContract> = SignalRContextValueBase<T, StatusStore<keyof T & HubString>>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dammers/use-signalr-svelte",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Fully-typed multi-hub SignalR provider + stores for Svelte: auto-reconnect, invoke retry, lazy hubs, live status.",
|
|
5
5
|
"author": "Dammers",
|
|
6
6
|
"license": "MIT",
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"url": "git+https://github.com/DammersCode/use-signalr.git",
|
|
10
10
|
"directory": "packages/svelte"
|
|
11
11
|
},
|
|
12
|
-
"homepage": "https://
|
|
12
|
+
"homepage": "https://use-signalr.vercel.app/docs/svelte",
|
|
13
13
|
"bugs": "https://github.com/DammersCode/use-signalr/issues",
|
|
14
14
|
"keywords": [
|
|
15
15
|
"svelte",
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"websocket"
|
|
22
22
|
],
|
|
23
23
|
"engines": {
|
|
24
|
-
"node": ">=
|
|
24
|
+
"node": ">=20.19"
|
|
25
25
|
},
|
|
26
26
|
"type": "module",
|
|
27
27
|
"sideEffects": false,
|
|
@@ -30,8 +30,10 @@
|
|
|
30
30
|
"exports": {
|
|
31
31
|
".": {
|
|
32
32
|
"types": "./dist/index.d.ts",
|
|
33
|
-
"import": "./dist/index.js"
|
|
34
|
-
|
|
33
|
+
"import": "./dist/index.js",
|
|
34
|
+
"default": "./dist/index.js"
|
|
35
|
+
},
|
|
36
|
+
"./package.json": "./package.json"
|
|
35
37
|
},
|
|
36
38
|
"files": [
|
|
37
39
|
"dist"
|
|
@@ -46,15 +48,15 @@
|
|
|
46
48
|
"test": "vitest run"
|
|
47
49
|
},
|
|
48
50
|
"dependencies": {
|
|
49
|
-
"@dammers/use-signalr-core": "
|
|
51
|
+
"@dammers/use-signalr-core": "1.1.0"
|
|
50
52
|
},
|
|
51
53
|
"peerDependencies": {
|
|
52
|
-
"@microsoft/signalr": "
|
|
53
|
-
"svelte": "
|
|
54
|
+
"@microsoft/signalr": "^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0",
|
|
55
|
+
"svelte": "^5.15.0"
|
|
54
56
|
},
|
|
55
57
|
"devDependencies": {
|
|
56
|
-
"@microsoft/signalr": "
|
|
57
|
-
"svelte": "^5.
|
|
58
|
+
"@microsoft/signalr": "^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0",
|
|
59
|
+
"svelte": "^5.15.0",
|
|
58
60
|
"@sveltejs/vite-plugin-svelte": "^7.3.0",
|
|
59
61
|
"@testing-library/svelte": "^5.4.2"
|
|
60
62
|
}
|