@statewalker/webrun-streams-peerjs 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -192,9 +192,9 @@ contract.
192
192
  ### Dependencies
193
193
 
194
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.
195
+ - `@statewalker/webrun-streams` at runtime, for `newMessagePipe`: the pipe module every transport adapter shares (listeners, delivery, life, the byte check, the frame ceiling, drain, close), so a pipe rule is fixed once for all of them (#151). The target is a `MessageTarget` by shape and carries its own `closeSignal` and `maxMessageSize`, so `overPipe(target, { codec, side })` needs nothing else.
196
+ `@statewalker/webrun-rpc` and `@statewalker/webrun-msgpack` are dev dependencies of the tests;
197
+ consumers supply their own `webrun-rpc` and codec.
198
198
  - Dev only: `peer` (the local broker), `@vitest/browser-playwright` and `playwright` (the browser
199
199
  run), `@statewalker/webrun-streams-conformance` (the suite).
200
200
 
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { DEFAULT_DRAIN_LOW_WATER, DEFAULT_DRAIN_POLL_MS, newMessagePipe } from "@statewalker/webrun-streams";
1
2
  //#region src/message-target.ts
2
3
  /**
3
4
  * The largest message a raw `DataConnection` delivers between any two
@@ -17,14 +18,12 @@ const DEFAULT_MAX_FRAME_BYTES = 16384;
17
18
  const FRAMING_MARGIN = 256;
18
19
  /** `DEFAULT_MAX_FRAME_BYTES` less the framing margin: what to give `overPipe`. */
19
20
  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
21
  /**
23
22
  * `whenDrained` resolves once PeerJS's own queue is empty and the data
24
23
  * channel's `bufferedAmount` is at most this: the channel can take more.
25
24
  * Waiting for zero would pause a sender that waits before every frame.
26
25
  */
27
- const DRAIN_LOW_WATER = 262144;
26
+ const DRAIN_LOW_WATER = DEFAULT_DRAIN_LOW_WATER;
28
27
  /** How long `close()` waits for queued messages to be written out. */
29
28
  const CLOSE_FLUSH_MS = 5e3;
30
29
  /**
@@ -51,93 +50,39 @@ function messageTargetOverPeerJs(conn, options = {}) {
51
50
  if (!conn.open) throw new Error("messageTargetOverPeerJs: DataConnection is not open; wait for its `open` event");
52
51
  const maxFrameBytes = options.maxFrameBytes ?? 16384;
53
52
  const maxMessageSize = options.maxMessageSize ?? maxFrameBytes - FRAMING_MARGIN;
54
- const listeners = /* @__PURE__ */ new Set();
55
- const life = new AbortController();
56
53
  const internals = conn;
57
- const onData = (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();
63
- return;
54
+ const held = () => (internals.bufferSize ?? 0) > 0 || (internals.dataChannel?.bufferedAmount ?? 0) > 0;
55
+ const onData = (data) => control.deliver(data);
56
+ const onClose = () => control.end(/* @__PURE__ */ new Error("webrun-streams-peerjs: the connection closed"));
57
+ const onError = (err) => control.end(new Error(`webrun-streams-peerjs: the connection failed: ${err?.message ?? String(err)}`, { cause: err }), true);
58
+ const control = newMessagePipe({
59
+ send: (bytes) => conn.send(bytes),
60
+ canSend: () => conn.open,
61
+ bufferedAmount: () => internals.dataChannel?.bufferedAmount ?? 0,
62
+ isDrained: () => !(internals.bufferSize ?? 0) && (internals.dataChannel?.bufferedAmount ?? 0) <= DRAIN_LOW_WATER,
63
+ flush: async () => {
64
+ const deadline = Date.now() + CLOSE_FLUSH_MS;
65
+ while (!control.ended && Date.now() < deadline && held()) await new Promise((resolve) => setTimeout(resolve, DEFAULT_DRAIN_POLL_MS));
66
+ },
67
+ close: (local) => {
68
+ conn.off("data", onData);
69
+ conn.off("close", onClose);
70
+ conn.off("error", onError);
71
+ if (local) try {
72
+ conn.close();
73
+ } catch {}
64
74
  }
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 {}
69
- };
70
- const end = (reason) => {
71
- if (life.signal.aborted) return;
72
- conn.off("data", onData);
73
- conn.off("close", onClose);
74
- conn.off("error", onError);
75
- life.abort(reason);
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 }));
75
+ }, {
76
+ name: "webrun-streams-peerjs",
77
+ maxFrameBytes,
78
+ maxMessageSize,
79
+ copyOnSend: true,
80
+ copyOnDeliver: true
81
+ });
79
82
  conn.on("data", onData);
80
83
  conn.on("close", onClose);
81
84
  conn.on("error", onError);
82
- const closeConn = () => {
83
- try {
84
- conn.close();
85
- } catch {}
86
- };
87
- return {
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() {
120
- return new Promise((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();
127
- });
128
- }
129
- }
130
- };
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;
85
+ return control.pipe;
141
86
  }
142
87
  //#endregion
143
88
  export { DEFAULT_MAX_FRAME_BYTES, DEFAULT_MAX_MESSAGE_SIZE, DRAIN_LOW_WATER, messageTargetOverPeerJs };
@@ -1,5 +1,5 @@
1
+ import { type MessagePipe, type MessagePipeTarget } from "@statewalker/webrun-streams";
1
2
  import type { DataConnection } from "peerjs";
2
- type Listener = (event: MessageEvent) => void | Promise<void>;
3
3
  /**
4
4
  * The largest message a raw `DataConnection` delivers between any two
5
5
  * browsers: PeerJS records Firefox-to-Chrome messages "cut off after 16384
@@ -29,23 +29,15 @@ export interface MessageTargetOverPeerJsOptions {
29
29
  maxMessageSize?: number;
30
30
  }
31
31
  /** What `messageTargetOverPeerJs` gives: a pipe of bytes, its life, and its payload ceiling. */
32
- export interface PeerJsMessageTarget {
32
+ export interface PeerJsMessageTarget extends MessagePipe {
33
33
  /**
34
34
  * A `MessageTarget` (as `@statewalker/webrun-rpc` defines it) whose messages
35
- * are `Uint8Array`s, one data channel message each.
35
+ * are `Uint8Array`s, one data channel message each. A post past
36
+ * `maxFrameBytes` throws `RangeError` and ends the pipe; `bufferedAmount` is
37
+ * the data channel's; `whenDrained` waits for PeerJS's own queue to empty
38
+ * and `bufferedAmount` to reach {@link DRAIN_LOW_WATER}.
36
39
  */
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
- };
40
+ target: MessagePipeTarget;
49
41
  /**
50
42
  * Aborts when the connection closes or fails, or a post exceeds
51
43
  * `maxFrameBytes`. Pass it as `overPipe`'s `signal`.
@@ -72,5 +64,4 @@ export interface PeerJsMessageTarget {
72
64
  * with a `TypeError`: dropping it would lose an envelope and hang its call.
73
65
  */
74
66
  export declare function messageTargetOverPeerJs(conn: DataConnection, options?: MessageTargetOverPeerJsOptions): PeerJsMessageTarget;
75
- export {};
76
67
  //# sourceMappingURL=message-target.d.ts.map
@@ -1 +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"}
1
+ {"version":3,"file":"message-target.d.ts","sourceRoot":"","sources":["../src/message-target.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,WAAW,EAChB,KAAK,iBAAiB,EAEvB,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAE7C;;;;;;;;GAQG;AACH,eAAO,MAAM,uBAAuB,QAAY,CAAC;AASjD,kFAAkF;AAClF,eAAO,MAAM,wBAAwB,QAA2C,CAAC;AAEjF;;;;GAIG;AACH,eAAO,MAAM,eAAe,QAA0B,CAAC;AAIvD,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,mBAAoB,SAAQ,WAAW;IACtD;;;;;;OAMG;IACH,MAAM,EAAE,iBAAiB,CAAC;IAC1B;;;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,CAqFrB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statewalker/webrun-streams-peerjs",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "PeerJS DataConnection-backed Connect/Serve adapter in the webrun-streams-* family",
@@ -32,6 +32,9 @@
32
32
  "peerDependencies": {
33
33
  "peerjs": "^1.5.5"
34
34
  },
35
+ "dependencies": {
36
+ "@statewalker/webrun-streams": "^0.5.0"
37
+ },
35
38
  "devDependencies": {
36
39
  "@biomejs/biome": "^2.5.15",
37
40
  "@roamhq/wrtc": "^0.10.0",
@@ -44,10 +47,9 @@
44
47
  "rolldown": "^1.2.12",
45
48
  "typescript": "^7.0.2",
46
49
  "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"
50
+ "@statewalker/webrun-rpc": "^0.13.0",
51
+ "@statewalker/webrun-msgpack": "^0.12.0",
52
+ "@statewalker/webrun-streams-conformance": "^0.6.0"
51
53
  },
52
54
  "sideEffects": false,
53
55
  "publishConfig": {
@@ -58,6 +60,8 @@
58
60
  "build": "rimraf dist && rolldown -c && tsc --emitDeclarationOnly --declaration",
59
61
  "test": "vitest run",
60
62
  "test:browser": "vitest run --config vitest.browser.config.ts",
63
+ "typecheck": "tsc --noEmit",
64
+ "typecheck:tests": "tsc -p tsconfig.tests.json",
61
65
  "lint": "biome check src tests"
62
66
  }
63
67
  }
@@ -1,7 +1,12 @@
1
+ import {
2
+ DEFAULT_DRAIN_LOW_WATER,
3
+ DEFAULT_DRAIN_POLL_MS,
4
+ type MessagePipe,
5
+ type MessagePipeTarget,
6
+ newMessagePipe,
7
+ } from "@statewalker/webrun-streams";
1
8
  import type { DataConnection } from "peerjs";
2
9
 
3
- type Listener = (event: MessageEvent) => void | Promise<void>;
4
-
5
10
  /**
6
11
  * The largest message a raw `DataConnection` delivers between any two
7
12
  * browsers: PeerJS records Firefox-to-Chrome messages "cut off after 16384
@@ -23,14 +28,12 @@ const FRAMING_MARGIN = 256;
23
28
  /** `DEFAULT_MAX_FRAME_BYTES` less the framing margin: what to give `overPipe`. */
24
29
  export const DEFAULT_MAX_MESSAGE_SIZE = DEFAULT_MAX_FRAME_BYTES - FRAMING_MARGIN;
25
30
 
26
- /** How often `whenDrained` looks: neither PeerJS's queue nor `bufferedAmount` reports emptying. */
27
- const DRAIN_POLL_MS = 5;
28
31
  /**
29
32
  * `whenDrained` resolves once PeerJS's own queue is empty and the data
30
33
  * channel's `bufferedAmount` is at most this: the channel can take more.
31
34
  * Waiting for zero would pause a sender that waits before every frame.
32
35
  */
33
- export const DRAIN_LOW_WATER = 256 * 1024;
36
+ export const DRAIN_LOW_WATER = DEFAULT_DRAIN_LOW_WATER;
34
37
  /** How long `close()` waits for queued messages to be written out. */
35
38
  const CLOSE_FLUSH_MS = 5000;
36
39
 
@@ -46,23 +49,15 @@ export interface MessageTargetOverPeerJsOptions {
46
49
  }
47
50
 
48
51
  /** What `messageTargetOverPeerJs` gives: a pipe of bytes, its life, and its payload ceiling. */
49
- export interface PeerJsMessageTarget {
52
+ export interface PeerJsMessageTarget extends MessagePipe {
50
53
  /**
51
54
  * A `MessageTarget` (as `@statewalker/webrun-rpc` defines it) whose messages
52
- * are `Uint8Array`s, one data channel message each.
55
+ * are `Uint8Array`s, one data channel message each. A post past
56
+ * `maxFrameBytes` throws `RangeError` and ends the pipe; `bufferedAmount` is
57
+ * the data channel's; `whenDrained` waits for PeerJS's own queue to empty
58
+ * and `bufferedAmount` to reach {@link DRAIN_LOW_WATER}.
53
59
  */
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
- };
60
+ target: MessagePipeTarget;
66
61
  /**
67
62
  * Aborts when the connection closes or fails, or a post exceeds
68
63
  * `maxFrameBytes`. Pass it as `overPipe`'s `signal`.
@@ -115,131 +110,66 @@ export function messageTargetOverPeerJs(
115
110
  }
116
111
  const maxFrameBytes = options.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
117
112
  const maxMessageSize = options.maxMessageSize ?? maxFrameBytes - FRAMING_MARGIN;
118
- const listeners = new Set<Listener>();
119
- const life = new AbortController();
120
113
  const internals = conn as unknown as {
121
114
  bufferSize?: number;
122
115
  dataChannel?: { bufferedAmount?: number };
123
116
  };
117
+ const held = (): boolean =>
118
+ (internals.bufferSize ?? 0) > 0 || (internals.dataChannel?.bufferedAmount ?? 0) > 0;
124
119
 
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"));
120
+ const onData = (data: unknown): void => control.deliver(data);
121
+ const onClose = (): void =>
122
+ control.end(new Error("webrun-streams-peerjs: the connection closed"));
123
+ // Ended as local: an error is not always followed by `close`, and the
124
+ // connection must still be released, or the peer never learns the pipe is gone.
153
125
  const onError = (err: unknown): void =>
154
- end(
126
+ control.end(
155
127
  new Error(
156
128
  `webrun-streams-peerjs: the connection failed: ${(err as Error)?.message ?? String(err)}`,
157
129
  { cause: err },
158
130
  ),
131
+ true,
159
132
  );
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.
133
+ const control = newMessagePipe(
134
+ {
135
+ send: (bytes) => conn.send(bytes),
136
+ canSend: () => conn.open,
137
+ bufferedAmount: () => internals.dataChannel?.bufferedAmount ?? 0,
138
+ isDrained: () =>
139
+ !(internals.bufferSize ?? 0) &&
140
+ (internals.dataChannel?.bufferedAmount ?? 0) <= DRAIN_LOW_WATER,
141
+ // `conn.close()` tears the peer connection down at once, discarding what
142
+ // PeerJS and the data channel still hold — the multiplexer's last close
143
+ // envelopes among it. Let that go out first, for at most CLOSE_FLUSH_MS.
144
+ flush: async () => {
203
145
  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));
146
+ while (!control.ended && Date.now() < deadline && held()) {
147
+ await new Promise((resolve) => setTimeout(resolve, DEFAULT_DRAIN_POLL_MS));
210
148
  }
211
- end(new Error("webrun-streams-peerjs: closed locally"));
212
- closeConn();
213
- },
214
- get bufferedAmount() {
215
- return internals.dataChannel?.bufferedAmount ?? 0;
216
149
  },
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
- });
150
+ close: (local) => {
151
+ conn.off("data", onData);
152
+ conn.off("close", onClose);
153
+ conn.off("error", onError);
154
+ if (local) {
155
+ try {
156
+ conn.close();
157
+ } catch {}
158
+ }
228
159
  },
229
160
  },
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;
161
+ {
162
+ name: "webrun-streams-peerjs",
163
+ maxFrameBytes,
164
+ maxMessageSize,
165
+ // PeerJS may queue a sent message past its own buffer threshold, and
166
+ // reuse the buffer it hands out.
167
+ copyOnSend: true,
168
+ copyOnDeliver: true,
169
+ },
170
+ );
171
+ conn.on("data", onData);
172
+ conn.on("close", onClose);
173
+ conn.on("error", onError);
174
+ return control.pipe as PeerJsMessageTarget;
245
175
  }