@dammers/use-signalr-svelte 0.4.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 ADDED
@@ -0,0 +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.
package/README.md ADDED
@@ -0,0 +1,207 @@
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)
@@ -0,0 +1,66 @@
1
+ import type { HubDef, HubString, InferContract, SignalRClientConfig } from "@dammers/use-signalr-core";
2
+ /**
3
+ * Creates a fully-typed SignalR client. Returns a provider function and a set
4
+ * of stores/functions, typed against the contract inferred from
5
+ * `config.hubs`: the keys declare the hubs, and each hub's
6
+ * `event()`/`method()` declarations declare its events and methods.
7
+ */
8
+ export declare function createSignalRClient<const H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>): {
9
+ /**
10
+ * Builds, starts, retries, and auto-reconnects every configured hub. Call
11
+ * once in your root component's script, before any other function — for
12
+ * example `+layout.svelte` in SvelteKit. Pass `baseUrl` and
13
+ * `accessTokenFactory`, and gate them with `enabled`. All connection work
14
+ * happens client-side only, so this is safe to call during SSR.
15
+ */
16
+ provideSignalR: (props: import("./types").SignalRProviderProps) => void;
17
+ /**
18
+ * Escape hatch to the raw SignalR context (`getConnection`, `getStatus`,
19
+ * `isHubConnected`, and more). Prefer the typed stores/functions below.
20
+ * Use this only for the underlying `HubConnection` or a point read.
21
+ */
22
+ getSignalR: () => import("./types").SignalRContextValue<InferContract<H>>;
23
+ /**
24
+ * Keeps a (possibly lazy) hub connected for the component's lifetime,
25
+ * without subscribing to events or status. Acquires at component init,
26
+ * releases on destroy.
27
+ */
28
+ keepHubAlive: (hub: keyof H & `/${string}`) => void;
29
+ /**
30
+ * Subscribes to a typed server event for the component's lifetime.
31
+ * Handler args are inferred from your contract. Re-attaches across
32
+ * reconnects.
33
+ */
34
+ 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
+ /**
36
+ * Typed invoker that waits for the connection and resolves with the
37
+ * method's return value. Fails fast by default. Opt in to retry for
38
+ * idempotent methods only.
39
+ */
40
+ 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
+ /**
42
+ * Typed fire-and-forget sender. Does not wait for the connection: it
43
+ * drops the call (resolves `false`) if not connected, otherwise it
44
+ * dispatches the call (`true`). Safe in teardowns.
45
+ */
46
+ 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
+ /**
48
+ * Typed RELIABLE teardown sender for a method invoked in a teardown.
49
+ * Survives the calling component's disposal, queues while the hub is
50
+ * still connecting instead of dropping, and holds a lazy hub open until
51
+ * the flush completes. Best-effort: resolves `true` if dispatched,
52
+ * `false` if the hub never connected in time. Never throws.
53
+ */
54
+ 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
+ /**
56
+ * Live connection status of a hub, as a Svelte store. Subscribe with `$`
57
+ * to re-render only when THIS hub's status changes. Also keeps a lazy hub
58
+ * connected while mounted.
59
+ */
60
+ hubStatus: <H_1 extends keyof H & `/${string}`>(hub: H_1) => import("svelte/store").Readable<import("@dammers/use-signalr-core").HubConnectionStatus>;
61
+ /**
62
+ * Runs a callback after each reconnect, not the first connect, to refetch
63
+ * state that went stale while offline.
64
+ */
65
+ onReconnected: <H_1 extends keyof H & `/${string}`>(hub: H_1, callback: () => void) => void;
66
+ };
@@ -0,0 +1,76 @@
1
+ import { hubKeys, resolveHubConfig } from "@dammers/use-signalr-core";
2
+ import { createSignalRProvider } from "./internal/create-provider";
3
+ import { createSignalRHooks } from "./internal/create-hooks";
4
+ /**
5
+ * Creates a fully-typed SignalR client. Returns a provider function and a set
6
+ * of stores/functions, typed against the contract inferred from
7
+ * `config.hubs`: the keys declare the hubs, and each hub's
8
+ * `event()`/`method()` declarations declare its events and methods.
9
+ */
10
+ export function createSignalRClient(config) {
11
+ const hubs = hubKeys(config);
12
+ const resolved = new Map(hubs.map((h) => [h, resolveHubConfig(config, config.hubs[h])]));
13
+ const resolve = (hub) => resolved.get(hub);
14
+ const contextKey = Symbol("use-signalr");
15
+ const provideSignalR = createSignalRProvider(contextKey, hubs, resolve);
16
+ const hooks = createSignalRHooks(contextKey);
17
+ return {
18
+ /**
19
+ * Builds, starts, retries, and auto-reconnects every configured hub. Call
20
+ * once in your root component's script, before any other function — for
21
+ * example `+layout.svelte` in SvelteKit. Pass `baseUrl` and
22
+ * `accessTokenFactory`, and gate them with `enabled`. All connection work
23
+ * happens client-side only, so this is safe to call during SSR.
24
+ */
25
+ provideSignalR,
26
+ /**
27
+ * Escape hatch to the raw SignalR context (`getConnection`, `getStatus`,
28
+ * `isHubConnected`, and more). Prefer the typed stores/functions below.
29
+ * Use this only for the underlying `HubConnection` or a point read.
30
+ */
31
+ getSignalR: hooks.getSignalR,
32
+ /**
33
+ * Keeps a (possibly lazy) hub connected for the component's lifetime,
34
+ * without subscribing to events or status. Acquires at component init,
35
+ * releases on destroy.
36
+ */
37
+ keepHubAlive: hooks.keepHubAlive,
38
+ /**
39
+ * Subscribes to a typed server event for the component's lifetime.
40
+ * Handler args are inferred from your contract. Re-attaches across
41
+ * reconnects.
42
+ */
43
+ onHubEvent: hooks.onHubEvent,
44
+ /**
45
+ * Typed invoker that waits for the connection and resolves with the
46
+ * method's return value. Fails fast by default. Opt in to retry for
47
+ * idempotent methods only.
48
+ */
49
+ hubInvoke: hooks.hubInvoke,
50
+ /**
51
+ * Typed fire-and-forget sender. Does not wait for the connection: it
52
+ * drops the call (resolves `false`) if not connected, otherwise it
53
+ * dispatches the call (`true`). Safe in teardowns.
54
+ */
55
+ hubSend: hooks.hubSend,
56
+ /**
57
+ * Typed RELIABLE teardown sender for a method invoked in a teardown.
58
+ * Survives the calling component's disposal, queues while the hub is
59
+ * still connecting instead of dropping, and holds a lazy hub open until
60
+ * the flush completes. Best-effort: resolves `true` if dispatched,
61
+ * `false` if the hub never connected in time. Never throws.
62
+ */
63
+ hubTeardown: hooks.hubTeardown,
64
+ /**
65
+ * Live connection status of a hub, as a Svelte store. Subscribe with `$`
66
+ * to re-render only when THIS hub's status changes. Also keeps a lazy hub
67
+ * connected while mounted.
68
+ */
69
+ hubStatus: hooks.hubStatus,
70
+ /**
71
+ * Runs a callback after each reconnect, not the first connect, to refetch
72
+ * state that went stale while offline.
73
+ */
74
+ onReconnected: hooks.onReconnected,
75
+ };
76
+ }
@@ -0,0 +1,5 @@
1
+ export { createSignalRClient } from "./create-signalr-client";
2
+ export { InvokeError, event, method } from "@dammers/use-signalr-core";
3
+ export type { StatusStore } from "./status-store";
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";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { createSignalRClient } from "./create-signalr-client";
2
+ export { InvokeError, event, method } from "@dammers/use-signalr-core";
@@ -0,0 +1,14 @@
1
+ import type { Readable } from "svelte/store";
2
+ import type { EventArgs, EventName, HubConnectionStatus, InvokeOptions, TeardownOptions, MethodArgs, MethodName, MethodReturn, SignalRContract } from "@dammers/use-signalr-core";
3
+ import type { SignalRContextValue } from "../types";
4
+ /** Builds the functions bound to one client's context. */
5
+ export declare function createSignalRHooks<T extends SignalRContract>(contextKey: symbol): {
6
+ getSignalR: () => SignalRContextValue<T>;
7
+ keepHubAlive: (hub: keyof T & `/${string}`) => void;
8
+ hubStatus: <H extends keyof T & `/${string}`>(hub: H) => Readable<HubConnectionStatus>;
9
+ onReconnected: <H extends keyof T & `/${string}`>(hub: H, callback: () => void) => void;
10
+ 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>;
14
+ };
@@ -0,0 +1,199 @@
1
+ import { getContext, onDestroy } from "svelte";
2
+ import { createInvoker, createSender, createTeardownSender } from "@dammers/use-signalr-core";
3
+ /** Builds the functions bound to one client's context. */
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() {
15
+ const ctx = getContext(contextKey);
16
+ if (!ctx)
17
+ throw new Error("getSignalR must be called during component init, below provideSignalR");
18
+ return ctx;
19
+ }
20
+ /**
21
+ * Keeps a (possibly lazy) hub alive for this component's lifetime, without
22
+ * subscribing to events or status. Acquires at component init, releases on
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
+ */
30
+ function keepHubAlive(hub) {
31
+ const { acquire, release } = getSignalR();
32
+ acquire(hub);
33
+ onDestroy(() => release(hub));
34
+ }
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
+ function hubStatus(hub) {
45
+ const { statusStore } = getSignalR();
46
+ keepHubAlive(hub);
47
+ return statusStore.readable(hub);
48
+ }
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
+ function onReconnected(hub, callback) {
58
+ const { registerReconnect } = getSignalR();
59
+ keepHubAlive(hub);
60
+ const unsub = registerReconnect(hub, () => callback());
61
+ onDestroy(unsub);
62
+ }
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
+ function onHubEvent(hub, event, handler) {
74
+ const { statusStore, getConnection } = getSignalR();
75
+ keepHubAlive(hub);
76
+ let attachedConn = null;
77
+ const listener = (...args) => handler(...args);
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
+ });
101
+ }
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
+ function hubInvoke(hub, method, options) {
127
+ const { waitForConnection, getConnection } = getSignalR();
128
+ keepHubAlive(hub);
129
+ let abort = null;
130
+ onDestroy(() => {
131
+ if (!options?.keepAliveOnUnmount)
132
+ abort?.abort();
133
+ });
134
+ return createInvoker({ waitForConnection, getConnection }, hub, method, () => options, (ac) => {
135
+ abort = ac;
136
+ });
137
+ }
138
+ /**
139
+ * Returns a stable, typed fire-and-forget sender. Unlike {@link hubInvoke},
140
+ * it does NOT wait for the connection and does NOT return the method's
141
+ * result. If the hub is not Connected, the call is dropped (resolves
142
+ * `false`); otherwise it is dispatched (resolves `true`).
143
+ *
144
+ * Reads the connection at call time and never depends on reactive state, so
145
+ * it is safe to capture in a teardown.
146
+ *
147
+ * @param hub The hub path.
148
+ * @param method The method name, a key of that hub's `methods`.
149
+ * @returns An async fn that takes the method's typed args and resolves
150
+ * `true` if dispatched, `false` if dropped because it was not connected.
151
+ */
152
+ function hubSend(hub, method) {
153
+ const { getConnection } = getSignalR();
154
+ keepHubAlive(hub);
155
+ return createSender(getConnection, hub, method);
156
+ }
157
+ /**
158
+ * Returns a stable, typed RELIABLE teardown sender, built for a method
159
+ * invoked in a teardown. Unlike {@link hubSend}, which drops a call if
160
+ * not yet connected, and {@link hubInvoke}, which aborts in-flight
161
+ * calls on `onDestroy`, the returned function:
162
+ *
163
+ * - **Survives the calling component's disposal.** It runs detached, not
164
+ * tied to any subscription or AbortController, so a call issued in
165
+ * `onDestroy` still lands.
166
+ * - **Queues while connecting.** It waits, up to `timeout`, for the hub to
167
+ * (re)connect, then sends, instead of dropping the call.
168
+ * - **Holds a lazy hub open** until the flush completes, even when the
169
+ * calling component was the last consumer — it acquires and releases
170
+ * independently.
171
+ * - **Is best-effort and fire-and-forget.** It resolves `true` once
172
+ * dispatched, `false` if the hub never connected within `timeout`, and
173
+ * never throws.
174
+ *
175
+ * Also lands when the calling component is destroyed immediately after
176
+ * initializing — the queued call still flushes.
177
+ *
178
+ * @param hub The hub path.
179
+ * @param method The teardown method name, a key of that hub's `methods`.
180
+ * @param options Optional `timeout` in ms to wait for a connection. Default 10_000.
181
+ * @returns An async fn that takes the method's typed args and resolves
182
+ * `true` if dispatched, `false` if the hub never connected in time.
183
+ */
184
+ function hubTeardown(hub, method, options) {
185
+ const { acquire, release, waitForConnection } = getSignalR();
186
+ keepHubAlive(hub);
187
+ return createTeardownSender({ acquire, release, waitForConnection }, hub, method, () => options);
188
+ }
189
+ return {
190
+ getSignalR,
191
+ keepHubAlive,
192
+ hubStatus,
193
+ onReconnected,
194
+ onHubEvent,
195
+ hubInvoke,
196
+ hubSend,
197
+ hubTeardown,
198
+ };
199
+ }
@@ -0,0 +1,4 @@
1
+ import type { HubString, ResolvedHubConfig, SignalRContract } from "@dammers/use-signalr-core";
2
+ import type { SignalRProviderProps } from "../types";
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;
@@ -0,0 +1,45 @@
1
+ import { setContext, onMount } from "svelte";
2
+ import { derived, readable } from "svelte/store";
3
+ import { createStatusStore } from "../status-store";
4
+ import { createSignalRSession } from "@dammers/use-signalr-core";
5
+ function isReadable(value) {
6
+ return (typeof value === "object" &&
7
+ value !== null &&
8
+ "subscribe" in value &&
9
+ typeof value.subscribe === "function");
10
+ }
11
+ function toReadable(value) {
12
+ return isReadable(value) ? value : readable(value, () => { });
13
+ }
14
+ /** Builds the `provideSignalR` function bound to one client's context. */
15
+ export function createSignalRProvider(contextKey, hubs, resolve) {
16
+ return function provideSignalR(props) {
17
+ const statusStore = createStatusStore();
18
+ const session = createSignalRSession({
19
+ hubs,
20
+ resolve,
21
+ statusStore,
22
+ getAccessToken: () => props.accessTokenFactory(),
23
+ onStatusChange: (hub, status) => props.onStatusChange?.(hub, status),
24
+ onError: (hub, err) => props.onError?.(hub, err),
25
+ });
26
+ const baseUrl$ = toReadable(props.baseUrl);
27
+ const enabled$ = toReadable(props.enabled ?? true);
28
+ const connectionKey$ = toReadable(props.connectionKey);
29
+ const identity$ = derived([baseUrl$, enabled$, connectionKey$], ([baseUrl, enabled]) => [baseUrl, enabled]);
30
+ // All connection work is client-side only: onMount never runs during SSR.
31
+ onMount(() => {
32
+ const unsubscribe = identity$.subscribe(([baseUrl, enabled]) => {
33
+ session.stop();
34
+ if (!enabled || !baseUrl)
35
+ return;
36
+ session.start(baseUrl);
37
+ });
38
+ return () => {
39
+ unsubscribe();
40
+ session.stop();
41
+ };
42
+ });
43
+ setContext(contextKey, session.context);
44
+ };
45
+ }
@@ -0,0 +1,12 @@
1
+ import type { Readable } from "svelte/store";
2
+ import type { HubConnectionStatus, StatusStore as StatusStoreBase } from "@dammers/use-signalr-core";
3
+ export interface StatusStore<H extends string> extends StatusStoreBase<H> {
4
+ /** Readable store for one hub's status; subscribe with `$` in components. */
5
+ readable: (hub: H) => Readable<HubConnectionStatus>;
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
+ */
12
+ export declare function createStatusStore<H extends string>(): StatusStore<H>;
@@ -0,0 +1,27 @@
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
+ */
7
+ export function createStatusStore() {
8
+ const stores = new Map();
9
+ const getOrCreate = (hub) => {
10
+ let store = stores.get(hub);
11
+ if (!store) {
12
+ store = writable("disconnected");
13
+ stores.set(hub, store);
14
+ }
15
+ return store;
16
+ };
17
+ return {
18
+ get: (hub) => readStore(getOrCreate(hub)),
19
+ set: (hub, status) => {
20
+ const store = getOrCreate(hub);
21
+ if (readStore(store) === status)
22
+ return;
23
+ store.set(status);
24
+ },
25
+ readable: (hub) => getOrCreate(hub),
26
+ };
27
+ }
@@ -0,0 +1,11 @@
1
+ import type { Readable } from "svelte/store";
2
+ import type { SignalRContract, SignalRProviderPropsBase, SignalRContextValueBase, HubString } from "@dammers/use-signalr-core";
3
+ import type { StatusStore } from "./status-store";
4
+ /** A value that can also be supplied as a store, to make the provider react to it. */
5
+ export type MaybeReadable<T> = T | Readable<T>;
6
+ export type SignalRProviderProps = Omit<SignalRProviderPropsBase<never>, "children" | "baseUrl" | "enabled" | "connectionKey"> & {
7
+ baseUrl: MaybeReadable<string | undefined>;
8
+ enabled?: MaybeReadable<boolean>;
9
+ connectionKey?: MaybeReadable<string | number | undefined>;
10
+ };
11
+ export type SignalRContextValue<T extends SignalRContract> = SignalRContextValueBase<T, StatusStore<keyof T & HubString>>;
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,60 @@
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
+ }