react-websocket 3.2.0 → 3.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.
- package/LICENSE +1 -0
- package/README.md +19 -7
- package/dist/chaos.cjs +284 -0
- package/dist/chaos.cjs.map +1 -0
- package/dist/chaos.d.cts +131 -0
- package/dist/chaos.d.ts +131 -0
- package/dist/chaos.js +283 -0
- package/dist/chaos.js.map +1 -0
- package/dist/core.cjs +1157 -759
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +645 -374
- package/dist/core.d.ts +645 -374
- package/dist/core.js +1149 -727
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +217 -151
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +705 -410
- package/dist/index.d.ts +453 -524
- package/dist/index.js +204 -121
- package/dist/index.js.map +1 -1
- package/dist/timeline.cjs +162 -0
- package/dist/timeline.cjs.map +1 -0
- package/dist/timeline.d.cts +379 -0
- package/dist/timeline.d.ts +140 -0
- package/dist/timeline.js +161 -0
- package/dist/timeline.js.map +1 -0
- package/package.json +94 -38
package/dist/core.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
//#region src/types.d.ts
|
|
1
2
|
/**
|
|
2
3
|
* Where to connect: a URL, or a function that returns one (sync or async).
|
|
3
4
|
*
|
|
@@ -24,105 +25,139 @@ type UrlSource = string | (() => string | Promise<string>);
|
|
|
24
25
|
type Status = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed';
|
|
25
26
|
/** The client's state as seen by React. A new object is created on every change. */
|
|
26
27
|
interface Snapshot<In> {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
28
|
+
/** Connection state. */
|
|
29
|
+
readonly status: Status;
|
|
30
|
+
/** Most recent message (after `parse`/`json` and `schema`), kept across reconnects. */
|
|
31
|
+
readonly lastMessage: In | undefined;
|
|
32
|
+
/** Consecutive failed attempts since the last successful open. `0` while open. */
|
|
33
|
+
readonly attempt: number;
|
|
33
34
|
}
|
|
34
35
|
/** Details of a closed connection, from the browser's `CloseEvent`. */
|
|
35
36
|
interface CloseInfo {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
37
|
+
/** Close code: `1000` is a normal close, `1006` an abnormal one (e.g. network loss), `4000`–`4999` are yours. */
|
|
38
|
+
readonly code: number;
|
|
39
|
+
/** Close reason sent by the side that closed the connection. Often empty. */
|
|
40
|
+
readonly reason: string;
|
|
41
|
+
/** Whether the closing handshake completed. */
|
|
42
|
+
readonly wasClean: boolean;
|
|
42
43
|
}
|
|
43
44
|
/** Anything `WebSocket.prototype.send` accepts: a string, `Blob`, `ArrayBuffer` or typed array. */
|
|
44
45
|
type SendData = Parameters<WebSocket['send']>[0];
|
|
45
46
|
/** Reconnect timing. Delay before attempt `n` = `min(maxDelay, minDelay * factor ** (n - 1))`, minus jitter. */
|
|
46
47
|
interface ReconnectOptions {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
48
|
+
/**
|
|
49
|
+
* Maximum consecutive reconnect attempts. When the last one fails too, the client
|
|
50
|
+
* gives up: the status becomes `closed` and `ready` rejects. `0` never retries.
|
|
51
|
+
* @default Infinity
|
|
52
|
+
*/
|
|
53
|
+
maxAttempts?: number;
|
|
54
|
+
/**
|
|
55
|
+
* Delay before the first retry, in ms.
|
|
56
|
+
* @default 1000
|
|
57
|
+
*/
|
|
58
|
+
minDelay?: number;
|
|
59
|
+
/**
|
|
60
|
+
* Upper bound for the delay, in ms.
|
|
61
|
+
* @default 30000
|
|
62
|
+
*/
|
|
63
|
+
maxDelay?: number;
|
|
64
|
+
/**
|
|
65
|
+
* Backoff multiplier applied per attempt.
|
|
66
|
+
* @default 2
|
|
67
|
+
*/
|
|
68
|
+
factor?: number;
|
|
69
|
+
/**
|
|
70
|
+
* Randomly shave up to this fraction (0–1) off each delay, so that many clients
|
|
71
|
+
* dropped at once don't all reconnect at the same moment.
|
|
72
|
+
* @default 0.5
|
|
73
|
+
*/
|
|
74
|
+
jitter?: number;
|
|
75
|
+
/**
|
|
76
|
+
* Called on every unexpected close. Return `false` to stop reconnecting.
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* ```ts
|
|
80
|
+
* // Don't retry when the server rejects our credentials.
|
|
81
|
+
* shouldReconnect: close => close.code !== 4001
|
|
82
|
+
* ```
|
|
83
|
+
* @default () => true
|
|
84
|
+
*/
|
|
85
|
+
shouldReconnect?: (close: CloseInfo) => boolean;
|
|
85
86
|
}
|
|
86
87
|
/** Application-level keep-alive. Useful behind proxies that drop idle connections. */
|
|
87
88
|
interface HeartbeatOptions {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
89
|
+
/** Send `message` every `interval` ms while open. */
|
|
90
|
+
interval: number;
|
|
91
|
+
/**
|
|
92
|
+
* Sent as-is (it is not passed through `serialize` or `json`).
|
|
93
|
+
* @default 'ping'
|
|
94
|
+
*/
|
|
95
|
+
message?: string;
|
|
96
|
+
/** Incoming data equal to this string is swallowed instead of being delivered as a message. */
|
|
97
|
+
pong?: string;
|
|
98
|
+
/**
|
|
99
|
+
* If nothing at all arrives within this many ms after a ping, the connection is
|
|
100
|
+
* treated as dead: it closes with code `4000` and reconnects.
|
|
101
|
+
*/
|
|
102
|
+
timeout?: number;
|
|
102
103
|
}
|
|
103
104
|
/** Per-message options for `send()`. */
|
|
104
105
|
interface SendOptions {
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
106
|
+
/**
|
|
107
|
+
* Drop the message instead of queueing it when the socket isn't open. For data that
|
|
108
|
+
* is stale by the time a reconnect finishes, such as player input or cursor positions.
|
|
109
|
+
* @default false
|
|
110
|
+
*/
|
|
111
|
+
volatile?: boolean;
|
|
112
|
+
/**
|
|
113
|
+
* Keep only the newest queued message with this key. Sending again with the same key
|
|
114
|
+
* while disconnected replaces the earlier one, which moves to the back of the queue
|
|
115
|
+
* (or of the `priority` messages, for a priority one).
|
|
116
|
+
* For state where only the latest value matters, such as "my position is now (x, y)".
|
|
117
|
+
*/
|
|
118
|
+
key?: string;
|
|
119
|
+
/**
|
|
120
|
+
* Queue this message ahead of every message queued without `priority`, after earlier
|
|
121
|
+
* priority messages. For control messages that must not wait behind a backlog, such as
|
|
122
|
+
* cancel, interrupt or a token refresh. Messages sent from `open` listeners still go first.
|
|
123
|
+
*
|
|
124
|
+
* It only matters while the socket isn't open: once a message is handed to the browser,
|
|
125
|
+
* nothing can overtake it. To keep that buffer short, send bulky streams with `maxBuffered`.
|
|
126
|
+
* @default false
|
|
127
|
+
*/
|
|
128
|
+
priority?: boolean;
|
|
129
|
+
/**
|
|
130
|
+
* Drop the message instead of sending it while more than this many bytes are already
|
|
131
|
+
* waiting in the browser's send buffer (`socket.bufferedAmount`). For high-rate streams on
|
|
132
|
+
* a slow link, such as audio frames or per-tick input, where a late message is worse than
|
|
133
|
+
* none. `send()` returns `false`, and `onDrop` isn't called.
|
|
134
|
+
*
|
|
135
|
+
* Only checked while the socket is open: a message queued while disconnected is sent on
|
|
136
|
+
* open regardless. `bufferedAmount` includes what you sent earlier in the same task, so set
|
|
137
|
+
* it well above one burst of messages.
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* ```ts
|
|
141
|
+
* voice.send(frame, { volatile: true, maxBuffered: 64 * 1024 });
|
|
142
|
+
* ```
|
|
143
|
+
*/
|
|
144
|
+
maxBuffered?: number;
|
|
145
|
+
/**
|
|
146
|
+
* Called if the message is dropped from the queue without being sent: replaced by a
|
|
147
|
+
* newer message with the same `key`, or evicted by `queue.limit`. Not called when the
|
|
148
|
+
* queue is cleared because the client closed or gave up, or when `send()` drops the
|
|
149
|
+
* message right away (`volatile` while not open, or `maxBuffered`) and returns `false`.
|
|
150
|
+
*/
|
|
151
|
+
onDrop?: () => void;
|
|
117
152
|
}
|
|
118
153
|
/** Bounds for the send queue. */
|
|
119
154
|
interface QueueOptions {
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
155
|
+
/**
|
|
156
|
+
* Maximum number of messages held while not connected. When full, the oldest
|
|
157
|
+
* message is dropped, skipping `priority` messages unless nothing else is queued.
|
|
158
|
+
* @default Infinity
|
|
159
|
+
*/
|
|
160
|
+
limit?: number;
|
|
126
161
|
}
|
|
127
162
|
/**
|
|
128
163
|
* The minimal [Standard Schema v1](https://standardschema.dev) interface, implemented
|
|
@@ -130,24 +165,24 @@ interface QueueOptions {
|
|
|
130
165
|
* import this; pass your schema object directly.
|
|
131
166
|
*/
|
|
132
167
|
interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
168
|
+
readonly '~standard': {
|
|
169
|
+
readonly version: 1;
|
|
170
|
+
readonly vendor: string;
|
|
171
|
+
readonly validate: (value: unknown) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;
|
|
172
|
+
readonly types?: {
|
|
173
|
+
readonly input: Input;
|
|
174
|
+
readonly output: Output;
|
|
175
|
+
} | undefined;
|
|
176
|
+
};
|
|
142
177
|
}
|
|
143
178
|
/** The result of a Standard Schema `validate` call. */
|
|
144
179
|
type StandardSchemaResult<Output> = {
|
|
145
|
-
|
|
146
|
-
|
|
180
|
+
readonly value: Output;
|
|
181
|
+
readonly issues?: undefined;
|
|
147
182
|
} | {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
183
|
+
readonly issues: ReadonlyArray<{
|
|
184
|
+
readonly message: string;
|
|
185
|
+
}>;
|
|
151
186
|
};
|
|
152
187
|
/**
|
|
153
188
|
* Connection options, shared by `createWebSocket(url, options)` and `useWebSocket(url, options)`.
|
|
@@ -156,66 +191,66 @@ type StandardSchemaResult<Output> = {
|
|
|
156
191
|
* @typeParam Out - Type accepted by `send()`.
|
|
157
192
|
*/
|
|
158
193
|
interface WebSocketOptions<In = unknown, Out = unknown> {
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
194
|
+
/** Sub-protocol(s) passed to the `WebSocket` constructor. */
|
|
195
|
+
protocols?: string | string[];
|
|
196
|
+
/**
|
|
197
|
+
* How binary messages are exposed.
|
|
198
|
+
* @default 'blob'
|
|
199
|
+
*/
|
|
200
|
+
binaryType?: BinaryType;
|
|
201
|
+
/**
|
|
202
|
+
* `JSON.parse` incoming and `JSON.stringify` outgoing messages. Messages that fail
|
|
203
|
+
* to parse are reported to `onError` as a {@link MessageError} and not delivered.
|
|
204
|
+
* @default false
|
|
205
|
+
*/
|
|
206
|
+
json?: boolean;
|
|
207
|
+
/**
|
|
208
|
+
* Custom decoder for incoming `event.data`. Takes precedence over `json`.
|
|
209
|
+
* Throwing reports a {@link MessageError} and drops the message.
|
|
210
|
+
*/
|
|
211
|
+
parse?: (data: unknown) => unknown;
|
|
212
|
+
/** Custom encoder for outgoing messages. Takes precedence over `json`. */
|
|
213
|
+
serialize?: (message: Out) => SendData;
|
|
214
|
+
/**
|
|
215
|
+
* Validate incoming messages (after parsing) with any Standard Schema library.
|
|
216
|
+
* Invalid messages are reported to `onError` as a {@link MessageError} and not delivered.
|
|
217
|
+
* The message type `In` is inferred from it.
|
|
218
|
+
*
|
|
219
|
+
* @example
|
|
220
|
+
* ```ts
|
|
221
|
+
* createWebSocket(url, { json: true, schema: z.object({ price: z.number() }) });
|
|
222
|
+
* ```
|
|
223
|
+
*/
|
|
224
|
+
schema?: StandardSchemaV1<unknown, In>;
|
|
225
|
+
/**
|
|
226
|
+
* Reconnect with exponential backoff after an unexpected close. `false` disables it.
|
|
227
|
+
* @default true
|
|
228
|
+
*/
|
|
229
|
+
reconnect?: boolean | ReconnectOptions;
|
|
230
|
+
/** Send a ping on an interval and, optionally, reconnect when the server goes quiet. */
|
|
231
|
+
heartbeat?: HeartbeatOptions;
|
|
232
|
+
/**
|
|
233
|
+
* Buffer `send()` calls made while not connected and send them, in order, on open
|
|
234
|
+
* (right after `open` listeners run).
|
|
235
|
+
* `false` drops them instead. `{ limit }` caps the buffer, dropping the oldest.
|
|
236
|
+
* The queue is cleared by `close()` or when the client gives up.
|
|
237
|
+
* @default true
|
|
238
|
+
*/
|
|
239
|
+
queue?: boolean | QueueOptions;
|
|
240
|
+
/**
|
|
241
|
+
* Receives debug messages about connection attempts, retries and dropped messages.
|
|
242
|
+
* @example
|
|
243
|
+
* ```ts
|
|
244
|
+
* logger: console.debug
|
|
245
|
+
* ```
|
|
246
|
+
*/
|
|
247
|
+
logger?: (message: string, ...details: unknown[]) => void;
|
|
248
|
+
/**
|
|
249
|
+
* `WebSocket` implementation to use, e.g. a mock in tests or the `ws` package in Node.
|
|
250
|
+
* When omitted, the global `WebSocket` is used in browsers. During a server render
|
|
251
|
+
* (no `window`), nothing connects unless an implementation is passed.
|
|
252
|
+
*/
|
|
253
|
+
WebSocket?: typeof WebSocket;
|
|
219
254
|
}
|
|
220
255
|
/**
|
|
221
256
|
* Reported via the `error` event (and `onError`) when an incoming message can't be
|
|
@@ -228,36 +263,36 @@ interface WebSocketOptions<In = unknown, Out = unknown> {
|
|
|
228
263
|
* }
|
|
229
264
|
* ```
|
|
230
265
|
*/
|
|
231
|
-
declare class MessageError extends Error {
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
266
|
+
export declare class MessageError extends Error {
|
|
267
|
+
/** The raw `event.data` that failed. */
|
|
268
|
+
readonly data: unknown;
|
|
269
|
+
/** Schema validation issues, when the message failed `schema`. */
|
|
270
|
+
readonly issues: ReadonlyArray<{
|
|
271
|
+
readonly message: string;
|
|
272
|
+
}> | undefined;
|
|
273
|
+
constructor(message: string, data: unknown, options?: {
|
|
274
|
+
cause?: unknown;
|
|
275
|
+
issues?: ReadonlyArray<{
|
|
276
|
+
readonly message: string;
|
|
277
|
+
}>;
|
|
278
|
+
});
|
|
244
279
|
}
|
|
245
280
|
/** Events emitted by a client. Subscribe with `client.on(type, listener)` or `useWebSocketEvent`. */
|
|
246
281
|
interface EventMap<In> {
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
282
|
+
/**
|
|
283
|
+
* The socket opened (initially or after a reconnect). Listeners run before queued
|
|
284
|
+
* messages are sent, so a handshake sent from here goes out first.
|
|
285
|
+
*/
|
|
286
|
+
open: (event: Event) => void;
|
|
287
|
+
/** A message arrived and passed `parse` and `schema`. */
|
|
288
|
+
message: (message: In, event: MessageEvent) => void;
|
|
289
|
+
/** A socket closed, whether it will be retried or not. */
|
|
290
|
+
close: (close: CloseInfo) => void;
|
|
291
|
+
/**
|
|
292
|
+
* A socket error `Event`, a {@link MessageError} for an undecodable or invalid message,
|
|
293
|
+
* or the `Error` thrown by the `WebSocket` constructor or a `url` function.
|
|
294
|
+
*/
|
|
295
|
+
error: (error: Event | MessageError | Error) => void;
|
|
261
296
|
}
|
|
262
297
|
/**
|
|
263
298
|
* A WebSocket connection that reconnects, queues, decodes and can be shared.
|
|
@@ -271,71 +306,74 @@ interface EventMap<In> {
|
|
|
271
306
|
* @typeParam Out - Type accepted by `send()`.
|
|
272
307
|
*/
|
|
273
308
|
interface WebSocketClient<In = unknown, Out = unknown> {
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
309
|
+
/** The URL (or URL function) the client was created with. */
|
|
310
|
+
readonly url: UrlSource;
|
|
311
|
+
/**
|
|
312
|
+
* A promise that resolves once the socket has opened. Reading it starts an idle client.
|
|
313
|
+
*
|
|
314
|
+
* It stays resolved through automatic reconnects, so `use(client.ready)` shows a
|
|
315
|
+
* Suspense fallback only for the first connection, never on a network blip; use
|
|
316
|
+
* `status` to show reconnects. It rejects when the client gives up reconnecting, when
|
|
317
|
+
* `close()` is called, and during a server render. After that, `connect()` or
|
|
318
|
+
* `reconnect()` make it a new pending promise.
|
|
319
|
+
*
|
|
320
|
+
* It is safe to pass to React 19's `use()`: the same promise is returned until its state
|
|
321
|
+
* changes, and it carries `status`/`value`/`reason` so `use()` doesn't suspend when it is
|
|
322
|
+
* already settled.
|
|
323
|
+
*/
|
|
324
|
+
readonly ready: Promise<void>;
|
|
325
|
+
/** The current underlying `WebSocket`, if any. An escape hatch; prefer the client's methods. */
|
|
326
|
+
readonly socket: WebSocket | null;
|
|
327
|
+
/** Subscribe to snapshot changes. Compatible with `useSyncExternalStore`. Returns an unsubscribe function. */
|
|
328
|
+
subscribe(listener: () => void): () => void;
|
|
329
|
+
/** The current {@link Snapshot}. Returns the same object until something changes. */
|
|
330
|
+
getSnapshot(): Snapshot<In>;
|
|
331
|
+
/**
|
|
332
|
+
* Listen to an event. Returns an unsubscribe function. Listener errors are re-thrown
|
|
333
|
+
* asynchronously, so one failing listener doesn't break the others.
|
|
334
|
+
*/
|
|
335
|
+
on<K extends keyof EventMap<In>>(type: K, listener: EventMap<In>[K]): () => void;
|
|
336
|
+
/**
|
|
337
|
+
* Send a message (encoded with `serialize`/`json` if configured). If the socket isn't
|
|
338
|
+
* open, the message is queued and sent on open (see the `queue` option), unless
|
|
339
|
+
* `options.volatile` is set.
|
|
340
|
+
* @returns `true` if it was sent immediately, `false` if it was queued or dropped
|
|
341
|
+
* (`volatile` while not open, or `maxBuffered` while open).
|
|
342
|
+
*
|
|
343
|
+
* @example
|
|
344
|
+
* ```ts
|
|
345
|
+
* game.send({ type: 'input', dx, dy }, { volatile: true }); // never replayed after a reconnect
|
|
346
|
+
* game.send({ type: 'position', x, y }, { key: 'position' }); // only the newest is queued
|
|
347
|
+
* game.send({ type: 'leave' }, { priority: true }); // ahead of everything already queued
|
|
348
|
+
* ```
|
|
349
|
+
*/
|
|
350
|
+
send(message: Out, options?: SendOptions): boolean;
|
|
351
|
+
/**
|
|
352
|
+
* Start connecting, and keep the connection open even when no hook is using the
|
|
353
|
+
* client, until `close()` is called. Does nothing if already connecting or open.
|
|
354
|
+
*/
|
|
355
|
+
connect(): void;
|
|
356
|
+
/**
|
|
357
|
+
* Close the connection and stop reconnecting. The status becomes `closed` and the
|
|
358
|
+
* send queue is cleared. Mounted hooks stay mounted; call `connect()` or `reconnect()`
|
|
359
|
+
* to start again.
|
|
360
|
+
* @param code - Close code. @default 1000
|
|
361
|
+
*/
|
|
362
|
+
close(code?: number, reason?: string): void;
|
|
363
|
+
/**
|
|
364
|
+
* Drop the current socket (if any) and connect again immediately, resetting the
|
|
365
|
+
* backoff. Also restarts a `closed` client.
|
|
366
|
+
*/
|
|
367
|
+
reconnect(): void;
|
|
368
|
+
/**
|
|
369
|
+
* Hold the connection open until the returned function is called. This is what the
|
|
370
|
+
* hooks use; call it yourself to integrate with non-React code.
|
|
371
|
+
* @returns A release function (safe to call more than once).
|
|
372
|
+
*/
|
|
373
|
+
acquire(): () => void;
|
|
337
374
|
}
|
|
338
|
-
|
|
375
|
+
//#endregion
|
|
376
|
+
//#region src/client.d.ts
|
|
339
377
|
/**
|
|
340
378
|
* Create a WebSocket client, usually at module level, to share across components.
|
|
341
379
|
*
|
|
@@ -355,57 +393,58 @@ interface WebSocketClient<In = unknown, Out = unknown> {
|
|
|
355
393
|
* export const chat = createWebSocket<ChatIn, ChatOut>('wss://api.example.com/chat', { json: true });
|
|
356
394
|
* ```
|
|
357
395
|
*/
|
|
358
|
-
declare function createWebSocket<In = unknown, Out = unknown>(url: UrlSource, options?: WebSocketOptions<In, Out>): WebSocketClient<In, Out>;
|
|
359
|
-
|
|
396
|
+
export declare function createWebSocket<In = unknown, Out = unknown>(url: UrlSource, options?: WebSocketOptions<In, Out>): WebSocketClient<In, Out>;
|
|
397
|
+
//#endregion
|
|
398
|
+
//#region src/latency.d.ts
|
|
360
399
|
/** Options for {@link createWebSocketLatency}: how pings and pongs look on the wire. */
|
|
361
400
|
interface WebSocketLatencyOptions<In, Out> {
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
401
|
+
/** The ping message, tagged with `id`. Sent with `volatile`, so pings are never queued. */
|
|
402
|
+
ping: (id: number) => Out;
|
|
403
|
+
/**
|
|
404
|
+
* Recognize a pong: return the `id` of the ping it answers, and the server's clock
|
|
405
|
+
* (`Date.now()` on the server, in ms) when it replied. Return `undefined` (or `null`)
|
|
406
|
+
* for any other message. Without `time`, only the round-trip time is measured.
|
|
407
|
+
*/
|
|
408
|
+
pong: (message: In) => {
|
|
409
|
+
id: number | string;
|
|
410
|
+
time?: number;
|
|
411
|
+
} | null | undefined;
|
|
412
|
+
/**
|
|
413
|
+
* How often to ping while open, in ms. The first ping goes out as soon as the socket opens.
|
|
414
|
+
* @default 2000
|
|
415
|
+
*/
|
|
416
|
+
interval?: number;
|
|
417
|
+
/**
|
|
418
|
+
* How many recent measurements to keep. `rtt` is their median, and `offset` comes from
|
|
419
|
+
* the one with the lowest round trip, the most accurate estimate.
|
|
420
|
+
* @default 5
|
|
421
|
+
*/
|
|
422
|
+
samples?: number;
|
|
384
423
|
}
|
|
385
424
|
/** Latest latency measurements. A new object is created on every change. */
|
|
386
425
|
interface Latency {
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
426
|
+
/** Round-trip time in ms: the median of recent pings. `undefined` until the first pong. */
|
|
427
|
+
readonly rtt: number | undefined;
|
|
428
|
+
/**
|
|
429
|
+
* Estimated server clock minus local clock, in ms. Add it to `Date.now()` for server time.
|
|
430
|
+
* `undefined` until a pong carries `time`.
|
|
431
|
+
*/
|
|
432
|
+
readonly offset: number | undefined;
|
|
394
433
|
}
|
|
395
434
|
/** Round-trip time and server clock offset for one client. Create with {@link createWebSocketLatency}. */
|
|
396
435
|
interface WebSocketLatency {
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
436
|
+
/** The client being measured. Hooks reading the latency keep it connected. */
|
|
437
|
+
readonly client: WebSocketClient<any, any>;
|
|
438
|
+
/** The current {@link Latency}. Returns the same object until it changes. */
|
|
439
|
+
getSnapshot(): Latency;
|
|
440
|
+
/** Called whenever a measurement changes. Compatible with `useSyncExternalStore`. */
|
|
441
|
+
subscribe(listener: () => void): () => void;
|
|
442
|
+
/** The estimated server time: `Date.now() + offset`, or `Date.now()` before any estimate. */
|
|
443
|
+
serverNow(): number;
|
|
444
|
+
/** Ping now instead of waiting for the next interval. Does nothing unless the socket is open. */
|
|
445
|
+
ping(): void;
|
|
446
|
+
/** Stop pinging and listening. Only needed for instances created dynamically. */
|
|
447
|
+
dispose(): void;
|
|
409
448
|
}
|
|
410
449
|
/**
|
|
411
450
|
* Measure round-trip time and estimate the server's clock, for ping displays, countdowns
|
|
@@ -431,55 +470,57 @@ interface WebSocketLatency {
|
|
|
431
470
|
* const left = (endsAt - latency.serverNow()) / 1000;
|
|
432
471
|
* ```
|
|
433
472
|
*/
|
|
434
|
-
declare function createWebSocketLatency<In, const Out>(client: WebSocketClient<In, Out>, options: WebSocketLatencyOptions<NoInfer<In>, NoInfer<Out>>): WebSocketLatency;
|
|
435
|
-
|
|
473
|
+
export declare function createWebSocketLatency<In, const Out>(client: WebSocketClient<In, Out>, options: WebSocketLatencyOptions<NoInfer<In>, NoInfer<Out>>): WebSocketLatency;
|
|
474
|
+
//#endregion
|
|
475
|
+
//#region src/requests.d.ts
|
|
436
476
|
/** Options for {@link createWebSocketRequests}: how requests and replies look on the wire. */
|
|
437
477
|
interface WebSocketRequestsOptions<Req, In, Out> {
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
478
|
+
/**
|
|
479
|
+
* Build the outgoing message for `request(message)`, tagged with `id`. Annotate `message`
|
|
480
|
+
* to type what `request()` accepts.
|
|
481
|
+
*/
|
|
482
|
+
send: (message: Req, id: number) => Out;
|
|
483
|
+
/**
|
|
484
|
+
* The id an incoming message replies to, or `undefined` (or `null`) if it isn't a reply.
|
|
485
|
+
* A string id matches the number it was sent as, so either echo works.
|
|
486
|
+
*/
|
|
487
|
+
reply: (message: In) => number | string | null | undefined;
|
|
488
|
+
/**
|
|
489
|
+
* Called on a reply. Return something other than `undefined` to reject the request with
|
|
490
|
+
* it instead of resolving, e.g. for a server-side error reply.
|
|
491
|
+
*/
|
|
492
|
+
error?: (message: In) => unknown;
|
|
493
|
+
/**
|
|
494
|
+
* Default time to wait for a reply, in ms. `Infinity` waits forever.
|
|
495
|
+
* @default 10000
|
|
496
|
+
*/
|
|
497
|
+
timeout?: number;
|
|
458
498
|
}
|
|
459
499
|
/** Per-call options for {@link WebSocketRequests.request}. */
|
|
460
500
|
interface RequestOptions extends SendOptions {
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
501
|
+
/** Time to wait for a reply, in ms. Overrides the manager's `timeout`. */
|
|
502
|
+
timeout?: number;
|
|
503
|
+
/** Abort the request. It rejects with `signal.reason`. A late reply is ignored. */
|
|
504
|
+
signal?: AbortSignal;
|
|
465
505
|
}
|
|
466
506
|
/** Request/response over one client. Create with {@link createWebSocketRequests}. */
|
|
467
507
|
interface WebSocketRequests<Req, In> {
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
508
|
+
/** The client requests are sent on. */
|
|
509
|
+
readonly client: WebSocketClient<any, any>;
|
|
510
|
+
/**
|
|
511
|
+
* Send a request and resolve with its reply. Holds the connection until it settles.
|
|
512
|
+
*
|
|
513
|
+
* Rejects with a `TimeoutError` `DOMException` after `timeout`, with `signal.reason` when
|
|
514
|
+
* aborted, and with an `Error` when the connection it was sent on closes (the reply can
|
|
515
|
+
* no longer arrive) or the client stops. A request made while disconnected is queued like
|
|
516
|
+
* any other message and waits for the connection; it rejects if it is dropped from the
|
|
517
|
+
* queue (replaced by a newer request with the same `key`, or evicted by `queue.limit`).
|
|
518
|
+
*/
|
|
519
|
+
request(message: Req, options?: RequestOptions): Promise<In>;
|
|
520
|
+
/** Number of requests waiting for a reply. */
|
|
521
|
+
pending(): number;
|
|
522
|
+
/** Reject every pending request and stop listening. Only needed for managers created dynamically. */
|
|
523
|
+
dispose(): void;
|
|
483
524
|
}
|
|
484
525
|
/**
|
|
485
526
|
* Send requests and await their replies, matched by an id the library generates.
|
|
@@ -499,17 +540,245 @@ interface WebSocketRequests<Req, In> {
|
|
|
499
540
|
* const reply = await rpc.request({ type: 'join', room: 'lobby' }, { timeout: 5000 });
|
|
500
541
|
* ```
|
|
501
542
|
*/
|
|
502
|
-
declare function createWebSocketRequests<Req, In, const Out>(client: WebSocketClient<In, Out>, options: WebSocketRequestsOptions<Req, NoInfer<In>, NoInfer<Out>>): WebSocketRequests<Req, In>;
|
|
503
|
-
|
|
543
|
+
export declare function createWebSocketRequests<Req, In, const Out>(client: WebSocketClient<In, Out>, options: WebSocketRequestsOptions<Req, NoInfer<In>, NoInfer<Out>>): WebSocketRequests<Req, In>;
|
|
544
|
+
//#endregion
|
|
545
|
+
//#region src/responder.d.ts
|
|
546
|
+
/** What `request` returns for a request: any object with these fields, such as the message itself. */
|
|
547
|
+
type RequestFields = {
|
|
548
|
+
id: number | string;
|
|
549
|
+
method: string;
|
|
550
|
+
params?: unknown;
|
|
551
|
+
timeout?: number;
|
|
552
|
+
};
|
|
553
|
+
/**
|
|
554
|
+
* The type of `params` in `Q`, keeping `undefined` when they're optional and giving `undefined`
|
|
555
|
+
* when there are none. (Inferring `params?: P` directly would drop the `undefined`.)
|
|
556
|
+
*/
|
|
557
|
+
type ParamsOf<Q> = Q extends unknown ? 'params' extends keyof Q ? Q['params' & keyof Q] : undefined : never;
|
|
558
|
+
/**
|
|
559
|
+
* Options for {@link createWebSocketResponder}: how the server's requests and your replies look
|
|
560
|
+
* on the wire.
|
|
561
|
+
*
|
|
562
|
+
* @typeParam Q - What `request` returns. Handlers receive its `params`.
|
|
563
|
+
* @typeParam R - What handlers return, from the annotation on `respond`'s `result`.
|
|
564
|
+
*/
|
|
565
|
+
interface WebSocketResponderOptions<Q extends RequestFields, R, In, Out> {
|
|
566
|
+
/**
|
|
567
|
+
* Recognize a request from the server: its `id`, the `method` handlers are registered for,
|
|
568
|
+
* and the `params` they receive. Return `undefined` (or `null`) for any other message.
|
|
569
|
+
* A `timeout` (in ms) overrides the manager's for this request.
|
|
570
|
+
*
|
|
571
|
+
* `params` come from the server, so validate them before acting on them.
|
|
572
|
+
*/
|
|
573
|
+
request: (message: In) => Q | null | undefined;
|
|
574
|
+
/** Build the reply to request `id`. Annotate `result` to type what handlers return. */
|
|
575
|
+
respond: (id: number | string, result: R) => Out;
|
|
576
|
+
/**
|
|
577
|
+
* Build the error reply to request `id`: what a handler threw, a `NotFoundError` `DOMException`
|
|
578
|
+
* when nothing is registered for the method, a `TimeoutError` after `timeout`, or an
|
|
579
|
+
* `AbortError` from `dispose()`.
|
|
580
|
+
*/
|
|
581
|
+
error: (id: number | string, error: unknown) => Out;
|
|
582
|
+
/**
|
|
583
|
+
* The id of a request the server withdrew, or `undefined` (or `null`) if the message isn't a
|
|
584
|
+
* cancellation. The request's `signal` aborts and nothing is sent.
|
|
585
|
+
*/
|
|
586
|
+
cancel?: (message: In) => number | string | null | undefined;
|
|
587
|
+
/**
|
|
588
|
+
* Time to answer a request, in ms. When it runs out, the `error` reply (a `TimeoutError`)
|
|
589
|
+
* is sent and the request's `signal` aborts.
|
|
590
|
+
* @default Infinity
|
|
591
|
+
*/
|
|
592
|
+
timeout?: number;
|
|
593
|
+
}
|
|
594
|
+
/** A request from the server that hasn't been answered yet. */
|
|
595
|
+
interface IncomingRequest<P = unknown, R = unknown> {
|
|
596
|
+
/** The id the server sent. Replies carry it back. */
|
|
597
|
+
readonly id: number | string;
|
|
598
|
+
/** The method it was sent for. */
|
|
599
|
+
readonly method: string;
|
|
600
|
+
/** The `params` from `request`. They come from the server, so validate them. */
|
|
601
|
+
readonly params: P;
|
|
602
|
+
/**
|
|
603
|
+
* Aborts when the answer is no longer wanted: the server cancelled the request, it timed out,
|
|
604
|
+
* the connection it arrived on closed, the responder was disposed, or it was answered with
|
|
605
|
+
* `respond` or `reject` while its handler was still running.
|
|
606
|
+
*/
|
|
607
|
+
readonly signal: AbortSignal;
|
|
608
|
+
/**
|
|
609
|
+
* Reply with `result`. Only the first answer counts.
|
|
610
|
+
* @returns `true` if the reply was sent, `false` if the request was already answered or is gone.
|
|
611
|
+
*/
|
|
612
|
+
respond(result: R): boolean;
|
|
613
|
+
/**
|
|
614
|
+
* Reply with an error, built by the `error` option. Only the first answer counts.
|
|
615
|
+
* @returns `true` if the reply was sent, `false` if the request was already answered or is gone.
|
|
616
|
+
*/
|
|
617
|
+
reject(error: unknown): boolean;
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Answers a request in code. Return (or resolve) the result to reply with it; throw (or reject)
|
|
621
|
+
* to send the `error` reply instead.
|
|
622
|
+
*/
|
|
623
|
+
type RequestHandler<P = unknown, R = unknown> = (params: P, request: IncomingRequest<P, R>) => R | PromiseLike<R>;
|
|
624
|
+
/** Answers the server's requests on one client. Create with {@link createWebSocketResponder}. */
|
|
625
|
+
interface WebSocketResponder<P = unknown, R = unknown> {
|
|
626
|
+
/** The client requests arrive on. Hooks reading the responder keep it connected. */
|
|
627
|
+
readonly client: WebSocketClient<any, any>;
|
|
628
|
+
/**
|
|
629
|
+
* Answer requests for `method` until the returned function is called.
|
|
630
|
+
*
|
|
631
|
+
* With a `handler`, requests are answered in code. Without one, they wait in
|
|
632
|
+
* {@link getSnapshot} until something calls `respond` or `reject` on them, e.g. a dialog
|
|
633
|
+
* that asks the user. When several registrations exist for one method, the newest one takes
|
|
634
|
+
* new requests, and unregistering it hands them back to the previous one. Requests for a
|
|
635
|
+
* method with no registration get a `NotFoundError` reply.
|
|
636
|
+
*
|
|
637
|
+
* @returns An unregister function (safe to call more than once). Requests already waiting stay.
|
|
638
|
+
*/
|
|
639
|
+
onRequest(method: string, handler?: RequestHandler<P, R>): () => void;
|
|
640
|
+
/**
|
|
641
|
+
* Requests waiting for an answer from outside a handler, oldest first. Returns the same array
|
|
642
|
+
* until it changes.
|
|
643
|
+
*/
|
|
644
|
+
getSnapshot(): readonly IncomingRequest<P, R>[];
|
|
645
|
+
/** Called whenever {@link getSnapshot} changes. Compatible with `useSyncExternalStore`. */
|
|
646
|
+
subscribe(listener: () => void): () => void;
|
|
647
|
+
/**
|
|
648
|
+
* Stop answering: send an `AbortError` reply to every request in flight and stop listening.
|
|
649
|
+
* Only needed for responders created dynamically.
|
|
650
|
+
*/
|
|
651
|
+
dispose(): void;
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Answer requests the server sends: run a handler for tools that only exist in the browser
|
|
655
|
+
* (selection, clipboard, geolocation), or let a person answer, e.g. to approve an agent's action.
|
|
656
|
+
* The reverse of `createWebSocketRequests`.
|
|
657
|
+
*
|
|
658
|
+
* Every request gets exactly one reply while its connection lives: the handler's result, an
|
|
659
|
+
* `error` reply when it throws, has no registration or times out. When the connection a request
|
|
660
|
+
* arrived on closes, the request is dropped and nothing is sent, since the server can't match a
|
|
661
|
+
* reply on a new connection. Replies are never queued.
|
|
662
|
+
*
|
|
663
|
+
* Requests are ordinary messages: they also reach `onMessage`, `lastMessage` and state stores.
|
|
664
|
+
*
|
|
665
|
+
* @example
|
|
666
|
+
* ```ts
|
|
667
|
+
* export const tools = createWebSocketResponder(agent, {
|
|
668
|
+
* request: message => (message.type === 'call' ? message : undefined),
|
|
669
|
+
* respond: (id, result: unknown) => ({ type: 'result', id, result }),
|
|
670
|
+
* error: (id, error) => ({ type: 'result', id, error: String(error) })
|
|
671
|
+
* });
|
|
672
|
+
*
|
|
673
|
+
* tools.onRequest('get_selection', () => window.getSelection()?.toString() ?? '');
|
|
674
|
+
*
|
|
675
|
+
* // In a component: requests a person answers.
|
|
676
|
+
* const approvals = useAgentApproval(tools, 'approve');
|
|
677
|
+
* approvals[0]?.respond({ approved: true });
|
|
678
|
+
* ```
|
|
679
|
+
*/
|
|
680
|
+
export declare function createWebSocketResponder<Q extends RequestFields, R, In, const Out>(client: WebSocketClient<In, Out>, options: WebSocketResponderOptions<Q, R, NoInfer<In>, NoInfer<Out>>): WebSocketResponder<ParamsOf<Q>, R>;
|
|
681
|
+
//#endregion
|
|
682
|
+
//#region src/sendrate.d.ts
|
|
683
|
+
/** Options for {@link createWebSocketSendRate}. */
|
|
684
|
+
interface WebSocketSendRateOptions {
|
|
685
|
+
/**
|
|
686
|
+
* Ticks per second while the connection keeps up.
|
|
687
|
+
* @default 30
|
|
688
|
+
*/
|
|
689
|
+
maxRate?: number;
|
|
690
|
+
/**
|
|
691
|
+
* The rate never drops below this, in ticks per second.
|
|
692
|
+
* @default 5
|
|
693
|
+
*/
|
|
694
|
+
minRate?: number;
|
|
695
|
+
/**
|
|
696
|
+
* Bytes waiting in the browser's send buffer (`socket.bufferedAmount`) above which a tick
|
|
697
|
+
* sends nothing and the rate halves.
|
|
698
|
+
* @default 1024
|
|
699
|
+
*/
|
|
700
|
+
maxBuffered?: number;
|
|
701
|
+
/**
|
|
702
|
+
* Measurements from `createWebSocketLatency` on the same client. With them, a round-trip time
|
|
703
|
+
* that rises also lowers the rate. Without them, only the send buffer is watched.
|
|
704
|
+
*/
|
|
705
|
+
latency?: Pick<WebSocketLatency, 'getSnapshot'>;
|
|
706
|
+
/**
|
|
707
|
+
* How far `rtt` may rise above the lowest one measured on this connection before the rate
|
|
708
|
+
* halves, in ms. A steady high ping keeps the full rate; only a rising one counts.
|
|
709
|
+
* @default 100
|
|
710
|
+
*/
|
|
711
|
+
maxRttIncrease?: number;
|
|
712
|
+
}
|
|
713
|
+
/** The current send rate. A new object is created on every change. */
|
|
714
|
+
interface SendRate {
|
|
715
|
+
/** Ticks per second, rounded. */
|
|
716
|
+
readonly rate: number;
|
|
717
|
+
/**
|
|
718
|
+
* Whether the last tick found the link congested: the send buffer above `maxBuffered`, or
|
|
719
|
+
* `rtt` risen more than `maxRttIncrease`.
|
|
720
|
+
*/
|
|
721
|
+
readonly congested: boolean;
|
|
722
|
+
}
|
|
723
|
+
/** Keyed sends coalesced at a rate that adapts to the link. Create with {@link createWebSocketSendRate}. */
|
|
724
|
+
interface WebSocketSendRate<Out> {
|
|
725
|
+
/** The client the messages are sent on. */
|
|
726
|
+
readonly client: WebSocketClient<any, Out>;
|
|
727
|
+
/**
|
|
728
|
+
* Send `message` at the next tick. A message with the same `key` still waiting for it is
|
|
729
|
+
* replaced, so only the newest one goes out. Sent with `volatile`.
|
|
730
|
+
*/
|
|
731
|
+
send(message: Out, key: string): void;
|
|
732
|
+
/** Send everything waiting now, e.g. right before a one-shot action that must carry the latest aim. */
|
|
733
|
+
flush(): void;
|
|
734
|
+
/** The current {@link SendRate}. Returns the same object until it changes. */
|
|
735
|
+
getSnapshot(): SendRate;
|
|
736
|
+
/** Called whenever the rate or `congested` changes. Compatible with `useSyncExternalStore`. */
|
|
737
|
+
subscribe(listener: () => void): () => void;
|
|
738
|
+
/** Stop sending and listening. Only needed for instances created dynamically. */
|
|
739
|
+
dispose(): void;
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* Send high-rate state, such as aim, cursor or position, at a rate that adapts to the
|
|
743
|
+
* connection. Messages are coalesced per key between ticks. The rate drops by half when the
|
|
744
|
+
* send buffer fills up or the round trip grows, and climbs back one tick per second at a time
|
|
745
|
+
* when the link keeps up, so players on a poor connection degrade smoothly instead of building
|
|
746
|
+
* up lag.
|
|
747
|
+
*
|
|
748
|
+
* Ticks run only while the socket is open and something is waiting. Messages waiting during a
|
|
749
|
+
* reconnect go out after it; `close()` drops them. It doesn't open the connection by itself.
|
|
750
|
+
*
|
|
751
|
+
* @example
|
|
752
|
+
* ```ts
|
|
753
|
+
* export const stream = createWebSocketSendRate(game, { latency, maxRate: 30 });
|
|
754
|
+
*
|
|
755
|
+
* // On every pointer move: at most 30 a second, fewer on a congested link.
|
|
756
|
+
* stream.send({ type: 'aim', angle }, 'aim');
|
|
757
|
+
* ```
|
|
758
|
+
*/
|
|
759
|
+
export declare function createWebSocketSendRate<Out>(client: WebSocketClient<any, Out>, options?: WebSocketSendRateOptions): WebSocketSendRate<Out>;
|
|
760
|
+
//#endregion
|
|
761
|
+
//#region src/state.d.ts
|
|
504
762
|
/** Options for {@link createWebSocketState}. */
|
|
505
763
|
interface WebSocketStateOptions<S, In> {
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
764
|
+
/** The state before any message arrives, and what `reset()` returns to. */
|
|
765
|
+
initialState: S;
|
|
766
|
+
/**
|
|
767
|
+
* Fold one incoming message into the state. Must be pure: return a new object for a
|
|
768
|
+
* change, or the same `state` to ignore the message (subscribers aren't notified).
|
|
769
|
+
*/
|
|
770
|
+
reduce: (state: S, message: In) => S;
|
|
771
|
+
/**
|
|
772
|
+
* `'frame'`: notify subscribers at most once per animation frame instead of once per
|
|
773
|
+
* message, so a fast stream (tokens, tickers, game state) renders once per frame.
|
|
774
|
+
* `getState()` is always current; only notifications wait. `setState` and `reset` still
|
|
775
|
+
* notify right away.
|
|
776
|
+
*
|
|
777
|
+
* Browsers pause animation frames in background tabs: the state keeps up, and subscribers
|
|
778
|
+
* hear about it when the tab is visible again. Without `requestAnimationFrame` (Node, some
|
|
779
|
+
* workers), it waits about 16 ms instead.
|
|
780
|
+
*/
|
|
781
|
+
batch?: 'frame';
|
|
513
782
|
}
|
|
514
783
|
/**
|
|
515
784
|
* State derived from a client's messages. Read it with `useWebSocketState(store, selector)`,
|
|
@@ -518,20 +787,20 @@ interface WebSocketStateOptions<S, In> {
|
|
|
518
787
|
* @typeParam S - The state type. Don't use a function type: `setState` treats functions as updaters.
|
|
519
788
|
*/
|
|
520
789
|
interface WebSocketState<S> {
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
790
|
+
/** The client whose messages this store reduces. Hooks reading the store keep it connected. */
|
|
791
|
+
readonly client: WebSocketClient<any, any>;
|
|
792
|
+
/** The `initialState` it was created with. Used for server rendering and hydration. */
|
|
793
|
+
readonly initialState: S;
|
|
794
|
+
/** The current state. Returns the same object until it changes. */
|
|
795
|
+
getState(): S;
|
|
796
|
+
/** Called whenever the state changes. Compatible with `useSyncExternalStore`. */
|
|
797
|
+
subscribe(listener: () => void): () => void;
|
|
798
|
+
/** Replace the state, or update it from the current one, e.g. for optimistic updates. */
|
|
799
|
+
setState(update: S | ((state: S) => S)): void;
|
|
800
|
+
/** Go back to `initialState`. */
|
|
801
|
+
reset(): void;
|
|
802
|
+
/** Stop reducing messages. Only needed for stores created dynamically rather than at module level. */
|
|
803
|
+
dispose(): void;
|
|
535
804
|
}
|
|
536
805
|
/**
|
|
537
806
|
* Keep state derived from a client's messages, like a reducer that runs on every message.
|
|
@@ -551,28 +820,29 @@ interface WebSocketState<S> {
|
|
|
551
820
|
* const acme = useWebSocketState(priceState, state => state.ACME);
|
|
552
821
|
* ```
|
|
553
822
|
*/
|
|
554
|
-
declare function createWebSocketState<S, In>(client: WebSocketClient<In, any>, options: WebSocketStateOptions<S, NoInfer<In>>): WebSocketState<S>;
|
|
555
|
-
|
|
823
|
+
export declare function createWebSocketState<S, In>(client: WebSocketClient<In, any>, options: WebSocketStateOptions<S, NoInfer<In>>): WebSocketState<S>;
|
|
824
|
+
//#endregion
|
|
825
|
+
//#region src/topics.d.ts
|
|
556
826
|
/** Options for {@link createWebSocketTopics}: the messages your server expects. */
|
|
557
827
|
interface WebSocketTopicsOptions<Out> {
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
828
|
+
/** The message that subscribes to `topic`. */
|
|
829
|
+
subscribe: (topic: string) => Out;
|
|
830
|
+
/** The message that unsubscribes from `topic`. Omit it if your server has none. */
|
|
831
|
+
unsubscribe?: (topic: string) => Out;
|
|
562
832
|
}
|
|
563
833
|
/** Reference-counted topic subscriptions on one client. Create with {@link createWebSocketTopics}. */
|
|
564
834
|
interface WebSocketTopics {
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
835
|
+
/** The client the subscription messages are sent on. */
|
|
836
|
+
readonly client: WebSocketClient<any, any>;
|
|
837
|
+
/**
|
|
838
|
+
* Hold a subscription to `topic`, and the client's connection, until the returned
|
|
839
|
+
* function is called. The release function is safe to call more than once.
|
|
840
|
+
*/
|
|
841
|
+
acquire(topic: string): () => void;
|
|
842
|
+
/** The topics currently held, in the order they were first acquired. */
|
|
843
|
+
active(): string[];
|
|
844
|
+
/** Stop managing subscriptions. Only needed for managers created dynamically. */
|
|
845
|
+
dispose(): void;
|
|
576
846
|
}
|
|
577
847
|
/**
|
|
578
848
|
* Manage topic subscriptions that survive reconnects.
|
|
@@ -596,6 +866,7 @@ interface WebSocketTopics {
|
|
|
596
866
|
* useWebSocketTopic(topics, `prices:${symbol}`);
|
|
597
867
|
* ```
|
|
598
868
|
*/
|
|
599
|
-
declare function createWebSocketTopics<const Out>(client: WebSocketClient<any, Out>, options: WebSocketTopicsOptions<NoInfer<Out>>): WebSocketTopics;
|
|
600
|
-
|
|
601
|
-
export {
|
|
869
|
+
export declare function createWebSocketTopics<const Out>(client: WebSocketClient<any, Out>, options: WebSocketTopicsOptions<NoInfer<Out>>): WebSocketTopics;
|
|
870
|
+
//#endregion
|
|
871
|
+
export type { CloseInfo, EventMap, HeartbeatOptions, IncomingRequest, Latency, QueueOptions, ReconnectOptions, RequestHandler, RequestOptions, SendData, SendOptions, SendRate, Snapshot, StandardSchemaV1, Status, UrlSource, WebSocketClient, WebSocketLatency, WebSocketLatencyOptions, WebSocketOptions, WebSocketRequests, WebSocketRequestsOptions, WebSocketResponder, WebSocketResponderOptions, WebSocketSendRate, WebSocketSendRateOptions, WebSocketState, WebSocketStateOptions, WebSocketTopics, WebSocketTopicsOptions };
|
|
872
|
+
//# sourceMappingURL=core.d.ts.map
|