@statewalker/webrun-streams-livekit 0.2.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,26 +2,33 @@
2
2
 
3
3
  ## What it is
4
4
 
5
- A `Connect` / `Serve` adapter that runs `@statewalker/webrun-streams` `Duplex` calls over a LiveKit
6
- room. A connected `Room` plus the identity of one remote participant becomes one `ByteChannel`
7
- (reliable data packets addressed to that participant), and `webrun-streams`' `emulateMux` runs
8
- many concurrent calls over it. Your handler is an ordinary `Duplex`,
9
- `(input: AsyncIterable<Uint8Array>) => AsyncGenerator<Uint8Array>`, the same function you would
10
- run over a WebSocket or a WebRTC data channel.
5
+ One remote participant of a LiveKit room as a pipe of bytes for `@statewalker/webrun-rpc`'s port
6
+ stack. `messageTargetOverLiveKit(room, peerIdentity)` turns a connected `Room` plus the identity of
7
+ the participant at the other end into `{ target, signal, maxMessageSize }`: a `MessageTarget` whose
8
+ messages are `Uint8Array`s (one reliable data packet each, addressed to that participant), a
9
+ signal that aborts when the room or the participant goes, and the payload ceiling to chunk to.
10
+ Hand all three to `webrun-rpc`'s `overPipe` with `msgpackCodec`, and `webrun-rpc`'s `connect` /
11
+ `serve` run many concurrent calls over the pair, one port per call. Your handler is an ordinary
12
+ `Duplex`, `(input: AsyncIterable<Uint8Array>) => AsyncGenerator<Uint8Array>`, the same function
13
+ you would run over a WebSocket or a WebRTC data channel.
11
14
 
12
15
  ## Why it exists
13
16
 
14
17
  Direct peer-to-peer links fail behind symmetric NATs, corporate firewalls and some mobile
15
18
  networks, and multi-party sessions want a server anyway. LiveKit is a managed SFU that already
16
19
  handles authentication, room membership and presence. What its data channel does not provide is
17
- request semantics: there are no calls, no streams, no flow control, only packets. This adapter
18
- adds them, so code written against the `Duplex` seam can move from a direct link to a LiveKit room
19
- by changing the `connect` / `serve` import, with handlers and the layers above them unchanged.
20
+ request semantics: there are no calls, no streams, no flow control, only packets. `webrun-rpc`'s
21
+ port stack adds those over any pipe of messages. What it needs from the transport is a pipe to one
22
+ peer, word of that pipe's end, and the largest message that crosses. A room is shared, stays
23
+ connected when one pipe ends, and caps packet size; this package addresses packets to one
24
+ participant on their own topic, turns room and participant events (and its own goodbye packet)
25
+ into the signal, and reports a safe ceiling. Code written against the `Duplex` seam moves from a
26
+ direct link to a LiveKit room by changing the pipe, with handlers and the layers above unchanged.
20
27
 
21
28
  ## How to use
22
29
 
23
30
  ```sh
24
- pnpm add @statewalker/webrun-streams-livekit livekit-client
31
+ pnpm add @statewalker/webrun-streams-livekit livekit-client @statewalker/webrun-rpc @statewalker/webrun-msgpack
25
32
  ```
26
33
 
27
34
  `livekit-client` is a required peer dependency (`^2.18.3`). You create the `Room`, get its token,
@@ -30,15 +37,15 @@ One entry point, `.`, ESM only.
30
37
 
31
38
  | Export | Purpose |
32
39
  | --- | --- |
33
- | `connect(params: LiveKitParams)` | `Connect<LiveKitParams>`. Resolves `{ call, close }`; each `call(input)` opens a new logical stream to `peerIdentity`. `close()` ends the mux, not the `Room`. |
34
- | `serve(params: LiveKitParams, handler)` | `Serve<LiveKitParams>`. Runs `handler` for every stream `peerIdentity` opens. Resolves an idempotent teardown. |
35
- | `LiveKitParams` | `{ room: Room; peerIdentity: string; mux?: EmulateMuxOptions }`. |
36
- | `byteChannelFromLiveKit(room, peerIdentity)` | The `ByteChannel` both use, for driving `emulateMux` yourself. |
40
+ | `messageTargetOverLiveKit(room, peerIdentity, options?)` | One remote participant as a `LiveKitMessageTarget`, `{ target, signal, maxMessageSize }`: a `MessageTarget` of bytes (one reliable packet each) with `bufferedAmount` / `whenDrained()`, a signal that aborts when the room disconnects, the participant leaves, the peer closes its pipe, a publish fails or a post exceeds `maxFrameBytes`, and the payload ceiling to give `overPipe`. |
41
+ | `MessageTargetOverLiveKitOptions` | `maxFrameBytes` (default `DEFAULT_MAX_FRAME_BYTES`), `maxMessageSize` (default `DEFAULT_MAX_MESSAGE_SIZE`), `topic` (default `DEFAULT_TOPIC`; both ends must agree; use another to run two pipes to the same participant). |
42
+ | `LiveKitMessageTarget` | The result type above. |
43
+ | `DEFAULT_MAX_FRAME_BYTES`, `DEFAULT_MAX_MESSAGE_SIZE`, `DRAIN_LOW_WATER` | 64,000 bytes, 12 KiB, 256 KiB: the defaults of the above. |
44
+ | `DEFAULT_TOPIC`, `CLOSE_TOPIC` | The data topic (`webrun/port-stack`) and the goodbye's (`webrun/port-stack/close`); `options.topic` changes both (the goodbye uses it with `/close` appended). |
37
45
 
38
- `mux` is forwarded to `emulateMux`: `mtu` (default here 12 KiB, see below), `maxStreamBuffer`
39
- (per-stream inbound cap and advertised credit; `webrun-streams` default 8 MiB), `maxStreams`
40
- (default 256). `side` is fixed by the function you call — `"initiator"` for `connect`,
41
- `"responder"` for `serve` — and overrides `mux.side`.
46
+ Both ends must run the port stack with the same codec and topic. Pass all three of `target`,
47
+ `signal` and `maxMessageSize` to `overPipe`: `signal` closes the multiplexer when the room or the
48
+ participant goes, and `maxMessageSize` chunks bodies under the packet limit.
42
49
 
43
50
  ## Examples
44
51
 
@@ -47,15 +54,22 @@ Both sides take a connected `Room` and the identity of the participant at the ot
47
54
  ### Serving
48
55
 
49
56
  ```ts
57
+ import { msgpackCodec } from "@statewalker/webrun-msgpack";
58
+ import { overPipe, serve } from "@statewalker/webrun-rpc";
59
+ import { messageTargetOverLiveKit } from "@statewalker/webrun-streams-livekit";
50
60
  import { Room } from "livekit-client";
51
- import { serve } from "@statewalker/webrun-streams-livekit";
52
61
 
53
62
  const room = new Room();
54
63
  await room.connect(url, token); // this participant's identity is "agent-7"
64
+ // ...once "client-3" is in the room:
55
65
 
56
- const stop = await serve({ room, peerIdentity: "client-3" }, async function* echo(input) {
57
- for await (const chunk of input) yield chunk;
58
- });
66
+ const { target, signal, maxMessageSize } = messageTargetOverLiveKit(room, "client-3");
67
+ const stop = await serve(
68
+ { mux: overPipe(target, { codec: msgpackCodec, side: "responder", signal, maxMessageSize }) },
69
+ async function* echo(input) {
70
+ for await (const chunk of input) yield chunk;
71
+ },
72
+ );
59
73
 
60
74
  // later
61
75
  await stop();
@@ -64,19 +78,25 @@ await stop();
64
78
  ### Calling
65
79
 
66
80
  ```ts
81
+ import { msgpackCodec } from "@statewalker/webrun-msgpack";
82
+ import { connect, overPipe } from "@statewalker/webrun-rpc";
83
+ import { messageTargetOverLiveKit } from "@statewalker/webrun-streams-livekit";
67
84
  import { Room } from "livekit-client";
68
- import { connect } from "@statewalker/webrun-streams-livekit";
69
85
 
70
86
  const room = new Room();
71
87
  await room.connect(url, token); // this participant's identity is "client-3"
88
+ // ...once "agent-7" is in the room:
72
89
 
73
- const { call, close } = await connect({ room, peerIdentity: "agent-7" });
90
+ const { target, signal, maxMessageSize } = messageTargetOverLiveKit(room, "agent-7");
91
+ const { call, close } = await connect({
92
+ mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal, maxMessageSize }),
93
+ });
74
94
 
75
95
  for await (const chunk of call([new TextEncoder().encode("ping")])) {
76
96
  console.log(new TextDecoder().decode(chunk)); // "ping"
77
97
  }
78
98
 
79
- await close();
99
+ await close(); // the Room stays connected
80
100
  ```
81
101
 
82
102
  ### HTTP over the room
@@ -87,65 +107,68 @@ import { fetchOverDuplex } from "@statewalker/webrun-http-streams";
87
107
  const response = await fetchOverDuplex(call, new Request("http://peer/api/events"));
88
108
  ```
89
109
 
90
- ### Driving the mux yourself
91
-
92
- ```ts
93
- import { emulateMux } from "@statewalker/webrun-streams";
94
- import { byteChannelFromLiveKit } from "@statewalker/webrun-streams-livekit";
95
-
96
- const channel = byteChannelFromLiveKit(room, "agent-7");
97
- const mux = emulateMux(channel, { mtu: 12 * 1024, side: "initiator" });
98
- // mux.call(input), mux.serve(handler), mux.close()
99
- ```
100
-
101
110
  ## Internals
102
111
 
103
112
  ```
104
113
  handler / caller (Duplex)
105
114
  │
106
- emulateMux (webrun-streams): [varint streamId][1-byte type] frames, credit flow control
115
+ webrun-rpc connect / serve: one stream per port
107
116
  │
108
- byteChannelFromLiveKit: one ByteChannel per (room, peerIdentity)
109
- │ out: publishData(bytes, { reliable: true, destinationIdentities: [peerIdentity] })
110
- │ in: "dataReceived" events, filtered by sender identity
117
+ overPipe + msgpackCodec (webrun-rpc): a port per call, framing, chunking to maxMessageSize
118
+ │
119
+ messageTargetOverLiveKit: one MessageTarget per (room, peerIdentity, topic)
120
+ │ out: publishData(bytes, { reliable: true, destinationIdentities: [peerIdentity], topic })
121
+ │ in: "dataReceived" events, filtered by sender identity and topic
111
122
  ▼
112
123
  LiveKit SFU
113
124
  ```
114
125
 
115
- ### Why every publish is reliable and addressed
126
+ ### Why every publish is reliable, addressed and on its own topic
127
+
128
+ Every packet is published with `reliable: true` (ordered and retransmitted), because the
129
+ multiplexer above assumes ordered delivery. Every packet carries `destinationIdentities:
130
+ [peerIdentity]`, so several pairs in one room do not fan out to every participant, and its own
131
+ topic, so an application's own `publishData` traffic does not reach the multiplexer. Inbound
132
+ packets from any other identity or on any other topic are ignored, so one `Room` can carry several
133
+ pipes, one per peer (or per topic). Each packet is copied before `publishData`, since
134
+ livekit-client serializes it after an await; each inbound packet is copied into a fresh
135
+ `Uint8Array`.
116
136
 
117
- Every packet is published with `reliable: true` (ordered and retransmitted), because the mux
118
- framing above assumes an ordered byte stream. Every packet carries `destinationIdentities:
119
- [peerIdentity]`, so several pairs in one room do not fan out to every participant. Inbound packets
120
- from any other identity are ignored, so one `Room` can carry several adapters, one per peer.
137
+ ### Why the ceiling is 12 KiB
121
138
 
122
- ### Why the default `mtu` is 12 KiB
139
+ livekit-client (2.x) refuses a data packet over 64,000 bytes with a `PublishDataError`; a post
140
+ past `maxFrameBytes` (that cap by default) ends the pipe with a `RangeError` before it gets that
141
+ far. The reported `maxMessageSize` is lower, 12 KiB, as this adapter has always used against a
142
+ real SFU: an older client dropped larger reliable packets silently, a body arriving as zero bytes
143
+ with no error on either side. 12 KiB leaves room for the port stack's framing well inside the
144
+ packet cap. Raise it with `options.maxMessageSize` (keeping it at least 256 bytes under the packet
145
+ limit) only for a deployment known to allow more.
123
146
 
124
- A LiveKit reliable data packet is capped at about 15 KiB, and a larger payload is dropped rather
125
- than fragmented. `emulateMux`'s own 64 KiB default therefore fails here, and silently: a 1 MiB body
126
- arrives as zero bytes and a 10 MiB body never completes, with no error on either side. So
127
- `connect` and `serve` default `mtu` to 12 KiB, which leaves room for the frame header inside the
128
- packet. An explicit `mux.mtu` still wins, for a deployment that allows larger packets.
147
+ ### What closes the pipe, and what you see
129
148
 
130
- ### What closes the channel, and what you see
149
+ `signal` aborts when the `Room` emits `disconnected`, when the `peerIdentity` participant
150
+ disconnects (`participantDisconnected`), when the peer's goodbye arrives on the close topic, when a
151
+ reliable publish fails (the stream above has lost a message), on an oversized post, or on
152
+ `close()`. `overPipe` closes the multiplexer on it, which fails every call in flight. The pipe does
153
+ not reopen: if the peer leaves and comes back, call `messageTargetOverLiveKit` again.
131
154
 
132
- The channel closes when the `Room` emits `disconnected`, when the `peerIdentity` participant
133
- disconnects (`participantDisconnected`), or when its `close()` is called. In-flight and later calls
134
- then fail with `webrun-streams`' `TransportClosedError` (`name` `"TransportClosedError"`). `serve`
135
- also closes its mux when the channel closes. The channel does not reopen: if the peer leaves and
136
- comes back, call `connect` / `serve` again.
155
+ Ending on this side (`close()`, an oversized post, a failed publish) sends a goodbye, an empty
156
+ packet on the close topic, which ends the peer's pipe: the room stays connected, so no LiveKit
157
+ event would tell it. `close()` detaches from the room and leaves it connected.
137
158
 
138
- A failed `publishData` is swallowed; it surfaces through the disconnect events, not as an error on
139
- the call.
159
+ `bufferedAmount` counts bytes whose `publishData` has not settled, and `whenDrained()` resolves
160
+ once that is at most `DRAIN_LOW_WATER`, or the pipe ended. `postMessage` throws a `TypeError` for
161
+ anything but bytes, and is a no-op once the pipe has ended: `signal` already says so.
140
162
 
141
163
  ### Two things that are easy to get wrong
142
164
 
143
- - **Wait for the peer to be in the room before the first call.** The adapter addresses the remote
144
- by identity, and LiveKit drops a data packet sent to a participant it has not announced yet
145
- rather than queueing it. Wait for `RoomEvent.ParticipantConnected` (or check
165
+ - **Wait for the peer to be in the room first.** The pipe addresses the remote by identity, and
166
+ LiveKit drops a data packet sent to a participant it has not announced yet rather than queueing
167
+ it, so `messageTargetOverLiveKit` throws `messageTargetOverLiveKit: "<identity>" is not in the
168
+ room; wait for it to join`. Wait for `RoomEvent.ParticipantConnected` (or check
146
169
  `room.remoteParticipants`) first.
147
- - **Each side names the other side's identity, exactly.** A wrong identity is not an error:
148
- packets are filtered out and the call waits.
170
+ - **Each side names the other side's identity, exactly, and the same topic.** A wrong identity or
171
+ topic is not an error: packets are filtered out and the call waits.
149
172
 
150
173
  ### Conformance runs in a browser against a real server
151
174
 
@@ -154,17 +177,21 @@ pnpm --filter @statewalker/webrun-streams-livekit test:browser
154
177
  ```
155
178
 
156
179
  This runs the `@statewalker/webrun-streams-conformance` suite in headless Chromium through
157
- Playwright. A Vitest global setup starts `livekit-server --dev` on a loopback port and mints the
158
- two access tokens with `livekit-server-sdk`, so the `livekit-server` binary must be on `PATH`.
159
- Without it the setup fails with `livekit-server exited early (code …). Install it from
180
+ Playwright, over the port stack (`overPipe` + `msgpackCodec`). L6 asserts the port stack's bound: a
181
+ consumer that stops reading lets the producer get at most one 4 KiB chunk ahead. A Vitest global
182
+ setup starts `livekit-server --dev` on a loopback port and mints the two access tokens with
183
+ `livekit-server-sdk`, so the `livekit-server` binary must be on `PATH`. Without it the setup fails
184
+ with `livekit-server exited early (code …). Install it from
160
185
  https://docs.livekit.io/home/self-hosting/local/`. Under plain `pnpm test` (Node) the suite is
161
- skipped, because `livekit-client` needs a browser.
186
+ skipped, because `livekit-client` needs a browser. `message-target.test.ts` pins the pipe's
187
+ contract.
162
188
 
163
189
  ### Dependencies
164
190
 
165
- - `@statewalker/webrun-streams` (runtime): the `Duplex` / `Connect` / `Serve` / `ByteChannel`
166
- types and `emulateMux`.
167
- - `livekit-client` (peer): you supply and own the `Room`.
191
+ - `livekit-client` (peer): you supply and own the `Room`. `src/` imports only its `Room` type.
192
+ - `@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.
193
+ `@statewalker/webrun-rpc` and `@statewalker/webrun-msgpack` are dev dependencies of the tests;
194
+ consumers supply their own `webrun-rpc` and codec.
168
195
  - Dev only: `livekit-server-sdk` for test tokens, `@vitest/browser-playwright` and `playwright`
169
196
  for the browser run, `@statewalker/webrun-streams-conformance` for the suite.
170
197
 
package/dist/index.d.ts CHANGED
@@ -1,3 +1,2 @@
1
- export { byteChannelFromLiveKit } from "./byte-channel.js";
2
- export { connect, type LiveKitParams, serve } from "./connect-serve.js";
1
+ export { CLOSE_TOPIC, DEFAULT_MAX_FRAME_BYTES, DEFAULT_MAX_MESSAGE_SIZE, DEFAULT_TOPIC, DRAIN_LOW_WATER, type LiveKitMessageTarget, type MessageTargetOverLiveKitOptions, messageTargetOverLiveKit, } 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,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,OAAO,EAAE,KAAK,aAAa,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,uBAAuB,EACvB,wBAAwB,EACxB,aAAa,EACb,eAAe,EACf,KAAK,oBAAoB,EACzB,KAAK,+BAA+B,EACpC,wBAAwB,GACzB,MAAM,qBAAqB,CAAC"}
package/dist/index.js CHANGED
@@ -1,136 +1,116 @@
1
- import { emulateMux } from "@statewalker/webrun-streams";
2
- //#region src/byte-channel.ts
1
+ import { DEFAULT_DRAIN_LOW_WATER, newMessagePipe } from "@statewalker/webrun-streams";
2
+ //#region src/message-target.ts
3
3
  /**
4
- * Wrap a connected LiveKit `Room` plus a remote participant identity into a
5
- * `ByteChannel`. Outbound bytes are addressed only to the named participant;
6
- * inbound is filtered by sender identity.
4
+ * The largest data packet livekit-client (2.x) publishes: `RTCEngine` refuses
5
+ * a larger one with a `PublishDataError`. A post past it ends the pipe with a
6
+ * `RangeError` before it gets that far.
7
7
  */
8
- function byteChannelFromLiveKit(room, peerIdentity) {
9
- let closedResolve;
10
- const closed = new Promise((r) => {
11
- closedResolve = r;
12
- });
13
- let isClosed = false;
14
- const queue = [];
15
- let pending = null;
16
- const deliver = (bytes) => {
17
- if (isClosed) return;
18
- if (pending) {
19
- const r = pending;
20
- pending = null;
21
- r({
22
- value: bytes,
23
- done: false
24
- });
25
- } else queue.push(bytes);
26
- };
27
- const onData = (payload, participant) => {
28
- if (!participant) return;
29
- if (participant.identity !== peerIdentity) return;
30
- deliver(new Uint8Array(payload));
8
+ const DEFAULT_MAX_FRAME_BYTES = 64e3;
9
+ /** The topic this pipe's packets carry; packets on other topics are someone else's. */
10
+ const DEFAULT_TOPIC = "webrun/port-stack";
11
+ /**
12
+ * The topic of the goodbye a pipe sends when it ends on its own side. The room
13
+ * stays connected, so without it the peer would never learn the pipe is gone.
14
+ */
15
+ const CLOSE_TOPIC = "webrun/port-stack/close";
16
+ /**
17
+ * The payload ceiling to give `overPipe`: 12 KiB, as this adapter has always
18
+ * used against a real SFU (an older client dropped larger reliable packets
19
+ * silently), well inside the packet cap with the port stack's framing.
20
+ */
21
+ const DEFAULT_MAX_MESSAGE_SIZE = 12288;
22
+ /**
23
+ * `whenDrained` resolves once the bytes whose publish has not settled are at
24
+ * most this: the room can take more.
25
+ */
26
+ const DRAIN_LOW_WATER = DEFAULT_DRAIN_LOW_WATER;
27
+ /**
28
+ * One remote participant of a connected `Room` as a pipe of messages, for a
29
+ * multiplexer to run over:
30
+ *
31
+ * ```ts
32
+ * const { target, signal, maxMessageSize } = messageTargetOverLiveKit(room, "bob");
33
+ * const { call } = await connect({
34
+ * mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal, maxMessageSize }),
35
+ * });
36
+ * ```
37
+ *
38
+ * Packets go out reliable (ordered, retransmitted), addressed to that
39
+ * participant only and on their own topic; inbound packets from anyone else,
40
+ * or on another topic, are ignored. The participant must already be in the
41
+ * room (LiveKit drops packets to one it has not announced), or this throws.
42
+ * When the pipe ends on this side — `close()`, an oversized post, a failed
43
+ * publish — a goodbye on the close topic ends the peer's pipe too.
44
+ */
45
+ function messageTargetOverLiveKit(room, peerIdentity, options = {}) {
46
+ const maxFrameBytes = options.maxFrameBytes ?? 64e3;
47
+ const maxMessageSize = options.maxMessageSize ?? 12288;
48
+ const topic = options.topic ?? "webrun/port-stack";
49
+ const closeTopic = `${topic}/close`;
50
+ const remotes = room.remoteParticipants;
51
+ if (!(remotes ? remotes.has(peerIdentity) || [...remotes.values()].some((p) => p.identity === peerIdentity) : true)) throw new Error(`messageTargetOverLiveKit: "${peerIdentity}" is not in the room; wait for it to join`);
52
+ const roomApi = room;
53
+ const publisher = room.localParticipant;
54
+ let inFlight = 0;
55
+ const drainWaiters = /* @__PURE__ */ new Set();
56
+ const wakeDrainWaiters = () => {
57
+ if (inFlight > DRAIN_LOW_WATER) return;
58
+ for (const w of [...drainWaiters]) w();
59
+ drainWaiters.clear();
31
60
  };
32
- const onDisconnected = () => {
33
- fireClose();
61
+ const onData = (...args) => {
62
+ const [payload, participant, , packetTopic] = args;
63
+ if (participant?.identity !== peerIdentity) return;
64
+ if (packetTopic === closeTopic) {
65
+ control.end(/* @__PURE__ */ new Error(`webrun-streams-livekit: "${peerIdentity}" closed the pipe`));
66
+ return;
67
+ }
68
+ if (packetTopic !== topic) return;
69
+ control.deliver(payload);
34
70
  };
35
- const onParticipantDisconnected = (participant) => {
36
- if (participant.identity !== peerIdentity) return;
37
- fireClose();
71
+ const onDisconnected = () => control.end(/* @__PURE__ */ new Error("webrun-streams-livekit: the room disconnected"));
72
+ const onParticipantDisconnected = (...args) => {
73
+ if (args[0]?.identity !== peerIdentity) return;
74
+ control.end(/* @__PURE__ */ new Error(`webrun-streams-livekit: "${peerIdentity}" left the room`));
38
75
  };
39
- const fireClose = () => {
40
- if (isClosed) return;
41
- isClosed = true;
42
- roomApi.off("dataReceived", onData);
43
- roomApi.off("disconnected", onDisconnected);
44
- roomApi.off("participantDisconnected", onParticipantDisconnected);
45
- if (pending) {
46
- const r = pending;
47
- pending = null;
48
- r({
49
- value: void 0,
50
- done: true
76
+ const control = newMessagePipe({
77
+ send: (bytes) => {
78
+ const size = bytes.byteLength;
79
+ inFlight += size;
80
+ publisher.publishData(bytes, {
81
+ reliable: true,
82
+ destinationIdentities: [peerIdentity],
83
+ topic
84
+ }).then(() => void 0, (err) => control.end(new Error(`webrun-streams-livekit: a reliable publish failed: ${err?.message ?? String(err)}`, { cause: err }), true)).finally(() => {
85
+ inFlight -= size;
86
+ wakeDrainWaiters();
51
87
  });
88
+ },
89
+ bufferedAmount: () => inFlight,
90
+ whenDrained: () => new Promise((resolve) => drainWaiters.add(resolve)),
91
+ /** `local`: the pipe ended on this side, and the room is still there to say so. */
92
+ close: (local) => {
93
+ roomApi.off("dataReceived", onData);
94
+ roomApi.off("disconnected", onDisconnected);
95
+ roomApi.off("participantDisconnected", onParticipantDisconnected);
96
+ drainWaiters.clear();
97
+ if (local) publisher.publishData(/* @__PURE__ */ new Uint8Array(0), {
98
+ reliable: true,
99
+ destinationIdentities: [peerIdentity],
100
+ topic: closeTopic
101
+ }).catch(() => void 0);
52
102
  }
53
- closedResolve();
54
- };
55
- const roomApi = room;
103
+ }, {
104
+ name: "webrun-streams-livekit",
105
+ maxFrameBytes,
106
+ maxMessageSize,
107
+ copyOnSend: true,
108
+ copyOnDeliver: true
109
+ });
56
110
  roomApi.on("dataReceived", onData);
57
111
  roomApi.on("disconnected", onDisconnected);
58
112
  roomApi.on("participantDisconnected", onParticipantDisconnected);
59
- return {
60
- send(bytes) {
61
- if (isClosed) return;
62
- room.localParticipant.publishData(bytes, {
63
- reliable: true,
64
- destinationIdentities: [peerIdentity]
65
- }).catch(() => {});
66
- },
67
- recv: { [Symbol.asyncIterator]() {
68
- return { next() {
69
- if (queue.length > 0) return Promise.resolve({
70
- value: queue.shift(),
71
- done: false
72
- });
73
- if (isClosed) return Promise.resolve({
74
- value: void 0,
75
- done: true
76
- });
77
- return new Promise((resolve) => {
78
- pending = resolve;
79
- });
80
- } };
81
- } },
82
- closed,
83
- close() {
84
- fireClose();
85
- }
86
- };
113
+ return control.pipe;
87
114
  }
88
115
  //#endregion
89
- //#region src/connect-serve.ts
90
- /**
91
- * Default `mtu` for this transport.
92
- *
93
- * `emulateMux` defaults to 64 KiB, which LiveKit cannot carry: a reliable data
94
- * packet is capped around 15 KiB, and anything larger is dropped rather than
95
- * fragmented. The symptom is not an error — a 1 MiB body simply arrives as
96
- * zero bytes and a 10 MiB body hangs — so the ceiling has to be applied here,
97
- * where the transport is known, rather than left to every caller.
98
- *
99
- * 12 KiB leaves room for the mux frame header (`[varint streamId][1-byte
100
- * type]`) inside that budget. An explicit `mux.mtu` still wins, so a caller who
101
- * knows their deployment allows more can raise it.
102
- */
103
- const LIVEKIT_SAFE_MTU = 12288;
104
- const connect = async ({ room, peerIdentity, mux: muxOpts }) => {
105
- const channel = byteChannelFromLiveKit(room, peerIdentity);
106
- const mux = emulateMux(channel, {
107
- mtu: LIVEKIT_SAFE_MTU,
108
- ...muxOpts,
109
- side: "initiator"
110
- });
111
- return {
112
- call: mux.call,
113
- async close() {
114
- await mux.close();
115
- }
116
- };
117
- };
118
- const serve = async ({ room, peerIdentity, mux: muxOpts }, handler) => {
119
- const channel = byteChannelFromLiveKit(room, peerIdentity);
120
- const mux = emulateMux(channel, {
121
- mtu: LIVEKIT_SAFE_MTU,
122
- ...muxOpts,
123
- side: "responder"
124
- });
125
- const off = mux.serve(handler);
126
- channel.closed.then(() => mux.close());
127
- let torn = false;
128
- return async () => {
129
- if (torn) return;
130
- torn = true;
131
- await off();
132
- await mux.close();
133
- };
134
- };
135
- //#endregion
136
- export { byteChannelFromLiveKit, connect, serve };
116
+ export { CLOSE_TOPIC, DEFAULT_MAX_FRAME_BYTES, DEFAULT_MAX_MESSAGE_SIZE, DEFAULT_TOPIC, DRAIN_LOW_WATER, messageTargetOverLiveKit };
@@ -0,0 +1,78 @@
1
+ import { type MessagePipe, type MessagePipeTarget } from "@statewalker/webrun-streams";
2
+ import type { Room } from "livekit-client";
3
+ /**
4
+ * The largest data packet livekit-client (2.x) publishes: `RTCEngine` refuses
5
+ * a larger one with a `PublishDataError`. A post past it ends the pipe with a
6
+ * `RangeError` before it gets that far.
7
+ */
8
+ export declare const DEFAULT_MAX_FRAME_BYTES = 64000;
9
+ /** The topic this pipe's packets carry; packets on other topics are someone else's. */
10
+ export declare const DEFAULT_TOPIC = "webrun/port-stack";
11
+ /**
12
+ * The topic of the goodbye a pipe sends when it ends on its own side. The room
13
+ * stays connected, so without it the peer would never learn the pipe is gone.
14
+ */
15
+ export declare const CLOSE_TOPIC = "webrun/port-stack/close";
16
+ /**
17
+ * The payload ceiling to give `overPipe`: 12 KiB, as this adapter has always
18
+ * used against a real SFU (an older client dropped larger reliable packets
19
+ * silently), well inside the packet cap with the port stack's framing.
20
+ */
21
+ export declare const DEFAULT_MAX_MESSAGE_SIZE: number;
22
+ /**
23
+ * `whenDrained` resolves once the bytes whose publish has not settled are at
24
+ * most this: the room can take more.
25
+ */
26
+ export declare const DRAIN_LOW_WATER: number;
27
+ export interface MessageTargetOverLiveKitOptions {
28
+ /** The largest packet posted; past it the pipe ends with `RangeError`. Default {@link DEFAULT_MAX_FRAME_BYTES}. */
29
+ maxFrameBytes?: number;
30
+ /** The payload ceiling to report. Default {@link DEFAULT_MAX_MESSAGE_SIZE}. */
31
+ maxMessageSize?: number;
32
+ /**
33
+ * The data topic, default {@link DEFAULT_TOPIC}; the goodbye uses it with
34
+ * `/close` appended. Both ends must agree. Use another to run two pipes to
35
+ * the same participant.
36
+ */
37
+ topic?: string;
38
+ }
39
+ /** What `messageTargetOverLiveKit` gives: a pipe of bytes to one participant, its life, and its payload ceiling. */
40
+ export interface LiveKitMessageTarget extends MessagePipe {
41
+ /**
42
+ * A `MessageTarget` (as `@statewalker/webrun-rpc` defines it) whose messages
43
+ * are `Uint8Array`s, one reliable data packet each. A post past
44
+ * `maxFrameBytes` throws `RangeError` and ends the pipe; `close()` detaches
45
+ * from the room, which stays connected (it is the caller's);
46
+ * `bufferedAmount` counts bytes whose `publishData` has not settled, and
47
+ * `whenDrained` waits for it to reach {@link DRAIN_LOW_WATER}.
48
+ */
49
+ target: MessagePipeTarget;
50
+ /**
51
+ * Aborts when the room disconnects, the participant leaves, a publish fails
52
+ * (the stream above lost a message), or a post exceeds `maxFrameBytes`.
53
+ * Pass it as `overPipe`'s `signal`.
54
+ */
55
+ signal: AbortSignal;
56
+ /** Pass as `overPipe`'s `maxMessageSize`, so bodies are chunked under the packet limit. */
57
+ maxMessageSize: number;
58
+ }
59
+ /**
60
+ * One remote participant of a connected `Room` as a pipe of messages, for a
61
+ * multiplexer to run over:
62
+ *
63
+ * ```ts
64
+ * const { target, signal, maxMessageSize } = messageTargetOverLiveKit(room, "bob");
65
+ * const { call } = await connect({
66
+ * mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal, maxMessageSize }),
67
+ * });
68
+ * ```
69
+ *
70
+ * Packets go out reliable (ordered, retransmitted), addressed to that
71
+ * participant only and on their own topic; inbound packets from anyone else,
72
+ * or on another topic, are ignored. The participant must already be in the
73
+ * room (LiveKit drops packets to one it has not announced), or this throws.
74
+ * When the pipe ends on this side — `close()`, an oversized post, a failed
75
+ * publish — a goodbye on the close topic ends the peer's pipe too.
76
+ */
77
+ export declare function messageTargetOverLiveKit(room: Room, peerIdentity: string, options?: MessageTargetOverLiveKitOptions): LiveKitMessageTarget;
78
+ //# sourceMappingURL=message-target.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"message-target.d.ts","sourceRoot":"","sources":["../src/message-target.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,WAAW,EAChB,KAAK,iBAAiB,EAEvB,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAE3C;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,QAAS,CAAC;AAE9C,uFAAuF;AACvF,eAAO,MAAM,aAAa,sBAAsB,CAAC;AAEjD;;;GAGG;AACH,eAAO,MAAM,WAAW,4BAA4B,CAAC;AAErD;;;;GAIG;AACH,eAAO,MAAM,wBAAwB,QAAY,CAAC;AAElD;;;GAGG;AACH,eAAO,MAAM,eAAe,QAA0B,CAAC;AAEvD,MAAM,WAAW,+BAA+B;IAC9C,mHAAmH;IACnH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,+EAA+E;IAC/E,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;;OAIG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,oHAAoH;AACpH,MAAM,WAAW,oBAAqB,SAAQ,WAAW;IACvD;;;;;;;OAOG;IACH,MAAM,EAAE,iBAAiB,CAAC;IAC1B;;;;OAIG;IACH,MAAM,EAAE,WAAW,CAAC;IACpB,2FAA2F;IAC3F,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,wBAAwB,CACtC,IAAI,EAAE,IAAI,EACV,YAAY,EAAE,MAAM,EACpB,OAAO,GAAE,+BAAoC,GAC5C,oBAAoB,CAkHtB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statewalker/webrun-streams-livekit",
3
- "version": "0.2.4",
3
+ "version": "0.4.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "LiveKit-backed Connect/Serve adapter in the webrun-streams-* family",
@@ -29,16 +29,16 @@
29
29
  "dist",
30
30
  "src"
31
31
  ],
32
- "dependencies": {
33
- "@statewalker/webrun-streams": "^0.2.3"
34
- },
35
32
  "peerDependencies": {
36
33
  "livekit-client": "^2.18.3"
37
34
  },
35
+ "dependencies": {
36
+ "@statewalker/webrun-streams": "^0.5.0"
37
+ },
38
38
  "devDependencies": {
39
39
  "@biomejs/biome": "^2.5.15",
40
40
  "@types/node": "^26.6.4",
41
- "@vitest/browser-playwright": "^5.0.3",
41
+ "@vitest/browser-playwright": "^5.0.5",
42
42
  "livekit-client": "^2.18.3",
43
43
  "livekit-server-sdk": "^2.19.1",
44
44
  "playwright": "^1.63.0",
@@ -46,8 +46,10 @@
46
46
  "rolldown": "^1.2.12",
47
47
  "testcontainers": "^12.2.0",
48
48
  "typescript": "^7.0.2",
49
- "vitest": "^5.0.3",
50
- "@statewalker/webrun-streams-conformance": "^0.3.3"
49
+ "vitest": "^5.0.5",
50
+ "@statewalker/webrun-msgpack": "^0.12.0",
51
+ "@statewalker/webrun-streams-conformance": "^0.6.0",
52
+ "@statewalker/webrun-rpc": "^0.13.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
  }
package/src/index.ts CHANGED
@@ -1,2 +1,10 @@
1
- export { byteChannelFromLiveKit } from "./byte-channel.js";
2
- export { connect, type LiveKitParams, serve } from "./connect-serve.js";
1
+ export {
2
+ CLOSE_TOPIC,
3
+ DEFAULT_MAX_FRAME_BYTES,
4
+ DEFAULT_MAX_MESSAGE_SIZE,
5
+ DEFAULT_TOPIC,
6
+ DRAIN_LOW_WATER,
7
+ type LiveKitMessageTarget,
8
+ type MessageTargetOverLiveKitOptions,
9
+ messageTargetOverLiveKit,
10
+ } from "./message-target.js";
@@ -0,0 +1,208 @@
1
+ import {
2
+ DEFAULT_DRAIN_LOW_WATER,
3
+ type MessagePipe,
4
+ type MessagePipeTarget,
5
+ newMessagePipe,
6
+ } from "@statewalker/webrun-streams";
7
+ import type { Room } from "livekit-client";
8
+
9
+ /**
10
+ * The largest data packet livekit-client (2.x) publishes: `RTCEngine` refuses
11
+ * a larger one with a `PublishDataError`. A post past it ends the pipe with a
12
+ * `RangeError` before it gets that far.
13
+ */
14
+ export const DEFAULT_MAX_FRAME_BYTES = 64_000;
15
+
16
+ /** The topic this pipe's packets carry; packets on other topics are someone else's. */
17
+ export const DEFAULT_TOPIC = "webrun/port-stack";
18
+
19
+ /**
20
+ * The topic of the goodbye a pipe sends when it ends on its own side. The room
21
+ * stays connected, so without it the peer would never learn the pipe is gone.
22
+ */
23
+ export const CLOSE_TOPIC = "webrun/port-stack/close";
24
+
25
+ /**
26
+ * The payload ceiling to give `overPipe`: 12 KiB, as this adapter has always
27
+ * used against a real SFU (an older client dropped larger reliable packets
28
+ * silently), well inside the packet cap with the port stack's framing.
29
+ */
30
+ export const DEFAULT_MAX_MESSAGE_SIZE = 12 * 1024;
31
+
32
+ /**
33
+ * `whenDrained` resolves once the bytes whose publish has not settled are at
34
+ * most this: the room can take more.
35
+ */
36
+ export const DRAIN_LOW_WATER = DEFAULT_DRAIN_LOW_WATER;
37
+
38
+ export interface MessageTargetOverLiveKitOptions {
39
+ /** The largest packet posted; past it the pipe ends with `RangeError`. Default {@link DEFAULT_MAX_FRAME_BYTES}. */
40
+ maxFrameBytes?: number;
41
+ /** The payload ceiling to report. Default {@link DEFAULT_MAX_MESSAGE_SIZE}. */
42
+ maxMessageSize?: number;
43
+ /**
44
+ * The data topic, default {@link DEFAULT_TOPIC}; the goodbye uses it with
45
+ * `/close` appended. Both ends must agree. Use another to run two pipes to
46
+ * the same participant.
47
+ */
48
+ topic?: string;
49
+ }
50
+
51
+ /** What `messageTargetOverLiveKit` gives: a pipe of bytes to one participant, its life, and its payload ceiling. */
52
+ export interface LiveKitMessageTarget extends MessagePipe {
53
+ /**
54
+ * A `MessageTarget` (as `@statewalker/webrun-rpc` defines it) whose messages
55
+ * are `Uint8Array`s, one reliable data packet each. A post past
56
+ * `maxFrameBytes` throws `RangeError` and ends the pipe; `close()` detaches
57
+ * from the room, which stays connected (it is the caller's);
58
+ * `bufferedAmount` counts bytes whose `publishData` has not settled, and
59
+ * `whenDrained` waits for it to reach {@link DRAIN_LOW_WATER}.
60
+ */
61
+ target: MessagePipeTarget;
62
+ /**
63
+ * Aborts when the room disconnects, the participant leaves, a publish fails
64
+ * (the stream above lost a message), or a post exceeds `maxFrameBytes`.
65
+ * Pass it as `overPipe`'s `signal`.
66
+ */
67
+ signal: AbortSignal;
68
+ /** Pass as `overPipe`'s `maxMessageSize`, so bodies are chunked under the packet limit. */
69
+ maxMessageSize: number;
70
+ }
71
+
72
+ /**
73
+ * One remote participant of a connected `Room` as a pipe of messages, for a
74
+ * multiplexer to run over:
75
+ *
76
+ * ```ts
77
+ * const { target, signal, maxMessageSize } = messageTargetOverLiveKit(room, "bob");
78
+ * const { call } = await connect({
79
+ * mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal, maxMessageSize }),
80
+ * });
81
+ * ```
82
+ *
83
+ * Packets go out reliable (ordered, retransmitted), addressed to that
84
+ * participant only and on their own topic; inbound packets from anyone else,
85
+ * or on another topic, are ignored. The participant must already be in the
86
+ * room (LiveKit drops packets to one it has not announced), or this throws.
87
+ * When the pipe ends on this side — `close()`, an oversized post, a failed
88
+ * publish — a goodbye on the close topic ends the peer's pipe too.
89
+ */
90
+ export function messageTargetOverLiveKit(
91
+ room: Room,
92
+ peerIdentity: string,
93
+ options: MessageTargetOverLiveKitOptions = {},
94
+ ): LiveKitMessageTarget {
95
+ const maxFrameBytes = options.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
96
+ const maxMessageSize = options.maxMessageSize ?? DEFAULT_MAX_MESSAGE_SIZE;
97
+ const topic = options.topic ?? DEFAULT_TOPIC;
98
+ const closeTopic = `${topic}/close`;
99
+ // Packets to a participant LiveKit does not know are dropped by the server,
100
+ // and no event would ever end the pipe.
101
+ const remotes = (room as unknown as { remoteParticipants?: Map<string, unknown> })
102
+ .remoteParticipants;
103
+ const present = remotes
104
+ ? remotes.has(peerIdentity) ||
105
+ [...remotes.values()].some((p) => (p as { identity?: string }).identity === peerIdentity)
106
+ : true;
107
+ if (!present) {
108
+ throw new Error(
109
+ `messageTargetOverLiveKit: "${peerIdentity}" is not in the room; wait for it to join`,
110
+ );
111
+ }
112
+ const roomApi = room as unknown as {
113
+ on(ev: string, fn: (...args: unknown[]) => void): void;
114
+ off(ev: string, fn: (...args: unknown[]) => void): void;
115
+ };
116
+ const publisher = room.localParticipant as unknown as {
117
+ publishData(
118
+ data: Uint8Array,
119
+ options: { reliable: boolean; destinationIdentities: string[]; topic: string },
120
+ ): Promise<void>;
121
+ };
122
+ let inFlight = 0;
123
+ const drainWaiters = new Set<() => void>();
124
+ const wakeDrainWaiters = (): void => {
125
+ if (inFlight > DRAIN_LOW_WATER) return;
126
+ for (const w of [...drainWaiters]) w();
127
+ drainWaiters.clear();
128
+ };
129
+
130
+ const onData = (...args: unknown[]): void => {
131
+ const [payload, participant, , packetTopic] = args as [
132
+ Uint8Array,
133
+ { identity?: string } | undefined,
134
+ unknown,
135
+ string | undefined,
136
+ ];
137
+ if (participant?.identity !== peerIdentity) return;
138
+ if (packetTopic === closeTopic) {
139
+ control.end(new Error(`webrun-streams-livekit: "${peerIdentity}" closed the pipe`));
140
+ return;
141
+ }
142
+ if (packetTopic !== topic) return;
143
+ control.deliver(payload);
144
+ };
145
+ const onDisconnected = (): void =>
146
+ control.end(new Error("webrun-streams-livekit: the room disconnected"));
147
+ const onParticipantDisconnected = (...args: unknown[]): void => {
148
+ if ((args[0] as { identity?: string } | undefined)?.identity !== peerIdentity) return;
149
+ control.end(new Error(`webrun-streams-livekit: "${peerIdentity}" left the room`));
150
+ };
151
+ const control = newMessagePipe(
152
+ {
153
+ send: (bytes) => {
154
+ const size = bytes.byteLength;
155
+ inFlight += size;
156
+ publisher
157
+ .publishData(bytes, { reliable: true, destinationIdentities: [peerIdentity], topic })
158
+ .then(
159
+ () => undefined,
160
+ // The stream above lost a message: end, and tell the peer.
161
+ (err: unknown) =>
162
+ control.end(
163
+ new Error(
164
+ `webrun-streams-livekit: a reliable publish failed: ${(err as Error)?.message ?? String(err)}`,
165
+ { cause: err },
166
+ ),
167
+ true,
168
+ ),
169
+ )
170
+ .finally(() => {
171
+ inFlight -= size;
172
+ wakeDrainWaiters();
173
+ });
174
+ },
175
+ bufferedAmount: () => inFlight,
176
+ whenDrained: () => new Promise<void>((resolve) => drainWaiters.add(resolve)),
177
+ /** `local`: the pipe ended on this side, and the room is still there to say so. */
178
+ close: (local) => {
179
+ roomApi.off("dataReceived", onData);
180
+ roomApi.off("disconnected", onDisconnected);
181
+ roomApi.off("participantDisconnected", onParticipantDisconnected);
182
+ drainWaiters.clear();
183
+ if (local) {
184
+ publisher
185
+ .publishData(new Uint8Array(0), {
186
+ reliable: true,
187
+ destinationIdentities: [peerIdentity],
188
+ topic: closeTopic,
189
+ })
190
+ .catch(() => undefined);
191
+ }
192
+ },
193
+ },
194
+ {
195
+ name: "webrun-streams-livekit",
196
+ maxFrameBytes,
197
+ maxMessageSize,
198
+ // livekit-client serializes the packet after an await, and may reuse
199
+ // the payload buffer it hands out.
200
+ copyOnSend: true,
201
+ copyOnDeliver: true,
202
+ },
203
+ );
204
+ roomApi.on("dataReceived", onData);
205
+ roomApi.on("disconnected", onDisconnected);
206
+ roomApi.on("participantDisconnected", onParticipantDisconnected);
207
+ return control.pipe as LiveKitMessageTarget;
208
+ }
@@ -1,9 +0,0 @@
1
- import type { ByteChannel } from "@statewalker/webrun-streams";
2
- import type { Room } from "livekit-client";
3
- /**
4
- * Wrap a connected LiveKit `Room` plus a remote participant identity into a
5
- * `ByteChannel`. Outbound bytes are addressed only to the named participant;
6
- * inbound is filtered by sender identity.
7
- */
8
- export declare function byteChannelFromLiveKit(room: Room, peerIdentity: string): 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,EAAqB,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAa9D;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,IAAI,EAAE,YAAY,EAAE,MAAM,GAAG,WAAW,CAsGpF"}
@@ -1,19 +0,0 @@
1
- import { type Connect, type EmulateMuxOptions, type Serve } from "@statewalker/webrun-streams";
2
- import type { Room } from "livekit-client";
3
- export interface LiveKitParams {
4
- /** Already-connected LiveKit `Room`. */
5
- room: Room;
6
- /** Identity of the remote participant the call addresses. */
7
- peerIdentity: string;
8
- /**
9
- * Flow-control tuning forwarded to `emulateMux` — `mtu` and
10
- * `maxStreamBuffer`, which is the credit this side advertises. `side` here
11
- * wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
12
- * suite's L6 uses this to run at a window small enough that a sender
13
- * genuinely stalls.
14
- */
15
- mux?: EmulateMuxOptions;
16
- }
17
- export declare const connect: Connect<LiveKitParams>;
18
- export declare const serve: Serve<LiveKitParams>;
19
- //# 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,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAkB3C,MAAM,WAAW,aAAa;IAC5B,wCAAwC;IACxC,IAAI,EAAE,IAAI,CAAC;IACX,6DAA6D;IAC7D,YAAY,EAAE,MAAM,CAAC;IACrB;;;;;;OAMG;IACH,GAAG,CAAC,EAAE,iBAAiB,CAAC;CACzB;AAED,eAAO,MAAM,OAAO,EAAE,OAAO,CAAC,aAAa,CAa1C,CAAC;AAEF,eAAO,MAAM,KAAK,EAAE,KAAK,CAAC,aAAa,CAmBtC,CAAC"}
@@ -1,122 +0,0 @@
1
- import type { ByteChannel } from "@statewalker/webrun-streams";
2
- import type { RemoteParticipant, Room } from "livekit-client";
3
-
4
- /**
5
- * livekit-client v2 `publishData` options shape. Reliable mode is ordered +
6
- * retransmitted; the bridged-byte contract requires this. `destinationIdentities`
7
- * restricts the publish to the named recipients so peer-to-peer pairings on the
8
- * same room don't fan out to every participant.
9
- */
10
- type DataPublishOptions = {
11
- reliable?: boolean;
12
- destinationIdentities?: string[];
13
- };
14
-
15
- /**
16
- * Wrap a connected LiveKit `Room` plus a remote participant identity into a
17
- * `ByteChannel`. Outbound bytes are addressed only to the named participant;
18
- * inbound is filtered by sender identity.
19
- */
20
- export function byteChannelFromLiveKit(room: Room, peerIdentity: string): ByteChannel {
21
- let closedResolve!: () => void;
22
- const closed = new Promise<void>((r) => {
23
- closedResolve = r;
24
- });
25
- let isClosed = false;
26
-
27
- const queue: Uint8Array[] = [];
28
- let pending: ((value: IteratorResult<Uint8Array>) => void) | null = null;
29
-
30
- const deliver = (bytes: Uint8Array): void => {
31
- if (isClosed) return;
32
- if (pending) {
33
- const r = pending;
34
- pending = null;
35
- r({ value: bytes, done: false });
36
- } else {
37
- queue.push(bytes);
38
- }
39
- };
40
-
41
- const onData = (payload: Uint8Array, participant?: RemoteParticipant): void => {
42
- if (!participant) return;
43
- if (participant.identity !== peerIdentity) return;
44
- deliver(new Uint8Array(payload));
45
- };
46
-
47
- const onDisconnected = (): void => {
48
- fireClose();
49
- };
50
-
51
- const onParticipantDisconnected = (participant: RemoteParticipant): void => {
52
- if (participant.identity !== peerIdentity) return;
53
- fireClose();
54
- };
55
-
56
- const fireClose = (): void => {
57
- if (isClosed) return;
58
- isClosed = true;
59
- roomApi.off("dataReceived", onData as (...args: unknown[]) => void);
60
- roomApi.off("disconnected", onDisconnected);
61
- roomApi.off(
62
- "participantDisconnected",
63
- onParticipantDisconnected as (...args: unknown[]) => void,
64
- );
65
- if (pending) {
66
- const r = pending;
67
- pending = null;
68
- r({ value: undefined, done: true } as IteratorResult<Uint8Array>);
69
- }
70
- closedResolve();
71
- };
72
-
73
- // livekit-client surfaces events via a typed emitter; coerce to the
74
- // structural on/off shape we need.
75
- const roomApi = room as unknown as {
76
- on(ev: string, fn: (...args: unknown[]) => void): void;
77
- off(ev: string, fn: (...args: unknown[]) => void): void;
78
- };
79
- roomApi.on("dataReceived", onData as (...args: unknown[]) => void);
80
- roomApi.on("disconnected", onDisconnected);
81
- roomApi.on("participantDisconnected", onParticipantDisconnected as (...args: unknown[]) => void);
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
- const publish = room.localParticipant as unknown as {
108
- publishData: (data: Uint8Array, options?: DataPublishOptions) => Promise<void>;
109
- };
110
- publish
111
- .publishData(bytes, { reliable: true, destinationIdentities: [peerIdentity] })
112
- .catch(() => {
113
- /* publish failure surfaces via disconnect events */
114
- });
115
- },
116
- recv,
117
- closed,
118
- close() {
119
- fireClose();
120
- },
121
- };
122
- }
@@ -1,75 +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 { Room } from "livekit-client";
9
- import { byteChannelFromLiveKit } from "./byte-channel.js";
10
-
11
- /**
12
- * Default `mtu` for this transport.
13
- *
14
- * `emulateMux` defaults to 64 KiB, which LiveKit cannot carry: a reliable data
15
- * packet is capped around 15 KiB, and anything larger is dropped rather than
16
- * fragmented. The symptom is not an error — a 1 MiB body simply arrives as
17
- * zero bytes and a 10 MiB body hangs — so the ceiling has to be applied here,
18
- * where the transport is known, rather than left to every caller.
19
- *
20
- * 12 KiB leaves room for the mux frame header (`[varint streamId][1-byte
21
- * type]`) inside that budget. An explicit `mux.mtu` still wins, so a caller who
22
- * knows their deployment allows more can raise it.
23
- */
24
- const LIVEKIT_SAFE_MTU = 12 * 1024;
25
-
26
- export interface LiveKitParams {
27
- /** Already-connected LiveKit `Room`. */
28
- room: Room;
29
- /** Identity of the remote participant the call addresses. */
30
- peerIdentity: string;
31
- /**
32
- * Flow-control tuning forwarded to `emulateMux` — `mtu` and
33
- * `maxStreamBuffer`, which is the credit this side advertises. `side` here
34
- * wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
35
- * suite's L6 uses this to run at a window small enough that a sender
36
- * genuinely stalls.
37
- */
38
- mux?: EmulateMuxOptions;
39
- }
40
-
41
- export const connect: Connect<LiveKitParams> = async ({ room, peerIdentity, mux: muxOpts }) => {
42
- const channel = byteChannelFromLiveKit(room, peerIdentity);
43
- const mux = emulateMux(channel, {
44
- mtu: LIVEKIT_SAFE_MTU,
45
- ...muxOpts,
46
- side: "initiator",
47
- });
48
- return {
49
- call: mux.call,
50
- async close() {
51
- await mux.close();
52
- },
53
- };
54
- };
55
-
56
- export const serve: Serve<LiveKitParams> = async (
57
- { room, peerIdentity, mux: muxOpts },
58
- handler: Duplex,
59
- ) => {
60
- const channel = byteChannelFromLiveKit(room, peerIdentity);
61
- const mux = emulateMux(channel, {
62
- mtu: LIVEKIT_SAFE_MTU,
63
- ...muxOpts,
64
- side: "responder",
65
- });
66
- const off = mux.serve(handler);
67
- void channel.closed.then(() => mux.close());
68
- let torn = false;
69
- return async () => {
70
- if (torn) return;
71
- torn = true;
72
- await off();
73
- await mux.close();
74
- };
75
- };