@statewalker/webrun-streams-signaling 0.1.6 → 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 +83 -36
- package/dist/byte-channel.d.ts +49 -9
- package/dist/byte-channel.d.ts.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +406 -56
- package/dist/message-target.d.ts +55 -0
- package/dist/message-target.d.ts.map +1 -0
- package/dist/peer-connection.d.ts +4 -3
- package/dist/peer-connection.d.ts.map +1 -1
- package/dist/peer-manager.d.ts +15 -4
- package/dist/peer-manager.d.ts.map +1 -1
- package/dist/qr-signaling.d.ts +2 -3
- package/dist/qr-signaling.d.ts.map +1 -1
- package/dist/room-manager.d.ts +5 -5
- package/dist/room-manager.d.ts.map +1 -1
- package/dist/types.d.ts +23 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +9 -6
- package/src/byte-channel.ts +188 -35
- package/src/index.ts +11 -3
- package/src/message-target.ts +137 -0
- package/src/peer-connection.ts +15 -2
- package/src/peer-manager.ts +71 -13
- package/src/qr-signaling.ts +56 -14
- package/src/room-manager.ts +6 -7
- package/src/types.ts +24 -3
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import type { ByteChannel } from "./types.js";
|
|
2
|
+
|
|
3
|
+
type Listener = (event: MessageEvent) => void | Promise<void>;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The payload ceiling for a channel over an `RTCDataChannel` (`PeerManager`,
|
|
7
|
+
* `QrSignaling`, `PeerConnection`): 16 KiB, the message size every browser
|
|
8
|
+
* pair delivers, less the 256 bytes the port stack's framing needs (spec D10).
|
|
9
|
+
* For a `byteChannelFromRoom` channel pass `maxMessageSize: 12 * 1024`, as
|
|
10
|
+
* `webrun-streams-livekit` uses: an older LiveKit client dropped larger
|
|
11
|
+
* reliable packets silently.
|
|
12
|
+
*/
|
|
13
|
+
export const DEFAULT_MAX_MESSAGE_SIZE = 16 * 1024 - 256;
|
|
14
|
+
|
|
15
|
+
/** What `messageTargetOverByteChannel` gives: a pipe of bytes, its life, and its payload ceiling. */
|
|
16
|
+
export interface ByteChannelMessageTarget {
|
|
17
|
+
/** A `MessageTarget` (as `@statewalker/webrun-rpc` defines it) of bytes, one channel message each. */
|
|
18
|
+
target: {
|
|
19
|
+
addEventListener(type: "message", listener: Listener): void;
|
|
20
|
+
removeEventListener(type: "message", listener: Listener): void;
|
|
21
|
+
/** Sends one message; `TypeError` for anything but bytes. */
|
|
22
|
+
postMessage(message: unknown): void;
|
|
23
|
+
/** Closes the channel. */
|
|
24
|
+
close(): Promise<void>;
|
|
25
|
+
/** The channel's `bufferedAmount`; 0 where it cannot tell. */
|
|
26
|
+
readonly bufferedAmount: number;
|
|
27
|
+
/**
|
|
28
|
+
* The channel's `whenDrained`: resolves once it can take more, or the pipe
|
|
29
|
+
* ended. Resolves at once over a channel without one.
|
|
30
|
+
*/
|
|
31
|
+
whenDrained(): Promise<void>;
|
|
32
|
+
};
|
|
33
|
+
/** Aborts when the channel closes. Pass it as `overPipe`'s `signal`. */
|
|
34
|
+
signal: AbortSignal;
|
|
35
|
+
/** Pass as `overPipe`'s `maxMessageSize`. */
|
|
36
|
+
maxMessageSize: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* A `ByteChannel` this package hands back (`PeerManager`, `QrSignaling`,
|
|
41
|
+
* `RoomManager`) as a pipe for `webrun-rpc`'s port stack:
|
|
42
|
+
*
|
|
43
|
+
* ```ts
|
|
44
|
+
* const { target, signal, maxMessageSize } = messageTargetOverByteChannel(channel);
|
|
45
|
+
* const { call } = await connect({
|
|
46
|
+
* mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal, maxMessageSize }),
|
|
47
|
+
* });
|
|
48
|
+
* ```
|
|
49
|
+
*
|
|
50
|
+
* It starts reading the channel at once, so attach listeners in the same tick;
|
|
51
|
+
* a message with no listener is dropped, as on a `MessagePort`. It must be the
|
|
52
|
+
* channel's only reader: a second reader of `recv` would take messages from it.
|
|
53
|
+
* Messages already received when the channel closes are still delivered.
|
|
54
|
+
*/
|
|
55
|
+
export function messageTargetOverByteChannel(
|
|
56
|
+
channel: ByteChannel,
|
|
57
|
+
options: { maxMessageSize?: number } = {},
|
|
58
|
+
): ByteChannelMessageTarget {
|
|
59
|
+
const listeners = new Set<Listener>();
|
|
60
|
+
const life = new AbortController();
|
|
61
|
+
let closedHere = false;
|
|
62
|
+
const end = (reason: Error): void => {
|
|
63
|
+
if (!life.signal.aborted) life.abort(reason);
|
|
64
|
+
};
|
|
65
|
+
void channel.closed.then(() => end(new Error("webrun-streams-signaling: the channel closed")));
|
|
66
|
+
void (async () => {
|
|
67
|
+
for await (const bytes of channel.recv) {
|
|
68
|
+
// The channel closing ends `recv` after what it already holds; only a
|
|
69
|
+
// close on this side stops delivery at once.
|
|
70
|
+
if (closedHere) break;
|
|
71
|
+
const event = new MessageEvent("message", { data: bytes.slice() });
|
|
72
|
+
for (const listener of [...listeners]) {
|
|
73
|
+
try {
|
|
74
|
+
Promise.resolve(listener(event)).catch(() => undefined);
|
|
75
|
+
} catch {}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
end(new Error("webrun-streams-signaling: the channel closed"));
|
|
79
|
+
})().catch((err: unknown) =>
|
|
80
|
+
end(err instanceof Error ? err : new Error(String(err), { cause: err })),
|
|
81
|
+
);
|
|
82
|
+
return {
|
|
83
|
+
signal: life.signal,
|
|
84
|
+
maxMessageSize: options.maxMessageSize ?? DEFAULT_MAX_MESSAGE_SIZE,
|
|
85
|
+
target: {
|
|
86
|
+
addEventListener: (_type, listener) => {
|
|
87
|
+
listeners.add(listener);
|
|
88
|
+
},
|
|
89
|
+
removeEventListener: (_type, listener) => {
|
|
90
|
+
listeners.delete(listener);
|
|
91
|
+
},
|
|
92
|
+
postMessage(message) {
|
|
93
|
+
const bytes =
|
|
94
|
+
message instanceof Uint8Array
|
|
95
|
+
? message
|
|
96
|
+
: message instanceof ArrayBuffer
|
|
97
|
+
? new Uint8Array(message)
|
|
98
|
+
: ArrayBuffer.isView(message)
|
|
99
|
+
? new Uint8Array(message.buffer, message.byteOffset, message.byteLength)
|
|
100
|
+
: undefined;
|
|
101
|
+
if (!bytes) {
|
|
102
|
+
throw new TypeError(
|
|
103
|
+
`webrun-streams-signaling: a byte pipe carries Uint8Array, ArrayBuffer or a view, got ${Object.prototype.toString.call(message)}`,
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
if (life.signal.aborted) return; // `signal` says so
|
|
107
|
+
channel.send(bytes.slice());
|
|
108
|
+
},
|
|
109
|
+
async close() {
|
|
110
|
+
listeners.clear();
|
|
111
|
+
closedHere = true;
|
|
112
|
+
end(new Error("webrun-streams-signaling: closed locally"));
|
|
113
|
+
try {
|
|
114
|
+
channel.close();
|
|
115
|
+
} catch {}
|
|
116
|
+
},
|
|
117
|
+
get bufferedAmount() {
|
|
118
|
+
return channel.bufferedAmount ?? 0;
|
|
119
|
+
},
|
|
120
|
+
whenDrained() {
|
|
121
|
+
if (life.signal.aborted || !channel.whenDrained) return Promise.resolve();
|
|
122
|
+
const signal = life.signal;
|
|
123
|
+
return new Promise<void>((resolve, reject) => {
|
|
124
|
+
const done = (): void => {
|
|
125
|
+
signal.removeEventListener("abort", done);
|
|
126
|
+
resolve();
|
|
127
|
+
};
|
|
128
|
+
signal.addEventListener("abort", done);
|
|
129
|
+
channel.whenDrained?.().then(done, (err: unknown) => {
|
|
130
|
+
signal.removeEventListener("abort", done);
|
|
131
|
+
reject(err);
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
}
|
package/src/peer-connection.ts
CHANGED
|
@@ -12,12 +12,12 @@
|
|
|
12
12
|
* - remote ICE candidates are added as plain `RTCIceCandidateInit` (accepted by
|
|
13
13
|
* `addIceCandidate`) instead of constructing a global `RTCIceCandidate`,
|
|
14
14
|
* which does not exist outside a browser.
|
|
15
|
-
* - `open()` yields a
|
|
15
|
+
* - `open()` yields a {@link ByteChannel} rather than a `MessagePort`.
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
|
-
import type { ByteChannel } from "@statewalker/webrun-streams";
|
|
19
18
|
import { byteChannelFromDataChannel } from "./byte-channel.js";
|
|
20
19
|
import type {
|
|
20
|
+
ByteChannel,
|
|
21
21
|
ConnectionState,
|
|
22
22
|
IceCandidate,
|
|
23
23
|
PeerConnectionEvents,
|
|
@@ -68,6 +68,11 @@ export class PeerConnection {
|
|
|
68
68
|
return this.role;
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
+
/** Whether the remote description (the peer's offer or answer) has been applied. */
|
|
72
|
+
hasRemoteDescription(): boolean {
|
|
73
|
+
return this.remoteDescriptionSet;
|
|
74
|
+
}
|
|
75
|
+
|
|
71
76
|
getDataChannel(): RTCDataChannel | null {
|
|
72
77
|
return this.dataChannel;
|
|
73
78
|
}
|
|
@@ -318,6 +323,7 @@ export class PeerConnection {
|
|
|
318
323
|
const cleanup = () => {
|
|
319
324
|
this.off("open", onOpen);
|
|
320
325
|
this.off("error", onError);
|
|
326
|
+
this.off("stateChange", onState);
|
|
321
327
|
clearTimeout(timer);
|
|
322
328
|
};
|
|
323
329
|
const onOpen = () => {
|
|
@@ -330,8 +336,15 @@ export class PeerConnection {
|
|
|
330
336
|
cleanup();
|
|
331
337
|
reject(error);
|
|
332
338
|
};
|
|
339
|
+
// Closed before the channel opened: it never will.
|
|
340
|
+
const onState = (state: ConnectionState) => {
|
|
341
|
+
if (state !== "closed") return;
|
|
342
|
+
cleanup();
|
|
343
|
+
reject(new Error("Connection closed before the data channel opened"));
|
|
344
|
+
};
|
|
333
345
|
this.on("open", onOpen);
|
|
334
346
|
this.on("error", onError);
|
|
347
|
+
this.on("stateChange", onState);
|
|
335
348
|
const timer = setTimeout(() => {
|
|
336
349
|
cleanup();
|
|
337
350
|
reject(new Error(`Connection timeout after ${timeout}ms`));
|
package/src/peer-manager.ts
CHANGED
|
@@ -4,16 +4,29 @@
|
|
|
4
4
|
* Wraps the low-level {@link PeerConnection} (relocated from
|
|
5
5
|
* `@statewalker/vcs-port-webrtc`) with a multi-peer, id-keyed surface: dial a
|
|
6
6
|
* peer with `connect(peerId)` or accept inbound dials via `onConnection`. Each
|
|
7
|
-
* established connection yields a
|
|
7
|
+
* established connection yields a {@link ByteChannel}. The WebRTC
|
|
8
8
|
* offer/answer/ICE routing is the original logic; only the routing-by-peer-id
|
|
9
9
|
* and the ByteChannel result are new.
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import type { ByteChannel } from "@statewalker/webrun-streams";
|
|
13
12
|
import { PeerConnection } from "./peer-connection.js";
|
|
14
|
-
import type {
|
|
13
|
+
import type {
|
|
14
|
+
ByteChannel,
|
|
15
|
+
SignalingMessage,
|
|
16
|
+
SignalingTransport,
|
|
17
|
+
WebRtcConnectionOptions,
|
|
18
|
+
} from "./types.js";
|
|
15
19
|
|
|
16
|
-
export type PeerManagerOptions = WebRtcConnectionOptions
|
|
20
|
+
export type PeerManagerOptions = WebRtcConnectionOptions & {
|
|
21
|
+
/**
|
|
22
|
+
* Called when a connection fails with no caller to tell: a signal it
|
|
23
|
+
* rejects (an offer during glare, malformed SDP or candidates), or an
|
|
24
|
+
* inbound connection whose channel never opens. The connection has already
|
|
25
|
+
* been closed and forgotten, so the peer can dial again. Errors are dropped
|
|
26
|
+
* when unset. A failed `connect()` rejects instead.
|
|
27
|
+
*/
|
|
28
|
+
onError?: (error: Error, peerId: string) => void;
|
|
29
|
+
};
|
|
17
30
|
|
|
18
31
|
export class PeerManager {
|
|
19
32
|
private readonly signaling: SignalingTransport;
|
|
@@ -30,10 +43,19 @@ export class PeerManager {
|
|
|
30
43
|
|
|
31
44
|
/** Dial `peerId` and resolve with the established channel. */
|
|
32
45
|
async connect(peerId: string): Promise<ByteChannel> {
|
|
46
|
+
// Dialing again replaces whatever connection to this peer there was.
|
|
47
|
+
const previous = this.connections.get(peerId);
|
|
48
|
+
if (previous) this.forget(peerId, previous);
|
|
33
49
|
const pc = this.makeConnection(peerId, "initiator");
|
|
34
50
|
const channel = pc.open();
|
|
35
|
-
|
|
36
|
-
|
|
51
|
+
try {
|
|
52
|
+
await pc.connect();
|
|
53
|
+
return await channel;
|
|
54
|
+
} catch (err) {
|
|
55
|
+
channel.catch(() => undefined);
|
|
56
|
+
this.forget(peerId, pc);
|
|
57
|
+
throw err;
|
|
58
|
+
}
|
|
37
59
|
}
|
|
38
60
|
|
|
39
61
|
/** Register a handler for inbound connections. Returns an unsubscribe fn. */
|
|
@@ -45,30 +67,66 @@ export class PeerManager {
|
|
|
45
67
|
/** Tear down all connections and stop listening for signaling. */
|
|
46
68
|
close(): void {
|
|
47
69
|
this.unsubscribe();
|
|
48
|
-
|
|
70
|
+
const all = [...this.connections.values()];
|
|
49
71
|
this.connections.clear();
|
|
72
|
+
for (const pc of all) pc.close();
|
|
50
73
|
this.connectionHandlers.clear();
|
|
51
74
|
}
|
|
52
75
|
|
|
53
76
|
private makeConnection(peerId: string, role: "initiator" | "responder"): PeerConnection {
|
|
54
77
|
const pc = new PeerConnection(role, this.options);
|
|
55
78
|
pc.on("signal", (msg) => this.signaling.send(peerId, msg));
|
|
56
|
-
pc.on("close", () => this.
|
|
79
|
+
pc.on("close", () => this.forget(peerId, pc));
|
|
80
|
+
// A failed connection never recovers: forget it so the peer's next offer
|
|
81
|
+
// starts a new one instead of reaching this one.
|
|
82
|
+
pc.on("stateChange", (state) => {
|
|
83
|
+
if (state === "failed" || state === "closed") this.forget(peerId, pc);
|
|
84
|
+
});
|
|
57
85
|
this.connections.set(peerId, pc);
|
|
58
86
|
return pc;
|
|
59
87
|
}
|
|
60
88
|
|
|
89
|
+
/** Close `pc` and drop it, unless a newer connection to `peerId` replaced it. */
|
|
90
|
+
private forget(peerId: string, pc: PeerConnection): void {
|
|
91
|
+
if (this.connections.get(peerId) !== pc) return;
|
|
92
|
+
this.connections.delete(peerId);
|
|
93
|
+
pc.close();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
private fail(peerId: string, pc: PeerConnection, err: unknown): void {
|
|
97
|
+
const live = this.connections.get(peerId) === pc;
|
|
98
|
+
this.forget(peerId, pc);
|
|
99
|
+
if (!live) return; // closed on purpose meanwhile
|
|
100
|
+
const error = err instanceof Error ? err : new Error(String(err), { cause: err });
|
|
101
|
+
try {
|
|
102
|
+
this.options.onError?.(error, peerId);
|
|
103
|
+
} catch {}
|
|
104
|
+
}
|
|
105
|
+
|
|
61
106
|
private onSignal(from: string, msg: SignalingMessage): void {
|
|
62
107
|
let pc = this.connections.get(from);
|
|
108
|
+
// A connection makes one offer, so a new offer from a peer we answered
|
|
109
|
+
// before, or whose answer we already applied, means it started over: the
|
|
110
|
+
// old connection is stale. (An offer to an initiator still waiting for
|
|
111
|
+
// its answer is glare: handleSignal rejects it below.)
|
|
112
|
+
if (pc && msg.type === "offer" && (pc.getRole() === "responder" || pc.hasRemoteDescription())) {
|
|
113
|
+
this.forget(from, pc);
|
|
114
|
+
pc = undefined;
|
|
115
|
+
}
|
|
63
116
|
if (!pc) {
|
|
64
117
|
// Only an inbound offer starts a new responder connection; stray
|
|
65
118
|
// candidates/answers for an unknown peer are ignored.
|
|
66
119
|
if (msg.type !== "offer") return;
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
120
|
+
const responder = this.makeConnection(from, "responder");
|
|
121
|
+
pc = responder;
|
|
122
|
+
responder.open().then(
|
|
123
|
+
(channel) => {
|
|
124
|
+
for (const handler of this.connectionHandlers) handler(from, channel);
|
|
125
|
+
},
|
|
126
|
+
(err: unknown) => this.fail(from, responder, err),
|
|
127
|
+
);
|
|
71
128
|
}
|
|
72
|
-
|
|
129
|
+
const target = pc;
|
|
130
|
+
target.handleSignal(msg).catch((err: unknown) => this.fail(from, target, err));
|
|
73
131
|
}
|
|
74
132
|
}
|
package/src/qr-signaling.ts
CHANGED
|
@@ -8,12 +8,12 @@
|
|
|
8
8
|
*
|
|
9
9
|
* The compress/expand/encode/decode functions are pure and unchanged; the
|
|
10
10
|
* {@link QrSignaling} class is adapted to the target API and yields
|
|
11
|
-
*
|
|
11
|
+
* {@link ByteChannel}s.
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
-
import type { ByteChannel } from "@statewalker/webrun-streams";
|
|
15
14
|
import { PeerConnection } from "./peer-connection.js";
|
|
16
15
|
import type {
|
|
16
|
+
ByteChannel,
|
|
17
17
|
CompressedSignal,
|
|
18
18
|
IceCandidate,
|
|
19
19
|
PeerRole,
|
|
@@ -67,15 +67,49 @@ function expandSdp(compressed: string): string {
|
|
|
67
67
|
return `${lines.join("\r\n")}\r\n`;
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
-
/**
|
|
70
|
+
/**
|
|
71
|
+
* Candidate attributes after `typ` that a connection needs: the related
|
|
72
|
+
* address of a srflx/relay candidate and the TCP type of a TCP one. Others
|
|
73
|
+
* (`generation`, `ufrag`, `network-id`, ...) are dropped to keep the QR small.
|
|
74
|
+
*/
|
|
75
|
+
const KEPT_CANDIDATE_ATTRIBUTES = new Set(["raddr", "rport", "tcptype"]);
|
|
76
|
+
|
|
77
|
+
/** An `sdpMLineIndex` as it travels: empty for null. */
|
|
78
|
+
function indexToString(index: number | null): string {
|
|
79
|
+
return index == null ? "" : String(index);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function indexFromString(text: string | undefined): number | null {
|
|
83
|
+
if (!text) return null;
|
|
84
|
+
const index = Number.parseInt(text, 10);
|
|
85
|
+
return Number.isNaN(index) ? null : index;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Compress an ICE candidate to its essential parts. A candidate that carries
|
|
90
|
+
* attributes a connection needs (see {@link KEPT_CANDIDATE_ATTRIBUTES}) goes
|
|
91
|
+
* in the raw (`R:`) form, with only those attributes kept.
|
|
92
|
+
*/
|
|
71
93
|
function compressCandidate(candidate: IceCandidate): string {
|
|
72
94
|
const { candidate: c, sdpMid, sdpMLineIndex } = candidate;
|
|
73
|
-
const
|
|
95
|
+
const index = indexToString(sdpMLineIndex);
|
|
96
|
+
const match = c.match(
|
|
97
|
+
/candidate:(\S+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(\S+)\s+(\d+)\s+typ\s+(\S+)(.*)$/,
|
|
98
|
+
);
|
|
74
99
|
if (!match) {
|
|
75
|
-
return `R:${sdpMid ?? ""}:${
|
|
100
|
+
return `R:${sdpMid ?? ""}:${index}:${c}`;
|
|
76
101
|
}
|
|
77
|
-
const [, foundation, component, protocol, priority, ip, port, type] = match;
|
|
78
|
-
|
|
102
|
+
const [base, foundation, component, protocol, priority, ip, port, type, rest] = match;
|
|
103
|
+
const words = rest.trim().split(/\s+/).filter(Boolean);
|
|
104
|
+
const kept: string[] = [];
|
|
105
|
+
for (let i = 0; i + 1 < words.length; i += 2) {
|
|
106
|
+
if (KEPT_CANDIDATE_ATTRIBUTES.has(words[i])) kept.push(words[i], words[i + 1]);
|
|
107
|
+
}
|
|
108
|
+
if (kept.length) {
|
|
109
|
+
const head = base.slice(0, base.length - rest.length);
|
|
110
|
+
return `R:${sdpMid ?? ""}:${index}:${head} ${kept.join(" ")}`;
|
|
111
|
+
}
|
|
112
|
+
return `${foundation}|${component}|${protocol}|${priority}|${ip}|${port}|${type}|${sdpMid ?? ""}|${index}`;
|
|
79
113
|
}
|
|
80
114
|
|
|
81
115
|
/** Expand a compressed ICE candidate. */
|
|
@@ -85,7 +119,7 @@ function expandCandidate(compressed: string): IceCandidate {
|
|
|
85
119
|
return {
|
|
86
120
|
candidate: rest.join(":"),
|
|
87
121
|
sdpMid: sdpMid || null,
|
|
88
|
-
sdpMLineIndex:
|
|
122
|
+
sdpMLineIndex: indexFromString(sdpMLineIndexStr),
|
|
89
123
|
};
|
|
90
124
|
}
|
|
91
125
|
const parts = compressed.split("|");
|
|
@@ -98,7 +132,7 @@ function expandCandidate(compressed: string): IceCandidate {
|
|
|
98
132
|
return {
|
|
99
133
|
candidate,
|
|
100
134
|
sdpMid: sdpMid || null,
|
|
101
|
-
sdpMLineIndex:
|
|
135
|
+
sdpMLineIndex: indexFromString(sdpMLineIndexStr),
|
|
102
136
|
};
|
|
103
137
|
}
|
|
104
138
|
|
|
@@ -181,7 +215,6 @@ export class QrSignaling {
|
|
|
181
215
|
/** Create an offer QR; `accept(answerQr)` finishes the handshake. */
|
|
182
216
|
async offer(): Promise<{ qr: string; accept(answerQr: string): Promise<ByteChannel> }> {
|
|
183
217
|
const pc = new PeerConnection("initiator", this.connection);
|
|
184
|
-
const channel = pc.open();
|
|
185
218
|
await pc.connect();
|
|
186
219
|
await pc.waitForIceGathering();
|
|
187
220
|
|
|
@@ -194,10 +227,19 @@ export class QrSignaling {
|
|
|
194
227
|
return {
|
|
195
228
|
qr,
|
|
196
229
|
accept: async (answerQr: string): Promise<ByteChannel> => {
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
230
|
+
// The connection timeout starts here, not at offer time: the QR
|
|
231
|
+
// exchange between the two takes as long as the people take.
|
|
232
|
+
const channel = pc.open();
|
|
233
|
+
try {
|
|
234
|
+
const parsed = parseCompressedSignal(decodeSignal(answerQr));
|
|
235
|
+
await pc.handleSignal({ type: "answer", sdp: parsed.description.sdp });
|
|
236
|
+
for (const candidate of parsed.candidates) {
|
|
237
|
+
await pc.handleSignal({ type: "candidate", candidate });
|
|
238
|
+
}
|
|
239
|
+
} catch (err) {
|
|
240
|
+
channel.catch(() => undefined);
|
|
241
|
+
pc.close();
|
|
242
|
+
throw err;
|
|
201
243
|
}
|
|
202
244
|
return channel;
|
|
203
245
|
},
|
package/src/room-manager.ts
CHANGED
|
@@ -4,16 +4,15 @@
|
|
|
4
4
|
* Relocated from `@statewalker/vcs-port-livekit`'s `RoomManager` and adapted to
|
|
5
5
|
* the target API: `join`/`participants`/`channelTo`/`leave`. Participant
|
|
6
6
|
* tracking is the original event-wiring; `channelTo` yields a per-participant
|
|
7
|
-
*
|
|
7
|
+
* {@link ByteChannel} (see {@link byteChannelFromRoom}).
|
|
8
8
|
*
|
|
9
9
|
* The vendor (`livekit-client`) stays an optional peerDependency: the `Room` is
|
|
10
10
|
* injected via {@link RoomManagerOptions.roomFactory} (production:
|
|
11
11
|
* `() => new Room()`), so this module never hard-imports it.
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
-
import type
|
|
15
|
-
import {
|
|
16
|
-
import type { RoomLike, RoomManagerOptions, RoomParticipantLike } from "./types.js";
|
|
14
|
+
import { type ByteChannelFromRoomOptions, byteChannelFromRoom } from "./byte-channel.js";
|
|
15
|
+
import type { ByteChannel, RoomLike, RoomManagerOptions, RoomParticipantLike } from "./types.js";
|
|
17
16
|
import { ROOM_EVENT } from "./types.js";
|
|
18
17
|
|
|
19
18
|
export class RoomManager {
|
|
@@ -95,10 +94,10 @@ export class RoomManager {
|
|
|
95
94
|
};
|
|
96
95
|
}
|
|
97
96
|
|
|
98
|
-
/** Open a {@link ByteChannel} to a specific participant. */
|
|
99
|
-
async channelTo(peerId: string): Promise<ByteChannel> {
|
|
97
|
+
/** Open a {@link ByteChannel} to a specific participant (see {@link byteChannelFromRoom}). */
|
|
98
|
+
async channelTo(peerId: string, options?: ByteChannelFromRoomOptions): Promise<ByteChannel> {
|
|
100
99
|
if (!this.room) throw new Error("channelTo() before join()");
|
|
101
|
-
return byteChannelFromRoom(this.room, peerId);
|
|
100
|
+
return byteChannelFromRoom(this.room, peerId, options);
|
|
102
101
|
}
|
|
103
102
|
|
|
104
103
|
/** Leave the room: unsubscribe and disconnect. */
|
package/src/types.ts
CHANGED
|
@@ -4,10 +4,30 @@
|
|
|
4
4
|
* Relocated from the retiring `@statewalker/vcs-port-{webrtc,livekit}` packages
|
|
5
5
|
* and neutralised: nothing here is VCS/Git-specific. These describe the generic
|
|
6
6
|
* P2P handshake (WebRTC offer/answer/ICE, QR payloads, LiveKit room membership)
|
|
7
|
-
* used to *establish* a channel
|
|
8
|
-
*
|
|
7
|
+
* used to *establish* a channel, and the `ByteChannel` an established data
|
|
8
|
+
* channel is handed back as.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
+
/**
|
|
12
|
+
* An established connection's bytes: inbound as an async iterable, outbound by
|
|
13
|
+
* `send`, message-oriented (each `send` arrives as one item). This package
|
|
14
|
+
* owns the type: it used to come from `@statewalker/webrun-streams`, whose
|
|
15
|
+
* `emulateMux` (its only other consumer) is gone.
|
|
16
|
+
*/
|
|
17
|
+
export type ByteChannel = {
|
|
18
|
+
send(bytes: Uint8Array): void;
|
|
19
|
+
recv: AsyncIterable<Uint8Array>;
|
|
20
|
+
closed: Promise<void>;
|
|
21
|
+
close(): void;
|
|
22
|
+
/** Bytes sent and not yet written out, where the transport can tell. */
|
|
23
|
+
readonly bufferedAmount?: number;
|
|
24
|
+
/**
|
|
25
|
+
* Resolves once the transport can take more (`bufferedAmount` at most a
|
|
26
|
+
* low-water mark) or the channel closed. Absent where it cannot tell.
|
|
27
|
+
*/
|
|
28
|
+
whenDrained?(): Promise<void>;
|
|
29
|
+
};
|
|
30
|
+
|
|
11
31
|
/** WebRTC peer role in the connection. */
|
|
12
32
|
export type PeerRole = "initiator" | "responder";
|
|
13
33
|
|
|
@@ -146,7 +166,7 @@ export interface RoomParticipantLike {
|
|
|
146
166
|
export interface RoomLocalParticipantLike {
|
|
147
167
|
publishData(
|
|
148
168
|
data: Uint8Array,
|
|
149
|
-
opts?: { reliable?: boolean; destinationIdentities?: string[] },
|
|
169
|
+
opts?: { reliable?: boolean; destinationIdentities?: string[]; topic?: string },
|
|
150
170
|
): Promise<void>;
|
|
151
171
|
}
|
|
152
172
|
|
|
@@ -173,5 +193,6 @@ export interface RoomManagerOptions {
|
|
|
173
193
|
export const ROOM_EVENT = {
|
|
174
194
|
participantConnected: "participantConnected",
|
|
175
195
|
participantDisconnected: "participantDisconnected",
|
|
196
|
+
disconnected: "disconnected",
|
|
176
197
|
dataReceived: "dataReceived",
|
|
177
198
|
} as const;
|