@dxos/network-manager 0.3.8-next.f4e0086 → 0.3.9-main.1d6fb54

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.
@@ -0,0 +1,3813 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var chunk_6AD7QA4X_exports = {};
30
+ __export(chunk_6AD7QA4X_exports, {
31
+ Connection: () => Connection,
32
+ ConnectionLimiter: () => ConnectionLimiter,
33
+ ConnectionLog: () => ConnectionLog,
34
+ ConnectionState: () => ConnectionState,
35
+ EventType: () => EventType,
36
+ FullyConnectedTopology: () => FullyConnectedTopology,
37
+ LibDataChannelTransport: () => LibDataChannelTransport,
38
+ MAX_CONCURRENT_INITIATING_CONNECTIONS: () => MAX_CONCURRENT_INITIATING_CONNECTIONS,
39
+ MMSTTopology: () => MMSTTopology,
40
+ MemoryTransport: () => MemoryTransport,
41
+ MemoryTransportFactory: () => MemoryTransportFactory,
42
+ NetworkManager: () => NetworkManager,
43
+ SimplePeerTransport: () => SimplePeerTransport,
44
+ SimplePeerTransportProxy: () => SimplePeerTransportProxy,
45
+ SimplePeerTransportProxyFactory: () => SimplePeerTransportProxyFactory,
46
+ SimplePeerTransportService: () => SimplePeerTransportService,
47
+ StarTopology: () => StarTopology,
48
+ Swarm: () => Swarm,
49
+ SwarmMapper: () => SwarmMapper,
50
+ SwarmMessenger: () => SwarmMessenger,
51
+ TcpTransport: () => TcpTransport,
52
+ TcpTransportFactory: () => TcpTransportFactory,
53
+ TransportKind: () => TransportKind,
54
+ createLibDataChannelTransportFactory: () => createLibDataChannelTransportFactory,
55
+ createSimplePeerTransportFactory: () => createSimplePeerTransportFactory,
56
+ createTeleportProtocolFactory: () => createTeleportProtocolFactory
57
+ });
58
+ module.exports = __toCommonJS(chunk_6AD7QA4X_exports);
59
+ var import_chunk_XE5JOIGD = require("./chunk-XE5JOIGD.cjs");
60
+ var import_async = require("@dxos/async");
61
+ var import_context = require("@dxos/context");
62
+ var import_debug = require("@dxos/debug");
63
+ var import_invariant = require("@dxos/invariant");
64
+ var import_keys = require("@dxos/keys");
65
+ var import_log = require("@dxos/log");
66
+ var import_protocols = require("@dxos/protocols");
67
+ var import_context2 = require("@dxos/context");
68
+ var import_invariant2 = require("@dxos/invariant");
69
+ var import_keys2 = require("@dxos/keys");
70
+ var import_log2 = require("@dxos/log");
71
+ var import_protocols2 = require("@dxos/protocols");
72
+ var import_util = require("@dxos/util");
73
+ var import_async2 = require("@dxos/async");
74
+ var import_context3 = require("@dxos/context");
75
+ var import_debug2 = require("@dxos/debug");
76
+ var import_invariant3 = require("@dxos/invariant");
77
+ var import_keys3 = require("@dxos/keys");
78
+ var import_log3 = require("@dxos/log");
79
+ var import_protocols3 = require("@dxos/protocols");
80
+ var import_util2 = require("@dxos/util");
81
+ var import_async3 = require("@dxos/async");
82
+ var import_context4 = require("@dxos/context");
83
+ var import_invariant4 = require("@dxos/invariant");
84
+ var import_keys4 = require("@dxos/keys");
85
+ var import_log4 = require("@dxos/log");
86
+ var import_protocols4 = require("@dxos/protocols");
87
+ var import_async4 = require("@dxos/async");
88
+ var import_keys5 = require("@dxos/keys");
89
+ var import_log5 = require("@dxos/log");
90
+ var import_util3 = require("@dxos/util");
91
+ var import_async5 = require("@dxos/async");
92
+ var import_context5 = require("@dxos/context");
93
+ var import_invariant5 = require("@dxos/invariant");
94
+ var import_keys6 = require("@dxos/keys");
95
+ var import_log6 = require("@dxos/log");
96
+ var import_protocols5 = require("@dxos/protocols");
97
+ var import_util4 = require("@dxos/util");
98
+ var import_async6 = require("@dxos/async");
99
+ var import_debug3 = require("@dxos/debug");
100
+ var import_keys7 = require("@dxos/keys");
101
+ var import_util5 = require("@dxos/util");
102
+ var import_async7 = require("@dxos/async");
103
+ var import_invariant6 = require("@dxos/invariant");
104
+ var import_keys8 = require("@dxos/keys");
105
+ var import_log7 = require("@dxos/log");
106
+ var import_messaging = require("@dxos/messaging");
107
+ var import_protocols6 = require("@dxos/protocols");
108
+ var import_services = require("@dxos/protocols/proto/dxos/client/services");
109
+ var import_util6 = require("@dxos/util");
110
+ var import_invariant7 = require("@dxos/invariant");
111
+ var import_xor_distance = __toESM(require("xor-distance"));
112
+ var import_invariant8 = require("@dxos/invariant");
113
+ var import_log8 = require("@dxos/log");
114
+ var import_invariant9 = require("@dxos/invariant");
115
+ var import_log9 = require("@dxos/log");
116
+ var import_node_stream = require("node:stream");
117
+ var import_async8 = require("@dxos/async");
118
+ var import_debug4 = require("@dxos/debug");
119
+ var import_invariant10 = require("@dxos/invariant");
120
+ var import_keys9 = require("@dxos/keys");
121
+ var import_log10 = require("@dxos/log");
122
+ var import_util7 = require("@dxos/util");
123
+ var import_simple_peer = __toESM(require("simple-peer"));
124
+ var import_tiny_invariant = __toESM(require("tiny-invariant"));
125
+ var import_async9 = require("@dxos/async");
126
+ var import_debug5 = require("@dxos/debug");
127
+ var import_keys10 = require("@dxos/keys");
128
+ var import_log11 = require("@dxos/log");
129
+ var import_protocols7 = require("@dxos/protocols");
130
+ var import_node_stream2 = require("node:stream");
131
+ var import_codec_protobuf = require("@dxos/codec-protobuf");
132
+ var import_invariant11 = require("@dxos/invariant");
133
+ var import_keys11 = require("@dxos/keys");
134
+ var import_log12 = require("@dxos/log");
135
+ var import_bridge = require("@dxos/protocols/proto/dxos/mesh/bridge");
136
+ var import_util8 = require("@dxos/util");
137
+ var import_node_stream3 = require("node:stream");
138
+ var import_async10 = require("@dxos/async");
139
+ var import_context6 = require("@dxos/context");
140
+ var import_debug6 = require("@dxos/debug");
141
+ var import_invariant12 = require("@dxos/invariant");
142
+ var import_keys12 = require("@dxos/keys");
143
+ var import_log13 = require("@dxos/log");
144
+ var import_protocols8 = require("@dxos/protocols");
145
+ var import_bridge2 = require("@dxos/protocols/proto/dxos/mesh/bridge");
146
+ var import_util9 = require("@dxos/util");
147
+ var import_stream = require("stream");
148
+ var import_async11 = require("@dxos/async");
149
+ var import_debug7 = require("@dxos/debug");
150
+ var import_log14 = require("@dxos/log");
151
+ var import_node_net = require("node:net");
152
+ var import_async12 = require("@dxos/async");
153
+ var import_debug8 = require("@dxos/debug");
154
+ var import_log15 = require("@dxos/log");
155
+ var import_teleport = require("@dxos/teleport");
156
+ function _ts_decorate(decorators, target, key, desc) {
157
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
158
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
159
+ r = Reflect.decorate(decorators, target, key, desc);
160
+ else
161
+ for (var i = decorators.length - 1; i >= 0; i--)
162
+ if (d = decorators[i])
163
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
164
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
165
+ }
166
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/connection.ts";
167
+ var STARTING_SIGNALLING_DELAY = 10;
168
+ var TRANSPORT_CONNECTION_TIMEOUT = 1e4;
169
+ var MAX_SIGNALLING_DELAY = 300;
170
+ var ConnectionState;
171
+ (function(ConnectionState5) {
172
+ ConnectionState5[
173
+ /**
174
+ * Connection is created, but not yet passed through the connection limiter.
175
+ */
176
+ "CREATED"
177
+ ] = "CREATED";
178
+ ConnectionState5[
179
+ /**
180
+ * Initial state. Connection is registered but no attempt to connect to the remote peer has been performed.
181
+ * Might mean that we are waiting for the answer signal from the remote peer.
182
+ */
183
+ "INITIAL"
184
+ ] = "INITIAL";
185
+ ConnectionState5[
186
+ /**
187
+ * Trying to establish connection.
188
+ */
189
+ "CONNECTING"
190
+ ] = "CONNECTING";
191
+ ConnectionState5[
192
+ /**
193
+ * Connection is established.
194
+ */
195
+ "CONNECTED"
196
+ ] = "CONNECTED";
197
+ ConnectionState5[
198
+ /**
199
+ * Connection is being closed.
200
+ */
201
+ "CLOSING"
202
+ ] = "CLOSING";
203
+ ConnectionState5[
204
+ /**
205
+ * Connection closed.
206
+ */
207
+ "CLOSED"
208
+ ] = "CLOSED";
209
+ ConnectionState5["ABORTING"] = "ABORTING";
210
+ ConnectionState5["ABORTED"] = "ABORTED";
211
+ })(ConnectionState || (ConnectionState = {}));
212
+ var Connection = class {
213
+ constructor(topic, ownId, remoteId, sessionId, initiator, _signalMessaging, _protocol, _transportFactory, _callbacks) {
214
+ this.topic = topic;
215
+ this.ownId = ownId;
216
+ this.remoteId = remoteId;
217
+ this.sessionId = sessionId;
218
+ this.initiator = initiator;
219
+ this._signalMessaging = _signalMessaging;
220
+ this._protocol = _protocol;
221
+ this._transportFactory = _transportFactory;
222
+ this._callbacks = _callbacks;
223
+ this._ctx = new import_context.Context();
224
+ this.connectedTimeoutContext = new import_context.Context();
225
+ this._state = ConnectionState.CREATED;
226
+ this._incomingSignalBuffer = [];
227
+ this._outgoingSignalBuffer = [];
228
+ this.stateChanged = new import_async.Event();
229
+ this.errors = new import_debug.ErrorStream();
230
+ this._instanceId = import_keys.PublicKey.random().toHex();
231
+ this._signalSendTask = new import_async.DeferredTask(this._ctx, async () => {
232
+ await this._flushSignalBuffer();
233
+ });
234
+ this._signallingDelay = STARTING_SIGNALLING_DELAY;
235
+ import_log.log.trace("dxos.mesh.connection.construct", {
236
+ sessionId: this.sessionId,
237
+ topic: this.topic,
238
+ localPeerId: this.ownId,
239
+ remotePeerId: this.remoteId,
240
+ initiator: this.initiator
241
+ }, {
242
+ F: __dxlog_file,
243
+ L: 130,
244
+ S: this,
245
+ C: (f, a) => f(...a)
246
+ });
247
+ }
248
+ get state() {
249
+ return this._state;
250
+ }
251
+ get transport() {
252
+ return this._transport;
253
+ }
254
+ get protocol() {
255
+ return this._protocol;
256
+ }
257
+ /**
258
+ * Create an underlying transport and prepares it for the connection.
259
+ */
260
+ async openConnection() {
261
+ (0, import_invariant.invariant)(this._state === ConnectionState.INITIAL, "Invalid state.", {
262
+ F: __dxlog_file,
263
+ L: 155,
264
+ S: this,
265
+ A: [
266
+ "this._state === ConnectionState.INITIAL",
267
+ "'Invalid state.'"
268
+ ]
269
+ });
270
+ import_log.log.trace("dxos.mesh.connection.open-connection", import_protocols.trace.begin({
271
+ id: this._instanceId
272
+ }), {
273
+ F: __dxlog_file,
274
+ L: 156,
275
+ S: this,
276
+ C: (f, a) => f(...a)
277
+ });
278
+ import_log.log.trace("dxos.mesh.connection.open", {
279
+ sessionId: this.sessionId,
280
+ topic: this.topic,
281
+ localPeerId: this.ownId,
282
+ remotePeerId: this.remoteId,
283
+ initiator: this.initiator
284
+ }, {
285
+ F: __dxlog_file,
286
+ L: 157,
287
+ S: this,
288
+ C: (f, a) => f(...a)
289
+ });
290
+ this._changeState(ConnectionState.CONNECTING);
291
+ this._protocol.open().catch((err) => {
292
+ this.errors.raise(err);
293
+ });
294
+ this._protocol.stream.on("close", () => {
295
+ (0, import_log.log)("protocol stream closed", void 0, {
296
+ F: __dxlog_file,
297
+ L: 174,
298
+ S: this,
299
+ C: (f, a) => f(...a)
300
+ });
301
+ this.close(new import_protocols.ProtocolError("protocol stream closed")).catch((err) => this.errors.raise(err));
302
+ });
303
+ (0, import_async.scheduleTask)(this.connectedTimeoutContext, async () => {
304
+ import_log.log.info(`timeout waiting ${TRANSPORT_CONNECTION_TIMEOUT / 1e3}s for transport to connect, aborting`, void 0, {
305
+ F: __dxlog_file,
306
+ L: 181,
307
+ S: this,
308
+ C: (f, a) => f(...a)
309
+ });
310
+ await this.abort(new import_protocols.TimeoutError(`${TRANSPORT_CONNECTION_TIMEOUT / 1e3}s for transport to connect`)).catch((err) => this.errors.raise(err));
311
+ }, TRANSPORT_CONNECTION_TIMEOUT);
312
+ (0, import_invariant.invariant)(!this._transport, void 0, {
313
+ F: __dxlog_file,
314
+ L: 189,
315
+ S: this,
316
+ A: [
317
+ "!this._transport",
318
+ ""
319
+ ]
320
+ });
321
+ this._transport = this._transportFactory.createTransport({
322
+ initiator: this.initiator,
323
+ stream: this._protocol.stream,
324
+ sendSignal: async (signal) => this._sendSignal(signal)
325
+ });
326
+ this._transport.connected.once(async () => {
327
+ this._changeState(ConnectionState.CONNECTED);
328
+ await this.connectedTimeoutContext.dispose();
329
+ this._callbacks?.onConnected?.();
330
+ });
331
+ this._transport.closed.once(() => {
332
+ this._transport = void 0;
333
+ (0, import_log.log)("abort triggered by transport close", void 0, {
334
+ F: __dxlog_file,
335
+ L: 204,
336
+ S: this,
337
+ C: (f, a) => f(...a)
338
+ });
339
+ this.abort().catch((err) => this.errors.raise(err));
340
+ });
341
+ this._transport.errors.handle(async (err) => {
342
+ (0, import_log.log)("transport error:", {
343
+ err
344
+ }, {
345
+ F: __dxlog_file,
346
+ L: 209,
347
+ S: this,
348
+ C: (f, a) => f(...a)
349
+ });
350
+ if (!this.closeReason) {
351
+ this.closeReason = err?.message;
352
+ }
353
+ if (err instanceof import_protocols.ConnectionResetError) {
354
+ import_log.log.info("aborting due to transport ConnectionResetError", void 0, {
355
+ F: __dxlog_file,
356
+ L: 216,
357
+ S: this,
358
+ C: (f, a) => f(...a)
359
+ });
360
+ this.abort().catch((err2) => this.errors.raise(err2));
361
+ } else if (err instanceof import_protocols.ConnectivityError) {
362
+ import_log.log.info("aborting due to transport ConnectivityError", void 0, {
363
+ F: __dxlog_file,
364
+ L: 219,
365
+ S: this,
366
+ C: (f, a) => f(...a)
367
+ });
368
+ this.abort().catch((err2) => this.errors.raise(err2));
369
+ } else if (err instanceof import_protocols.UnknownProtocolError) {
370
+ import_log.log.warn("unsure what to do with UnknownProtocolError, will keep on truckin", {
371
+ err
372
+ }, {
373
+ F: __dxlog_file,
374
+ L: 222,
375
+ S: this,
376
+ C: (f, a) => f(...a)
377
+ });
378
+ }
379
+ if (this._state !== ConnectionState.CLOSED && this._state !== ConnectionState.CLOSING) {
380
+ await this.connectedTimeoutContext.dispose();
381
+ this.errors.raise(err);
382
+ }
383
+ });
384
+ for (const signal of this._incomingSignalBuffer) {
385
+ void this._transport.signal(signal);
386
+ }
387
+ this._incomingSignalBuffer = [];
388
+ import_log.log.trace("dxos.mesh.connection.open-connection", import_protocols.trace.end({
389
+ id: this._instanceId
390
+ }), {
391
+ F: __dxlog_file,
392
+ L: 238,
393
+ S: this,
394
+ C: (f, a) => f(...a)
395
+ });
396
+ }
397
+ async abort(err) {
398
+ (0, import_log.log)("aborting...", {
399
+ err
400
+ }, {
401
+ F: __dxlog_file,
402
+ L: 245,
403
+ S: this,
404
+ C: (f, a) => f(...a)
405
+ });
406
+ if (this._state === ConnectionState.CLOSED || this._state === ConnectionState.ABORTED) {
407
+ (0, import_log.log)(`abort ignored: already ${this._state}`, this.closeReason, {
408
+ F: __dxlog_file,
409
+ L: 247,
410
+ S: this,
411
+ C: (f, a) => f(...a)
412
+ });
413
+ return;
414
+ }
415
+ await this.connectedTimeoutContext.dispose();
416
+ this._changeState(ConnectionState.ABORTING);
417
+ if (!this.closeReason) {
418
+ this.closeReason = err?.message;
419
+ }
420
+ await this._ctx.dispose();
421
+ try {
422
+ (0, import_log.log)("aborting protocol... ", void 0, {
423
+ F: __dxlog_file,
424
+ L: 261,
425
+ S: this,
426
+ C: (f, a) => f(...a)
427
+ });
428
+ await this._protocol.abort();
429
+ } catch (err2) {
430
+ import_log.log.catch(err2, void 0, {
431
+ F: __dxlog_file,
432
+ L: 264,
433
+ S: this,
434
+ C: (f, a) => f(...a)
435
+ });
436
+ }
437
+ try {
438
+ await this._transport?.destroy();
439
+ } catch (err2) {
440
+ import_log.log.catch(err2, void 0, {
441
+ F: __dxlog_file,
442
+ L: 271,
443
+ S: this,
444
+ C: (f, a) => f(...a)
445
+ });
446
+ }
447
+ try {
448
+ this._callbacks?.onClosed?.(err);
449
+ } catch (err2) {
450
+ import_log.log.catch(err2, void 0, {
451
+ F: __dxlog_file,
452
+ L: 277,
453
+ S: this,
454
+ C: (f, a) => f(...a)
455
+ });
456
+ }
457
+ this._changeState(ConnectionState.ABORTED);
458
+ }
459
+ async close(err) {
460
+ if (!this.closeReason) {
461
+ this.closeReason = err?.message;
462
+ } else {
463
+ this.closeReason += `; ${err?.message}`;
464
+ }
465
+ if (this._state === ConnectionState.CLOSED || this._state === ConnectionState.ABORTING || this._state === ConnectionState.ABORTED) {
466
+ return;
467
+ }
468
+ const lastState = this._state;
469
+ this._changeState(ConnectionState.CLOSING);
470
+ await this.connectedTimeoutContext.dispose();
471
+ await this._ctx.dispose();
472
+ (0, import_log.log)("closing...", {
473
+ peerId: this.ownId
474
+ }, {
475
+ F: __dxlog_file,
476
+ L: 302,
477
+ S: this,
478
+ C: (f, a) => f(...a)
479
+ });
480
+ if (lastState === ConnectionState.CONNECTED) {
481
+ try {
482
+ await this._protocol.close();
483
+ } catch (err2) {
484
+ import_log.log.catch(err2, void 0, {
485
+ F: __dxlog_file,
486
+ L: 309,
487
+ S: this,
488
+ C: (f, a) => f(...a)
489
+ });
490
+ }
491
+ try {
492
+ await this._transport?.destroy();
493
+ } catch (err2) {
494
+ import_log.log.catch(err2, void 0, {
495
+ F: __dxlog_file,
496
+ L: 316,
497
+ S: this,
498
+ C: (f, a) => f(...a)
499
+ });
500
+ }
501
+ } else {
502
+ import_log.log.info(`graceful close requested when we were in ${lastState} state? aborting`, void 0, {
503
+ F: __dxlog_file,
504
+ L: 319,
505
+ S: this,
506
+ C: (f, a) => f(...a)
507
+ });
508
+ try {
509
+ await this._protocol.abort();
510
+ } catch (err2) {
511
+ import_log.log.catch(err2, void 0, {
512
+ F: __dxlog_file,
513
+ L: 323,
514
+ S: this,
515
+ C: (f, a) => f(...a)
516
+ });
517
+ }
518
+ try {
519
+ await this._transport?.destroy();
520
+ } catch (err2) {
521
+ import_log.log.catch(err2, void 0, {
522
+ F: __dxlog_file,
523
+ L: 328,
524
+ S: this,
525
+ C: (f, a) => f(...a)
526
+ });
527
+ }
528
+ }
529
+ (0, import_log.log)("closed", {
530
+ peerId: this.ownId
531
+ }, {
532
+ F: __dxlog_file,
533
+ L: 332,
534
+ S: this,
535
+ C: (f, a) => f(...a)
536
+ });
537
+ this._changeState(ConnectionState.CLOSED);
538
+ this._callbacks?.onClosed?.(err);
539
+ }
540
+ _sendSignal(signal) {
541
+ this._outgoingSignalBuffer.push(signal);
542
+ this._signalSendTask.schedule();
543
+ }
544
+ async _flushSignalBuffer() {
545
+ if (this._outgoingSignalBuffer.length === 0) {
546
+ return;
547
+ }
548
+ try {
549
+ if (process.env.NODE_ENV !== "test") {
550
+ await (0, import_context.cancelWithContext)(this._ctx, (0, import_async.sleep)(this._signallingDelay));
551
+ this._signallingDelay = Math.min(this._signallingDelay * 2, MAX_SIGNALLING_DELAY);
552
+ }
553
+ const signals = [
554
+ ...this._outgoingSignalBuffer
555
+ ];
556
+ this._outgoingSignalBuffer.length = 0;
557
+ await this._signalMessaging.signal({
558
+ author: this.ownId,
559
+ recipient: this.remoteId,
560
+ sessionId: this.sessionId,
561
+ topic: this.topic,
562
+ data: {
563
+ signalBatch: {
564
+ signals
565
+ }
566
+ }
567
+ });
568
+ } catch (err) {
569
+ if (err instanceof import_protocols.CancelledError || err instanceof Error && err.message?.includes("CANCELLED")) {
570
+ return;
571
+ }
572
+ import_log.log.info("signal message failed to deliver", {
573
+ err
574
+ }, {
575
+ F: __dxlog_file,
576
+ L: 370,
577
+ S: this,
578
+ C: (f, a) => f(...a)
579
+ });
580
+ await this.close(new import_protocols.ConnectivityError("signal message failed to deliver", err));
581
+ }
582
+ }
583
+ /**
584
+ * Receive a signal from the remote peer.
585
+ */
586
+ async signal(msg) {
587
+ (0, import_invariant.invariant)(msg.sessionId, void 0, {
588
+ F: __dxlog_file,
589
+ L: 379,
590
+ S: this,
591
+ A: [
592
+ "msg.sessionId",
593
+ ""
594
+ ]
595
+ });
596
+ if (!msg.sessionId.equals(this.sessionId)) {
597
+ (0, import_log.log)("dropping signal for incorrect session id", void 0, {
598
+ F: __dxlog_file,
599
+ L: 381,
600
+ S: this,
601
+ C: (f, a) => f(...a)
602
+ });
603
+ return;
604
+ }
605
+ (0, import_invariant.invariant)(msg.data.signal || msg.data.signalBatch, void 0, {
606
+ F: __dxlog_file,
607
+ L: 384,
608
+ S: this,
609
+ A: [
610
+ "msg.data.signal || msg.data.signalBatch",
611
+ ""
612
+ ]
613
+ });
614
+ (0, import_invariant.invariant)(msg.author?.equals(this.remoteId), void 0, {
615
+ F: __dxlog_file,
616
+ L: 385,
617
+ S: this,
618
+ A: [
619
+ "msg.author?.equals(this.remoteId)",
620
+ ""
621
+ ]
622
+ });
623
+ (0, import_invariant.invariant)(msg.recipient?.equals(this.ownId), void 0, {
624
+ F: __dxlog_file,
625
+ L: 386,
626
+ S: this,
627
+ A: [
628
+ "msg.recipient?.equals(this.ownId)",
629
+ ""
630
+ ]
631
+ });
632
+ const signals = msg.data.signalBatch ? msg.data.signalBatch.signals ?? [] : [
633
+ msg.data.signal
634
+ ];
635
+ for (const signal of signals) {
636
+ if (!signal) {
637
+ continue;
638
+ }
639
+ if ([
640
+ ConnectionState.CREATED,
641
+ ConnectionState.INITIAL
642
+ ].includes(this.state)) {
643
+ (0, import_log.log)("buffered signal", {
644
+ peerId: this.ownId,
645
+ remoteId: this.remoteId,
646
+ msg: msg.data
647
+ }, {
648
+ F: __dxlog_file,
649
+ L: 395,
650
+ S: this,
651
+ C: (f, a) => f(...a)
652
+ });
653
+ this._incomingSignalBuffer.push(signal);
654
+ } else {
655
+ (0, import_invariant.invariant)(this._transport, "Connection not ready to accept signals.", {
656
+ F: __dxlog_file,
657
+ L: 398,
658
+ S: this,
659
+ A: [
660
+ "this._transport",
661
+ "'Connection not ready to accept signals.'"
662
+ ]
663
+ });
664
+ (0, import_log.log)("received signal", {
665
+ peerId: this.ownId,
666
+ remoteId: this.remoteId,
667
+ msg: msg.data
668
+ }, {
669
+ F: __dxlog_file,
670
+ L: 399,
671
+ S: this,
672
+ C: (f, a) => f(...a)
673
+ });
674
+ await this._transport.signal(signal);
675
+ }
676
+ }
677
+ }
678
+ initiate() {
679
+ this._changeState(ConnectionState.INITIAL);
680
+ }
681
+ _changeState(state) {
682
+ (0, import_log.log)("stateChanged", {
683
+ from: this._state,
684
+ to: state,
685
+ peerId: this.ownId
686
+ }, {
687
+ F: __dxlog_file,
688
+ L: 410,
689
+ S: this,
690
+ C: (f, a) => f(...a)
691
+ });
692
+ (0, import_invariant.invariant)(state !== this._state, "Already in this state.", {
693
+ F: __dxlog_file,
694
+ L: 411,
695
+ S: this,
696
+ A: [
697
+ "state !== this._state",
698
+ "'Already in this state.'"
699
+ ]
700
+ });
701
+ this._state = state;
702
+ this.stateChanged.emit(state);
703
+ }
704
+ };
705
+ _ts_decorate([
706
+ import_async.synchronized
707
+ ], Connection.prototype, "abort", null);
708
+ _ts_decorate([
709
+ import_async.synchronized
710
+ ], Connection.prototype, "close", null);
711
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/signal/swarm-messenger.ts";
712
+ var SwarmMessage = import_protocols2.schema.getCodecForType("dxos.mesh.swarm.SwarmMessage");
713
+ var SwarmMessenger = class {
714
+ constructor({ sendMessage, onSignal, onOffer, topic }) {
715
+ this._ctx = new import_context2.Context();
716
+ this._offerRecords = new import_util.ComplexMap((key) => key.toHex());
717
+ this._sendMessage = sendMessage;
718
+ this._onSignal = onSignal;
719
+ this._onOffer = onOffer;
720
+ this._topic = topic;
721
+ }
722
+ async receiveMessage({ author, recipient, payload }) {
723
+ if (payload.type_url !== "dxos.mesh.swarm.SwarmMessage") {
724
+ return;
725
+ }
726
+ const message = SwarmMessage.decode(payload.value);
727
+ if (!this._topic.equals(message.topic)) {
728
+ return;
729
+ }
730
+ (0, import_log2.log)("received", {
731
+ from: author,
732
+ to: recipient,
733
+ msg: message
734
+ }, {
735
+ F: __dxlog_file2,
736
+ L: 69,
737
+ S: this,
738
+ C: (f, a) => f(...a)
739
+ });
740
+ if (message.data?.offer) {
741
+ await this._handleOffer({
742
+ author,
743
+ recipient,
744
+ message
745
+ });
746
+ } else if (message.data?.answer) {
747
+ await this._resolveAnswers(message);
748
+ } else if (message.data?.signal) {
749
+ await this._handleSignal({
750
+ author,
751
+ recipient,
752
+ message
753
+ });
754
+ } else if (message.data?.signalBatch) {
755
+ await this._handleSignal({
756
+ author,
757
+ recipient,
758
+ message
759
+ });
760
+ } else {
761
+ import_log2.log.warn("unknown message", {
762
+ message
763
+ }, {
764
+ F: __dxlog_file2,
765
+ L: 80,
766
+ S: this,
767
+ C: (f, a) => f(...a)
768
+ });
769
+ }
770
+ }
771
+ async signal(message) {
772
+ (0, import_invariant2.invariant)(message.data?.signal || message.data?.signalBatch, "Invalid message", {
773
+ F: __dxlog_file2,
774
+ L: 85,
775
+ S: this,
776
+ A: [
777
+ "message.data?.signal || message.data?.signalBatch",
778
+ "'Invalid message'"
779
+ ]
780
+ });
781
+ await this._sendReliableMessage({
782
+ author: message.author,
783
+ recipient: message.recipient,
784
+ message
785
+ });
786
+ }
787
+ async offer(message) {
788
+ const networkMessage = {
789
+ ...message,
790
+ messageId: import_keys2.PublicKey.random()
791
+ };
792
+ return new Promise((resolve, reject) => {
793
+ this._offerRecords.set(networkMessage.messageId, {
794
+ resolve
795
+ });
796
+ this._sendReliableMessage({
797
+ author: message.author,
798
+ recipient: message.recipient,
799
+ message: networkMessage
800
+ }).catch((err) => reject(err));
801
+ });
802
+ }
803
+ async _sendReliableMessage({ author, recipient, message }) {
804
+ const networkMessage = {
805
+ ...message,
806
+ // Setting unique message_id if it not specified yet.
807
+ messageId: message.messageId ?? import_keys2.PublicKey.random()
808
+ };
809
+ (0, import_log2.log)("sending", {
810
+ from: author,
811
+ to: recipient,
812
+ msg: networkMessage
813
+ }, {
814
+ F: __dxlog_file2,
815
+ L: 123,
816
+ S: this,
817
+ C: (f, a) => f(...a)
818
+ });
819
+ await this._sendMessage({
820
+ author,
821
+ recipient,
822
+ payload: {
823
+ type_url: "dxos.mesh.swarm.SwarmMessage",
824
+ value: SwarmMessage.encode(networkMessage)
825
+ }
826
+ });
827
+ }
828
+ async _resolveAnswers(message) {
829
+ (0, import_invariant2.invariant)(message.data?.answer?.offerMessageId, "No offerMessageId", {
830
+ F: __dxlog_file2,
831
+ L: 135,
832
+ S: this,
833
+ A: [
834
+ "message.data?.answer?.offerMessageId",
835
+ "'No offerMessageId'"
836
+ ]
837
+ });
838
+ const offerRecord = this._offerRecords.get(message.data.answer.offerMessageId);
839
+ if (offerRecord) {
840
+ this._offerRecords.delete(message.data.answer.offerMessageId);
841
+ (0, import_invariant2.invariant)(message.data?.answer, "No answer", {
842
+ F: __dxlog_file2,
843
+ L: 139,
844
+ S: this,
845
+ A: [
846
+ "message.data?.answer",
847
+ "'No answer'"
848
+ ]
849
+ });
850
+ (0, import_log2.log)("resolving", {
851
+ answer: message.data.answer
852
+ }, {
853
+ F: __dxlog_file2,
854
+ L: 140,
855
+ S: this,
856
+ C: (f, a) => f(...a)
857
+ });
858
+ offerRecord.resolve(message.data.answer);
859
+ }
860
+ }
861
+ async _handleOffer({ author, recipient, message }) {
862
+ (0, import_invariant2.invariant)(message.data.offer, "No offer", {
863
+ F: __dxlog_file2,
864
+ L: 154,
865
+ S: this,
866
+ A: [
867
+ "message.data.offer",
868
+ "'No offer'"
869
+ ]
870
+ });
871
+ const offerMessage = {
872
+ author,
873
+ recipient,
874
+ ...message,
875
+ data: {
876
+ offer: message.data.offer
877
+ }
878
+ };
879
+ const answer = await this._onOffer(offerMessage);
880
+ answer.offerMessageId = message.messageId;
881
+ try {
882
+ await this._sendReliableMessage({
883
+ author: recipient,
884
+ recipient: author,
885
+ message: {
886
+ topic: message.topic,
887
+ sessionId: message.sessionId,
888
+ data: {
889
+ answer
890
+ }
891
+ }
892
+ });
893
+ } catch (err) {
894
+ if (err instanceof import_protocols2.TimeoutError) {
895
+ import_log2.log.info("timeout sending answer to offer", {
896
+ err
897
+ }, {
898
+ F: __dxlog_file2,
899
+ L: 175,
900
+ S: this,
901
+ C: (f, a) => f(...a)
902
+ });
903
+ } else {
904
+ import_log2.log.info("error sending answer to offer", {
905
+ err
906
+ }, {
907
+ F: __dxlog_file2,
908
+ L: 177,
909
+ S: this,
910
+ C: (f, a) => f(...a)
911
+ });
912
+ }
913
+ }
914
+ }
915
+ async _handleSignal({ author, recipient, message }) {
916
+ (0, import_invariant2.invariant)(message.messageId, void 0, {
917
+ F: __dxlog_file2,
918
+ L: 191,
919
+ S: this,
920
+ A: [
921
+ "message.messageId",
922
+ ""
923
+ ]
924
+ });
925
+ (0, import_invariant2.invariant)(message.data.signal || message.data.signalBatch, "Invalid message", {
926
+ F: __dxlog_file2,
927
+ L: 192,
928
+ S: this,
929
+ A: [
930
+ "message.data.signal || message.data.signalBatch",
931
+ "'Invalid message'"
932
+ ]
933
+ });
934
+ const signalMessage = {
935
+ author,
936
+ recipient,
937
+ ...message,
938
+ data: {
939
+ signal: message.data.signal,
940
+ signalBatch: message.data.signalBatch
941
+ }
942
+ };
943
+ await this._onSignal(signalMessage);
944
+ }
945
+ };
946
+ function _ts_decorate2(decorators, target, key, desc) {
947
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
948
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
949
+ r = Reflect.decorate(decorators, target, key, desc);
950
+ else
951
+ for (var i = decorators.length - 1; i >= 0; i--)
952
+ if (d = decorators[i])
953
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
954
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
955
+ }
956
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/peer.ts";
957
+ var ConnectionDisplacedError = class extends import_protocols4.SystemError {
958
+ constructor() {
959
+ super("Connection displaced by remote initiator.");
960
+ }
961
+ };
962
+ var CONNECTION_COUNTS_STABLE_AFTER = 5e3;
963
+ var Peer = class {
964
+ // TODO(burdon): Convert to map?
965
+ constructor(id, topic, localPeerId, _signalMessaging, _protocolProvider, _transportFactory, _connectionLimiter, _callbacks) {
966
+ this.id = id;
967
+ this.topic = topic;
968
+ this.localPeerId = localPeerId;
969
+ this._signalMessaging = _signalMessaging;
970
+ this._protocolProvider = _protocolProvider;
971
+ this._transportFactory = _transportFactory;
972
+ this._connectionLimiter = _connectionLimiter;
973
+ this._callbacks = _callbacks;
974
+ this._availableAfter = 0;
975
+ this.availableToConnect = true;
976
+ this._ctx = new import_context4.Context();
977
+ this.advertizing = false;
978
+ this.initiating = false;
979
+ this.connectionDisplaced = new import_async3.Event();
980
+ }
981
+ /**
982
+ * Respond to remote offer.
983
+ */
984
+ async onOffer(message) {
985
+ const remoteId = message.author;
986
+ if (this.connection && ![
987
+ ConnectionState.CREATED,
988
+ ConnectionState.INITIAL,
989
+ ConnectionState.CONNECTING
990
+ ].includes(this.connection.state)) {
991
+ import_log4.log.info(`received offer when connection already in ${this.connection.state} state`, void 0, {
992
+ F: __dxlog_file3,
993
+ L: 115,
994
+ S: this,
995
+ C: (f, a) => f(...a)
996
+ });
997
+ return {
998
+ accept: false
999
+ };
1000
+ }
1001
+ if (this.connection || this.initiating) {
1002
+ if (remoteId.toHex() < this.localPeerId.toHex()) {
1003
+ (0, import_log4.log)("close local connection", {
1004
+ localPeerId: this.id,
1005
+ topic: this.topic,
1006
+ remotePeerId: this.localPeerId,
1007
+ sessionId: this.connection?.sessionId
1008
+ }, {
1009
+ F: __dxlog_file3,
1010
+ L: 124,
1011
+ S: this,
1012
+ C: (f, a) => f(...a)
1013
+ });
1014
+ if (this.connection) {
1015
+ await this.closeConnection(new ConnectionDisplacedError());
1016
+ }
1017
+ } else {
1018
+ return {
1019
+ accept: false
1020
+ };
1021
+ }
1022
+ }
1023
+ if (await this._callbacks.onOffer(remoteId)) {
1024
+ if (!this.connection) {
1025
+ (0, import_invariant4.invariant)(message.sessionId, void 0, {
1026
+ F: __dxlog_file3,
1027
+ L: 144,
1028
+ S: this,
1029
+ A: [
1030
+ "message.sessionId",
1031
+ ""
1032
+ ]
1033
+ });
1034
+ const connection = this._createConnection(false, message.sessionId);
1035
+ try {
1036
+ await this._connectionLimiter.connecting(message.sessionId);
1037
+ connection.initiate();
1038
+ await connection.openConnection();
1039
+ } catch (err) {
1040
+ if (!(err instanceof import_protocols4.CancelledError)) {
1041
+ import_log4.log.info("connection error", {
1042
+ topic: this.topic,
1043
+ peerId: this.localPeerId,
1044
+ remoteId: this.id,
1045
+ err
1046
+ }, {
1047
+ F: __dxlog_file3,
1048
+ L: 154,
1049
+ S: this,
1050
+ C: (f, a) => f(...a)
1051
+ });
1052
+ }
1053
+ await this.closeConnection(err);
1054
+ }
1055
+ return {
1056
+ accept: true
1057
+ };
1058
+ }
1059
+ }
1060
+ return {
1061
+ accept: false
1062
+ };
1063
+ }
1064
+ /**
1065
+ * Initiate a connection to the remote peer.
1066
+ */
1067
+ async initiateConnection() {
1068
+ (0, import_invariant4.invariant)(!this.initiating, "Initiation in progress.", {
1069
+ F: __dxlog_file3,
1070
+ L: 171,
1071
+ S: this,
1072
+ A: [
1073
+ "!this.initiating",
1074
+ "'Initiation in progress.'"
1075
+ ]
1076
+ });
1077
+ (0, import_invariant4.invariant)(!this.connection, "Already connected.", {
1078
+ F: __dxlog_file3,
1079
+ L: 172,
1080
+ S: this,
1081
+ A: [
1082
+ "!this.connection",
1083
+ "'Already connected.'"
1084
+ ]
1085
+ });
1086
+ const sessionId = import_keys4.PublicKey.random();
1087
+ (0, import_log4.log)("initiating...", {
1088
+ id: this.id,
1089
+ topic: this.topic,
1090
+ peerId: this.id,
1091
+ sessionId
1092
+ }, {
1093
+ F: __dxlog_file3,
1094
+ L: 174,
1095
+ S: this,
1096
+ C: (f, a) => f(...a)
1097
+ });
1098
+ const connection = this._createConnection(true, sessionId);
1099
+ this.initiating = true;
1100
+ let answer;
1101
+ try {
1102
+ await this._connectionLimiter.connecting(sessionId);
1103
+ connection.initiate();
1104
+ answer = await this._signalMessaging.offer({
1105
+ author: this.localPeerId,
1106
+ recipient: this.id,
1107
+ sessionId,
1108
+ topic: this.topic,
1109
+ data: {
1110
+ offer: {}
1111
+ }
1112
+ });
1113
+ (0, import_log4.log)("received", {
1114
+ answer,
1115
+ topic: this.topic,
1116
+ ownId: this.localPeerId,
1117
+ remoteId: this.id
1118
+ }, {
1119
+ F: __dxlog_file3,
1120
+ L: 191,
1121
+ S: this,
1122
+ C: (f, a) => f(...a)
1123
+ });
1124
+ if (connection.state !== ConnectionState.INITIAL) {
1125
+ (0, import_log4.log)("ignoring response", void 0, {
1126
+ F: __dxlog_file3,
1127
+ L: 193,
1128
+ S: this,
1129
+ C: (f, a) => f(...a)
1130
+ });
1131
+ return;
1132
+ }
1133
+ } catch (err) {
1134
+ (0, import_log4.log)("initiation error: send offer", {
1135
+ err,
1136
+ topic: this.topic,
1137
+ peerId: this.localPeerId,
1138
+ remoteId: this.id
1139
+ }, {
1140
+ F: __dxlog_file3,
1141
+ L: 197,
1142
+ S: this,
1143
+ C: (f, a) => f(...a)
1144
+ });
1145
+ await connection.abort(err);
1146
+ throw err;
1147
+ } finally {
1148
+ this.initiating = false;
1149
+ }
1150
+ try {
1151
+ if (!answer.accept) {
1152
+ this._callbacks.onRejected();
1153
+ return;
1154
+ }
1155
+ } catch (err) {
1156
+ (0, import_log4.log)("initiation error: accept answer", {
1157
+ err,
1158
+ topic: this.topic,
1159
+ peerId: this.localPeerId,
1160
+ remoteId: this.id
1161
+ }, {
1162
+ F: __dxlog_file3,
1163
+ L: 210,
1164
+ S: this,
1165
+ C: (f, a) => f(...a)
1166
+ });
1167
+ await connection.abort(err);
1168
+ throw err;
1169
+ } finally {
1170
+ this.initiating = false;
1171
+ }
1172
+ try {
1173
+ (0, import_log4.log)("opening connection as initiator", void 0, {
1174
+ F: __dxlog_file3,
1175
+ L: 223,
1176
+ S: this,
1177
+ C: (f, a) => f(...a)
1178
+ });
1179
+ await connection.openConnection();
1180
+ this._callbacks.onAccepted();
1181
+ } catch (err) {
1182
+ (0, import_log4.log)("initiation error: open connection", {
1183
+ err,
1184
+ topic: this.topic,
1185
+ peerId: this.localPeerId,
1186
+ remoteId: this.id
1187
+ }, {
1188
+ F: __dxlog_file3,
1189
+ L: 227,
1190
+ S: this,
1191
+ C: (f, a) => f(...a)
1192
+ });
1193
+ import_log4.log.warn("closing connection due to unhandled error on openConnection", {
1194
+ err
1195
+ }, {
1196
+ F: __dxlog_file3,
1197
+ L: 234,
1198
+ S: this,
1199
+ C: (f, a) => f(...a)
1200
+ });
1201
+ await this.closeConnection(err);
1202
+ throw err;
1203
+ } finally {
1204
+ this.initiating = false;
1205
+ }
1206
+ }
1207
+ /**
1208
+ * Create new connection.
1209
+ * Either we're initiating a connection or creating one in response to an offer from the other peer.
1210
+ */
1211
+ _createConnection(initiator, sessionId) {
1212
+ (0, import_log4.log)("creating connection", {
1213
+ topic: this.topic,
1214
+ peerId: this.localPeerId,
1215
+ remoteId: this.id,
1216
+ initiator,
1217
+ sessionId
1218
+ }, {
1219
+ F: __dxlog_file3,
1220
+ L: 248,
1221
+ S: this,
1222
+ C: (f, a) => f(...a)
1223
+ });
1224
+ (0, import_invariant4.invariant)(!this.connection, "Already connected.", {
1225
+ F: __dxlog_file3,
1226
+ L: 255,
1227
+ S: this,
1228
+ A: [
1229
+ "!this.connection",
1230
+ "'Already connected.'"
1231
+ ]
1232
+ });
1233
+ const connection = new Connection(
1234
+ this.topic,
1235
+ this.localPeerId,
1236
+ this.id,
1237
+ sessionId,
1238
+ initiator,
1239
+ this._signalMessaging,
1240
+ // TODO(dmaretskyi): Init only when connection is established.
1241
+ this._protocolProvider({
1242
+ initiator,
1243
+ localPeerId: this.localPeerId,
1244
+ remotePeerId: this.id,
1245
+ topic: this.topic
1246
+ }),
1247
+ this._transportFactory,
1248
+ {
1249
+ onConnected: () => {
1250
+ this.availableToConnect = true;
1251
+ this._lastConnectionTime = Date.now();
1252
+ this._callbacks.onConnected();
1253
+ this._connectionLimiter.doneConnecting(sessionId);
1254
+ import_log4.log.trace("dxos.mesh.connection.connected", {
1255
+ topic: this.topic,
1256
+ localPeerId: this.localPeerId,
1257
+ remotePeerId: this.id,
1258
+ sessionId,
1259
+ initiator
1260
+ }, {
1261
+ F: __dxlog_file3,
1262
+ L: 274,
1263
+ S: this,
1264
+ C: (f, a) => f(...a)
1265
+ });
1266
+ },
1267
+ onClosed: (err) => {
1268
+ (0, import_log4.log)("connection closed", {
1269
+ topic: this.topic,
1270
+ peerId: this.localPeerId,
1271
+ remoteId: this.id,
1272
+ initiator
1273
+ }, {
1274
+ F: __dxlog_file3,
1275
+ L: 283,
1276
+ S: this,
1277
+ C: (f, a) => f(...a)
1278
+ });
1279
+ this._connectionLimiter.doneConnecting(sessionId);
1280
+ (0, import_invariant4.invariant)(this.connection === connection, "Connection mismatch (race condition).", {
1281
+ F: __dxlog_file3,
1282
+ L: 288,
1283
+ S: this,
1284
+ A: [
1285
+ "this.connection === connection",
1286
+ "'Connection mismatch (race condition).'"
1287
+ ]
1288
+ });
1289
+ import_log4.log.trace("dxos.mesh.connection.closed", {
1290
+ topic: this.topic,
1291
+ localPeerId: this.localPeerId,
1292
+ remotePeerId: this.id,
1293
+ sessionId,
1294
+ initiator
1295
+ }, {
1296
+ F: __dxlog_file3,
1297
+ L: 290,
1298
+ S: this,
1299
+ C: (f, a) => f(...a)
1300
+ });
1301
+ if (err instanceof ConnectionDisplacedError) {
1302
+ this.connectionDisplaced.emit(this.connection);
1303
+ } else {
1304
+ if (this._lastConnectionTime && this._lastConnectionTime + CONNECTION_COUNTS_STABLE_AFTER < Date.now()) {
1305
+ this._availableAfter = 0;
1306
+ } else {
1307
+ this.availableToConnect = false;
1308
+ this._availableAfter = increaseInterval(this._availableAfter);
1309
+ }
1310
+ this._callbacks.onDisconnected();
1311
+ (0, import_async3.scheduleTask)(this._connectionCtx, () => {
1312
+ this.availableToConnect = true;
1313
+ this._callbacks.onPeerAvailable();
1314
+ }, this._availableAfter);
1315
+ }
1316
+ this.connection = void 0;
1317
+ }
1318
+ }
1319
+ );
1320
+ this._callbacks.onInitiated(connection);
1321
+ void this._connectionCtx?.dispose();
1322
+ this._connectionCtx = this._ctx.derive();
1323
+ connection.errors.handle((err) => {
1324
+ import_log4.log.info("connection error, closing", {
1325
+ topic: this.topic,
1326
+ peerId: this.localPeerId,
1327
+ remoteId: this.id,
1328
+ initiator,
1329
+ err
1330
+ }, {
1331
+ F: __dxlog_file3,
1332
+ L: 330,
1333
+ S: this,
1334
+ C: (f, a) => f(...a)
1335
+ });
1336
+ import_log4.log.trace("dxos.mesh.connection.error", {
1337
+ topic: this.topic,
1338
+ localPeerId: this.localPeerId,
1339
+ remotePeerId: this.id,
1340
+ sessionId,
1341
+ initiator,
1342
+ err
1343
+ }, {
1344
+ F: __dxlog_file3,
1345
+ L: 337,
1346
+ S: this,
1347
+ C: (f, a) => f(...a)
1348
+ });
1349
+ void this.closeConnection(err);
1350
+ });
1351
+ this.connection = connection;
1352
+ return connection;
1353
+ }
1354
+ async closeConnection(err) {
1355
+ if (!this.connection) {
1356
+ return;
1357
+ }
1358
+ const connection = this.connection;
1359
+ (0, import_log4.log)("closing...", {
1360
+ peerId: this.id,
1361
+ sessionId: connection.sessionId
1362
+ }, {
1363
+ F: __dxlog_file3,
1364
+ L: 362,
1365
+ S: this,
1366
+ C: (f, a) => f(...a)
1367
+ });
1368
+ await connection.close(err);
1369
+ (0, import_log4.log)("closed", {
1370
+ peerId: this.id,
1371
+ sessionId: connection.sessionId
1372
+ }, {
1373
+ F: __dxlog_file3,
1374
+ L: 368,
1375
+ S: this,
1376
+ C: (f, a) => f(...a)
1377
+ });
1378
+ }
1379
+ async onSignal(message) {
1380
+ if (!this.connection) {
1381
+ (0, import_log4.log)("dropping signal message for non-existent connection", {
1382
+ message
1383
+ }, {
1384
+ F: __dxlog_file3,
1385
+ L: 373,
1386
+ S: this,
1387
+ C: (f, a) => f(...a)
1388
+ });
1389
+ return;
1390
+ }
1391
+ await this.connection.signal(message);
1392
+ }
1393
+ async destroy(reason) {
1394
+ await this._ctx.dispose();
1395
+ (0, import_log4.log)("Destroying peer", {
1396
+ peerId: this.id,
1397
+ topic: this.topic
1398
+ }, {
1399
+ F: __dxlog_file3,
1400
+ L: 383,
1401
+ S: this,
1402
+ C: (f, a) => f(...a)
1403
+ });
1404
+ await this?.connection?.close(reason);
1405
+ }
1406
+ };
1407
+ _ts_decorate2([
1408
+ import_async3.synchronized
1409
+ ], Peer.prototype, "destroy", null);
1410
+ var increaseInterval = (interval) => {
1411
+ if (interval === 0) {
1412
+ return 50;
1413
+ } else if (interval < 500) {
1414
+ return 500;
1415
+ } else if (interval < 1e3) {
1416
+ return 1e3;
1417
+ } else if (interval < 5e3) {
1418
+ return 5e3;
1419
+ }
1420
+ return 1e4;
1421
+ };
1422
+ function _ts_decorate3(decorators, target, key, desc) {
1423
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1424
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
1425
+ r = Reflect.decorate(decorators, target, key, desc);
1426
+ else
1427
+ for (var i = decorators.length - 1; i >= 0; i--)
1428
+ if (d = decorators[i])
1429
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1430
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1431
+ }
1432
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm.ts";
1433
+ var INITIATION_DELAY = 100;
1434
+ var getClassName = (obj) => Object.getPrototypeOf(obj).constructor.name;
1435
+ var Swarm = class {
1436
+ // TODO(burdon): Swarm => Peer.create/destroy =< Connection.open/close
1437
+ // TODO(burdon): Split up properties.
1438
+ constructor(_topic, _ownPeerId, _topology, _protocolProvider, _messenger, _transportFactory, _label, _connectionLimiter, _initiationDelay = INITIATION_DELAY) {
1439
+ this._topic = _topic;
1440
+ this._ownPeerId = _ownPeerId;
1441
+ this._topology = _topology;
1442
+ this._protocolProvider = _protocolProvider;
1443
+ this._messenger = _messenger;
1444
+ this._transportFactory = _transportFactory;
1445
+ this._label = _label;
1446
+ this._connectionLimiter = _connectionLimiter;
1447
+ this._initiationDelay = _initiationDelay;
1448
+ this._ctx = new import_context3.Context();
1449
+ this._listeningHandle = void 0;
1450
+ this._peers = new import_util2.ComplexMap(import_keys3.PublicKey.hash);
1451
+ this._instanceId = import_keys3.PublicKey.random().toHex();
1452
+ this.connectionAdded = new import_async2.Event();
1453
+ this.disconnected = new import_async2.Event();
1454
+ this.connected = new import_async2.Event();
1455
+ this.errors = new import_debug2.ErrorStream();
1456
+ import_log3.log.trace("dxos.mesh.swarm.constructor", import_protocols3.trace.begin({
1457
+ id: this._instanceId,
1458
+ data: {
1459
+ topic: this._topic.toHex(),
1460
+ peerId: this._ownPeerId.toHex()
1461
+ }
1462
+ }), {
1463
+ F: __dxlog_file4,
1464
+ L: 88,
1465
+ S: this,
1466
+ C: (f, a) => f(...a)
1467
+ });
1468
+ (0, import_log3.log)("creating swarm", {
1469
+ peerId: _ownPeerId
1470
+ }, {
1471
+ F: __dxlog_file4,
1472
+ L: 92,
1473
+ S: this,
1474
+ C: (f, a) => f(...a)
1475
+ });
1476
+ _topology.init(this._getSwarmController());
1477
+ this._swarmMessenger = new SwarmMessenger({
1478
+ sendMessage: async (msg) => await this._messenger.sendMessage(msg),
1479
+ onSignal: async (msg) => await this.onSignal(msg),
1480
+ onOffer: async (msg) => await this.onOffer(msg),
1481
+ topic: this._topic
1482
+ });
1483
+ import_log3.log.trace("dxos.mesh.swarm.constructor", import_protocols3.trace.end({
1484
+ id: this._instanceId
1485
+ }), {
1486
+ F: __dxlog_file4,
1487
+ L: 101,
1488
+ S: this,
1489
+ C: (f, a) => f(...a)
1490
+ });
1491
+ }
1492
+ get connections() {
1493
+ return Array.from(this._peers.values()).map((peer) => peer.connection).filter(import_util2.isNotNullOrUndefined);
1494
+ }
1495
+ get ownPeerId() {
1496
+ return this._ownPeerId;
1497
+ }
1498
+ /**
1499
+ * Custom label assigned to this swarm. Used in devtools to display human-readable names for swarms.
1500
+ */
1501
+ get label() {
1502
+ return this._label;
1503
+ }
1504
+ get topic() {
1505
+ return this._topic;
1506
+ }
1507
+ async open() {
1508
+ (0, import_invariant3.invariant)(!this._listeningHandle, void 0, {
1509
+ F: __dxlog_file4,
1510
+ L: 128,
1511
+ S: this,
1512
+ A: [
1513
+ "!this._listeningHandle",
1514
+ ""
1515
+ ]
1516
+ });
1517
+ this._listeningHandle = await this._messenger.listen({
1518
+ peerId: this._ownPeerId,
1519
+ payloadType: "dxos.mesh.swarm.SwarmMessage",
1520
+ onMessage: async (message) => {
1521
+ await this._swarmMessenger.receiveMessage(message).catch((err) => import_log3.log.info("Error while receiving message", {
1522
+ err
1523
+ }, {
1524
+ F: __dxlog_file4,
1525
+ L: 136,
1526
+ S: this,
1527
+ C: (f, a) => f(...a)
1528
+ }));
1529
+ }
1530
+ });
1531
+ }
1532
+ async destroy() {
1533
+ (0, import_log3.log)("destroying...", void 0, {
1534
+ F: __dxlog_file4,
1535
+ L: 142,
1536
+ S: this,
1537
+ C: (f, a) => f(...a)
1538
+ });
1539
+ await this._listeningHandle?.unsubscribe();
1540
+ this._listeningHandle = void 0;
1541
+ await this._ctx.dispose();
1542
+ await this._topology.destroy();
1543
+ await Promise.all(Array.from(this._peers.keys()).map((key) => this._destroyPeer(key, "swarm destroyed")));
1544
+ (0, import_log3.log)("destroyed", void 0, {
1545
+ F: __dxlog_file4,
1546
+ L: 149,
1547
+ S: this,
1548
+ C: (f, a) => f(...a)
1549
+ });
1550
+ }
1551
+ async setTopology(topology) {
1552
+ (0, import_invariant3.invariant)(!this._ctx.disposed, "Swarm is offline", {
1553
+ F: __dxlog_file4,
1554
+ L: 153,
1555
+ S: this,
1556
+ A: [
1557
+ "!this._ctx.disposed",
1558
+ "'Swarm is offline'"
1559
+ ]
1560
+ });
1561
+ if (topology === this._topology) {
1562
+ return;
1563
+ }
1564
+ (0, import_log3.log)("setting topology", {
1565
+ previous: getClassName(this._topology),
1566
+ topology: getClassName(topology)
1567
+ }, {
1568
+ F: __dxlog_file4,
1569
+ L: 157,
1570
+ S: this,
1571
+ C: (f, a) => f(...a)
1572
+ });
1573
+ await this._topology.destroy();
1574
+ this._topology = topology;
1575
+ this._topology.init(this._getSwarmController());
1576
+ this._topology.update();
1577
+ }
1578
+ onSwarmEvent(swarmEvent) {
1579
+ (0, import_log3.log)("swarm event", {
1580
+ swarmEvent
1581
+ }, {
1582
+ F: __dxlog_file4,
1583
+ L: 170,
1584
+ S: this,
1585
+ C: (f, a) => f(...a)
1586
+ });
1587
+ if (this._ctx.disposed) {
1588
+ (0, import_log3.log)("swarm event ignored for disposed swarm", void 0, {
1589
+ F: __dxlog_file4,
1590
+ L: 173,
1591
+ S: this,
1592
+ C: (f, a) => f(...a)
1593
+ });
1594
+ return;
1595
+ }
1596
+ if (swarmEvent.peerAvailable) {
1597
+ const peerId = import_keys3.PublicKey.from(swarmEvent.peerAvailable.peer);
1598
+ (0, import_log3.log)("new peer", {
1599
+ peerId
1600
+ }, {
1601
+ F: __dxlog_file4,
1602
+ L: 179,
1603
+ S: this,
1604
+ C: (f, a) => f(...a)
1605
+ });
1606
+ if (!peerId.equals(this._ownPeerId)) {
1607
+ const peer = this._getOrCreatePeer(peerId);
1608
+ peer.advertizing = true;
1609
+ }
1610
+ } else if (swarmEvent.peerLeft) {
1611
+ const peer = this._peers.get(import_keys3.PublicKey.from(swarmEvent.peerLeft.peer));
1612
+ if (peer) {
1613
+ peer.advertizing = false;
1614
+ if (peer.connection?.state !== ConnectionState.CONNECTED) {
1615
+ void this._destroyPeer(peer.id, "peer left").catch((err) => import_log3.log.catch(err, void 0, {
1616
+ F: __dxlog_file4,
1617
+ L: 190,
1618
+ S: this,
1619
+ C: (f, a) => f(...a)
1620
+ }));
1621
+ }
1622
+ } else {
1623
+ (0, import_log3.log)("received peerLeft but no peer found", {
1624
+ peer: swarmEvent.peerLeft.peer
1625
+ }, {
1626
+ F: __dxlog_file4,
1627
+ L: 193,
1628
+ S: this,
1629
+ C: (f, a) => f(...a)
1630
+ });
1631
+ }
1632
+ }
1633
+ this._topology.update();
1634
+ }
1635
+ async onOffer(message) {
1636
+ (0, import_log3.log)("offer", {
1637
+ message
1638
+ }, {
1639
+ F: __dxlog_file4,
1640
+ L: 202,
1641
+ S: this,
1642
+ C: (f, a) => f(...a)
1643
+ });
1644
+ if (this._ctx.disposed) {
1645
+ (0, import_log3.log)("ignored for disposed swarm", void 0, {
1646
+ F: __dxlog_file4,
1647
+ L: 204,
1648
+ S: this,
1649
+ C: (f, a) => f(...a)
1650
+ });
1651
+ return {
1652
+ accept: false
1653
+ };
1654
+ }
1655
+ (0, import_invariant3.invariant)(message.author, void 0, {
1656
+ F: __dxlog_file4,
1657
+ L: 209,
1658
+ S: this,
1659
+ A: [
1660
+ "message.author",
1661
+ ""
1662
+ ]
1663
+ });
1664
+ if (!message.recipient?.equals(this._ownPeerId)) {
1665
+ (0, import_log3.log)("rejecting offer with incorrect peerId", {
1666
+ message
1667
+ }, {
1668
+ F: __dxlog_file4,
1669
+ L: 211,
1670
+ S: this,
1671
+ C: (f, a) => f(...a)
1672
+ });
1673
+ return {
1674
+ accept: false
1675
+ };
1676
+ }
1677
+ if (!message.topic?.equals(this._topic)) {
1678
+ (0, import_log3.log)("rejecting offer with incorrect topic", {
1679
+ message
1680
+ }, {
1681
+ F: __dxlog_file4,
1682
+ L: 215,
1683
+ S: this,
1684
+ C: (f, a) => f(...a)
1685
+ });
1686
+ return {
1687
+ accept: false
1688
+ };
1689
+ }
1690
+ const peer = this._getOrCreatePeer(message.author);
1691
+ const answer = await peer.onOffer(message);
1692
+ this._topology.update();
1693
+ return answer;
1694
+ }
1695
+ async onSignal(message) {
1696
+ (0, import_log3.log)("signal", {
1697
+ message
1698
+ }, {
1699
+ F: __dxlog_file4,
1700
+ L: 226,
1701
+ S: this,
1702
+ C: (f, a) => f(...a)
1703
+ });
1704
+ if (this._ctx.disposed) {
1705
+ import_log3.log.info("ignored for offline swarm", void 0, {
1706
+ F: __dxlog_file4,
1707
+ L: 228,
1708
+ S: this,
1709
+ C: (f, a) => f(...a)
1710
+ });
1711
+ return;
1712
+ }
1713
+ (0, import_invariant3.invariant)(message.recipient?.equals(this._ownPeerId), `Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`, {
1714
+ F: __dxlog_file4,
1715
+ L: 231,
1716
+ S: this,
1717
+ A: [
1718
+ "message.recipient?.equals(this._ownPeerId)",
1719
+ "`Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`"
1720
+ ]
1721
+ });
1722
+ (0, import_invariant3.invariant)(message.topic?.equals(this._topic), void 0, {
1723
+ F: __dxlog_file4,
1724
+ L: 235,
1725
+ S: this,
1726
+ A: [
1727
+ "message.topic?.equals(this._topic)",
1728
+ ""
1729
+ ]
1730
+ });
1731
+ (0, import_invariant3.invariant)(message.author, void 0, {
1732
+ F: __dxlog_file4,
1733
+ L: 236,
1734
+ S: this,
1735
+ A: [
1736
+ "message.author",
1737
+ ""
1738
+ ]
1739
+ });
1740
+ const peer = this._getOrCreatePeer(message.author);
1741
+ await peer.onSignal(message);
1742
+ }
1743
+ // For debug purposes
1744
+ async goOffline() {
1745
+ await this._ctx.dispose();
1746
+ await Promise.all([
1747
+ ...this._peers.keys()
1748
+ ].map((peerId) => this._destroyPeer(peerId, "goOffline")));
1749
+ }
1750
+ // For debug purposes
1751
+ async goOnline() {
1752
+ this._ctx = new import_context3.Context();
1753
+ }
1754
+ _getOrCreatePeer(peerId) {
1755
+ let peer = this._peers.get(peerId);
1756
+ if (!peer) {
1757
+ peer = new Peer(peerId, this._topic, this._ownPeerId, this._swarmMessenger, this._protocolProvider, this._transportFactory, this._connectionLimiter, {
1758
+ onInitiated: (connection) => {
1759
+ this.connectionAdded.emit(connection);
1760
+ },
1761
+ onConnected: () => {
1762
+ this.connected.emit(peerId);
1763
+ },
1764
+ onDisconnected: async () => {
1765
+ if (!peer.advertizing) {
1766
+ await this._destroyPeer(peer.id, "peer disconnected");
1767
+ }
1768
+ this.disconnected.emit(peerId);
1769
+ this._topology.update();
1770
+ },
1771
+ onRejected: () => {
1772
+ if (this._peers.has(peerId)) {
1773
+ (0, import_log3.log)("peer rejected connection", {
1774
+ peerId
1775
+ }, {
1776
+ F: __dxlog_file4,
1777
+ L: 285,
1778
+ S: this,
1779
+ C: (f, a) => f(...a)
1780
+ });
1781
+ void this._destroyPeer(peerId, "peer rejected connection");
1782
+ }
1783
+ },
1784
+ onAccepted: () => {
1785
+ this._topology.update();
1786
+ },
1787
+ onOffer: (remoteId) => {
1788
+ return this._topology.onOffer(remoteId);
1789
+ },
1790
+ onPeerAvailable: () => {
1791
+ this._topology.update();
1792
+ }
1793
+ });
1794
+ this._peers.set(peerId, peer);
1795
+ }
1796
+ return peer;
1797
+ }
1798
+ async _destroyPeer(peerId, reason) {
1799
+ (0, import_invariant3.invariant)(this._peers.has(peerId), void 0, {
1800
+ F: __dxlog_file4,
1801
+ L: 307,
1802
+ S: this,
1803
+ A: [
1804
+ "this._peers.has(peerId)",
1805
+ ""
1806
+ ]
1807
+ });
1808
+ await this._peers.get(peerId).destroy(new Error(reason));
1809
+ this._peers.delete(peerId);
1810
+ }
1811
+ _getSwarmController() {
1812
+ return {
1813
+ getState: () => ({
1814
+ ownPeerId: this._ownPeerId,
1815
+ connected: Array.from(this._peers.values()).filter((peer) => peer.connection).map((peer) => peer.id),
1816
+ candidates: Array.from(this._peers.values()).filter((peer) => !peer.connection && peer.advertizing && peer.availableToConnect).map((peer) => peer.id)
1817
+ }),
1818
+ connect: (peer) => {
1819
+ if (this._ctx.disposed) {
1820
+ return;
1821
+ }
1822
+ (0, import_async2.scheduleTask)(this._ctx, async () => {
1823
+ try {
1824
+ await this._initiateConnection(peer);
1825
+ } catch (err) {
1826
+ (0, import_log3.log)("initiation error", err, {
1827
+ F: __dxlog_file4,
1828
+ L: 333,
1829
+ S: this,
1830
+ C: (f, a) => f(...a)
1831
+ });
1832
+ }
1833
+ });
1834
+ },
1835
+ disconnect: async (peer) => {
1836
+ if (this._ctx.disposed) {
1837
+ return;
1838
+ }
1839
+ (0, import_async2.scheduleTask)(this._ctx, async () => {
1840
+ await this._closeConnection(peer);
1841
+ this._topology.update();
1842
+ });
1843
+ }
1844
+ };
1845
+ }
1846
+ /**
1847
+ * Creates a connection then sends message over signal network.
1848
+ */
1849
+ async _initiateConnection(remoteId) {
1850
+ const ctx = this._ctx;
1851
+ if (remoteId.toHex() < this._ownPeerId.toHex()) {
1852
+ (0, import_log3.log)("initiation delay", {
1853
+ remoteId
1854
+ }, {
1855
+ F: __dxlog_file4,
1856
+ L: 360,
1857
+ S: this,
1858
+ C: (f, a) => f(...a)
1859
+ });
1860
+ await (0, import_async2.sleep)(this._initiationDelay);
1861
+ }
1862
+ if (ctx.disposed) {
1863
+ return;
1864
+ }
1865
+ const peer = this._getOrCreatePeer(remoteId);
1866
+ if (peer.connection) {
1867
+ return;
1868
+ }
1869
+ (0, import_log3.log)("initiating connection...", {
1870
+ remoteId
1871
+ }, {
1872
+ F: __dxlog_file4,
1873
+ L: 374,
1874
+ S: this,
1875
+ C: (f, a) => f(...a)
1876
+ });
1877
+ await peer.initiateConnection();
1878
+ this._topology.update();
1879
+ (0, import_log3.log)("initiated", {
1880
+ remoteId
1881
+ }, {
1882
+ F: __dxlog_file4,
1883
+ L: 377,
1884
+ S: this,
1885
+ C: (f, a) => f(...a)
1886
+ });
1887
+ }
1888
+ async _closeConnection(peerId) {
1889
+ const peer = this._peers.get(peerId);
1890
+ if (!peer) {
1891
+ return;
1892
+ }
1893
+ await peer.closeConnection();
1894
+ }
1895
+ };
1896
+ _ts_decorate3([
1897
+ import_log3.logInfo
1898
+ ], Swarm.prototype, "_instanceId", void 0);
1899
+ _ts_decorate3([
1900
+ import_log3.logInfo
1901
+ ], Swarm.prototype, "ownPeerId", null);
1902
+ _ts_decorate3([
1903
+ import_log3.logInfo
1904
+ ], Swarm.prototype, "topic", null);
1905
+ _ts_decorate3([
1906
+ import_async2.synchronized
1907
+ ], Swarm.prototype, "onSwarmEvent", null);
1908
+ _ts_decorate3([
1909
+ import_async2.synchronized
1910
+ ], Swarm.prototype, "onOffer", null);
1911
+ _ts_decorate3([
1912
+ import_async2.synchronized
1913
+ ], Swarm.prototype, "goOffline", null);
1914
+ _ts_decorate3([
1915
+ import_async2.synchronized
1916
+ ], Swarm.prototype, "goOnline", null);
1917
+ var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm-mapper.ts";
1918
+ var SwarmMapper = class {
1919
+ get peers() {
1920
+ return Array.from(this._peers.values());
1921
+ }
1922
+ constructor(_swarm) {
1923
+ this._swarm = _swarm;
1924
+ this._subscriptions = new import_async4.EventSubscriptions();
1925
+ this._connectionSubscriptions = new import_util3.ComplexMap(import_keys5.PublicKey.hash);
1926
+ this._peers = new import_util3.ComplexMap(import_keys5.PublicKey.hash);
1927
+ this.mapUpdated = new import_async4.Event();
1928
+ this._subscriptions.add(_swarm.connectionAdded.on((connection) => {
1929
+ this._update();
1930
+ this._connectionSubscriptions.set(connection.remoteId, connection.stateChanged.on(() => {
1931
+ this._update();
1932
+ }));
1933
+ }));
1934
+ this._subscriptions.add(_swarm.disconnected.on((peerId) => {
1935
+ this._connectionSubscriptions.get(peerId)?.();
1936
+ this._connectionSubscriptions.delete(peerId);
1937
+ this._update();
1938
+ }));
1939
+ this._update();
1940
+ }
1941
+ _update() {
1942
+ (0, import_log5.log)("updating swarm", void 0, {
1943
+ F: __dxlog_file5,
1944
+ L: 72,
1945
+ S: this,
1946
+ C: (f, a) => f(...a)
1947
+ });
1948
+ this._peers.clear();
1949
+ this._peers.set(this._swarm.ownPeerId, {
1950
+ id: this._swarm.ownPeerId,
1951
+ state: "ME",
1952
+ connections: []
1953
+ });
1954
+ for (const connection of this._swarm.connections) {
1955
+ this._peers.set(connection.remoteId, {
1956
+ id: connection.remoteId,
1957
+ state: connection.state,
1958
+ connections: [
1959
+ this._swarm.ownPeerId
1960
+ ]
1961
+ });
1962
+ }
1963
+ (0, import_log5.log)("graph changed", {
1964
+ directConnections: this._swarm.connections.length,
1965
+ totalPeersInSwarm: this._peers.size
1966
+ }, {
1967
+ F: __dxlog_file5,
1968
+ L: 113,
1969
+ S: this,
1970
+ C: (f, a) => f(...a)
1971
+ });
1972
+ this.mapUpdated.emit(Array.from(this._peers.values()));
1973
+ }
1974
+ // TODO(burdon): Async open/close.
1975
+ destroy() {
1976
+ Array.from(this._connectionSubscriptions.values()).forEach((cb) => cb());
1977
+ this._subscriptions.clear();
1978
+ }
1979
+ };
1980
+ var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/connection-limiter.ts";
1981
+ var MAX_CONCURRENT_INITIATING_CONNECTIONS = 50;
1982
+ var ConnectionLimiter = class {
1983
+ constructor({ maxConcurrentInitConnections = MAX_CONCURRENT_INITIATING_CONNECTIONS } = {}) {
1984
+ this._ctx = new import_context5.Context();
1985
+ this._waitingPromises = new import_util4.ComplexMap(import_keys6.PublicKey.hash);
1986
+ this.resolveWaitingPromises = new import_async5.DeferredTask(this._ctx, async () => {
1987
+ Array.from(this._waitingPromises.values()).slice(0, this._maxConcurrentInitConnections).forEach(({ resolve }) => {
1988
+ resolve();
1989
+ });
1990
+ });
1991
+ this._maxConcurrentInitConnections = maxConcurrentInitConnections;
1992
+ }
1993
+ /**
1994
+ * @returns Promise that resolves in queue when connections amount with 'CONNECTING' state is below the limit.
1995
+ */
1996
+ async connecting(sessionId) {
1997
+ (0, import_invariant5.invariant)(!this._waitingPromises.has(sessionId), "Peer is already waiting for connection", {
1998
+ F: __dxlog_file6,
1999
+ L: 48,
2000
+ S: this,
2001
+ A: [
2002
+ "!this._waitingPromises.has(sessionId)",
2003
+ "'Peer is already waiting for connection'"
2004
+ ]
2005
+ });
2006
+ (0, import_log6.log)("waiting", {
2007
+ sessionId
2008
+ }, {
2009
+ F: __dxlog_file6,
2010
+ L: 49,
2011
+ S: this,
2012
+ C: (f, a) => f(...a)
2013
+ });
2014
+ await new Promise((resolve, reject) => {
2015
+ this._waitingPromises.set(sessionId, {
2016
+ resolve,
2017
+ reject
2018
+ });
2019
+ this.resolveWaitingPromises.schedule();
2020
+ });
2021
+ (0, import_log6.log)("allow", {
2022
+ sessionId
2023
+ }, {
2024
+ F: __dxlog_file6,
2025
+ L: 57,
2026
+ S: this,
2027
+ C: (f, a) => f(...a)
2028
+ });
2029
+ }
2030
+ /**
2031
+ * Rejects promise returned by `connecting` method.
2032
+ */
2033
+ doneConnecting(sessionId) {
2034
+ (0, import_log6.log)("done", {
2035
+ sessionId
2036
+ }, {
2037
+ F: __dxlog_file6,
2038
+ L: 64,
2039
+ S: this,
2040
+ C: (f, a) => f(...a)
2041
+ });
2042
+ if (!this._waitingPromises.has(sessionId)) {
2043
+ return;
2044
+ }
2045
+ this._waitingPromises.get(sessionId).reject(new import_protocols5.CancelledError());
2046
+ this._waitingPromises.delete(sessionId);
2047
+ this.resolveWaitingPromises.schedule();
2048
+ }
2049
+ };
2050
+ var CONNECTION_GC_THRESHOLD = 1e3 * 60 * 15;
2051
+ var EventType;
2052
+ (function(EventType2) {
2053
+ EventType2["CONNECTION_STATE_CHANGED"] = "CONNECTION_STATE_CHANGED";
2054
+ EventType2["PROTOCOL_ERROR"] = "PROTOCOL_ERROR";
2055
+ EventType2["PROTOCOL_EXTENSIONS_INITIALIZED"] = "PROTOCOL_EXTENSIONS_INITIALIZED";
2056
+ EventType2["PROTOCOL_EXTENSIONS_HANDSHAKE"] = "PROTOCOL_EXTENSIONS_HANDSHAKE";
2057
+ EventType2["PROTOCOL_HANDSHAKE"] = "PROTOCOL_HANDSHAKE";
2058
+ })(EventType || (EventType = {}));
2059
+ var ConnectionLog = class {
2060
+ constructor() {
2061
+ this._swarms = new import_util5.ComplexMap(import_keys7.PublicKey.hash);
2062
+ this.update = new import_async6.Event();
2063
+ }
2064
+ getSwarmInfo(swarmId) {
2065
+ return this._swarms.get(swarmId) ?? (0, import_debug3.raise)(new Error(`Swarm not found: ${swarmId}`));
2066
+ }
2067
+ get swarms() {
2068
+ return Array.from(this._swarms.values());
2069
+ }
2070
+ joinedSwarm(swarm) {
2071
+ const info = {
2072
+ id: import_keys7.PublicKey.from(swarm._instanceId),
2073
+ topic: swarm.topic,
2074
+ isActive: true,
2075
+ label: swarm.label,
2076
+ connections: []
2077
+ };
2078
+ this._swarms.set(import_keys7.PublicKey.from(swarm._instanceId), info);
2079
+ this.update.emit();
2080
+ swarm.connectionAdded.on((connection) => {
2081
+ const connectionInfo = {
2082
+ state: ConnectionState.CREATED,
2083
+ closeReason: connection.closeReason,
2084
+ remotePeerId: connection.remoteId,
2085
+ sessionId: connection.sessionId,
2086
+ transport: connection.transport && Object.getPrototypeOf(connection.transport).constructor.name,
2087
+ protocolExtensions: [],
2088
+ events: [],
2089
+ lastUpdate: /* @__PURE__ */ new Date()
2090
+ };
2091
+ info.connections.push(connectionInfo);
2092
+ this.update.emit();
2093
+ connection.stateChanged.on((state) => {
2094
+ connectionInfo.state = state;
2095
+ connectionInfo.closeReason = connection.closeReason;
2096
+ connectionInfo.lastUpdate = /* @__PURE__ */ new Date();
2097
+ connectionInfo.events.push({
2098
+ type: EventType.CONNECTION_STATE_CHANGED,
2099
+ newState: state
2100
+ });
2101
+ this.update.emit();
2102
+ });
2103
+ connection.protocol?.stats?.on((stats) => {
2104
+ connectionInfo.readBufferSize = stats.readBufferSize;
2105
+ connectionInfo.writeBufferSize = stats.writeBufferSize;
2106
+ connectionInfo.streams = stats.channels;
2107
+ connectionInfo.lastUpdate = /* @__PURE__ */ new Date();
2108
+ this.update.emit();
2109
+ });
2110
+ gcSwarm(info);
2111
+ });
2112
+ }
2113
+ leftSwarm(swarm) {
2114
+ this.getSwarmInfo(import_keys7.PublicKey.from(swarm._instanceId)).isActive = false;
2115
+ this.update.emit();
2116
+ }
2117
+ };
2118
+ var gcSwarm = (swarm) => {
2119
+ swarm.connections = swarm.connections?.filter((connection) => {
2120
+ return connection.lastUpdate ? Date.now() - connection.lastUpdate.getTime() < CONNECTION_GC_THRESHOLD : true;
2121
+ });
2122
+ };
2123
+ var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/network-manager.ts";
2124
+ var NetworkManager = class {
2125
+ constructor({ transportFactory, signalManager, log: log1 }) {
2126
+ this._swarms = new import_util6.ComplexMap(import_keys8.PublicKey.hash);
2127
+ this._mappers = new import_util6.ComplexMap(import_keys8.PublicKey.hash);
2128
+ this._connectionState = import_services.ConnectionState.ONLINE;
2129
+ this.connectionStateChanged = new import_async7.Event();
2130
+ this.topicsUpdated = new import_async7.Event();
2131
+ this._instanceId = import_keys8.PublicKey.random().toHex();
2132
+ this._transportFactory = transportFactory;
2133
+ this._signalManager = signalManager;
2134
+ this._signalManager.swarmEvent.on(({ topic, swarmEvent: event }) => this._swarms.get(topic)?.onSwarmEvent(event));
2135
+ this._messenger = new import_messaging.Messenger({
2136
+ signalManager: this._signalManager
2137
+ });
2138
+ this._signalConnection = {
2139
+ join: (opts) => this._signalManager.join(opts),
2140
+ leave: (opts) => this._signalManager.leave(opts)
2141
+ };
2142
+ this._connectionLimiter = new ConnectionLimiter();
2143
+ if (log1) {
2144
+ this._connectionLog = new ConnectionLog();
2145
+ }
2146
+ }
2147
+ // TODO(burdon): Remove access (Devtools only).
2148
+ get connectionLog() {
2149
+ return this._connectionLog;
2150
+ }
2151
+ get connectionState() {
2152
+ return this._connectionState;
2153
+ }
2154
+ // TODO(burdon): Reconcile with "discovery_key".
2155
+ get topics() {
2156
+ return Array.from(this._swarms.keys());
2157
+ }
2158
+ getSwarmMap(topic) {
2159
+ return this._mappers.get(topic);
2160
+ }
2161
+ getSwarm(topic) {
2162
+ return this._swarms.get(topic);
2163
+ }
2164
+ async open() {
2165
+ import_log7.log.trace("dxos.mesh.network-manager.open", import_protocols6.trace.begin({
2166
+ id: this._instanceId
2167
+ }), {
2168
+ F: __dxlog_file7,
2169
+ L: 130,
2170
+ S: this,
2171
+ C: (f, a) => f(...a)
2172
+ });
2173
+ await this._messenger.open();
2174
+ await this._signalManager.open();
2175
+ import_log7.log.trace("dxos.mesh.network-manager.open", import_protocols6.trace.end({
2176
+ id: this._instanceId
2177
+ }), {
2178
+ F: __dxlog_file7,
2179
+ L: 133,
2180
+ S: this,
2181
+ C: (f, a) => f(...a)
2182
+ });
2183
+ }
2184
+ async close() {
2185
+ for (const topic of this._swarms.keys()) {
2186
+ await this.leaveSwarm(topic).catch((err) => {
2187
+ (0, import_log7.log)(err, void 0, {
2188
+ F: __dxlog_file7,
2189
+ L: 139,
2190
+ S: this,
2191
+ C: (f, a) => f(...a)
2192
+ });
2193
+ });
2194
+ }
2195
+ await this._messenger.close();
2196
+ await this._signalManager.close();
2197
+ }
2198
+ /**
2199
+ * Join the swarm.
2200
+ */
2201
+ async joinSwarm({ topic, peerId, topology, protocolProvider: protocol, label }) {
2202
+ (0, import_invariant6.invariant)(import_keys8.PublicKey.isPublicKey(topic), void 0, {
2203
+ F: __dxlog_file7,
2204
+ L: 157,
2205
+ S: this,
2206
+ A: [
2207
+ "PublicKey.isPublicKey(topic)",
2208
+ ""
2209
+ ]
2210
+ });
2211
+ (0, import_invariant6.invariant)(import_keys8.PublicKey.isPublicKey(peerId), void 0, {
2212
+ F: __dxlog_file7,
2213
+ L: 158,
2214
+ S: this,
2215
+ A: [
2216
+ "PublicKey.isPublicKey(peerId)",
2217
+ ""
2218
+ ]
2219
+ });
2220
+ (0, import_invariant6.invariant)(topology, void 0, {
2221
+ F: __dxlog_file7,
2222
+ L: 159,
2223
+ S: this,
2224
+ A: [
2225
+ "topology",
2226
+ ""
2227
+ ]
2228
+ });
2229
+ (0, import_invariant6.invariant)(typeof protocol === "function", void 0, {
2230
+ F: __dxlog_file7,
2231
+ L: 160,
2232
+ S: this,
2233
+ A: [
2234
+ "typeof protocol === 'function'",
2235
+ ""
2236
+ ]
2237
+ });
2238
+ if (this._swarms.has(topic)) {
2239
+ throw new Error(`Already connected to swarm: ${import_keys8.PublicKey.from(topic)}`);
2240
+ }
2241
+ (0, import_log7.log)("joining", {
2242
+ topic: import_keys8.PublicKey.from(topic),
2243
+ peerId,
2244
+ topology: topology.toString()
2245
+ }, {
2246
+ F: __dxlog_file7,
2247
+ L: 165,
2248
+ S: this,
2249
+ C: (f, a) => f(...a)
2250
+ });
2251
+ const swarm = new Swarm(topic, peerId, topology, protocol, this._messenger, this._transportFactory, label, this._connectionLimiter);
2252
+ swarm.errors.handle((error) => {
2253
+ (0, import_log7.log)("swarm error", {
2254
+ error
2255
+ }, {
2256
+ F: __dxlog_file7,
2257
+ L: 178,
2258
+ S: this,
2259
+ C: (f, a) => f(...a)
2260
+ });
2261
+ });
2262
+ this._swarms.set(topic, swarm);
2263
+ this._mappers.set(topic, new SwarmMapper(swarm));
2264
+ await swarm.open();
2265
+ this._signalConnection.join({
2266
+ topic,
2267
+ peerId
2268
+ }).catch((error) => import_log7.log.catch(error, void 0, {
2269
+ F: __dxlog_file7,
2270
+ L: 187,
2271
+ S: this,
2272
+ C: (f, a) => f(...a)
2273
+ }));
2274
+ this.topicsUpdated.emit();
2275
+ this._connectionLog?.joinedSwarm(swarm);
2276
+ (0, import_log7.log)("joined", {
2277
+ topic: import_keys8.PublicKey.from(topic),
2278
+ count: this._swarms.size
2279
+ }, {
2280
+ F: __dxlog_file7,
2281
+ L: 191,
2282
+ S: this,
2283
+ C: (f, a) => f(...a)
2284
+ });
2285
+ return {
2286
+ close: () => this.leaveSwarm(topic)
2287
+ };
2288
+ }
2289
+ /**
2290
+ * Close the connection.
2291
+ */
2292
+ async leaveSwarm(topic) {
2293
+ if (!this._swarms.has(topic)) {
2294
+ return;
2295
+ }
2296
+ (0, import_log7.log)("leaving", {
2297
+ topic: import_keys8.PublicKey.from(topic)
2298
+ }, {
2299
+ F: __dxlog_file7,
2300
+ L: 207,
2301
+ S: this,
2302
+ C: (f, a) => f(...a)
2303
+ });
2304
+ const swarm = this._swarms.get(topic);
2305
+ await this._signalConnection.leave({
2306
+ topic,
2307
+ peerId: swarm.ownPeerId
2308
+ });
2309
+ const map = this._mappers.get(topic);
2310
+ map.destroy();
2311
+ this._mappers.delete(topic);
2312
+ this._connectionLog?.leftSwarm(swarm);
2313
+ await swarm.destroy();
2314
+ this._swarms.delete(topic);
2315
+ await this.topicsUpdated.emit();
2316
+ (0, import_log7.log)("left", {
2317
+ topic: import_keys8.PublicKey.from(topic),
2318
+ count: this._swarms.size
2319
+ }, {
2320
+ F: __dxlog_file7,
2321
+ L: 221,
2322
+ S: this,
2323
+ C: (f, a) => f(...a)
2324
+ });
2325
+ }
2326
+ async setConnectionState(state) {
2327
+ if (state === this._connectionState) {
2328
+ return;
2329
+ }
2330
+ switch (state) {
2331
+ case import_services.ConnectionState.OFFLINE: {
2332
+ this._connectionState = state;
2333
+ await Promise.all([
2334
+ ...this._swarms.values()
2335
+ ].map((swarm) => swarm.goOffline()));
2336
+ await this._messenger.close();
2337
+ await this._signalManager.close();
2338
+ break;
2339
+ }
2340
+ case import_services.ConnectionState.ONLINE: {
2341
+ this._connectionState = state;
2342
+ this._messenger.open();
2343
+ await Promise.all([
2344
+ ...this._swarms.values()
2345
+ ].map((swarm) => swarm.goOnline()));
2346
+ await this._signalManager.open();
2347
+ break;
2348
+ }
2349
+ }
2350
+ this.connectionStateChanged.emit(this._connectionState);
2351
+ }
2352
+ };
2353
+ var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/topology/fully-connected-topology.ts";
2354
+ var FullyConnectedTopology = class {
2355
+ toString() {
2356
+ return "FullyConnectedTopology";
2357
+ }
2358
+ init(controller) {
2359
+ (0, import_invariant7.invariant)(!this._controller, "Already initialized", {
2360
+ F: __dxlog_file8,
2361
+ L: 18,
2362
+ S: this,
2363
+ A: [
2364
+ "!this._controller",
2365
+ "'Already initialized'"
2366
+ ]
2367
+ });
2368
+ this._controller = controller;
2369
+ }
2370
+ update() {
2371
+ (0, import_invariant7.invariant)(this._controller, "Not initialized", {
2372
+ F: __dxlog_file8,
2373
+ L: 23,
2374
+ S: this,
2375
+ A: [
2376
+ "this._controller",
2377
+ "'Not initialized'"
2378
+ ]
2379
+ });
2380
+ const { candidates: discovered } = this._controller.getState();
2381
+ for (const peer of discovered) {
2382
+ this._controller.connect(peer);
2383
+ }
2384
+ }
2385
+ async onOffer(peer) {
2386
+ return true;
2387
+ }
2388
+ async destroy() {
2389
+ }
2390
+ };
2391
+ var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/topology/mmst-topology.ts";
2392
+ var MMSTTopology = class {
2393
+ constructor({ originateConnections = 2, maxPeers = 4, sampleSize = 10 } = {}) {
2394
+ this._sampleCollected = false;
2395
+ this._originateConnections = originateConnections;
2396
+ this._maxPeers = maxPeers;
2397
+ this._sampleSize = sampleSize;
2398
+ }
2399
+ init(controller) {
2400
+ (0, import_invariant8.invariant)(!this._controller, "Already initialized", {
2401
+ F: __dxlog_file9,
2402
+ L: 46,
2403
+ S: this,
2404
+ A: [
2405
+ "!this._controller",
2406
+ "'Already initialized'"
2407
+ ]
2408
+ });
2409
+ this._controller = controller;
2410
+ }
2411
+ update() {
2412
+ (0, import_invariant8.invariant)(this._controller, "Not initialized", {
2413
+ F: __dxlog_file9,
2414
+ L: 51,
2415
+ S: this,
2416
+ A: [
2417
+ "this._controller",
2418
+ "'Not initialized'"
2419
+ ]
2420
+ });
2421
+ const { connected, candidates } = this._controller.getState();
2422
+ if (this._sampleCollected || connected.length > this._maxPeers || candidates.length > 0) {
2423
+ (0, import_log8.log)("Running the algorithm.", void 0, {
2424
+ F: __dxlog_file9,
2425
+ L: 55,
2426
+ S: this,
2427
+ C: (f, a) => f(...a)
2428
+ });
2429
+ this._sampleCollected = true;
2430
+ this._runAlgorithm();
2431
+ }
2432
+ }
2433
+ async onOffer(peer) {
2434
+ (0, import_invariant8.invariant)(this._controller, "Not initialized", {
2435
+ F: __dxlog_file9,
2436
+ L: 62,
2437
+ S: this,
2438
+ A: [
2439
+ "this._controller",
2440
+ "'Not initialized'"
2441
+ ]
2442
+ });
2443
+ const { connected } = this._controller.getState();
2444
+ const accept = connected.length < this._maxPeers;
2445
+ (0, import_log8.log)(`Offer ${peer} accept=${accept}`, void 0, {
2446
+ F: __dxlog_file9,
2447
+ L: 65,
2448
+ S: this,
2449
+ C: (f, a) => f(...a)
2450
+ });
2451
+ return accept;
2452
+ }
2453
+ async destroy() {
2454
+ }
2455
+ _runAlgorithm() {
2456
+ (0, import_invariant8.invariant)(this._controller, "Not initialized", {
2457
+ F: __dxlog_file9,
2458
+ L: 74,
2459
+ S: this,
2460
+ A: [
2461
+ "this._controller",
2462
+ "'Not initialized'"
2463
+ ]
2464
+ });
2465
+ const { connected, candidates, ownPeerId } = this._controller.getState();
2466
+ if (connected.length > this._maxPeers) {
2467
+ const sorted = sortByXorDistance(connected, ownPeerId).reverse().slice(0, this._maxPeers - connected.length);
2468
+ for (const peer of sorted) {
2469
+ (0, import_log8.log)(`Disconnect ${peer}.`, void 0, {
2470
+ F: __dxlog_file9,
2471
+ L: 83,
2472
+ S: this,
2473
+ C: (f, a) => f(...a)
2474
+ });
2475
+ this._controller.disconnect(peer);
2476
+ }
2477
+ } else if (connected.length < this._originateConnections) {
2478
+ const sample = candidates.sort(() => Math.random() - 0.5).slice(0, this._sampleSize);
2479
+ const sorted = sortByXorDistance(sample, ownPeerId).slice(0, this._originateConnections - connected.length);
2480
+ for (const peer of sorted) {
2481
+ (0, import_log8.log)(`Connect ${peer}.`, void 0, {
2482
+ F: __dxlog_file9,
2483
+ L: 91,
2484
+ S: this,
2485
+ C: (f, a) => f(...a)
2486
+ });
2487
+ this._controller.connect(peer);
2488
+ }
2489
+ }
2490
+ }
2491
+ toString() {
2492
+ return "MMSTTopology";
2493
+ }
2494
+ };
2495
+ var sortByXorDistance = (keys, reference) => keys.sort((a, b) => import_xor_distance.default.gt((0, import_xor_distance.default)(a.asBuffer(), reference.asBuffer()), (0, import_xor_distance.default)(b.asBuffer(), reference.asBuffer())));
2496
+ var __dxlog_file10 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/topology/star-topology.ts";
2497
+ var StarTopology = class {
2498
+ constructor(_centralPeer) {
2499
+ this._centralPeer = _centralPeer;
2500
+ }
2501
+ toString() {
2502
+ return `StarTopology(${this._centralPeer.truncate()})`;
2503
+ }
2504
+ init(controller) {
2505
+ (0, import_invariant9.invariant)(!this._controller, "Already initialized.", {
2506
+ F: __dxlog_file10,
2507
+ L: 21,
2508
+ S: this,
2509
+ A: [
2510
+ "!this._controller",
2511
+ "'Already initialized.'"
2512
+ ]
2513
+ });
2514
+ this._controller = controller;
2515
+ }
2516
+ update() {
2517
+ (0, import_invariant9.invariant)(this._controller, "Not initialized.", {
2518
+ F: __dxlog_file10,
2519
+ L: 26,
2520
+ S: this,
2521
+ A: [
2522
+ "this._controller",
2523
+ "'Not initialized.'"
2524
+ ]
2525
+ });
2526
+ const { candidates, connected, ownPeerId } = this._controller.getState();
2527
+ if (!ownPeerId.equals(this._centralPeer)) {
2528
+ (0, import_log9.log)("leaf peer dropping all connections apart from central peer.", void 0, {
2529
+ F: __dxlog_file10,
2530
+ L: 29,
2531
+ S: this,
2532
+ C: (f, a) => f(...a)
2533
+ });
2534
+ for (const peer of connected) {
2535
+ if (!peer.equals(this._centralPeer)) {
2536
+ (0, import_log9.log)("dropping connection", {
2537
+ peer
2538
+ }, {
2539
+ F: __dxlog_file10,
2540
+ L: 34,
2541
+ S: this,
2542
+ C: (f, a) => f(...a)
2543
+ });
2544
+ this._controller.disconnect(peer);
2545
+ }
2546
+ }
2547
+ }
2548
+ for (const peer of candidates) {
2549
+ if (peer.equals(this._centralPeer) || ownPeerId.equals(this._centralPeer)) {
2550
+ (0, import_log9.log)("connecting to peer", {
2551
+ peer
2552
+ }, {
2553
+ F: __dxlog_file10,
2554
+ L: 43,
2555
+ S: this,
2556
+ C: (f, a) => f(...a)
2557
+ });
2558
+ this._controller.connect(peer);
2559
+ }
2560
+ }
2561
+ }
2562
+ async onOffer(peer) {
2563
+ (0, import_invariant9.invariant)(this._controller, "Not initialized.", {
2564
+ F: __dxlog_file10,
2565
+ L: 50,
2566
+ S: this,
2567
+ A: [
2568
+ "this._controller",
2569
+ "'Not initialized.'"
2570
+ ]
2571
+ });
2572
+ const { ownPeerId } = this._controller.getState();
2573
+ (0, import_log9.log)("offer", {
2574
+ peer,
2575
+ isCentral: peer.equals(this._centralPeer),
2576
+ isSelfCentral: ownPeerId.equals(this._centralPeer)
2577
+ }, {
2578
+ F: __dxlog_file10,
2579
+ L: 52,
2580
+ S: this,
2581
+ C: (f, a) => f(...a)
2582
+ });
2583
+ return ownPeerId.equals(this._centralPeer) || peer.equals(this._centralPeer);
2584
+ }
2585
+ async destroy() {
2586
+ }
2587
+ };
2588
+ function _ts_decorate4(decorators, target, key, desc) {
2589
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2590
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
2591
+ r = Reflect.decorate(decorators, target, key, desc);
2592
+ else
2593
+ for (var i = decorators.length - 1; i >= 0; i--)
2594
+ if (d = decorators[i])
2595
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2596
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2597
+ }
2598
+ var __dxlog_file11 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/memory-transport.ts";
2599
+ var MEMORY_TRANSPORT_DELAY = 1;
2600
+ var createStreamDelay = (delay) => {
2601
+ return new import_node_stream.Transform({
2602
+ objectMode: true,
2603
+ transform: (chunk, _, cb) => {
2604
+ setTimeout(() => cb(null, chunk), delay);
2605
+ }
2606
+ });
2607
+ };
2608
+ var MemoryTransportFactory = {
2609
+ createTransport: (params) => new MemoryTransport(params)
2610
+ };
2611
+ var MemoryTransport = class _MemoryTransport {
2612
+ static {
2613
+ this._connections = new import_util7.ComplexMap(import_keys9.PublicKey.hash);
2614
+ }
2615
+ constructor(options) {
2616
+ this.options = options;
2617
+ this.closed = new import_async8.Event();
2618
+ this.connected = new import_async8.Event();
2619
+ this.errors = new import_debug4.ErrorStream();
2620
+ this._instanceId = import_keys9.PublicKey.random();
2621
+ this._remote = new import_async8.Trigger();
2622
+ this._outgoingDelay = createStreamDelay(MEMORY_TRANSPORT_DELAY);
2623
+ this._incomingDelay = createStreamDelay(MEMORY_TRANSPORT_DELAY);
2624
+ this._destroyed = false;
2625
+ (0, import_log10.log)("creating", void 0, {
2626
+ F: __dxlog_file11,
2627
+ L: 64,
2628
+ S: this,
2629
+ C: (f, a) => f(...a)
2630
+ });
2631
+ (0, import_invariant10.invariant)(!_MemoryTransport._connections.has(this._instanceId), "Duplicate memory connection", {
2632
+ F: __dxlog_file11,
2633
+ L: 66,
2634
+ S: this,
2635
+ A: [
2636
+ "!MemoryTransport._connections.has(this._instanceId)",
2637
+ "'Duplicate memory connection'"
2638
+ ]
2639
+ });
2640
+ _MemoryTransport._connections.set(this._instanceId, this);
2641
+ if (this.options.initiator) {
2642
+ setTimeout(async () => {
2643
+ (0, import_log10.log)("sending signal", void 0, {
2644
+ F: __dxlog_file11,
2645
+ L: 73,
2646
+ S: this,
2647
+ C: (f, a) => f(...a)
2648
+ });
2649
+ void this.options.sendSignal({
2650
+ payload: {
2651
+ transportId: this._instanceId.toHex()
2652
+ }
2653
+ }).catch((err) => {
2654
+ if (!this._destroyed) {
2655
+ this.errors.raise(err);
2656
+ }
2657
+ });
2658
+ });
2659
+ } else {
2660
+ this._remote.wait({
2661
+ timeout: this.options.timeout ?? 1e3
2662
+ }).then((remoteId) => {
2663
+ if (this._destroyed) {
2664
+ return;
2665
+ }
2666
+ this._remoteInstanceId = remoteId;
2667
+ this._remoteConnection = _MemoryTransport._connections.get(this._remoteInstanceId);
2668
+ if (!this._remoteConnection) {
2669
+ this._destroyed = true;
2670
+ this.closed.emit();
2671
+ return;
2672
+ }
2673
+ (0, import_invariant10.invariant)(!this._remoteConnection._remoteConnection, `Remote already connected: ${this._remoteInstanceId}`, {
2674
+ F: __dxlog_file11,
2675
+ L: 99,
2676
+ S: this,
2677
+ A: [
2678
+ "!this._remoteConnection._remoteConnection",
2679
+ "`Remote already connected: ${this._remoteInstanceId}`"
2680
+ ]
2681
+ });
2682
+ this._remoteConnection._remoteConnection = this;
2683
+ this._remoteConnection._remoteInstanceId = this._instanceId;
2684
+ (0, import_log10.log)("connected", void 0, {
2685
+ F: __dxlog_file11,
2686
+ L: 103,
2687
+ S: this,
2688
+ C: (f, a) => f(...a)
2689
+ });
2690
+ this.options.stream.pipe(this._outgoingDelay).pipe(this._remoteConnection.options.stream).pipe(this._incomingDelay).pipe(this.options.stream);
2691
+ this.connected.emit();
2692
+ this._remoteConnection.connected.emit();
2693
+ }).catch((err) => {
2694
+ if (this._destroyed) {
2695
+ return;
2696
+ }
2697
+ this.errors.raise(err);
2698
+ });
2699
+ }
2700
+ }
2701
+ async destroy() {
2702
+ (0, import_log10.log)("closing", void 0, {
2703
+ F: __dxlog_file11,
2704
+ L: 124,
2705
+ S: this,
2706
+ C: (f, a) => f(...a)
2707
+ });
2708
+ this._destroyed = true;
2709
+ _MemoryTransport._connections.delete(this._instanceId);
2710
+ if (this._remoteConnection) {
2711
+ (0, import_log10.log)("closing", void 0, {
2712
+ F: __dxlog_file11,
2713
+ L: 129,
2714
+ S: this,
2715
+ C: (f, a) => f(...a)
2716
+ });
2717
+ this._remoteConnection._destroyed = true;
2718
+ _MemoryTransport._connections.delete(this._remoteInstanceId);
2719
+ this.options.stream.unpipe(this._incomingDelay);
2720
+ this._incomingDelay.unpipe(this._remoteConnection.options.stream);
2721
+ this._remoteConnection.options.stream.unpipe(this._outgoingDelay);
2722
+ this._outgoingDelay.unpipe(this.options.stream);
2723
+ this.options.stream.unpipe(this._outgoingDelay);
2724
+ this._remoteConnection.closed.emit();
2725
+ this._remoteConnection._remoteConnection = void 0;
2726
+ this._remoteConnection = void 0;
2727
+ (0, import_log10.log)("closed", void 0, {
2728
+ F: __dxlog_file11,
2729
+ L: 150,
2730
+ S: this,
2731
+ C: (f, a) => f(...a)
2732
+ });
2733
+ }
2734
+ this.closed.emit();
2735
+ (0, import_log10.log)("closed", void 0, {
2736
+ F: __dxlog_file11,
2737
+ L: 154,
2738
+ S: this,
2739
+ C: (f, a) => f(...a)
2740
+ });
2741
+ }
2742
+ signal({ payload }) {
2743
+ (0, import_log10.log)("received signal", {
2744
+ payload
2745
+ }, {
2746
+ F: __dxlog_file11,
2747
+ L: 158,
2748
+ S: this,
2749
+ C: (f, a) => f(...a)
2750
+ });
2751
+ if (!payload?.transportId) {
2752
+ return;
2753
+ }
2754
+ const transportId = payload.transportId;
2755
+ if (transportId) {
2756
+ const remoteId = import_keys9.PublicKey.fromHex(transportId);
2757
+ this._remote.wake(remoteId);
2758
+ }
2759
+ }
2760
+ };
2761
+ _ts_decorate4([
2762
+ import_log10.logInfo
2763
+ ], MemoryTransport.prototype, "_instanceId", void 0);
2764
+ _ts_decorate4([
2765
+ import_log10.logInfo
2766
+ ], MemoryTransport.prototype, "_remoteInstanceId", void 0);
2767
+ var TransportKind;
2768
+ (function(TransportKind2) {
2769
+ TransportKind2["SIMPLE_PEER"] = "SIMPLE_PEER";
2770
+ TransportKind2["LIBDATACHANNEL"] = "LIBDATACHANNEL";
2771
+ TransportKind2["SIMPLE_PEER_PROXY"] = "SIMPLE_PEER_PROXY";
2772
+ TransportKind2["MEMORY"] = "MEMORY";
2773
+ TransportKind2["TCP"] = "TCP";
2774
+ })(TransportKind || (TransportKind = {}));
2775
+ var wrtc = null;
2776
+ try {
2777
+ wrtc = (0, import_chunk_XE5JOIGD.__require)("@koush/wrtc");
2778
+ } catch {
2779
+ }
2780
+ var __dxlog_file12 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/simplepeer-transport.ts";
2781
+ var SimplePeerTransport = class {
2782
+ constructor(params) {
2783
+ this.params = params;
2784
+ this._closed = false;
2785
+ this._piped = false;
2786
+ this.closed = new import_async9.Event();
2787
+ this.connected = new import_async9.Event();
2788
+ this.errors = new import_debug5.ErrorStream();
2789
+ this._instanceId = import_keys10.PublicKey.random().toHex();
2790
+ import_log11.log.trace("dxos.mesh.webrtc-transport.constructor", import_protocols7.trace.begin({
2791
+ id: this._instanceId
2792
+ }), {
2793
+ F: __dxlog_file12,
2794
+ L: 41,
2795
+ S: this,
2796
+ C: (f, a) => f(...a)
2797
+ });
2798
+ (0, import_log11.log)("created connection", params, {
2799
+ F: __dxlog_file12,
2800
+ L: 42,
2801
+ S: this,
2802
+ C: (f, a) => f(...a)
2803
+ });
2804
+ this._peer = new import_simple_peer.default({
2805
+ channelName: "dxos.mesh.transport",
2806
+ initiator: this.params.initiator,
2807
+ wrtc: import_simple_peer.default.WEBRTC_SUPPORT ? void 0 : wrtc ?? (0, import_debug5.raise)(new Error("wrtc not available")),
2808
+ config: this.params.webrtcConfig
2809
+ });
2810
+ this._peer.on("signal", async (data) => {
2811
+ (0, import_log11.log)("signal", data, {
2812
+ F: __dxlog_file12,
2813
+ L: 51,
2814
+ S: this,
2815
+ C: (f, a) => f(...a)
2816
+ });
2817
+ await this.params.sendSignal({
2818
+ payload: {
2819
+ data
2820
+ }
2821
+ });
2822
+ });
2823
+ this._peer.on("connect", () => {
2824
+ (0, import_log11.log)("connected", void 0, {
2825
+ F: __dxlog_file12,
2826
+ L: 56,
2827
+ S: this,
2828
+ C: (f, a) => f(...a)
2829
+ });
2830
+ this.params.stream.pipe(this._peer).pipe(this.params.stream);
2831
+ this._piped = true;
2832
+ this.connected.emit();
2833
+ });
2834
+ this._peer.on("close", async () => {
2835
+ (0, import_log11.log)("closed", void 0, {
2836
+ F: __dxlog_file12,
2837
+ L: 63,
2838
+ S: this,
2839
+ C: (f, a) => f(...a)
2840
+ });
2841
+ await this.destroy();
2842
+ });
2843
+ this._peer.on("error", async (err) => {
2844
+ if (typeof RTCError !== "undefined" && err instanceof RTCError) {
2845
+ if (err.errorDetail === "sctp-failure") {
2846
+ this.errors.raise(new import_protocols7.ConnectionResetError("sctp-failure from RTCError", err));
2847
+ } else {
2848
+ import_log11.log.info("unknown RTCError", {
2849
+ err
2850
+ }, {
2851
+ F: __dxlog_file12,
2852
+ L: 74,
2853
+ S: this,
2854
+ C: (f, a) => f(...a)
2855
+ });
2856
+ this.errors.raise(new import_protocols7.UnknownProtocolError("unknown RTCError", err));
2857
+ }
2858
+ } else if ("code" in err) {
2859
+ import_log11.log.info("simple-peer error", err, {
2860
+ F: __dxlog_file12,
2861
+ L: 79,
2862
+ S: this,
2863
+ C: (f, a) => f(...a)
2864
+ });
2865
+ switch (err.code) {
2866
+ case "ERR_WEBRTC_SUPPORT":
2867
+ this.errors.raise(new import_protocols7.ProtocolError("WebRTC not supported", err));
2868
+ break;
2869
+ case "ERR_SIGNALING":
2870
+ this.errors.raise(new import_protocols7.ConnectivityError("signaling failure", err));
2871
+ break;
2872
+ case "ERR_ICE_CONNECTION_FAILURE":
2873
+ case "ERR_DATA_CHANNEL":
2874
+ case "ERR_CONNECTION_FAILURE":
2875
+ this.errors.raise(new import_protocols7.ConnectivityError("unknown communication failure", err));
2876
+ break;
2877
+ case "ERR_CREATE_OFFER":
2878
+ case "ERR_CREATE_ANSWER":
2879
+ case "ERR_SET_LOCAL_DESCRIPTION":
2880
+ case "ERR_SET_REMOTE_DESCRIPTION":
2881
+ case "ERR_ADD_ICE_CANDIDATE":
2882
+ this.errors.raise(new import_protocols7.UnknownProtocolError("unknown simple-peer library failure", err));
2883
+ break;
2884
+ default:
2885
+ this.errors.raise(new Error("unknown simple-peer error"));
2886
+ break;
2887
+ }
2888
+ } else {
2889
+ import_log11.log.info("unknown peer connection error", err, {
2890
+ F: __dxlog_file12,
2891
+ L: 105,
2892
+ S: this,
2893
+ C: (f, a) => f(...a)
2894
+ });
2895
+ this.errors.raise(err);
2896
+ }
2897
+ try {
2898
+ if (typeof this._peer?._pc?.getStats === "function") {
2899
+ this._peer._pc.getStats().then((stats) => {
2900
+ import_log11.log.info("report after webrtc error", {
2901
+ config: this.params.webrtcConfig,
2902
+ stats
2903
+ }, {
2904
+ F: __dxlog_file12,
2905
+ L: 113,
2906
+ S: this,
2907
+ C: (f, a) => f(...a)
2908
+ });
2909
+ });
2910
+ }
2911
+ } catch (err2) {
2912
+ import_log11.log.catch(err2, void 0, {
2913
+ F: __dxlog_file12,
2914
+ L: 120,
2915
+ S: this,
2916
+ C: (f, a) => f(...a)
2917
+ });
2918
+ }
2919
+ await this.destroy();
2920
+ });
2921
+ import_log11.log.trace("dxos.mesh.webrtc-transport.constructor", import_protocols7.trace.end({
2922
+ id: this._instanceId
2923
+ }), {
2924
+ F: __dxlog_file12,
2925
+ L: 125,
2926
+ S: this,
2927
+ C: (f, a) => f(...a)
2928
+ });
2929
+ }
2930
+ async destroy() {
2931
+ (0, import_log11.log)("closing...", void 0, {
2932
+ F: __dxlog_file12,
2933
+ L: 129,
2934
+ S: this,
2935
+ C: (f, a) => f(...a)
2936
+ });
2937
+ if (this._closed) {
2938
+ return;
2939
+ }
2940
+ this._closed = true;
2941
+ this._disconnectStreams();
2942
+ this._peer.destroy();
2943
+ this.closed.emit();
2944
+ (0, import_log11.log)("closed", void 0, {
2945
+ F: __dxlog_file12,
2946
+ L: 137,
2947
+ S: this,
2948
+ C: (f, a) => f(...a)
2949
+ });
2950
+ }
2951
+ signal(signal) {
2952
+ if (this._closed) {
2953
+ return;
2954
+ }
2955
+ (0, import_tiny_invariant.default)(signal.payload.data, "Signal message must contain signal data.");
2956
+ this._peer.signal(signal.payload.data);
2957
+ }
2958
+ _disconnectStreams() {
2959
+ if (this._piped) {
2960
+ this.params.stream.unpipe?.(this._peer)?.unpipe?.(this.params.stream);
2961
+ }
2962
+ }
2963
+ };
2964
+ var createSimplePeerTransportFactory = (webrtcConfig) => ({
2965
+ createTransport: (params) => new SimplePeerTransport({
2966
+ ...params,
2967
+ webrtcConfig
2968
+ })
2969
+ });
2970
+ var __dxlog_file13 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/simplepeer-transport-service.ts";
2971
+ var SimplePeerTransportService = class {
2972
+ constructor(_webrtcConfig) {
2973
+ this._webrtcConfig = _webrtcConfig;
2974
+ this.transports = new import_util8.ComplexMap(import_keys11.PublicKey.hash);
2975
+ }
2976
+ open(request) {
2977
+ const rpcStream = new import_codec_protobuf.Stream(({ ready, next, close }) => {
2978
+ const duplex = new import_node_stream2.Duplex({
2979
+ read: () => {
2980
+ const callbacks = [
2981
+ ...transportState.writeCallbacks
2982
+ ];
2983
+ transportState.writeCallbacks.length = 0;
2984
+ for (const cb of callbacks) {
2985
+ cb();
2986
+ }
2987
+ },
2988
+ write: function(chunk, _, callback) {
2989
+ next({
2990
+ data: {
2991
+ payload: chunk
2992
+ }
2993
+ });
2994
+ callback();
2995
+ }
2996
+ });
2997
+ const transport = new SimplePeerTransport({
2998
+ initiator: request.initiator,
2999
+ stream: duplex,
3000
+ webrtcConfig: this._webrtcConfig,
3001
+ sendSignal: async (signal) => {
3002
+ next({
3003
+ signal: {
3004
+ payload: signal
3005
+ }
3006
+ });
3007
+ }
3008
+ });
3009
+ next({
3010
+ connection: {
3011
+ state: import_bridge.ConnectionState.CONNECTING
3012
+ }
3013
+ });
3014
+ transport.connected.on(() => {
3015
+ next({
3016
+ connection: {
3017
+ state: import_bridge.ConnectionState.CONNECTED
3018
+ }
3019
+ });
3020
+ });
3021
+ transport.errors.handle((err) => {
3022
+ next({
3023
+ connection: {
3024
+ state: import_bridge.ConnectionState.CLOSED,
3025
+ error: err.toString()
3026
+ }
3027
+ });
3028
+ close(err);
3029
+ });
3030
+ transport.closed.on(() => {
3031
+ next({
3032
+ connection: {
3033
+ state: import_bridge.ConnectionState.CLOSED
3034
+ }
3035
+ });
3036
+ close();
3037
+ });
3038
+ const transportState = {
3039
+ transport,
3040
+ stream: duplex,
3041
+ writeCallbacks: [],
3042
+ state: "OPEN"
3043
+ };
3044
+ ready();
3045
+ this.transports.set(request.proxyId, transportState);
3046
+ });
3047
+ return rpcStream;
3048
+ }
3049
+ async sendSignal({ proxyId, signal }) {
3050
+ (0, import_invariant11.invariant)(this.transports.has(proxyId), void 0, {
3051
+ F: __dxlog_file13,
3052
+ L: 112,
3053
+ S: this,
3054
+ A: [
3055
+ "this.transports.has(proxyId)",
3056
+ ""
3057
+ ]
3058
+ });
3059
+ await this.transports.get(proxyId).transport.signal(signal);
3060
+ }
3061
+ async sendData({ proxyId, payload }) {
3062
+ if (this.transports.get(proxyId)?.state !== "OPEN") {
3063
+ import_log12.log.debug("transport is closed", void 0, {
3064
+ F: __dxlog_file13,
3065
+ L: 118,
3066
+ S: this,
3067
+ C: (f, a) => f(...a)
3068
+ });
3069
+ }
3070
+ (0, import_invariant11.invariant)(this.transports.has(proxyId), void 0, {
3071
+ F: __dxlog_file13,
3072
+ L: 120,
3073
+ S: this,
3074
+ A: [
3075
+ "this.transports.has(proxyId)",
3076
+ ""
3077
+ ]
3078
+ });
3079
+ const state = this.transports.get(proxyId);
3080
+ const bufferHasSpace = state.stream.push(payload);
3081
+ if (!bufferHasSpace) {
3082
+ await new Promise((resolve) => {
3083
+ state.writeCallbacks.push(resolve);
3084
+ });
3085
+ }
3086
+ }
3087
+ async close({ proxyId }) {
3088
+ await this.transports.get(proxyId)?.transport.destroy();
3089
+ await this.transports.get(proxyId)?.stream.end();
3090
+ if (this.transports.get(proxyId)) {
3091
+ this.transports.get(proxyId).state = "CLOSED";
3092
+ }
3093
+ (0, import_log12.log)("Closed.", void 0, {
3094
+ F: __dxlog_file13,
3095
+ L: 136,
3096
+ S: this,
3097
+ C: (f, a) => f(...a)
3098
+ });
3099
+ }
3100
+ };
3101
+ var __dxlog_file14 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/simplepeer-transport-proxy.ts";
3102
+ var RESP_MIN_THRESHOLD = 500;
3103
+ var TIMEOUT_THRESHOLD = 10;
3104
+ var SimplePeerTransportProxy = class {
3105
+ constructor(_params) {
3106
+ this._params = _params;
3107
+ this._proxyId = import_keys12.PublicKey.random();
3108
+ this._ctx = new import_context6.Context();
3109
+ this._timeoutCount = 0;
3110
+ this.closed = new import_async10.Event();
3111
+ this.connected = new import_async10.Event();
3112
+ this.errors = new import_debug6.ErrorStream();
3113
+ this._closed = false;
3114
+ this._serviceStream = this._params.bridgeService.open({
3115
+ proxyId: this._proxyId,
3116
+ initiator: this._params.initiator
3117
+ });
3118
+ this._serviceStream.waitUntilReady().then(() => {
3119
+ this._serviceStream.subscribe(async (event) => {
3120
+ (0, import_log13.log)("SimplePeerTransportProxy: event", event, {
3121
+ F: __dxlog_file14,
3122
+ L: 59,
3123
+ S: this,
3124
+ C: (f, a) => f(...a)
3125
+ });
3126
+ if (event.connection) {
3127
+ await this._handleConnection(event.connection);
3128
+ } else if (event.data) {
3129
+ this._handleData(event.data);
3130
+ } else if (event.signal) {
3131
+ await this._handleSignal(event.signal);
3132
+ }
3133
+ });
3134
+ const proxyStream = new import_node_stream3.Writable({
3135
+ write: (chunk, _, callback) => {
3136
+ const then = performance.now();
3137
+ this._params.bridgeService.sendData({
3138
+ proxyId: this._proxyId,
3139
+ payload: chunk
3140
+ }).then(() => {
3141
+ if (performance.now() - then > RESP_MIN_THRESHOLD) {
3142
+ (0, import_log13.log)("slow response, delaying callback", void 0, {
3143
+ F: __dxlog_file14,
3144
+ L: 80,
3145
+ S: this,
3146
+ C: (f, a) => f(...a)
3147
+ });
3148
+ (0, import_async10.scheduleTask)(this._ctx, () => callback(), RESP_MIN_THRESHOLD);
3149
+ } else {
3150
+ callback();
3151
+ }
3152
+ this._timeoutCount = 0;
3153
+ }, (err) => {
3154
+ if (err instanceof import_protocols8.TimeoutError || err.constructor.name === "TimeoutError") {
3155
+ if (this._timeoutCount++ > TIMEOUT_THRESHOLD) {
3156
+ throw new import_protocols8.TimeoutError(`too many timeoutes (${this._timeoutCount} > ${TIMEOUT_THRESHOLD}`);
3157
+ } else {
3158
+ (0, import_log13.log)("timeout error, but still invoking callback", void 0, {
3159
+ F: __dxlog_file14,
3160
+ L: 92,
3161
+ S: this,
3162
+ C: (f, a) => f(...a)
3163
+ });
3164
+ callback();
3165
+ }
3166
+ } else {
3167
+ import_log13.log.catch(err, void 0, {
3168
+ F: __dxlog_file14,
3169
+ L: 96,
3170
+ S: this,
3171
+ C: (f, a) => f(...a)
3172
+ });
3173
+ }
3174
+ });
3175
+ }
3176
+ });
3177
+ proxyStream.on("error", (err) => {
3178
+ (0, import_log13.log)("proxystream error", {
3179
+ err
3180
+ }, {
3181
+ F: __dxlog_file14,
3182
+ L: 104,
3183
+ S: this,
3184
+ C: (f, a) => f(...a)
3185
+ });
3186
+ });
3187
+ this._params.stream.pipe(proxyStream);
3188
+ }, (error) => import_log13.log.catch(error, void 0, {
3189
+ F: __dxlog_file14,
3190
+ L: 109,
3191
+ S: this,
3192
+ C: (f, a) => f(...a)
3193
+ }));
3194
+ }
3195
+ async _handleConnection(connectionEvent) {
3196
+ if (connectionEvent.error) {
3197
+ this.errors.raise(decodeError(connectionEvent.error));
3198
+ }
3199
+ switch (connectionEvent.state) {
3200
+ case import_bridge2.ConnectionState.CONNECTED: {
3201
+ this.connected.emit();
3202
+ break;
3203
+ }
3204
+ case import_bridge2.ConnectionState.CLOSED: {
3205
+ await this.destroy();
3206
+ break;
3207
+ }
3208
+ }
3209
+ }
3210
+ _handleData(dataEvent) {
3211
+ this._params.stream.write((0, import_util9.arrayToBuffer)(dataEvent.payload));
3212
+ }
3213
+ async _handleSignal(signalEvent) {
3214
+ await this._params.sendSignal(signalEvent.payload);
3215
+ }
3216
+ signal(signal) {
3217
+ this._params.bridgeService.sendSignal({
3218
+ proxyId: this._proxyId,
3219
+ signal
3220
+ }).catch((err) => this.errors.raise(decodeError(err)));
3221
+ }
3222
+ // TODO(burdon): Move open from constructor.
3223
+ async destroy() {
3224
+ await this._ctx.dispose();
3225
+ if (this._closed) {
3226
+ return;
3227
+ }
3228
+ await this._serviceStream.close();
3229
+ try {
3230
+ await this._params.bridgeService.close({
3231
+ proxyId: this._proxyId
3232
+ });
3233
+ } catch (err) {
3234
+ import_log13.log.catch(err, void 0, {
3235
+ F: __dxlog_file14,
3236
+ L: 160,
3237
+ S: this,
3238
+ C: (f, a) => f(...a)
3239
+ });
3240
+ }
3241
+ this.closed.emit();
3242
+ this._closed = true;
3243
+ }
3244
+ /**
3245
+ * Called when underlying proxy service becomes unavailable.
3246
+ */
3247
+ // TODO(burdon): Option on close method.
3248
+ forceClose() {
3249
+ void this._serviceStream.close();
3250
+ this.closed.emit();
3251
+ this._closed = true;
3252
+ }
3253
+ };
3254
+ var SimplePeerTransportProxyFactory = class {
3255
+ constructor() {
3256
+ this._connections = /* @__PURE__ */ new Set();
3257
+ }
3258
+ /**
3259
+ * Sets the current BridgeService to be used to open connections.
3260
+ * Calling this method will close any existing connections.
3261
+ */
3262
+ setBridgeService(bridgeService) {
3263
+ this._bridgeService = bridgeService;
3264
+ for (const connection of this._connections) {
3265
+ connection.forceClose();
3266
+ }
3267
+ return this;
3268
+ }
3269
+ createTransport(options) {
3270
+ (0, import_invariant12.invariant)(this._bridgeService, "SimplePeerTransportProxyFactory is not ready to open connections", {
3271
+ F: __dxlog_file14,
3272
+ L: 197,
3273
+ S: this,
3274
+ A: [
3275
+ "this._bridgeService",
3276
+ "'SimplePeerTransportProxyFactory is not ready to open connections'"
3277
+ ]
3278
+ });
3279
+ const transport = new SimplePeerTransportProxy({
3280
+ ...options,
3281
+ bridgeService: this._bridgeService
3282
+ });
3283
+ this._connections.add(transport);
3284
+ transport.closed.on(() => this._connections.delete(transport));
3285
+ return transport;
3286
+ }
3287
+ };
3288
+ var decodeError = (err) => {
3289
+ const message = typeof err === "string" ? err : err.message;
3290
+ if (message.includes("CONNECTION_RESET")) {
3291
+ return new import_protocols8.ConnectionResetError(message);
3292
+ } else if (message.includes("TIMEOUT")) {
3293
+ return new import_protocols8.TimeoutError(message);
3294
+ } else if (message.includes("PROTOCOL_ERROR")) {
3295
+ return new import_protocols8.ProtocolError(message);
3296
+ } else if (message.includes("CONNECTIVITY_ERROR")) {
3297
+ return new import_protocols8.ConnectivityError(message);
3298
+ } else if (message.includes("UNKNOWN_PROTOCOL_ERROR")) {
3299
+ return new import_protocols8.UnknownProtocolError(message);
3300
+ } else {
3301
+ return typeof err === "string" ? new Error(err) : err;
3302
+ }
3303
+ };
3304
+ function _ts_decorate5(decorators, target, key, desc) {
3305
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3306
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3307
+ r = Reflect.decorate(decorators, target, key, desc);
3308
+ else
3309
+ for (var i = decorators.length - 1; i >= 0; i--)
3310
+ if (d = decorators[i])
3311
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3312
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3313
+ }
3314
+ var __dxlog_file15 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/libdatachannel-transport.ts";
3315
+ var DATACHANNEL_LABEL = "dxos.mesh.transport";
3316
+ var MAX_BUFFERED_AMOUNT = 64 * 1024;
3317
+ var MAX_MESSAGE_SIZE = 64 * 1024;
3318
+ var LibDataChannelTransport = class {
3319
+ constructor(params) {
3320
+ this.params = params;
3321
+ this._closed = false;
3322
+ this.closed = new import_async11.Event();
3323
+ this._connected = false;
3324
+ this.connected = new import_async11.Event();
3325
+ this.errors = new import_debug7.ErrorStream();
3326
+ this._readyForCandidates = new import_async11.Trigger();
3327
+ this._writeCallback = null;
3328
+ this._peer = (async () => {
3329
+ const { RTCPeerConnection: PeerConnection } = await import("./datachannel-53JZPGFA.cjs");
3330
+ if (this._closed) {
3331
+ this.errors.raise(new Error("connection already closed"));
3332
+ }
3333
+ const peer = new PeerConnection(params.webrtcConfig);
3334
+ peer.onicecandidateerror = (event) => {
3335
+ import_log14.log.error("peer.onicecandidateerror", {
3336
+ event
3337
+ }, {
3338
+ F: __dxlog_file15,
3339
+ L: 53,
3340
+ S: this,
3341
+ C: (f, a) => f(...a)
3342
+ });
3343
+ };
3344
+ peer.onconnectionstatechange = (event) => {
3345
+ import_log14.log.debug("peer.onconnectionstatechange", {
3346
+ event,
3347
+ peerConnectionState: peer.connectionState,
3348
+ transportConnectionState: this._connected
3349
+ }, {
3350
+ F: __dxlog_file15,
3351
+ L: 57,
3352
+ S: this,
3353
+ C: (f, a) => f(...a)
3354
+ });
3355
+ };
3356
+ peer.onicecandidate = async (event) => {
3357
+ import_log14.log.debug("peer.onicecandidate", {
3358
+ event
3359
+ }, {
3360
+ F: __dxlog_file15,
3361
+ L: 66,
3362
+ S: this,
3363
+ C: (f, a) => f(...a)
3364
+ });
3365
+ if (event.candidate) {
3366
+ try {
3367
+ await params.sendSignal({
3368
+ payload: {
3369
+ data: {
3370
+ type: "candidate",
3371
+ candidate: {
3372
+ candidate: event.candidate.candidate,
3373
+ // these fields never seem to be not null, but connecting to Chrome doesn't work if they are
3374
+ sdpMLineIndex: event.candidate.sdpMLineIndex ?? 0,
3375
+ sdpMid: event.candidate.sdpMid ?? 0
3376
+ }
3377
+ }
3378
+ }
3379
+ });
3380
+ } catch (err) {
3381
+ import_log14.log.info("signaling errror", {
3382
+ err
3383
+ }, {
3384
+ F: __dxlog_file15,
3385
+ L: 83,
3386
+ S: this,
3387
+ C: (f, a) => f(...a)
3388
+ });
3389
+ }
3390
+ }
3391
+ };
3392
+ if (params.initiator) {
3393
+ peer.createOffer().then(async (offer) => {
3394
+ if (peer.connectionState !== "connecting") {
3395
+ import_log14.log.error("i am initiator but peer not in state connecting", {
3396
+ peer
3397
+ }, {
3398
+ F: __dxlog_file15,
3399
+ L: 92,
3400
+ S: this,
3401
+ C: (f, a) => f(...a)
3402
+ });
3403
+ this.errors.raise(new Error("invalid state: peer is initiator, but other peer not in state connecting"));
3404
+ }
3405
+ import_log14.log.debug(`im the initiator, creating offer, peer is in state ${peer.connectionState}`, {
3406
+ offer
3407
+ }, {
3408
+ F: __dxlog_file15,
3409
+ L: 95,
3410
+ S: this,
3411
+ C: (f, a) => f(...a)
3412
+ });
3413
+ await peer.setLocalDescription(offer);
3414
+ await params.sendSignal({
3415
+ payload: {
3416
+ data: {
3417
+ type: offer.type,
3418
+ sdp: offer.sdp
3419
+ }
3420
+ }
3421
+ });
3422
+ return offer;
3423
+ }).catch((err) => {
3424
+ this.errors.raise(err);
3425
+ });
3426
+ this.handleChannel(peer.createDataChannel(DATACHANNEL_LABEL));
3427
+ import_log14.log.debug("created data channel", void 0, {
3428
+ F: __dxlog_file15,
3429
+ L: 104,
3430
+ S: this,
3431
+ C: (f, a) => f(...a)
3432
+ });
3433
+ peer.ondatachannel = (event) => {
3434
+ this.errors.raise(new Error("got ondatachannel when i am the initiator?"));
3435
+ };
3436
+ } else {
3437
+ peer.ondatachannel = (event) => {
3438
+ import_log14.log.debug("peer.ondatachannel (non-initiator)", {
3439
+ event
3440
+ }, {
3441
+ F: __dxlog_file15,
3442
+ L: 110,
3443
+ S: this,
3444
+ C: (f, a) => f(...a)
3445
+ });
3446
+ if (event.channel.label !== DATACHANNEL_LABEL) {
3447
+ this.errors.raise(new Error(`unexpected channel label ${event.channel.label}`));
3448
+ }
3449
+ this.handleChannel(event.channel);
3450
+ };
3451
+ }
3452
+ return peer;
3453
+ })();
3454
+ }
3455
+ handleChannel(dataChannel) {
3456
+ this._channel = dataChannel;
3457
+ this._channel.onopen = () => {
3458
+ import_log14.log.debug("dataChannel.onopen", void 0, {
3459
+ F: __dxlog_file15,
3460
+ L: 126,
3461
+ S: this,
3462
+ C: (f, a) => f(...a)
3463
+ });
3464
+ const duplex = new import_stream.Duplex({
3465
+ read: () => {
3466
+ },
3467
+ write: async (chunk, encoding, callback) => {
3468
+ if (chunk.length > MAX_MESSAGE_SIZE) {
3469
+ this.errors.raise(new Error(`message too large: ${chunk.length} > ${MAX_MESSAGE_SIZE}`));
3470
+ }
3471
+ try {
3472
+ dataChannel.send(chunk);
3473
+ } catch (err) {
3474
+ this.errors.raise(err);
3475
+ await this._close();
3476
+ }
3477
+ if (this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {
3478
+ if (this._writeCallback !== null) {
3479
+ import_log14.log.error("consumer trying to write before we're ready for more data", void 0, {
3480
+ F: __dxlog_file15,
3481
+ L: 143,
3482
+ S: this,
3483
+ C: (f, a) => f(...a)
3484
+ });
3485
+ }
3486
+ this._writeCallback = callback;
3487
+ } else {
3488
+ callback();
3489
+ }
3490
+ }
3491
+ });
3492
+ duplex.pipe(this.params.stream).pipe(duplex);
3493
+ this._stream = duplex;
3494
+ this._connected = true;
3495
+ this.connected.emit();
3496
+ };
3497
+ this._channel.onerror = async (err) => {
3498
+ this.errors.raise(new Error("channel error: " + err.toString()));
3499
+ await this._close();
3500
+ };
3501
+ this._channel.onclose = async (err) => {
3502
+ import_log14.log.info("channel onclose", {
3503
+ err
3504
+ }, {
3505
+ F: __dxlog_file15,
3506
+ L: 163,
3507
+ S: this,
3508
+ C: (f, a) => f(...a)
3509
+ });
3510
+ await this._close();
3511
+ };
3512
+ this._channel.onmessage = (event) => {
3513
+ let data = event.data;
3514
+ if (data instanceof ArrayBuffer) {
3515
+ data = Buffer.from(data);
3516
+ }
3517
+ this._stream.push(data);
3518
+ };
3519
+ this._channel.onbufferedamountlow = () => {
3520
+ const cb = this._writeCallback;
3521
+ this._writeCallback = null;
3522
+ cb?.();
3523
+ };
3524
+ }
3525
+ async _close() {
3526
+ if (this._closed) {
3527
+ return;
3528
+ }
3529
+ await this._disconnectStreams();
3530
+ this._closed = true;
3531
+ this.closed.emit();
3532
+ }
3533
+ signal(signal) {
3534
+ this._peer.then(async (peer) => {
3535
+ const data = signal.payload.data;
3536
+ switch (data.type) {
3537
+ case "offer": {
3538
+ if ((await this._peer).connectionState !== "new") {
3539
+ import_log14.log.error("received offer but peer not in state new", {
3540
+ peer
3541
+ }, {
3542
+ F: __dxlog_file15,
3543
+ L: 198,
3544
+ S: this,
3545
+ C: (f, a) => f(...a)
3546
+ });
3547
+ this.errors.raise(new Error("invalid signalling state: received offer when peer is not in state new"));
3548
+ break;
3549
+ }
3550
+ try {
3551
+ await peer.setRemoteDescription({
3552
+ type: data.type,
3553
+ sdp: data.sdp
3554
+ });
3555
+ const answer = await peer.createAnswer();
3556
+ await peer.setLocalDescription(answer);
3557
+ await this.params.sendSignal({
3558
+ payload: {
3559
+ data: {
3560
+ type: answer.type,
3561
+ sdp: answer.sdp
3562
+ }
3563
+ }
3564
+ });
3565
+ this._readyForCandidates.wake();
3566
+ } catch (err) {
3567
+ import_log14.log.error("can't handle offer from signalling server", {
3568
+ err
3569
+ }, {
3570
+ F: __dxlog_file15,
3571
+ L: 209,
3572
+ S: this,
3573
+ C: (f, a) => f(...a)
3574
+ });
3575
+ this.errors.raise(new Error("error handling offer"));
3576
+ }
3577
+ break;
3578
+ }
3579
+ case "answer":
3580
+ try {
3581
+ await peer.setRemoteDescription({
3582
+ type: data.type,
3583
+ sdp: data.sdp
3584
+ });
3585
+ this._readyForCandidates.wake();
3586
+ } catch (err) {
3587
+ import_log14.log.error("can't handle answer from signalling server", {
3588
+ err
3589
+ }, {
3590
+ F: __dxlog_file15,
3591
+ L: 220,
3592
+ S: this,
3593
+ C: (f, a) => f(...a)
3594
+ });
3595
+ this.errors.raise(new Error("error handling answer"));
3596
+ }
3597
+ break;
3598
+ case "candidate":
3599
+ await this._readyForCandidates.wait();
3600
+ await peer.addIceCandidate({
3601
+ candidate: data.candidate.candidate
3602
+ });
3603
+ break;
3604
+ default:
3605
+ import_log14.log.error("unhandled signal type", {
3606
+ type: data.type,
3607
+ signal
3608
+ }, {
3609
+ F: __dxlog_file15,
3610
+ L: 231,
3611
+ S: this,
3612
+ C: (f, a) => f(...a)
3613
+ });
3614
+ this.errors.raise(new Error(`unhandled signal type ${data.type}`));
3615
+ }
3616
+ }).catch((err) => {
3617
+ import_log14.log.catch(err, void 0, {
3618
+ F: __dxlog_file15,
3619
+ L: 236,
3620
+ S: this,
3621
+ C: (f, a) => f(...a)
3622
+ });
3623
+ });
3624
+ }
3625
+ // TODO(nf): add classmethod to call node-datachannel.cleanup() when all instances have been destroyed?
3626
+ async destroy() {
3627
+ await this._close();
3628
+ }
3629
+ async _disconnectStreams() {
3630
+ this.params.stream.unpipe?.(this._stream)?.unpipe?.(this.params.stream);
3631
+ }
3632
+ };
3633
+ _ts_decorate5([
3634
+ import_async11.synchronized
3635
+ ], LibDataChannelTransport.prototype, "_close", null);
3636
+ var createLibDataChannelTransportFactory = (webrtcConfig) => ({
3637
+ createTransport: (params) => new LibDataChannelTransport({
3638
+ ...params,
3639
+ webrtcConfig
3640
+ })
3641
+ });
3642
+ var __dxlog_file16 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/tcp-transport.ts";
3643
+ var TcpTransportFactory = {
3644
+ createTransport: (params) => new TcpTransport(params)
3645
+ };
3646
+ var TcpTransport = class {
3647
+ constructor(options) {
3648
+ this.options = options;
3649
+ this._server = void 0;
3650
+ this._socket = void 0;
3651
+ this.closed = new import_async12.Event();
3652
+ this.connected = new import_async12.Event();
3653
+ this.errors = new import_debug8.ErrorStream();
3654
+ this._destroyed = false;
3655
+ this._connected = false;
3656
+ (0, import_log15.log)("creating", void 0, {
3657
+ F: __dxlog_file16,
3658
+ L: 34,
3659
+ S: this,
3660
+ C: (f, a) => f(...a)
3661
+ });
3662
+ if (this.options.initiator) {
3663
+ setTimeout(async () => {
3664
+ const { Server } = await import("node:net");
3665
+ this._server = new Server((socket) => {
3666
+ (0, import_log15.log)("new connection", void 0, {
3667
+ F: __dxlog_file16,
3668
+ L: 42,
3669
+ S: this,
3670
+ C: (f, a) => f(...a)
3671
+ });
3672
+ if (this._connected) {
3673
+ socket.destroy();
3674
+ }
3675
+ this._handleSocket(socket);
3676
+ });
3677
+ this._server.on("listening", () => {
3678
+ const { port } = this._server.address();
3679
+ (0, import_log15.log)("listening", {
3680
+ port
3681
+ }, {
3682
+ F: __dxlog_file16,
3683
+ L: 51,
3684
+ S: this,
3685
+ C: (f, a) => f(...a)
3686
+ });
3687
+ void this.options.sendSignal({
3688
+ payload: {
3689
+ port
3690
+ }
3691
+ }).catch((err) => {
3692
+ if (!this._destroyed) {
3693
+ this.errors.raise(err);
3694
+ }
3695
+ });
3696
+ });
3697
+ this._server.on("error", (err) => {
3698
+ this.errors.raise(err);
3699
+ });
3700
+ this._server.listen(0);
3701
+ });
3702
+ }
3703
+ }
3704
+ async destroy() {
3705
+ (0, import_log15.log)("closing", void 0, {
3706
+ F: __dxlog_file16,
3707
+ L: 72,
3708
+ S: this,
3709
+ C: (f, a) => f(...a)
3710
+ });
3711
+ this._socket?.destroy();
3712
+ this._server?.close();
3713
+ this._destroyed = true;
3714
+ }
3715
+ signal({ payload }) {
3716
+ (0, import_log15.log)("received signal", {
3717
+ payload
3718
+ }, {
3719
+ F: __dxlog_file16,
3720
+ L: 80,
3721
+ S: this,
3722
+ C: (f, a) => f(...a)
3723
+ });
3724
+ if (this.options.initiator || this._connected) {
3725
+ return;
3726
+ }
3727
+ const socket = new import_node_net.Socket();
3728
+ this._handleSocket(socket);
3729
+ socket.connect({
3730
+ port: payload.port,
3731
+ host: "localhost"
3732
+ });
3733
+ }
3734
+ _handleSocket(socket) {
3735
+ (0, import_log15.log)("handling socket", {
3736
+ remotePort: socket.remotePort,
3737
+ localPort: socket.localPort
3738
+ }, {
3739
+ F: __dxlog_file16,
3740
+ L: 91,
3741
+ S: this,
3742
+ C: (f, a) => f(...a)
3743
+ });
3744
+ this._socket = socket;
3745
+ this.connected.emit();
3746
+ this.options.stream.pipe(this._socket).pipe(this.options.stream);
3747
+ this._socket.on("connect", () => {
3748
+ (0, import_log15.log)("connected to", {
3749
+ port: this._socket?.remotePort
3750
+ }, {
3751
+ F: __dxlog_file16,
3752
+ L: 97,
3753
+ S: this,
3754
+ C: (f, a) => f(...a)
3755
+ });
3756
+ this._connected = true;
3757
+ });
3758
+ this._socket.on("error", (err) => {
3759
+ this.errors.raise(err);
3760
+ });
3761
+ this._socket.on("close", () => {
3762
+ this.closed.emit();
3763
+ });
3764
+ }
3765
+ };
3766
+ var createTeleportProtocolFactory = (onConnection) => {
3767
+ return (params) => {
3768
+ const teleport = new import_teleport.Teleport(params);
3769
+ return {
3770
+ stream: teleport.stream,
3771
+ open: async () => {
3772
+ await teleport.open();
3773
+ await onConnection(teleport);
3774
+ },
3775
+ close: async () => {
3776
+ await teleport.close();
3777
+ },
3778
+ abort: async () => {
3779
+ await teleport.abort();
3780
+ }
3781
+ };
3782
+ };
3783
+ };
3784
+ // Annotate the CommonJS export names for ESM import in node:
3785
+ 0 && (module.exports = {
3786
+ Connection,
3787
+ ConnectionLimiter,
3788
+ ConnectionLog,
3789
+ ConnectionState,
3790
+ EventType,
3791
+ FullyConnectedTopology,
3792
+ LibDataChannelTransport,
3793
+ MAX_CONCURRENT_INITIATING_CONNECTIONS,
3794
+ MMSTTopology,
3795
+ MemoryTransport,
3796
+ MemoryTransportFactory,
3797
+ NetworkManager,
3798
+ SimplePeerTransport,
3799
+ SimplePeerTransportProxy,
3800
+ SimplePeerTransportProxyFactory,
3801
+ SimplePeerTransportService,
3802
+ StarTopology,
3803
+ Swarm,
3804
+ SwarmMapper,
3805
+ SwarmMessenger,
3806
+ TcpTransport,
3807
+ TcpTransportFactory,
3808
+ TransportKind,
3809
+ createLibDataChannelTransportFactory,
3810
+ createSimplePeerTransportFactory,
3811
+ createTeleportProtocolFactory
3812
+ });
3813
+ //# sourceMappingURL=chunk-6AD7QA4X.cjs.map