@statewalker/webrun-streams-ws 0.2.4 → 0.4.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 +153 -120
- package/dist/index.d.ts +1 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +54 -142
- package/dist/message-target.d.ts +69 -0
- package/dist/message-target.d.ts.map +1 -0
- package/dist/websocket-like.d.ts +4 -0
- package/dist/websocket-like.d.ts.map +1 -1
- package/package.json +6 -4
- package/src/index.ts +7 -3
- package/src/message-target.ts +169 -0
- package/src/websocket-like.ts +4 -0
- package/dist/byte-channel.d.ts +0 -12
- package/dist/byte-channel.d.ts.map +0 -1
- package/dist/connect.d.ts +0 -28
- package/dist/connect.d.ts.map +0 -1
- package/dist/serve.d.ts +0 -29
- package/dist/serve.d.ts.map +0 -1
- package/src/byte-channel.ts +0 -122
- package/src/connect.ts +0 -76
- package/src/serve.ts +0 -44
package/README.md
CHANGED
|
@@ -2,91 +2,102 @@
|
|
|
2
2
|
|
|
3
3
|
## What it is
|
|
4
4
|
|
|
5
|
-
A WebSocket
|
|
6
|
-
`
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
5
|
+
A WebSocket as a pipe of bytes for `@statewalker/webrun-rpc`'s port stack.
|
|
6
|
+
`messageTargetOverWebSocket(ws)` turns one open socket into `{ target, signal }`:
|
|
7
|
+
`target` is a `MessageTarget` whose messages are `Uint8Array`s, one WebSocket
|
|
8
|
+
message each, and `signal` aborts when the socket closes. Hand both to
|
|
9
|
+
`webrun-rpc`'s `overPipe` with `msgpackCodec`, and `webrun-rpc`'s `connect` /
|
|
10
|
+
`serve` run many concurrent calls over the socket, one port per call. The
|
|
11
|
+
handler is an ordinary `Duplex` (`(input) => AsyncGenerator<Uint8Array>`) and
|
|
12
|
+
never sees the socket.
|
|
11
13
|
|
|
12
14
|
## Why it exists
|
|
13
15
|
|
|
14
16
|
A raw WebSocket is one message pipe. It has no notion of a request, no
|
|
15
17
|
concurrency, no half-close, and no way to deliver the far end's exception as
|
|
16
|
-
an `Error`.
|
|
17
|
-
|
|
18
|
-
`
|
|
19
|
-
|
|
20
|
-
the
|
|
18
|
+
an `Error`. `webrun-rpc`'s port stack supplies all of that over any pipe of
|
|
19
|
+
messages: `overPipe` invents a port per call on the pipe, and `connect` /
|
|
20
|
+
`serve` run one stream per port, with a producer never more than one chunk
|
|
21
|
+
ahead of its consumer. What it needs from a transport is the pipe, plus a
|
|
22
|
+
way to learn that the pipe died. A WebSocket says so only through its `close`
|
|
23
|
+
event, delivers binary messages in a form that depends on the runtime and on
|
|
24
|
+
`binaryType`, and has no drain event. This package handles those three things
|
|
25
|
+
and nothing else. Because the handler is a plain `Duplex`, the same function
|
|
26
|
+
runs over any other transport that implements the seam.
|
|
21
27
|
|
|
22
28
|
## How to use
|
|
23
29
|
|
|
24
30
|
```sh
|
|
25
|
-
pnpm add @statewalker/webrun-streams-ws
|
|
31
|
+
pnpm add @statewalker/webrun-streams-ws @statewalker/webrun-rpc @statewalker/webrun-msgpack
|
|
26
32
|
```
|
|
27
33
|
|
|
28
|
-
|
|
29
|
-
|
|
34
|
+
The pipe is built on `newMessagePipe` from `@statewalker/webrun-streams`, its one
|
|
35
|
+
runtime dependency; `@statewalker/webrun-rpc` and `@statewalker/webrun-msgpack` are
|
|
36
|
+
what you run over it. No peer dependencies.
|
|
37
|
+
One entry point, `.`.
|
|
30
38
|
|
|
31
|
-
- **Browser and worker**: `
|
|
39
|
+
- **Browser and worker**: `openWebSocket` uses the global `WebSocket`.
|
|
32
40
|
- **Node**: pass a constructor as `WebSocketCtor`. The `ws` package works
|
|
33
|
-
(`pnpm add ws`). On the server side
|
|
34
|
-
|
|
35
|
-
`
|
|
41
|
+
(`pnpm add ws`). On the server side there is no server object to hand over:
|
|
42
|
+
call `messageTargetOverWebSocket` on each socket your server accepts, so it
|
|
43
|
+
works with `ws`'s `WebSocketServer`, a runtime's built-in upgrade, or any
|
|
44
|
+
other source of open sockets.
|
|
36
45
|
|
|
37
46
|
| Export | What it gives |
|
|
38
47
|
| --- | --- |
|
|
39
|
-
| `
|
|
40
|
-
| `
|
|
41
|
-
| `
|
|
42
|
-
| `WebSocketLike` | Structural socket type accepted everywhere: `readyState`, `send`, `close`, `addEventListener` / `removeEventListener` for `message`, `open`, `close`, `error`. Node's `ws` satisfies it as is; the DOM `WebSocket` satisfies it at runtime but needs a cast at the type level (see Internals). |
|
|
48
|
+
| `messageTargetOverWebSocket(ws)` | One open socket as a `WebSocketMessageTarget`, `{ target, signal }`: `target` is a `MessageTarget` of bytes (one WebSocket message each) with `bufferedAmount` and `whenDrained()`; `signal` aborts when the socket closes. Hand both to `overPipe` with `msgpackCodec`; see below. |
|
|
49
|
+
| `openWebSocket(params)` | Opens a socket and resolves once it is `OPEN`; rejects if it fails or closes first. `params` is `OpenWebSocketParams`. |
|
|
50
|
+
| `DRAIN_LOW_WATER` | `256 * 1024`. `whenDrained()` resolves once `bufferedAmount` is at most this. |
|
|
51
|
+
| `WebSocketLike` | Structural socket type accepted everywhere: `readyState`, optional `bufferedAmount` and `binaryType`, `send`, `close`, `addEventListener` / `removeEventListener` for `message`, `open`, `close`, `error`. Node's `ws` satisfies it as is; the DOM `WebSocket` satisfies it at runtime but needs a cast at the type level (see Internals). |
|
|
43
52
|
| `WS_READY_STATE` | `{ CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3 }`. |
|
|
44
|
-
| `
|
|
53
|
+
| `WebSocketMessageTarget`, `OpenWebSocketParams` | Types for the two functions above. |
|
|
45
54
|
|
|
46
|
-
`
|
|
55
|
+
`OpenWebSocketParams`:
|
|
47
56
|
|
|
48
57
|
| Field | Type | Default | Meaning |
|
|
49
58
|
| --- | --- | --- | --- |
|
|
50
59
|
| `url` | `string` | required | `ws://` or `wss://` URL. |
|
|
51
60
|
| `protocols` | `string \| string[]` | none | Subprotocols passed to the constructor. |
|
|
52
61
|
| `WebSocketCtor` | `new (url, protocols?) => WebSocketLike` | `globalThis.WebSocket` | Required where there is no global `WebSocket`. |
|
|
53
|
-
| `mux` | `EmulateMuxOptions` | `emulateMux` defaults | `mtu`, `maxStreams`, `maxStreamBuffer`. `side` is always `"initiator"`. |
|
|
54
62
|
|
|
55
|
-
`
|
|
56
|
-
|
|
57
|
-
| Field | Type | Meaning |
|
|
58
|
-
| --- | --- | --- |
|
|
59
|
-
| `onConnection` | `(cb: (ws: WebSocketLike) => void) => () => void` | Subscribes to inbound open sockets; returns an unsubscribe function. |
|
|
60
|
-
| `mux` | `EmulateMuxOptions` | As above. `side` is always `"responder"`. |
|
|
61
|
-
|
|
62
|
-
Both sides of a connection must run this package's `emulateMux` wire format;
|
|
63
|
-
a plain WebSocket peer cannot talk to it.
|
|
63
|
+
Both ends of a connection must run the port stack (`overPipe` with the same
|
|
64
|
+
codec); a plain WebSocket peer cannot talk to it.
|
|
64
65
|
|
|
65
66
|
## Examples
|
|
66
67
|
|
|
67
68
|
### Serve and call in Node
|
|
68
69
|
|
|
69
70
|
```ts
|
|
70
|
-
import {
|
|
71
|
+
import { msgpackCodec } from "@statewalker/webrun-msgpack";
|
|
72
|
+
import { connect, overPipe, serve } from "@statewalker/webrun-rpc";
|
|
73
|
+
import {
|
|
74
|
+
messageTargetOverWebSocket,
|
|
75
|
+
openWebSocket,
|
|
76
|
+
type WebSocketLike,
|
|
77
|
+
} from "@statewalker/webrun-streams-ws";
|
|
71
78
|
import { WebSocket as NodeWebSocket, WebSocketServer } from "ws";
|
|
72
79
|
|
|
73
80
|
const wss = new WebSocketServer({ port: 8080 });
|
|
74
81
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
82
|
+
// server, per accepted socket
|
|
83
|
+
wss.on("connection", (socket) => {
|
|
84
|
+
const { target, signal } = messageTargetOverWebSocket(socket as unknown as WebSocketLike);
|
|
85
|
+
void serve(
|
|
86
|
+
{ mux: overPipe(target, { codec: msgpackCodec, side: "responder", signal }) },
|
|
87
|
+
async function* echo(input) {
|
|
88
|
+
for await (const chunk of input) yield chunk;
|
|
80
89
|
},
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
for await (const chunk of input) yield chunk;
|
|
84
|
-
},
|
|
85
|
-
);
|
|
90
|
+
);
|
|
91
|
+
});
|
|
86
92
|
|
|
87
|
-
|
|
93
|
+
// client
|
|
94
|
+
const ws = await openWebSocket({
|
|
88
95
|
url: "ws://127.0.0.1:8080",
|
|
89
|
-
WebSocketCtor: NodeWebSocket,
|
|
96
|
+
WebSocketCtor: NodeWebSocket as unknown as new (url: string) => WebSocketLike,
|
|
97
|
+
});
|
|
98
|
+
const pipe = messageTargetOverWebSocket(ws);
|
|
99
|
+
const { call, close } = await connect({
|
|
100
|
+
mux: overPipe(pipe.target, { codec: msgpackCodec, side: "initiator", signal: pipe.signal }),
|
|
90
101
|
});
|
|
91
102
|
|
|
92
103
|
for await (const chunk of call([new TextEncoder().encode("hello")])) {
|
|
@@ -94,20 +105,34 @@ for await (const chunk of call([new TextEncoder().encode("hello")])) {
|
|
|
94
105
|
}
|
|
95
106
|
|
|
96
107
|
await close();
|
|
97
|
-
await stop();
|
|
98
108
|
wss.close();
|
|
99
109
|
```
|
|
100
110
|
|
|
111
|
+
Pass `signal`: a WebSocket that dies says so only through its `close` event,
|
|
112
|
+
and without it the multiplexer's ports stay open forever. No `maxMessageSize`
|
|
113
|
+
is reported, because WebSocket limits are deployment settings: the `ws` server
|
|
114
|
+
closes with 1009 past its `maxPayload` (100 MiB by default), and browsers and
|
|
115
|
+
proxies have their own. Without one, a chunk crosses as one message; set
|
|
116
|
+
`overPipe`'s `maxMessageSize` (256 bytes under the real limit) or `frameSize`
|
|
117
|
+
if your path has a smaller ceiling.
|
|
118
|
+
|
|
101
119
|
### Browser client, concurrent calls
|
|
102
120
|
|
|
103
121
|
```ts
|
|
122
|
+
import { msgpackCodec } from "@statewalker/webrun-msgpack";
|
|
123
|
+
import { connect, overPipe } from "@statewalker/webrun-rpc";
|
|
104
124
|
import { collectBytes } from "@statewalker/webrun-streams";
|
|
105
|
-
import {
|
|
125
|
+
import { messageTargetOverWebSocket, openWebSocket } from "@statewalker/webrun-streams-ws";
|
|
106
126
|
|
|
107
|
-
const {
|
|
127
|
+
const { target, signal } = messageTargetOverWebSocket(
|
|
128
|
+
await openWebSocket({ url: "wss://example.com/socket" }),
|
|
129
|
+
);
|
|
130
|
+
const { call, close } = await connect({
|
|
131
|
+
mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal }),
|
|
132
|
+
});
|
|
108
133
|
const enc = new TextEncoder();
|
|
109
134
|
|
|
110
|
-
// Each call is an independent
|
|
135
|
+
// Each call is an independent port on the same socket.
|
|
111
136
|
const [a, b] = await Promise.all([
|
|
112
137
|
collectBytes(call([enc.encode("first")])),
|
|
113
138
|
collectBytes(call([enc.encode("second")])),
|
|
@@ -118,67 +143,71 @@ await close();
|
|
|
118
143
|
### HTTP over the socket
|
|
119
144
|
|
|
120
145
|
`@statewalker/webrun-http-streams` carries `Request` / `Response` over any
|
|
121
|
-
`Duplex
|
|
146
|
+
`Duplex`, so it runs on the `call` from the previous example:
|
|
122
147
|
|
|
123
148
|
```ts
|
|
124
149
|
import { fetchOverDuplex } from "@statewalker/webrun-http-streams";
|
|
125
|
-
import { connect } from "@statewalker/webrun-streams-ws";
|
|
126
150
|
|
|
127
|
-
const { call } = await connect({ url: "wss://example.com/socket" });
|
|
128
151
|
const response = await fetchOverDuplex(call, new Request("http://peer/api/todo"));
|
|
129
152
|
```
|
|
130
153
|
|
|
131
|
-
### Driving `emulateMux` on a socket you own
|
|
132
|
-
|
|
133
|
-
```ts
|
|
134
|
-
import { emulateMux } from "@statewalker/webrun-streams";
|
|
135
|
-
import { byteChannelFromWebSocket, type WebSocketLike } from "@statewalker/webrun-streams-ws";
|
|
136
|
-
|
|
137
|
-
declare const socket: WebSocket; // already open
|
|
138
|
-
// The cast is needed with current DOM typings; see "WebSocketLike and the DOM type" below.
|
|
139
|
-
const mux = emulateMux(byteChannelFromWebSocket(socket as unknown as WebSocketLike), {
|
|
140
|
-
side: "initiator",
|
|
141
|
-
});
|
|
142
|
-
const response = mux.call([new TextEncoder().encode("ping")]);
|
|
143
|
-
```
|
|
144
|
-
|
|
145
154
|
## Internals
|
|
146
155
|
|
|
147
|
-
### One socket, one
|
|
156
|
+
### One socket, one pipe, many ports
|
|
148
157
|
|
|
149
158
|
```
|
|
150
|
-
client
|
|
151
|
-
call(a) ──┐
|
|
152
|
-
call(b) ──┼─
|
|
153
|
-
call(c) ──┘ (initiator)
|
|
154
|
-
|
|
159
|
+
client server
|
|
160
|
+
call(a) ──┐ ┌──> handler(a)
|
|
161
|
+
call(b) ──┼─ overPipe ══ WebSocket ══ overPipe ─┼──> handler(b)
|
|
162
|
+
call(c) ──┘ (initiator) (responder) └──> handler(c)
|
|
163
|
+
messageTargetOverWebSocket messageTargetOverWebSocket
|
|
155
164
|
```
|
|
156
165
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
### Why
|
|
165
|
-
|
|
166
|
-
`
|
|
167
|
-
dependency on a server library. It can be wired to `ws`, to a
|
|
168
|
-
built-in WebSocket upgrade, or to a custom accept loop.
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
-
|
|
181
|
-
|
|
166
|
+
Each socket is one pipe. `overPipe` (`webrun-rpc`'s `multiplexPort` with a
|
|
167
|
+
codec) opens a port per call on it, and `webrun-rpc`'s `connect` / `serve`
|
|
168
|
+
run one stream per port. The two ends must pass opposite `side`s so they
|
|
169
|
+
allocate port ids from different sets. Framing, flow control, port lifetimes
|
|
170
|
+
and error propagation are `webrun-rpc`'s; see its README. This package only
|
|
171
|
+
maps the socket onto a `MessageTarget` and reports its death.
|
|
172
|
+
|
|
173
|
+
### Why there is no server object
|
|
174
|
+
|
|
175
|
+
`messageTargetOverWebSocket` takes one socket, whoever accepted it, so this
|
|
176
|
+
package has no dependency on a server library. It can be wired to `ws`, to a
|
|
177
|
+
runtime's built-in WebSocket upgrade, or to a custom accept loop. Tearing a
|
|
178
|
+
server down is two steps: the teardown `webrun-rpc`'s `serve` resolves to
|
|
179
|
+
closes that connection's multiplexer, failing its calls in flight; stop
|
|
180
|
+
accepting and close the sockets yourself (for example `wss.close()` plus
|
|
181
|
+
`terminate()` on each client with `ws`).
|
|
182
|
+
|
|
183
|
+
### How `messageTargetOverWebSocket` maps the socket
|
|
184
|
+
|
|
185
|
+
- The socket must be `OPEN`. Messages must arrive as bytes at once: a socket
|
|
186
|
+
on `binaryType` "blob" (read asynchronously, so a later message could
|
|
187
|
+
overtake it) or `ws`'s "fragments" is switched to "arraybuffer";
|
|
188
|
+
"arraybuffer" and `ws`'s "nodebuffer" are left alone.
|
|
189
|
+
- Each WebSocket message is one `message` event whose `data` is a
|
|
190
|
+
`Uint8Array`. `Uint8Array` (including Node `Buffer`), `ArrayBuffer` and
|
|
191
|
+
other `ArrayBufferView`s are passed through without copying. A text message
|
|
192
|
+
is delivered as its UTF-8 bytes. A message of any other kind ends the pipe
|
|
193
|
+
with a `TypeError` and closes the socket instead of being dropped, since a
|
|
194
|
+
lost envelope would hang its call. Messages that reach no listener are
|
|
195
|
+
dropped, as on a `MessagePort`; one listener throwing does not stop
|
|
196
|
+
delivery to the others.
|
|
197
|
+
- `postMessage` sends one binary message. It throws `TypeError` for anything
|
|
198
|
+
but bytes, so a codec breaking its contract is not papered over. After the
|
|
199
|
+
socket has closed it is a no-op: `signal` already says so.
|
|
200
|
+
- The socket's `close` event (a failing socket fires `error` and then always
|
|
201
|
+
`close`) aborts `signal` with `webrun-streams-ws: the WebSocket closed (code
|
|
202
|
+
<n>)`. `overPipe` closes the multiplexer on it, which fails every call in
|
|
203
|
+
flight. `target.close()` closes the socket and aborts `signal` with
|
|
204
|
+
`webrun-streams-ws: closed locally`.
|
|
205
|
+
- `bufferedAmount` is the socket's own. A WebSocket has no drain event, so
|
|
206
|
+
`whenDrained()` polls it every 5 ms (with an unref'd timer, so a peer that
|
|
207
|
+
stops reading never keeps Node alive) and resolves once it is at most
|
|
208
|
+
`DRAIN_LOW_WATER`, or the socket has closed. Waiting for zero would make a
|
|
209
|
+
sender that waits before every frame (`overPipe`'s `frameSize`) pause a poll
|
|
210
|
+
interval per frame.
|
|
182
211
|
|
|
183
212
|
### WebSocketLike and the DOM type
|
|
184
213
|
|
|
@@ -187,34 +216,36 @@ both fit without this package depending on either. `ws`'s `WebSocket` type
|
|
|
187
216
|
checks as is. The DOM type does not: `WebSocketLike.send` accepts
|
|
188
217
|
`Uint8Array<ArrayBufferLike>`, which the current DOM `WebSocket.send` typing
|
|
189
218
|
(`BufferSource`) rejects, so passing a DOM socket to
|
|
190
|
-
`
|
|
191
|
-
`as unknown as WebSocketLike`. `
|
|
192
|
-
global `WebSocket` and does the cast itself.
|
|
219
|
+
`messageTargetOverWebSocket` or a DOM constructor as `WebSocketCtor` needs
|
|
220
|
+
`as unknown as WebSocketLike`. `openWebSocket` without `WebSocketCtor` uses
|
|
221
|
+
the global `WebSocket` and does the cast itself.
|
|
193
222
|
|
|
194
223
|
### Failure modes
|
|
195
224
|
|
|
196
225
|
| Situation | Error |
|
|
197
226
|
| --- | --- |
|
|
198
|
-
| No `WebSocketCtor` and no global `WebSocket` | `webrun-streams-ws
|
|
227
|
+
| No `WebSocketCtor` and no global `WebSocket` | `webrun-streams-ws: no WebSocket constructor available. Pass \`WebSocketCtor\` (e.g. the \`ws\` package's WebSocket in Node).` |
|
|
199
228
|
| Socket errors before opening | `WebSocket error before open` |
|
|
200
229
|
| Socket closes before opening | `WebSocket closed before it opened` |
|
|
201
|
-
| `
|
|
202
|
-
|
|
|
203
|
-
|
|
204
|
-
`
|
|
205
|
-
the promise pending.
|
|
206
|
-
|
|
207
|
-
### Teardown is listener-only on the server
|
|
230
|
+
| `messageTargetOverWebSocket` on a socket that is not open | `messageTargetOverWebSocket: WebSocket is in readyState <n>, expected OPEN (1)` |
|
|
231
|
+
| `postMessage` with something other than bytes | `TypeError: webrun-streams-ws: a byte pipe carries Uint8Array, ArrayBuffer or a view, got <type>` |
|
|
232
|
+
| A message arrives as something other than bytes or text | `signal` aborts with `TypeError: webrun-streams-ws: a message arrived as <type>; set binaryType to "arraybuffer" or "nodebuffer"` |
|
|
233
|
+
| Socket closes | `signal` aborts with `webrun-streams-ws: the WebSocket closed (code <n>)`; calls in flight fail through `webrun-rpc`. |
|
|
208
234
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
socket closes. To drop live connections, close the sockets (for example
|
|
212
|
-
`wss.close()` plus `terminate()` on each client with `ws`).
|
|
235
|
+
`openWebSocket` has no timeout of its own; a socket that never opens or fails
|
|
236
|
+
leaves the promise pending.
|
|
213
237
|
|
|
214
238
|
### Tests and measurements
|
|
215
239
|
|
|
216
|
-
`pnpm test` runs the shared conformance suite (L0 to L6) against an
|
|
217
|
-
`ws` server
|
|
240
|
+
`pnpm test` runs the shared conformance suite (L0 to L6) against an
|
|
241
|
+
in-process `ws` server over the port stack (`overPipe` + `msgpackCodec`).
|
|
242
|
+
L6 asserts the port stack's bound in both directions: a consumer that stops
|
|
243
|
+
reading lets the producer get at most one 4 KiB chunk ahead (measured 0). `message-target.test.ts`
|
|
244
|
+
pins the pipe's contract: bytes only (anything else is a `TypeError`), text
|
|
245
|
+
frames as UTF-8 bytes, `signal` aborted by a dead peer, `whenDrained`
|
|
246
|
+
resolving at the low-water mark, sockets on "fragments" or "blob" delivering
|
|
247
|
+
bytes in order, a dead peer failing the calls in flight over the multiplexer,
|
|
248
|
+
and `serve`'s teardown failing a call in flight on each connection.
|
|
218
249
|
`pnpm run test:bench` runs a separate measurement that compares a direct
|
|
219
250
|
WebSocket round trip with one bridged through a `MessageChannel`. It reports
|
|
220
251
|
numbers and does not gate on a threshold, because a timing threshold on
|
|
@@ -222,10 +253,12 @@ shared CI hardware is unreliable, and it is excluded from `pnpm test`.
|
|
|
222
253
|
|
|
223
254
|
### Dependencies
|
|
224
255
|
|
|
225
|
-
- `@statewalker/webrun-streams` (
|
|
226
|
-
`
|
|
227
|
-
|
|
228
|
-
|
|
256
|
+
- `@statewalker/webrun-streams` at runtime, for `newMessagePipe`: the pipe module every transport adapter shares (listeners, delivery, life, the byte check, the frame ceiling, drain, close), so a pipe rule is fixed once for all of them (#151). The target is a `MessageTarget` by shape and carries its own `closeSignal` and `maxMessageSize`, so `overPipe(target, { codec, side })` needs nothing else.
|
|
257
|
+
`messageTargetOverWebSocket` takes `maxFrameBytes` and `maxMessageSize`
|
|
258
|
+
options, both unset by default.
|
|
259
|
+
- `ws`, `@statewalker/webrun-rpc`, `@statewalker/webrun-msgpack` and
|
|
260
|
+
`@statewalker/webrun-streams-conformance` are dev dependencies used only by
|
|
261
|
+
the tests; consumers supply their own `webrun-rpc` and codec.
|
|
229
262
|
|
|
230
263
|
## License
|
|
231
264
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
export {
|
|
2
|
-
export { type ConnectWsParams, connect } from "./connect.js";
|
|
3
|
-
export { type ServeWsParams, serve } from "./serve.js";
|
|
1
|
+
export { DRAIN_LOW_WATER, messageTargetOverWebSocket, type OpenWebSocketParams, openWebSocket, type WebSocketMessageTarget, } from "./message-target.js";
|
|
4
2
|
export { type WebSocketLike, WS_READY_STATE } from "./websocket-like.js";
|
|
5
3
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,0BAA0B,EAC1B,KAAK,mBAAmB,EACxB,aAAa,EACb,KAAK,sBAAsB,GAC5B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,KAAK,aAAa,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { DEFAULT_DRAIN_LOW_WATER, newMessagePipe } from "@statewalker/webrun-streams";
|
|
2
2
|
//#region src/websocket-like.ts
|
|
3
3
|
const WS_READY_STATE = {
|
|
4
4
|
CONNECTING: 0,
|
|
@@ -7,129 +7,69 @@ const WS_READY_STATE = {
|
|
|
7
7
|
CLOSED: 3
|
|
8
8
|
};
|
|
9
9
|
//#endregion
|
|
10
|
-
//#region src/
|
|
10
|
+
//#region src/message-target.ts
|
|
11
11
|
/**
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* `
|
|
12
|
+
* `whenDrained` resolves once `bufferedAmount` is at most this: the socket can
|
|
13
|
+
* take more. Waiting for zero would make a sender that waits before every
|
|
14
|
+
* frame (`overPipe`'s `frameSize`) pause a poll interval per frame.
|
|
15
|
+
*/
|
|
16
|
+
const DRAIN_LOW_WATER = DEFAULT_DRAIN_LOW_WATER;
|
|
17
|
+
/**
|
|
18
|
+
* One open WebSocket as a pipe of messages, for a multiplexer to run over:
|
|
15
19
|
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
20
|
+
* ```ts
|
|
21
|
+
* const { target, signal } = messageTargetOverWebSocket(ws);
|
|
22
|
+
* const { call } = await connect({
|
|
23
|
+
* mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal }),
|
|
24
|
+
* });
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* The socket must be `OPEN`. Binary messages arrive as `Uint8Array`, in order:
|
|
28
|
+
* a browser socket still on the default `binaryType` "blob" is switched to
|
|
29
|
+
* "arraybuffer", because reading a `Blob` is asynchronous and would let a later
|
|
30
|
+
* message overtake it. A text message arrives as its UTF-8 bytes; anything
|
|
31
|
+
* else ends the pipe with a `TypeError`. Messages reaching no listener are
|
|
32
|
+
* dropped, as on a `MessagePort`. Built on `newMessagePipe`
|
|
33
|
+
* (`@statewalker/webrun-streams`), which owns the pipe's rules.
|
|
18
34
|
*/
|
|
19
|
-
function
|
|
20
|
-
if (ws.readyState !== WS_READY_STATE.OPEN) throw new Error(`
|
|
21
|
-
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
const queue = [];
|
|
27
|
-
let pending = null;
|
|
28
|
-
const onMessage = (event) => {
|
|
29
|
-
if (isClosed) return;
|
|
30
|
-
const data = event.data;
|
|
31
|
-
let normalised;
|
|
32
|
-
if (data instanceof Uint8Array) normalised = data;
|
|
33
|
-
else if (data instanceof ArrayBuffer) normalised = new Uint8Array(data);
|
|
34
|
-
else if (ArrayBuffer.isView(data)) {
|
|
35
|
-
const view = data;
|
|
36
|
-
normalised = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
|
|
37
|
-
} else if (typeof Blob !== "undefined" && data instanceof Blob) {
|
|
38
|
-
data.arrayBuffer().then((buf) => deliver(new Uint8Array(buf)));
|
|
39
|
-
return;
|
|
40
|
-
} else if (typeof data === "string") {
|
|
41
|
-
const n = normalizeToUint8Array(data);
|
|
42
|
-
if (n instanceof Uint8Array) normalised = n;
|
|
43
|
-
else {
|
|
44
|
-
n.then(deliver);
|
|
45
|
-
return;
|
|
46
|
-
}
|
|
47
|
-
} else return;
|
|
48
|
-
deliver(normalised);
|
|
49
|
-
};
|
|
50
|
-
const deliver = (bytes) => {
|
|
51
|
-
if (isClosed) return;
|
|
52
|
-
if (pending) {
|
|
53
|
-
const r = pending;
|
|
54
|
-
pending = null;
|
|
55
|
-
r({
|
|
56
|
-
value: bytes,
|
|
57
|
-
done: false
|
|
58
|
-
});
|
|
59
|
-
} else queue.push(bytes);
|
|
60
|
-
};
|
|
61
|
-
const onClose = () => {
|
|
62
|
-
if (isClosed) return;
|
|
63
|
-
isClosed = true;
|
|
64
|
-
ws.removeEventListener("message", onMessage);
|
|
65
|
-
ws.removeEventListener("close", onClose);
|
|
66
|
-
if (pending) {
|
|
67
|
-
const r = pending;
|
|
68
|
-
pending = null;
|
|
69
|
-
r({
|
|
70
|
-
value: void 0,
|
|
71
|
-
done: true
|
|
72
|
-
});
|
|
73
|
-
}
|
|
74
|
-
closedResolve();
|
|
35
|
+
function messageTargetOverWebSocket(ws, options = {}) {
|
|
36
|
+
if (ws.readyState !== WS_READY_STATE.OPEN) throw new Error(`messageTargetOverWebSocket: WebSocket is in readyState ${ws.readyState}, expected OPEN (1)`);
|
|
37
|
+
if (ws.binaryType !== void 0 && ws.binaryType !== "arraybuffer" && ws.binaryType !== "nodebuffer") ws.binaryType = "arraybuffer";
|
|
38
|
+
const onMessage = (event) => control.deliver(event.data);
|
|
39
|
+
const onClose = (event) => {
|
|
40
|
+
const code = event?.code;
|
|
41
|
+
control.end(/* @__PURE__ */ new Error(`webrun-streams-ws: the WebSocket closed${code ? ` (code ${code})` : ""}`));
|
|
75
42
|
};
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
ws.
|
|
83
|
-
|
|
84
|
-
recv: { [Symbol.asyncIterator]() {
|
|
85
|
-
return { next() {
|
|
86
|
-
if (queue.length > 0) return Promise.resolve({
|
|
87
|
-
value: queue.shift(),
|
|
88
|
-
done: false
|
|
89
|
-
});
|
|
90
|
-
if (isClosed) return Promise.resolve({
|
|
91
|
-
value: void 0,
|
|
92
|
-
done: true
|
|
93
|
-
});
|
|
94
|
-
return new Promise((resolve) => {
|
|
95
|
-
pending = resolve;
|
|
96
|
-
});
|
|
97
|
-
} };
|
|
98
|
-
} },
|
|
99
|
-
closed,
|
|
100
|
-
close() {
|
|
101
|
-
if (isClosed) return;
|
|
102
|
-
try {
|
|
43
|
+
const control = newMessagePipe({
|
|
44
|
+
send: (bytes) => ws.send(bytes),
|
|
45
|
+
canSend: () => ws.readyState === WS_READY_STATE.OPEN,
|
|
46
|
+
bufferedAmount: () => ws.bufferedAmount ?? 0,
|
|
47
|
+
close: (local) => {
|
|
48
|
+
ws.removeEventListener("message", onMessage);
|
|
49
|
+
ws.removeEventListener("close", onClose);
|
|
50
|
+
if (local) try {
|
|
103
51
|
ws.close();
|
|
104
52
|
} catch {}
|
|
105
|
-
onClose();
|
|
106
53
|
}
|
|
107
|
-
}
|
|
54
|
+
}, {
|
|
55
|
+
name: "webrun-streams-ws",
|
|
56
|
+
textAsBytes: true,
|
|
57
|
+
maxFrameBytes: options.maxFrameBytes,
|
|
58
|
+
maxMessageSize: options.maxMessageSize
|
|
59
|
+
});
|
|
60
|
+
ws.addEventListener("message", onMessage);
|
|
61
|
+
ws.addEventListener("close", onClose);
|
|
62
|
+
return control.pipe;
|
|
108
63
|
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Open a WebSocket to `params.url`, wrap it as a `ByteChannel`, and run it
|
|
113
|
-
* through `emulateMux`. Returns `{ call, close }` where `call` is the
|
|
114
|
-
* caller-side `Duplex`.
|
|
115
|
-
*/
|
|
116
|
-
const connect = async (params) => {
|
|
64
|
+
/** Opens a WebSocket and resolves once it is `OPEN`; rejects if it fails or closes first. */
|
|
65
|
+
async function openWebSocket(params) {
|
|
117
66
|
const Ctor = params.WebSocketCtor ?? globalThis.WebSocket;
|
|
118
|
-
if (!Ctor) throw new Error("webrun-streams-ws
|
|
67
|
+
if (!Ctor) throw new Error("webrun-streams-ws: no WebSocket constructor available. Pass `WebSocketCtor` (e.g. the `ws` package's WebSocket in Node).");
|
|
119
68
|
const ws = new Ctor(params.url, params.protocols);
|
|
120
69
|
await waitForOpen(ws);
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
side: "initiator"
|
|
125
|
-
});
|
|
126
|
-
return {
|
|
127
|
-
call: mux.call,
|
|
128
|
-
async close() {
|
|
129
|
-
await mux.close();
|
|
130
|
-
}
|
|
131
|
-
};
|
|
132
|
-
};
|
|
70
|
+
return ws;
|
|
71
|
+
}
|
|
72
|
+
/** Resolves once `ws` is `OPEN`; rejects if it fails or closes first. */
|
|
133
73
|
function waitForOpen(ws) {
|
|
134
74
|
if (ws.readyState === WS_READY_STATE.OPEN) return Promise.resolve();
|
|
135
75
|
return new Promise((resolve, reject) => {
|
|
@@ -156,32 +96,4 @@ function waitForOpen(ws) {
|
|
|
156
96
|
});
|
|
157
97
|
}
|
|
158
98
|
//#endregion
|
|
159
|
-
|
|
160
|
-
/**
|
|
161
|
-
* Register a `Duplex` handler against an inbound-WebSocket source. The
|
|
162
|
-
* `onConnection` callback is invoked once per accepted connection; the
|
|
163
|
-
* adapter wraps each in `emulateMux` and binds the handler.
|
|
164
|
-
*
|
|
165
|
-
* Returns an idempotent teardown that unregisters the connection listener.
|
|
166
|
-
* Open `emulateMux` instances continue running until their underlying
|
|
167
|
-
* WebSocket closes.
|
|
168
|
-
*/
|
|
169
|
-
async function serve(params, handler) {
|
|
170
|
-
const off = params.onConnection((ws) => {
|
|
171
|
-
const channel = byteChannelFromWebSocket(ws);
|
|
172
|
-
const mux = emulateMux(channel, {
|
|
173
|
-
...params.mux,
|
|
174
|
-
side: "responder"
|
|
175
|
-
});
|
|
176
|
-
mux.serve(handler);
|
|
177
|
-
channel.closed.then(() => mux.close());
|
|
178
|
-
});
|
|
179
|
-
let torn = false;
|
|
180
|
-
return async () => {
|
|
181
|
-
if (torn) return;
|
|
182
|
-
torn = true;
|
|
183
|
-
off();
|
|
184
|
-
};
|
|
185
|
-
}
|
|
186
|
-
//#endregion
|
|
187
|
-
export { WS_READY_STATE, byteChannelFromWebSocket, connect, serve };
|
|
99
|
+
export { DRAIN_LOW_WATER, WS_READY_STATE, messageTargetOverWebSocket, openWebSocket };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { type MessagePipe, type MessagePipeTarget } from "@statewalker/webrun-streams";
|
|
2
|
+
import { type WebSocketLike } from "./websocket-like.js";
|
|
3
|
+
/** What `messageTargetOverWebSocket` gives: a pipe of bytes, and its life. */
|
|
4
|
+
export interface WebSocketMessageTarget extends MessagePipe {
|
|
5
|
+
/**
|
|
6
|
+
* A `MessageTarget` (as `@statewalker/webrun-rpc` defines it) whose messages
|
|
7
|
+
* are `Uint8Array`s, one WebSocket message each. `bufferedAmount` is the
|
|
8
|
+
* socket's; `whenDrained` resolves once it is at most
|
|
9
|
+
* {@link DRAIN_LOW_WATER}, or the socket has closed.
|
|
10
|
+
*/
|
|
11
|
+
target: MessagePipeTarget;
|
|
12
|
+
/**
|
|
13
|
+
* Aborts when the socket closes, with an `Error` saying how; the same as
|
|
14
|
+
* `target.closeSignal`. Pass it as `multiplexPort`'s / `overPipe`'s
|
|
15
|
+
* `signal`, so a dead peer closes the multiplexer and every port on it at
|
|
16
|
+
* once instead of leaving them open.
|
|
17
|
+
*/
|
|
18
|
+
signal: AbortSignal;
|
|
19
|
+
}
|
|
20
|
+
export interface MessageTargetOverWebSocketOptions {
|
|
21
|
+
/**
|
|
22
|
+
* The largest message posted; past it the pipe ends with a `RangeError`.
|
|
23
|
+
* Default: none, a WebSocket carries messages of any size.
|
|
24
|
+
*/
|
|
25
|
+
maxFrameBytes?: number;
|
|
26
|
+
/** The payload ceiling to report, for `overPipe`'s `maxMessageSize`. Default: none. */
|
|
27
|
+
maxMessageSize?: number;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* `whenDrained` resolves once `bufferedAmount` is at most this: the socket can
|
|
31
|
+
* take more. Waiting for zero would make a sender that waits before every
|
|
32
|
+
* frame (`overPipe`'s `frameSize`) pause a poll interval per frame.
|
|
33
|
+
*/
|
|
34
|
+
export declare const DRAIN_LOW_WATER: number;
|
|
35
|
+
/**
|
|
36
|
+
* One open WebSocket as a pipe of messages, for a multiplexer to run over:
|
|
37
|
+
*
|
|
38
|
+
* ```ts
|
|
39
|
+
* const { target, signal } = messageTargetOverWebSocket(ws);
|
|
40
|
+
* const { call } = await connect({
|
|
41
|
+
* mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal }),
|
|
42
|
+
* });
|
|
43
|
+
* ```
|
|
44
|
+
*
|
|
45
|
+
* The socket must be `OPEN`. Binary messages arrive as `Uint8Array`, in order:
|
|
46
|
+
* a browser socket still on the default `binaryType` "blob" is switched to
|
|
47
|
+
* "arraybuffer", because reading a `Blob` is asynchronous and would let a later
|
|
48
|
+
* message overtake it. A text message arrives as its UTF-8 bytes; anything
|
|
49
|
+
* else ends the pipe with a `TypeError`. Messages reaching no listener are
|
|
50
|
+
* dropped, as on a `MessagePort`. Built on `newMessagePipe`
|
|
51
|
+
* (`@statewalker/webrun-streams`), which owns the pipe's rules.
|
|
52
|
+
*/
|
|
53
|
+
export declare function messageTargetOverWebSocket(ws: WebSocketLike, options?: MessageTargetOverWebSocketOptions): WebSocketMessageTarget;
|
|
54
|
+
export interface OpenWebSocketParams {
|
|
55
|
+
/** WebSocket URL (`ws://` or `wss://`). */
|
|
56
|
+
url: string;
|
|
57
|
+
/** Optional subprotocol(s) passed to the WebSocket constructor. */
|
|
58
|
+
protocols?: string | string[];
|
|
59
|
+
/**
|
|
60
|
+
* WebSocket constructor. Defaults to the global `WebSocket` when present;
|
|
61
|
+
* pass the `ws` package's `WebSocket` in Node versions without one.
|
|
62
|
+
*/
|
|
63
|
+
WebSocketCtor?: new (url: string, protocols?: string | string[]) => WebSocketLike;
|
|
64
|
+
}
|
|
65
|
+
/** Opens a WebSocket and resolves once it is `OPEN`; rejects if it fails or closes first. */
|
|
66
|
+
export declare function openWebSocket(params: OpenWebSocketParams): Promise<WebSocketLike>;
|
|
67
|
+
/** Resolves once `ws` is `OPEN`; rejects if it fails or closes first. */
|
|
68
|
+
export declare function waitForOpen(ws: WebSocketLike): Promise<void>;
|
|
69
|
+
//# sourceMappingURL=message-target.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"message-target.d.ts","sourceRoot":"","sources":["../src/message-target.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,WAAW,EAChB,KAAK,iBAAiB,EAEvB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,KAAK,aAAa,EAAkB,MAAM,qBAAqB,CAAC;AAEzE,8EAA8E;AAC9E,MAAM,WAAW,sBAAuB,SAAQ,WAAW;IACzD;;;;;OAKG;IACH,MAAM,EAAE,iBAAiB,CAAC;IAC1B;;;;;OAKG;IACH,MAAM,EAAE,WAAW,CAAC;CACrB;AAED,MAAM,WAAW,iCAAiC;IAChD;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,uFAAuF;IACvF,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;;GAIG;AACH,eAAO,MAAM,eAAe,QAA0B,CAAC;AAEvD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,0BAA0B,CACxC,EAAE,EAAE,aAAa,EACjB,OAAO,GAAE,iCAAsC,GAC9C,sBAAsB,CAiDxB;AAED,MAAM,WAAW,mBAAmB;IAClC,2CAA2C;IAC3C,GAAG,EAAE,MAAM,CAAC;IACZ,mEAAmE;IACnE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC9B;;;OAGG;IACH,aAAa,CAAC,EAAE,KACd,GAAG,EAAE,MAAM,EACX,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,KAC1B,aAAa,CAAC;CACpB;AAED,6FAA6F;AAC7F,wBAAsB,aAAa,CAAC,MAAM,EAAE,mBAAmB,GAAG,OAAO,CAAC,aAAa,CAAC,CAUvF;AAED,yEAAyE;AACzE,wBAAgB,WAAW,CAAC,EAAE,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAwB5D"}
|
package/dist/websocket-like.d.ts
CHANGED
|
@@ -5,6 +5,10 @@
|
|
|
5
5
|
*/
|
|
6
6
|
export interface WebSocketLike {
|
|
7
7
|
readonly readyState: number;
|
|
8
|
+
/** Bytes queued by `send` and not yet written out. */
|
|
9
|
+
readonly bufferedAmount?: number;
|
|
10
|
+
/** How binary messages arrive: "blob" or "arraybuffer" in browsers, "nodebuffer" in `ws`. */
|
|
11
|
+
binaryType?: string;
|
|
8
12
|
send(data: string | ArrayBuffer | Blob | Uint8Array): void;
|
|
9
13
|
close(): void;
|
|
10
14
|
addEventListener(type: "message", listener: (event: MessageEvent) => void): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"websocket-like.d.ts","sourceRoot":"","sources":["../src/websocket-like.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,IAAI,GAAG,UAAU,GAAG,IAAI,CAAC;IAC3D,KAAK,IAAI,IAAI,CAAC;IACd,gBAAgB,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,GAAG,IAAI,CAAC;IACjF,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;IAC3D,gBAAgB,CAAC,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;IAC5D,gBAAgB,CAAC,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;IAC5D,mBAAmB,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,GAAG,IAAI,CAAC;IACpF,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;IAC9D,mBAAmB,CAAC,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;IAC/D,mBAAmB,CAAC,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;CAChE;AAED,eAAO,MAAM,cAAc;aACzB,UAAU,EAAE,CAAC;aACb,IAAI,EAAE,CAAC;aACP,OAAO,EAAE,CAAC;aACV,MAAM,EAAE,CAAC;CACD,CAAC"}
|
|
1
|
+
{"version":3,"file":"websocket-like.d.ts","sourceRoot":"","sources":["../src/websocket-like.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,sDAAsD;IACtD,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACjC,6FAA6F;IAC7F,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,IAAI,GAAG,UAAU,GAAG,IAAI,CAAC;IAC3D,KAAK,IAAI,IAAI,CAAC;IACd,gBAAgB,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,GAAG,IAAI,CAAC;IACjF,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;IAC3D,gBAAgB,CAAC,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;IAC5D,gBAAgB,CAAC,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;IAC5D,mBAAmB,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,GAAG,IAAI,CAAC;IACpF,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;IAC9D,mBAAmB,CAAC,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;IAC/D,mBAAmB,CAAC,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;CAChE;AAED,eAAO,MAAM,cAAc;aACzB,UAAU,EAAE,CAAC;aACb,IAAI,EAAE,CAAC;aACP,OAAO,EAAE,CAAC;aACV,MAAM,EAAE,CAAC;CACD,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@statewalker/webrun-streams-ws",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "WebSocket-backed Connect/Serve adapter in the webrun-streams-* family",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"src"
|
|
31
31
|
],
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@statewalker/webrun-streams": "^0.
|
|
33
|
+
"@statewalker/webrun-streams": "^0.5.0"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
36
|
"@biomejs/biome": "^2.5.15",
|
|
@@ -39,9 +39,11 @@
|
|
|
39
39
|
"rimraf": "^6.1.3",
|
|
40
40
|
"rolldown": "^1.2.12",
|
|
41
41
|
"typescript": "^7.0.2",
|
|
42
|
-
"vitest": "^5.0.
|
|
42
|
+
"vitest": "^5.0.5",
|
|
43
43
|
"ws": "^8.22.0",
|
|
44
|
-
"@statewalker/webrun-streams-conformance": "^0.
|
|
44
|
+
"@statewalker/webrun-streams-conformance": "^0.6.0",
|
|
45
|
+
"@statewalker/webrun-rpc": "^0.13.0",
|
|
46
|
+
"@statewalker/webrun-msgpack": "^0.12.0"
|
|
45
47
|
},
|
|
46
48
|
"sideEffects": false,
|
|
47
49
|
"publishConfig": {
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
export {
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
export {
|
|
2
|
+
DRAIN_LOW_WATER,
|
|
3
|
+
messageTargetOverWebSocket,
|
|
4
|
+
type OpenWebSocketParams,
|
|
5
|
+
openWebSocket,
|
|
6
|
+
type WebSocketMessageTarget,
|
|
7
|
+
} from "./message-target.js";
|
|
4
8
|
export { type WebSocketLike, WS_READY_STATE } from "./websocket-like.js";
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_DRAIN_LOW_WATER,
|
|
3
|
+
type MessagePipe,
|
|
4
|
+
type MessagePipeTarget,
|
|
5
|
+
newMessagePipe,
|
|
6
|
+
} from "@statewalker/webrun-streams";
|
|
7
|
+
import { type WebSocketLike, WS_READY_STATE } from "./websocket-like.js";
|
|
8
|
+
|
|
9
|
+
/** What `messageTargetOverWebSocket` gives: a pipe of bytes, and its life. */
|
|
10
|
+
export interface WebSocketMessageTarget extends MessagePipe {
|
|
11
|
+
/**
|
|
12
|
+
* A `MessageTarget` (as `@statewalker/webrun-rpc` defines it) whose messages
|
|
13
|
+
* are `Uint8Array`s, one WebSocket message each. `bufferedAmount` is the
|
|
14
|
+
* socket's; `whenDrained` resolves once it is at most
|
|
15
|
+
* {@link DRAIN_LOW_WATER}, or the socket has closed.
|
|
16
|
+
*/
|
|
17
|
+
target: MessagePipeTarget;
|
|
18
|
+
/**
|
|
19
|
+
* Aborts when the socket closes, with an `Error` saying how; the same as
|
|
20
|
+
* `target.closeSignal`. Pass it as `multiplexPort`'s / `overPipe`'s
|
|
21
|
+
* `signal`, so a dead peer closes the multiplexer and every port on it at
|
|
22
|
+
* once instead of leaving them open.
|
|
23
|
+
*/
|
|
24
|
+
signal: AbortSignal;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface MessageTargetOverWebSocketOptions {
|
|
28
|
+
/**
|
|
29
|
+
* The largest message posted; past it the pipe ends with a `RangeError`.
|
|
30
|
+
* Default: none, a WebSocket carries messages of any size.
|
|
31
|
+
*/
|
|
32
|
+
maxFrameBytes?: number;
|
|
33
|
+
/** The payload ceiling to report, for `overPipe`'s `maxMessageSize`. Default: none. */
|
|
34
|
+
maxMessageSize?: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* `whenDrained` resolves once `bufferedAmount` is at most this: the socket can
|
|
39
|
+
* take more. Waiting for zero would make a sender that waits before every
|
|
40
|
+
* frame (`overPipe`'s `frameSize`) pause a poll interval per frame.
|
|
41
|
+
*/
|
|
42
|
+
export const DRAIN_LOW_WATER = DEFAULT_DRAIN_LOW_WATER;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* One open WebSocket as a pipe of messages, for a multiplexer to run over:
|
|
46
|
+
*
|
|
47
|
+
* ```ts
|
|
48
|
+
* const { target, signal } = messageTargetOverWebSocket(ws);
|
|
49
|
+
* const { call } = await connect({
|
|
50
|
+
* mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal }),
|
|
51
|
+
* });
|
|
52
|
+
* ```
|
|
53
|
+
*
|
|
54
|
+
* The socket must be `OPEN`. Binary messages arrive as `Uint8Array`, in order:
|
|
55
|
+
* a browser socket still on the default `binaryType` "blob" is switched to
|
|
56
|
+
* "arraybuffer", because reading a `Blob` is asynchronous and would let a later
|
|
57
|
+
* message overtake it. A text message arrives as its UTF-8 bytes; anything
|
|
58
|
+
* else ends the pipe with a `TypeError`. Messages reaching no listener are
|
|
59
|
+
* dropped, as on a `MessagePort`. Built on `newMessagePipe`
|
|
60
|
+
* (`@statewalker/webrun-streams`), which owns the pipe's rules.
|
|
61
|
+
*/
|
|
62
|
+
export function messageTargetOverWebSocket(
|
|
63
|
+
ws: WebSocketLike,
|
|
64
|
+
options: MessageTargetOverWebSocketOptions = {},
|
|
65
|
+
): WebSocketMessageTarget {
|
|
66
|
+
if (ws.readyState !== WS_READY_STATE.OPEN) {
|
|
67
|
+
throw new Error(
|
|
68
|
+
`messageTargetOverWebSocket: WebSocket is in readyState ${ws.readyState}, expected OPEN (1)`,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
// "arraybuffer" (browsers) and "nodebuffer" (`ws`) arrive as bytes at once;
|
|
72
|
+
// anything else — "blob" (read asynchronously, so a later message could
|
|
73
|
+
// overtake it), `ws`'s "fragments" (an array of Buffers) — is switched.
|
|
74
|
+
if (
|
|
75
|
+
ws.binaryType !== undefined &&
|
|
76
|
+
ws.binaryType !== "arraybuffer" &&
|
|
77
|
+
ws.binaryType !== "nodebuffer"
|
|
78
|
+
)
|
|
79
|
+
ws.binaryType = "arraybuffer";
|
|
80
|
+
|
|
81
|
+
const onMessage = (event: MessageEvent): void => control.deliver(event.data);
|
|
82
|
+
const onClose = (event?: unknown): void => {
|
|
83
|
+
const code = (event as { code?: number } | undefined)?.code;
|
|
84
|
+
control.end(
|
|
85
|
+
new Error(`webrun-streams-ws: the WebSocket closed${code ? ` (code ${code})` : ""}`),
|
|
86
|
+
);
|
|
87
|
+
};
|
|
88
|
+
const control = newMessagePipe(
|
|
89
|
+
{
|
|
90
|
+
send: (bytes) => ws.send(bytes),
|
|
91
|
+
canSend: () => ws.readyState === WS_READY_STATE.OPEN,
|
|
92
|
+
bufferedAmount: () => ws.bufferedAmount ?? 0,
|
|
93
|
+
close: (local) => {
|
|
94
|
+
ws.removeEventListener("message", onMessage);
|
|
95
|
+
ws.removeEventListener("close", onClose);
|
|
96
|
+
if (local) {
|
|
97
|
+
try {
|
|
98
|
+
ws.close();
|
|
99
|
+
} catch {}
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
name: "webrun-streams-ws",
|
|
105
|
+
textAsBytes: true,
|
|
106
|
+
maxFrameBytes: options.maxFrameBytes,
|
|
107
|
+
maxMessageSize: options.maxMessageSize,
|
|
108
|
+
},
|
|
109
|
+
);
|
|
110
|
+
ws.addEventListener("message", onMessage);
|
|
111
|
+
// A failing socket fires `error` and then always `close`: `close` alone ends it.
|
|
112
|
+
ws.addEventListener("close", onClose);
|
|
113
|
+
return control.pipe as WebSocketMessageTarget;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export interface OpenWebSocketParams {
|
|
117
|
+
/** WebSocket URL (`ws://` or `wss://`). */
|
|
118
|
+
url: string;
|
|
119
|
+
/** Optional subprotocol(s) passed to the WebSocket constructor. */
|
|
120
|
+
protocols?: string | string[];
|
|
121
|
+
/**
|
|
122
|
+
* WebSocket constructor. Defaults to the global `WebSocket` when present;
|
|
123
|
+
* pass the `ws` package's `WebSocket` in Node versions without one.
|
|
124
|
+
*/
|
|
125
|
+
WebSocketCtor?: new (
|
|
126
|
+
url: string,
|
|
127
|
+
protocols?: string | string[],
|
|
128
|
+
) => WebSocketLike;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Opens a WebSocket and resolves once it is `OPEN`; rejects if it fails or closes first. */
|
|
132
|
+
export async function openWebSocket(params: OpenWebSocketParams): Promise<WebSocketLike> {
|
|
133
|
+
const Ctor = params.WebSocketCtor ?? (globalThis as { WebSocket?: typeof WebSocket }).WebSocket;
|
|
134
|
+
if (!Ctor) {
|
|
135
|
+
throw new Error(
|
|
136
|
+
"webrun-streams-ws: no WebSocket constructor available. Pass `WebSocketCtor` (e.g. the `ws` package's WebSocket in Node).",
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
const ws = new Ctor(params.url, params.protocols) as WebSocketLike;
|
|
140
|
+
await waitForOpen(ws);
|
|
141
|
+
return ws;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Resolves once `ws` is `OPEN`; rejects if it fails or closes first. */
|
|
145
|
+
export function waitForOpen(ws: WebSocketLike): Promise<void> {
|
|
146
|
+
if (ws.readyState === WS_READY_STATE.OPEN) return Promise.resolve();
|
|
147
|
+
return new Promise<void>((resolve, reject) => {
|
|
148
|
+
const cleanup = (): void => {
|
|
149
|
+
ws.removeEventListener("open", onOpen);
|
|
150
|
+
ws.removeEventListener("error", onError);
|
|
151
|
+
ws.removeEventListener("close", onCloseEarly);
|
|
152
|
+
};
|
|
153
|
+
const onOpen = (): void => {
|
|
154
|
+
cleanup();
|
|
155
|
+
resolve();
|
|
156
|
+
};
|
|
157
|
+
const onError = (): void => {
|
|
158
|
+
cleanup();
|
|
159
|
+
reject(new Error("WebSocket error before open"));
|
|
160
|
+
};
|
|
161
|
+
const onCloseEarly = (): void => {
|
|
162
|
+
cleanup();
|
|
163
|
+
reject(new Error("WebSocket closed before it opened"));
|
|
164
|
+
};
|
|
165
|
+
ws.addEventListener("open", onOpen);
|
|
166
|
+
ws.addEventListener("error", onError);
|
|
167
|
+
ws.addEventListener("close", onCloseEarly);
|
|
168
|
+
});
|
|
169
|
+
}
|
package/src/websocket-like.ts
CHANGED
|
@@ -5,6 +5,10 @@
|
|
|
5
5
|
*/
|
|
6
6
|
export interface WebSocketLike {
|
|
7
7
|
readonly readyState: number;
|
|
8
|
+
/** Bytes queued by `send` and not yet written out. */
|
|
9
|
+
readonly bufferedAmount?: number;
|
|
10
|
+
/** How binary messages arrive: "blob" or "arraybuffer" in browsers, "nodebuffer" in `ws`. */
|
|
11
|
+
binaryType?: string;
|
|
8
12
|
send(data: string | ArrayBuffer | Blob | Uint8Array): void;
|
|
9
13
|
close(): void;
|
|
10
14
|
addEventListener(type: "message", listener: (event: MessageEvent) => void): void;
|
package/dist/byte-channel.d.ts
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { type ByteChannel } from "@statewalker/webrun-streams";
|
|
2
|
-
import { type WebSocketLike } from "./websocket-like.js";
|
|
3
|
-
/**
|
|
4
|
-
* Wrap an open `WebSocket` (or any `WebSocketLike` — Node `ws` works) into a
|
|
5
|
-
* `ByteChannel` consumable by `emulateMux`. The socket MUST already be in the
|
|
6
|
-
* `OPEN` state; the adapter does not perform handshakes.
|
|
7
|
-
*
|
|
8
|
-
* Inbound binary frames are normalised to `Uint8Array`. Text frames are also
|
|
9
|
-
* accepted (rare on this transport) and surfaced as their UTF-8 bytes.
|
|
10
|
-
*/
|
|
11
|
-
export declare function byteChannelFromWebSocket(ws: WebSocketLike): ByteChannel;
|
|
12
|
-
//# sourceMappingURL=byte-channel.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"byte-channel.d.ts","sourceRoot":"","sources":["../src/byte-channel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,WAAW,EAAyB,MAAM,6BAA6B,CAAC;AACtF,OAAO,EAAE,KAAK,aAAa,EAAkB,MAAM,qBAAqB,CAAC;AAEzE;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,EAAE,EAAE,aAAa,GAAG,WAAW,CA8GvE"}
|
package/dist/connect.d.ts
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import { type Connect, type EmulateMuxOptions } from "@statewalker/webrun-streams";
|
|
2
|
-
import { type WebSocketLike } from "./websocket-like.js";
|
|
3
|
-
export interface ConnectWsParams {
|
|
4
|
-
/** WebSocket URL (`ws://` or `wss://`). */
|
|
5
|
-
url: string;
|
|
6
|
-
/** Optional subprotocol(s) passed to the WebSocket constructor. */
|
|
7
|
-
protocols?: string | string[];
|
|
8
|
-
/**
|
|
9
|
-
* WebSocket constructor. Defaults to the global `WebSocket` when present
|
|
10
|
-
* (browser); pass Node's `ws` package's `WebSocket` in Node.
|
|
11
|
-
*/
|
|
12
|
-
WebSocketCtor?: new (url: string, protocols?: string | string[]) => WebSocketLike;
|
|
13
|
-
/**
|
|
14
|
-
* Flow-control tuning forwarded to `emulateMux` — `mtu` and
|
|
15
|
-
* `maxStreamBuffer`, which is the credit this side advertises. `side` here
|
|
16
|
-
* wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
|
|
17
|
-
* suite's L6 uses this to run at a window small enough that a sender
|
|
18
|
-
* genuinely stalls.
|
|
19
|
-
*/
|
|
20
|
-
mux?: EmulateMuxOptions;
|
|
21
|
-
}
|
|
22
|
-
/**
|
|
23
|
-
* Open a WebSocket to `params.url`, wrap it as a `ByteChannel`, and run it
|
|
24
|
-
* through `emulateMux`. Returns `{ call, close }` where `call` is the
|
|
25
|
-
* caller-side `Duplex`.
|
|
26
|
-
*/
|
|
27
|
-
export declare const connect: Connect<ConnectWsParams>;
|
|
28
|
-
//# sourceMappingURL=connect.d.ts.map
|
package/dist/connect.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,iBAAiB,EAAc,MAAM,6BAA6B,CAAC;AAE/F,OAAO,EAAE,KAAK,aAAa,EAAkB,MAAM,qBAAqB,CAAC;AAEzE,MAAM,WAAW,eAAe;IAC9B,2CAA2C;IAC3C,GAAG,EAAE,MAAM,CAAC;IACZ,mEAAmE;IACnE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC9B;;;OAGG;IACH,aAAa,CAAC,EAAE,KACd,GAAG,EAAE,MAAM,EACX,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,KAC1B,aAAa,CAAC;IACnB;;;;;;OAMG;IACH,GAAG,CAAC,EAAE,iBAAiB,CAAC;CACzB;AAED;;;;GAIG;AACH,eAAO,MAAM,OAAO,EAAE,OAAO,CAAC,eAAe,CAiB5C,CAAC"}
|
package/dist/serve.d.ts
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { type Duplex, type EmulateMuxOptions } from "@statewalker/webrun-streams";
|
|
2
|
-
import type { WebSocketLike } from "./websocket-like.js";
|
|
3
|
-
export interface ServeWsParams {
|
|
4
|
-
/**
|
|
5
|
-
* Source of inbound WebSocket connections. Either a `wss` instance with a
|
|
6
|
-
* `connection` event, or a manual handler the caller wires to its own
|
|
7
|
-
* server.
|
|
8
|
-
*/
|
|
9
|
-
onConnection: (cb: (ws: WebSocketLike) => void) => () => void;
|
|
10
|
-
/**
|
|
11
|
-
* Flow-control tuning forwarded to `emulateMux` — `mtu` and
|
|
12
|
-
* `maxStreamBuffer`, which is the credit this side advertises. `side` here
|
|
13
|
-
* wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
|
|
14
|
-
* suite's L6 uses this to run at a window small enough that a sender
|
|
15
|
-
* genuinely stalls.
|
|
16
|
-
*/
|
|
17
|
-
mux?: EmulateMuxOptions;
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* Register a `Duplex` handler against an inbound-WebSocket source. The
|
|
21
|
-
* `onConnection` callback is invoked once per accepted connection; the
|
|
22
|
-
* adapter wraps each in `emulateMux` and binds the handler.
|
|
23
|
-
*
|
|
24
|
-
* Returns an idempotent teardown that unregisters the connection listener.
|
|
25
|
-
* Open `emulateMux` instances continue running until their underlying
|
|
26
|
-
* WebSocket closes.
|
|
27
|
-
*/
|
|
28
|
-
export declare function serve(params: ServeWsParams, handler: Duplex): Promise<() => Promise<void>>;
|
|
29
|
-
//# sourceMappingURL=serve.d.ts.map
|
package/dist/serve.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../src/serve.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,KAAK,iBAAiB,EAAc,MAAM,6BAA6B,CAAC;AAE9F,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD,MAAM,WAAW,aAAa;IAC5B;;;;OAIG;IACH,YAAY,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,aAAa,KAAK,IAAI,KAAK,MAAM,IAAI,CAAC;IAC9D;;;;;;OAMG;IACH,GAAG,CAAC,EAAE,iBAAiB,CAAC;CACzB;AAED;;;;;;;;GAQG;AACH,wBAAsB,KAAK,CAAC,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,CAahG"}
|
package/src/byte-channel.ts
DELETED
|
@@ -1,122 +0,0 @@
|
|
|
1
|
-
import { type ByteChannel, normalizeToUint8Array } from "@statewalker/webrun-streams";
|
|
2
|
-
import { type WebSocketLike, WS_READY_STATE } from "./websocket-like.js";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Wrap an open `WebSocket` (or any `WebSocketLike` — Node `ws` works) into a
|
|
6
|
-
* `ByteChannel` consumable by `emulateMux`. The socket MUST already be in the
|
|
7
|
-
* `OPEN` state; the adapter does not perform handshakes.
|
|
8
|
-
*
|
|
9
|
-
* Inbound binary frames are normalised to `Uint8Array`. Text frames are also
|
|
10
|
-
* accepted (rare on this transport) and surfaced as their UTF-8 bytes.
|
|
11
|
-
*/
|
|
12
|
-
export function byteChannelFromWebSocket(ws: WebSocketLike): ByteChannel {
|
|
13
|
-
if (ws.readyState !== WS_READY_STATE.OPEN) {
|
|
14
|
-
throw new Error(
|
|
15
|
-
`byteChannelFromWebSocket: WebSocket is in readyState ${ws.readyState}, expected OPEN (1)`,
|
|
16
|
-
);
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
let closedResolve!: () => void;
|
|
20
|
-
const closed = new Promise<void>((r) => {
|
|
21
|
-
closedResolve = r;
|
|
22
|
-
});
|
|
23
|
-
let isClosed = false;
|
|
24
|
-
|
|
25
|
-
// Inbound: queue of received chunks + pending next() resolver
|
|
26
|
-
const queue: Uint8Array[] = [];
|
|
27
|
-
let pending: ((value: IteratorResult<Uint8Array>) => void) | null = null;
|
|
28
|
-
|
|
29
|
-
const onMessage = (event: MessageEvent): void => {
|
|
30
|
-
if (isClosed) return;
|
|
31
|
-
const data = event.data as unknown;
|
|
32
|
-
let normalised: Uint8Array;
|
|
33
|
-
if (data instanceof Uint8Array) {
|
|
34
|
-
normalised = data;
|
|
35
|
-
} else if (data instanceof ArrayBuffer) {
|
|
36
|
-
normalised = new Uint8Array(data);
|
|
37
|
-
} else if (ArrayBuffer.isView(data)) {
|
|
38
|
-
const view = data as ArrayBufferView;
|
|
39
|
-
normalised = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
|
|
40
|
-
} else if (typeof Blob !== "undefined" && data instanceof Blob) {
|
|
41
|
-
void data.arrayBuffer().then((buf) => deliver(new Uint8Array(buf)));
|
|
42
|
-
return;
|
|
43
|
-
} else if (typeof data === "string") {
|
|
44
|
-
const n = normalizeToUint8Array(data);
|
|
45
|
-
if (n instanceof Uint8Array) normalised = n;
|
|
46
|
-
else {
|
|
47
|
-
void n.then(deliver);
|
|
48
|
-
return;
|
|
49
|
-
}
|
|
50
|
-
} else {
|
|
51
|
-
return;
|
|
52
|
-
}
|
|
53
|
-
deliver(normalised);
|
|
54
|
-
};
|
|
55
|
-
|
|
56
|
-
const deliver = (bytes: Uint8Array): void => {
|
|
57
|
-
if (isClosed) return;
|
|
58
|
-
if (pending) {
|
|
59
|
-
const r = pending;
|
|
60
|
-
pending = null;
|
|
61
|
-
r({ value: bytes, done: false });
|
|
62
|
-
} else {
|
|
63
|
-
queue.push(bytes);
|
|
64
|
-
}
|
|
65
|
-
};
|
|
66
|
-
|
|
67
|
-
const onClose = (): void => {
|
|
68
|
-
if (isClosed) return;
|
|
69
|
-
isClosed = true;
|
|
70
|
-
ws.removeEventListener("message", onMessage);
|
|
71
|
-
ws.removeEventListener("close", onClose);
|
|
72
|
-
if (pending) {
|
|
73
|
-
const r = pending;
|
|
74
|
-
pending = null;
|
|
75
|
-
r({ value: undefined, done: true } as IteratorResult<Uint8Array>);
|
|
76
|
-
}
|
|
77
|
-
closedResolve();
|
|
78
|
-
};
|
|
79
|
-
|
|
80
|
-
ws.addEventListener("message", onMessage);
|
|
81
|
-
ws.addEventListener("close", onClose);
|
|
82
|
-
|
|
83
|
-
const recv: AsyncIterable<Uint8Array> = {
|
|
84
|
-
[Symbol.asyncIterator]() {
|
|
85
|
-
return {
|
|
86
|
-
next(): Promise<IteratorResult<Uint8Array>> {
|
|
87
|
-
if (queue.length > 0) {
|
|
88
|
-
return Promise.resolve({ value: queue.shift() as Uint8Array, done: false });
|
|
89
|
-
}
|
|
90
|
-
if (isClosed) {
|
|
91
|
-
return Promise.resolve({
|
|
92
|
-
value: undefined,
|
|
93
|
-
done: true,
|
|
94
|
-
} as IteratorResult<Uint8Array>);
|
|
95
|
-
}
|
|
96
|
-
return new Promise<IteratorResult<Uint8Array>>((resolve) => {
|
|
97
|
-
pending = resolve;
|
|
98
|
-
});
|
|
99
|
-
},
|
|
100
|
-
};
|
|
101
|
-
},
|
|
102
|
-
};
|
|
103
|
-
|
|
104
|
-
return {
|
|
105
|
-
send(bytes) {
|
|
106
|
-
if (isClosed) return;
|
|
107
|
-
if (ws.readyState !== WS_READY_STATE.OPEN) return;
|
|
108
|
-
ws.send(bytes);
|
|
109
|
-
},
|
|
110
|
-
recv,
|
|
111
|
-
closed,
|
|
112
|
-
close() {
|
|
113
|
-
if (isClosed) return;
|
|
114
|
-
try {
|
|
115
|
-
ws.close();
|
|
116
|
-
} catch {
|
|
117
|
-
/* ignore */
|
|
118
|
-
}
|
|
119
|
-
onClose();
|
|
120
|
-
},
|
|
121
|
-
};
|
|
122
|
-
}
|
package/src/connect.ts
DELETED
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
import { type Connect, type EmulateMuxOptions, emulateMux } from "@statewalker/webrun-streams";
|
|
2
|
-
import { byteChannelFromWebSocket } from "./byte-channel.js";
|
|
3
|
-
import { type WebSocketLike, WS_READY_STATE } from "./websocket-like.js";
|
|
4
|
-
|
|
5
|
-
export interface ConnectWsParams {
|
|
6
|
-
/** WebSocket URL (`ws://` or `wss://`). */
|
|
7
|
-
url: string;
|
|
8
|
-
/** Optional subprotocol(s) passed to the WebSocket constructor. */
|
|
9
|
-
protocols?: string | string[];
|
|
10
|
-
/**
|
|
11
|
-
* WebSocket constructor. Defaults to the global `WebSocket` when present
|
|
12
|
-
* (browser); pass Node's `ws` package's `WebSocket` in Node.
|
|
13
|
-
*/
|
|
14
|
-
WebSocketCtor?: new (
|
|
15
|
-
url: string,
|
|
16
|
-
protocols?: string | string[],
|
|
17
|
-
) => WebSocketLike;
|
|
18
|
-
/**
|
|
19
|
-
* Flow-control tuning forwarded to `emulateMux` — `mtu` and
|
|
20
|
-
* `maxStreamBuffer`, which is the credit this side advertises. `side` here
|
|
21
|
-
* wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
|
|
22
|
-
* suite's L6 uses this to run at a window small enough that a sender
|
|
23
|
-
* genuinely stalls.
|
|
24
|
-
*/
|
|
25
|
-
mux?: EmulateMuxOptions;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* Open a WebSocket to `params.url`, wrap it as a `ByteChannel`, and run it
|
|
30
|
-
* through `emulateMux`. Returns `{ call, close }` where `call` is the
|
|
31
|
-
* caller-side `Duplex`.
|
|
32
|
-
*/
|
|
33
|
-
export const connect: Connect<ConnectWsParams> = async (params) => {
|
|
34
|
-
const Ctor = params.WebSocketCtor ?? (globalThis as { WebSocket?: typeof WebSocket }).WebSocket;
|
|
35
|
-
if (!Ctor) {
|
|
36
|
-
throw new Error(
|
|
37
|
-
"webrun-streams-ws connect: no WebSocket constructor available. Pass `params.WebSocketCtor` (e.g. the `ws` package's WebSocket in Node).",
|
|
38
|
-
);
|
|
39
|
-
}
|
|
40
|
-
const ws = new Ctor(params.url, params.protocols) as WebSocketLike;
|
|
41
|
-
await waitForOpen(ws);
|
|
42
|
-
const channel = byteChannelFromWebSocket(ws);
|
|
43
|
-
const mux = emulateMux(channel, { ...params.mux, side: "initiator" });
|
|
44
|
-
return {
|
|
45
|
-
call: mux.call,
|
|
46
|
-
async close() {
|
|
47
|
-
await mux.close();
|
|
48
|
-
},
|
|
49
|
-
};
|
|
50
|
-
};
|
|
51
|
-
|
|
52
|
-
function waitForOpen(ws: WebSocketLike): Promise<void> {
|
|
53
|
-
if (ws.readyState === WS_READY_STATE.OPEN) return Promise.resolve();
|
|
54
|
-
return new Promise<void>((resolve, reject) => {
|
|
55
|
-
const cleanup = (): void => {
|
|
56
|
-
ws.removeEventListener("open", onOpen);
|
|
57
|
-
ws.removeEventListener("error", onError);
|
|
58
|
-
ws.removeEventListener("close", onCloseEarly);
|
|
59
|
-
};
|
|
60
|
-
const onOpen = (): void => {
|
|
61
|
-
cleanup();
|
|
62
|
-
resolve();
|
|
63
|
-
};
|
|
64
|
-
const onError = (): void => {
|
|
65
|
-
cleanup();
|
|
66
|
-
reject(new Error("WebSocket error before open"));
|
|
67
|
-
};
|
|
68
|
-
const onCloseEarly = (): void => {
|
|
69
|
-
cleanup();
|
|
70
|
-
reject(new Error("WebSocket closed before it opened"));
|
|
71
|
-
};
|
|
72
|
-
ws.addEventListener("open", onOpen);
|
|
73
|
-
ws.addEventListener("error", onError);
|
|
74
|
-
ws.addEventListener("close", onCloseEarly);
|
|
75
|
-
});
|
|
76
|
-
}
|
package/src/serve.ts
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import { type Duplex, type EmulateMuxOptions, emulateMux } from "@statewalker/webrun-streams";
|
|
2
|
-
import { byteChannelFromWebSocket } from "./byte-channel.js";
|
|
3
|
-
import type { WebSocketLike } from "./websocket-like.js";
|
|
4
|
-
|
|
5
|
-
export interface ServeWsParams {
|
|
6
|
-
/**
|
|
7
|
-
* Source of inbound WebSocket connections. Either a `wss` instance with a
|
|
8
|
-
* `connection` event, or a manual handler the caller wires to its own
|
|
9
|
-
* server.
|
|
10
|
-
*/
|
|
11
|
-
onConnection: (cb: (ws: WebSocketLike) => void) => () => void;
|
|
12
|
-
/**
|
|
13
|
-
* Flow-control tuning forwarded to `emulateMux` — `mtu` and
|
|
14
|
-
* `maxStreamBuffer`, which is the credit this side advertises. `side` here
|
|
15
|
-
* wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
|
|
16
|
-
* suite's L6 uses this to run at a window small enough that a sender
|
|
17
|
-
* genuinely stalls.
|
|
18
|
-
*/
|
|
19
|
-
mux?: EmulateMuxOptions;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* Register a `Duplex` handler against an inbound-WebSocket source. The
|
|
24
|
-
* `onConnection` callback is invoked once per accepted connection; the
|
|
25
|
-
* adapter wraps each in `emulateMux` and binds the handler.
|
|
26
|
-
*
|
|
27
|
-
* Returns an idempotent teardown that unregisters the connection listener.
|
|
28
|
-
* Open `emulateMux` instances continue running until their underlying
|
|
29
|
-
* WebSocket closes.
|
|
30
|
-
*/
|
|
31
|
-
export async function serve(params: ServeWsParams, handler: Duplex): Promise<() => Promise<void>> {
|
|
32
|
-
const off = params.onConnection((ws) => {
|
|
33
|
-
const channel = byteChannelFromWebSocket(ws);
|
|
34
|
-
const mux = emulateMux(channel, { ...params.mux, side: "responder" });
|
|
35
|
-
mux.serve(handler);
|
|
36
|
-
void channel.closed.then(() => mux.close());
|
|
37
|
-
});
|
|
38
|
-
let torn = false;
|
|
39
|
-
return async () => {
|
|
40
|
-
if (torn) return;
|
|
41
|
-
torn = true;
|
|
42
|
-
off();
|
|
43
|
-
};
|
|
44
|
-
}
|