@dammers/use-signalr-vue 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +284 -284
  3. package/package.json +61 -61
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 DammersCode
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DammersCode
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,284 +1,284 @@
1
- # @dammers/use-signalr-vue
2
-
3
- A typed, reusable [SignalR](https://learn.microsoft.com/aspnet/core/signalr) plugin and composable set for Vue 3, driven by your contract.
4
-
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.
22
-
23
- ## Install
24
-
25
- ```bash
26
- npm i @dammers/use-signalr-vue @microsoft/signalr
27
- ```
28
-
29
- Requires Vue ≥ 3.3 and `@microsoft/signalr` ≥ 8.
30
-
31
- ## Usage
32
-
33
- ### 1. Define your contract and create the client
34
-
35
- The **keys of `config.hubs` declare the hubs**. Declare server events and methods inline with `event()` and `method()`.
36
-
37
- ```ts
38
- // signalr.ts
39
- import { createSignalRClient, event, method } from "@dammers/use-signalr-vue";
40
-
41
- export const signalR = createSignalRClient({
42
- 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)
53
- },
54
- },
55
- // global defaults (all optional):
56
- // lazy: false, reconnect: true, maxConnectRetries: 2, logLevel: LogLevel.Information
57
- });
58
-
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
- 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
- })
94
- .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
-
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
- });
231
- ```
232
-
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.
279
-
280
- [CONTRIBUTING.md](https://github.com/DammersCode/use-signalr/blob/main/CONTRIBUTING.md) documents the development workflow.
281
-
282
- ## License
283
-
284
- MIT © [DammersCode](https://github.com/DammersCode)
1
+ # @dammers/use-signalr-vue
2
+
3
+ A typed, reusable [SignalR](https://learn.microsoft.com/aspnet/core/signalr) plugin and composable set for Vue 3, driven by your contract.
4
+
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.
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ npm i @dammers/use-signalr-vue @microsoft/signalr
27
+ ```
28
+
29
+ Requires Vue ≥ 3.3 and `@microsoft/signalr` ≥ 8.
30
+
31
+ ## Usage
32
+
33
+ ### 1. Define your contract and create the client
34
+
35
+ The **keys of `config.hubs` declare the hubs**. Declare server events and methods inline with `event()` and `method()`.
36
+
37
+ ```ts
38
+ // signalr.ts
39
+ import { createSignalRClient, event, method } from "@dammers/use-signalr-vue";
40
+
41
+ export const signalR = createSignalRClient({
42
+ 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)
53
+ },
54
+ },
55
+ // global defaults (all optional):
56
+ // lazy: false, reconnect: true, maxConnectRetries: 2, logLevel: LogLevel.Information
57
+ });
58
+
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
+ 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
+ })
94
+ .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
+
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
+ });
231
+ ```
232
+
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.
279
+
280
+ [CONTRIBUTING.md](https://github.com/DammersCode/use-signalr/blob/main/CONTRIBUTING.md) documents the development workflow.
281
+
282
+ ## License
283
+
284
+ MIT © [DammersCode](https://github.com/DammersCode)
package/package.json CHANGED
@@ -1,61 +1,61 @@
1
- {
2
- "name": "@dammers/use-signalr-vue",
3
- "version": "0.4.0",
4
- "description": "Fully-typed multi-hub SignalR plugin + composables for Vue.",
5
- "author": "Dammers",
6
- "license": "MIT",
7
- "repository": {
8
- "type": "git",
9
- "url": "git+https://github.com/DammersCode/use-signalr.git",
10
- "directory": "packages/vue"
11
- },
12
- "homepage": "https://github.com/DammersCode/use-signalr/tree/main/packages/vue#readme",
13
- "bugs": {
14
- "url": "https://github.com/DammersCode/use-signalr/issues"
15
- },
16
- "keywords": [
17
- "signalr",
18
- "typescript",
19
- "realtime",
20
- "websocket",
21
- "vue",
22
- "composables"
23
- ],
24
- "engines": {
25
- "node": ">=18"
26
- },
27
- "type": "module",
28
- "sideEffects": false,
29
- "main": "./dist/index.js",
30
- "types": "./dist/index.d.ts",
31
- "exports": {
32
- ".": {
33
- "types": "./dist/index.d.ts",
34
- "import": "./dist/index.js"
35
- }
36
- },
37
- "files": [
38
- "dist"
39
- ],
40
- "publishConfig": {
41
- "access": "public"
42
- },
43
- "scripts": {
44
- "prebuild": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
45
- "build": "tsc -p tsconfig.build.json",
46
- "typecheck": "tsc --noEmit",
47
- "test": "vitest run"
48
- },
49
- "dependencies": {
50
- "@dammers/use-signalr-core": "0.4.0"
51
- },
52
- "peerDependencies": {
53
- "@microsoft/signalr": ">=8",
54
- "vue": ">=3.3"
55
- },
56
- "devDependencies": {
57
- "@microsoft/signalr": ">=8",
58
- "@vue/test-utils": "^2.4.11",
59
- "vue": "^3.5.40"
60
- }
61
- }
1
+ {
2
+ "name": "@dammers/use-signalr-vue",
3
+ "version": "0.5.0",
4
+ "description": "Fully-typed multi-hub SignalR plugin + composables for Vue.",
5
+ "author": "Dammers",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/DammersCode/use-signalr.git",
10
+ "directory": "packages/vue"
11
+ },
12
+ "homepage": "https://github.com/DammersCode/use-signalr/tree/main/packages/vue#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/DammersCode/use-signalr/issues"
15
+ },
16
+ "keywords": [
17
+ "signalr",
18
+ "typescript",
19
+ "realtime",
20
+ "websocket",
21
+ "vue",
22
+ "composables"
23
+ ],
24
+ "engines": {
25
+ "node": ">=18"
26
+ },
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "main": "./dist/index.js",
30
+ "types": "./dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "import": "./dist/index.js"
35
+ }
36
+ },
37
+ "files": [
38
+ "dist"
39
+ ],
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "scripts": {
44
+ "prebuild": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
45
+ "build": "tsc -p tsconfig.build.json",
46
+ "typecheck": "tsc --noEmit",
47
+ "test": "vitest run"
48
+ },
49
+ "dependencies": {
50
+ "@dammers/use-signalr-core": "0.5.0"
51
+ },
52
+ "peerDependencies": {
53
+ "@microsoft/signalr": ">=8",
54
+ "vue": ">=3.3"
55
+ },
56
+ "devDependencies": {
57
+ "@microsoft/signalr": ">=8",
58
+ "@vue/test-utils": "^2.4.11",
59
+ "vue": "^3.5.40"
60
+ }
61
+ }