@dammers/use-signalr-lit 0.5.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -173
- package/dist/create-signalr-client.d.ts +44 -11
- package/dist/create-signalr-client.js +101 -70
- package/dist/index.d.ts +4 -3
- package/dist/index.js +1 -1
- package/dist/status-store.js +2 -2
- package/dist/types.d.ts +6 -6
- package/package.json +12 -10
package/README.md
CHANGED
|
@@ -1,203 +1,63 @@
|
|
|
1
1
|
# @dammers/use-signalr-lit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Reactive controllers for typed [SignalR](https://learn.microsoft.com/aspnet/core/signalr) in Lit. Part of [use-signalr](https://use-signalr.vercel.app).
|
|
4
4
|
|
|
5
5
|
[](https://www.npmjs.com/package/@dammers/use-signalr-lit)
|
|
6
|
-
[](./LICENSE)
|
|
8
|
-
|
|
9
|
-
```ts
|
|
10
|
-
const { createSession } = createSignalRClient({
|
|
11
|
-
hubs: {
|
|
12
|
-
"/hubs/chat": {
|
|
13
|
-
methods: { Join: method<[room: string]>() },
|
|
14
|
-
},
|
|
15
|
-
},
|
|
16
|
-
});
|
|
17
|
-
```
|
|
18
|
-
|
|
19
|
-
One factory call infers every hub, event, method, argument, and result type. Reactive Controllers adapt the shared core session to Lit.
|
|
20
|
-
|
|
21
|
-
The [root README](https://github.com/DammersCode/use-signalr#readme) documents shared configuration and call behavior. This document covers Lit-specific installation and usage.
|
|
6
|
+
[](https://github.com/DammersCode/use-signalr/blob/main/LICENSE)
|
|
22
7
|
|
|
23
8
|
## Install
|
|
24
9
|
|
|
25
10
|
```bash
|
|
26
|
-
npm
|
|
11
|
+
npm install @dammers/use-signalr-lit @microsoft/signalr
|
|
27
12
|
```
|
|
28
13
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
## Usage
|
|
14
|
+
It needs Lit ^3, `@microsoft/signalr` ^8 || ^9 || ^10 || ^11, and Node 20.19 or later.
|
|
32
15
|
|
|
33
|
-
|
|
16
|
+
## Example
|
|
34
17
|
|
|
35
|
-
|
|
18
|
+
This file declares a hub, connects it, and reads a typed method result:
|
|
36
19
|
|
|
20
|
+
<!-- hero:lit:start -->
|
|
37
21
|
```ts
|
|
38
|
-
import {
|
|
22
|
+
import { LitElement, html } from "lit";
|
|
23
|
+
import { customElement, state } from "lit/decorators.js";
|
|
24
|
+
import { createSignalRClient, method } from "@dammers/use-signalr-lit";
|
|
39
25
|
|
|
40
|
-
|
|
26
|
+
const { createSession } = createSignalRClient({
|
|
41
27
|
hubs: {
|
|
42
|
-
"/hubs/
|
|
43
|
-
|
|
44
|
-
events: { Receive: event<[user: string, text: string]>() },
|
|
45
|
-
methods: {
|
|
46
|
-
Join: method<[room: string]>(),
|
|
47
|
-
Typing: method<[room: string]>(),
|
|
48
|
-
Leave: method<[room: string]>(),
|
|
49
|
-
},
|
|
28
|
+
"/hubs/rooms": {
|
|
29
|
+
methods: { GetHistory: method<[roomId: string], { text: string }[]>() },
|
|
50
30
|
},
|
|
51
31
|
},
|
|
52
32
|
});
|
|
33
|
+
const session = createSession({ baseUrl: "https://api.example.com", accessTokenFactory: () => "token" });
|
|
53
34
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
The factory does not start connections. The first connected controller starts the shared session.
|
|
61
|
-
|
|
62
|
-
### 2. Attach a hub controller
|
|
63
|
-
|
|
64
|
-
Create one hub controller in each custom element that uses a hub.
|
|
35
|
+
@customElement("history-count")
|
|
36
|
+
export class HistoryCount extends LitElement {
|
|
37
|
+
private rooms = session.hub(this, "/hubs/rooms");
|
|
38
|
+
private getHistory = this.rooms.invoke("GetHistory");
|
|
39
|
+
@state() private count = 0;
|
|
65
40
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
import { signalRSession } from "./signalr";
|
|
69
|
-
|
|
70
|
-
class ChatView extends LitElement {
|
|
71
|
-
private readonly chat = signalRSession.hub(this, "/hubs/chat", {
|
|
72
|
-
reactiveStatus: true,
|
|
73
|
-
});
|
|
74
|
-
private readonly join = this.chat.invoke("Join");
|
|
75
|
-
private readonly leave = this.chat.teardown("Leave");
|
|
76
|
-
|
|
77
|
-
constructor() {
|
|
78
|
-
super();
|
|
79
|
-
this.chat.on("Receive", (user, text) => console.log(user, text));
|
|
80
|
-
this.chat.onReconnected(() => this.loadMessages());
|
|
41
|
+
private load() {
|
|
42
|
+
this.getHistory("general").then((m) => (this.count = m.length)).catch(console.error);
|
|
81
43
|
}
|
|
82
44
|
|
|
83
|
-
render() {
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
```
|
|
87
|
-
|
|
88
|
-
The controller acquires the lazy hub in `hostConnected()`. It releases the hub and event listeners in `hostDisconnected()`.
|
|
89
|
-
|
|
90
|
-
### 3. Invoke, send, and teardown
|
|
91
|
-
|
|
92
|
-
The call factories preserve the method types from the contract.
|
|
93
|
-
|
|
94
|
-
```ts
|
|
95
|
-
private readonly join = this.chat.invoke("Join");
|
|
96
|
-
private readonly typing = this.chat.send("Typing");
|
|
97
|
-
private readonly leave = this.chat.teardown("Leave");
|
|
98
|
-
|
|
99
|
-
async enterRoom(room: string) {
|
|
100
|
-
await this.join(room);
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
override disconnectedCallback() {
|
|
104
|
-
super.disconnectedCallback();
|
|
105
|
-
void this.leave("general");
|
|
45
|
+
render() {
|
|
46
|
+
return html`<button @click=${this.load}>${this.count} messages</button>`;
|
|
47
|
+
}
|
|
106
48
|
}
|
|
107
49
|
```
|
|
50
|
+
<!-- hero:lit:end -->
|
|
108
51
|
|
|
109
|
-
##
|
|
110
|
-
|
|
111
|
-
Set `reactiveStatus: true` when status changes must render the host. The controller requests updates only for that hub. Events are imperative. An event handler does not request a render. Call `this.requestUpdate()` in the handler when event data changes rendered state.
|
|
112
|
-
|
|
113
|
-
`on(event, handler)` returns an unsubscribe function. Multiple handlers can use the same event. `onReconnected(callback)` runs after reconnect.
|
|
114
|
-
|
|
115
|
-
## Calls and lazy hubs
|
|
116
|
-
|
|
117
|
-
`invoke(method, options?)` waits for a connection and returns the typed result. It aborts pending retry work when the host disconnects unless `keepAliveOnUnmount` is true.
|
|
118
|
-
|
|
119
|
-
`send(method)` returns `false` when the hub is disconnected. `teardown(method, options?)` waits for a connection and remains active after host disconnection. Use teardown calls for leave operations.
|
|
120
|
-
|
|
121
|
-
`invoke` accepts a `timeout`. It bounds only the wait for a connected hub before dispatch. SignalR cannot cancel an invocation after dispatch.
|
|
122
|
-
|
|
123
|
-
Lazy hubs connect when a controller host connects. They stop after all hosts disconnect and the configured `graceMs` period passes.
|
|
124
|
-
|
|
125
|
-
Set `graceMs` for each hub in the client configuration. After the last host disconnects, the connection stays open for `graceMs` milliseconds. If a new host connects inside that window, the connection stays. The default is `0`.
|
|
126
|
-
|
|
127
|
-
```ts
|
|
128
|
-
createSignalRClient({
|
|
129
|
-
hubs: {
|
|
130
|
-
"/hubs/chat": { lazy: true, graceMs: 5000 },
|
|
131
|
-
},
|
|
132
|
-
});
|
|
133
|
-
```
|
|
134
|
-
|
|
135
|
-
Eager hubs remain active until `signalRSession.stop()` runs.
|
|
136
|
-
|
|
137
|
-
## `InvokeError`
|
|
138
|
-
|
|
139
|
-
`invoke` throws `InvokeError` when its retry budget is exhausted. The error carries `cause` (the last underlying error), `attempts` (the total number of attempts), and `retriable` (whether the final failure was classed as retriable).
|
|
140
|
-
|
|
141
|
-
`InvokeError` is thrown only when you set `retries` above `0`. With the default `retries: 0`, the raw server error propagates unchanged.
|
|
142
|
-
|
|
143
|
-
## Sharing across custom elements
|
|
144
|
-
|
|
145
|
-
Export the session from a normal module. Import the same session into each custom element that needs SignalR.
|
|
146
|
-
|
|
147
|
-
This pattern does not require a global application root or `@lit/context`. Components in separate DOM trees can share the same session instance.
|
|
148
|
-
|
|
149
|
-
Create a different session when an application needs an independent base URL or authentication boundary. Call `signalRSession.stop()` during logout or application shutdown.
|
|
150
|
-
|
|
151
|
-
The current token is read through `accessTokenFactory` during each negotiation. Token rotation does not create a new session.
|
|
152
|
-
|
|
153
|
-
## Session options are read once
|
|
154
|
-
|
|
155
|
-
The session reads `baseUrl` and `enabled` once, when the first host connects. There is no `connectionKey`.
|
|
156
|
-
|
|
157
|
-
To change either option, call `session.stop()` and create a new session with the new values. This is intentional. Lit has no application-wide provider to watch for a changed option.
|
|
158
|
-
|
|
159
|
-
```ts
|
|
160
|
-
signalRSession.stop();
|
|
161
|
-
export const signalRSession = signalR.createSession({ baseUrl: nextUrl });
|
|
162
|
-
```
|
|
163
|
-
|
|
164
|
-
Every other adapter rebuilds its connections when `baseUrl`, `enabled`, or `connectionKey` change.
|
|
165
|
-
|
|
166
|
-
## Raw escape hatch
|
|
167
|
-
|
|
168
|
-
`session.context` exposes the raw core context: `getConnection`, `isHubConnected`, and `getStatus`. Use it only when the typed controller surface cannot express a call.
|
|
169
|
-
|
|
170
|
-
```ts
|
|
171
|
-
signalRSession.context.getConnection("/hubs/chat")?.send("Typing", "general");
|
|
172
|
-
```
|
|
173
|
-
|
|
174
|
-
This member has the same role as `useSignalR()` in React, `getSignalR()` in Svelte, and `injectSignalR()` in Angular.
|
|
175
|
-
|
|
176
|
-
## SSR
|
|
177
|
-
|
|
178
|
-
Package import, client creation, session creation, and controller construction do not start connections. Lit calls `hostConnected()` only in the browser.
|
|
179
|
-
|
|
180
|
-
## API
|
|
181
|
-
|
|
182
|
-
| Export | Description |
|
|
183
|
-
| --- | --- |
|
|
184
|
-
| `createSignalRClient(config)` | Creates a typed client factory. |
|
|
185
|
-
| `createSession(options)` | Creates an explicit shared runtime session. |
|
|
186
|
-
| `session.hub(host, hub, options?)` | Creates a per-hub Reactive Controller. |
|
|
187
|
-
| `controller.status` | Reads the current hub status. |
|
|
188
|
-
| `controller.on()` | Registers a typed imperative event handler. |
|
|
189
|
-
| `controller.invoke()` | Creates a typed invoker. |
|
|
190
|
-
| `controller.send()` | Creates a typed lossy sender. |
|
|
191
|
-
| `controller.teardown()` | Creates a typed reliable teardown sender. |
|
|
192
|
-
| `controller.onReconnected()` | Registers a callback that runs after reconnect. |
|
|
193
|
-
| `session.context` | Reads the raw core context: `getConnection`, `isHubConnected`, `getStatus`. |
|
|
194
|
-
| `session.stop()` | Stops all connections in the shared session. |
|
|
195
|
-
| `InvokeError` | Wraps the last invoke failure after configured retries are exhausted. |
|
|
196
|
-
|
|
197
|
-
## More
|
|
52
|
+
## Documentation
|
|
198
53
|
|
|
199
|
-
|
|
54
|
+
- [Quick start](https://use-signalr.vercel.app/docs/lit/quick-start)
|
|
55
|
+
- [Session setup](https://use-signalr.vercel.app/docs/lit/concepts/provider)
|
|
56
|
+
- [Events](https://use-signalr.vercel.app/docs/lit/concepts/events) and [calls](https://use-signalr.vercel.app/docs/lit/concepts/calls)
|
|
57
|
+
- [Connection status](https://use-signalr.vercel.app/docs/lit/concepts/connection-status) and [recovery](https://use-signalr.vercel.app/docs/lit/concepts/recovery)
|
|
58
|
+
- [API reference](https://use-signalr.vercel.app/docs/lit/reference/api)
|
|
59
|
+
- [Troubleshooting](https://use-signalr.vercel.app/docs/lit/reference/troubleshooting)
|
|
200
60
|
|
|
201
61
|
## License
|
|
202
62
|
|
|
203
|
-
MIT © [DammersCode](https://github.com/DammersCode)
|
|
63
|
+
[MIT](https://github.com/DammersCode/use-signalr/blob/main/LICENSE) © [DammersCode](https://github.com/DammersCode)
|
|
@@ -1,17 +1,40 @@
|
|
|
1
1
|
import type { ReactiveController, ReactiveControllerHost } from "lit";
|
|
2
|
-
import type { EventArgs, EventName, HubConnectionStatus, HubDef, HubString, InferContract, InvokeOptions, MethodName, SignalRClientConfig, SignalRContract, TeardownOptions } from "@dammers/use-signalr-core";
|
|
3
|
-
import type { SignalRContextValue, SignalRSessionOptions } from "./types.js";
|
|
2
|
+
import type { EventArgs, EventName, HubConnectionStatus, HubDef, HubString, InferContract, InvokeOptions, MethodName, ResolvedHubConfig, SignalRClientConfig, SignalRContract, TeardownOptions } from "@dammers/use-signalr-core";
|
|
3
|
+
import type { SignalRContextValue, SignalRSessionOptions, SignalRSessionUpdate } from "./types.js";
|
|
4
|
+
/** Creates a typed SignalR client. Call `createSession` once to get a session for your app. */
|
|
4
5
|
export declare function createSignalRClient<const H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>): {
|
|
6
|
+
/** Builds a session that starts, retries, and reconnects every configured hub. It starts when the first host connects. Pass `baseUrl` and `accessTokenFactory`, and gate them with `enabled`. */
|
|
5
7
|
createSession(options: SignalRSessionOptions<keyof H & `/${string}`>): {
|
|
8
|
+
/** Creates a `HubController` for one hub on a Lit host. The hub connects while the host is connected. */
|
|
6
9
|
hub: <H_1 extends keyof H & `/${string}`>(host: ReactiveControllerHost, name: H_1, controllerOptions?: {
|
|
10
|
+
/** Set to `false` to not request a host update on each status change. The default is `true`. */
|
|
7
11
|
reactiveStatus?: boolean;
|
|
8
12
|
} | undefined) => HubController<InferContract<H>, H_1>;
|
|
13
|
+
/** Changes session options, for example a new `baseUrl` or `enabled`. Values set before the first host connects apply when it connects. It restarts a stopped session. An `undefined` `accessTokenFactory` keeps the old one. */
|
|
14
|
+
update: (partial: Partial<Pick<SignalRSessionOptions<`/${string}`>, "baseUrl" | "enabled" | "connectionKey" | "accessTokenFactory">>) => void;
|
|
15
|
+
/** Stops every hub and closes the connections. A connection with a pending teardown call stays open until the send ends. The session stays stopped until the next `update()`. */
|
|
9
16
|
stop: () => void;
|
|
10
|
-
context
|
|
17
|
+
/** Gives access to the SignalR context (`getConnection`, `getStatus`, and `waitForConnection`). Use this only for the underlying `HubConnection` or a one-time read. */
|
|
18
|
+
context: import("@dammers/use-signalr-core").SignalRPublicContext<InferContract<H>>;
|
|
11
19
|
};
|
|
12
20
|
};
|
|
13
|
-
declare
|
|
21
|
+
declare function createRuntime<T extends SignalRContract>(hubs: Array<keyof T & HubString>, resolve: (hub: keyof T & HubString) => ResolvedHubConfig, options: SignalRSessionOptions<keyof T & HubString>): {
|
|
22
|
+
/** Creates a `HubController` for one hub on a Lit host. The hub connects while the host is connected. */
|
|
23
|
+
hub: <H extends keyof T & `/${string}`>(host: ReactiveControllerHost, name: H, controllerOptions?: {
|
|
24
|
+
/** Set to `false` to not request a host update on each status change. The default is `true`. */
|
|
25
|
+
reactiveStatus?: boolean;
|
|
26
|
+
}) => HubController<T, H>;
|
|
27
|
+
/** Changes session options, for example a new `baseUrl` or `enabled`. Values set before the first host connects apply when it connects. It restarts a stopped session. An `undefined` `accessTokenFactory` keeps the old one. */
|
|
28
|
+
update: (partial: SignalRSessionUpdate) => void;
|
|
29
|
+
/** Stops every hub and closes the connections. A connection with a pending teardown call stays open until the send ends. The session stays stopped until the next `update()`. */
|
|
30
|
+
stop: () => void;
|
|
31
|
+
/** Gives access to the SignalR context (`getConnection`, `getStatus`, and `waitForConnection`). Use this only for the underlying `HubConnection` or a one-time read. */
|
|
32
|
+
context: import("@dammers/use-signalr-core").SignalRPublicContext<T>;
|
|
33
|
+
};
|
|
34
|
+
export type LitSignalRSession<T extends SignalRContract> = ReturnType<typeof createRuntime<T>>;
|
|
35
|
+
export declare class HubController<T extends SignalRContract, H extends keyof T & HubString> implements ReactiveController {
|
|
14
36
|
private readonly host;
|
|
37
|
+
/** Name of the hub this controller uses. */
|
|
15
38
|
readonly hub: H;
|
|
16
39
|
private readonly context;
|
|
17
40
|
private readonly start;
|
|
@@ -19,20 +42,30 @@ declare class HubController<T extends SignalRContract, H extends keyof T & HubSt
|
|
|
19
42
|
private connected;
|
|
20
43
|
private unsubscribeStatus?;
|
|
21
44
|
private readonly reconnectEntries;
|
|
22
|
-
private readonly
|
|
23
|
-
private readonly
|
|
24
|
-
constructor(host: ReactiveControllerHost,
|
|
45
|
+
private readonly abortScope;
|
|
46
|
+
private readonly eventEntries;
|
|
47
|
+
constructor(host: ReactiveControllerHost,
|
|
48
|
+
/** Name of the hub this controller uses. */
|
|
49
|
+
hub: H, context: SignalRContextValue<T>, start: () => void, reactiveStatus: boolean);
|
|
50
|
+
/** Live connection status of the hub. Requests a host update on each change unless `reactiveStatus` is `false`. */
|
|
25
51
|
get status(): HubConnectionStatus;
|
|
52
|
+
/** Lit calls this when the host connects. It acquires the hub, and does nothing during a server render. */
|
|
26
53
|
hostConnected(): void;
|
|
54
|
+
/** Lit calls this when the host disconnects. Pending calls abort a moment later, unless the host connects again first. */
|
|
27
55
|
hostDisconnected(): void;
|
|
56
|
+
/** Disconnects the controller and removes it from the host. */
|
|
57
|
+
dispose(): void;
|
|
58
|
+
/** Subscribes to a typed server event while the host is connected. Handler arguments are inferred from your contract. Returns an unsubscribe function. */
|
|
28
59
|
on<E extends EventName<T, H>>(event: E, handler: (...args: EventArgs<T, H, E>) => void): () => void;
|
|
60
|
+
/** Runs a callback after each reconnect, not the first connect, to refetch state that went stale while offline. It also runs after a rebuild, but only for a hub that was connected before. */
|
|
29
61
|
onReconnected(callback: () => void): () => void;
|
|
62
|
+
/** Typed invoker that waits for the connection and resolves with the method's return value. Fails fast by default. Opt in to retry for idempotent methods only. A pending call rejects with an `AbortError` when the host disconnects, unless `keepAliveOnUnmount` is true. With `keepAliveOnUnmount`, the call also holds a lazy hub open until it settles. */
|
|
30
63
|
invoke<M extends MethodName<T, 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>>;
|
|
64
|
+
/** Typed fire-and-forget sender. It does not wait for the connection. It resolves `true` when it sends the call, and `false` when the hub is not connected and it drops the call. It also resolves `false` when the send fails. It never throws, so a cleanup can call it. For a call that must land in a cleanup, use `teardown`. */
|
|
31
65
|
send<M extends MethodName<T, H>>(method: M): (...args: import("@dammers/use-signalr-core").MethodArgs<T, H, M>) => Promise<boolean>;
|
|
66
|
+
/** Typed teardown sender for a method invoked in a cleanup. Survives the host disconnect, queues while the hub is still connecting instead of dropping, and holds a lazy hub open until the send ends. Resolves `true` if the call is sent. Resolves `false` if the hub does not connect in time, the session stops while the call waits for the hub, the session is disabled, the hub failed, or the send fails or does not end in time. Never throws. If the session stops while the call is pending on a connected hub, the call is sent before the connection closes. */
|
|
32
67
|
teardown<M extends MethodName<T, H>>(method: M, options?: TeardownOptions): (...args: import("@dammers/use-signalr-core").MethodArgs<T, H, M>) => Promise<boolean>;
|
|
33
|
-
private
|
|
34
|
-
private
|
|
35
|
-
private detachAll;
|
|
36
|
-
private detach;
|
|
68
|
+
private subscribeEntry;
|
|
69
|
+
private unsubscribeEntry;
|
|
37
70
|
}
|
|
38
71
|
export {};
|
|
@@ -1,45 +1,69 @@
|
|
|
1
|
-
import { createInvoker, createSender, createSignalRSession, createTeardownSender, hubKeys, resolveHubConfig, } from "@dammers/use-signalr-core";
|
|
1
|
+
import { createAbortScope, createInvoker, createSender, createSignalRSession, createTeardownSender, hubKeys, resolveHubConfig, } from "@dammers/use-signalr-core";
|
|
2
|
+
import { isServer } from "lit";
|
|
2
3
|
import { createStatusStore } from "./status-store.js";
|
|
4
|
+
/** Creates a typed SignalR client. Call `createSession` once to get a session for your app. */
|
|
3
5
|
export function createSignalRClient(config) {
|
|
4
6
|
const hubs = hubKeys(config);
|
|
5
|
-
const resolved = new Map(hubs.map((hub) => [hub, resolveHubConfig(config,
|
|
7
|
+
const resolved = new Map(hubs.map((hub) => [hub, resolveHubConfig(config, hub)]));
|
|
6
8
|
return {
|
|
9
|
+
/** Builds a session that starts, retries, and reconnects every configured hub. It starts when the first host connects. Pass `baseUrl` and `accessTokenFactory`, and gate them with `enabled`. */
|
|
7
10
|
createSession(options) {
|
|
8
11
|
return createRuntime(hubs, (hub) => resolved.get(hub), options);
|
|
9
12
|
},
|
|
10
13
|
};
|
|
11
14
|
}
|
|
12
15
|
function createRuntime(hubs, resolve, options) {
|
|
16
|
+
let values = { ...options };
|
|
17
|
+
let stopped = false;
|
|
18
|
+
let hasHost = false;
|
|
13
19
|
const statusStore = createStatusStore();
|
|
14
20
|
const session = createSignalRSession({
|
|
15
21
|
hubs,
|
|
16
22
|
resolve,
|
|
17
23
|
statusStore,
|
|
18
|
-
getAccessToken: () =>
|
|
24
|
+
getAccessToken: () => values.accessTokenFactory(),
|
|
19
25
|
onStatusChange: (hub, status) => options.onStatusChange?.(hub, status),
|
|
20
|
-
onError: (hub, error) => options.onError?.(hub, error),
|
|
26
|
+
onError: (hub, error, info) => options.onError?.(hub, error, info),
|
|
21
27
|
});
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
if (started || options.enabled === false || !options.baseUrl)
|
|
28
|
+
const sync = () => {
|
|
29
|
+
if (stopped)
|
|
25
30
|
return;
|
|
26
|
-
|
|
27
|
-
|
|
31
|
+
session.update({
|
|
32
|
+
baseUrl: values.baseUrl,
|
|
33
|
+
enabled: values.enabled,
|
|
34
|
+
connectionKey: values.connectionKey,
|
|
35
|
+
});
|
|
28
36
|
};
|
|
29
37
|
function hub(host, name, controllerOptions) {
|
|
30
|
-
return new HubController(host, name, session.context,
|
|
38
|
+
return new HubController(host, name, session.context, () => {
|
|
39
|
+
hasHost = true;
|
|
40
|
+
sync();
|
|
41
|
+
}, controllerOptions?.reactiveStatus ?? true);
|
|
31
42
|
}
|
|
32
43
|
return {
|
|
44
|
+
/** Creates a `HubController` for one hub on a Lit host. The hub connects while the host is connected. */
|
|
33
45
|
hub,
|
|
46
|
+
/** Changes session options, for example a new `baseUrl` or `enabled`. Values set before the first host connects apply when it connects. It restarts a stopped session. An `undefined` `accessTokenFactory` keeps the old one. */
|
|
47
|
+
update: (partial) => {
|
|
48
|
+
const { accessTokenFactory, ...rest } = partial;
|
|
49
|
+
values = { ...values, ...rest, ...(accessTokenFactory && { accessTokenFactory }) };
|
|
50
|
+
stopped = false;
|
|
51
|
+
if (hasHost)
|
|
52
|
+
sync();
|
|
53
|
+
},
|
|
54
|
+
/** Stops every hub and closes the connections. A connection with a pending teardown call stays open until the send ends. The session stays stopped until the next `update()`. */
|
|
34
55
|
stop: () => {
|
|
35
|
-
|
|
56
|
+
stopped = true;
|
|
36
57
|
session.stop();
|
|
37
58
|
},
|
|
38
|
-
context
|
|
59
|
+
/** Gives access to the SignalR context (`getConnection`, `getStatus`, and `waitForConnection`). Use this only for the underlying `HubConnection` or a one-time read. */
|
|
60
|
+
context: session.publicContext,
|
|
39
61
|
};
|
|
40
62
|
}
|
|
41
|
-
class HubController {
|
|
42
|
-
constructor(host,
|
|
63
|
+
export class HubController {
|
|
64
|
+
constructor(host,
|
|
65
|
+
/** Name of the hub this controller uses. */
|
|
66
|
+
hub, context, start, reactiveStatus) {
|
|
43
67
|
this.host = host;
|
|
44
68
|
this.hub = hub;
|
|
45
69
|
this.context = context;
|
|
@@ -47,105 +71,112 @@ class HubController {
|
|
|
47
71
|
this.reactiveStatus = reactiveStatus;
|
|
48
72
|
this.connected = false;
|
|
49
73
|
this.reconnectEntries = new Set();
|
|
50
|
-
this.
|
|
51
|
-
this.
|
|
74
|
+
this.abortScope = createAbortScope();
|
|
75
|
+
this.eventEntries = new Set();
|
|
52
76
|
host.addController(this);
|
|
53
77
|
}
|
|
78
|
+
/** Live connection status of the hub. Requests a host update on each change unless `reactiveStatus` is `false`. */
|
|
54
79
|
get status() {
|
|
55
80
|
return this.context.statusStore.get(this.hub);
|
|
56
81
|
}
|
|
82
|
+
/** Lit calls this when the host connects. It acquires the hub, and does nothing during a server render. */
|
|
57
83
|
hostConnected() {
|
|
84
|
+
if (isServer || this.connected)
|
|
85
|
+
return;
|
|
58
86
|
this.connected = true;
|
|
59
87
|
this.start();
|
|
60
88
|
this.context.acquire(this.hub);
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
if (this.reactiveStatus)
|
|
67
|
-
this.host.requestUpdate();
|
|
68
|
-
});
|
|
89
|
+
if (this.reactiveStatus) {
|
|
90
|
+
this.unsubscribeStatus = this.context.statusStore.subscribe(this.hub, () => this.host.requestUpdate());
|
|
91
|
+
this.host.requestUpdate();
|
|
92
|
+
}
|
|
93
|
+
this.eventEntries.forEach((entry) => this.subscribeEntry(entry));
|
|
69
94
|
this.reconnectEntries.forEach((entry) => {
|
|
70
|
-
entry.unsubscribe = this.context.registerReconnect(this.hub, entry.
|
|
95
|
+
entry.unsubscribe = this.context.registerReconnect(this.hub, entry.run);
|
|
71
96
|
});
|
|
72
|
-
if (this.status === "connected")
|
|
73
|
-
this.attachAll();
|
|
74
|
-
if (this.reactiveStatus)
|
|
75
|
-
this.host.requestUpdate();
|
|
76
97
|
}
|
|
98
|
+
/** Lit calls this when the host disconnects. Pending calls abort a moment later, unless the host connects again first. */
|
|
77
99
|
hostDisconnected() {
|
|
100
|
+
if (!this.connected)
|
|
101
|
+
return;
|
|
78
102
|
this.connected = false;
|
|
79
103
|
this.unsubscribeStatus?.();
|
|
80
104
|
this.unsubscribeStatus = undefined;
|
|
105
|
+
this.eventEntries.forEach((entry) => this.unsubscribeEntry(entry));
|
|
81
106
|
this.reconnectEntries.forEach((entry) => {
|
|
82
107
|
entry.unsubscribe?.();
|
|
83
108
|
entry.unsubscribe = undefined;
|
|
84
109
|
});
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
110
|
+
queueMicrotask(() => {
|
|
111
|
+
if (!this.connected)
|
|
112
|
+
this.abortScope.abort();
|
|
113
|
+
});
|
|
88
114
|
this.context.release(this.hub);
|
|
89
115
|
}
|
|
116
|
+
/** Disconnects the controller and removes it from the host. */
|
|
117
|
+
dispose() {
|
|
118
|
+
this.hostDisconnected();
|
|
119
|
+
this.host.removeController(this);
|
|
120
|
+
}
|
|
121
|
+
/** Subscribes to a typed server event while the host is connected. Handler arguments are inferred from your contract. Returns an unsubscribe function. */
|
|
90
122
|
on(event, handler) {
|
|
91
123
|
const entry = {
|
|
92
|
-
|
|
124
|
+
event: String(event),
|
|
125
|
+
handle: (...args) => handler(...args),
|
|
93
126
|
};
|
|
94
|
-
|
|
95
|
-
if (
|
|
96
|
-
this.
|
|
97
|
-
entries.add(entry);
|
|
98
|
-
this.attach(event, entry);
|
|
127
|
+
this.eventEntries.add(entry);
|
|
128
|
+
if (this.connected)
|
|
129
|
+
this.subscribeEntry(entry);
|
|
99
130
|
return () => {
|
|
100
|
-
this.
|
|
101
|
-
|
|
102
|
-
if (entries.size === 0)
|
|
103
|
-
this.listeners.delete(String(event));
|
|
131
|
+
this.unsubscribeEntry(entry);
|
|
132
|
+
this.eventEntries.delete(entry);
|
|
104
133
|
};
|
|
105
134
|
}
|
|
135
|
+
/** Runs a callback after each reconnect, not the first connect, to refetch state that went stale while offline. It also runs after a rebuild, but only for a hub that was connected before. */
|
|
106
136
|
onReconnected(callback) {
|
|
107
|
-
const entry = { callback };
|
|
137
|
+
const entry = { run: () => callback() };
|
|
108
138
|
this.reconnectEntries.add(entry);
|
|
109
139
|
if (this.connected) {
|
|
110
|
-
entry.unsubscribe = this.context.registerReconnect(this.hub,
|
|
140
|
+
entry.unsubscribe = this.context.registerReconnect(this.hub, entry.run);
|
|
111
141
|
}
|
|
112
142
|
return () => {
|
|
113
143
|
entry.unsubscribe?.();
|
|
114
144
|
this.reconnectEntries.delete(entry);
|
|
115
145
|
};
|
|
116
146
|
}
|
|
147
|
+
/** Typed invoker that waits for the connection and resolves with the method's return value. Fails fast by default. Opt in to retry for idempotent methods only. A pending call rejects with an `AbortError` when the host disconnects, unless `keepAliveOnUnmount` is true. With `keepAliveOnUnmount`, the call also holds a lazy hub open until it settles. */
|
|
117
148
|
invoke(method, options) {
|
|
118
|
-
return createInvoker(
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
149
|
+
return createInvoker({
|
|
150
|
+
target: this.context,
|
|
151
|
+
hub: this.hub,
|
|
152
|
+
method,
|
|
153
|
+
getOptions: () => options,
|
|
154
|
+
getSignal: () => (options?.keepAliveOnUnmount ? undefined : this.abortScope.signal()),
|
|
155
|
+
});
|
|
122
156
|
}
|
|
157
|
+
/** Typed fire-and-forget sender. It does not wait for the connection. It resolves `true` when it sends the call, and `false` when the hub is not connected and it drops the call. It also resolves `false` when the send fails. It never throws, so a cleanup can call it. For a call that must land in a cleanup, use `teardown`. */
|
|
123
158
|
send(method) {
|
|
124
|
-
return createSender(
|
|
159
|
+
return createSender({
|
|
160
|
+
getConnection: this.context.getConnection,
|
|
161
|
+
hub: this.hub,
|
|
162
|
+
method,
|
|
163
|
+
});
|
|
125
164
|
}
|
|
165
|
+
/** Typed teardown sender for a method invoked in a cleanup. Survives the host disconnect, queues while the hub is still connecting instead of dropping, and holds a lazy hub open until the send ends. Resolves `true` if the call is sent. Resolves `false` if the hub does not connect in time, the session stops while the call waits for the hub, the session is disabled, the hub failed, or the send fails or does not end in time. Never throws. If the session stops while the call is pending on a connected hub, the call is sent before the connection closes. */
|
|
126
166
|
teardown(method, options) {
|
|
127
|
-
return createTeardownSender(
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
this.detach(event, entry);
|
|
134
|
-
if (!this.connected || this.status !== "connected")
|
|
135
|
-
return;
|
|
136
|
-
const connection = this.context.getConnection(this.hub);
|
|
137
|
-
if (!connection)
|
|
138
|
-
return;
|
|
139
|
-
entry.listener = (...args) => entry.handler(...args);
|
|
140
|
-
connection.on(event, entry.listener);
|
|
167
|
+
return createTeardownSender({
|
|
168
|
+
target: this.context,
|
|
169
|
+
hub: this.hub,
|
|
170
|
+
method,
|
|
171
|
+
getOptions: () => options,
|
|
172
|
+
});
|
|
141
173
|
}
|
|
142
|
-
|
|
143
|
-
this.
|
|
174
|
+
subscribeEntry(entry) {
|
|
175
|
+
this.unsubscribeEntry(entry);
|
|
176
|
+
entry.unsubscribe = this.context.subscribe(this.hub, entry.event, entry.handle);
|
|
144
177
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
this.context.getConnection(this.hub)?.off(event, entry.listener);
|
|
149
|
-
entry.listener = undefined;
|
|
178
|
+
unsubscribeEntry(entry) {
|
|
179
|
+
entry.unsubscribe?.();
|
|
180
|
+
entry.unsubscribe = undefined;
|
|
150
181
|
}
|
|
151
182
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { createSignalRClient } from "./create-signalr-client.js";
|
|
2
|
-
export {
|
|
3
|
-
export
|
|
4
|
-
export type {
|
|
2
|
+
export type { HubController, LitSignalRSession } from "./create-signalr-client.js";
|
|
3
|
+
export { event, method } from "@dammers/use-signalr-core";
|
|
4
|
+
export type { SignalRSessionOptions, SignalRSessionUpdate, } from "./types.js";
|
|
5
|
+
export type { EventArgs, EventDef, EventName, HubConnectionStatus, SignalRErrorInfo, SignalRPublicContext, HubContract, HubDef, HubString, InferContract, InvokeOptions, MethodArgs, MethodDef, MethodName, MethodReturn, PerHubConfig, HubProtocolConfig, ConfigureBuilder, BuilderContext, HttpOptions, ReconnectConfig, SignalRClientConfig, SignalRContract, TeardownOptions, } 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 {
|
|
2
|
+
export { event, method } from "@dammers/use-signalr-core";
|
package/dist/status-store.js
CHANGED
|
@@ -2,9 +2,9 @@ export function createStatusStore() {
|
|
|
2
2
|
const values = new Map();
|
|
3
3
|
const listeners = new Map();
|
|
4
4
|
return {
|
|
5
|
-
get: (hub) => values.get(hub) ?? "
|
|
5
|
+
get: (hub) => values.get(hub) ?? "idle",
|
|
6
6
|
set: (hub, status) => {
|
|
7
|
-
if (values.get(hub) === status)
|
|
7
|
+
if ((values.get(hub) ?? "idle") === status)
|
|
8
8
|
return;
|
|
9
9
|
values.set(hub, status);
|
|
10
10
|
listeners.get(hub)?.forEach((listener) => listener());
|
package/dist/types.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import type { HubConnectionStatus, HubString, SignalRContract, SignalRContextValueBase } from "@dammers/use-signalr-core";
|
|
1
|
+
import type { HubConnectionStatus, SignalRErrorInfo, HubString, SignalRContract, SignalRContextValueBase, SignalRProviderPropsBase } from "@dammers/use-signalr-core";
|
|
2
2
|
import type { StatusStore } from "./status-store.js";
|
|
3
|
-
export interface SignalRSessionOptions<H extends HubString = HubString> {
|
|
4
|
-
|
|
5
|
-
accessTokenFactory: () => string | Promise<string>;
|
|
6
|
-
enabled?: boolean;
|
|
3
|
+
export interface SignalRSessionOptions<H extends HubString = HubString> extends SignalRProviderPropsBase<H> {
|
|
4
|
+
/** Runs when the status of a hub changes. The session reads it once when it is created, so `update()` does not change it. */
|
|
7
5
|
onStatusChange?: (hub: H, status: HubConnectionStatus) => void;
|
|
8
|
-
|
|
6
|
+
/** Runs on a connection error and on an error that your callback throws. `info.source` is `"connection"` or `"callback"`. The session reads it once when it is created, so `update()` does not change it. */
|
|
7
|
+
onError?: (hub: H, error: unknown, info: SignalRErrorInfo) => void;
|
|
9
8
|
}
|
|
9
|
+
export type SignalRSessionUpdate = Partial<Pick<SignalRSessionOptions, "baseUrl" | "enabled" | "connectionKey" | "accessTokenFactory">>;
|
|
10
10
|
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-lit",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Fully-typed SignalR Reactive Controllers for Lit.",
|
|
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/lit"
|
|
11
11
|
},
|
|
12
|
-
"homepage": "https://
|
|
12
|
+
"homepage": "https://use-signalr.vercel.app/docs/lit",
|
|
13
13
|
"bugs": {
|
|
14
14
|
"url": "https://github.com/DammersCode/use-signalr/issues"
|
|
15
15
|
},
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
"web-components"
|
|
21
21
|
],
|
|
22
22
|
"engines": {
|
|
23
|
-
"node": ">=
|
|
23
|
+
"node": ">=20.19"
|
|
24
24
|
},
|
|
25
25
|
"type": "module",
|
|
26
26
|
"sideEffects": false,
|
|
@@ -29,8 +29,10 @@
|
|
|
29
29
|
"exports": {
|
|
30
30
|
".": {
|
|
31
31
|
"types": "./dist/index.d.ts",
|
|
32
|
-
"import": "./dist/index.js"
|
|
33
|
-
|
|
32
|
+
"import": "./dist/index.js",
|
|
33
|
+
"default": "./dist/index.js"
|
|
34
|
+
},
|
|
35
|
+
"./package.json": "./package.json"
|
|
34
36
|
},
|
|
35
37
|
"files": [
|
|
36
38
|
"dist"
|
|
@@ -45,14 +47,14 @@
|
|
|
45
47
|
"test": "vitest run"
|
|
46
48
|
},
|
|
47
49
|
"dependencies": {
|
|
48
|
-
"@dammers/use-signalr-core": "
|
|
50
|
+
"@dammers/use-signalr-core": "1.1.0"
|
|
49
51
|
},
|
|
50
52
|
"peerDependencies": {
|
|
51
|
-
"@microsoft/signalr": "
|
|
52
|
-
"lit": "
|
|
53
|
+
"@microsoft/signalr": "^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0",
|
|
54
|
+
"lit": "^3.0.0"
|
|
53
55
|
},
|
|
54
56
|
"devDependencies": {
|
|
55
|
-
"@microsoft/signalr": "
|
|
56
|
-
"lit": "^3.
|
|
57
|
+
"@microsoft/signalr": "^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0",
|
|
58
|
+
"lit": "^3.0.0"
|
|
57
59
|
}
|
|
58
60
|
}
|