@dammers/use-signalr-vue 0.5.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,284 +1,59 @@
1
1
  # @dammers/use-signalr-vue
2
2
 
3
- A typed, reusable [SignalR](https://learn.microsoft.com/aspnet/core/signalr) plugin and composable set for Vue 3, driven by your contract.
3
+ Plugin and composables for typed [SignalR](https://learn.microsoft.com/aspnet/core/signalr) in Vue. Part of [use-signalr](https://use-signalr.vercel.app).
4
4
 
5
5
  [![npm](https://img.shields.io/npm/v/@dammers/use-signalr-vue.svg)](https://www.npmjs.com/package/@dammers/use-signalr-vue)
6
- [![types](https://img.shields.io/badge/types-included-blue.svg)](#api)
7
- [![license](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)
8
-
9
- ```ts
10
- const signalR = 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 Vue plugin and composables. Each member uses types inferred from your hub contract.
20
-
21
- The [root README](https://github.com/DammersCode/use-signalr#readme) documents shared configuration and call behavior. This document covers Vue-specific installation and usage.
6
+ [![license](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/DammersCode/use-signalr/blob/main/LICENSE)
22
7
 
23
8
  ## Install
24
9
 
25
10
  ```bash
26
- npm i @dammers/use-signalr-vue @microsoft/signalr
11
+ npm install @dammers/use-signalr-vue @microsoft/signalr
27
12
  ```
28
13
 
29
- Requires Vue ≥ 3.3 and `@microsoft/signalr` ≥ 8.
30
-
31
- ## Usage
14
+ It needs Vue ^3.3, `@microsoft/signalr` ^8 || ^9 || ^10, and Node 20.19 or later.
32
15
 
33
- ### 1. Define your contract and create the client
16
+ ## Example
34
17
 
35
- The **keys of `config.hubs` declare the hubs**. Declare server events and methods inline with `event()` and `method()`.
18
+ This file declares a hub, connects it, and reads a typed method result:
36
19
 
20
+ <!-- hero:vue:start -->
37
21
  ```ts
38
- // signalr.ts
39
- import { createSignalRClient, event, method } from "@dammers/use-signalr-vue";
22
+ import { createApp, ref } from "vue";
23
+ import { createSignalRClient, method } from "@dammers/use-signalr-vue";
24
+ import App from "./App.vue";
40
25
 
41
26
  export const signalR = createSignalRClient({
42
27
  hubs: {
43
- "/hubs/chat": {
44
- events: {
45
- ReceiveMessage: event<[user: string, message: string]>(),
46
- },
47
- methods: {
48
- SendMessage: method<[roomId: string, message: string]>(),
49
- JoinRoomAsync: method<[roomId: string], { success: boolean }>(),
50
- LeaveRoomAsync: method<[roomId: string]>(),
51
- },
52
- // per-hub config also goes here (see the root README)
28
+ "/hubs/rooms": {
29
+ methods: { GetHistory: method<[roomId: string], { text: string }[]>() },
53
30
  },
54
31
  },
55
- // global defaults (all optional):
56
- // lazy: false, reconnect: true, maxConnectRetries: 2, logLevel: LogLevel.Information
57
32
  });
58
33
 
59
- export const {
60
- useSignalR,
61
- useSignalREvent,
62
- useSignalRInvoke,
63
- useSignalRSend,
64
- useSignalRTeardown,
65
- useHubStatus,
66
- useOnReconnected,
67
- useHubConsumer,
68
- } = signalR;
69
- ```
70
-
71
- `event<Args>()` takes the handler argument tuple. `method<Args, Return>()` takes the argument tuple and resolved return type.
72
-
73
- ### 2. Install the plugin with your authentication
74
-
75
- ```ts
76
- // main.ts
77
- import { computed, createApp, ref } from "vue";
78
- import App from "./App.vue";
79
- import { signalR } from "./signalr";
80
-
81
- const token = ref("");
82
- const enabled = computed(() => token.value.length > 0);
83
-
84
34
  createApp(App)
85
- .use(signalR, {
86
- baseUrl: import.meta.env.VITE_API_URL,
87
- accessTokenFactory: () => token.value,
88
- enabled,
89
- onError: (hub, error) => console.error(`Connection to ${hub} failed`, error),
90
- onStatusChange: (hub, status) => {
91
- if (status === "reconnecting") console.warn(`Reconnecting to ${hub}`);
92
- },
93
- })
35
+ .use(signalR, { baseUrl: "https://api.example.com", accessTokenFactory: () => "token" })
94
36
  .mount("#app");
95
- ```
96
-
97
- `baseUrl`, `enabled`, and `connectionKey` accept a value, ref, computed ref, or getter.
98
-
99
- Changes to these identity values rebuild the connections. `accessTokenFactory` reads the current token during each negotiation without a rebuild.
100
-
101
- ### 3. Use the composables — everything below is fully typed
102
-
103
- ```vue
104
- <script setup lang="ts">
105
- import { onMounted, onUnmounted } from "vue";
106
- import {
107
- useHubConsumer,
108
- useHubStatus,
109
- useOnReconnected,
110
- useSignalR,
111
- useSignalREvent,
112
- useSignalRInvoke,
113
- useSignalRSend,
114
- useSignalRTeardown,
115
- } from "./signalr";
116
-
117
- const roomId = "general";
118
-
119
- // One readonly ref per hub
120
- const status = useHubStatus("/hubs/chat");
121
-
122
- // Event arguments come from the contract
123
- useSignalREvent("/hubs/chat", "ReceiveMessage", (user, message) => {
124
- console.log(user, message);
125
- });
126
-
127
- // Invoke waits for the connection and returns the typed server result
128
- const sendMessage = useSignalRInvoke("/hubs/chat", "SendMessage");
129
- await sendMessage(roomId, "hello");
130
-
131
- // Send drops the call when the hub is not connected
132
- const send = useSignalRSend("/hubs/chat", "SendMessage");
133
- await send(roomId, "typing");
134
-
135
- // Teardown survives component disposal and waits for a connecting hub
136
- const leaveRoom = useSignalRTeardown("/hubs/chat", "LeaveRoomAsync");
137
- onUnmounted(() => void leaveRoom(roomId));
138
-
139
- // Re-sync data after a reconnect
140
- useOnReconnected("/hubs/chat", () => refetchMessages());
141
-
142
- // Keep a lazy hub connected without subscribing to status or events
143
- useHubConsumer("/hubs/chat");
144
-
145
- // Last resort: access the raw HubConnection
146
- const { getConnection } = useSignalR();
147
- onMounted(() => getConnection("/hubs/chat")?.send("SendMessage", roomId, "ready"));
148
- </script>
149
-
150
- <template>
151
- <p>Status: {{ status }}</p>
152
- </template>
153
- ```
154
-
155
- ### Reliable join/leave (session pattern)
156
-
157
- A common pattern joins a session on mount and leaves it on unmount.
158
-
159
- ```vue
160
- <script setup lang="ts">
161
- import { onMounted, onUnmounted } from "vue";
162
- import { useSignalRInvoke, useSignalRTeardown } from "./signalr";
163
37
 
164
- const roomId = "general";
165
- const joinRoom = useSignalRInvoke("/hubs/chat", "JoinRoomAsync");
166
- const leaveRoom = useSignalRTeardown("/hubs/chat", "LeaveRoomAsync");
167
-
168
- onMounted(() => void joinRoom(roomId));
169
- onUnmounted(() => void leaveRoom(roomId));
170
- </script>
171
- ```
172
-
173
- A plain `useSignalRInvoke` or `useSignalRSend` makes the **leave** unreliable:
174
-
175
- - `useSignalRInvoke` aborts active calls on disposal. A leave from `onUnmounted` can stop before it reaches the server.
176
- - `useSignalRSend` drops calls when the hub is not `Connected`. A leave can race a connecting socket.
177
-
178
- `useSignalRTeardown` fixes both cases. It:
179
-
180
- - **survives the calling scope disposal** because it runs detached,
181
- - **queues while connecting** for up to `timeout` (default 10s),
182
- - **holds a lazy hub open** until the send operation is complete.
183
-
184
- It resolves `true` after dispatch. It resolves `false` after a connection timeout and never throws.
185
-
186
- > If an invoke only needs to survive disposal, pass `{ keepAliveOnUnmount: true }`. Use teardown for the connecting race.
187
-
188
- ## Lazy hubs and `graceMs`
189
-
190
- Set `lazy: true` on a hub to connect it only when the first composable for that hub is set up. Consumers are ref-counted.
191
-
192
- After the last consumer is disposed, the connection stays open for `graceMs` milliseconds. If a new consumer appears inside that window, the connection stays. The default is `0`.
193
-
194
- ```ts
195
- createSignalRClient({
196
- hubs: {
197
- "/hubs/presence": { lazy: true, graceMs: 5000 },
198
- },
199
- });
200
- ```
201
-
202
- ## Vue-specific behavior
203
-
204
- - **The configured client is the plugin.** Pass it to `app.use(signalR, options)` before the application mounts.
205
- - **`useHubStatus` returns a readonly `Ref<HubConnectionStatus>`.** Vue templates unwrap it. Scripts read its current value through `.value`.
206
- - **Status refs are granular.** A status change for hub B does not update a consumer of hub A.
207
- - **Composables use the active effect scope.** Components and manual effect scopes release listeners and lazy references during disposal.
208
- - **Hub, event, and method arguments are read once.** Call a composable again when an application needs a different static target.
209
- - **Handlers are normal Vue closures.** Read refs inside handlers to get their current values.
210
- - **The plugin supports reactive identity options.** Only `baseUrl`, `enabled`, and `connectionKey` cause connection rebuilds.
211
-
212
- ## Nuxt and SSR
213
-
214
- Package imports do not access browser globals or start connections. Server plugin installation provides an inert context for composables during rendering.
215
-
216
- Use one universal Nuxt plugin. Do not add the `.client` suffix because server-rendered composables also need the provided context.
217
-
218
- ```ts
219
- // plugins/signalr.ts
220
- import { signalR } from "~/signalr";
221
-
222
- export default defineNuxtPlugin((nuxtApp) => {
223
- const token = useCookie("token");
224
-
225
- nuxtApp.vueApp.use(signalR, {
226
- baseUrl: useRuntimeConfig().public.apiUrl,
227
- enabled: () => import.meta.client && Boolean(token.value),
228
- accessTokenFactory: () => token.value ?? "",
229
- });
230
- });
38
+ // Call this composable in a component's setup().
39
+ export function useHistoryCount(roomId: string) {
40
+ const getHistory = signalR.useSignalRInvoke("/hubs/rooms", "GetHistory");
41
+ const count = ref(0);
42
+ const load = () => getHistory(roomId).then((m) => (count.value = m.length)).catch(console.error);
43
+ return { count, load };
44
+ }
231
45
  ```
46
+ <!-- hero:vue:end -->
232
47
 
233
- The browser installation starts connections. The server installation always reports each hub as `"disconnected"`.
234
-
235
- ## Differences from other Vue SignalR wrappers
236
-
237
- [`@dreamonkey/vue-signalr`](https://www.npmjs.com/package/@dreamonkey/vue-signalr) also uses a Vue plugin and composable.
238
-
239
- That package requires users to build and supply one `HubConnection`. It types commands and events through module augmentation.
240
-
241
- This adapter infers its contract from `config.hubs`. The shared core also manages these behaviors:
242
-
243
- - multiple hubs and shared connections,
244
- - one status ref per hub,
245
- - lazy reference counting and grace periods,
246
- - initial retry and automatic reconnect,
247
- - invoke retry, send, and teardown semantics,
248
- - token rotation without connection recreation.
249
-
250
- ## API
251
-
252
- | Export | Description |
253
- | --- | --- |
254
- | `createSignalRClient(config)` | Returns the configured plugin and composables, typed against the inferred contract. |
255
- | `app.use(signalR, options)` | Builds, starts, retries, and reconnects configured hubs for one Vue application. |
256
- | `useSignalR()` | Returns the raw context, including connection access and point status reads. |
257
- | `useHubStatus(hub)` | Returns a readonly status ref for one hub. It also keeps the hub alive. |
258
- | `useSignalREvent(hub, event, handler)` | Subscribes to a typed server event for the active effect scope. |
259
- | `useSignalRInvoke(hub, method, options?)` | Waits for the connection and returns the typed method result. Retry is optional. |
260
- | `useSignalRSend(hub, method)` | Sends without waiting. It returns `false` when the hub is not connected. |
261
- | `useSignalRTeardown(hub, method, options?)` | Survives disposal, waits while connecting, and holds a lazy hub until dispatch. |
262
- | `useOnReconnected(hub, callback)` | Runs a callback after each reconnect, but not after the first connection. |
263
- | `useHubConsumer(hub)` | Keeps a lazy hub connected for the active effect scope without another subscription. |
264
- | `event<Args>()` | Declares the handler argument tuple for a server event. |
265
- | `method<Args, Return>()` | Declares the argument tuple and return type for a server method. |
266
- | `InvokeError` | Wraps the last invoke failure after configured retries are exhausted. |
267
-
268
- ### Plugin options
269
-
270
- Required: `baseUrl`, `accessTokenFactory`.
271
-
272
- Optional: `enabled` (default `true`), `connectionKey`, `onStatusChange`, `onError`.
273
-
274
- Connection behavior belongs in the configuration passed to `createSignalRClient`.
275
-
276
- ## More
277
-
278
- The [root README](https://github.com/DammersCode/use-signalr#readme) documents per-hub configuration and call semantics.
48
+ ## Documentation
279
49
 
280
- [CONTRIBUTING.md](https://github.com/DammersCode/use-signalr/blob/main/CONTRIBUTING.md) documents the development workflow.
50
+ - [Quick start](https://use-signalr.vercel.app/docs/vue/quick-start)
51
+ - [Provider setup](https://use-signalr.vercel.app/docs/vue/concepts/provider)
52
+ - [Events](https://use-signalr.vercel.app/docs/vue/concepts/events) and [calls](https://use-signalr.vercel.app/docs/vue/concepts/calls)
53
+ - [Connection status](https://use-signalr.vercel.app/docs/vue/concepts/connection-status) and [recovery](https://use-signalr.vercel.app/docs/vue/concepts/recovery)
54
+ - [API reference](https://use-signalr.vercel.app/docs/vue/reference/api)
55
+ - [Troubleshooting](https://use-signalr.vercel.app/docs/vue/reference/troubleshooting)
281
56
 
282
57
  ## License
283
58
 
284
- MIT © [DammersCode](https://github.com/DammersCode)
59
+ [MIT](https://github.com/DammersCode/use-signalr/blob/main/LICENSE) © [DammersCode](https://github.com/DammersCode)
@@ -1,13 +1,62 @@
1
1
  import type { HubDef, HubString, InferContract, SignalRClientConfig } from "@dammers/use-signalr-core";
2
- import type { SignalRContextValue } from "./types.js";
3
2
  /** Creates a typed Vue plugin and the composables bound to its app context. */
4
- export declare function createSignalRClient<const H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>): import("vue").Plugin<[import("./types.js").SignalROptions<InferContract<H>>]> & {
5
- useSignalR: () => SignalRContextValue<InferContract<H>>;
3
+ export declare function createSignalRClient<const H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>): import("vue").Plugin<[import("./types.js").SignalROptions<keyof H & `/${string}`>]> & {
4
+ /**
5
+ * Gives the SignalR context (`getConnection`, `getStatus`, and
6
+ * `waitForConnection`). Use it for the underlying `HubConnection` or a
7
+ * point read. Prefer the typed composables. Call it in `setup()` or inside
8
+ * `app.runWithContext()`.
9
+ */
10
+ useSignalR: () => import("@dammers/use-signalr-core").SignalRPublicContext<InferContract<H>>;
11
+ /**
12
+ * Keeps a (possibly lazy) hub connected while the scope is alive, without
13
+ * subscribing to events or status. Call it in `setup()` or an effect scope.
14
+ */
6
15
  useHubConsumer: <H_1 extends keyof H & `/${string}`>(hub: H_1) => void;
7
- useHubStatus: <H_1 extends keyof H & `/${string}`>(hub: H_1) => Readonly<import("vue").Ref<import("@dammers/use-signalr-core").HubConnectionStatus, import("@dammers/use-signalr-core").HubConnectionStatus>>;
16
+ /**
17
+ * Gives the live connection status of a hub as a read-only `Ref`. It
18
+ * updates only when this hub's status changes. It also keeps a lazy hub
19
+ * connected while the scope is alive. A component that hydrates shows
20
+ * `"idle"` until it mounts. Call it in `setup()` or an effect scope.
21
+ */
22
+ useHubStatus: <H_1 extends keyof H & `/${string}`>(hub: H_1) => import("./status-store.js").HubStatusRef;
23
+ /**
24
+ * Subscribes to a typed server event while the scope is alive. Handler
25
+ * args come from your contract. The subscription survives reconnects and
26
+ * rebuilds. Call it in `setup()` or an effect scope.
27
+ */
8
28
  useSignalREvent: <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;
29
+ /**
30
+ * Gives a typed invoker that waits for the connection and resolves with
31
+ * the method's return value. It fails fast by default. Opt in to retry for
32
+ * idempotent methods only. When the scope ends, a waiting call rejects
33
+ * with `AbortError`, unless you set `keepAliveOnUnmount`. Call it in
34
+ * `setup()` or an effect scope.
35
+ */
9
36
  useSignalRInvoke: <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>>;
37
+ /**
38
+ * Gives a typed fire-and-forget sender. It does not wait for the
39
+ * connection. It resolves `true` when it sends the call. It resolves
40
+ * `false` when the hub is not connected and it drops the call, or when
41
+ * the send fails. It never throws, so a cleanup can call it. For a call
42
+ * that must land in a cleanup, use `useSignalRTeardown`. Call it in
43
+ * `setup()` or an effect scope.
44
+ */
10
45
  useSignalRSend: <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>;
46
+ /**
47
+ * Gives a typed teardown sender for a method that a cleanup invokes. It
48
+ * survives the end of the calling scope, queues while the hub connects,
49
+ * and holds a lazy hub open until the flush completes. It resolves `true`
50
+ * when it dispatches the call. It resolves `false` when the hub does not
51
+ * connect in time, the session is disabled, the hub failed, or the send
52
+ * fails. It never throws. Call it in `setup()` or an effect scope.
53
+ */
11
54
  useSignalRTeardown: <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
+ * Runs a callback after each reconnect, not the first connect, to refetch
57
+ * state that went stale while offline. It also runs after a rebuild from
58
+ * a `baseUrl`, `enabled`, or `connectionKey` change. Call it in `setup()`
59
+ * or an effect scope.
60
+ */
12
61
  useOnReconnected: <H_1 extends keyof H & `/${string}`>(hub: H_1, callback: () => void) => void;
13
62
  };
@@ -4,8 +4,68 @@ import { createPlugin } from "./internal/create-plugin.js";
4
4
  /** Creates a typed Vue plugin and the composables bound to its app context. */
5
5
  export function createSignalRClient(config) {
6
6
  const hubs = hubKeys(config);
7
- const resolved = new Map(hubs.map((hub) => [hub, resolveHubConfig(config, config.hubs[hub])]));
7
+ const resolved = new Map(hubs.map((hub) => [hub, resolveHubConfig(config, hub)]));
8
8
  const key = Symbol("use-signalr");
9
9
  const plugin = createPlugin(key, hubs, (hub) => resolved.get(hub));
10
- return Object.assign(plugin, createComposables(key));
10
+ const composables = createComposables(key);
11
+ return Object.assign(plugin, {
12
+ /**
13
+ * Gives the SignalR context (`getConnection`, `getStatus`, and
14
+ * `waitForConnection`). Use it for the underlying `HubConnection` or a
15
+ * point read. Prefer the typed composables. Call it in `setup()` or inside
16
+ * `app.runWithContext()`.
17
+ */
18
+ useSignalR: composables.useSignalR,
19
+ /**
20
+ * Keeps a (possibly lazy) hub connected while the scope is alive, without
21
+ * subscribing to events or status. Call it in `setup()` or an effect scope.
22
+ */
23
+ useHubConsumer: composables.useHubConsumer,
24
+ /**
25
+ * Gives the live connection status of a hub as a read-only `Ref`. It
26
+ * updates only when this hub's status changes. It also keeps a lazy hub
27
+ * connected while the scope is alive. A component that hydrates shows
28
+ * `"idle"` until it mounts. Call it in `setup()` or an effect scope.
29
+ */
30
+ useHubStatus: composables.useHubStatus,
31
+ /**
32
+ * Subscribes to a typed server event while the scope is alive. Handler
33
+ * args come from your contract. The subscription survives reconnects and
34
+ * rebuilds. Call it in `setup()` or an effect scope.
35
+ */
36
+ useSignalREvent: composables.useSignalREvent,
37
+ /**
38
+ * Gives a typed invoker that waits for the connection and resolves with
39
+ * the method's return value. It fails fast by default. Opt in to retry for
40
+ * idempotent methods only. When the scope ends, a waiting call rejects
41
+ * with `AbortError`, unless you set `keepAliveOnUnmount`. Call it in
42
+ * `setup()` or an effect scope.
43
+ */
44
+ useSignalRInvoke: composables.useSignalRInvoke,
45
+ /**
46
+ * Gives a typed fire-and-forget sender. It does not wait for the
47
+ * connection. It resolves `true` when it sends the call. It resolves
48
+ * `false` when the hub is not connected and it drops the call, or when
49
+ * the send fails. It never throws, so a cleanup can call it. For a call
50
+ * that must land in a cleanup, use `useSignalRTeardown`. Call it in
51
+ * `setup()` or an effect scope.
52
+ */
53
+ useSignalRSend: composables.useSignalRSend,
54
+ /**
55
+ * Gives a typed teardown sender for a method that a cleanup invokes. It
56
+ * survives the end of the calling scope, queues while the hub connects,
57
+ * and holds a lazy hub open until the flush completes. It resolves `true`
58
+ * when it dispatches the call. It resolves `false` when the hub does not
59
+ * connect in time, the session is disabled, the hub failed, or the send
60
+ * fails. It never throws. Call it in `setup()` or an effect scope.
61
+ */
62
+ useSignalRTeardown: composables.useSignalRTeardown,
63
+ /**
64
+ * Runs a callback after each reconnect, not the first connect, to refetch
65
+ * state that went stale while offline. It also runs after a rebuild from
66
+ * a `baseUrl`, `enabled`, or `connectionKey` change. Call it in `setup()`
67
+ * or an effect scope.
68
+ */
69
+ useOnReconnected: composables.useOnReconnected,
70
+ });
11
71
  }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { createSignalRClient } from "./create-signalr-client.js";
2
- export { InvokeError, event, method } from "@dammers/use-signalr-core";
3
- export type { StatusStore } from "./status-store.js";
4
- export type { MaybeRefOrGetter, SignalROptions, SignalRContextValue, } from "./types.js";
5
- 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";
2
+ export { event, method } from "@dammers/use-signalr-core";
3
+ export type { HubStatusRef } from "./status-store.js";
4
+ export type { MaybeRefOrGetter, SignalROptions, } from "./types.js";
5
+ 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";
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  export { createSignalRClient } from "./create-signalr-client.js";
2
- export { InvokeError, event, method } from "@dammers/use-signalr-core";
2
+ export { event, method } from "@dammers/use-signalr-core";
@@ -1,10 +1,11 @@
1
1
  import type { InjectionKey } from "vue";
2
- import type { EventArgs, EventName, InvokeOptions, MethodName, SignalRContract, TeardownOptions } from "@dammers/use-signalr-core";
2
+ import type { EventArgs, EventName, InvokeOptions, MethodName, SignalRContract, SignalRPublicContext, TeardownOptions } from "@dammers/use-signalr-core";
3
+ import type { HubStatusRef } from "../status-store.js";
3
4
  import type { SignalRContextValue } from "../types.js";
4
5
  export declare function createComposables<T extends SignalRContract>(key: InjectionKey<SignalRContextValue<T>>): {
5
- useSignalR: () => SignalRContextValue<T>;
6
+ useSignalR: () => SignalRPublicContext<T>;
6
7
  useHubConsumer: <H extends keyof T & `/${string}`>(hub: H) => void;
7
- useHubStatus: <H extends keyof T & `/${string}`>(hub: H) => Readonly<import("vue").Ref<import("@dammers/use-signalr-core").HubConnectionStatus, import("@dammers/use-signalr-core").HubConnectionStatus>>;
8
+ useHubStatus: <H extends keyof T & `/${string}`>(hub: H) => HubStatusRef;
8
9
  useSignalREvent: <H extends keyof T & `/${string}`, E extends EventName<T, H>>(hub: H, event: E, handler: (...args: EventArgs<T, H, E>) => void) => void;
9
10
  useSignalRInvoke: <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>>;
10
11
  useSignalRSend: <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>;
@@ -1,62 +1,79 @@
1
- import { inject, onScopeDispose, watch } from "vue";
1
+ import { computed, getCurrentInstance, getCurrentScope, hasInjectionContext, inject, onMounted, onScopeDispose, shallowRef, } from "vue";
2
2
  import { createAbortScope, createInvoker, createSender, createTeardownSender, } from "@dammers/use-signalr-core";
3
3
  export function createComposables(key) {
4
- function useSignalR() {
4
+ function useInternalContext(name) {
5
+ if (!hasInjectionContext())
6
+ throw new Error(`${name} must be called inside setup() or app.runWithContext()`);
5
7
  const context = inject(key, null);
6
8
  if (!context)
7
9
  throw new Error("useSignalR must be used after app.use(signalR, options)");
8
10
  return context;
9
11
  }
10
- function useHubConsumer(hub) {
11
- const context = useSignalR();
12
+ function useScopedContext(name) {
13
+ if (!getCurrentScope())
14
+ throw new Error(`${name} must be called inside setup() or an effectScope`);
15
+ return useInternalContext(name);
16
+ }
17
+ function useSignalR() {
18
+ return useInternalContext("useSignalR").publicContext;
19
+ }
20
+ function consume(context, hub) {
12
21
  context.acquire(hub);
13
22
  onScopeDispose(() => context.release(hub));
14
23
  }
24
+ function useHubConsumer(hub) {
25
+ consume(useScopedContext("useHubConsumer"), hub);
26
+ }
15
27
  function useHubStatus(hub) {
16
- const context = useSignalR();
17
- useHubConsumer(hub);
18
- return context.statusStore.ref(hub);
28
+ const context = useScopedContext("useHubStatus");
29
+ consume(context, hub);
30
+ const status = context.statusStore.ref(hub);
31
+ if (!getCurrentInstance()?.vnode.el)
32
+ return status;
33
+ // Async components hydrate after the session started; idle until mount matches the server HTML.
34
+ const mounted = shallowRef(false);
35
+ onMounted(() => {
36
+ mounted.value = true;
37
+ });
38
+ return computed(() => (mounted.value ? status.value : "idle"));
19
39
  }
20
40
  function useSignalREvent(hub, event, handler) {
21
- const context = useSignalR();
22
- useHubConsumer(hub);
23
- const stop = watch(() => context.statusStore.ref(hub).value, (status, _, cleanup) => {
24
- if (status !== "connected")
25
- return;
26
- const connection = context.getConnection(hub);
27
- if (!connection)
28
- return;
29
- const listener = (...args) => handler(...args);
30
- connection.on(event, listener);
31
- cleanup(() => connection.off(event, listener));
32
- }, { immediate: true, flush: "sync" });
33
- onScopeDispose(stop);
41
+ const context = useScopedContext("useSignalREvent");
42
+ consume(context, hub);
43
+ const unsubscribe = context.subscribe(hub, event, (...args) => handler(...args));
44
+ onScopeDispose(unsubscribe);
34
45
  }
35
46
  function useOnReconnected(hub, callback) {
36
- const context = useSignalR();
37
- useHubConsumer(hub);
38
- const unregister = context.registerReconnect(hub, callback);
47
+ const context = useScopedContext("useOnReconnected");
48
+ consume(context, hub);
49
+ const unregister = context.registerReconnect(hub, () => callback());
39
50
  onScopeDispose(unregister);
40
51
  }
41
52
  function useSignalRInvoke(hub, method, options) {
42
- const context = useSignalR();
43
- useHubConsumer(hub);
53
+ const context = useScopedContext("useSignalRInvoke");
54
+ consume(context, hub);
44
55
  const scope = createAbortScope();
45
56
  onScopeDispose(() => {
46
57
  if (!options?.keepAliveOnUnmount)
47
- scope.abortAll();
58
+ scope.abort();
59
+ });
60
+ return createInvoker({
61
+ target: context,
62
+ hub,
63
+ method,
64
+ getOptions: () => options,
65
+ getSignal: scope.signal,
48
66
  });
49
- return createInvoker(context, hub, method, () => options, scope.track, scope.untrack);
50
67
  }
51
68
  function useSignalRSend(hub, method) {
52
- const context = useSignalR();
53
- useHubConsumer(hub);
54
- return createSender(context.getConnection, hub, method);
69
+ const context = useScopedContext("useSignalRSend");
70
+ consume(context, hub);
71
+ return createSender({ getConnection: context.getConnection, hub, method });
55
72
  }
56
73
  function useSignalRTeardown(hub, method, options) {
57
- const context = useSignalR();
58
- useHubConsumer(hub);
59
- return createTeardownSender(context, hub, method, () => options);
74
+ const context = useScopedContext("useSignalRTeardown");
75
+ consume(context, hub);
76
+ return createTeardownSender({ target: context, hub, method, getOptions: () => options });
60
77
  }
61
78
  return {
62
79
  useSignalR,
@@ -1,4 +1,4 @@
1
1
  import type { InjectionKey, Plugin } from "vue";
2
2
  import type { HubString, ResolvedHubConfig, SignalRContract } from "@dammers/use-signalr-core";
3
3
  import type { SignalRContextValue, SignalROptions } from "../types.js";
4
- export declare function createPlugin<T extends SignalRContract>(key: InjectionKey<SignalRContextValue<T>>, hubs: Array<keyof T & HubString>, resolve: (hub: keyof T & HubString) => ResolvedHubConfig): Plugin<[SignalROptions<T>]>;
4
+ export declare function createPlugin<T extends SignalRContract>(key: InjectionKey<SignalRContextValue<T>>, hubs: Array<keyof T & HubString>, resolve: (hub: keyof T & HubString) => ResolvedHubConfig): Plugin<[SignalROptions<keyof T & HubString>]>;
@@ -11,7 +11,7 @@ export function createPlugin(key, hubs, resolve) {
11
11
  statusStore,
12
12
  getAccessToken: () => options.accessTokenFactory(),
13
13
  onStatusChange: (hub, status) => options.onStatusChange?.(hub, status),
14
- onError: (hub, error) => options.onError?.(hub, error),
14
+ onError: (hub, error, info) => options.onError?.(hub, error, info),
15
15
  });
16
16
  app.provide(key, session.context);
17
17
  let disposed = false;
@@ -22,20 +22,29 @@ export function createPlugin(key, hubs, resolve) {
22
22
  scope?.stop();
23
23
  session.stop();
24
24
  };
25
- const scope = typeof window === "undefined" ? undefined : effectScope();
26
- scope?.run(() => {
27
- watch(() => [toValue(options.baseUrl), toValue(options.enabled ?? true), toValue(options.connectionKey)], ([baseUrl, enabled]) => {
28
- session.stop();
29
- if (enabled && baseUrl)
30
- session.start(baseUrl);
31
- }, { immediate: true });
25
+ const scope = typeof window === "undefined" ? undefined : effectScope(true);
26
+ const startWatching = () => scope?.run(() => {
27
+ watch(() => ({
28
+ baseUrl: toValue(options.baseUrl),
29
+ enabled: toValue(options.enabled ?? true),
30
+ connectionKey: toValue(options.connectionKey),
31
+ }), (values) => session.update(values), { immediate: true });
32
32
  });
33
- const appWithHook = app;
34
- if (appWithHook.onUnmount)
35
- appWithHook.onUnmount(dispose);
33
+ // Starting after mount keeps the first client render equal to the server HTML.
34
+ const mount = app.mount.bind(app);
35
+ app.mount = (...args) => {
36
+ const instance = mount(...args);
37
+ if (instance)
38
+ startWatching();
39
+ return instance;
40
+ };
41
+ const unmount = app.unmount.bind(app);
42
+ // On Vue 3.5 types the else branch narrows `app` to never, so it writes through a plain `App`.
43
+ const fallbackTarget = app;
44
+ if (hasOnUnmount(app))
45
+ app.onUnmount(dispose);
36
46
  else {
37
- const unmount = app.unmount.bind(app);
38
- app.unmount = () => {
47
+ fallbackTarget.unmount = () => {
39
48
  dispose();
40
49
  unmount();
41
50
  };
@@ -43,3 +52,7 @@ export function createPlugin(key, hubs, resolve) {
43
52
  },
44
53
  };
45
54
  }
55
+ // Vue before 3.5 has no app.onUnmount, and its App type does not declare it.
56
+ function hasOnUnmount(app) {
57
+ return "onUnmount" in app;
58
+ }
@@ -1,7 +1,10 @@
1
1
  import type { Ref } from "vue";
2
2
  import type { HubConnectionStatus, StatusStore as StatusStoreBase } from "@dammers/use-signalr-core";
3
+ /** Read-only ref with the status of one hub. */
4
+ export interface HubStatusRef extends Readonly<Ref<HubConnectionStatus>> {
5
+ }
3
6
  export interface StatusStore<H extends string> extends StatusStoreBase<H> {
4
- ref: (hub: H) => Readonly<Ref<HubConnectionStatus>>;
7
+ ref: (hub: H) => HubStatusRef;
5
8
  }
6
9
  /** One shallow ref per hub prevents unrelated status writes from invalidating it. */
7
10
  export declare function createStatusStore<H extends string>(): StatusStore<H>;
@@ -5,7 +5,7 @@ export function createStatusStore() {
5
5
  const getOrCreate = (hub) => {
6
6
  let value = refs.get(hub);
7
7
  if (!value) {
8
- value = shallowRef("disconnected");
8
+ value = shallowRef("idle");
9
9
  refs.set(hub, value);
10
10
  }
11
11
  return value;
package/dist/types.d.ts CHANGED
@@ -1,12 +1,16 @@
1
1
  import type { MaybeRefOrGetter } from "vue";
2
- import type { HubConnectionStatus, HubString, SignalRContract, SignalRContextValueBase, SignalRProviderPropsBase } from "@dammers/use-signalr-core";
2
+ import type { HubString, SignalRContract, SignalRContextValueBase, SignalRProviderPropsBase } from "@dammers/use-signalr-core";
3
3
  import type { StatusStore } from "./status-store.js";
4
4
  export type { MaybeRefOrGetter } from "vue";
5
- export type SignalROptions<T extends SignalRContract = SignalRContract> = Omit<SignalRProviderPropsBase<never>, "children" | "baseUrl" | "enabled" | "connectionKey" | "onStatusChange" | "onError"> & {
5
+ export type SignalROptions<THub extends HubString = HubString> = Omit<SignalRProviderPropsBase<THub>, "baseUrl" | "enabled" | "connectionKey"> & {
6
+ /** 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. */
6
7
  baseUrl: MaybeRefOrGetter<string | undefined>;
8
+ /**
9
+ * 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`.
10
+ * @default true
11
+ */
7
12
  enabled?: MaybeRefOrGetter<boolean>;
13
+ /** A new value rebuilds all connections. Use it to recover from `disconnected`. Pass a user ID or a login counter, not the token. */
8
14
  connectionKey?: MaybeRefOrGetter<string | number | undefined>;
9
- onStatusChange?: (hub: keyof T & HubString, status: HubConnectionStatus) => void;
10
- onError?: (hub: keyof T & HubString, error: unknown) => void;
11
15
  };
12
16
  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-vue",
3
- "version": "0.5.0",
3
+ "version": "1.0.0",
4
4
  "description": "Fully-typed multi-hub SignalR plugin + composables for Vue.",
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/vue"
11
11
  },
12
- "homepage": "https://github.com/DammersCode/use-signalr/tree/main/packages/vue#readme",
12
+ "homepage": "https://use-signalr.vercel.app/docs/vue",
13
13
  "bugs": {
14
14
  "url": "https://github.com/DammersCode/use-signalr/issues"
15
15
  },
@@ -22,7 +22,7 @@
22
22
  "composables"
23
23
  ],
24
24
  "engines": {
25
- "node": ">=18"
25
+ "node": ">=20.19"
26
26
  },
27
27
  "type": "module",
28
28
  "sideEffects": false,
@@ -31,8 +31,10 @@
31
31
  "exports": {
32
32
  ".": {
33
33
  "types": "./dist/index.d.ts",
34
- "import": "./dist/index.js"
35
- }
34
+ "import": "./dist/index.js",
35
+ "default": "./dist/index.js"
36
+ },
37
+ "./package.json": "./package.json"
36
38
  },
37
39
  "files": [
38
40
  "dist"
@@ -47,15 +49,15 @@
47
49
  "test": "vitest run"
48
50
  },
49
51
  "dependencies": {
50
- "@dammers/use-signalr-core": "0.5.0"
52
+ "@dammers/use-signalr-core": "1.0.0"
51
53
  },
52
54
  "peerDependencies": {
53
- "@microsoft/signalr": ">=8",
54
- "vue": ">=3.3"
55
+ "@microsoft/signalr": "^8.0.0 || ^9.0.0 || ^10.0.0",
56
+ "vue": "^3.3.0"
55
57
  },
56
58
  "devDependencies": {
57
- "@microsoft/signalr": ">=8",
59
+ "@microsoft/signalr": "^8.0.0 || ^9.0.0 || ^10.0.0",
58
60
  "@vue/test-utils": "^2.4.11",
59
- "vue": "^3.5.40"
61
+ "vue": "^3.3.0"
60
62
  }
61
63
  }