@statewalker/webrun-streams-peerjs 0.2.3 → 0.3.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 CHANGED
@@ -2,81 +2,106 @@
2
2
 
3
3
  ## What it is
4
4
 
5
- A `Connect` / `Serve` adapter that runs `@statewalker/webrun-streams` `Duplex` calls over a PeerJS
6
- [`DataConnection`](https://peerjs.com/docs/#dataconnection). One connection becomes one
7
- `ByteChannel`, and `webrun-streams`' `emulateMux` runs many concurrent calls over it. Your handler
8
- is an ordinary `Duplex`, `(input: AsyncIterable<Uint8Array>) => AsyncGenerator<Uint8Array>`, the
9
- same function you would run over a WebSocket or a `MessagePort`.
5
+ A PeerJS [`DataConnection`](https://peerjs.com/docs/#dataconnection) as a pipe of bytes for
6
+ `@statewalker/webrun-rpc`'s port stack. `messageTargetOverPeerJs(conn)` turns one open raw
7
+ connection into `{ target, signal, maxMessageSize }`: a `MessageTarget` whose messages are
8
+ `Uint8Array`s (one data channel message each), a signal that aborts when the connection closes or
9
+ fails, and the payload ceiling the connection can carry. Hand all three to `webrun-rpc`'s
10
+ `overPipe` with `msgpackCodec`, and `webrun-rpc`'s `connect` / `serve` run many concurrent calls
11
+ over the connection, one port per call. Your handler is an ordinary `Duplex`,
12
+ `(input: AsyncIterable<Uint8Array>) => AsyncGenerator<Uint8Array>`, the same function you would
13
+ run over a WebSocket or a `MessagePort`.
10
14
 
11
15
  ## Why it exists
12
16
 
13
17
  PeerJS is the least-effort route to a browser-to-browser connection: it ships a public broker, so
14
18
  you get a working peer link without running signalling infrastructure. What it hands you is one
15
- message pipe with no request framing, no concurrency, no half-close and no error propagation. This
16
- adapter supplies those, so the transport becomes a detail: a handler prototyped over PeerJS runs
17
- unchanged over any other `webrun-streams` adapter.
19
+ message pipe with no request framing, no concurrency, no half-close and no error propagation.
20
+ `webrun-rpc`'s port stack supplies those over any pipe of messages. What it needs from the
21
+ transport is the pipe, word of the pipe's death, and the largest message that survives the trip.
22
+ A PeerJS connection gets the last one wrong silently: a message past the data channel's ceiling
23
+ arrives as nothing, with no error on either side. This package supplies all three, checks the
24
+ connection options that would otherwise corrupt streams without an error, and nothing else. A
25
+ handler prototyped over PeerJS runs unchanged over any other transport.
18
26
 
19
27
  ## How to use
20
28
 
21
29
  ```sh
22
- pnpm add @statewalker/webrun-streams-peerjs peerjs
30
+ pnpm add @statewalker/webrun-streams-peerjs peerjs @statewalker/webrun-rpc @statewalker/webrun-msgpack
23
31
  ```
24
32
 
25
33
  `peerjs` is a required peer dependency (`^1.5.5`). You create and own the `Peer`, its broker
26
34
  configuration and its connections. Browser only in practice: PeerJS needs WebRTC. One entry point,
27
35
  `.`, ESM only.
28
36
 
29
- **Connections must use `serialization: "raw"`.** Otherwise PeerJS encodes the bytes itself and the
30
- mux framing does not survive. The adapter checks and throws
31
- `TypeError: byteChannelFromPeerJs: DataConnection serialization is '<value>', expected 'raw'`.
37
+ **Connections must be open, use `serialization: "raw"` and be `reliable: true`.** With any other
38
+ serialization PeerJS encodes the bytes itself; PeerJS's default `reliable: false` means unordered
39
+ delivery, which would reorder envelopes and corrupt every stream without an error; a connection
40
+ that is not yet open would drop posts, and one already closed would never abort the signal.
41
+ `messageTargetOverPeerJs` checks all three and throws.
32
42
 
33
43
  | Export | Purpose |
34
44
  | --- | --- |
35
- | `connect(params: ConnectPeerJsParams)` | `Connect`. Takes one open `DataConnection`. Resolves `{ call, close }`; each `call(input)` opens a new logical stream. `close()` ends the mux and closes the connection. |
36
- | `serve(params: ServePeerJsParams, handler)` | `Serve`. Takes a `Peer`, serves `handler` on every inbound connection. Resolves an idempotent teardown. |
37
- | `ConnectPeerJsParams` | `{ conn: DataConnection; mux?: EmulateMuxOptions }`. |
38
- | `ServePeerJsParams` | `{ peer: Peer; mux?: EmulateMuxOptions }`. |
39
- | `byteChannelFromPeerJs(conn)` | The `ByteChannel` both use, for driving `emulateMux` yourself. |
45
+ | `messageTargetOverPeerJs(conn, options?)` | One open raw, reliable connection as a `PeerJsMessageTarget`, `{ target, signal, maxMessageSize }`: a `MessageTarget` of bytes with `bufferedAmount` / `whenDrained()`, a signal that aborts when the connection closes or fails or a post exceeds `maxFrameBytes`, and the payload ceiling to give `overPipe`. |
46
+ | `MessageTargetOverPeerJsOptions` | `maxFrameBytes` (the largest message the connection carries; default `DEFAULT_MAX_FRAME_BYTES`) and `maxMessageSize` (the payload ceiling to report; default `maxFrameBytes` − 256). |
47
+ | `PeerJsMessageTarget` | The result type above. |
48
+ | `DEFAULT_MAX_FRAME_BYTES`, `DEFAULT_MAX_MESSAGE_SIZE`, `DRAIN_LOW_WATER` | 16 KiB, 16 KiB − 256, 256 KiB: the defaults of the above. |
40
49
 
41
- `mux` is forwarded to `emulateMux` (`mtu`, `maxStreamBuffer`, `maxStreams`, with `webrun-streams`'
42
- defaults: 64 KiB, 8 MiB, 256). `side` is fixed by the function you call — `"initiator"` for
43
- `connect`, `"responder"` for `serve` — and overrides `mux.side`.
44
-
45
- `serve` takes the `Peer` because it accepts many inbound connections; `connect` takes one
46
- connection you already opened.
50
+ Both ends must run the port stack with the same codec. Pass all three of `target`, `signal` and
51
+ `maxMessageSize` to `overPipe`: `signal` closes the multiplexer when the connection dies, and
52
+ `maxMessageSize` chunks bodies under the frame limit.
47
53
 
48
54
  ## Examples
49
55
 
50
56
  ### Serving
51
57
 
52
58
  ```ts
59
+ import { msgpackCodec } from "@statewalker/webrun-msgpack";
60
+ import { overPipe, serve } from "@statewalker/webrun-rpc";
61
+ import { messageTargetOverPeerJs } from "@statewalker/webrun-streams-peerjs";
53
62
  import { Peer } from "peerjs";
54
- import { serve } from "@statewalker/webrun-streams-peerjs";
55
63
 
56
64
  const peer = new Peer("my-server-id");
57
- await new Promise((resolve) => peer.on("open", resolve));
65
+ await new Promise<void>((resolve) => peer.on("open", () => resolve()));
58
66
 
59
- const stop = await serve({ peer }, async function* echo(input) {
67
+ async function* echo(input: AsyncIterable<Uint8Array> | Iterable<Uint8Array>) {
60
68
  for await (const chunk of input) yield chunk;
61
- });
69
+ }
62
70
 
63
- // later: stop accepting, close every served connection's mux
64
- await stop();
71
+ peer.on("connection", (conn) => {
72
+ const ready = () => {
73
+ const { target, signal, maxMessageSize } = messageTargetOverPeerJs(conn);
74
+ void serve(
75
+ { mux: overPipe(target, { codec: msgpackCodec, side: "responder", signal, maxMessageSize }) },
76
+ echo,
77
+ );
78
+ };
79
+ if (conn.open) ready();
80
+ else conn.on("open", ready);
81
+ });
65
82
  ```
66
83
 
84
+ The caller must open the connection raw and reliable; one opened otherwise makes
85
+ `messageTargetOverPeerJs` throw inside `ready`, and that connection is not served.
86
+
67
87
  ### Calling
68
88
 
69
89
  ```ts
90
+ import { msgpackCodec } from "@statewalker/webrun-msgpack";
91
+ import { connect, overPipe } from "@statewalker/webrun-rpc";
92
+ import { messageTargetOverPeerJs } from "@statewalker/webrun-streams-peerjs";
70
93
  import { Peer } from "peerjs";
71
- import { connect } from "@statewalker/webrun-streams-peerjs";
72
94
 
73
95
  const peer = new Peer();
74
- await new Promise((resolve) => peer.on("open", resolve));
96
+ await new Promise<void>((resolve) => peer.on("open", () => resolve()));
75
97
 
76
- const conn = peer.connect("my-server-id", { serialization: "raw" });
77
- await new Promise((resolve) => conn.on("open", resolve));
98
+ const conn = peer.connect("my-server-id", { serialization: "raw", reliable: true });
99
+ await new Promise<void>((resolve) => conn.on("open", () => resolve()));
78
100
 
79
- const { call, close } = await connect({ conn });
101
+ const { target, signal, maxMessageSize } = messageTargetOverPeerJs(conn);
102
+ const { call, close } = await connect({
103
+ mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal, maxMessageSize }),
104
+ });
80
105
 
81
106
  for await (const chunk of call([new TextEncoder().encode("ping")])) {
82
107
  console.log(new TextDecoder().decode(chunk)); // "ping"
@@ -93,48 +118,56 @@ import { fetchOverDuplex } from "@statewalker/webrun-http-streams";
93
118
  const response = await fetchOverDuplex(call, new Request("http://peer/api/todo"));
94
119
  ```
95
120
 
96
- ### Driving the mux yourself
97
-
98
- ```ts
99
- import { emulateMux } from "@statewalker/webrun-streams";
100
- import { byteChannelFromPeerJs } from "@statewalker/webrun-streams-peerjs";
101
-
102
- const channel = byteChannelFromPeerJs(conn); // conn opened with serialization: "raw"
103
- const mux = emulateMux(channel, { side: "initiator" });
104
- // mux.call(input), mux.serve(handler), mux.close()
105
- ```
106
-
107
121
  ## Internals
108
122
 
109
123
  ```
110
124
  handler / caller (Duplex)
111
125
  │
112
- emulateMux (webrun-streams): framed streams, credit flow control
126
+ webrun-rpc connect / serve: one stream per port
127
+ │
128
+ overPipe + msgpackCodec (webrun-rpc): a port per call, framing, chunking to maxMessageSize
113
129
  │
114
- byteChannelFromPeerJs: one ByteChannel per DataConnection
130
+ messageTargetOverPeerJs: one MessageTarget per DataConnection
115
131
  │ out: conn.send(bytes) in: "data" events
116
132
  ▼
117
- PeerJS DataConnection (serialization: "raw") ── WebRTC data channel
133
+ PeerJS DataConnection (serialization: "raw", reliable) ── WebRTC data channel
118
134
  ```
119
135
 
120
- ### What the channel accepts, and what it drops
136
+ ### The message ceiling (measured)
137
+
138
+ PeerJS hands a raw message to the data channel unchanged. Between two Chromiums a message of
139
+ 262,143 bytes arrives; one of 262,145 arrives as nothing, with no throw and no error event, and
140
+ the connection silently closes (`tests/message-ceiling.test.ts`, `test:browser`). Firefox to
141
+ Chrome cuts off at 16,384, as PeerJS itself records. So the pipe defaults to `maxFrameBytes`
142
+ 16 KiB, reports `maxMessageSize` 256 bytes under it (the port stack's framing adds up to 134), and
143
+ a post past `maxFrameBytes` ends the pipe and throws a `RangeError` instead of vanishing. Raise
144
+ `maxFrameBytes` only for peers known to allow more.
145
+
146
+ ### What the pipe accepts, and what it refuses
147
+
148
+ Inbound `data` may be a `Uint8Array`, an `ArrayBuffer` or any `ArrayBufferView`; each is copied
149
+ into a fresh `Uint8Array`, since PeerJS may reuse the buffer it hands out. Anything else (a
150
+ `Blob`, a string) ends the pipe with a `TypeError` and closes the connection: dropping it would
151
+ lose an envelope and hang its call. Messages that reach no listener are dropped, as on a
152
+ `MessagePort`.
121
153
 
122
- Inbound `data` may be a `Uint8Array`, an `ArrayBuffer`, any `ArrayBufferView` or a `Blob` (read
123
- asynchronously); each is copied into a fresh `Uint8Array`. Anything else is ignored. Outbound
124
- `send` is a silent no-op while `conn.open` is false, so **wait for the connection's `open` event
125
- before `connect`**; bytes sent earlier are lost without an error.
154
+ Outbound, `postMessage` throws a `TypeError` for anything but bytes, so a codec breaking its
155
+ contract is not papered over. After the connection has closed it is a no-op: `signal` already says
156
+ so. Each message is copied before `conn.send`, because PeerJS may queue it past its own buffer
157
+ threshold.
126
158
 
127
- ### What closes the channel, and what you see
159
+ ### What closes the pipe, and what you see
128
160
 
129
- The channel closes on the connection's `close` event or when its `close()` is called. In-flight
130
- and later calls then fail with `webrun-streams`' `TransportClosedError`. On the serving side each
131
- inbound connection gets its own mux, created when the connection opens and closed when the
132
- connection closes. A connection that arrives without `serialization: "raw"` makes the adapter
133
- throw the `TypeError` above inside the connection's `open` handler, and that connection is not
134
- served.
161
+ `signal` aborts on the connection's `close` event (`webrun-streams-peerjs: the connection
162
+ closed`), on its `error` event (`webrun-streams-peerjs: the connection failed: <message>`), on an
163
+ oversized post, or on inbound data that is not bytes. `overPipe` closes the multiplexer on it,
164
+ which fails every call in flight.
135
165
 
136
- The serve teardown removes the `connection` listener and closes every mux it created. Muxes are
137
- kept in a list until then, including those whose connection already closed.
166
+ `target.close()` waits up to 5 s for PeerJS's queue and the data channel's `bufferedAmount` to
167
+ empty before calling `conn.close()`, because `conn.close()` tears the peer connection down at once
168
+ and discards what they still hold, the multiplexer's last close envelopes among it.
169
+ `whenDrained()` polls the same two (neither reports emptying) every 5 ms and resolves once
170
+ PeerJS's queue is empty and `bufferedAmount` is at most `DRAIN_LOW_WATER`, or the pipe ended.
138
171
 
139
172
  ### Conformance runs in a browser against a local broker
140
173
 
@@ -143,19 +176,25 @@ pnpm --filter @statewalker/webrun-streams-peerjs test:browser # runs the suite
143
176
  pnpm --filter @statewalker/webrun-streams-peerjs test # reports it skipped
144
177
  ```
145
178
 
146
- The `@statewalker/webrun-streams-conformance` suite runs in headless Chromium through Playwright.
179
+ The `@statewalker/webrun-streams-conformance` suite runs in headless Chromium through Playwright,
180
+ over the port stack (`overPipe` + `msgpackCodec`, with the pipe's 16 KiB-safe `maxMessageSize`, so
181
+ L6's 256 KiB body crosses as chunks under the cross-browser frame limit). L6 asserts the port
182
+ stack's bound: a consumer that stops reading lets the producer get at most one 4 KiB chunk ahead (measured 0).
147
183
  A Vitest global setup starts the reference broker (the [`peer`](https://www.npmjs.com/package/peer)
148
184
  package's `PeerServer`) on a loopback port in a child process, so runs need no internet access.
149
185
  The broker runs out of process because, hosted in-process, it keeps the test run alive after the
150
186
  last test: its `close()` waits on the browser's WebSockets and it holds client-expiry timers with
151
187
  no public way to clear them. Under plain `pnpm test` (Node) the suite is skipped: the full PeerJS
152
- handshake hangs there.
188
+ handshake hangs there. The browser run also includes the message-ceiling measurement.
189
+ `message-target.test.ts` runs in Node against a structural fake connection and pins the pipe's
190
+ contract.
153
191
 
154
192
  ### Dependencies
155
193
 
156
- - `@statewalker/webrun-streams` (runtime): the `Duplex` / `Connect` / `Serve` / `ByteChannel`
157
- types and `emulateMux`.
158
- - `peerjs` (peer): you supply and own the `Peer`.
194
+ - `peerjs` (peer): you supply and own the `Peer`. `src/` imports only its `DataConnection` type.
195
+ - Nothing from this repository at runtime: the target is a `MessageTarget` by shape.
196
+ `@statewalker/webrun-rpc`, `@statewalker/webrun-msgpack` and `@statewalker/webrun-streams` are
197
+ dev dependencies of the tests; consumers supply their own `webrun-rpc` and codec.
159
198
  - Dev only: `peer` (the local broker), `@vitest/browser-playwright` and `playwright` (the browser
160
199
  run), `@statewalker/webrun-streams-conformance` (the suite).
161
200
 
package/dist/index.d.ts CHANGED
@@ -1,3 +1,2 @@
1
- export { byteChannelFromPeerJs } from "./byte-channel.js";
2
- export { type ConnectPeerJsParams, connect, type ServePeerJsParams, serve, } from "./connect-serve.js";
1
+ export { DEFAULT_MAX_FRAME_BYTES, DEFAULT_MAX_MESSAGE_SIZE, DRAIN_LOW_WATER, type MessageTargetOverPeerJsOptions, messageTargetOverPeerJs, type PeerJsMessageTarget, } from "./message-target.js";
3
2
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EACL,KAAK,mBAAmB,EACxB,OAAO,EACP,KAAK,iBAAiB,EACtB,KAAK,GACN,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,wBAAwB,EACxB,eAAe,EACf,KAAK,8BAA8B,EACnC,uBAAuB,EACvB,KAAK,mBAAmB,GACzB,MAAM,qBAAqB,CAAC"}
package/dist/index.js CHANGED
@@ -1,133 +1,143 @@
1
- import { emulateMux } from "@statewalker/webrun-streams";
2
- //#region src/byte-channel.ts
1
+ //#region src/message-target.ts
3
2
  /**
4
- * Wrap an open PeerJS `DataConnection` into a `ByteChannel`. The connection
5
- * MUST be constructed with `{ serialization: "raw" }` so payloads arrive as
6
- * `Uint8Array` rather than PeerJS's own JSON envelopes.
3
+ * The largest message a raw `DataConnection` delivers between any two
4
+ * browsers: PeerJS records Firefox-to-Chrome messages "cut off after 16384
5
+ * bytes", and `-webrtc` chunks to the same 16 KiB. Chromium to Chromium
6
+ * carries up to 256 KiB, and one byte past that is measured to arrive as
7
+ * nothing at all, with no error on either side and the connection closed
8
+ * (`tests/message-ceiling.test.ts`). Raise it with `maxFrameBytes` only for
9
+ * peers known to allow more.
7
10
  */
8
- function byteChannelFromPeerJs(conn) {
11
+ const DEFAULT_MAX_FRAME_BYTES = 16384;
12
+ /**
13
+ * The margin spec D10 asks for: the port stack's framing adds up to 134 bytes
14
+ * (measured 123-128) on top of each payload, so payloads stay 256 below the
15
+ * frame limit.
16
+ */
17
+ const FRAMING_MARGIN = 256;
18
+ /** `DEFAULT_MAX_FRAME_BYTES` less the framing margin: what to give `overPipe`. */
19
+ const DEFAULT_MAX_MESSAGE_SIZE = 16128;
20
+ /** How often `whenDrained` looks: neither PeerJS's queue nor `bufferedAmount` reports emptying. */
21
+ const DRAIN_POLL_MS = 5;
22
+ /**
23
+ * `whenDrained` resolves once PeerJS's own queue is empty and the data
24
+ * channel's `bufferedAmount` is at most this: the channel can take more.
25
+ * Waiting for zero would pause a sender that waits before every frame.
26
+ */
27
+ const DRAIN_LOW_WATER = 262144;
28
+ /** How long `close()` waits for queued messages to be written out. */
29
+ const CLOSE_FLUSH_MS = 5e3;
30
+ /**
31
+ * One open PeerJS `DataConnection` as a pipe of messages, for a multiplexer to
32
+ * run over:
33
+ *
34
+ * ```ts
35
+ * const { target, signal, maxMessageSize } = messageTargetOverPeerJs(conn);
36
+ * const { call } = await connect({
37
+ * mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal, maxMessageSize }),
38
+ * });
39
+ * ```
40
+ *
41
+ * The connection must be open, use `serialization: "raw"` (PeerJS hands each
42
+ * message to the data channel unchanged) and be `reliable` (ordered); anything
43
+ * else throws. Inbound messages arrive
44
+ * as `Uint8Array` copies. Anything else (a `Blob`, a string) ends the pipe
45
+ * with a `TypeError`: dropping it would lose an envelope and hang its call.
46
+ */
47
+ function messageTargetOverPeerJs(conn, options = {}) {
9
48
  const serialization = conn.serialization;
10
- if (serialization !== "raw") throw new TypeError(`byteChannelFromPeerJs: DataConnection serialization is '${serialization}', expected 'raw'`);
11
- let closedResolve;
12
- const closed = new Promise((r) => {
13
- closedResolve = r;
14
- });
15
- let isClosed = false;
16
- const queue = [];
17
- let pending = null;
18
- const deliver = (bytes) => {
19
- if (isClosed) return;
20
- if (pending) {
21
- const r = pending;
22
- pending = null;
23
- r({
24
- value: bytes,
25
- done: false
26
- });
27
- } else queue.push(bytes);
28
- };
49
+ if (serialization !== "raw") throw new TypeError(`messageTargetOverPeerJs: DataConnection serialization is '${serialization}', expected 'raw'`);
50
+ if (conn.reliable !== true) throw new TypeError("messageTargetOverPeerJs: DataConnection must be opened with `reliable: true` (ordered delivery)");
51
+ if (!conn.open) throw new Error("messageTargetOverPeerJs: DataConnection is not open; wait for its `open` event");
52
+ const maxFrameBytes = options.maxFrameBytes ?? 16384;
53
+ const maxMessageSize = options.maxMessageSize ?? maxFrameBytes - FRAMING_MARGIN;
54
+ const listeners = /* @__PURE__ */ new Set();
55
+ const life = new AbortController();
56
+ const internals = conn;
29
57
  const onData = (data) => {
30
- if (data instanceof Uint8Array) {
31
- deliver(new Uint8Array(data));
32
- return;
33
- }
34
- if (data instanceof ArrayBuffer) {
35
- deliver(new Uint8Array(data));
58
+ if (life.signal.aborted) return;
59
+ const bytes = copyBytes(data);
60
+ if (!bytes) {
61
+ end(/* @__PURE__ */ new TypeError(`webrun-streams-peerjs: a message arrived as ${Object.prototype.toString.call(data)}, not bytes`));
62
+ closeConn();
36
63
  return;
37
64
  }
38
- if (ArrayBuffer.isView(data)) {
39
- const view = data;
40
- deliver(new Uint8Array(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength)));
41
- return;
42
- }
43
- if (typeof Blob !== "undefined" && data instanceof Blob) data.arrayBuffer().then((buf) => deliver(new Uint8Array(buf)));
65
+ const event = new MessageEvent("message", { data: bytes });
66
+ for (const listener of [...listeners]) try {
67
+ Promise.resolve(listener(event)).catch(() => void 0);
68
+ } catch {}
44
69
  };
45
- const onClose = () => {
46
- if (isClosed) return;
47
- isClosed = true;
70
+ const end = (reason) => {
71
+ if (life.signal.aborted) return;
48
72
  conn.off("data", onData);
49
73
  conn.off("close", onClose);
50
- if (pending) {
51
- const r = pending;
52
- pending = null;
53
- r({
54
- value: void 0,
55
- done: true
56
- });
57
- }
58
- closedResolve();
74
+ conn.off("error", onError);
75
+ life.abort(reason);
59
76
  };
77
+ const onClose = () => end(/* @__PURE__ */ new Error("webrun-streams-peerjs: the connection closed"));
78
+ const onError = (err) => end(new Error(`webrun-streams-peerjs: the connection failed: ${err?.message ?? String(err)}`, { cause: err }));
60
79
  conn.on("data", onData);
61
80
  conn.on("close", onClose);
81
+ conn.on("error", onError);
82
+ const closeConn = () => {
83
+ try {
84
+ conn.close();
85
+ } catch {}
86
+ };
62
87
  return {
63
- send(bytes) {
64
- if (isClosed) return;
65
- if (!conn.open) return;
66
- conn.send(bytes);
67
- },
68
- recv: { [Symbol.asyncIterator]() {
69
- return { next() {
70
- if (queue.length > 0) return Promise.resolve({
71
- value: queue.shift(),
72
- done: false
73
- });
74
- if (isClosed) return Promise.resolve({
75
- value: void 0,
76
- done: true
77
- });
88
+ signal: life.signal,
89
+ maxMessageSize,
90
+ target: {
91
+ addEventListener: (_type, listener) => {
92
+ listeners.add(listener);
93
+ },
94
+ removeEventListener: (_type, listener) => {
95
+ listeners.delete(listener);
96
+ },
97
+ postMessage(message) {
98
+ const bytes = viewBytes(message);
99
+ if (!bytes) throw new TypeError(`webrun-streams-peerjs: a byte pipe carries Uint8Array, ArrayBuffer or a view, got ${Object.prototype.toString.call(message)}`);
100
+ if (life.signal.aborted || !conn.open) return;
101
+ if (bytes.byteLength > maxFrameBytes) {
102
+ const err = /* @__PURE__ */ new RangeError(`webrun-streams-peerjs: a ${bytes.byteLength}-byte message exceeds maxFrameBytes (${maxFrameBytes}); the data channel would drop it silently`);
103
+ end(err);
104
+ closeConn();
105
+ throw err;
106
+ }
107
+ conn.send(bytes.slice());
108
+ },
109
+ async close() {
110
+ listeners.clear();
111
+ const deadline = Date.now() + CLOSE_FLUSH_MS;
112
+ while (!life.signal.aborted && Date.now() < deadline && ((internals.bufferSize ?? 0) > 0 || (internals.dataChannel?.bufferedAmount ?? 0) > 0)) await new Promise((resolve) => setTimeout(resolve, DRAIN_POLL_MS));
113
+ end(/* @__PURE__ */ new Error("webrun-streams-peerjs: closed locally"));
114
+ closeConn();
115
+ },
116
+ get bufferedAmount() {
117
+ return internals.dataChannel?.bufferedAmount ?? 0;
118
+ },
119
+ whenDrained() {
78
120
  return new Promise((resolve) => {
79
- pending = resolve;
121
+ const check = () => {
122
+ const idle = !(internals.bufferSize ?? 0) && (internals.dataChannel?.bufferedAmount ?? 0) <= 262144;
123
+ if (life.signal.aborted || idle) resolve();
124
+ else setTimeout(check, DRAIN_POLL_MS).unref?.();
125
+ };
126
+ check();
80
127
  });
81
- } };
82
- } },
83
- closed,
84
- close() {
85
- try {
86
- conn.close();
87
- } catch {}
88
- onClose();
128
+ }
89
129
  }
90
130
  };
91
131
  }
132
+ function viewBytes(data) {
133
+ if (data instanceof Uint8Array) return data;
134
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
135
+ if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
136
+ }
137
+ /** A copy: PeerJS may reuse the buffer it hands out. */
138
+ function copyBytes(data) {
139
+ const view = viewBytes(data);
140
+ return view ? view.slice() : void 0;
141
+ }
92
142
  //#endregion
93
- //#region src/connect-serve.ts
94
- const connect = async ({ conn, mux: muxOpts }) => {
95
- const channel = byteChannelFromPeerJs(conn);
96
- const mux = emulateMux(channel, {
97
- ...muxOpts,
98
- side: "initiator"
99
- });
100
- return {
101
- call: mux.call,
102
- async close() {
103
- await mux.close();
104
- }
105
- };
106
- };
107
- const serve = async ({ peer, mux: muxOpts }, handler) => {
108
- const muxes = [];
109
- const onConnection = (conn) => {
110
- const ready = () => {
111
- const channel = byteChannelFromPeerJs(conn);
112
- const mux = emulateMux(channel, {
113
- ...muxOpts,
114
- side: "responder"
115
- });
116
- mux.serve(handler);
117
- muxes.push(mux);
118
- channel.closed.then(() => mux.close());
119
- };
120
- if (conn.open) ready();
121
- else conn.on("open", ready);
122
- };
123
- peer.on("connection", onConnection);
124
- let torn = false;
125
- return async () => {
126
- if (torn) return;
127
- torn = true;
128
- peer.off("connection", onConnection);
129
- await Promise.all(muxes.map((m) => m.close()));
130
- };
131
- };
132
- //#endregion
133
- export { byteChannelFromPeerJs, connect, serve };
143
+ export { DEFAULT_MAX_FRAME_BYTES, DEFAULT_MAX_MESSAGE_SIZE, DRAIN_LOW_WATER, messageTargetOverPeerJs };
@@ -0,0 +1,76 @@
1
+ import type { DataConnection } from "peerjs";
2
+ type Listener = (event: MessageEvent) => void | Promise<void>;
3
+ /**
4
+ * The largest message a raw `DataConnection` delivers between any two
5
+ * browsers: PeerJS records Firefox-to-Chrome messages "cut off after 16384
6
+ * bytes", and `-webrtc` chunks to the same 16 KiB. Chromium to Chromium
7
+ * carries up to 256 KiB, and one byte past that is measured to arrive as
8
+ * nothing at all, with no error on either side and the connection closed
9
+ * (`tests/message-ceiling.test.ts`). Raise it with `maxFrameBytes` only for
10
+ * peers known to allow more.
11
+ */
12
+ export declare const DEFAULT_MAX_FRAME_BYTES: number;
13
+ /** `DEFAULT_MAX_FRAME_BYTES` less the framing margin: what to give `overPipe`. */
14
+ export declare const DEFAULT_MAX_MESSAGE_SIZE: number;
15
+ /**
16
+ * `whenDrained` resolves once PeerJS's own queue is empty and the data
17
+ * channel's `bufferedAmount` is at most this: the channel can take more.
18
+ * Waiting for zero would pause a sender that waits before every frame.
19
+ */
20
+ export declare const DRAIN_LOW_WATER: number;
21
+ export interface MessageTargetOverPeerJsOptions {
22
+ /**
23
+ * The largest message the connection carries. A post past it ends the pipe
24
+ * with a `RangeError` rather than letting the data channel drop it
25
+ * silently. Default {@link DEFAULT_MAX_FRAME_BYTES}.
26
+ */
27
+ maxFrameBytes?: number;
28
+ /** The payload ceiling to report. Default `maxFrameBytes` less 256. */
29
+ maxMessageSize?: number;
30
+ }
31
+ /** What `messageTargetOverPeerJs` gives: a pipe of bytes, its life, and its payload ceiling. */
32
+ export interface PeerJsMessageTarget {
33
+ /**
34
+ * A `MessageTarget` (as `@statewalker/webrun-rpc` defines it) whose messages
35
+ * are `Uint8Array`s, one data channel message each.
36
+ */
37
+ target: {
38
+ addEventListener(type: "message", listener: Listener): void;
39
+ removeEventListener(type: "message", listener: Listener): void;
40
+ /** Sends one message. `TypeError` for non-bytes; `RangeError`, ending the pipe, past `maxFrameBytes`. */
41
+ postMessage(message: unknown): void;
42
+ /** Closes the connection. */
43
+ close(): Promise<void>;
44
+ /** The data channel's `bufferedAmount`. */
45
+ readonly bufferedAmount: number;
46
+ /** Resolves once PeerJS's own queue is empty and `bufferedAmount` is at most {@link DRAIN_LOW_WATER}, or the pipe ended. */
47
+ whenDrained(): Promise<void>;
48
+ };
49
+ /**
50
+ * Aborts when the connection closes or fails, or a post exceeds
51
+ * `maxFrameBytes`. Pass it as `overPipe`'s `signal`.
52
+ */
53
+ signal: AbortSignal;
54
+ /** Pass as `overPipe`'s `maxMessageSize`, so bodies are chunked under the frame limit. */
55
+ maxMessageSize: number;
56
+ }
57
+ /**
58
+ * One open PeerJS `DataConnection` as a pipe of messages, for a multiplexer to
59
+ * run over:
60
+ *
61
+ * ```ts
62
+ * const { target, signal, maxMessageSize } = messageTargetOverPeerJs(conn);
63
+ * const { call } = await connect({
64
+ * mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal, maxMessageSize }),
65
+ * });
66
+ * ```
67
+ *
68
+ * The connection must be open, use `serialization: "raw"` (PeerJS hands each
69
+ * message to the data channel unchanged) and be `reliable` (ordered); anything
70
+ * else throws. Inbound messages arrive
71
+ * as `Uint8Array` copies. Anything else (a `Blob`, a string) ends the pipe
72
+ * with a `TypeError`: dropping it would lose an envelope and hang its call.
73
+ */
74
+ export declare function messageTargetOverPeerJs(conn: DataConnection, options?: MessageTargetOverPeerJsOptions): PeerJsMessageTarget;
75
+ export {};
76
+ //# 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,KAAK,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAE7C,KAAK,QAAQ,GAAG,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE9D;;;;;;;;GAQG;AACH,eAAO,MAAM,uBAAuB,QAAY,CAAC;AASjD,kFAAkF;AAClF,eAAO,MAAM,wBAAwB,QAA2C,CAAC;AAIjF;;;;GAIG;AACH,eAAO,MAAM,eAAe,QAAa,CAAC;AAI1C,MAAM,WAAW,8BAA8B;IAC7C;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,uEAAuE;IACvE,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,gGAAgG;AAChG,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,MAAM,EAAE;QACN,gBAAgB,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;QAC5D,mBAAmB,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;QAC/D,yGAAyG;QACzG,WAAW,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;QACpC,6BAA6B;QAC7B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;QACvB,2CAA2C;QAC3C,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;QAChC,4HAA4H;QAC5H,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;KAC9B,CAAC;IACF;;;OAGG;IACH,MAAM,EAAE,WAAW,CAAC;IACpB,0FAA0F;IAC1F,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,uBAAuB,CACrC,IAAI,EAAE,cAAc,EACpB,OAAO,GAAE,8BAAmC,GAC3C,mBAAmB,CAwIrB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statewalker/webrun-streams-peerjs",
3
- "version": "0.2.3",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "PeerJS DataConnection-backed Connect/Serve adapter in the webrun-streams-* family",
@@ -29,9 +29,6 @@
29
29
  "dist",
30
30
  "src"
31
31
  ],
32
- "dependencies": {
33
- "@statewalker/webrun-streams": "^0.2.2"
34
- },
35
32
  "peerDependencies": {
36
33
  "peerjs": "^1.5.5"
37
34
  },
@@ -39,15 +36,18 @@
39
36
  "@biomejs/biome": "^2.5.15",
40
37
  "@roamhq/wrtc": "^0.10.0",
41
38
  "@types/node": "^26.6.4",
42
- "@vitest/browser-playwright": "^5.0.3",
39
+ "@vitest/browser-playwright": "^5.0.5",
43
40
  "peer": "^1.0.2",
44
41
  "peerjs": "^1.5.5",
45
42
  "playwright": "^1.63.0",
46
43
  "rimraf": "^6.1.3",
47
44
  "rolldown": "^1.2.12",
48
45
  "typescript": "^7.0.2",
49
- "vitest": "^5.0.3",
50
- "@statewalker/webrun-streams-conformance": "^0.3.2"
46
+ "vitest": "^5.0.5",
47
+ "@statewalker/webrun-msgpack": "^0.10.0",
48
+ "@statewalker/webrun-rpc": "^0.11.0",
49
+ "@statewalker/webrun-streams": "^0.3.0",
50
+ "@statewalker/webrun-streams-conformance": "^0.4.0"
51
51
  },
52
52
  "sideEffects": false,
53
53
  "publishConfig": {
package/src/index.ts CHANGED
@@ -1,7 +1,8 @@
1
- export { byteChannelFromPeerJs } from "./byte-channel.js";
2
1
  export {
3
- type ConnectPeerJsParams,
4
- connect,
5
- type ServePeerJsParams,
6
- serve,
7
- } from "./connect-serve.js";
2
+ DEFAULT_MAX_FRAME_BYTES,
3
+ DEFAULT_MAX_MESSAGE_SIZE,
4
+ DRAIN_LOW_WATER,
5
+ type MessageTargetOverPeerJsOptions,
6
+ messageTargetOverPeerJs,
7
+ type PeerJsMessageTarget,
8
+ } from "./message-target.js";
@@ -0,0 +1,245 @@
1
+ import type { DataConnection } from "peerjs";
2
+
3
+ type Listener = (event: MessageEvent) => void | Promise<void>;
4
+
5
+ /**
6
+ * The largest message a raw `DataConnection` delivers between any two
7
+ * browsers: PeerJS records Firefox-to-Chrome messages "cut off after 16384
8
+ * bytes", and `-webrtc` chunks to the same 16 KiB. Chromium to Chromium
9
+ * carries up to 256 KiB, and one byte past that is measured to arrive as
10
+ * nothing at all, with no error on either side and the connection closed
11
+ * (`tests/message-ceiling.test.ts`). Raise it with `maxFrameBytes` only for
12
+ * peers known to allow more.
13
+ */
14
+ export const DEFAULT_MAX_FRAME_BYTES = 16 * 1024;
15
+
16
+ /**
17
+ * The margin spec D10 asks for: the port stack's framing adds up to 134 bytes
18
+ * (measured 123-128) on top of each payload, so payloads stay 256 below the
19
+ * frame limit.
20
+ */
21
+ const FRAMING_MARGIN = 256;
22
+
23
+ /** `DEFAULT_MAX_FRAME_BYTES` less the framing margin: what to give `overPipe`. */
24
+ export const DEFAULT_MAX_MESSAGE_SIZE = DEFAULT_MAX_FRAME_BYTES - FRAMING_MARGIN;
25
+
26
+ /** How often `whenDrained` looks: neither PeerJS's queue nor `bufferedAmount` reports emptying. */
27
+ const DRAIN_POLL_MS = 5;
28
+ /**
29
+ * `whenDrained` resolves once PeerJS's own queue is empty and the data
30
+ * channel's `bufferedAmount` is at most this: the channel can take more.
31
+ * Waiting for zero would pause a sender that waits before every frame.
32
+ */
33
+ export const DRAIN_LOW_WATER = 256 * 1024;
34
+ /** How long `close()` waits for queued messages to be written out. */
35
+ const CLOSE_FLUSH_MS = 5000;
36
+
37
+ export interface MessageTargetOverPeerJsOptions {
38
+ /**
39
+ * The largest message the connection carries. A post past it ends the pipe
40
+ * with a `RangeError` rather than letting the data channel drop it
41
+ * silently. Default {@link DEFAULT_MAX_FRAME_BYTES}.
42
+ */
43
+ maxFrameBytes?: number;
44
+ /** The payload ceiling to report. Default `maxFrameBytes` less 256. */
45
+ maxMessageSize?: number;
46
+ }
47
+
48
+ /** What `messageTargetOverPeerJs` gives: a pipe of bytes, its life, and its payload ceiling. */
49
+ export interface PeerJsMessageTarget {
50
+ /**
51
+ * A `MessageTarget` (as `@statewalker/webrun-rpc` defines it) whose messages
52
+ * are `Uint8Array`s, one data channel message each.
53
+ */
54
+ target: {
55
+ addEventListener(type: "message", listener: Listener): void;
56
+ removeEventListener(type: "message", listener: Listener): void;
57
+ /** Sends one message. `TypeError` for non-bytes; `RangeError`, ending the pipe, past `maxFrameBytes`. */
58
+ postMessage(message: unknown): void;
59
+ /** Closes the connection. */
60
+ close(): Promise<void>;
61
+ /** The data channel's `bufferedAmount`. */
62
+ readonly bufferedAmount: number;
63
+ /** Resolves once PeerJS's own queue is empty and `bufferedAmount` is at most {@link DRAIN_LOW_WATER}, or the pipe ended. */
64
+ whenDrained(): Promise<void>;
65
+ };
66
+ /**
67
+ * Aborts when the connection closes or fails, or a post exceeds
68
+ * `maxFrameBytes`. Pass it as `overPipe`'s `signal`.
69
+ */
70
+ signal: AbortSignal;
71
+ /** Pass as `overPipe`'s `maxMessageSize`, so bodies are chunked under the frame limit. */
72
+ maxMessageSize: number;
73
+ }
74
+
75
+ /**
76
+ * One open PeerJS `DataConnection` as a pipe of messages, for a multiplexer to
77
+ * run over:
78
+ *
79
+ * ```ts
80
+ * const { target, signal, maxMessageSize } = messageTargetOverPeerJs(conn);
81
+ * const { call } = await connect({
82
+ * mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal, maxMessageSize }),
83
+ * });
84
+ * ```
85
+ *
86
+ * The connection must be open, use `serialization: "raw"` (PeerJS hands each
87
+ * message to the data channel unchanged) and be `reliable` (ordered); anything
88
+ * else throws. Inbound messages arrive
89
+ * as `Uint8Array` copies. Anything else (a `Blob`, a string) ends the pipe
90
+ * with a `TypeError`: dropping it would lose an envelope and hang its call.
91
+ */
92
+ export function messageTargetOverPeerJs(
93
+ conn: DataConnection,
94
+ options: MessageTargetOverPeerJsOptions = {},
95
+ ): PeerJsMessageTarget {
96
+ const serialization = (conn as unknown as { serialization?: string }).serialization;
97
+ if (serialization !== "raw") {
98
+ throw new TypeError(
99
+ `messageTargetOverPeerJs: DataConnection serialization is '${serialization}', expected 'raw'`,
100
+ );
101
+ }
102
+ // PeerJS's default `reliable: false` means `ordered: false`: envelopes would
103
+ // arrive out of order and corrupt every stream without an error.
104
+ if ((conn as unknown as { reliable?: boolean }).reliable !== true) {
105
+ throw new TypeError(
106
+ "messageTargetOverPeerJs: DataConnection must be opened with `reliable: true` (ordered delivery)",
107
+ );
108
+ }
109
+ // Not yet open, posts would be dropped; already closed, `close` has fired and
110
+ // the signal would never abort. Either way calls would hang.
111
+ if (!conn.open) {
112
+ throw new Error(
113
+ "messageTargetOverPeerJs: DataConnection is not open; wait for its `open` event",
114
+ );
115
+ }
116
+ const maxFrameBytes = options.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
117
+ const maxMessageSize = options.maxMessageSize ?? maxFrameBytes - FRAMING_MARGIN;
118
+ const listeners = new Set<Listener>();
119
+ const life = new AbortController();
120
+ const internals = conn as unknown as {
121
+ bufferSize?: number;
122
+ dataChannel?: { bufferedAmount?: number };
123
+ };
124
+
125
+ const onData = (data: unknown): void => {
126
+ if (life.signal.aborted) return;
127
+ const bytes = copyBytes(data);
128
+ if (!bytes) {
129
+ // Dropping it would lose a multiplexer envelope and hang its call: fail loudly.
130
+ end(
131
+ new TypeError(
132
+ `webrun-streams-peerjs: a message arrived as ${Object.prototype.toString.call(data)}, not bytes`,
133
+ ),
134
+ );
135
+ closeConn();
136
+ return;
137
+ }
138
+ const event = new MessageEvent("message", { data: bytes });
139
+ for (const listener of [...listeners]) {
140
+ try {
141
+ Promise.resolve(listener(event)).catch(() => undefined);
142
+ } catch {}
143
+ }
144
+ };
145
+ const end = (reason: Error): void => {
146
+ if (life.signal.aborted) return;
147
+ conn.off("data", onData);
148
+ conn.off("close", onClose);
149
+ conn.off("error", onError);
150
+ life.abort(reason);
151
+ };
152
+ const onClose = (): void => end(new Error("webrun-streams-peerjs: the connection closed"));
153
+ const onError = (err: unknown): void =>
154
+ end(
155
+ new Error(
156
+ `webrun-streams-peerjs: the connection failed: ${(err as Error)?.message ?? String(err)}`,
157
+ { cause: err },
158
+ ),
159
+ );
160
+ conn.on("data", onData);
161
+ conn.on("close", onClose);
162
+ conn.on("error", onError);
163
+ const closeConn = (): void => {
164
+ try {
165
+ conn.close();
166
+ } catch {}
167
+ };
168
+
169
+ return {
170
+ signal: life.signal,
171
+ maxMessageSize,
172
+ target: {
173
+ addEventListener: (_type, listener) => {
174
+ listeners.add(listener);
175
+ },
176
+ removeEventListener: (_type, listener) => {
177
+ listeners.delete(listener);
178
+ },
179
+ postMessage(message) {
180
+ const bytes = viewBytes(message);
181
+ if (!bytes) {
182
+ throw new TypeError(
183
+ `webrun-streams-peerjs: a byte pipe carries Uint8Array, ArrayBuffer or a view, got ${Object.prototype.toString.call(message)}`,
184
+ );
185
+ }
186
+ if (life.signal.aborted || !conn.open) return; // `signal` says so
187
+ if (bytes.byteLength > maxFrameBytes) {
188
+ const err = new RangeError(
189
+ `webrun-streams-peerjs: a ${bytes.byteLength}-byte message exceeds maxFrameBytes (${maxFrameBytes}); the data channel would drop it silently`,
190
+ );
191
+ end(err);
192
+ closeConn();
193
+ throw err;
194
+ }
195
+ // A copy: PeerJS may queue the message past its own buffer threshold.
196
+ conn.send(bytes.slice());
197
+ },
198
+ async close() {
199
+ listeners.clear();
200
+ // `conn.close()` tears the peer connection down at once, discarding what
201
+ // PeerJS and the data channel still hold — the multiplexer's last close
202
+ // envelopes among it. Let that go out first, for at most CLOSE_FLUSH_MS.
203
+ const deadline = Date.now() + CLOSE_FLUSH_MS;
204
+ while (
205
+ !life.signal.aborted &&
206
+ Date.now() < deadline &&
207
+ ((internals.bufferSize ?? 0) > 0 || (internals.dataChannel?.bufferedAmount ?? 0) > 0)
208
+ ) {
209
+ await new Promise((resolve) => setTimeout(resolve, DRAIN_POLL_MS));
210
+ }
211
+ end(new Error("webrun-streams-peerjs: closed locally"));
212
+ closeConn();
213
+ },
214
+ get bufferedAmount() {
215
+ return internals.dataChannel?.bufferedAmount ?? 0;
216
+ },
217
+ whenDrained() {
218
+ return new Promise<void>((resolve) => {
219
+ const check = (): void => {
220
+ const idle =
221
+ !(internals.bufferSize ?? 0) &&
222
+ (internals.dataChannel?.bufferedAmount ?? 0) <= DRAIN_LOW_WATER;
223
+ if (life.signal.aborted || idle) resolve();
224
+ else (setTimeout(check, DRAIN_POLL_MS) as { unref?: () => void }).unref?.();
225
+ };
226
+ check();
227
+ });
228
+ },
229
+ },
230
+ };
231
+ }
232
+
233
+ function viewBytes(data: unknown): Uint8Array | undefined {
234
+ if (data instanceof Uint8Array) return data;
235
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
236
+ if (ArrayBuffer.isView(data))
237
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
238
+ return undefined;
239
+ }
240
+
241
+ /** A copy: PeerJS may reuse the buffer it hands out. */
242
+ function copyBytes(data: unknown): Uint8Array | undefined {
243
+ const view = viewBytes(data);
244
+ return view ? view.slice() : undefined;
245
+ }
@@ -1,9 +0,0 @@
1
- import type { ByteChannel } from "@statewalker/webrun-streams";
2
- import type { DataConnection } from "peerjs";
3
- /**
4
- * Wrap an open PeerJS `DataConnection` into a `ByteChannel`. The connection
5
- * MUST be constructed with `{ serialization: "raw" }` so payloads arrive as
6
- * `Uint8Array` rather than PeerJS's own JSON envelopes.
7
- */
8
- export declare function byteChannelFromPeerJs(conn: DataConnection): ByteChannel;
9
- //# 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,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC/D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAE7C;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,cAAc,GAAG,WAAW,CAuGvE"}
@@ -1,29 +0,0 @@
1
- import { type Connect, type EmulateMuxOptions, type Serve } from "@statewalker/webrun-streams";
2
- import type { DataConnection, Peer } from "peerjs";
3
- export interface ConnectPeerJsParams {
4
- /** Already-open `DataConnection` with `serialization: "raw"`. */
5
- conn: DataConnection;
6
- /**
7
- * Flow-control tuning forwarded to `emulateMux` — `mtu` and
8
- * `maxStreamBuffer`, which is the credit this side advertises. `side` here
9
- * wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
10
- * suite's L6 uses this to run at a window small enough that a sender
11
- * genuinely stalls.
12
- */
13
- mux?: EmulateMuxOptions;
14
- }
15
- export interface ServePeerJsParams {
16
- /** Connected `Peer`. The adapter listens for inbound `DataConnection`s. */
17
- peer: Peer;
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
- export declare const connect: Connect<ConnectPeerJsParams>;
28
- export declare const serve: Serve<ServePeerJsParams>;
29
- //# sourceMappingURL=connect-serve.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"connect-serve.d.ts","sourceRoot":"","sources":["../src/connect-serve.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,OAAO,EAEZ,KAAK,iBAAiB,EAEtB,KAAK,KAAK,EACX,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAGnD,MAAM,WAAW,mBAAmB;IAClC,iEAAiE;IACjE,IAAI,EAAE,cAAc,CAAC;IACrB;;;;;;OAMG;IACH,GAAG,CAAC,EAAE,iBAAiB,CAAC;CACzB;AAED,MAAM,WAAW,iBAAiB;IAChC,2EAA2E;IAC3E,IAAI,EAAE,IAAI,CAAC;IACX;;;;;;OAMG;IACH,GAAG,CAAC,EAAE,iBAAiB,CAAC;CACzB;AAED,eAAO,MAAM,OAAO,EAAE,OAAO,CAAC,mBAAmB,CAShD,CAAC;AAEF,eAAO,MAAM,KAAK,EAAE,KAAK,CAAC,iBAAiB,CAuB1C,CAAC"}
@@ -1,112 +0,0 @@
1
- import type { ByteChannel } from "@statewalker/webrun-streams";
2
- import type { DataConnection } from "peerjs";
3
-
4
- /**
5
- * Wrap an open PeerJS `DataConnection` into a `ByteChannel`. The connection
6
- * MUST be constructed with `{ serialization: "raw" }` so payloads arrive as
7
- * `Uint8Array` rather than PeerJS's own JSON envelopes.
8
- */
9
- export function byteChannelFromPeerJs(conn: DataConnection): ByteChannel {
10
- const serialization = (conn as unknown as { serialization?: string }).serialization;
11
- if (serialization !== "raw") {
12
- throw new TypeError(
13
- `byteChannelFromPeerJs: DataConnection serialization is '${serialization}', expected 'raw'`,
14
- );
15
- }
16
-
17
- let closedResolve!: () => void;
18
- const closed = new Promise<void>((r) => {
19
- closedResolve = r;
20
- });
21
- let isClosed = false;
22
-
23
- const queue: Uint8Array[] = [];
24
- let pending: ((value: IteratorResult<Uint8Array>) => void) | null = null;
25
-
26
- const deliver = (bytes: Uint8Array): void => {
27
- if (isClosed) return;
28
- if (pending) {
29
- const r = pending;
30
- pending = null;
31
- r({ value: bytes, done: false });
32
- } else {
33
- queue.push(bytes);
34
- }
35
- };
36
-
37
- const onData = (data: unknown): void => {
38
- if (data instanceof Uint8Array) {
39
- deliver(new Uint8Array(data));
40
- return;
41
- }
42
- if (data instanceof ArrayBuffer) {
43
- deliver(new Uint8Array(data));
44
- return;
45
- }
46
- if (ArrayBuffer.isView(data)) {
47
- const view = data as ArrayBufferView;
48
- deliver(
49
- new Uint8Array(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength)),
50
- );
51
- return;
52
- }
53
- if (typeof Blob !== "undefined" && data instanceof Blob) {
54
- void data.arrayBuffer().then((buf) => deliver(new Uint8Array(buf)));
55
- }
56
- };
57
-
58
- const onClose = (): void => {
59
- if (isClosed) return;
60
- isClosed = true;
61
- conn.off("data", onData);
62
- conn.off("close", onClose);
63
- if (pending) {
64
- const r = pending;
65
- pending = null;
66
- r({ value: undefined, done: true } as IteratorResult<Uint8Array>);
67
- }
68
- closedResolve();
69
- };
70
-
71
- conn.on("data", onData);
72
- conn.on("close", onClose);
73
-
74
- const recv: AsyncIterable<Uint8Array> = {
75
- [Symbol.asyncIterator]() {
76
- return {
77
- next(): Promise<IteratorResult<Uint8Array>> {
78
- if (queue.length > 0) {
79
- return Promise.resolve({ value: queue.shift() as Uint8Array, done: false });
80
- }
81
- if (isClosed) {
82
- return Promise.resolve({
83
- value: undefined,
84
- done: true,
85
- } as IteratorResult<Uint8Array>);
86
- }
87
- return new Promise<IteratorResult<Uint8Array>>((resolve) => {
88
- pending = resolve;
89
- });
90
- },
91
- };
92
- },
93
- };
94
-
95
- return {
96
- send(bytes) {
97
- if (isClosed) return;
98
- if (!conn.open) return;
99
- conn.send(bytes);
100
- },
101
- recv,
102
- closed,
103
- close() {
104
- try {
105
- conn.close();
106
- } catch {
107
- /* ignore */
108
- }
109
- onClose();
110
- },
111
- };
112
- }
@@ -1,71 +0,0 @@
1
- import {
2
- type Connect,
3
- type Duplex,
4
- type EmulateMuxOptions,
5
- emulateMux,
6
- type Serve,
7
- } from "@statewalker/webrun-streams";
8
- import type { DataConnection, Peer } from "peerjs";
9
- import { byteChannelFromPeerJs } from "./byte-channel.js";
10
-
11
- export interface ConnectPeerJsParams {
12
- /** Already-open `DataConnection` with `serialization: "raw"`. */
13
- conn: DataConnection;
14
- /**
15
- * Flow-control tuning forwarded to `emulateMux` — `mtu` and
16
- * `maxStreamBuffer`, which is the credit this side advertises. `side` here
17
- * wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
18
- * suite's L6 uses this to run at a window small enough that a sender
19
- * genuinely stalls.
20
- */
21
- mux?: EmulateMuxOptions;
22
- }
23
-
24
- export interface ServePeerJsParams {
25
- /** Connected `Peer`. The adapter listens for inbound `DataConnection`s. */
26
- peer: Peer;
27
- /**
28
- * Flow-control tuning forwarded to `emulateMux` — `mtu` and
29
- * `maxStreamBuffer`, which is the credit this side advertises. `side` here
30
- * wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
31
- * suite's L6 uses this to run at a window small enough that a sender
32
- * genuinely stalls.
33
- */
34
- mux?: EmulateMuxOptions;
35
- }
36
-
37
- export const connect: Connect<ConnectPeerJsParams> = async ({ conn, mux: muxOpts }) => {
38
- const channel = byteChannelFromPeerJs(conn);
39
- const mux = emulateMux(channel, { ...muxOpts, side: "initiator" });
40
- return {
41
- call: mux.call,
42
- async close() {
43
- await mux.close();
44
- },
45
- };
46
- };
47
-
48
- export const serve: Serve<ServePeerJsParams> = async ({ peer, mux: muxOpts }, handler: Duplex) => {
49
- const muxes: Array<{ close: () => Promise<void> }> = [];
50
-
51
- const onConnection = (conn: DataConnection): void => {
52
- const ready = (): void => {
53
- const channel = byteChannelFromPeerJs(conn);
54
- const mux = emulateMux(channel, { ...muxOpts, side: "responder" });
55
- mux.serve(handler);
56
- muxes.push(mux);
57
- void channel.closed.then(() => mux.close());
58
- };
59
- if (conn.open) ready();
60
- else conn.on("open", ready);
61
- };
62
- peer.on("connection", onConnection);
63
-
64
- let torn = false;
65
- return async () => {
66
- if (torn) return;
67
- torn = true;
68
- peer.off("connection", onConnection);
69
- await Promise.all(muxes.map((m) => m.close()));
70
- };
71
- };