@statewalker/webrun-streams-ws 0.2.0 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +163 -107
  3. package/package.json +16 -10
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022-2026 statewalker
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,48 +1,70 @@
1
1
  # @statewalker/webrun-streams-ws
2
2
 
3
- WebSocket-backed `Connect` / `Serve` adapter in the `webrun-streams-*` family.
3
+ ## What it is
4
4
 
5
- ## What this is
6
-
7
- A binding between a `WebSocket` and the [`webrun-streams`](../webrun-streams)
8
- `Duplex` seam. One `WebSocket` becomes one
9
- [`ByteChannel`](../webrun-streams#the-duplex-seam); `emulateMux` layers many
10
- concurrent logical calls on top of that single socket.
11
-
12
- The point is that your handler never mentions WebSockets. It is an ordinary
13
- `Duplex` — `(input: AsyncIterable<Uint8Array>) => AsyncGenerator<Uint8Array>` —
14
- so the same function runs unchanged over a `MessagePort`, a WebRTC data
15
- channel, libp2p, or an in-process pipe. Swapping transports is swapping the
16
- import.
5
+ A WebSocket adapter for the `Duplex` seam from `@statewalker/webrun-streams`.
6
+ `connect` opens a WebSocket and returns a `call` function; `serve` binds a
7
+ handler to every inbound WebSocket. Each socket is wrapped as a `ByteChannel`
8
+ and run through `emulateMux`, so many concurrent calls share one socket. The
9
+ handler is an ordinary `Duplex`
10
+ (`(input) => AsyncGenerator<Uint8Array>`) and never sees the socket.
17
11
 
18
12
  ## Why it exists
19
13
 
20
- A raw `WebSocket` gives you one unordered-in-practice message pipe with no
21
- notion of a request, no concurrency, no half-close, and no way to propagate an
22
- error from the far end as an `Error`. Everything above it has to reinvent
23
- framing, correlation and teardown.
24
-
25
- This adapter supplies the missing piece exactly once: it wraps the socket as a
26
- `ByteChannel`, and `emulateMux` turns that into as many independent
27
- back-pressured byte streams as you need — each with proper end-of-stream,
28
- mid-stream cancellation, and error propagation.
14
+ A raw WebSocket is one message pipe. It has no notion of a request, no
15
+ concurrency, no half-close, and no way to deliver the far end's exception as
16
+ an `Error`. Everything above it would have to build framing, correlation and
17
+ teardown. This adapter wraps the socket as a `ByteChannel` and lets
18
+ `emulateMux` provide independent streams with backpressure, end-of-stream,
19
+ cancellation and error propagation. Because the handler is a plain `Duplex`,
20
+ the same function runs over any other adapter that implements the seam.
29
21
 
30
- ## Install
22
+ ## How to use
31
23
 
32
24
  ```sh
33
- npm install @statewalker/webrun-streams-ws
25
+ pnpm add @statewalker/webrun-streams-ws
34
26
  ```
35
27
 
36
- In the browser the global `WebSocket` is used automatically. In Node, supply a
37
- constructor — the [`ws`](https://www.npmjs.com/package/ws) package works as-is:
28
+ Runtime dependency: `@statewalker/webrun-streams`. No peer dependencies. One
29
+ entry point, `.`.
38
30
 
39
- ```sh
40
- npm install ws
41
- ```
31
+ - **Browser and worker**: `connect` uses the global `WebSocket`.
32
+ - **Node**: pass a constructor as `WebSocketCtor`. The `ws` package works
33
+ (`pnpm add ws`). On the server side, `serve` takes an `onConnection`
34
+ subscription instead of a server object, so it works with `ws`'s
35
+ `WebSocketServer` or any other source of open sockets.
36
+
37
+ | Export | What it gives |
38
+ | --- | --- |
39
+ | `connect(params)` | `Connect<ConnectWsParams>`. Opens a socket, waits for it to open, resolves `{ call, close }`. Each `call(input)` opens a new stream on the socket; `close()` closes the mux and the socket. |
40
+ | `serve(params, handler)` | `Serve<ServeWsParams>`. Wraps each socket from `onConnection` in its own `emulateMux` and binds `handler`. Resolves to an idempotent teardown. |
41
+ | `byteChannelFromWebSocket(ws)` | Wraps one open socket as a `ByteChannel`, for driving `emulateMux` yourself or reusing a socket you already own. |
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). |
43
+ | `WS_READY_STATE` | `{ CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3 }`. |
44
+ | `ConnectWsParams`, `ServeWsParams` | Parameter types, below. |
42
45
 
43
- ## Getting started
46
+ `ConnectWsParams`:
44
47
 
45
- Serve a handler over an in-process `WebSocketServer` and call it:
48
+ | Field | Type | Default | Meaning |
49
+ | --- | --- | --- | --- |
50
+ | `url` | `string` | required | `ws://` or `wss://` URL. |
51
+ | `protocols` | `string \| string[]` | none | Subprotocols passed to the constructor. |
52
+ | `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
+
55
+ `ServeWsParams`:
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.
64
+
65
+ ## Examples
66
+
67
+ ### Serve and call in Node
46
68
 
47
69
  ```ts
48
70
  import { connect, serve } from "@statewalker/webrun-streams-ws";
@@ -50,7 +72,6 @@ import { WebSocket as NodeWebSocket, WebSocketServer } from "ws";
50
72
 
51
73
  const wss = new WebSocketServer({ port: 8080 });
52
74
 
53
- // The handler is a plain Duplex: bytes in, bytes out.
54
75
  const stop = await serve(
55
76
  {
56
77
  onConnection: (cb) => {
@@ -64,8 +85,8 @@ const stop = await serve(
64
85
  );
65
86
 
66
87
  const { call, close } = await connect({
67
- url: "ws://localhost:8080",
68
- WebSocketCtor: NodeWebSocket, // omit in the browser
88
+ url: "ws://127.0.0.1:8080",
89
+ WebSocketCtor: NodeWebSocket,
69
90
  });
70
91
 
71
92
  for await (const chunk of call([new TextEncoder().encode("hello")])) {
@@ -74,103 +95,138 @@ for await (const chunk of call([new TextEncoder().encode("hello")])) {
74
95
 
75
96
  await close();
76
97
  await stop();
98
+ wss.close();
77
99
  ```
78
100
 
79
- In a browser the client side is just:
80
-
81
- ```ts
82
- const { call, close } = await connect({ url: "wss://example.com/socket" });
83
- ```
84
-
85
- ### Concurrent calls
86
-
87
- Each `call(...)` is an independent stream over the same socket. They interleave
88
- without interfering:
101
+ ### Browser client, concurrent calls
89
102
 
90
103
  ```ts
91
104
  import { collectBytes } from "@statewalker/webrun-streams";
105
+ import { connect } from "@statewalker/webrun-streams-ws";
106
+
107
+ const { call, close } = await connect({ url: "wss://example.com/socket" });
108
+ const enc = new TextEncoder();
92
109
 
110
+ // Each call is an independent stream on the same socket.
93
111
  const [a, b] = await Promise.all([
94
- collectBytes(call(requestA)),
95
- collectBytes(call(requestB)),
112
+ collectBytes(call([enc.encode("first")])),
113
+ collectBytes(call([enc.encode("second")])),
96
114
  ]);
115
+ await close();
97
116
  ```
98
117
 
99
- ### Carrying HTTP over it
118
+ ### HTTP over the socket
100
119
 
101
- Pair with [`webrun-http-streams`](../webrun-http-streams) to move real
102
- `Request` / `Response` objects across the socket:
120
+ `@statewalker/webrun-http-streams` carries `Request` / `Response` over any
121
+ `Duplex`:
103
122
 
104
123
  ```ts
105
124
  import { fetchOverDuplex } from "@statewalker/webrun-http-streams";
125
+ import { connect } from "@statewalker/webrun-streams-ws";
106
126
 
107
- const response = await fetchOverDuplex(call, new Request("http://x/api/todo"));
127
+ const { call } = await connect({ url: "wss://example.com/socket" });
128
+ const response = await fetchOverDuplex(call, new Request("http://peer/api/todo"));
108
129
  ```
109
130
 
110
- ## API
111
-
112
- ### `connect(params): Promise<{ call, close }>`
113
-
114
- Opens a `WebSocket` and resolves once it is open. Type: `Connect<ConnectWsParams>`.
115
-
116
- | Field | Type | Default | Meaning |
117
- | --- | --- | --- | --- |
118
- | `url` | `string` | — | WebSocket URL (`ws://` or `wss://`). |
119
- | `protocols` | `string \| string[]` | — | Subprotocol(s) passed to the constructor. |
120
- | `WebSocketCtor` | constructor | global `WebSocket` | Constructor to use. Required where there is no global `WebSocket` (Node). |
121
- | `mux` | `EmulateMuxOptions` | `emulateMux`'s own | Flow-control tuning (`mtu`, `maxStreamBuffer`) forwarded to `emulateMux`. `side` is always `"initiator"` regardless of `mux.side`. |
122
-
123
- Resolves to `{ call: Duplex, close: () => Promise<void> }`. Each `call(input)`
124
- opens a fresh logical stream; `close()` tears down the socket and every stream
125
- on it.
126
-
127
- ### `serve(params, handler): Promise<() => Promise<void>>`
128
-
129
- Registers `handler` against a source of inbound sockets. Type: `Serve<ServeWsParams>`.
130
-
131
- | Field | Type | Meaning |
132
- | --- | --- | --- |
133
- | `onConnection` | `(cb: (ws: WebSocketLike) => void) => () => void` | Subscribes to inbound connections; returns an unsubscribe function. |
134
- | `mux` | `EmulateMuxOptions` | Flow-control tuning (`mtu`, `maxStreamBuffer`) forwarded to `emulateMux`. `side` is always `"responder"` regardless of `mux.side`. |
131
+ ### Driving `emulateMux` on a socket you own
135
132
 
136
- The indirection means this package never depends on a particular server
137
- library — wire it to `ws`, to a Deno/Bun handler, or to your own accept loop.
138
- Returns an idempotent teardown.
139
-
140
- ### `byteChannelFromWebSocket(ws): ByteChannel`
141
-
142
- Wraps a single socket as a `ByteChannel` (`send` / `recv` / `closed` / `close`).
143
- Use this when you want to drive `emulateMux` yourself, or reuse a socket you
144
- already own.
145
-
146
- ### `WebSocketLike` / `WS_READY_STATE`
133
+ ```ts
134
+ import { emulateMux } from "@statewalker/webrun-streams";
135
+ import { byteChannelFromWebSocket, type WebSocketLike } from "@statewalker/webrun-streams-ws";
147
136
 
148
- The structural socket interface this package accepts, and the
149
- `CONNECTING`/`OPEN`/`CLOSING`/`CLOSED` constants. Typing against `WebSocketLike`
150
- rather than the DOM `WebSocket` is what lets the same code accept Node's `ws`.
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
+ ```
151
144
 
152
- ## Conformance
145
+ ## Internals
153
146
 
154
- Passes every level (L0–L6) of
155
- [`@statewalker/webrun-streams-conformance`](../webrun-streams-conformance)
156
- against an in-process `WebSocketServer`: body sizes up to 10 MiB, concurrent
157
- calls, half-close, mid-stream cancellation, error propagation with stack and
158
- custom fields preserved, idempotent teardown, and flow control against a slow
159
- consumer at a small advertised window.
147
+ ### One socket, one mux
160
148
 
161
- ```sh
162
- pnpm --filter @statewalker/webrun-streams-ws test
149
+ ```
150
+ client server
151
+ call(a) ──┐ ┌──> handler(a)
152
+ call(b) ──┼─ emulateMux ══ WebSocket ══ emulateMux ─┼──> handler(b)
153
+ call(c) ──┘ (initiator) (responder) └──> handler(c)
154
+ ByteChannel ByteChannel
163
155
  ```
164
156
 
165
- ## Dependencies
166
-
167
- | Dependency | Kind | Why |
168
- | --- | --- | --- |
169
- | [`@statewalker/webrun-streams`](../webrun-streams) | runtime | The `Duplex` / `ByteChannel` seam and `emulateMux`. |
170
- | `ws` | dev / your choice | Only for the Node tests. Consumers pass their own constructor. |
171
-
172
- No other runtime dependencies. ESM only (`"type": "module"`).
157
+ `connect` creates one socket and one `emulateMux` with `side: "initiator"`.
158
+ `serve` creates one `emulateMux` with `side: "responder"` per inbound socket,
159
+ and closes it when that socket closes. The sides are forced, overriding any
160
+ `mux.side`, so the two ends always allocate stream ids from different sets
161
+ (even and odd). Flow control, framing and stream lifetimes are `emulateMux`'s;
162
+ see `@statewalker/webrun-streams`.
163
+
164
+ ### Why the server takes `onConnection` and not a server object
165
+
166
+ `serve` depends only on a subscription function, so this package has no
167
+ dependency on a server library. It can be wired to `ws`, to a runtime's
168
+ built-in WebSocket upgrade, or to a custom accept loop.
169
+
170
+ ### How `byteChannelFromWebSocket` maps the socket
171
+
172
+ - Each WebSocket message is one `recv` item. `Uint8Array` (including Node
173
+ `Buffer`), `ArrayBuffer` and other `ArrayBufferView`s are passed through
174
+ without copying. A `Blob` is read asynchronously, which can reorder it
175
+ relative to later messages; set `binaryType = "arraybuffer"` in the browser
176
+ if that matters. Text messages are accepted and delivered as UTF-8 bytes.
177
+ Anything else is ignored.
178
+ - `send` is silently dropped when the socket is not `OPEN` or the channel is
179
+ closed; `emulateMux` learns about the failure from `closed`.
180
+ - The socket's `close` event ends `recv` and resolves `closed`, which fails
181
+ every in-flight call with `TransportClosedError`.
182
+
183
+ ### WebSocketLike and the DOM type
184
+
185
+ `WebSocketLike` is structural so that the DOM `WebSocket` and Node's `ws`
186
+ both fit without this package depending on either. `ws`'s `WebSocket` type
187
+ checks as is. The DOM type does not: `WebSocketLike.send` accepts
188
+ `Uint8Array<ArrayBufferLike>`, which the current DOM `WebSocket.send` typing
189
+ (`BufferSource`) rejects, so passing a DOM socket to
190
+ `byteChannelFromWebSocket` or a DOM constructor as `WebSocketCtor` needs
191
+ `as unknown as WebSocketLike`. `connect` without `WebSocketCtor` uses the
192
+ global `WebSocket` and does the cast itself.
193
+
194
+ ### Failure modes
195
+
196
+ | Situation | Error |
197
+ | --- | --- |
198
+ | No `WebSocketCtor` and no global `WebSocket` | `webrun-streams-ws connect: no WebSocket constructor available. Pass \`params.WebSocketCtor\` (e.g. the \`ws\` package's WebSocket in Node).` |
199
+ | Socket errors before opening | `WebSocket error before open` |
200
+ | Socket closes before opening | `WebSocket closed before it opened` |
201
+ | `byteChannelFromWebSocket` on a socket that is not open | `byteChannelFromWebSocket: WebSocket is in readyState <n>, expected OPEN (1)` |
202
+ | Socket closes with calls in flight | `TransportClosedError` (`transport closed`) |
203
+
204
+ `connect` has no timeout of its own; a socket that never opens or fails leaves
205
+ the promise pending.
206
+
207
+ ### Teardown is listener-only on the server
208
+
209
+ The function `serve` resolves to unsubscribes from `onConnection` and nothing
210
+ else. Muxes on sockets that are already connected keep running until their
211
+ socket closes. To drop live connections, close the sockets (for example
212
+ `wss.close()` plus `terminate()` on each client with `ws`).
213
+
214
+ ### Tests and measurements
215
+
216
+ `pnpm test` runs the shared conformance suite (L0 to L6) against an in-process
217
+ `ws` server; the pair helper forwards L6's small window through `mux`.
218
+ `pnpm run test:bench` runs a separate measurement that compares a direct
219
+ WebSocket round trip with one bridged through a `MessageChannel`. It reports
220
+ numbers and does not gate on a threshold, because a timing threshold on
221
+ shared CI hardware is unreliable, and it is excluded from `pnpm test`.
222
+
223
+ ### Dependencies
224
+
225
+ - `@statewalker/webrun-streams` (`workspace:^`): `emulateMux`, the
226
+ `ByteChannel` / `Duplex` types and `normalizeToUint8Array`.
227
+ - No other runtime dependencies. `ws` is a dev dependency used only by the
228
+ tests; consumers supply their own constructor.
173
229
 
174
230
  ## License
175
231
 
176
- MIT © statewalker — see [LICENSE](../../LICENSE).
232
+ MIT
package/package.json CHANGED
@@ -1,10 +1,13 @@
1
1
  {
2
2
  "name": "@statewalker/webrun-streams-ws",
3
- "version": "0.2.0",
3
+ "version": "0.2.3",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "WebSocket-backed Connect/Serve adapter in the webrun-streams-* family",
7
- "homepage": "https://github.com/statewalker/webrun-wire",
7
+ "bugs": {
8
+ "url": "https://github.com/statewalker/webrun-wire/issues"
9
+ },
10
+ "homepage": "https://github.com/statewalker/webrun-wire/tree/main/packages/webrun-streams-ws#readme",
8
11
  "author": {
9
12
  "name": "Mikhail Kotelnikov",
10
13
  "email": "mikhail.kotelnikov@gmail.com"
@@ -12,10 +15,12 @@
12
15
  "license": "MIT",
13
16
  "repository": {
14
17
  "type": "git",
15
- "url": "git@github.com:statewalker/webrun-wire.git"
18
+ "url": "git+https://github.com/statewalker/webrun-wire.git",
19
+ "directory": "packages/webrun-streams-ws"
16
20
  },
17
21
  "exports": {
18
22
  ".": {
23
+ "source": "./src/index.ts",
19
24
  "types": "./dist/index.d.ts",
20
25
  "import": "./dist/index.js"
21
26
  }
@@ -25,17 +30,18 @@
25
30
  "src"
26
31
  ],
27
32
  "dependencies": {
28
- "@statewalker/webrun-streams": "0.2.0"
33
+ "@statewalker/webrun-streams": "^0.2.2"
29
34
  },
30
35
  "devDependencies": {
31
- "@types/node": "^26.2.0",
32
- "@types/ws": "^8.5.13",
36
+ "@biomejs/biome": "^2.5.15",
37
+ "@types/node": "^26.6.4",
38
+ "@types/ws": "^8.18.2",
33
39
  "rimraf": "^6.1.3",
34
- "rolldown": "^1.2.4",
40
+ "rolldown": "^1.2.12",
35
41
  "typescript": "^7.0.2",
36
- "vitest": "^4.1.10",
37
- "ws": "^8.18.0",
38
- "@statewalker/webrun-streams-conformance": "0.2.0"
42
+ "vitest": "^5.0.3",
43
+ "ws": "^8.22.0",
44
+ "@statewalker/webrun-streams-conformance": "^0.3.2"
39
45
  },
40
46
  "sideEffects": false,
41
47
  "publishConfig": {