@statewalker/webrun-streams-ws 0.1.1

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 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 ADDED
@@ -0,0 +1,24 @@
1
+ # @statewalker/webrun-streams-ws
2
+
3
+ WebSocket-backed `Connect` / `Serve` adapter in the `webrun-streams-*` family. Each `WebSocket` is one byte channel; `emulateMux` provides the multi-stream layer on top.
4
+
5
+ ```ts
6
+ import { connect, serve } from "@statewalker/webrun-streams-ws";
7
+ import { WebSocket as NodeWebSocket, WebSocketServer } from "ws";
8
+
9
+ const wss = new WebSocketServer({ port: 8080 });
10
+ const stop = await serve(
11
+ { onConnection: (cb) => { wss.on("connection", cb); return () => wss.off("connection", cb); } },
12
+ async function* (input) { for await (const c of input) yield c; },
13
+ );
14
+
15
+ const { call } = await connect({ url: "ws://localhost:8080", WebSocketCtor: NodeWebSocket });
16
+ ```
17
+
18
+ ## Conformance
19
+
20
+ Passes every level of `@statewalker/webrun-streams-conformance` against an in-process `WebSocketServer`.
21
+
22
+ ## License
23
+
24
+ MIT
@@ -0,0 +1,12 @@
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
@@ -0,0 +1 @@
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"}
@@ -0,0 +1,20 @@
1
+ import { type Connect } 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
+ /**
15
+ * Open a WebSocket to `params.url`, wrap it as a `ByteChannel`, and run it
16
+ * through `emulateMux`. Returns `{ call, close }` where `call` is the
17
+ * caller-side `Duplex`.
18
+ */
19
+ export declare const connect: Connect<ConnectWsParams>;
20
+ //# sourceMappingURL=connect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,OAAO,EAAc,MAAM,6BAA6B,CAAC;AAEvE,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;CACpB;AAED;;;;GAIG;AACH,eAAO,MAAM,OAAO,EAAE,OAAO,CAAC,eAAe,CAiB5C,CAAC"}
@@ -0,0 +1,5 @@
1
+ export { byteChannelFromWebSocket } from "./byte-channel.js";
2
+ export { type ConnectWsParams, connect } from "./connect.js";
3
+ export { type ServeWsParams, serve } from "./serve.js";
4
+ export { type WebSocketLike, WS_READY_STATE } from "./websocket-like.js";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,KAAK,eAAe,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,EAAE,KAAK,aAAa,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,EAAE,KAAK,aAAa,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,181 @@
1
+ import { emulateMux, normalizeToUint8Array } from "@statewalker/webrun-streams";
2
+ //#region src/websocket-like.ts
3
+ const WS_READY_STATE = {
4
+ CONNECTING: 0,
5
+ OPEN: 1,
6
+ CLOSING: 2,
7
+ CLOSED: 3
8
+ };
9
+ //#endregion
10
+ //#region src/byte-channel.ts
11
+ /**
12
+ * Wrap an open `WebSocket` (or any `WebSocketLike` — Node `ws` works) into a
13
+ * `ByteChannel` consumable by `emulateMux`. The socket MUST already be in the
14
+ * `OPEN` state; the adapter does not perform handshakes.
15
+ *
16
+ * Inbound binary frames are normalised to `Uint8Array`. Text frames are also
17
+ * accepted (rare on this transport) and surfaced as their UTF-8 bytes.
18
+ */
19
+ function byteChannelFromWebSocket(ws) {
20
+ if (ws.readyState !== WS_READY_STATE.OPEN) throw new Error(`byteChannelFromWebSocket: WebSocket is in readyState ${ws.readyState}, expected OPEN (1)`);
21
+ let closedResolve;
22
+ const closed = new Promise((r) => {
23
+ closedResolve = r;
24
+ });
25
+ let isClosed = false;
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();
75
+ };
76
+ ws.addEventListener("message", onMessage);
77
+ ws.addEventListener("close", onClose);
78
+ return {
79
+ send(bytes) {
80
+ if (isClosed) return;
81
+ if (ws.readyState !== WS_READY_STATE.OPEN) return;
82
+ ws.send(bytes);
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 {
103
+ ws.close();
104
+ } catch {}
105
+ onClose();
106
+ }
107
+ };
108
+ }
109
+ //#endregion
110
+ //#region src/connect.ts
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) => {
117
+ const Ctor = params.WebSocketCtor ?? globalThis.WebSocket;
118
+ if (!Ctor) throw new Error("webrun-streams-ws connect: no WebSocket constructor available. Pass `params.WebSocketCtor` (e.g. the `ws` package's WebSocket in Node).");
119
+ const ws = new Ctor(params.url, params.protocols);
120
+ await waitForOpen(ws);
121
+ const channel = byteChannelFromWebSocket(ws);
122
+ const mux = emulateMux(channel, { side: "initiator" });
123
+ return {
124
+ call: mux.call,
125
+ async close() {
126
+ await mux.close();
127
+ }
128
+ };
129
+ };
130
+ function waitForOpen(ws) {
131
+ if (ws.readyState === WS_READY_STATE.OPEN) return Promise.resolve();
132
+ return new Promise((resolve, reject) => {
133
+ const cleanup = () => {
134
+ ws.removeEventListener("open", onOpen);
135
+ ws.removeEventListener("error", onError);
136
+ ws.removeEventListener("close", onCloseEarly);
137
+ };
138
+ const onOpen = () => {
139
+ cleanup();
140
+ resolve();
141
+ };
142
+ const onError = () => {
143
+ cleanup();
144
+ reject(/* @__PURE__ */ new Error("WebSocket error before open"));
145
+ };
146
+ const onCloseEarly = () => {
147
+ cleanup();
148
+ reject(/* @__PURE__ */ new Error("WebSocket closed before it opened"));
149
+ };
150
+ ws.addEventListener("open", onOpen);
151
+ ws.addEventListener("error", onError);
152
+ ws.addEventListener("close", onCloseEarly);
153
+ });
154
+ }
155
+ //#endregion
156
+ //#region src/serve.ts
157
+ /**
158
+ * Register a `Duplex` handler against an inbound-WebSocket source. The
159
+ * `onConnection` callback is invoked once per accepted connection; the
160
+ * adapter wraps each in `emulateMux` and binds the handler.
161
+ *
162
+ * Returns an idempotent teardown that unregisters the connection listener.
163
+ * Open `emulateMux` instances continue running until their underlying
164
+ * WebSocket closes.
165
+ */
166
+ async function serve(params, handler) {
167
+ const off = params.onConnection((ws) => {
168
+ const channel = byteChannelFromWebSocket(ws);
169
+ const mux = emulateMux(channel, { side: "responder" });
170
+ mux.serve(handler);
171
+ channel.closed.then(() => mux.close());
172
+ });
173
+ let torn = false;
174
+ return async () => {
175
+ if (torn) return;
176
+ torn = true;
177
+ off();
178
+ };
179
+ }
180
+ //#endregion
181
+ export { WS_READY_STATE, byteChannelFromWebSocket, connect, serve };
@@ -0,0 +1,21 @@
1
+ import { type Duplex } 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
+ /**
12
+ * Register a `Duplex` handler against an inbound-WebSocket source. The
13
+ * `onConnection` callback is invoked once per accepted connection; the
14
+ * adapter wraps each in `emulateMux` and binds the handler.
15
+ *
16
+ * Returns an idempotent teardown that unregisters the connection listener.
17
+ * Open `emulateMux` instances continue running until their underlying
18
+ * WebSocket closes.
19
+ */
20
+ export declare function serve(params: ServeWsParams, handler: Duplex): Promise<() => Promise<void>>;
21
+ //# sourceMappingURL=serve.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../src/serve.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAc,MAAM,6BAA6B,CAAC;AAEtE,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;CAC/D;AAED;;;;;;;;GAQG;AACH,wBAAsB,KAAK,CAAC,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,CAahG"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Structural subset of the WHATWG `WebSocket` interface that also matches the
3
+ * Node.js `ws` package. Anything that implements this surface works with the
4
+ * helpers in this package.
5
+ */
6
+ export interface WebSocketLike {
7
+ readonly readyState: number;
8
+ send(data: string | ArrayBuffer | Blob | Uint8Array): void;
9
+ close(): void;
10
+ addEventListener(type: "message", listener: (event: MessageEvent) => void): void;
11
+ addEventListener(type: "open", listener: () => void): void;
12
+ addEventListener(type: "close", listener: () => void): void;
13
+ addEventListener(type: "error", listener: () => void): void;
14
+ removeEventListener(type: "message", listener: (event: MessageEvent) => void): void;
15
+ removeEventListener(type: "open", listener: () => void): void;
16
+ removeEventListener(type: "close", listener: () => void): void;
17
+ removeEventListener(type: "error", listener: () => void): void;
18
+ }
19
+ export declare const WS_READY_STATE: {
20
+ readonly CONNECTING: 0;
21
+ readonly OPEN: 1;
22
+ readonly CLOSING: 2;
23
+ readonly CLOSED: 3;
24
+ };
25
+ //# sourceMappingURL=websocket-like.d.ts.map
@@ -0,0 +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"}
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@statewalker/webrun-streams-ws",
3
+ "version": "0.1.1",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "WebSocket-backed Connect/Serve adapter in the webrun-streams-* family",
7
+ "homepage": "https://github.com/statewalker/webrun-wire",
8
+ "author": {
9
+ "name": "Mikhail Kotelnikov",
10
+ "email": "mikhail.kotelnikov@gmail.com"
11
+ },
12
+ "license": "MIT",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git@github.com:statewalker/webrun-wire.git"
16
+ },
17
+ "exports": {
18
+ ".": "./src/index.ts"
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "src"
23
+ ],
24
+ "dependencies": {
25
+ "@statewalker/webrun-streams": "0.1.1"
26
+ },
27
+ "devDependencies": {
28
+ "@types/node": "^26.2.0",
29
+ "@types/ws": "^8.5.13",
30
+ "rimraf": "^6.1.3",
31
+ "rolldown": "^1.2.4",
32
+ "typescript": "^7.0.2",
33
+ "vitest": "^4.1.10",
34
+ "ws": "^8.18.0",
35
+ "@statewalker/webrun-streams-conformance": "0.1.1"
36
+ },
37
+ "sideEffects": false,
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "scripts": {
42
+ "build": "rimraf dist && rolldown -c && tsc --emitDeclarationOnly --declaration",
43
+ "test": "vitest run",
44
+ "lint": "biome check src tests"
45
+ }
46
+ }
@@ -0,0 +1,122 @@
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 ADDED
@@ -0,0 +1,68 @@
1
+ import { type Connect, 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
+
20
+ /**
21
+ * Open a WebSocket to `params.url`, wrap it as a `ByteChannel`, and run it
22
+ * through `emulateMux`. Returns `{ call, close }` where `call` is the
23
+ * caller-side `Duplex`.
24
+ */
25
+ export const connect: Connect<ConnectWsParams> = async (params) => {
26
+ const Ctor = params.WebSocketCtor ?? (globalThis as { WebSocket?: typeof WebSocket }).WebSocket;
27
+ if (!Ctor) {
28
+ throw new Error(
29
+ "webrun-streams-ws connect: no WebSocket constructor available. Pass `params.WebSocketCtor` (e.g. the `ws` package's WebSocket in Node).",
30
+ );
31
+ }
32
+ const ws = new Ctor(params.url, params.protocols) as WebSocketLike;
33
+ await waitForOpen(ws);
34
+ const channel = byteChannelFromWebSocket(ws);
35
+ const mux = emulateMux(channel, { side: "initiator" });
36
+ return {
37
+ call: mux.call,
38
+ async close() {
39
+ await mux.close();
40
+ },
41
+ };
42
+ };
43
+
44
+ function waitForOpen(ws: WebSocketLike): Promise<void> {
45
+ if (ws.readyState === WS_READY_STATE.OPEN) return Promise.resolve();
46
+ return new Promise<void>((resolve, reject) => {
47
+ const cleanup = (): void => {
48
+ ws.removeEventListener("open", onOpen);
49
+ ws.removeEventListener("error", onError);
50
+ ws.removeEventListener("close", onCloseEarly);
51
+ };
52
+ const onOpen = (): void => {
53
+ cleanup();
54
+ resolve();
55
+ };
56
+ const onError = (): void => {
57
+ cleanup();
58
+ reject(new Error("WebSocket error before open"));
59
+ };
60
+ const onCloseEarly = (): void => {
61
+ cleanup();
62
+ reject(new Error("WebSocket closed before it opened"));
63
+ };
64
+ ws.addEventListener("open", onOpen);
65
+ ws.addEventListener("error", onError);
66
+ ws.addEventListener("close", onCloseEarly);
67
+ });
68
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export { byteChannelFromWebSocket } from "./byte-channel.js";
2
+ export { type ConnectWsParams, connect } from "./connect.js";
3
+ export { type ServeWsParams, serve } from "./serve.js";
4
+ export { type WebSocketLike, WS_READY_STATE } from "./websocket-like.js";
package/src/serve.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { type Duplex, 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
+
14
+ /**
15
+ * Register a `Duplex` handler against an inbound-WebSocket source. The
16
+ * `onConnection` callback is invoked once per accepted connection; the
17
+ * adapter wraps each in `emulateMux` and binds the handler.
18
+ *
19
+ * Returns an idempotent teardown that unregisters the connection listener.
20
+ * Open `emulateMux` instances continue running until their underlying
21
+ * WebSocket closes.
22
+ */
23
+ export async function serve(params: ServeWsParams, handler: Duplex): Promise<() => Promise<void>> {
24
+ const off = params.onConnection((ws) => {
25
+ const channel = byteChannelFromWebSocket(ws);
26
+ const mux = emulateMux(channel, { side: "responder" });
27
+ mux.serve(handler);
28
+ void channel.closed.then(() => mux.close());
29
+ });
30
+ let torn = false;
31
+ return async () => {
32
+ if (torn) return;
33
+ torn = true;
34
+ off();
35
+ };
36
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Structural subset of the WHATWG `WebSocket` interface that also matches the
3
+ * Node.js `ws` package. Anything that implements this surface works with the
4
+ * helpers in this package.
5
+ */
6
+ export interface WebSocketLike {
7
+ readonly readyState: number;
8
+ send(data: string | ArrayBuffer | Blob | Uint8Array): void;
9
+ close(): void;
10
+ addEventListener(type: "message", listener: (event: MessageEvent) => void): void;
11
+ addEventListener(type: "open", listener: () => void): void;
12
+ addEventListener(type: "close", listener: () => void): void;
13
+ addEventListener(type: "error", listener: () => void): void;
14
+ removeEventListener(type: "message", listener: (event: MessageEvent) => void): void;
15
+ removeEventListener(type: "open", listener: () => void): void;
16
+ removeEventListener(type: "close", listener: () => void): void;
17
+ removeEventListener(type: "error", listener: () => void): void;
18
+ }
19
+
20
+ export const WS_READY_STATE = {
21
+ CONNECTING: 0,
22
+ OPEN: 1,
23
+ CLOSING: 2,
24
+ CLOSED: 3,
25
+ } as const;