@avijs/websocket 0.0.0-stage → 1.2.0-rc.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 +21 -0
- package/README.md +34 -2
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/websocket.d.ts +53 -0
- package/dist/websocket.d.ts.map +1 -0
- package/dist/websocket.js +315 -0
- package/dist/websocket.js.map +1 -0
- package/package.json +54 -3
- package/src/index.ts +8 -0
- package/src/websocket.ts +389 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Christopher Robin Chase
|
|
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,3 +1,35 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @avijs/websocket
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
WebSocket routes for Avi.js. A WebSocket endpoint is an ordinary `GET` route, so guards,
|
|
4
|
+
middleware, dependency injection and params work as on any other route. Runs on
|
|
5
|
+
[`ws`](https://github.com/websockets/ws). Experimental: the API may change in a 1.x minor release.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @avijs/websocket
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { Controller, Get, UseGuards, type Context } from '@avijs/core';
|
|
13
|
+
import { websocket } from '@avijs/websocket';
|
|
14
|
+
|
|
15
|
+
@Controller('/echo')
|
|
16
|
+
export class EchoController {
|
|
17
|
+
@Get('/')
|
|
18
|
+
@UseGuards(signedIn)
|
|
19
|
+
connect(ctx: Context) {
|
|
20
|
+
return websocket(ctx, async (socket) => {
|
|
21
|
+
for await (const message of socket) await socket.send(`echo: ${String(message)}`);
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Messages can be validated with any Standard Schema (`{ message: schema }`), browser origins are
|
|
28
|
+
checked by default, and connections close with code 1001 when the app shuts down.
|
|
29
|
+
|
|
30
|
+
Part of [Avi.js](https://github.com/chrischase011/avi-js), a TypeScript framework for Node.js with
|
|
31
|
+
modules, controllers and dependency injection, without `reflect-metadata`. See the
|
|
32
|
+
[WebSockets chapter](https://github.com/chrischase011/avi-js/blob/main/docs/tutorial/19-websockets.md)
|
|
33
|
+
of the tutorial.
|
|
34
|
+
|
|
35
|
+
Requires Node.js 22.12 or newer. MIT licensed.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,YAAY,EACV,SAAS,EACT,mBAAmB,EACnB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,gBAAgB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { type Context, type InferOutput, type StandardSchemaV1, type Upgrade } from '@avijs/core';
|
|
2
|
+
import { WebSocket } from 'ws';
|
|
3
|
+
/** A message as received: text frames as strings, binary frames as bytes. */
|
|
4
|
+
export type WebSocketMessage = string | Uint8Array;
|
|
5
|
+
/** What iterating a connection gives: validated JSON with a `message` schema, else raw messages. */
|
|
6
|
+
export type MessageOf<S> = S extends StandardSchemaV1 ? InferOutput<S> : WebSocketMessage;
|
|
7
|
+
export interface WebSocketOptions<S extends StandardSchemaV1 | undefined = undefined> {
|
|
8
|
+
/**
|
|
9
|
+
* Parses each message as JSON and validates it. A message that is not JSON or fails the schema
|
|
10
|
+
* closes the connection with code 1007; a binary one with 1003.
|
|
11
|
+
*/
|
|
12
|
+
message?: S;
|
|
13
|
+
/** The largest message accepted, in bytes. Larger ones close the connection (1009). Default 1 MiB. */
|
|
14
|
+
maxPayload?: number;
|
|
15
|
+
/** Pings this often, in ms, and drops a client that missed the previous ping. Default 30 000. */
|
|
16
|
+
heartbeat?: number | false;
|
|
17
|
+
/**
|
|
18
|
+
* Origins allowed to connect from a browser, such as `https://app.example.com`. Default: only
|
|
19
|
+
* pages served from the same host. `'*'` allows any, or pass a function. Clients that send no
|
|
20
|
+
* `Origin` (not browsers) are always allowed.
|
|
21
|
+
*/
|
|
22
|
+
origins?: readonly string[] | '*' | ((origin: string) => boolean);
|
|
23
|
+
/** Subprotocols the server speaks, in order of preference. Default: accept the client's first. */
|
|
24
|
+
protocols?: readonly string[];
|
|
25
|
+
}
|
|
26
|
+
/** One client connection. Iterate it for the client's messages. */
|
|
27
|
+
export interface WebSocketConnection<T = WebSocketMessage> extends AsyncIterable<T> {
|
|
28
|
+
/** Aborts when the connection closes, for either side's reason. */
|
|
29
|
+
readonly signal: AbortSignal;
|
|
30
|
+
/** The subprotocol agreed on, or `''`. */
|
|
31
|
+
readonly protocol: string;
|
|
32
|
+
/**
|
|
33
|
+
* Sends strings as text, bytes as binary and anything else as JSON. Resolves once written, so
|
|
34
|
+
* awaiting it keeps a slow client from piling up messages. Does nothing once closed.
|
|
35
|
+
*/
|
|
36
|
+
send(data: unknown): Promise<void>;
|
|
37
|
+
/** Starts the closing handshake. Default code 1000. */
|
|
38
|
+
close(code?: number, reason?: string): void;
|
|
39
|
+
/**
|
|
40
|
+
* The `ws` socket underneath, for what this interface lacks. Not covered by the stability
|
|
41
|
+
* promise. Reading it before iterating hands message events over to it: iterating then throws.
|
|
42
|
+
*/
|
|
43
|
+
readonly raw: WebSocket;
|
|
44
|
+
}
|
|
45
|
+
export type WebSocketHandler<T> = (socket: WebSocketConnection<T>) => unknown;
|
|
46
|
+
/**
|
|
47
|
+
* Accepts a WebSocket connection on this route. Return the result from the handler: guards,
|
|
48
|
+
* middleware and validation run first, and `handler` gets the connection once it is open.
|
|
49
|
+
* Plain requests get a 426. The connection stays open until either side closes it; an error
|
|
50
|
+
* thrown by `handler` closes it with 1011 and is logged.
|
|
51
|
+
*/
|
|
52
|
+
export declare function websocket<S extends StandardSchemaV1 | undefined = undefined>(ctx: Context, handler: WebSocketHandler<MessageOf<S>>, options?: WebSocketOptions<S>): Upgrade;
|
|
53
|
+
//# sourceMappingURL=websocket.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../src/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,E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AAC,GAAG,EAAE,SAAS,CAAC;CACzB;AAED,MAAM,MAAM,gBAAgB,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC;AAc9E;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,CAAC,SAAS,gBAAgB,GAAG,SAAS,GAAG,SAAS,EAC1E,GAAG,EAAE,OAAO,EACZ,OAAO,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EACvC,OAAO,GAAE,gBAAgB,CAAC,CAAC,CAAM,GAChC,OAAO,CA0BT"}
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { HttpError, upgrade, } from '@avijs/core';
|
|
2
|
+
import { WebSocket, WebSocketServer } from 'ws';
|
|
3
|
+
const MAX_PAYLOAD = 1024 * 1024;
|
|
4
|
+
const HEARTBEAT = 30_000;
|
|
5
|
+
// Messages read ahead of the handler before the socket stops reading.
|
|
6
|
+
const QUEUE = 16;
|
|
7
|
+
// Headers ws writes itself; one set by a hook would make a broken 101.
|
|
8
|
+
const OWN_HEADERS = new Set([
|
|
9
|
+
'connection',
|
|
10
|
+
'upgrade',
|
|
11
|
+
'sec-websocket-accept',
|
|
12
|
+
'sec-websocket-protocol',
|
|
13
|
+
]);
|
|
14
|
+
/**
|
|
15
|
+
* Accepts a WebSocket connection on this route. Return the result from the handler: guards,
|
|
16
|
+
* middleware and validation run first, and `handler` gets the connection once it is open.
|
|
17
|
+
* Plain requests get a 426. The connection stays open until either side closes it; an error
|
|
18
|
+
* thrown by `handler` closes it with 1011 and is logged.
|
|
19
|
+
*/
|
|
20
|
+
export function websocket(ctx, handler, options = {}) {
|
|
21
|
+
const maxPayload = options.maxPayload ?? MAX_PAYLOAD;
|
|
22
|
+
if (!Number.isInteger(maxPayload) || maxPayload <= 0) {
|
|
23
|
+
throw new RangeError(`websocket maxPayload must be a positive integer, got ${String(maxPayload)}`);
|
|
24
|
+
}
|
|
25
|
+
const heartbeat = options.heartbeat ?? HEARTBEAT;
|
|
26
|
+
if (heartbeat !== false && (!Number.isInteger(heartbeat) || heartbeat <= 0)) {
|
|
27
|
+
throw new RangeError(`websocket heartbeat must be a positive integer or false, got ${String(heartbeat)}`);
|
|
28
|
+
}
|
|
29
|
+
const accepted = upgrade(ctx, (connection) => open(connection, handler, options, maxPayload, heartbeat), {
|
|
30
|
+
protocol: 'websocket',
|
|
31
|
+
});
|
|
32
|
+
checkHandshake(ctx);
|
|
33
|
+
const origin = ctx.headers.origin;
|
|
34
|
+
if (origin !== undefined && !originAllowed(origin, ctx.headers.host, options.origins)) {
|
|
35
|
+
throw new HttpError(403, 'This origin may not connect');
|
|
36
|
+
}
|
|
37
|
+
return accepted;
|
|
38
|
+
}
|
|
39
|
+
const KEY = /^[+/0-9A-Za-z]{22}==$/;
|
|
40
|
+
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
41
|
+
/** The checks `ws` makes, done here so a refusal is an ordinary error response. */
|
|
42
|
+
function checkHandshake(ctx) {
|
|
43
|
+
if (ctx.method !== 'GET')
|
|
44
|
+
throw new HttpError(405, 'A WebSocket handshake must be a GET');
|
|
45
|
+
const key = ctx.headers['sec-websocket-key'];
|
|
46
|
+
if (key === undefined || !KEY.test(key)) {
|
|
47
|
+
throw new HttpError(400, 'Missing or invalid Sec-WebSocket-Key header');
|
|
48
|
+
}
|
|
49
|
+
const version = ctx.headers['sec-websocket-version'];
|
|
50
|
+
if (version !== '13' && version !== '8') {
|
|
51
|
+
throw new HttpError(400, 'Missing or invalid Sec-WebSocket-Version header', {
|
|
52
|
+
headers: { 'sec-websocket-version': '13, 8' },
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
const protocols = ctx.headers['sec-websocket-protocol'];
|
|
56
|
+
if (protocols !== undefined) {
|
|
57
|
+
const names = protocols.split(',').map((name) => name.trim());
|
|
58
|
+
if (names.some((name) => !TOKEN.test(name)) || new Set(names).size !== names.length) {
|
|
59
|
+
throw new HttpError(400, 'Invalid Sec-WebSocket-Protocol header');
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function originAllowed(origin, host, allowed) {
|
|
64
|
+
if (allowed === '*')
|
|
65
|
+
return true;
|
|
66
|
+
if (typeof allowed === 'function')
|
|
67
|
+
return allowed(origin);
|
|
68
|
+
const normalized = origin.toLowerCase();
|
|
69
|
+
if (allowed)
|
|
70
|
+
return allowed.some((entry) => entry.toLowerCase().replace(/\/$/, '') === normalized);
|
|
71
|
+
try {
|
|
72
|
+
return new URL(origin).host === host?.toLowerCase();
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function open({ req, socket, head, signal, headers }, handler, options, maxPayload, heartbeat) {
|
|
79
|
+
const protocols = options.protocols;
|
|
80
|
+
const server = new WebSocketServer({
|
|
81
|
+
noServer: true,
|
|
82
|
+
clientTracking: false,
|
|
83
|
+
maxPayload,
|
|
84
|
+
...(protocols && {
|
|
85
|
+
handleProtocols: (offered) => protocols.find((name) => offered.has(name)) ?? false,
|
|
86
|
+
}),
|
|
87
|
+
});
|
|
88
|
+
server.once('headers', (lines) => {
|
|
89
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
90
|
+
if (value === undefined || OWN_HEADERS.has(name))
|
|
91
|
+
continue;
|
|
92
|
+
for (const item of Array.isArray(value) ? value : [value])
|
|
93
|
+
lines.push(`${name}: ${String(item)}`);
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
return new Promise((resolve, reject) => {
|
|
97
|
+
server.handleUpgrade(req, socket, head, (ws) => {
|
|
98
|
+
const connection = new Connection(ws, options.message, heartbeat);
|
|
99
|
+
const shutdown = () => {
|
|
100
|
+
ws.close(1001, 'Server shutting down');
|
|
101
|
+
};
|
|
102
|
+
if (signal.aborted)
|
|
103
|
+
shutdown();
|
|
104
|
+
else
|
|
105
|
+
signal.addEventListener('abort', shutdown, { once: true });
|
|
106
|
+
connection.signal.addEventListener('abort', () => {
|
|
107
|
+
signal.removeEventListener('abort', shutdown);
|
|
108
|
+
});
|
|
109
|
+
const fail = (error) => {
|
|
110
|
+
if (ws.readyState === WebSocket.OPEN)
|
|
111
|
+
ws.close(1011, 'Internal error');
|
|
112
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
113
|
+
};
|
|
114
|
+
try {
|
|
115
|
+
Promise.resolve(handler(connection)).then(() => {
|
|
116
|
+
resolve();
|
|
117
|
+
}, fail);
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
fail(error);
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
class Connection {
|
|
126
|
+
#ws;
|
|
127
|
+
#schema;
|
|
128
|
+
#closed = new AbortController();
|
|
129
|
+
#queue = [];
|
|
130
|
+
#waiting;
|
|
131
|
+
#iterating = false;
|
|
132
|
+
#detached = false;
|
|
133
|
+
#paused = false;
|
|
134
|
+
#alive = true;
|
|
135
|
+
// Validation can be async; this keeps messages in order.
|
|
136
|
+
#chain = Promise.resolve();
|
|
137
|
+
// Messages still being validated, counted with the queue.
|
|
138
|
+
#validating = 0;
|
|
139
|
+
constructor(ws, schema, heartbeat) {
|
|
140
|
+
this.#ws = ws;
|
|
141
|
+
this.#schema = schema;
|
|
142
|
+
const onMessage = (data, binary) => {
|
|
143
|
+
this.#receive(data, binary);
|
|
144
|
+
};
|
|
145
|
+
ws.on('message', onMessage);
|
|
146
|
+
ws.on('error', () => undefined);
|
|
147
|
+
let timer;
|
|
148
|
+
if (heartbeat !== false) {
|
|
149
|
+
ws.on('pong', () => (this.#alive = true));
|
|
150
|
+
timer = setInterval(() => {
|
|
151
|
+
// A paused socket reads no pongs; the client is not to blame for that.
|
|
152
|
+
if (this.#paused)
|
|
153
|
+
return;
|
|
154
|
+
if (!this.#alive) {
|
|
155
|
+
ws.terminate();
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
this.#alive = false;
|
|
159
|
+
ws.ping();
|
|
160
|
+
}, heartbeat);
|
|
161
|
+
timer.unref();
|
|
162
|
+
}
|
|
163
|
+
ws.once('close', () => {
|
|
164
|
+
clearInterval(timer);
|
|
165
|
+
ws.off('message', onMessage);
|
|
166
|
+
this.#closed.abort();
|
|
167
|
+
this.#waiting?.({ done: true, value: undefined });
|
|
168
|
+
this.#waiting = undefined;
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
get signal() {
|
|
172
|
+
return this.#closed.signal;
|
|
173
|
+
}
|
|
174
|
+
get protocol() {
|
|
175
|
+
return this.#ws.protocol;
|
|
176
|
+
}
|
|
177
|
+
get raw() {
|
|
178
|
+
if (!this.#iterating) {
|
|
179
|
+
this.#detached = true;
|
|
180
|
+
this.#queue.length = 0;
|
|
181
|
+
this.#resume();
|
|
182
|
+
}
|
|
183
|
+
return this.#ws;
|
|
184
|
+
}
|
|
185
|
+
send(data) {
|
|
186
|
+
const ws = this.#ws;
|
|
187
|
+
if (ws.readyState !== WebSocket.OPEN)
|
|
188
|
+
return Promise.resolve();
|
|
189
|
+
const binary = data instanceof Uint8Array || data instanceof ArrayBuffer;
|
|
190
|
+
// JSON.stringify gives undefined for functions and undefined itself.
|
|
191
|
+
const payload = binary || typeof data === 'string' ? data : JSON.stringify(data);
|
|
192
|
+
if (payload === undefined) {
|
|
193
|
+
return Promise.reject(new TypeError('websocket send: this value has no JSON form'));
|
|
194
|
+
}
|
|
195
|
+
return new Promise((resolve, reject) => {
|
|
196
|
+
ws.send(payload, { binary }, (error) => {
|
|
197
|
+
// A client that left mid-send is not the sender's error.
|
|
198
|
+
if (error && ws.readyState === WebSocket.OPEN)
|
|
199
|
+
reject(error);
|
|
200
|
+
else
|
|
201
|
+
resolve();
|
|
202
|
+
});
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
close(code = 1000, reason) {
|
|
206
|
+
this.#ws.close(code, reason);
|
|
207
|
+
}
|
|
208
|
+
[Symbol.asyncIterator]() {
|
|
209
|
+
if (this.#detached) {
|
|
210
|
+
throw new Error('This connection is read through socket.raw; it cannot be iterated too');
|
|
211
|
+
}
|
|
212
|
+
if (this.#iterating)
|
|
213
|
+
throw new Error('A connection can be iterated only once');
|
|
214
|
+
this.#iterating = true;
|
|
215
|
+
return {
|
|
216
|
+
next: () => {
|
|
217
|
+
if (this.#queue.length > 0) {
|
|
218
|
+
const value = this.#queue.shift();
|
|
219
|
+
if (this.#queue.length < QUEUE / 2)
|
|
220
|
+
this.#resume();
|
|
221
|
+
return Promise.resolve({ done: false, value });
|
|
222
|
+
}
|
|
223
|
+
if (this.#closed.signal.aborted || this.#detached) {
|
|
224
|
+
return Promise.resolve({ done: true, value: undefined });
|
|
225
|
+
}
|
|
226
|
+
return new Promise((resolve) => (this.#waiting = resolve));
|
|
227
|
+
},
|
|
228
|
+
// Breaking out of the loop stops reading; the connection stays open until closed.
|
|
229
|
+
return: () => {
|
|
230
|
+
this.#detached = true;
|
|
231
|
+
this.#queue.length = 0;
|
|
232
|
+
this.#resume();
|
|
233
|
+
return Promise.resolve({ done: true, value: undefined });
|
|
234
|
+
},
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
#receive(data, binary) {
|
|
238
|
+
if (this.#detached)
|
|
239
|
+
return;
|
|
240
|
+
const bytes = Buffer.isBuffer(data)
|
|
241
|
+
? data
|
|
242
|
+
: Array.isArray(data)
|
|
243
|
+
? Buffer.concat(data)
|
|
244
|
+
: Buffer.from(data);
|
|
245
|
+
const schema = this.#schema;
|
|
246
|
+
if (!schema) {
|
|
247
|
+
this.#push((binary ? bytes : bytes.toString('utf8')));
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (binary) {
|
|
251
|
+
this.close(1003, 'Binary messages are not accepted');
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
let parsed;
|
|
255
|
+
try {
|
|
256
|
+
parsed = JSON.parse(bytes.toString('utf8'));
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
this.close(1007, 'Invalid JSON');
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (this.#full())
|
|
263
|
+
return;
|
|
264
|
+
this.#validating++;
|
|
265
|
+
this.#chain = this.#chain
|
|
266
|
+
.then(async () => {
|
|
267
|
+
const result = await schema['~standard'].validate(parsed);
|
|
268
|
+
this.#validating--;
|
|
269
|
+
if (result.issues)
|
|
270
|
+
this.close(1007, 'Invalid message');
|
|
271
|
+
else
|
|
272
|
+
this.#push(result.value);
|
|
273
|
+
})
|
|
274
|
+
.catch(() => {
|
|
275
|
+
this.close(1011, 'Internal error');
|
|
276
|
+
});
|
|
277
|
+
this.#pauseIfFull();
|
|
278
|
+
}
|
|
279
|
+
#push(value) {
|
|
280
|
+
if (this.#detached || this.#ws.readyState !== WebSocket.OPEN)
|
|
281
|
+
return;
|
|
282
|
+
const waiting = this.#waiting;
|
|
283
|
+
if (waiting) {
|
|
284
|
+
this.#waiting = undefined;
|
|
285
|
+
waiting({ done: false, value });
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (!this.#iterating && this.#queue.length >= QUEUE)
|
|
289
|
+
return;
|
|
290
|
+
this.#queue.push(value);
|
|
291
|
+
this.#pauseIfFull();
|
|
292
|
+
}
|
|
293
|
+
/** Until the handler iterates, messages past the read-ahead are dropped instead of waiting. */
|
|
294
|
+
#full() {
|
|
295
|
+
return !this.#iterating && this.#queue.length + this.#validating >= QUEUE;
|
|
296
|
+
}
|
|
297
|
+
// Only a handler that is reading gets to hold the socket back.
|
|
298
|
+
#pauseIfFull() {
|
|
299
|
+
if (!this.#iterating || this.#paused)
|
|
300
|
+
return;
|
|
301
|
+
if (this.#queue.length + this.#validating < QUEUE)
|
|
302
|
+
return;
|
|
303
|
+
this.#paused = true;
|
|
304
|
+
this.#ws.pause();
|
|
305
|
+
}
|
|
306
|
+
#resume() {
|
|
307
|
+
if (!this.#paused)
|
|
308
|
+
return;
|
|
309
|
+
this.#paused = false;
|
|
310
|
+
// Pongs that arrived while paused are only read now.
|
|
311
|
+
this.#alive = true;
|
|
312
|
+
this.#ws.resume();
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
//# sourceMappingURL=websocket.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"websocket.js","sourceRoot":"","sources":["../src/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,OAAO,GAMR,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,SAAS,EAAE,eAAe,EAAgB,MAAM,IAAI,CAAC;AAkD9D,MAAM,WAAW,GAAG,IAAI,GAAG,IAAI,CAAC;AAChC,MAAM,SAAS,GAAG,MAAM,CAAC;AACzB,sEAAsE;AACtE,MAAM,KAAK,GAAG,EAAE,CAAC;AACjB,uEAAuE;AACvE,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC;IAC1B,YAAY;IACZ,SAAS;IACT,sBAAsB;IACtB,wBAAwB;CACzB,CAAC,CAAC;AAEH;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CACvB,GAAY,EACZ,OAAuC,EACvC,UAA+B,EAAE;IAEjC,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,WAAW,CAAC;IACrD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,UAAU,IAAI,CAAC,EAAE,CAAC;QACrD,MAAM,IAAI,UAAU,CAClB,wDAAwD,MAAM,CAAC,UAAU,CAAC,EAAE,CAC7E,CAAC;IACJ,CAAC;IACD,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,SAAS,CAAC;IACjD,IAAI,SAAS,KAAK,KAAK,IAAI,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,SAAS,CAAC,IAAI,SAAS,IAAI,CAAC,CAAC,EAAE,CAAC;QAC5E,MAAM,IAAI,UAAU,CAClB,gEAAgE,MAAM,CAAC,SAAS,CAAC,EAA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;YAC1B,OAAO,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;YAChC,OAAO;QACT,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,UAAU,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,IAAI,KAAK;YAAE,OAAO;QAC5D,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxB,IAAI,CAAC,YAAY,EAAE,CAAC;IACtB,CAAC;IAED,+FAA+F;IAC/F,KAAK;QACH,OAAO,CAAC,IAAI,CAAC,UAAU,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,WAAW,IAAI,KAAK,CAAC;IAC5E,CAAC;IAED,+DAA+D;IAC/D,YAAY;QACV,IAAI,CAAC,IAAI,CAAC,UAAU,IAAI,IAAI,CAAC,OAAO;YAAE,OAAO;QAC7C,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,WAAW,GAAG,KAAK;YAAE,OAAO;QAC1D,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC;IACnB,CAAC;IAED,OAAO;QACL,IAAI,CAAC,IAAI,CAAC,OAAO;YAAE,OAAO;QAC1B,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QACrB,qDAAqD;QACrD,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC;IACpB,CAAC;CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,57 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@avijs/websocket",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.2.0-rc.0",
|
|
4
|
+
"description": "WebSocket routes for Avi.js, with guards, dependency injection and typed messages.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"avi",
|
|
7
|
+
"avi.js",
|
|
8
|
+
"websocket",
|
|
9
|
+
"ws",
|
|
10
|
+
"realtime"
|
|
11
|
+
],
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"author": "Christopher Robin Chase",
|
|
14
|
+
"homepage": "https://chrischase011.github.io/avi-js/",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/chrischase011/avi-js/issues"
|
|
17
|
+
},
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/chrischase011/avi-js.git",
|
|
21
|
+
"directory": "packages/websocket"
|
|
22
|
+
},
|
|
23
|
+
"type": "module",
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=22.12"
|
|
26
|
+
},
|
|
27
|
+
"sideEffects": false,
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"@avijs/source": "./src/index.ts",
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"default": "./dist/index.js"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"dist",
|
|
37
|
+
"src",
|
|
38
|
+
"README.md",
|
|
39
|
+
"LICENSE"
|
|
40
|
+
],
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public"
|
|
43
|
+
},
|
|
44
|
+
"dependencies": {
|
|
45
|
+
"@avijs/core": "^1.2.0-rc.0",
|
|
46
|
+
"@types/ws": "^8.18.1",
|
|
47
|
+
"ws": "^8.23.0"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@avijs/pubsub": "^1.2.0-rc.0",
|
|
51
|
+
"@avijs/testing": "^1.2.0-rc.0",
|
|
52
|
+
"valibot": "1.5.0"
|
|
53
|
+
},
|
|
54
|
+
"scripts": {
|
|
55
|
+
"typecheck": "tsc -p tsconfig.json"
|
|
56
|
+
}
|
|
6
57
|
}
|
package/src/index.ts
ADDED
package/src/websocket.ts
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
import {
|
|
2
|
+
HttpError,
|
|
3
|
+
upgrade,
|
|
4
|
+
type Context,
|
|
5
|
+
type InferOutput,
|
|
6
|
+
type StandardSchemaV1,
|
|
7
|
+
type Upgrade,
|
|
8
|
+
type UpgradeConnection,
|
|
9
|
+
} from '@avijs/core';
|
|
10
|
+
import { WebSocket, WebSocketServer, type RawData } from 'ws';
|
|
11
|
+
|
|
12
|
+
/** A message as received: text frames as strings, binary frames as bytes. */
|
|
13
|
+
export type WebSocketMessage = string | Uint8Array;
|
|
14
|
+
|
|
15
|
+
/** What iterating a connection gives: validated JSON with a `message` schema, else raw messages. */
|
|
16
|
+
export type MessageOf<S> = S extends StandardSchemaV1 ? InferOutput<S> : WebSocketMessage;
|
|
17
|
+
|
|
18
|
+
export interface WebSocketOptions<S extends StandardSchemaV1 | undefined = undefined> {
|
|
19
|
+
/**
|
|
20
|
+
* Parses each message as JSON and validates it. A message that is not JSON or fails the schema
|
|
21
|
+
* closes the connection with code 1007; a binary one with 1003.
|
|
22
|
+
*/
|
|
23
|
+
message?: S;
|
|
24
|
+
/** The largest message accepted, in bytes. Larger ones close the connection (1009). Default 1 MiB. */
|
|
25
|
+
maxPayload?: number;
|
|
26
|
+
/** Pings this often, in ms, and drops a client that missed the previous ping. Default 30 000. */
|
|
27
|
+
heartbeat?: number | false;
|
|
28
|
+
/**
|
|
29
|
+
* Origins allowed to connect from a browser, such as `https://app.example.com`. Default: only
|
|
30
|
+
* pages served from the same host. `'*'` allows any, or pass a function. Clients that send no
|
|
31
|
+
* `Origin` (not browsers) are always allowed.
|
|
32
|
+
*/
|
|
33
|
+
origins?: readonly string[] | '*' | ((origin: string) => boolean);
|
|
34
|
+
/** Subprotocols the server speaks, in order of preference. Default: accept the client's first. */
|
|
35
|
+
protocols?: readonly string[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** One client connection. Iterate it for the client's messages. */
|
|
39
|
+
export interface WebSocketConnection<T = WebSocketMessage> extends AsyncIterable<T> {
|
|
40
|
+
/** Aborts when the connection closes, for either side's reason. */
|
|
41
|
+
readonly signal: AbortSignal;
|
|
42
|
+
/** The subprotocol agreed on, or `''`. */
|
|
43
|
+
readonly protocol: string;
|
|
44
|
+
/**
|
|
45
|
+
* Sends strings as text, bytes as binary and anything else as JSON. Resolves once written, so
|
|
46
|
+
* awaiting it keeps a slow client from piling up messages. Does nothing once closed.
|
|
47
|
+
*/
|
|
48
|
+
send(data: unknown): Promise<void>;
|
|
49
|
+
/** Starts the closing handshake. Default code 1000. */
|
|
50
|
+
close(code?: number, reason?: string): void;
|
|
51
|
+
/**
|
|
52
|
+
* The `ws` socket underneath, for what this interface lacks. Not covered by the stability
|
|
53
|
+
* promise. Reading it before iterating hands message events over to it: iterating then throws.
|
|
54
|
+
*/
|
|
55
|
+
readonly raw: WebSocket;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export type WebSocketHandler<T> = (socket: WebSocketConnection<T>) => unknown;
|
|
59
|
+
|
|
60
|
+
const MAX_PAYLOAD = 1024 * 1024;
|
|
61
|
+
const HEARTBEAT = 30_000;
|
|
62
|
+
// Messages read ahead of the handler before the socket stops reading.
|
|
63
|
+
const QUEUE = 16;
|
|
64
|
+
// Headers ws writes itself; one set by a hook would make a broken 101.
|
|
65
|
+
const OWN_HEADERS = new Set([
|
|
66
|
+
'connection',
|
|
67
|
+
'upgrade',
|
|
68
|
+
'sec-websocket-accept',
|
|
69
|
+
'sec-websocket-protocol',
|
|
70
|
+
]);
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Accepts a WebSocket connection on this route. Return the result from the handler: guards,
|
|
74
|
+
* middleware and validation run first, and `handler` gets the connection once it is open.
|
|
75
|
+
* Plain requests get a 426. The connection stays open until either side closes it; an error
|
|
76
|
+
* thrown by `handler` closes it with 1011 and is logged.
|
|
77
|
+
*/
|
|
78
|
+
export function websocket<S extends StandardSchemaV1 | undefined = undefined>(
|
|
79
|
+
ctx: Context,
|
|
80
|
+
handler: WebSocketHandler<MessageOf<S>>,
|
|
81
|
+
options: WebSocketOptions<S> = {},
|
|
82
|
+
): Upgrade {
|
|
83
|
+
const maxPayload = options.maxPayload ?? MAX_PAYLOAD;
|
|
84
|
+
if (!Number.isInteger(maxPayload) || maxPayload <= 0) {
|
|
85
|
+
throw new RangeError(
|
|
86
|
+
`websocket maxPayload must be a positive integer, got ${String(maxPayload)}`,
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
const heartbeat = options.heartbeat ?? HEARTBEAT;
|
|
90
|
+
if (heartbeat !== false && (!Number.isInteger(heartbeat) || heartbeat <= 0)) {
|
|
91
|
+
throw new RangeError(
|
|
92
|
+
`websocket heartbeat must be a positive integer or false, got ${String(heartbeat)}`,
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
const accepted = upgrade(
|
|
96
|
+
ctx,
|
|
97
|
+
(connection) => open(connection, handler, options, maxPayload, heartbeat),
|
|
98
|
+
{
|
|
99
|
+
protocol: 'websocket',
|
|
100
|
+
},
|
|
101
|
+
);
|
|
102
|
+
checkHandshake(ctx);
|
|
103
|
+
const origin = ctx.headers.origin;
|
|
104
|
+
if (origin !== undefined && !originAllowed(origin, ctx.headers.host, options.origins)) {
|
|
105
|
+
throw new HttpError(403, 'This origin may not connect');
|
|
106
|
+
}
|
|
107
|
+
return accepted;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const KEY = /^[+/0-9A-Za-z]{22}==$/;
|
|
111
|
+
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
112
|
+
|
|
113
|
+
/** The checks `ws` makes, done here so a refusal is an ordinary error response. */
|
|
114
|
+
function checkHandshake(ctx: Context): void {
|
|
115
|
+
if (ctx.method !== 'GET') throw new HttpError(405, 'A WebSocket handshake must be a GET');
|
|
116
|
+
const key = ctx.headers['sec-websocket-key'];
|
|
117
|
+
if (key === undefined || !KEY.test(key)) {
|
|
118
|
+
throw new HttpError(400, 'Missing or invalid Sec-WebSocket-Key header');
|
|
119
|
+
}
|
|
120
|
+
const version = ctx.headers['sec-websocket-version'];
|
|
121
|
+
if (version !== '13' && version !== '8') {
|
|
122
|
+
throw new HttpError(400, 'Missing or invalid Sec-WebSocket-Version header', {
|
|
123
|
+
headers: { 'sec-websocket-version': '13, 8' },
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
const protocols = ctx.headers['sec-websocket-protocol'];
|
|
127
|
+
if (protocols !== undefined) {
|
|
128
|
+
const names = protocols.split(',').map((name) => name.trim());
|
|
129
|
+
if (names.some((name) => !TOKEN.test(name)) || new Set(names).size !== names.length) {
|
|
130
|
+
throw new HttpError(400, 'Invalid Sec-WebSocket-Protocol header');
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function originAllowed(
|
|
136
|
+
origin: string,
|
|
137
|
+
host: string | undefined,
|
|
138
|
+
allowed: WebSocketOptions['origins'],
|
|
139
|
+
): boolean {
|
|
140
|
+
if (allowed === '*') return true;
|
|
141
|
+
if (typeof allowed === 'function') return allowed(origin);
|
|
142
|
+
const normalized = origin.toLowerCase();
|
|
143
|
+
if (allowed)
|
|
144
|
+
return allowed.some((entry) => entry.toLowerCase().replace(/\/$/, '') === normalized);
|
|
145
|
+
try {
|
|
146
|
+
return new URL(origin).host === host?.toLowerCase();
|
|
147
|
+
} catch {
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function open<S extends StandardSchemaV1 | undefined>(
|
|
153
|
+
{ req, socket, head, signal, headers }: UpgradeConnection,
|
|
154
|
+
handler: WebSocketHandler<MessageOf<S>>,
|
|
155
|
+
options: WebSocketOptions<S>,
|
|
156
|
+
maxPayload: number,
|
|
157
|
+
heartbeat: number | false,
|
|
158
|
+
): Promise<void> {
|
|
159
|
+
const protocols = options.protocols;
|
|
160
|
+
const server = new WebSocketServer({
|
|
161
|
+
noServer: true,
|
|
162
|
+
clientTracking: false,
|
|
163
|
+
maxPayload,
|
|
164
|
+
...(protocols && {
|
|
165
|
+
handleProtocols: (offered: Set<string>) =>
|
|
166
|
+
protocols.find((name) => offered.has(name)) ?? false,
|
|
167
|
+
}),
|
|
168
|
+
});
|
|
169
|
+
server.once('headers', (lines: string[]) => {
|
|
170
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
171
|
+
if (value === undefined || OWN_HEADERS.has(name)) continue;
|
|
172
|
+
for (const item of Array.isArray(value) ? value : [value])
|
|
173
|
+
lines.push(`${name}: ${String(item)}`);
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
return new Promise((resolve, reject) => {
|
|
178
|
+
server.handleUpgrade(req, socket, head, (ws) => {
|
|
179
|
+
const connection = new Connection<MessageOf<S>>(ws, options.message, heartbeat);
|
|
180
|
+
const shutdown = () => {
|
|
181
|
+
ws.close(1001, 'Server shutting down');
|
|
182
|
+
};
|
|
183
|
+
if (signal.aborted) shutdown();
|
|
184
|
+
else signal.addEventListener('abort', shutdown, { once: true });
|
|
185
|
+
connection.signal.addEventListener('abort', () => {
|
|
186
|
+
signal.removeEventListener('abort', shutdown);
|
|
187
|
+
});
|
|
188
|
+
const fail = (error: unknown) => {
|
|
189
|
+
if (ws.readyState === WebSocket.OPEN) ws.close(1011, 'Internal error');
|
|
190
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
191
|
+
};
|
|
192
|
+
try {
|
|
193
|
+
Promise.resolve(handler(connection)).then(() => {
|
|
194
|
+
resolve();
|
|
195
|
+
}, fail);
|
|
196
|
+
} catch (error) {
|
|
197
|
+
fail(error);
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
class Connection<T> implements WebSocketConnection<T> {
|
|
204
|
+
readonly #ws: WebSocket;
|
|
205
|
+
readonly #schema: StandardSchemaV1 | undefined;
|
|
206
|
+
readonly #closed = new AbortController();
|
|
207
|
+
readonly #queue: T[] = [];
|
|
208
|
+
#waiting: ((result: IteratorResult<T>) => void) | undefined;
|
|
209
|
+
#iterating = false;
|
|
210
|
+
#detached = false;
|
|
211
|
+
#paused = false;
|
|
212
|
+
#alive = true;
|
|
213
|
+
// Validation can be async; this keeps messages in order.
|
|
214
|
+
#chain: Promise<void> = Promise.resolve();
|
|
215
|
+
// Messages still being validated, counted with the queue.
|
|
216
|
+
#validating = 0;
|
|
217
|
+
|
|
218
|
+
constructor(ws: WebSocket, schema: StandardSchemaV1 | undefined, heartbeat: number | false) {
|
|
219
|
+
this.#ws = ws;
|
|
220
|
+
this.#schema = schema;
|
|
221
|
+
const onMessage = (data: RawData, binary: boolean) => {
|
|
222
|
+
this.#receive(data, binary);
|
|
223
|
+
};
|
|
224
|
+
ws.on('message', onMessage);
|
|
225
|
+
ws.on('error', () => undefined);
|
|
226
|
+
let timer: ReturnType<typeof setInterval> | undefined;
|
|
227
|
+
if (heartbeat !== false) {
|
|
228
|
+
ws.on('pong', () => (this.#alive = true));
|
|
229
|
+
timer = setInterval(() => {
|
|
230
|
+
// A paused socket reads no pongs; the client is not to blame for that.
|
|
231
|
+
if (this.#paused) return;
|
|
232
|
+
if (!this.#alive) {
|
|
233
|
+
ws.terminate();
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
this.#alive = false;
|
|
237
|
+
ws.ping();
|
|
238
|
+
}, heartbeat);
|
|
239
|
+
timer.unref();
|
|
240
|
+
}
|
|
241
|
+
ws.once('close', () => {
|
|
242
|
+
clearInterval(timer);
|
|
243
|
+
ws.off('message', onMessage);
|
|
244
|
+
this.#closed.abort();
|
|
245
|
+
this.#waiting?.({ done: true, value: undefined });
|
|
246
|
+
this.#waiting = undefined;
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
get signal(): AbortSignal {
|
|
251
|
+
return this.#closed.signal;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
get protocol(): string {
|
|
255
|
+
return this.#ws.protocol;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
get raw(): WebSocket {
|
|
259
|
+
if (!this.#iterating) {
|
|
260
|
+
this.#detached = true;
|
|
261
|
+
this.#queue.length = 0;
|
|
262
|
+
this.#resume();
|
|
263
|
+
}
|
|
264
|
+
return this.#ws;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
send(data: unknown): Promise<void> {
|
|
268
|
+
const ws = this.#ws;
|
|
269
|
+
if (ws.readyState !== WebSocket.OPEN) return Promise.resolve();
|
|
270
|
+
const binary = data instanceof Uint8Array || data instanceof ArrayBuffer;
|
|
271
|
+
// JSON.stringify gives undefined for functions and undefined itself.
|
|
272
|
+
const payload =
|
|
273
|
+
binary || typeof data === 'string' ? data : (JSON.stringify(data) as string | undefined);
|
|
274
|
+
if (payload === undefined) {
|
|
275
|
+
return Promise.reject(new TypeError('websocket send: this value has no JSON form'));
|
|
276
|
+
}
|
|
277
|
+
return new Promise((resolve, reject) => {
|
|
278
|
+
ws.send(payload, { binary }, (error) => {
|
|
279
|
+
// A client that left mid-send is not the sender's error.
|
|
280
|
+
if (error && ws.readyState === WebSocket.OPEN) reject(error);
|
|
281
|
+
else resolve();
|
|
282
|
+
});
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
close(code = 1000, reason?: string): void {
|
|
287
|
+
this.#ws.close(code, reason);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
[Symbol.asyncIterator](): AsyncIterator<T> {
|
|
291
|
+
if (this.#detached) {
|
|
292
|
+
throw new Error('This connection is read through socket.raw; it cannot be iterated too');
|
|
293
|
+
}
|
|
294
|
+
if (this.#iterating) throw new Error('A connection can be iterated only once');
|
|
295
|
+
this.#iterating = true;
|
|
296
|
+
return {
|
|
297
|
+
next: () => {
|
|
298
|
+
if (this.#queue.length > 0) {
|
|
299
|
+
const value = this.#queue.shift() as T;
|
|
300
|
+
if (this.#queue.length < QUEUE / 2) this.#resume();
|
|
301
|
+
return Promise.resolve({ done: false, value });
|
|
302
|
+
}
|
|
303
|
+
if (this.#closed.signal.aborted || this.#detached) {
|
|
304
|
+
return Promise.resolve({ done: true, value: undefined });
|
|
305
|
+
}
|
|
306
|
+
return new Promise((resolve) => (this.#waiting = resolve));
|
|
307
|
+
},
|
|
308
|
+
// Breaking out of the loop stops reading; the connection stays open until closed.
|
|
309
|
+
return: () => {
|
|
310
|
+
this.#detached = true;
|
|
311
|
+
this.#queue.length = 0;
|
|
312
|
+
this.#resume();
|
|
313
|
+
return Promise.resolve({ done: true, value: undefined });
|
|
314
|
+
},
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
#receive(data: RawData, binary: boolean): void {
|
|
319
|
+
if (this.#detached) return;
|
|
320
|
+
const bytes = Buffer.isBuffer(data)
|
|
321
|
+
? data
|
|
322
|
+
: Array.isArray(data)
|
|
323
|
+
? Buffer.concat(data)
|
|
324
|
+
: Buffer.from(data);
|
|
325
|
+
const schema = this.#schema;
|
|
326
|
+
if (!schema) {
|
|
327
|
+
this.#push((binary ? bytes : bytes.toString('utf8')) as T);
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
if (binary) {
|
|
331
|
+
this.close(1003, 'Binary messages are not accepted');
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
let parsed: unknown;
|
|
335
|
+
try {
|
|
336
|
+
parsed = JSON.parse(bytes.toString('utf8'));
|
|
337
|
+
} catch {
|
|
338
|
+
this.close(1007, 'Invalid JSON');
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
if (this.#full()) return;
|
|
342
|
+
this.#validating++;
|
|
343
|
+
this.#chain = this.#chain
|
|
344
|
+
.then(async () => {
|
|
345
|
+
const result = await schema['~standard'].validate(parsed);
|
|
346
|
+
this.#validating--;
|
|
347
|
+
if (result.issues) this.close(1007, 'Invalid message');
|
|
348
|
+
else this.#push(result.value as T);
|
|
349
|
+
})
|
|
350
|
+
.catch(() => {
|
|
351
|
+
this.close(1011, 'Internal error');
|
|
352
|
+
});
|
|
353
|
+
this.#pauseIfFull();
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
#push(value: T): void {
|
|
357
|
+
if (this.#detached || this.#ws.readyState !== WebSocket.OPEN) return;
|
|
358
|
+
const waiting = this.#waiting;
|
|
359
|
+
if (waiting) {
|
|
360
|
+
this.#waiting = undefined;
|
|
361
|
+
waiting({ done: false, value });
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
if (!this.#iterating && this.#queue.length >= QUEUE) return;
|
|
365
|
+
this.#queue.push(value);
|
|
366
|
+
this.#pauseIfFull();
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Until the handler iterates, messages past the read-ahead are dropped instead of waiting. */
|
|
370
|
+
#full(): boolean {
|
|
371
|
+
return !this.#iterating && this.#queue.length + this.#validating >= QUEUE;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// Only a handler that is reading gets to hold the socket back.
|
|
375
|
+
#pauseIfFull(): void {
|
|
376
|
+
if (!this.#iterating || this.#paused) return;
|
|
377
|
+
if (this.#queue.length + this.#validating < QUEUE) return;
|
|
378
|
+
this.#paused = true;
|
|
379
|
+
this.#ws.pause();
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
#resume(): void {
|
|
383
|
+
if (!this.#paused) return;
|
|
384
|
+
this.#paused = false;
|
|
385
|
+
// Pongs that arrived while paused are only read now.
|
|
386
|
+
this.#alive = true;
|
|
387
|
+
this.#ws.resume();
|
|
388
|
+
}
|
|
389
|
+
}
|