@xconnio/xconn 0.0.0-stage → 0.6.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/LICENSE +22 -0
  3. package/README.md +281 -2
  4. package/dist/auth.d.ts +51 -0
  5. package/dist/auth.js +57 -0
  6. package/dist/call.d.ts +38 -0
  7. package/dist/call.js +146 -0
  8. package/dist/client.d.ts +21 -0
  9. package/dist/client.js +62 -0
  10. package/dist/constants.d.ts +60 -0
  11. package/dist/constants.js +61 -0
  12. package/dist/crypto.d.ts +9 -0
  13. package/dist/crypto.js +25 -0
  14. package/dist/discovery.d.ts +20 -0
  15. package/dist/discovery.js +25 -0
  16. package/dist/exception.d.ts +12 -0
  17. package/dist/exception.js +28 -0
  18. package/dist/inbox.d.ts +14 -0
  19. package/dist/inbox.js +71 -0
  20. package/dist/index.d.ts +26 -0
  21. package/dist/index.js +15 -0
  22. package/dist/message.d.ts +33 -0
  23. package/dist/message.js +59 -0
  24. package/dist/native.d.ts +6 -0
  25. package/dist/native.js +35 -0
  26. package/dist/package.json +1 -0
  27. package/dist/payload.d.ts +48 -0
  28. package/dist/payload.js +314 -0
  29. package/dist/peer.d.ts +16 -0
  30. package/dist/peer.js +124 -0
  31. package/dist/requests.d.ts +57 -0
  32. package/dist/requests.js +121 -0
  33. package/dist/rpc-streams.d.ts +13 -0
  34. package/dist/rpc-streams.js +31 -0
  35. package/dist/serializers.d.ts +29 -0
  36. package/dist/serializers.js +44 -0
  37. package/dist/session.d.ts +67 -0
  38. package/dist/session.js +528 -0
  39. package/dist/toolchain.txt +3 -0
  40. package/dist/transport.d.ts +47 -0
  41. package/dist/transport.js +201 -0
  42. package/dist/types.d.ts +70 -0
  43. package/dist/types.js +140 -0
  44. package/dist/util.d.ts +2 -0
  45. package/dist/util.js +20 -0
  46. package/dist/wasm/xconn_browser.d.ts +176 -0
  47. package/dist/wasm/xconn_browser.js +1467 -0
  48. package/dist/wasm/xconn_browser_bg.wasm +0 -0
  49. package/dist/wasm/xconn_browser_bg.wasm.d.ts +53 -0
  50. package/dist/webrtc.d.ts +98 -0
  51. package/dist/webrtc.js +712 -0
  52. package/dist/webtransport.d.ts +31 -0
  53. package/dist/webtransport.js +242 -0
  54. package/package.json +47 -4
package/dist/webrtc.js ADDED
@@ -0,0 +1,712 @@
1
+ import { ProtocolError } from "./exception.js";
2
+ import { Inbox } from "./inbox.js";
3
+ import { getNative, initializeWasm, rustCall } from "./native.js";
4
+ import { connectPeer, payloadBytes } from "./peer.js";
5
+ import { getSubProtocol } from "./serializers.js";
6
+ import { Session } from "./session.js";
7
+ import { abortable, timeoutValue } from "./util.js";
8
+ function byteLength(data) {
9
+ return typeof data === "string" ? new TextEncoder().encode(data).length : data.length;
10
+ }
11
+ function asError(error) {
12
+ return error instanceof Error ? error : new ProtocolError(String(error));
13
+ }
14
+ /** Browser-owned RTCDataChannel with Rust-owned chunk framing. */
15
+ export class DataChannel {
16
+ channel;
17
+ receiveLimit;
18
+ opened;
19
+ inbox = new Inbox(byteLength, 32 * 1024 * 1024, 256);
20
+ listeners = new Set();
21
+ decoder;
22
+ encoder;
23
+ writes = Promise.resolve();
24
+ closing;
25
+ closed = false;
26
+ reading = false;
27
+ queuedBytes = 0;
28
+ queuedWrites = 0;
29
+ bufferWaiters = new Map();
30
+ resolveOpen;
31
+ rejectOpen;
32
+ constructor(channel, receiveLimit) {
33
+ this.channel = channel;
34
+ this.receiveLimit = receiveLimit;
35
+ this.opened = new Promise((resolve, reject) => {
36
+ this.resolveOpen = resolve;
37
+ this.rejectOpen = reject;
38
+ });
39
+ void this.opened.catch(() => undefined);
40
+ channel.binaryType = "arraybuffer";
41
+ channel.addEventListener("open", this.onOpen);
42
+ channel.addEventListener("message", this.onMessage);
43
+ channel.addEventListener("error", this.onError);
44
+ channel.addEventListener("close", this.onClose);
45
+ if (channel.readyState === "open") {
46
+ this.onOpen();
47
+ }
48
+ else if (channel.readyState === "closed") {
49
+ this.onClose();
50
+ }
51
+ }
52
+ get label() {
53
+ return this.channel.label;
54
+ }
55
+ get protocol() {
56
+ return this.channel.protocol;
57
+ }
58
+ isConnected() {
59
+ return !this.closed && this.channel.readyState === "open";
60
+ }
61
+ onOpen = () => this.resolveOpen();
62
+ onClose = () => this.stop(new ProtocolError("Data channel closed"));
63
+ onError = () => {
64
+ this.stop(new ProtocolError("Data channel failed"));
65
+ this.channel.close();
66
+ };
67
+ onMessage = (event) => {
68
+ try {
69
+ const value = typeof event.data === "string"
70
+ ? event.data
71
+ : event.data instanceof ArrayBuffer
72
+ ? new Uint8Array(event.data)
73
+ : undefined;
74
+ if (value === undefined) {
75
+ throw new ProtocolError("Unsupported data-channel packet");
76
+ }
77
+ if (typeof value === "string" && value.length > getNative().channel_packet_limit()) {
78
+ throw new ProtocolError("Data-channel packet exceeds its limit");
79
+ }
80
+ const size = byteLength(value);
81
+ if (size > getNative().channel_packet_limit()) {
82
+ throw new ProtocolError("Data-channel packet exceeds its limit");
83
+ }
84
+ this.inbox.push(value);
85
+ }
86
+ catch (error) {
87
+ this.stop(asError(error));
88
+ this.channel.close();
89
+ }
90
+ };
91
+ stop(error) {
92
+ if (this.closed) {
93
+ return;
94
+ }
95
+ this.closed = true;
96
+ this.rejectOpen(error);
97
+ this.inbox.close(error);
98
+ this.decoder?.free();
99
+ this.encoder?.free();
100
+ this.decoder = undefined;
101
+ this.encoder = undefined;
102
+ this.channel.removeEventListener("open", this.onOpen);
103
+ this.channel.removeEventListener("message", this.onMessage);
104
+ this.channel.removeEventListener("close", this.onClose);
105
+ this.channel.removeEventListener("error", this.onError);
106
+ for (const callback of this.listeners) {
107
+ callback(error.message);
108
+ }
109
+ this.listeners.clear();
110
+ }
111
+ onDisconnect(callback) {
112
+ if (this.closed) {
113
+ callback("Data channel closed");
114
+ }
115
+ else {
116
+ this.listeners.add(callback);
117
+ }
118
+ }
119
+ /** Bytes waiting in both the owned write queue and the browser transport. */
120
+ get bufferedAmount() {
121
+ return this.queuedBytes + this.channel.bufferedAmount;
122
+ }
123
+ /** Wait for preceding writes and browser backpressure to drain. */
124
+ async waitBufferedBelow(threshold) {
125
+ if (!Number.isFinite(threshold) || threshold < 0) {
126
+ throw new RangeError("Buffer threshold must be a nonnegative finite number");
127
+ }
128
+ await this.writes;
129
+ if (!this.isConnected()) {
130
+ throw new ProtocolError("Data channel closed");
131
+ }
132
+ await this.bufferedBelow(threshold);
133
+ }
134
+ bufferedBelow(threshold) {
135
+ if (this.channel.bufferedAmount <= threshold) {
136
+ return Promise.resolve();
137
+ }
138
+ return new Promise((resolve, reject) => {
139
+ const token = Symbol();
140
+ const refreshThreshold = () => {
141
+ this.channel.bufferedAmountLowThreshold = this.bufferWaiters.size
142
+ ? Math.min(...this.bufferWaiters.values())
143
+ : 256 * 1024;
144
+ };
145
+ this.bufferWaiters.set(token, threshold);
146
+ refreshThreshold();
147
+ const cleanup = () => {
148
+ this.channel.removeEventListener("bufferedamountlow", low);
149
+ this.channel.removeEventListener("close", closed);
150
+ this.bufferWaiters.delete(token);
151
+ refreshThreshold();
152
+ };
153
+ const low = () => {
154
+ if (this.channel.bufferedAmount <= threshold) {
155
+ cleanup();
156
+ resolve();
157
+ }
158
+ };
159
+ const closed = () => {
160
+ cleanup();
161
+ reject(new ProtocolError("Data channel closed"));
162
+ };
163
+ this.channel.addEventListener("bufferedamountlow", low);
164
+ this.channel.addEventListener("close", closed);
165
+ if (this.channel.readyState === "closed") {
166
+ closed();
167
+ }
168
+ else {
169
+ low();
170
+ }
171
+ });
172
+ }
173
+ async packet(data) {
174
+ const size = byteLength(data);
175
+ if (size > getNative().channel_packet_limit()) {
176
+ throw new ProtocolError("Data-channel packet exceeds its limit");
177
+ }
178
+ await this.bufferedBelow(256 * 1024);
179
+ if (!this.isConnected()) {
180
+ throw new ProtocolError("Data channel closed");
181
+ }
182
+ if (typeof data === "string") {
183
+ this.channel.send(data);
184
+ }
185
+ else {
186
+ this.channel.send(new Uint8Array(data));
187
+ }
188
+ }
189
+ enqueue(data, write) {
190
+ if (this.closed || this.closing) {
191
+ return Promise.reject(new ProtocolError("Data channel closed"));
192
+ }
193
+ const size = byteLength(data);
194
+ if (this.queuedWrites >= 256 || this.queuedBytes + size > 32 * 1024 * 1024) {
195
+ return Promise.reject(new ProtocolError("Data-channel write queue exceeded its limit"));
196
+ }
197
+ const owned = typeof data === "string" ? data : data.slice();
198
+ this.queuedBytes += size;
199
+ this.queuedWrites++;
200
+ const result = this.writes
201
+ .then(() => {
202
+ if (this.closed) {
203
+ throw new ProtocolError("Data channel closed");
204
+ }
205
+ return write(owned);
206
+ })
207
+ .finally(() => {
208
+ this.queuedBytes -= size;
209
+ this.queuedWrites--;
210
+ });
211
+ this.writes = result.catch((error) => {
212
+ this.stop(asError(error));
213
+ this.channel.close();
214
+ });
215
+ return result;
216
+ }
217
+ send(data) {
218
+ return this.enqueue(data, (owned) => this.packet(owned));
219
+ }
220
+ reliable() {
221
+ if (!this.channel.ordered || this.channel.maxRetransmits !== null || this.channel.maxPacketLifeTime !== null) {
222
+ throw new ProtocolError("Chunked messages require an ordered, reliable channel");
223
+ }
224
+ }
225
+ writeMessage(data) {
226
+ this.reliable();
227
+ return this.enqueue(data, async (owned) => {
228
+ this.encoder ??= new (getNative().ChannelFraming)();
229
+ const chunks = rustCall(() => this.encoder.encode(owned));
230
+ for (const chunk of chunks) {
231
+ await this.packet(chunk);
232
+ }
233
+ });
234
+ }
235
+ async receive(signal) {
236
+ if (this.closed) {
237
+ throw new ProtocolError("Data channel closed");
238
+ }
239
+ if (this.reading) {
240
+ throw new ProtocolError("A channel read is already pending");
241
+ }
242
+ this.reading = true;
243
+ try {
244
+ return await this.inbox.receive(signal);
245
+ }
246
+ finally {
247
+ this.reading = false;
248
+ }
249
+ }
250
+ async readMessage(signal) {
251
+ if (this.closed) {
252
+ throw new ProtocolError("Data channel closed");
253
+ }
254
+ this.reliable();
255
+ if (this.reading) {
256
+ throw new ProtocolError("A channel read is already pending");
257
+ }
258
+ this.reading = true;
259
+ try {
260
+ this.decoder ??= new (getNative().ChannelFraming)(this.receiveLimit);
261
+ for (;;) {
262
+ const packet = await this.inbox.receive(signal);
263
+ if (this.closed) {
264
+ throw new ProtocolError("Data channel closed");
265
+ }
266
+ if (typeof packet === "string") {
267
+ throw new ProtocolError("Text packet in a chunked message");
268
+ }
269
+ const result = rustCall(() => this.decoder.feed(packet));
270
+ if (result !== undefined) {
271
+ return result;
272
+ }
273
+ }
274
+ }
275
+ catch (error) {
276
+ if (!signal?.aborted) {
277
+ this.stop(asError(error));
278
+ this.channel.close();
279
+ }
280
+ throw error;
281
+ }
282
+ finally {
283
+ this.reading = false;
284
+ }
285
+ }
286
+ close() {
287
+ return (this.closing ??= (async () => {
288
+ let timer;
289
+ try {
290
+ await Promise.race([
291
+ this.writes.then(() => this.bufferedBelow(0)),
292
+ new Promise((resolve) => {
293
+ timer = setTimeout(resolve, 2000);
294
+ }),
295
+ ]);
296
+ }
297
+ finally {
298
+ clearTimeout(timer);
299
+ this.stop(new ProtocolError("Data channel closed"));
300
+ this.channel.close();
301
+ }
302
+ })());
303
+ }
304
+ }
305
+ class ChannelPeer {
306
+ channel;
307
+ framing;
308
+ constructor(channel, serializer) {
309
+ this.channel = channel;
310
+ this.framing = new (getNative().RawSocketFraming)(getSubProtocol(serializer).slice("wamp.2.".length), getNative().channel_message_limit());
311
+ channel.onDisconnect(() => this.framing.free());
312
+ }
313
+ async negotiate(signal) {
314
+ await abortable(this.channel.opened, signal);
315
+ await abortable(this.channel.send(rustCall(() => this.framing.handshake())), signal);
316
+ const response = await this.channel.receive(signal);
317
+ if (typeof response === "string") {
318
+ throw new ProtocolError("Text RawSocket handshake");
319
+ }
320
+ rustCall(() => this.framing.accept_handshake(response));
321
+ }
322
+ send(payload) {
323
+ const data = payloadBytes(payload);
324
+ if (data.length > this.framing.send_limit()) {
325
+ throw new ProtocolError("WAMP payload exceeds peer limit");
326
+ }
327
+ return this.channel.writeMessage(data);
328
+ }
329
+ receive() {
330
+ return this.channel.readMessage();
331
+ }
332
+ onDisconnect(callback) {
333
+ this.channel.onDisconnect(callback);
334
+ }
335
+ isConnected() {
336
+ return this.channel.isConnected();
337
+ }
338
+ close() {
339
+ return this.channel.close();
340
+ }
341
+ }
342
+ export class WebRTCSession extends Session {
343
+ connection;
344
+ constructor(base, connection, options = {}) {
345
+ super(base, options);
346
+ this.connection = connection;
347
+ }
348
+ }
349
+ /** Browser ICE, DTLS and SCTP; WAMP and message framing remain in Rust/WASM. */
350
+ export class WebRTCConnection {
351
+ peer;
352
+ signaling;
353
+ options;
354
+ rpcSessionOpened = false;
355
+ incoming = new Inbox(() => 1, 256, 256);
356
+ channels = new Set();
357
+ initial;
358
+ subscription;
359
+ closing;
360
+ closed = false;
361
+ setup;
362
+ requestID;
363
+ publishingActive = false;
364
+ remoteQueued = 0;
365
+ remote = Promise.resolve();
366
+ publishing = Promise.resolve();
367
+ remotePending = [];
368
+ localPending = [];
369
+ constructor(peer, signaling, options) {
370
+ this.peer = peer;
371
+ this.signaling = signaling;
372
+ this.options = options;
373
+ peer.addEventListener("datachannel", (event) => {
374
+ if (event.channel.protocol !== getNative().raw_channel_protocol()) {
375
+ event.channel.close();
376
+ return;
377
+ }
378
+ const channel = this.track(event.channel);
379
+ try {
380
+ this.incoming.push(channel);
381
+ }
382
+ catch {
383
+ void channel.close();
384
+ void this.close();
385
+ }
386
+ });
387
+ peer.addEventListener("connectionstatechange", () => {
388
+ if (peer.connectionState === "failed" || peer.connectionState === "closed") {
389
+ void this.close();
390
+ }
391
+ });
392
+ peer.addEventListener("icecandidate", (event) => {
393
+ if (this.closed) {
394
+ return;
395
+ }
396
+ const candidate = event.candidate?.toJSON() ?? { candidate: "" };
397
+ if (!this.publishingActive) {
398
+ if (this.localPending.length >= 256) {
399
+ void this.close();
400
+ return;
401
+ }
402
+ this.localPending.push(candidate);
403
+ }
404
+ else {
405
+ this.publish(candidate);
406
+ }
407
+ });
408
+ }
409
+ track(channel) {
410
+ const wrapped = new DataChannel(channel);
411
+ this.channels.add(wrapped);
412
+ wrapped.onDisconnect(() => this.channels.delete(wrapped));
413
+ return wrapped;
414
+ }
415
+ publish(candidate) {
416
+ this.publishing = this.publishing
417
+ .then(async () => {
418
+ if (this.closed) {
419
+ return;
420
+ }
421
+ const json = rustCall(() => getNative().signaling_encode(candidate));
422
+ await this.signaling.publish(this.options.localCandidatesTopic).args(this.requestID, json).execute();
423
+ })
424
+ .catch(() => {
425
+ void this.close();
426
+ });
427
+ }
428
+ candidate(id, json) {
429
+ if (this.closed) {
430
+ return;
431
+ }
432
+ if (++this.remoteQueued > 256) {
433
+ void this.close();
434
+ return;
435
+ }
436
+ // A single chain preserves ordering across early-candidate activation and live trickle.
437
+ this.remote = this.remote
438
+ .then(async () => {
439
+ if (this.closed) {
440
+ return;
441
+ }
442
+ const candidate = rustCall(() => getNative().signaling_decode(json));
443
+ if (typeof candidate.candidate !== "string") {
444
+ throw new ProtocolError("Invalid ICE candidate");
445
+ }
446
+ if (!this.requestID) {
447
+ if (this.remotePending.length >= 256) {
448
+ throw new ProtocolError("Too many pending ICE candidates");
449
+ }
450
+ this.remotePending.push([id, candidate]);
451
+ }
452
+ else if (id === this.requestID) {
453
+ await this.peer.addIceCandidate(candidate.candidate ? candidate : null);
454
+ }
455
+ })
456
+ .catch(() => {
457
+ void this.close();
458
+ })
459
+ .finally(() => {
460
+ this.remoteQueued--;
461
+ });
462
+ }
463
+ static async connect(signaling, realm, options) {
464
+ if (typeof RTCPeerConnection === "undefined") {
465
+ throw new ProtocolError("WebRTC is unavailable in this runtime");
466
+ }
467
+ for (const value of [options.offerProcedure, options.remoteCandidatesTopic, options.localCandidatesTopic]) {
468
+ if (typeof value !== "string" || !value) {
469
+ throw new ProtocolError("WebRTC offer and candidate endpoints are required");
470
+ }
471
+ }
472
+ const timeout = timeoutValue(options.connectTimeout ?? 20000, "connectTimeout");
473
+ timeoutValue(options.openTimeout ?? 20000, "openTimeout");
474
+ timeoutValue(options.handshakeTimeout ?? 5000, "handshakeTimeout");
475
+ const controller = new AbortController();
476
+ const abort = () => controller.abort(options.signal?.reason);
477
+ options.signal?.addEventListener("abort", abort, { once: true });
478
+ if (options.signal?.aborted) {
479
+ abort();
480
+ }
481
+ const timer = timeout > 0
482
+ ? setTimeout(() => controller.abort(new ProtocolError("WebRTC connection timed out")), timeout)
483
+ : undefined;
484
+ let connection;
485
+ try {
486
+ controller.signal.throwIfAborted();
487
+ await abortable(initializeWasm(), controller.signal);
488
+ connection = new WebRTCConnection(new RTCPeerConnection({ iceServers: options.iceServers }), signaling, options);
489
+ const current = connection;
490
+ current.setup = controller;
491
+ current.initial = current.track(current.peer.createDataChannel("data"));
492
+ const pending = signaling
493
+ .subscribe(options.remoteCandidatesTopic, (event) => {
494
+ const [id, json] = event.args ?? [];
495
+ if (typeof id === "string" && typeof json === "string") {
496
+ current.candidate(id, json);
497
+ }
498
+ })
499
+ .execute()
500
+ .then((subscription) => {
501
+ if (current.closed) {
502
+ void subscription.unsubscribe().catch(() => undefined);
503
+ }
504
+ else {
505
+ current.subscription = subscription;
506
+ }
507
+ return subscription;
508
+ });
509
+ await abortable(pending, controller.signal);
510
+ const offer = await abortable(current.peer.createOffer(), controller.signal);
511
+ await abortable(current.peer.setLocalDescription(offer), controller.signal);
512
+ const payload = rustCall(() => getNative().signaling_encode({ description: offer, candidates: [] }));
513
+ const result = await signaling
514
+ .call(options.offerProcedure)
515
+ .arg(payload)
516
+ .signal(controller.signal)
517
+ .execute();
518
+ if (typeof result.args?.[0] !== "string") {
519
+ throw new ProtocolError("Invalid WebRTC offer response");
520
+ }
521
+ const response = rustCall(() => getNative().signaling_decode(result.args[0]));
522
+ if (typeof response.requestID !== "string" ||
523
+ !response.requestID ||
524
+ response.answer?.description?.type !== "answer") {
525
+ throw new ProtocolError("Invalid WebRTC answer");
526
+ }
527
+ await abortable(current.peer.setRemoteDescription(response.answer.description), controller.signal);
528
+ current.remote = current.remote.then(async () => {
529
+ current.requestID = response.requestID;
530
+ for (const candidate of response.answer.candidates ?? []) {
531
+ await current.peer.addIceCandidate(candidate.candidate ? candidate : null);
532
+ }
533
+ for (const [id, candidate] of current.remotePending.splice(0)) {
534
+ if (id === current.requestID) {
535
+ await current.peer.addIceCandidate(candidate.candidate ? candidate : null);
536
+ }
537
+ }
538
+ });
539
+ await abortable(current.remote, controller.signal);
540
+ for (const candidate of current.localPending.splice(0)) {
541
+ current.publish(candidate);
542
+ }
543
+ current.publishingActive = true;
544
+ const session = await current.openSession(realm, { ...options, signal: controller.signal });
545
+ return session;
546
+ }
547
+ catch (error) {
548
+ await connection?.close();
549
+ throw error;
550
+ }
551
+ finally {
552
+ if (connection) {
553
+ connection.setup = undefined;
554
+ }
555
+ clearTimeout(timer);
556
+ options.signal?.removeEventListener("abort", abort);
557
+ }
558
+ }
559
+ openSession(realm, options = {}) {
560
+ const streamOpener = this.rpcSessionOpened ? undefined : () => this.openRPCStream();
561
+ this.rpcSessionOpened = true;
562
+ return connectPeer(async (serializer, signal) => {
563
+ if (this.closed) {
564
+ throw new ProtocolError("WebRTC connection closed");
565
+ }
566
+ const channel = this.initial ?? this.track(this.peer.createDataChannel("data"));
567
+ this.initial = undefined;
568
+ const peer = new ChannelPeer(channel, serializer);
569
+ try {
570
+ await this.waitChannel(channel, this.options.openTimeout, signal);
571
+ const controller = new AbortController();
572
+ const abort = () => controller.abort(signal.reason);
573
+ signal.addEventListener("abort", abort, { once: true });
574
+ if (signal.aborted) {
575
+ abort();
576
+ }
577
+ const deadline = timeoutValue(this.options.handshakeTimeout ?? 5000, "handshakeTimeout");
578
+ const timer = setTimeout(() => controller.abort(new ProtocolError("WebRTC handshake timed out")), deadline);
579
+ try {
580
+ await peer.negotiate(controller.signal);
581
+ }
582
+ finally {
583
+ clearTimeout(timer);
584
+ signal.removeEventListener("abort", abort);
585
+ }
586
+ return peer;
587
+ }
588
+ catch (error) {
589
+ await peer.close();
590
+ throw error;
591
+ }
592
+ }, realm, { connectTimeout: this.options.openTimeout ?? 20000, ...options }, (base, config) => new WebRTCSession(base, this, { ...config, streamOpener }));
593
+ }
594
+ async openRPCStream() {
595
+ if (this.closed)
596
+ throw new ProtocolError("WebRTC connection closed");
597
+ const channel = this.track(this.peer.createDataChannel("xconn.rpc.stream.v1", {
598
+ ordered: true,
599
+ protocol: "xconn.rpc.stream.v1",
600
+ }));
601
+ try {
602
+ await this.waitChannel(channel);
603
+ return new ChannelStream(channel);
604
+ }
605
+ catch (error) {
606
+ await channel.close();
607
+ throw error;
608
+ }
609
+ }
610
+ async openChannel(label, options = {}) {
611
+ if (this.closed) {
612
+ throw new ProtocolError("WebRTC connection closed");
613
+ }
614
+ const { signal, openTimeout, ...config } = options;
615
+ const channel = this.track(this.peer.createDataChannel(label, { ...config, protocol: getNative().raw_channel_protocol() }));
616
+ try {
617
+ await this.waitChannel(channel, openTimeout, signal);
618
+ return channel;
619
+ }
620
+ catch (error) {
621
+ await channel.close();
622
+ throw error;
623
+ }
624
+ }
625
+ async acceptChannel(options = {}) {
626
+ const channel = await this.incoming.receive(options.signal);
627
+ try {
628
+ await this.waitChannel(channel, options.openTimeout, options.signal);
629
+ return channel;
630
+ }
631
+ catch (error) {
632
+ await channel.close();
633
+ throw error;
634
+ }
635
+ }
636
+ async waitChannel(channel, timeout, signal) {
637
+ const milliseconds = timeoutValue(timeout ?? this.options.openTimeout ?? 20000, "openTimeout");
638
+ const controller = new AbortController();
639
+ const abort = () => controller.abort(signal?.reason);
640
+ signal?.addEventListener("abort", abort, { once: true });
641
+ if (signal?.aborted) {
642
+ abort();
643
+ }
644
+ const timer = milliseconds > 0
645
+ ? setTimeout(() => controller.abort(new ProtocolError("Data channel open timed out")), milliseconds)
646
+ : undefined;
647
+ try {
648
+ await abortable(channel.opened, controller.signal);
649
+ }
650
+ finally {
651
+ clearTimeout(timer);
652
+ signal?.removeEventListener("abort", abort);
653
+ }
654
+ }
655
+ close() {
656
+ return (this.closing ??= (async () => {
657
+ this.closed = true;
658
+ this.setup?.abort(new ProtocolError("WebRTC connection closed"));
659
+ this.peer.onicecandidate = null;
660
+ this.peer.close();
661
+ this.incoming.close(new ProtocolError("WebRTC connection closed"));
662
+ await Promise.allSettled([...this.channels].map((channel) => channel.close()));
663
+ await this.subscription?.unsubscribe().catch(() => undefined);
664
+ this.remotePending.length = 0;
665
+ this.localPending.length = 0;
666
+ })());
667
+ }
668
+ }
669
+ /** SCTP carries independent streams; one marker distinguishes bytes from write EOF. */
670
+ class ChannelStream {
671
+ channel;
672
+ writes = Promise.resolve();
673
+ eof = false;
674
+ finished = false;
675
+ constructor(channel) {
676
+ this.channel = channel;
677
+ }
678
+ async read() {
679
+ if (this.eof)
680
+ return undefined;
681
+ const packet = await this.channel.receive();
682
+ if (!(packet instanceof Uint8Array) || packet.length === 0 || packet.length > 16385) {
683
+ throw new ProtocolError("Invalid RPC stream packet");
684
+ }
685
+ if (packet[0] === 1 && packet.length === 1) {
686
+ this.eof = true;
687
+ return undefined;
688
+ }
689
+ if (packet[0] !== 0 || packet.length === 1)
690
+ throw new ProtocolError("Invalid RPC stream packet");
691
+ return packet.subarray(1);
692
+ }
693
+ write(data) {
694
+ if (this.finished)
695
+ return Promise.reject(new ProtocolError("RPC stream write side closed"));
696
+ return (this.writes = this.writes.then(async () => {
697
+ for (let offset = 0; offset < data.length; offset += 16384) {
698
+ await this.channel.send(new Uint8Array([0, ...data.subarray(offset, offset + 16384)]));
699
+ }
700
+ }));
701
+ }
702
+ writeEof() {
703
+ if (!this.finished) {
704
+ this.finished = true;
705
+ this.writes = this.writes.then(() => this.channel.send(new Uint8Array([1])));
706
+ }
707
+ return this.writes;
708
+ }
709
+ close() {
710
+ return this.channel.close();
711
+ }
712
+ }