@kyneta/webrtc-transport 1.3.1 → 1.5.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/dist/index.d.ts +125 -122
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +263 -222
- package/dist/index.js.map +1 -1
- package/package.json +9 -9
- package/src/__tests__/webrtc-transport.test.ts +33 -25
- package/src/webrtc-transport.ts +35 -11
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { GeneratedChannel, Transport, TransportFactory } from "@kyneta/transport";
|
|
2
2
|
|
|
3
|
+
//#region src/data-channel-like.d.ts
|
|
3
4
|
/**
|
|
4
5
|
* Minimal interface for a WebRTC-style data channel.
|
|
5
6
|
*
|
|
@@ -27,61 +28,62 @@ import { Transport, GeneratedChannel, TransportFactory } from '@kyneta/transport
|
|
|
27
28
|
* the WebRTC connection lifecycle independently.
|
|
28
29
|
*/
|
|
29
30
|
interface DataChannelLike {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
31
|
+
/**
|
|
32
|
+
* Current state of the data channel.
|
|
33
|
+
*
|
|
34
|
+
* The transport treats `"open"` as sendable; all other values
|
|
35
|
+
* (including `"connecting"`, `"closing"`, `"closed"`) as not sendable.
|
|
36
|
+
*
|
|
37
|
+
* For native `RTCDataChannel`, this is one of:
|
|
38
|
+
* `"connecting" | "open" | "closing" | "closed"`.
|
|
39
|
+
*
|
|
40
|
+
* Wrappers may return any string — the transport only checks `=== "open"`.
|
|
41
|
+
*/
|
|
42
|
+
readonly readyState: string;
|
|
43
|
+
/**
|
|
44
|
+
* Binary type hint for incoming data.
|
|
45
|
+
*
|
|
46
|
+
* The transport writes `"arraybuffer"` on attach as a best-effort hint.
|
|
47
|
+
* It does NOT depend on this being respected — the message handler
|
|
48
|
+
* accepts both `ArrayBuffer` and `Uint8Array` data regardless.
|
|
49
|
+
*
|
|
50
|
+
* For native `RTCDataChannel`, this controls whether `MessageEvent.data`
|
|
51
|
+
* is an `ArrayBuffer` or a `Blob`. For wrappers that ignore this
|
|
52
|
+
* property (e.g. simple-peer bridges), the write is harmless.
|
|
53
|
+
*/
|
|
54
|
+
binaryType: string;
|
|
55
|
+
/**
|
|
56
|
+
* Send binary data through the data channel.
|
|
57
|
+
*
|
|
58
|
+
* The transport always sends `Uint8Array` instances (CBOR-encoded
|
|
59
|
+
* wire frames, optionally fragmented). Native `RTCDataChannel.send`
|
|
60
|
+
* accepts `ArrayBufferView` (which `Uint8Array` satisfies), so
|
|
61
|
+
* conformance is structural.
|
|
62
|
+
*/
|
|
63
|
+
send(data: Uint8Array): void;
|
|
64
|
+
/**
|
|
65
|
+
* Register an event listener.
|
|
66
|
+
*
|
|
67
|
+
* The transport uses this for `"open"`, `"close"`, `"error"`, and
|
|
68
|
+
* `"message"` events. For `"message"` events, the transport reads
|
|
69
|
+
* `event.data` and handles both `ArrayBuffer` and `Uint8Array`.
|
|
70
|
+
*
|
|
71
|
+
* @param type - Event type string
|
|
72
|
+
* @param listener - Callback. The `event` parameter is untyped to
|
|
73
|
+
* avoid coupling to DOM `Event` / `MessageEvent` types.
|
|
74
|
+
*/
|
|
75
|
+
addEventListener(type: string, listener: (event: any) => void): void;
|
|
76
|
+
/**
|
|
77
|
+
* Remove a previously registered event listener.
|
|
78
|
+
*
|
|
79
|
+
* Called during `detachDataChannel()` to clean up all four event
|
|
80
|
+
* listeners. The transport always passes the same function reference
|
|
81
|
+
* that was used in `addEventListener`.
|
|
82
|
+
*/
|
|
83
|
+
removeEventListener(type: string, listener: (event: any) => void): void;
|
|
83
84
|
}
|
|
84
|
-
|
|
85
|
+
//#endregion
|
|
86
|
+
//#region src/webrtc-transport.d.ts
|
|
85
87
|
/**
|
|
86
88
|
* Default fragment threshold in bytes.
|
|
87
89
|
*
|
|
@@ -96,20 +98,20 @@ declare const DEFAULT_FRAGMENT_THRESHOLD: number;
|
|
|
96
98
|
* Configuration options for the WebRTC transport.
|
|
97
99
|
*/
|
|
98
100
|
interface WebrtcTransportOptions {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
101
|
+
/**
|
|
102
|
+
* Fragment threshold in bytes. Messages larger than this are fragmented
|
|
103
|
+
* for SCTP compatibility. Set to 0 to disable fragmentation (not recommended).
|
|
104
|
+
*
|
|
105
|
+
* @default 204800 (200KB)
|
|
106
|
+
*/
|
|
107
|
+
fragmentThreshold?: number;
|
|
106
108
|
}
|
|
107
109
|
/**
|
|
108
110
|
* Context for each attached data channel — stored per remotePeerId.
|
|
109
111
|
*/
|
|
110
112
|
type DataChannelContext = {
|
|
111
|
-
|
|
112
|
-
|
|
113
|
+
remotePeerId: string;
|
|
114
|
+
channel: DataChannelLike;
|
|
113
115
|
};
|
|
114
116
|
/**
|
|
115
117
|
* WebRTC data channel transport for @kyneta/exchange.
|
|
@@ -130,7 +132,7 @@ type DataChannelContext = {
|
|
|
130
132
|
* const webrtcTransport = createWebrtcTransport()
|
|
131
133
|
*
|
|
132
134
|
* const exchange = new Exchange({
|
|
133
|
-
*
|
|
135
|
+
* id: { peerId: "alice", name: "Alice" },
|
|
134
136
|
* transports: [webrtcTransport],
|
|
135
137
|
* })
|
|
136
138
|
*
|
|
@@ -149,61 +151,61 @@ type DataChannelContext = {
|
|
|
149
151
|
* WebRTC connection lifecycle independently.
|
|
150
152
|
*/
|
|
151
153
|
declare class WebrtcTransport extends Transport<DataChannelContext> {
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
154
|
+
#private;
|
|
155
|
+
constructor(options?: WebrtcTransportOptions);
|
|
156
|
+
/**
|
|
157
|
+
* Generate a channel for a data channel context.
|
|
158
|
+
*
|
|
159
|
+
* Called internally by the `Transport` base class when `addChannel()` is
|
|
160
|
+
* invoked. Users never call this directly — use `attachDataChannel()`.
|
|
161
|
+
*/
|
|
162
|
+
protected generate(context: DataChannelContext): GeneratedChannel;
|
|
163
|
+
/**
|
|
164
|
+
* Called when the transport starts.
|
|
165
|
+
*
|
|
166
|
+
* No-op for WebRTC — channels are added dynamically via
|
|
167
|
+
* `attachDataChannel()`, not at start time.
|
|
168
|
+
*/
|
|
169
|
+
onStart(): Promise<void>;
|
|
170
|
+
/**
|
|
171
|
+
* Called when the transport stops.
|
|
172
|
+
*
|
|
173
|
+
* Detaches all attached data channels and cleans up resources.
|
|
174
|
+
*/
|
|
175
|
+
onStop(): Promise<void>;
|
|
176
|
+
/**
|
|
177
|
+
* Attach a data channel for a remote peer.
|
|
178
|
+
*
|
|
179
|
+
* Creates an internal sync channel when the data channel is open
|
|
180
|
+
* (or waits for the `"open"` event if still connecting). The sync
|
|
181
|
+
* channel triggers the establishment handshake with the remote peer.
|
|
182
|
+
*
|
|
183
|
+
* If a data channel is already attached for this peer, the old one
|
|
184
|
+
* is detached first.
|
|
185
|
+
*
|
|
186
|
+
* @param remotePeerId - The stable peer ID of the remote peer
|
|
187
|
+
* @param channel - Any object satisfying `DataChannelLike`
|
|
188
|
+
* @returns A cleanup function that calls `detachDataChannel(remotePeerId)`
|
|
189
|
+
*/
|
|
190
|
+
attachDataChannel(remotePeerId: string, channel: DataChannelLike): () => void;
|
|
191
|
+
/**
|
|
192
|
+
* Detach a data channel for a remote peer.
|
|
193
|
+
*
|
|
194
|
+
* Removes the sync channel, cleans up event listeners, and disposes
|
|
195
|
+
* the reassembler. Does NOT close the data channel — the application
|
|
196
|
+
* manages the WebRTC connection lifecycle.
|
|
197
|
+
*
|
|
198
|
+
* @param remotePeerId - The peer ID to detach
|
|
199
|
+
*/
|
|
200
|
+
detachDataChannel(remotePeerId: string): void;
|
|
201
|
+
/**
|
|
202
|
+
* Check if a data channel is attached for a peer.
|
|
203
|
+
*/
|
|
204
|
+
hasDataChannel(remotePeerId: string): boolean;
|
|
205
|
+
/**
|
|
206
|
+
* Get all peer IDs with attached data channels.
|
|
207
|
+
*/
|
|
208
|
+
getAttachedPeerIds(): string[];
|
|
207
209
|
}
|
|
208
210
|
/**
|
|
209
211
|
* Create a WebRTC transport factory for use with `Exchange`.
|
|
@@ -222,11 +224,12 @@ declare class WebrtcTransport extends Transport<DataChannelContext> {
|
|
|
222
224
|
* import { createWebrtcTransport } from "@kyneta/webrtc-transport"
|
|
223
225
|
*
|
|
224
226
|
* const exchange = new Exchange({
|
|
225
|
-
*
|
|
227
|
+
* id: { peerId: "alice", name: "Alice" },
|
|
226
228
|
* transports: [createWebrtcTransport()],
|
|
227
229
|
* })
|
|
228
230
|
* ```
|
|
229
231
|
*/
|
|
230
232
|
declare function createWebrtcTransport(options?: WebrtcTransportOptions): TransportFactory;
|
|
231
|
-
|
|
233
|
+
//#endregion
|
|
232
234
|
export { DEFAULT_FRAGMENT_THRESHOLD, type DataChannelLike, WebrtcTransport, type WebrtcTransportOptions, createWebrtcTransport };
|
|
235
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/data-channel-like.ts","../src/webrtc-transport.ts"],"mappings":";;;;;;AA6CA;;;;;;;;;;;;;;;;;;;;;;ACCA;UDDiB,eAAA;;;;ACUjB;;;;;AAQC;;;WDNU,UAAA;ECgBT;;;;;AA2DF;;;;;;ED9DE,UAAA;ECyHiB;;;;;;;;ED/GjB,IAAA,CAAK,IAAA,EAAM,UAAA;;;;;;;;;;;;EAaX,gBAAA,CAAiB,IAAA,UAAc,QAAA,GAAW,KAAA;ECkIxC;;;;;;;EDzHF,mBAAA,CAAoB,IAAA,UAAc,QAAA,GAAW,KAAA;AAAA;;;AAzD/C;;;;;;;;;AAAA,cCCa,0BAAA;;;;UASI,sBAAA;ED+CK;;;;;;ECxCpB,iBAAA;AAAA;AAhBF;;;AAAA,KA0BK,kBAAA;EACH,YAAA;EACA,OAAA,EAAS,eAAA;AAAA;;;;AAXV;;;;;;;;;AAqED;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,eAAA,SAAwB,SAAA,CAAU,kBAAA;EAAA;cAWjC,OAAA,GAAU,sBAAA;EAgFpB;;;;;;EAAA,UAhEQ,QAAA,CAAS,OAAA,EAAS,kBAAA,GAAqB,gBAAA;EAuKjD;;;AA+HF;;;EAtQQ,OAAA,CAAA,GAAW,OAAA;EAuQP;;;;;EAhQJ,MAAA,CAAA,GAAU,OAAA;;;;;;;;;;;;;;;EAwBhB,iBAAA,CACE,YAAA,UACA,OAAA,EAAS,eAAA;;;;;;;;;;EA2EX,iBAAA,CAAkB,YAAA;;;;EAoBlB,cAAA,CAAe,YAAA;;;;EAOf,kBAAA,CAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;iBA+Hc,qBAAA,CACd,OAAA,GAAU,sBAAA,GACT,gBAAA"}
|
package/dist/index.js
CHANGED
|
@@ -1,228 +1,269 @@
|
|
|
1
|
-
// src/webrtc-transport.ts
|
|
2
1
|
import { Transport } from "@kyneta/transport";
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
2
|
+
import { FragmentReassembler, applyInboundAliasing, applyOutboundAliasing, createFrameIdCounter, decodeBinaryWires, emptyAliasState, encodeWireFrameAndSend } from "@kyneta/wire";
|
|
3
|
+
//#region src/webrtc-transport.ts
|
|
4
|
+
/**
|
|
5
|
+
* Default fragment threshold in bytes.
|
|
6
|
+
*
|
|
7
|
+
* SCTP (the underlying transport for WebRTC data channels) has a message
|
|
8
|
+
* size limit of approximately 256KB. 200KB provides a safe margin.
|
|
9
|
+
*
|
|
10
|
+
* This differs from the WebSocket transport's 100KB default, which
|
|
11
|
+
* targets AWS API Gateway's 128KB limit. WebRTC has no such gateway.
|
|
12
|
+
*/
|
|
13
|
+
const DEFAULT_FRAGMENT_THRESHOLD = 200 * 1024;
|
|
14
|
+
/**
|
|
15
|
+
* WebRTC data channel transport for @kyneta/exchange.
|
|
16
|
+
*
|
|
17
|
+
* Follows a "Bring Your Own Data Channel" (BYODC) design — the application
|
|
18
|
+
* manages WebRTC connections and attaches data channels to this transport
|
|
19
|
+
* for kyneta document synchronization.
|
|
20
|
+
*
|
|
21
|
+
* Uses binary CBOR encoding with transport-level fragmentation via
|
|
22
|
+
* `@kyneta/wire` — the same pipeline as the WebSocket transport.
|
|
23
|
+
*
|
|
24
|
+
* ## Usage
|
|
25
|
+
*
|
|
26
|
+
* ```typescript
|
|
27
|
+
* import { Exchange } from "@kyneta/exchange"
|
|
28
|
+
* import { createWebrtcTransport } from "@kyneta/webrtc-transport"
|
|
29
|
+
*
|
|
30
|
+
* const webrtcTransport = createWebrtcTransport()
|
|
31
|
+
*
|
|
32
|
+
* const exchange = new Exchange({
|
|
33
|
+
* id: { peerId: "alice", name: "Alice" },
|
|
34
|
+
* transports: [webrtcTransport],
|
|
35
|
+
* })
|
|
36
|
+
*
|
|
37
|
+
* // When a WebRTC connection is established:
|
|
38
|
+
* const cleanup = transport.attachDataChannel(remotePeerId, dataChannel)
|
|
39
|
+
*
|
|
40
|
+
* // When done:
|
|
41
|
+
* cleanup() // or transport.detachDataChannel(remotePeerId)
|
|
42
|
+
* ```
|
|
43
|
+
*
|
|
44
|
+
* ## Ownership
|
|
45
|
+
*
|
|
46
|
+
* The transport does NOT own the data channel. `detachDataChannel()`
|
|
47
|
+
* removes the sync channel and event listeners but does not close the
|
|
48
|
+
* data channel or the peer connection. The application manages the
|
|
49
|
+
* WebRTC connection lifecycle independently.
|
|
50
|
+
*/
|
|
9
51
|
var WebrtcTransport = class extends Transport {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
const syncChannel = this.channels.get(attached.channelId);
|
|
199
|
-
if (!syncChannel) return;
|
|
200
|
-
const raw = event.data;
|
|
201
|
-
const bytes = raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw instanceof Uint8Array ? raw : null;
|
|
202
|
-
if (!bytes) {
|
|
203
|
-
return;
|
|
204
|
-
}
|
|
205
|
-
try {
|
|
206
|
-
const messages = decodeBinaryMessages(bytes, attached.reassembler);
|
|
207
|
-
if (messages) {
|
|
208
|
-
for (const msg of messages) {
|
|
209
|
-
syncChannel.onReceive(msg);
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
} catch (error) {
|
|
213
|
-
console.error(
|
|
214
|
-
`[webrtc-transport] Failed to decode message from peer ${remotePeerId}:`,
|
|
215
|
-
error
|
|
216
|
-
);
|
|
217
|
-
}
|
|
218
|
-
}
|
|
52
|
+
/**
|
|
53
|
+
* Map of remotePeerId → attached channel tracking.
|
|
54
|
+
*/
|
|
55
|
+
#attachedChannels = /* @__PURE__ */ new Map();
|
|
56
|
+
/**
|
|
57
|
+
* Fragment threshold in bytes.
|
|
58
|
+
*/
|
|
59
|
+
#fragmentThreshold;
|
|
60
|
+
constructor(options) {
|
|
61
|
+
super({ transportType: "webrtc-datachannel" });
|
|
62
|
+
this.#fragmentThreshold = options?.fragmentThreshold ?? 204800;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Generate a channel for a data channel context.
|
|
66
|
+
*
|
|
67
|
+
* Called internally by the `Transport` base class when `addChannel()` is
|
|
68
|
+
* invoked. Users never call this directly — use `attachDataChannel()`.
|
|
69
|
+
*/
|
|
70
|
+
generate(context) {
|
|
71
|
+
const { channel } = context;
|
|
72
|
+
return {
|
|
73
|
+
transportType: this.transportType,
|
|
74
|
+
send: (msg) => {
|
|
75
|
+
const attached = this.#attachedChannels.get(context.remotePeerId);
|
|
76
|
+
if (!attached || channel.readyState !== "open") return;
|
|
77
|
+
const { state, wire } = applyOutboundAliasing(attached.aliasState, msg);
|
|
78
|
+
attached.aliasState = state;
|
|
79
|
+
encodeWireFrameAndSend(wire, (data) => channel.send(data), this.#fragmentThreshold, attached.nextFrameId);
|
|
80
|
+
},
|
|
81
|
+
stop: () => {}
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Called when the transport starts.
|
|
86
|
+
*
|
|
87
|
+
* No-op for WebRTC — channels are added dynamically via
|
|
88
|
+
* `attachDataChannel()`, not at start time.
|
|
89
|
+
*/
|
|
90
|
+
async onStart() {}
|
|
91
|
+
/**
|
|
92
|
+
* Called when the transport stops.
|
|
93
|
+
*
|
|
94
|
+
* Detaches all attached data channels and cleans up resources.
|
|
95
|
+
*/
|
|
96
|
+
async onStop() {
|
|
97
|
+
for (const remotePeerId of [...this.#attachedChannels.keys()]) this.detachDataChannel(remotePeerId);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Attach a data channel for a remote peer.
|
|
101
|
+
*
|
|
102
|
+
* Creates an internal sync channel when the data channel is open
|
|
103
|
+
* (or waits for the `"open"` event if still connecting). The sync
|
|
104
|
+
* channel triggers the establishment handshake with the remote peer.
|
|
105
|
+
*
|
|
106
|
+
* If a data channel is already attached for this peer, the old one
|
|
107
|
+
* is detached first.
|
|
108
|
+
*
|
|
109
|
+
* @param remotePeerId - The stable peer ID of the remote peer
|
|
110
|
+
* @param channel - Any object satisfying `DataChannelLike`
|
|
111
|
+
* @returns A cleanup function that calls `detachDataChannel(remotePeerId)`
|
|
112
|
+
*/
|
|
113
|
+
attachDataChannel(remotePeerId, channel) {
|
|
114
|
+
if (this.#attachedChannels.has(remotePeerId)) this.detachDataChannel(remotePeerId);
|
|
115
|
+
channel.binaryType = "arraybuffer";
|
|
116
|
+
const reassembler = new FragmentReassembler({ timeoutMs: 1e4 });
|
|
117
|
+
const onOpen = () => {
|
|
118
|
+
this.#createSyncChannel(remotePeerId);
|
|
119
|
+
};
|
|
120
|
+
const onClose = () => {
|
|
121
|
+
this.#removeSyncChannel(remotePeerId);
|
|
122
|
+
};
|
|
123
|
+
const onError = () => {
|
|
124
|
+
this.#removeSyncChannel(remotePeerId);
|
|
125
|
+
};
|
|
126
|
+
const onMessage = (event) => {
|
|
127
|
+
this.#handleMessage(remotePeerId, event);
|
|
128
|
+
};
|
|
129
|
+
const cleanup = () => {
|
|
130
|
+
channel.removeEventListener("open", onOpen);
|
|
131
|
+
channel.removeEventListener("close", onClose);
|
|
132
|
+
channel.removeEventListener("error", onError);
|
|
133
|
+
channel.removeEventListener("message", onMessage);
|
|
134
|
+
};
|
|
135
|
+
channel.addEventListener("open", onOpen);
|
|
136
|
+
channel.addEventListener("close", onClose);
|
|
137
|
+
channel.addEventListener("error", onError);
|
|
138
|
+
channel.addEventListener("message", onMessage);
|
|
139
|
+
const attached = {
|
|
140
|
+
remotePeerId,
|
|
141
|
+
channel,
|
|
142
|
+
channelId: null,
|
|
143
|
+
reassembler,
|
|
144
|
+
nextFrameId: createFrameIdCounter(),
|
|
145
|
+
aliasState: emptyAliasState(),
|
|
146
|
+
cleanup
|
|
147
|
+
};
|
|
148
|
+
this.#attachedChannels.set(remotePeerId, attached);
|
|
149
|
+
if (channel.readyState === "open") this.#createSyncChannel(remotePeerId);
|
|
150
|
+
return () => this.detachDataChannel(remotePeerId);
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Detach a data channel for a remote peer.
|
|
154
|
+
*
|
|
155
|
+
* Removes the sync channel, cleans up event listeners, and disposes
|
|
156
|
+
* the reassembler. Does NOT close the data channel — the application
|
|
157
|
+
* manages the WebRTC connection lifecycle.
|
|
158
|
+
*
|
|
159
|
+
* @param remotePeerId - The peer ID to detach
|
|
160
|
+
*/
|
|
161
|
+
detachDataChannel(remotePeerId) {
|
|
162
|
+
const attached = this.#attachedChannels.get(remotePeerId);
|
|
163
|
+
if (!attached) return;
|
|
164
|
+
this.#removeSyncChannel(remotePeerId);
|
|
165
|
+
attached.reassembler.dispose();
|
|
166
|
+
attached.cleanup();
|
|
167
|
+
this.#attachedChannels.delete(remotePeerId);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Check if a data channel is attached for a peer.
|
|
171
|
+
*/
|
|
172
|
+
hasDataChannel(remotePeerId) {
|
|
173
|
+
return this.#attachedChannels.has(remotePeerId);
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Get all peer IDs with attached data channels.
|
|
177
|
+
*/
|
|
178
|
+
getAttachedPeerIds() {
|
|
179
|
+
return [...this.#attachedChannels.keys()];
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Create an internal sync channel for an attached data channel.
|
|
183
|
+
*
|
|
184
|
+
* Called when the data channel's `"open"` event fires (or immediately
|
|
185
|
+
* if already open on attach). The sync channel is registered with the
|
|
186
|
+
* Transport base class, which triggers the establishment handshake.
|
|
187
|
+
*/
|
|
188
|
+
#createSyncChannel(remotePeerId) {
|
|
189
|
+
const attached = this.#attachedChannels.get(remotePeerId);
|
|
190
|
+
if (!attached) return;
|
|
191
|
+
if (attached.channelId !== null) return;
|
|
192
|
+
const syncChannel = this.addChannel({
|
|
193
|
+
remotePeerId,
|
|
194
|
+
channel: attached.channel
|
|
195
|
+
});
|
|
196
|
+
attached.channelId = syncChannel.channelId;
|
|
197
|
+
this.establishChannel(syncChannel.channelId);
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Remove the internal sync channel for a peer.
|
|
201
|
+
*/
|
|
202
|
+
#removeSyncChannel(remotePeerId) {
|
|
203
|
+
const attached = this.#attachedChannels.get(remotePeerId);
|
|
204
|
+
if (!attached || attached.channelId === null) return;
|
|
205
|
+
this.removeChannel(attached.channelId);
|
|
206
|
+
attached.channelId = null;
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Handle an incoming message from a data channel.
|
|
210
|
+
*
|
|
211
|
+
* Extracts binary data from the event, feeding both `ArrayBuffer`
|
|
212
|
+
* (native RTCDataChannel with binaryType "arraybuffer") and
|
|
213
|
+
* `Uint8Array` (simple-peer and other wrappers) into the shared
|
|
214
|
+
* decode pipeline.
|
|
215
|
+
*/
|
|
216
|
+
#handleMessage(remotePeerId, event) {
|
|
217
|
+
const attached = this.#attachedChannels.get(remotePeerId);
|
|
218
|
+
if (!attached || attached.channelId === null) return;
|
|
219
|
+
const syncChannel = this.channels.get(attached.channelId);
|
|
220
|
+
if (!syncChannel) return;
|
|
221
|
+
const raw = event.data;
|
|
222
|
+
const bytes = raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw instanceof Uint8Array ? raw : null;
|
|
223
|
+
if (!bytes) return;
|
|
224
|
+
try {
|
|
225
|
+
const wires = decodeBinaryWires(bytes, attached.reassembler);
|
|
226
|
+
if (!wires) return;
|
|
227
|
+
for (const wire of wires) {
|
|
228
|
+
const result = applyInboundAliasing(attached.aliasState, wire);
|
|
229
|
+
attached.aliasState = result.state;
|
|
230
|
+
if (result.error || !result.msg) {
|
|
231
|
+
console.warn(`[webrtc-transport] alias resolution failed for peer ${remotePeerId}:`, result.error);
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
syncChannel.onReceive(result.msg);
|
|
235
|
+
}
|
|
236
|
+
} catch (error) {
|
|
237
|
+
console.error(`[webrtc-transport] Failed to decode message from peer ${remotePeerId}:`, error);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
219
240
|
};
|
|
241
|
+
/**
|
|
242
|
+
* Create a WebRTC transport factory for use with `Exchange`.
|
|
243
|
+
*
|
|
244
|
+
* Returns a `TransportFactory` — pass directly to
|
|
245
|
+
* `Exchange({ transports: [...] })`. The returned transport instance
|
|
246
|
+
* exposes `attachDataChannel()` / `detachDataChannel()` for BYODC
|
|
247
|
+
* data channel management.
|
|
248
|
+
*
|
|
249
|
+
* To access the transport instance after creation, use
|
|
250
|
+
* `exchange.getTransport("webrtc-datachannel")`.
|
|
251
|
+
*
|
|
252
|
+
* @example
|
|
253
|
+
* ```typescript
|
|
254
|
+
* import { Exchange } from "@kyneta/exchange"
|
|
255
|
+
* import { createWebrtcTransport } from "@kyneta/webrtc-transport"
|
|
256
|
+
*
|
|
257
|
+
* const exchange = new Exchange({
|
|
258
|
+
* id: { peerId: "alice", name: "Alice" },
|
|
259
|
+
* transports: [createWebrtcTransport()],
|
|
260
|
+
* })
|
|
261
|
+
* ```
|
|
262
|
+
*/
|
|
220
263
|
function createWebrtcTransport(options) {
|
|
221
|
-
|
|
264
|
+
return () => new WebrtcTransport(options);
|
|
222
265
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
createWebrtcTransport
|
|
227
|
-
};
|
|
266
|
+
//#endregion
|
|
267
|
+
export { DEFAULT_FRAGMENT_THRESHOLD, WebrtcTransport, createWebrtcTransport };
|
|
268
|
+
|
|
228
269
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/webrtc-transport.ts"],"sourcesContent":["// webrtc-transport — BYODC WebRTC data channel transport for @kyneta/exchange.\n//\n// \"Bring Your Own Data Channel\" design: the application manages WebRTC\n// connections (signaling, ICE, media streams). This transport attaches\n// to already-established data channels for kyneta document sync.\n//\n// Uses the shared binary pipeline from @kyneta/wire (same as WebSocket):\n// encodeBinaryAndSend — outbound: encode → fragment → sendFn\n// decodeBinaryMessages — inbound: reassemble → decode → ChannelMsg[]\n//\n// The transport accepts any object satisfying `DataChannelLike` — a\n// 5-member interface that native RTCDataChannel satisfies structurally\n// and that libraries like simple-peer can conform to via a trivial bridge.\n\nimport type {\n ChannelId,\n ChannelMsg,\n GeneratedChannel,\n TransportFactory,\n} from \"@kyneta/transport\"\nimport { Transport } from \"@kyneta/transport\"\nimport {\n decodeBinaryMessages,\n encodeBinaryAndSend,\n FragmentReassembler,\n} from \"@kyneta/wire\"\nimport type { DataChannelLike } from \"./data-channel-like.js\"\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Default fragment threshold in bytes.\n *\n * SCTP (the underlying transport for WebRTC data channels) has a message\n * size limit of approximately 256KB. 200KB provides a safe margin.\n *\n * This differs from the WebSocket transport's 100KB default, which\n * targets AWS API Gateway's 128KB limit. WebRTC has no such gateway.\n */\nexport const DEFAULT_FRAGMENT_THRESHOLD = 200 * 1024\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Configuration options for the WebRTC transport.\n */\nexport interface WebrtcTransportOptions {\n /**\n * Fragment threshold in bytes. Messages larger than this are fragmented\n * for SCTP compatibility. Set to 0 to disable fragmentation (not recommended).\n *\n * @default 204800 (200KB)\n */\n fragmentThreshold?: number\n}\n\n// ---------------------------------------------------------------------------\n// Internal types\n// ---------------------------------------------------------------------------\n\n/**\n * Context for each attached data channel — stored per remotePeerId.\n */\ntype DataChannelContext = {\n remotePeerId: string\n channel: DataChannelLike\n}\n\n/**\n * Internal tracking for an attached data channel.\n */\ntype AttachedChannel = {\n remotePeerId: string\n channel: DataChannelLike\n channelId: ChannelId | null\n reassembler: FragmentReassembler\n cleanup: () => void\n}\n\n// ---------------------------------------------------------------------------\n// WebrtcTransport\n// ---------------------------------------------------------------------------\n\n/**\n * WebRTC data channel transport for @kyneta/exchange.\n *\n * Follows a \"Bring Your Own Data Channel\" (BYODC) design — the application\n * manages WebRTC connections and attaches data channels to this transport\n * for kyneta document synchronization.\n *\n * Uses binary CBOR encoding with transport-level fragmentation via\n * `@kyneta/wire` — the same pipeline as the WebSocket transport.\n *\n * ## Usage\n *\n * ```typescript\n * import { Exchange } from \"@kyneta/exchange\"\n * import { createWebrtcTransport } from \"@kyneta/webrtc-transport\"\n *\n * const webrtcTransport = createWebrtcTransport()\n *\n * const exchange = new Exchange({\n * identity: { peerId: \"alice\", name: \"Alice\" },\n * transports: [webrtcTransport],\n * })\n *\n * // When a WebRTC connection is established:\n * const cleanup = transport.attachDataChannel(remotePeerId, dataChannel)\n *\n * // When done:\n * cleanup() // or transport.detachDataChannel(remotePeerId)\n * ```\n *\n * ## Ownership\n *\n * The transport does NOT own the data channel. `detachDataChannel()`\n * removes the sync channel and event listeners but does not close the\n * data channel or the peer connection. The application manages the\n * WebRTC connection lifecycle independently.\n */\nexport class WebrtcTransport extends Transport<DataChannelContext> {\n /**\n * Map of remotePeerId → attached channel tracking.\n */\n readonly #attachedChannels = new Map<string, AttachedChannel>()\n\n /**\n * Fragment threshold in bytes.\n */\n readonly #fragmentThreshold: number\n\n constructor(options?: WebrtcTransportOptions) {\n super({ transportType: \"webrtc-datachannel\" })\n this.#fragmentThreshold =\n options?.fragmentThreshold ?? DEFAULT_FRAGMENT_THRESHOLD\n }\n\n // ==========================================================================\n // Transport abstract method implementations\n // ==========================================================================\n\n /**\n * Generate a channel for a data channel context.\n *\n * Called internally by the `Transport` base class when `addChannel()` is\n * invoked. Users never call this directly — use `attachDataChannel()`.\n */\n protected generate(context: DataChannelContext): GeneratedChannel {\n const { channel } = context\n\n return {\n transportType: this.transportType,\n send: (msg: ChannelMsg) => {\n if (channel.readyState !== \"open\") {\n return\n }\n encodeBinaryAndSend(msg, this.#fragmentThreshold, data =>\n channel.send(data),\n )\n },\n stop: () => {\n // Cleanup is handled by detachDataChannel().\n // This callback fires when the internal channel is removed.\n },\n }\n }\n\n /**\n * Called when the transport starts.\n *\n * No-op for WebRTC — channels are added dynamically via\n * `attachDataChannel()`, not at start time.\n */\n async onStart(): Promise<void> {}\n\n /**\n * Called when the transport stops.\n *\n * Detaches all attached data channels and cleans up resources.\n */\n async onStop(): Promise<void> {\n for (const remotePeerId of [...this.#attachedChannels.keys()]) {\n this.detachDataChannel(remotePeerId)\n }\n }\n\n // ==========================================================================\n // Public API — data channel management\n // ==========================================================================\n\n /**\n * Attach a data channel for a remote peer.\n *\n * Creates an internal sync channel when the data channel is open\n * (or waits for the `\"open\"` event if still connecting). The sync\n * channel triggers the establishment handshake with the remote peer.\n *\n * If a data channel is already attached for this peer, the old one\n * is detached first.\n *\n * @param remotePeerId - The stable peer ID of the remote peer\n * @param channel - Any object satisfying `DataChannelLike`\n * @returns A cleanup function that calls `detachDataChannel(remotePeerId)`\n */\n attachDataChannel(\n remotePeerId: string,\n channel: DataChannelLike,\n ): () => void {\n // Detach existing channel for this peer if any\n if (this.#attachedChannels.has(remotePeerId)) {\n this.detachDataChannel(remotePeerId)\n }\n\n // Best-effort: request arraybuffer mode for incoming data.\n // The message handler doesn't depend on this — it accepts both\n // ArrayBuffer and Uint8Array regardless.\n channel.binaryType = \"arraybuffer\"\n\n // Create reassembler for this data channel\n const reassembler = new FragmentReassembler({ timeoutMs: 10_000 })\n\n // Event handlers — stored as named functions for removeEventListener\n const onOpen = () => {\n this.#createSyncChannel(remotePeerId)\n }\n\n const onClose = () => {\n this.#removeSyncChannel(remotePeerId)\n }\n\n const onError = () => {\n this.#removeSyncChannel(remotePeerId)\n }\n\n const onMessage = (event: any) => {\n this.#handleMessage(remotePeerId, event)\n }\n\n // Cleanup function to remove all event listeners\n const cleanup = () => {\n channel.removeEventListener(\"open\", onOpen)\n channel.removeEventListener(\"close\", onClose)\n channel.removeEventListener(\"error\", onError)\n channel.removeEventListener(\"message\", onMessage)\n }\n\n // Register event listeners\n channel.addEventListener(\"open\", onOpen)\n channel.addEventListener(\"close\", onClose)\n channel.addEventListener(\"error\", onError)\n channel.addEventListener(\"message\", onMessage)\n\n // Track the attached channel\n const attached: AttachedChannel = {\n remotePeerId,\n channel,\n channelId: null,\n reassembler,\n cleanup,\n }\n this.#attachedChannels.set(remotePeerId, attached)\n\n // If the channel is already open, create the sync channel immediately\n if (channel.readyState === \"open\") {\n this.#createSyncChannel(remotePeerId)\n }\n\n return () => this.detachDataChannel(remotePeerId)\n }\n\n /**\n * Detach a data channel for a remote peer.\n *\n * Removes the sync channel, cleans up event listeners, and disposes\n * the reassembler. Does NOT close the data channel — the application\n * manages the WebRTC connection lifecycle.\n *\n * @param remotePeerId - The peer ID to detach\n */\n detachDataChannel(remotePeerId: string): void {\n const attached = this.#attachedChannels.get(remotePeerId)\n if (!attached) return\n\n // Remove the sync channel if it exists\n this.#removeSyncChannel(remotePeerId)\n\n // Dispose the reassembler to clean up timers\n attached.reassembler.dispose()\n\n // Remove event listeners from the data channel\n attached.cleanup()\n\n // Remove from tracking\n this.#attachedChannels.delete(remotePeerId)\n }\n\n /**\n * Check if a data channel is attached for a peer.\n */\n hasDataChannel(remotePeerId: string): boolean {\n return this.#attachedChannels.has(remotePeerId)\n }\n\n /**\n * Get all peer IDs with attached data channels.\n */\n getAttachedPeerIds(): string[] {\n return [...this.#attachedChannels.keys()]\n }\n\n // ==========================================================================\n // Internal — sync channel lifecycle\n // ==========================================================================\n\n /**\n * Create an internal sync channel for an attached data channel.\n *\n * Called when the data channel's `\"open\"` event fires (or immediately\n * if already open on attach). The sync channel is registered with the\n * Transport base class, which triggers the establishment handshake.\n */\n #createSyncChannel(remotePeerId: string): void {\n const attached = this.#attachedChannels.get(remotePeerId)\n if (!attached) return\n\n // Don't create if already exists\n if (attached.channelId !== null) return\n\n // addChannel() creates and registers the sync channel\n const syncChannel = this.addChannel({\n remotePeerId,\n channel: attached.channel,\n })\n attached.channelId = syncChannel.channelId\n\n // Start the establishment handshake\n this.establishChannel(syncChannel.channelId)\n }\n\n /**\n * Remove the internal sync channel for a peer.\n */\n #removeSyncChannel(remotePeerId: string): void {\n const attached = this.#attachedChannels.get(remotePeerId)\n if (!attached || attached.channelId === null) return\n\n this.removeChannel(attached.channelId)\n attached.channelId = null\n }\n\n // ==========================================================================\n // Internal — message handling\n // ==========================================================================\n\n /**\n * Handle an incoming message from a data channel.\n *\n * Extracts binary data from the event, feeding both `ArrayBuffer`\n * (native RTCDataChannel with binaryType \"arraybuffer\") and\n * `Uint8Array` (simple-peer and other wrappers) into the shared\n * decode pipeline.\n */\n #handleMessage(remotePeerId: string, event: any): void {\n const attached = this.#attachedChannels.get(remotePeerId)\n if (!attached || attached.channelId === null) return\n\n const syncChannel = this.channels.get(attached.channelId)\n if (!syncChannel) return\n\n // Extract bytes — robust to both ArrayBuffer and Uint8Array\n const raw = event.data\n const bytes =\n raw instanceof ArrayBuffer\n ? new Uint8Array(raw)\n : raw instanceof Uint8Array\n ? raw\n : null\n\n if (!bytes) {\n // Unexpected data type (e.g. string) — ignore silently\n return\n }\n\n try {\n const messages = decodeBinaryMessages(bytes, attached.reassembler)\n if (messages) {\n for (const msg of messages) {\n syncChannel.onReceive(msg)\n }\n }\n } catch (error) {\n console.error(\n `[webrtc-transport] Failed to decode message from peer ${remotePeerId}:`,\n error,\n )\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory function\n// ---------------------------------------------------------------------------\n\n/**\n * Create a WebRTC transport factory for use with `Exchange`.\n *\n * Returns a `TransportFactory` — pass directly to\n * `Exchange({ transports: [...] })`. The returned transport instance\n * exposes `attachDataChannel()` / `detachDataChannel()` for BYODC\n * data channel management.\n *\n * To access the transport instance after creation, use\n * `exchange.getTransport(\"webrtc-datachannel\")`.\n *\n * @example\n * ```typescript\n * import { Exchange } from \"@kyneta/exchange\"\n * import { createWebrtcTransport } from \"@kyneta/webrtc-transport\"\n *\n * const exchange = new Exchange({\n * identity: { peerId: \"alice\", name: \"Alice\" },\n * transports: [createWebrtcTransport()],\n * })\n * ```\n */\nexport function createWebrtcTransport(\n options?: WebrtcTransportOptions,\n): TransportFactory {\n return () => new WebrtcTransport(options)\n}\n"],"mappings":";AAoBA,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAgBA,IAAM,6BAA6B,MAAM;AAmFzC,IAAM,kBAAN,cAA8B,UAA8B;AAAA;AAAA;AAAA;AAAA,EAIxD,oBAAoB,oBAAI,IAA6B;AAAA;AAAA;AAAA;AAAA,EAKrD;AAAA,EAET,YAAY,SAAkC;AAC5C,UAAM,EAAE,eAAe,qBAAqB,CAAC;AAC7C,SAAK,qBACH,SAAS,qBAAqB;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYU,SAAS,SAA+C;AAChE,UAAM,EAAE,QAAQ,IAAI;AAEpB,WAAO;AAAA,MACL,eAAe,KAAK;AAAA,MACpB,MAAM,CAAC,QAAoB;AACzB,YAAI,QAAQ,eAAe,QAAQ;AACjC;AAAA,QACF;AACA;AAAA,UAAoB;AAAA,UAAK,KAAK;AAAA,UAAoB,UAChD,QAAQ,KAAK,IAAI;AAAA,QACnB;AAAA,MACF;AAAA,MACA,MAAM,MAAM;AAAA,MAGZ;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,UAAyB;AAAA,EAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOhC,MAAM,SAAwB;AAC5B,eAAW,gBAAgB,CAAC,GAAG,KAAK,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AGlB,UAAM,MAAM,MAAM;AAClB,UAAM,QACJ,eAAe,cACX,IAAI,WAAW,GAAG,IAClB,eAAe,aACb,MACA;AAER,QAAI,CAAC,OAAO;AAEV;AAAA,IACF;AAEA,QAAI;AACF,YAAM,WAAW,qBAAqB,OAAO,SAAS,WAAW;AACjE,UAAI,UAAU;AACZ,mBAAW,OAAO,UAAU;AAC1B,sBAAY,UAAU,GAAG;AAAA,QAC3B;AAAA,MACF;AAAA,IACF,SAAS,OAAO;AACd,cAAQ;AAAA,QACN,yDAAyD,YAAY;AAAA,QACrE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AA4BO,SAAS,sBACd,SACkB;AAClB,SAAO,MAAM,IAAI,gBAAgB,OAAO;AAC1C;","names":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#attachedChannels","#fragmentThreshold","#createSyncChannel","#removeSyncChannel","#handleMessage"],"sources":["../src/webrtc-transport.ts"],"sourcesContent":["// webrtc-transport — BYODC WebRTC data channel transport for @kyneta/exchange.\n//\n// \"Bring Your Own Data Channel\" design: the application manages WebRTC\n// connections (signaling, ICE, media streams). This transport attaches\n// to already-established data channels for kyneta document sync.\n//\n// Uses the shared binary pipeline from @kyneta/wire (same as WebSocket):\n// encodeBinaryAndSend — outbound: encode → fragment → sendFn\n// decodeBinaryMessages — inbound: reassemble → decode → ChannelMsg[]\n//\n// The transport accepts any object satisfying `DataChannelLike` — a\n// 5-member interface that native RTCDataChannel satisfies structurally\n// and that libraries like simple-peer can conform to via a trivial bridge.\n\nimport type {\n ChannelId,\n ChannelMsg,\n GeneratedChannel,\n TransportFactory,\n} from \"@kyneta/transport\"\nimport { Transport } from \"@kyneta/transport\"\nimport {\n type AliasState,\n applyInboundAliasing,\n applyOutboundAliasing,\n createFrameIdCounter,\n decodeBinaryWires,\n emptyAliasState,\n encodeWireFrameAndSend,\n FragmentReassembler,\n} from \"@kyneta/wire\"\nimport type { DataChannelLike } from \"./data-channel-like.js\"\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Default fragment threshold in bytes.\n *\n * SCTP (the underlying transport for WebRTC data channels) has a message\n * size limit of approximately 256KB. 200KB provides a safe margin.\n *\n * This differs from the WebSocket transport's 100KB default, which\n * targets AWS API Gateway's 128KB limit. WebRTC has no such gateway.\n */\nexport const DEFAULT_FRAGMENT_THRESHOLD = 200 * 1024\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Configuration options for the WebRTC transport.\n */\nexport interface WebrtcTransportOptions {\n /**\n * Fragment threshold in bytes. Messages larger than this are fragmented\n * for SCTP compatibility. Set to 0 to disable fragmentation (not recommended).\n *\n * @default 204800 (200KB)\n */\n fragmentThreshold?: number\n}\n\n// ---------------------------------------------------------------------------\n// Internal types\n// ---------------------------------------------------------------------------\n\n/**\n * Context for each attached data channel — stored per remotePeerId.\n */\ntype DataChannelContext = {\n remotePeerId: string\n channel: DataChannelLike\n}\n\n/**\n * Internal tracking for an attached data channel.\n */\ntype AttachedChannel = {\n remotePeerId: string\n channel: DataChannelLike\n channelId: ChannelId | null\n reassembler: FragmentReassembler\n nextFrameId: () => number\n /** Per-channel alias state (Phase 4). */\n aliasState: AliasState\n cleanup: () => void\n}\n\n// ---------------------------------------------------------------------------\n// WebrtcTransport\n// ---------------------------------------------------------------------------\n\n/**\n * WebRTC data channel transport for @kyneta/exchange.\n *\n * Follows a \"Bring Your Own Data Channel\" (BYODC) design — the application\n * manages WebRTC connections and attaches data channels to this transport\n * for kyneta document synchronization.\n *\n * Uses binary CBOR encoding with transport-level fragmentation via\n * `@kyneta/wire` — the same pipeline as the WebSocket transport.\n *\n * ## Usage\n *\n * ```typescript\n * import { Exchange } from \"@kyneta/exchange\"\n * import { createWebrtcTransport } from \"@kyneta/webrtc-transport\"\n *\n * const webrtcTransport = createWebrtcTransport()\n *\n * const exchange = new Exchange({\n * id: { peerId: \"alice\", name: \"Alice\" },\n * transports: [webrtcTransport],\n * })\n *\n * // When a WebRTC connection is established:\n * const cleanup = transport.attachDataChannel(remotePeerId, dataChannel)\n *\n * // When done:\n * cleanup() // or transport.detachDataChannel(remotePeerId)\n * ```\n *\n * ## Ownership\n *\n * The transport does NOT own the data channel. `detachDataChannel()`\n * removes the sync channel and event listeners but does not close the\n * data channel or the peer connection. The application manages the\n * WebRTC connection lifecycle independently.\n */\nexport class WebrtcTransport extends Transport<DataChannelContext> {\n /**\n * Map of remotePeerId → attached channel tracking.\n */\n readonly #attachedChannels = new Map<string, AttachedChannel>()\n\n /**\n * Fragment threshold in bytes.\n */\n readonly #fragmentThreshold: number\n\n constructor(options?: WebrtcTransportOptions) {\n super({ transportType: \"webrtc-datachannel\" })\n this.#fragmentThreshold =\n options?.fragmentThreshold ?? DEFAULT_FRAGMENT_THRESHOLD\n }\n\n // ==========================================================================\n // Transport abstract method implementations\n // ==========================================================================\n\n /**\n * Generate a channel for a data channel context.\n *\n * Called internally by the `Transport` base class when `addChannel()` is\n * invoked. Users never call this directly — use `attachDataChannel()`.\n */\n protected generate(context: DataChannelContext): GeneratedChannel {\n const { channel } = context\n\n return {\n transportType: this.transportType,\n send: (msg: ChannelMsg) => {\n const attached = this.#attachedChannels.get(context.remotePeerId)\n if (!attached || channel.readyState !== \"open\") {\n return\n }\n const { state, wire } = applyOutboundAliasing(attached.aliasState, msg)\n attached.aliasState = state\n encodeWireFrameAndSend(\n wire,\n data => channel.send(data),\n this.#fragmentThreshold,\n attached.nextFrameId,\n )\n },\n stop: () => {\n // Cleanup is handled by detachDataChannel().\n // This callback fires when the internal channel is removed.\n },\n }\n }\n\n /**\n * Called when the transport starts.\n *\n * No-op for WebRTC — channels are added dynamically via\n * `attachDataChannel()`, not at start time.\n */\n async onStart(): Promise<void> {}\n\n /**\n * Called when the transport stops.\n *\n * Detaches all attached data channels and cleans up resources.\n */\n async onStop(): Promise<void> {\n for (const remotePeerId of [...this.#attachedChannels.keys()]) {\n this.detachDataChannel(remotePeerId)\n }\n }\n\n // ==========================================================================\n // Public API — data channel management\n // ==========================================================================\n\n /**\n * Attach a data channel for a remote peer.\n *\n * Creates an internal sync channel when the data channel is open\n * (or waits for the `\"open\"` event if still connecting). The sync\n * channel triggers the establishment handshake with the remote peer.\n *\n * If a data channel is already attached for this peer, the old one\n * is detached first.\n *\n * @param remotePeerId - The stable peer ID of the remote peer\n * @param channel - Any object satisfying `DataChannelLike`\n * @returns A cleanup function that calls `detachDataChannel(remotePeerId)`\n */\n attachDataChannel(\n remotePeerId: string,\n channel: DataChannelLike,\n ): () => void {\n // Detach existing channel for this peer if any\n if (this.#attachedChannels.has(remotePeerId)) {\n this.detachDataChannel(remotePeerId)\n }\n\n // Best-effort: request arraybuffer mode for incoming data.\n // The message handler doesn't depend on this — it accepts both\n // ArrayBuffer and Uint8Array regardless.\n channel.binaryType = \"arraybuffer\"\n\n // Create reassembler for this data channel\n const reassembler = new FragmentReassembler({ timeoutMs: 10_000 })\n\n // Event handlers — stored as named functions for removeEventListener\n const onOpen = () => {\n this.#createSyncChannel(remotePeerId)\n }\n\n const onClose = () => {\n this.#removeSyncChannel(remotePeerId)\n }\n\n const onError = () => {\n this.#removeSyncChannel(remotePeerId)\n }\n\n const onMessage = (event: any) => {\n this.#handleMessage(remotePeerId, event)\n }\n\n // Cleanup function to remove all event listeners\n const cleanup = () => {\n channel.removeEventListener(\"open\", onOpen)\n channel.removeEventListener(\"close\", onClose)\n channel.removeEventListener(\"error\", onError)\n channel.removeEventListener(\"message\", onMessage)\n }\n\n // Register event listeners\n channel.addEventListener(\"open\", onOpen)\n channel.addEventListener(\"close\", onClose)\n channel.addEventListener(\"error\", onError)\n channel.addEventListener(\"message\", onMessage)\n\n // Track the attached channel\n const attached: AttachedChannel = {\n remotePeerId,\n channel,\n channelId: null,\n reassembler,\n nextFrameId: createFrameIdCounter(),\n aliasState: emptyAliasState(),\n cleanup,\n }\n this.#attachedChannels.set(remotePeerId, attached)\n\n // If the channel is already open, create the sync channel immediately\n if (channel.readyState === \"open\") {\n this.#createSyncChannel(remotePeerId)\n }\n\n return () => this.detachDataChannel(remotePeerId)\n }\n\n /**\n * Detach a data channel for a remote peer.\n *\n * Removes the sync channel, cleans up event listeners, and disposes\n * the reassembler. Does NOT close the data channel — the application\n * manages the WebRTC connection lifecycle.\n *\n * @param remotePeerId - The peer ID to detach\n */\n detachDataChannel(remotePeerId: string): void {\n const attached = this.#attachedChannels.get(remotePeerId)\n if (!attached) return\n\n // Remove the sync channel if it exists\n this.#removeSyncChannel(remotePeerId)\n\n // Dispose the reassembler to clean up timers\n attached.reassembler.dispose()\n\n // Remove event listeners from the data channel\n attached.cleanup()\n\n // Remove from tracking\n this.#attachedChannels.delete(remotePeerId)\n }\n\n /**\n * Check if a data channel is attached for a peer.\n */\n hasDataChannel(remotePeerId: string): boolean {\n return this.#attachedChannels.has(remotePeerId)\n }\n\n /**\n * Get all peer IDs with attached data channels.\n */\n getAttachedPeerIds(): string[] {\n return [...this.#attachedChannels.keys()]\n }\n\n // ==========================================================================\n // Internal — sync channel lifecycle\n // ==========================================================================\n\n /**\n * Create an internal sync channel for an attached data channel.\n *\n * Called when the data channel's `\"open\"` event fires (or immediately\n * if already open on attach). The sync channel is registered with the\n * Transport base class, which triggers the establishment handshake.\n */\n #createSyncChannel(remotePeerId: string): void {\n const attached = this.#attachedChannels.get(remotePeerId)\n if (!attached) return\n\n // Don't create if already exists\n if (attached.channelId !== null) return\n\n // addChannel() creates and registers the sync channel\n const syncChannel = this.addChannel({\n remotePeerId,\n channel: attached.channel,\n })\n attached.channelId = syncChannel.channelId\n\n // Start the establishment handshake\n this.establishChannel(syncChannel.channelId)\n }\n\n /**\n * Remove the internal sync channel for a peer.\n */\n #removeSyncChannel(remotePeerId: string): void {\n const attached = this.#attachedChannels.get(remotePeerId)\n if (!attached || attached.channelId === null) return\n\n this.removeChannel(attached.channelId)\n attached.channelId = null\n }\n\n // ==========================================================================\n // Internal — message handling\n // ==========================================================================\n\n /**\n * Handle an incoming message from a data channel.\n *\n * Extracts binary data from the event, feeding both `ArrayBuffer`\n * (native RTCDataChannel with binaryType \"arraybuffer\") and\n * `Uint8Array` (simple-peer and other wrappers) into the shared\n * decode pipeline.\n */\n #handleMessage(remotePeerId: string, event: any): void {\n const attached = this.#attachedChannels.get(remotePeerId)\n if (!attached || attached.channelId === null) return\n\n const syncChannel = this.channels.get(attached.channelId)\n if (!syncChannel) return\n\n // Extract bytes — robust to both ArrayBuffer and Uint8Array\n const raw = event.data\n const bytes =\n raw instanceof ArrayBuffer\n ? new Uint8Array(raw)\n : raw instanceof Uint8Array\n ? raw\n : null\n\n if (!bytes) {\n // Unexpected data type (e.g. string) — ignore silently\n return\n }\n\n try {\n const wires = decodeBinaryWires(bytes, attached.reassembler)\n if (!wires) return\n for (const wire of wires) {\n const result = applyInboundAliasing(attached.aliasState, wire)\n attached.aliasState = result.state\n if (result.error || !result.msg) {\n console.warn(\n `[webrtc-transport] alias resolution failed for peer ${remotePeerId}:`,\n result.error,\n )\n continue\n }\n syncChannel.onReceive(result.msg)\n }\n } catch (error) {\n console.error(\n `[webrtc-transport] Failed to decode message from peer ${remotePeerId}:`,\n error,\n )\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory function\n// ---------------------------------------------------------------------------\n\n/**\n * Create a WebRTC transport factory for use with `Exchange`.\n *\n * Returns a `TransportFactory` — pass directly to\n * `Exchange({ transports: [...] })`. The returned transport instance\n * exposes `attachDataChannel()` / `detachDataChannel()` for BYODC\n * data channel management.\n *\n * To access the transport instance after creation, use\n * `exchange.getTransport(\"webrtc-datachannel\")`.\n *\n * @example\n * ```typescript\n * import { Exchange } from \"@kyneta/exchange\"\n * import { createWebrtcTransport } from \"@kyneta/webrtc-transport\"\n *\n * const exchange = new Exchange({\n * id: { peerId: \"alice\", name: \"Alice\" },\n * transports: [createWebrtcTransport()],\n * })\n * ```\n */\nexport function createWebrtcTransport(\n options?: WebrtcTransportOptions,\n): TransportFactory {\n return () => new WebrtcTransport(options)\n}\n"],"mappings":";;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AevB,eAAe,cAAsB,OAAkB;EACrD,MAAM,WAAW,MAAA,iBAAuB,IAAI,aAAa;AACzD,MAAI,CAAC,YAAY,SAAS,cAAc,KAAM;EAE9C,MAAM,cAAc,KAAK,SAAS,IAAI,SAAS,UAAU;AACzD,MAAI,CAAC,YAAa;EAGlB,MAAM,MAAM,MAAM;EAClB,MAAM,QACJ,eAAe,cACX,IAAI,WAAW,IAAI,GACnB,eAAe,aACb,MACA;AAER,MAAI,CAAC,MAEH;AAGF,MAAI;GACF,MAAM,QAAQ,kBAAkB,OAAO,SAAS,YAAY;AAC5D,OAAI,CAAC,MAAO;AACZ,QAAK,MAAM,QAAQ,OAAO;IACxB,MAAM,SAAS,qBAAqB,SAAS,YAAY,KAAK;AAC9D,aAAS,aAAa,OAAO;AAC7B,QAAI,OAAO,SAAS,CAAC,OAAO,KAAK;AAC/B,aAAQ,KACN,uDAAuD,aAAa,IACpE,OAAO,MACR;AACD;;AAEF,gBAAY,UAAU,OAAO,IAAI;;WAE5B,OAAO;AACd,WAAQ,MACN,yDAAyD,aAAa,IACtE,MACD;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BP,SAAgB,sBACd,SACkB;AAClB,cAAa,IAAI,gBAAgB,QAAQ"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kyneta/webrtc-transport",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "WebRTC data channel transport for @kyneta/exchange — BYODC (Bring Your Own Data Channel) with DataChannelLike interface",
|
|
5
5
|
"author": "Duane Johnson",
|
|
6
6
|
"license": "MIT",
|
|
@@ -25,21 +25,21 @@
|
|
|
25
25
|
"./src/*": "./src/*"
|
|
26
26
|
},
|
|
27
27
|
"peerDependencies": {
|
|
28
|
-
"@kyneta/transport": "^1.
|
|
29
|
-
"@kyneta/wire": "^1.
|
|
28
|
+
"@kyneta/transport": "^1.5.0",
|
|
29
|
+
"@kyneta/wire": "^1.5.0"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
32
|
"@types/node": "^22",
|
|
33
|
-
"
|
|
33
|
+
"tsdown": "^0.21.9",
|
|
34
34
|
"typescript": "^5.9.2",
|
|
35
35
|
"vitest": "^4.0.17",
|
|
36
|
-
"@kyneta/exchange": "^1.
|
|
37
|
-
"@kyneta/wire": "^1.
|
|
38
|
-
"@kyneta/schema": "^1.
|
|
39
|
-
"@kyneta/transport": "^1.
|
|
36
|
+
"@kyneta/exchange": "^1.5.0",
|
|
37
|
+
"@kyneta/wire": "^1.5.0",
|
|
38
|
+
"@kyneta/schema": "^1.5.0",
|
|
39
|
+
"@kyneta/transport": "^1.5.0"
|
|
40
40
|
},
|
|
41
41
|
"scripts": {
|
|
42
|
-
"build": "
|
|
42
|
+
"build": "tsdown",
|
|
43
43
|
"test": "verify logic",
|
|
44
44
|
"verify": "verify"
|
|
45
45
|
}
|
|
@@ -6,10 +6,13 @@
|
|
|
6
6
|
|
|
7
7
|
import type { ChannelMsg } from "@kyneta/transport"
|
|
8
8
|
import {
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
applyOutboundAliasing,
|
|
10
|
+
complete,
|
|
11
|
+
emptyAliasState,
|
|
12
|
+
encodeBinaryFrame,
|
|
13
|
+
encodeWireMessage,
|
|
11
14
|
fragmentPayload,
|
|
12
|
-
|
|
15
|
+
WIRE_VERSION,
|
|
13
16
|
} from "@kyneta/wire"
|
|
14
17
|
import { beforeEach, describe, expect, it, vi } from "vitest"
|
|
15
18
|
import { WebrtcTransport } from "../webrtc-transport.js"
|
|
@@ -45,12 +48,20 @@ async function initializeTransport(
|
|
|
45
48
|
return ctx
|
|
46
49
|
}
|
|
47
50
|
|
|
48
|
-
/** A minimal establish
|
|
51
|
+
/** A minimal establish message for send/receive tests. */
|
|
49
52
|
const TEST_MSG: ChannelMsg = {
|
|
50
|
-
type: "establish
|
|
53
|
+
type: "establish",
|
|
51
54
|
identity: { peerId: "remote", name: "R", type: "user" },
|
|
52
55
|
}
|
|
53
56
|
|
|
57
|
+
/** Encode a ChannelMsg through the alias-aware pipeline. */
|
|
58
|
+
function encodeViaAlias(msg: ChannelMsg): Uint8Array<ArrayBuffer> {
|
|
59
|
+
const state = emptyAliasState()
|
|
60
|
+
const { wire } = applyOutboundAliasing(state, msg)
|
|
61
|
+
const payload = encodeWireMessage(wire)
|
|
62
|
+
return encodeBinaryFrame(complete(WIRE_VERSION, payload))
|
|
63
|
+
}
|
|
64
|
+
|
|
54
65
|
// ---------------------------------------------------------------------------
|
|
55
66
|
// 1. Lifecycle
|
|
56
67
|
// ---------------------------------------------------------------------------
|
|
@@ -193,14 +204,13 @@ describe("Receive", () => {
|
|
|
193
204
|
const dc = new MockDataChannel("open")
|
|
194
205
|
transport.attachDataChannel("peer-1", dc)
|
|
195
206
|
|
|
196
|
-
// Encode a test message through the
|
|
197
|
-
const encoded =
|
|
198
|
-
const wrapped = wrapCompleteMessage(encoded)
|
|
207
|
+
// Encode a test message through the alias-aware pipeline
|
|
208
|
+
const encoded = encodeViaAlias(TEST_MSG)
|
|
199
209
|
|
|
200
210
|
// Convert to ArrayBuffer (as native RTCDataChannel with binaryType "arraybuffer" would deliver)
|
|
201
|
-
const ab =
|
|
202
|
-
|
|
203
|
-
|
|
211
|
+
const ab = encoded.buffer.slice(
|
|
212
|
+
encoded.byteOffset,
|
|
213
|
+
encoded.byteOffset + encoded.byteLength,
|
|
204
214
|
)
|
|
205
215
|
|
|
206
216
|
dc.emit("message", { data: ab })
|
|
@@ -210,7 +220,7 @@ describe("Receive", () => {
|
|
|
210
220
|
if (!callArgs)
|
|
211
221
|
throw new Error("expected onChannelReceive to have been called")
|
|
212
222
|
const [, receivedMsg] = callArgs
|
|
213
|
-
expect(receivedMsg.type).toBe("establish
|
|
223
|
+
expect(receivedMsg.type).toBe("establish")
|
|
214
224
|
expect((receivedMsg as any).identity.peerId).toBe("remote")
|
|
215
225
|
})
|
|
216
226
|
|
|
@@ -218,18 +228,17 @@ describe("Receive", () => {
|
|
|
218
228
|
const dc = new MockDataChannel("open")
|
|
219
229
|
transport.attachDataChannel("peer-1", dc)
|
|
220
230
|
|
|
221
|
-
const encoded =
|
|
222
|
-
const wrapped = wrapCompleteMessage(encoded)
|
|
231
|
+
const encoded = encodeViaAlias(TEST_MSG)
|
|
223
232
|
|
|
224
233
|
// Pass Uint8Array directly (as simple-peer and other wrappers may deliver)
|
|
225
|
-
dc.emit("message", { data:
|
|
234
|
+
dc.emit("message", { data: encoded })
|
|
226
235
|
|
|
227
236
|
expect(ctx.onChannelReceive).toHaveBeenCalled()
|
|
228
237
|
const callArgs = ctx.onChannelReceive.mock.calls.at(0)
|
|
229
238
|
if (!callArgs)
|
|
230
239
|
throw new Error("expected onChannelReceive to have been called")
|
|
231
240
|
const [, receivedMsg] = callArgs
|
|
232
|
-
expect(receivedMsg.type).toBe("establish
|
|
241
|
+
expect(receivedMsg.type).toBe("establish")
|
|
233
242
|
expect((receivedMsg as any).identity.peerId).toBe("remote")
|
|
234
243
|
})
|
|
235
244
|
|
|
@@ -303,7 +312,7 @@ describe("Fragmentation", () => {
|
|
|
303
312
|
// binary frame may exceed it if the CBOR encoding + frame header is large enough.
|
|
304
313
|
// Use a message with enough payload to guarantee fragmentation.
|
|
305
314
|
const largeMsg: ChannelMsg = {
|
|
306
|
-
type: "establish
|
|
315
|
+
type: "establish",
|
|
307
316
|
identity: {
|
|
308
317
|
peerId: `a]very-long-peer-id-${"x".repeat(200)}`,
|
|
309
318
|
name: `A Long Name ${"y".repeat(200)}`,
|
|
@@ -326,7 +335,7 @@ describe("Fragmentation", () => {
|
|
|
326
335
|
|
|
327
336
|
// Build a message large enough to guarantee multiple fragments at chunk size 50
|
|
328
337
|
const largeMsg: ChannelMsg = {
|
|
329
|
-
type: "establish
|
|
338
|
+
type: "establish",
|
|
330
339
|
identity: {
|
|
331
340
|
peerId: `peer-${"z".repeat(200)}`,
|
|
332
341
|
name: `Name-${"w".repeat(200)}`,
|
|
@@ -334,8 +343,8 @@ describe("Fragmentation", () => {
|
|
|
334
343
|
},
|
|
335
344
|
}
|
|
336
345
|
|
|
337
|
-
const encoded =
|
|
338
|
-
const fragments = fragmentPayload(encoded, 50)
|
|
346
|
+
const encoded = encodeViaAlias(largeMsg)
|
|
347
|
+
const fragments = fragmentPayload(encoded, 50, 1)
|
|
339
348
|
expect(fragments.length).toBeGreaterThan(1)
|
|
340
349
|
|
|
341
350
|
// Emit all but the last fragment — should NOT trigger receive yet
|
|
@@ -364,7 +373,7 @@ describe("Fragmentation", () => {
|
|
|
364
373
|
if (!callArgs)
|
|
365
374
|
throw new Error("expected onChannelReceive to have been called")
|
|
366
375
|
const [, receivedMsg] = callArgs
|
|
367
|
-
expect(receivedMsg.type).toBe("establish
|
|
376
|
+
expect(receivedMsg.type).toBe("establish")
|
|
368
377
|
expect((receivedMsg as any).identity.peerId).toBe(`peer-${"z".repeat(200)}`)
|
|
369
378
|
})
|
|
370
379
|
})
|
|
@@ -466,9 +475,8 @@ describe("Message before open (race condition)", () => {
|
|
|
466
475
|
expect(transport.channels.size).toBe(0)
|
|
467
476
|
|
|
468
477
|
// Simulate a message arriving before the open event
|
|
469
|
-
const encoded =
|
|
470
|
-
|
|
471
|
-
dc.emit("message", { data: wrapped })
|
|
478
|
+
const encoded = encodeViaAlias(TEST_MSG)
|
|
479
|
+
dc.emit("message", { data: encoded })
|
|
472
480
|
|
|
473
481
|
// Message should be silently dropped — no delivery, no error
|
|
474
482
|
expect(ctx.onChannelReceive).not.toHaveBeenCalled()
|
|
@@ -477,7 +485,7 @@ describe("Message before open (race condition)", () => {
|
|
|
477
485
|
dc.open()
|
|
478
486
|
expect(transport.channels.size).toBe(1)
|
|
479
487
|
|
|
480
|
-
dc.emit("message", { data:
|
|
488
|
+
dc.emit("message", { data: encoded })
|
|
481
489
|
expect(ctx.onChannelReceive).toHaveBeenCalledOnce()
|
|
482
490
|
})
|
|
483
491
|
})
|
package/src/webrtc-transport.ts
CHANGED
|
@@ -20,8 +20,13 @@ import type {
|
|
|
20
20
|
} from "@kyneta/transport"
|
|
21
21
|
import { Transport } from "@kyneta/transport"
|
|
22
22
|
import {
|
|
23
|
-
|
|
24
|
-
|
|
23
|
+
type AliasState,
|
|
24
|
+
applyInboundAliasing,
|
|
25
|
+
applyOutboundAliasing,
|
|
26
|
+
createFrameIdCounter,
|
|
27
|
+
decodeBinaryWires,
|
|
28
|
+
emptyAliasState,
|
|
29
|
+
encodeWireFrameAndSend,
|
|
25
30
|
FragmentReassembler,
|
|
26
31
|
} from "@kyneta/wire"
|
|
27
32
|
import type { DataChannelLike } from "./data-channel-like.js"
|
|
@@ -78,6 +83,9 @@ type AttachedChannel = {
|
|
|
78
83
|
channel: DataChannelLike
|
|
79
84
|
channelId: ChannelId | null
|
|
80
85
|
reassembler: FragmentReassembler
|
|
86
|
+
nextFrameId: () => number
|
|
87
|
+
/** Per-channel alias state (Phase 4). */
|
|
88
|
+
aliasState: AliasState
|
|
81
89
|
cleanup: () => void
|
|
82
90
|
}
|
|
83
91
|
|
|
@@ -104,7 +112,7 @@ type AttachedChannel = {
|
|
|
104
112
|
* const webrtcTransport = createWebrtcTransport()
|
|
105
113
|
*
|
|
106
114
|
* const exchange = new Exchange({
|
|
107
|
-
*
|
|
115
|
+
* id: { peerId: "alice", name: "Alice" },
|
|
108
116
|
* transports: [webrtcTransport],
|
|
109
117
|
* })
|
|
110
118
|
*
|
|
@@ -155,11 +163,17 @@ export class WebrtcTransport extends Transport<DataChannelContext> {
|
|
|
155
163
|
return {
|
|
156
164
|
transportType: this.transportType,
|
|
157
165
|
send: (msg: ChannelMsg) => {
|
|
158
|
-
|
|
166
|
+
const attached = this.#attachedChannels.get(context.remotePeerId)
|
|
167
|
+
if (!attached || channel.readyState !== "open") {
|
|
159
168
|
return
|
|
160
169
|
}
|
|
161
|
-
|
|
162
|
-
|
|
170
|
+
const { state, wire } = applyOutboundAliasing(attached.aliasState, msg)
|
|
171
|
+
attached.aliasState = state
|
|
172
|
+
encodeWireFrameAndSend(
|
|
173
|
+
wire,
|
|
174
|
+
data => channel.send(data),
|
|
175
|
+
this.#fragmentThreshold,
|
|
176
|
+
attached.nextFrameId,
|
|
163
177
|
)
|
|
164
178
|
},
|
|
165
179
|
stop: () => {
|
|
@@ -260,6 +274,8 @@ export class WebrtcTransport extends Transport<DataChannelContext> {
|
|
|
260
274
|
channel,
|
|
261
275
|
channelId: null,
|
|
262
276
|
reassembler,
|
|
277
|
+
nextFrameId: createFrameIdCounter(),
|
|
278
|
+
aliasState: emptyAliasState(),
|
|
263
279
|
cleanup,
|
|
264
280
|
}
|
|
265
281
|
this.#attachedChannels.set(remotePeerId, attached)
|
|
@@ -386,11 +402,19 @@ export class WebrtcTransport extends Transport<DataChannelContext> {
|
|
|
386
402
|
}
|
|
387
403
|
|
|
388
404
|
try {
|
|
389
|
-
const
|
|
390
|
-
if (
|
|
391
|
-
|
|
392
|
-
|
|
405
|
+
const wires = decodeBinaryWires(bytes, attached.reassembler)
|
|
406
|
+
if (!wires) return
|
|
407
|
+
for (const wire of wires) {
|
|
408
|
+
const result = applyInboundAliasing(attached.aliasState, wire)
|
|
409
|
+
attached.aliasState = result.state
|
|
410
|
+
if (result.error || !result.msg) {
|
|
411
|
+
console.warn(
|
|
412
|
+
`[webrtc-transport] alias resolution failed for peer ${remotePeerId}:`,
|
|
413
|
+
result.error,
|
|
414
|
+
)
|
|
415
|
+
continue
|
|
393
416
|
}
|
|
417
|
+
syncChannel.onReceive(result.msg)
|
|
394
418
|
}
|
|
395
419
|
} catch (error) {
|
|
396
420
|
console.error(
|
|
@@ -422,7 +446,7 @@ export class WebrtcTransport extends Transport<DataChannelContext> {
|
|
|
422
446
|
* import { createWebrtcTransport } from "@kyneta/webrtc-transport"
|
|
423
447
|
*
|
|
424
448
|
* const exchange = new Exchange({
|
|
425
|
-
*
|
|
449
|
+
* id: { peerId: "alice", name: "Alice" },
|
|
426
450
|
* transports: [createWebrtcTransport()],
|
|
427
451
|
* })
|
|
428
452
|
* ```
|