@dxos/network-manager 0.1.56-main.d0c207f → 0.1.56-main.d36ce19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/lib/browser/{chunk-MIYEP22D.mjs → chunk-BVDMMHEG.mjs} +889 -371
  2. package/dist/lib/browser/chunk-BVDMMHEG.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +5 -1
  4. package/dist/lib/browser/meta.json +1 -1
  5. package/dist/lib/browser/testing/index.mjs +23 -16
  6. package/dist/lib/browser/testing/index.mjs.map +3 -3
  7. package/dist/lib/node/index.cjs +908 -388
  8. package/dist/lib/node/index.cjs.map +4 -4
  9. package/dist/lib/node/meta.json +1 -1
  10. package/dist/lib/node/testing/index.cjs +859 -392
  11. package/dist/lib/node/testing/index.cjs.map +4 -4
  12. package/dist/types/src/connection-log.d.ts.map +1 -1
  13. package/dist/types/src/network-manager.d.ts +1 -1
  14. package/dist/types/src/network-manager.d.ts.map +1 -1
  15. package/dist/types/src/signal/swarm-messenger.d.ts +1 -1
  16. package/dist/types/src/signal/swarm-messenger.d.ts.map +1 -1
  17. package/dist/types/src/swarm/connection-limiter.d.ts +28 -0
  18. package/dist/types/src/swarm/connection-limiter.d.ts.map +1 -0
  19. package/dist/types/src/swarm/connection-limiter.test.d.ts +2 -0
  20. package/dist/types/src/swarm/connection-limiter.test.d.ts.map +1 -0
  21. package/dist/types/src/swarm/connection.d.ts +3 -2
  22. package/dist/types/src/swarm/connection.d.ts.map +1 -1
  23. package/dist/types/src/swarm/connection.test.d.ts +2 -0
  24. package/dist/types/src/swarm/connection.test.d.ts.map +1 -0
  25. package/dist/types/src/swarm/index.d.ts +1 -0
  26. package/dist/types/src/swarm/index.d.ts.map +1 -1
  27. package/dist/types/src/swarm/peer.d.ts +4 -2
  28. package/dist/types/src/swarm/peer.d.ts.map +1 -1
  29. package/dist/types/src/swarm/swarm.d.ts +3 -1
  30. package/dist/types/src/swarm/swarm.d.ts.map +1 -1
  31. package/dist/types/src/testing/test-builder.d.ts +4 -3
  32. package/dist/types/src/testing/test-builder.d.ts.map +1 -1
  33. package/dist/types/src/testing/test-wire-protocol.d.ts +13 -2
  34. package/dist/types/src/testing/test-wire-protocol.d.ts.map +1 -1
  35. package/dist/types/src/topology/fully-connected-topology.d.ts.map +1 -1
  36. package/dist/types/src/topology/star-topology.d.ts.map +1 -1
  37. package/dist/types/src/transport/memory-transport.d.ts.map +1 -1
  38. package/dist/types/src/transport/webrtc-transport-proxy.d.ts +1 -1
  39. package/dist/types/src/transport/webrtc-transport-proxy.d.ts.map +1 -1
  40. package/dist/types/src/transport/webrtc-transport-service.d.ts.map +1 -1
  41. package/dist/types/src/transport/webrtc-transport.d.ts +3 -3
  42. package/dist/types/src/transport/webrtc-transport.d.ts.map +1 -1
  43. package/package.json +18 -18
  44. package/src/connection-log.ts +2 -0
  45. package/src/network-manager.ts +19 -6
  46. package/src/signal/swarm-messenger.ts +3 -4
  47. package/src/swarm/connection-limiter.test.ts +44 -0
  48. package/src/swarm/connection-limiter.ts +72 -0
  49. package/src/swarm/connection.test.ts +72 -0
  50. package/src/swarm/connection.ts +26 -6
  51. package/src/swarm/index.ts +1 -0
  52. package/src/swarm/peer.ts +53 -14
  53. package/src/swarm/swarm.test.ts +140 -90
  54. package/src/swarm/swarm.ts +9 -8
  55. package/src/testing/test-builder.ts +9 -5
  56. package/src/testing/test-wire-protocol.ts +22 -2
  57. package/src/tests/memory-transport.test.ts +1 -1
  58. package/src/topology/fully-connected-topology.ts +1 -2
  59. package/src/topology/mmst-topology.ts +1 -1
  60. package/src/topology/star-topology.ts +1 -2
  61. package/src/transport/memory-transport.ts +1 -1
  62. package/src/transport/webrtc-transport-proxy.ts +18 -16
  63. package/src/transport/webrtc-transport-service.ts +31 -8
  64. package/src/transport/webrtc-transport.ts +21 -7
  65. package/dist/lib/browser/chunk-MIYEP22D.mjs.map +0 -7
@@ -4,15 +4,15 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
4
4
  }) : x)(function(x) {
5
5
  if (typeof require !== "undefined")
6
6
  return require.apply(this, arguments);
7
- throw new Error('Dynamic require of "' + x + '" is not supported');
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
8
  });
9
9
 
10
10
  // packages/core/mesh/network-manager/src/swarm/connection.ts
11
- import invariant from "tiny-invariant";
12
11
  import { DeferredTask, Event, sleep, synchronized } from "@dxos/async";
13
12
  import { Context, cancelWithContext } from "@dxos/context";
14
13
  import { ErrorStream } from "@dxos/debug";
15
14
  import { CancelledError } from "@dxos/errors";
15
+ import { invariant } from "@dxos/invariant";
16
16
  import { PublicKey } from "@dxos/keys";
17
17
  import { log } from "@dxos/log";
18
18
  import { trace } from "@dxos/protocols";
@@ -84,6 +84,18 @@ var Connection = class {
84
84
  await this._flushSignalBuffer();
85
85
  });
86
86
  this._signallingDelay = STARTING_SIGNALLING_DELAY;
87
+ log.trace("dxos.mesh.connection.construct", {
88
+ sessionId: this.sessionId,
89
+ topic: this.topic,
90
+ localPeerId: this.ownId,
91
+ remotePeerId: this.remoteId,
92
+ initiator: this.initiator
93
+ }, {
94
+ F: __dxlog_file,
95
+ L: 96,
96
+ S: this,
97
+ C: (f, a) => f(...a)
98
+ });
87
99
  }
88
100
  get state() {
89
101
  return this._state;
@@ -97,14 +109,33 @@ var Connection = class {
97
109
  /**
98
110
  * Create an underlying transport and prepares it for the connection.
99
111
  */
100
- // TODO(burdon): Make async?
101
- openConnection() {
102
- invariant(this._state === ConnectionState.INITIAL, "Invalid state.");
112
+ async openConnection() {
113
+ invariant(this._state === ConnectionState.INITIAL, "Invalid state.", {
114
+ F: __dxlog_file,
115
+ L: 121,
116
+ S: this,
117
+ A: [
118
+ "this._state === ConnectionState.INITIAL",
119
+ "'Invalid state.'"
120
+ ]
121
+ });
103
122
  log.trace("dxos.mesh.connection.open-connection", trace.begin({
104
123
  id: this._instanceId
105
124
  }), {
106
125
  F: __dxlog_file,
107
- L: 115,
126
+ L: 122,
127
+ S: this,
128
+ C: (f, a) => f(...a)
129
+ });
130
+ log.trace("dxos.mesh.connection.open", {
131
+ sessionId: this.sessionId,
132
+ topic: this.topic,
133
+ localPeerId: this.ownId,
134
+ remotePeerId: this.remoteId,
135
+ initiator: this.initiator
136
+ }, {
137
+ F: __dxlog_file,
138
+ L: 123,
108
139
  S: this,
109
140
  C: (f, a) => f(...a)
110
141
  });
@@ -115,13 +146,21 @@ var Connection = class {
115
146
  this._protocol.stream.on("close", () => {
116
147
  log("protocol stream closed", void 0, {
117
148
  F: __dxlog_file,
118
- L: 126,
149
+ L: 140,
119
150
  S: this,
120
151
  C: (f, a) => f(...a)
121
152
  });
122
153
  this.close().catch((err) => this.errors.raise(err));
123
154
  });
124
- invariant(!this._transport);
155
+ invariant(!this._transport, void 0, {
156
+ F: __dxlog_file,
157
+ L: 144,
158
+ S: this,
159
+ A: [
160
+ "!this._transport",
161
+ ""
162
+ ]
163
+ });
125
164
  this._transport = this._transportFactory.createTransport({
126
165
  initiator: this.initiator,
127
166
  stream: this._protocol.stream,
@@ -135,6 +174,9 @@ var Connection = class {
135
174
  this.close().catch((err) => this.errors.raise(err));
136
175
  });
137
176
  this._transport.errors.handle((err) => {
177
+ if (!this.closeReason) {
178
+ this.closeReason = err?.message;
179
+ }
138
180
  if (this._state !== ConnectionState.CLOSED && this._state !== ConnectionState.CLOSING) {
139
181
  this.errors.raise(err);
140
182
  }
@@ -147,13 +189,15 @@ var Connection = class {
147
189
  id: this._instanceId
148
190
  }), {
149
191
  F: __dxlog_file,
150
- L: 159,
192
+ L: 176,
151
193
  S: this,
152
194
  C: (f, a) => f(...a)
153
195
  });
154
196
  }
155
- async close() {
156
- var _a;
197
+ async close(err) {
198
+ if (!this.closeReason) {
199
+ this.closeReason = err?.message;
200
+ }
157
201
  if (this._state === ConnectionState.CLOSED) {
158
202
  return;
159
203
  }
@@ -163,26 +207,26 @@ var Connection = class {
163
207
  peerId: this.ownId
164
208
  }, {
165
209
  F: __dxlog_file,
166
- L: 171,
210
+ L: 191,
167
211
  S: this,
168
212
  C: (f, a) => f(...a)
169
213
  });
170
214
  try {
171
215
  await this._protocol.destroy();
172
- } catch (err) {
173
- log.catch(err, void 0, {
216
+ } catch (err2) {
217
+ log.catch(err2, void 0, {
174
218
  F: __dxlog_file,
175
- L: 177,
219
+ L: 197,
176
220
  S: this,
177
221
  C: (f, a) => f(...a)
178
222
  });
179
223
  }
180
224
  try {
181
- await ((_a = this._transport) == null ? void 0 : _a.destroy());
182
- } catch (err) {
183
- log.catch(err, void 0, {
225
+ await this._transport?.destroy();
226
+ } catch (err2) {
227
+ log.catch(err2, void 0, {
184
228
  F: __dxlog_file,
185
- L: 184,
229
+ L: 204,
186
230
  S: this,
187
231
  C: (f, a) => f(...a)
188
232
  });
@@ -191,7 +235,7 @@ var Connection = class {
191
235
  peerId: this.ownId
192
236
  }, {
193
237
  F: __dxlog_file,
194
- L: 187,
238
+ L: 207,
195
239
  S: this,
196
240
  C: (f, a) => f(...a)
197
241
  });
@@ -231,7 +275,7 @@ var Connection = class {
231
275
  err
232
276
  }, {
233
277
  F: __dxlog_file,
234
- L: 221,
278
+ L: 241,
235
279
  S: this,
236
280
  C: (f, a) => f(...a)
237
281
  });
@@ -242,21 +286,52 @@ var Connection = class {
242
286
  * Receive a signal from the remote peer.
243
287
  */
244
288
  async signal(msg) {
245
- var _a, _b, _c;
246
- invariant(msg.sessionId);
289
+ invariant(msg.sessionId, void 0, {
290
+ F: __dxlog_file,
291
+ L: 250,
292
+ S: this,
293
+ A: [
294
+ "msg.sessionId",
295
+ ""
296
+ ]
297
+ });
247
298
  if (!msg.sessionId.equals(this.sessionId)) {
248
299
  log("dropping signal for incorrect session id", void 0, {
249
300
  F: __dxlog_file,
250
- L: 232,
301
+ L: 252,
251
302
  S: this,
252
303
  C: (f, a) => f(...a)
253
304
  });
254
305
  return;
255
306
  }
256
- invariant(msg.data.signal || msg.data.signalBatch);
257
- invariant((_a = msg.author) == null ? void 0 : _a.equals(this.remoteId));
258
- invariant((_b = msg.recipient) == null ? void 0 : _b.equals(this.ownId));
259
- const signals = msg.data.signalBatch ? (_c = msg.data.signalBatch.signals) != null ? _c : [] : [
307
+ invariant(msg.data.signal || msg.data.signalBatch, void 0, {
308
+ F: __dxlog_file,
309
+ L: 255,
310
+ S: this,
311
+ A: [
312
+ "msg.data.signal || msg.data.signalBatch",
313
+ ""
314
+ ]
315
+ });
316
+ invariant(msg.author?.equals(this.remoteId), void 0, {
317
+ F: __dxlog_file,
318
+ L: 256,
319
+ S: this,
320
+ A: [
321
+ "msg.author?.equals(this.remoteId)",
322
+ ""
323
+ ]
324
+ });
325
+ invariant(msg.recipient?.equals(this.ownId), void 0, {
326
+ F: __dxlog_file,
327
+ L: 257,
328
+ S: this,
329
+ A: [
330
+ "msg.recipient?.equals(this.ownId)",
331
+ ""
332
+ ]
333
+ });
334
+ const signals = msg.data.signalBatch ? msg.data.signalBatch.signals ?? [] : [
260
335
  msg.data.signal
261
336
  ];
262
337
  for (const signal of signals) {
@@ -270,20 +345,28 @@ var Connection = class {
270
345
  msg: msg.data
271
346
  }, {
272
347
  F: __dxlog_file,
273
- L: 246,
348
+ L: 266,
274
349
  S: this,
275
350
  C: (f, a) => f(...a)
276
351
  });
277
352
  this._incomingSignalBuffer.push(signal);
278
353
  } else {
279
- invariant(this._transport, "Connection not ready to accept signals.");
354
+ invariant(this._transport, "Connection not ready to accept signals.", {
355
+ F: __dxlog_file,
356
+ L: 269,
357
+ S: this,
358
+ A: [
359
+ "this._transport",
360
+ "'Connection not ready to accept signals.'"
361
+ ]
362
+ });
280
363
  log("received signal", {
281
364
  peerId: this.ownId,
282
365
  remoteId: this.remoteId,
283
366
  msg: msg.data
284
367
  }, {
285
368
  F: __dxlog_file,
286
- L: 250,
369
+ L: 270,
287
370
  S: this,
288
371
  C: (f, a) => f(...a)
289
372
  });
@@ -298,11 +381,19 @@ var Connection = class {
298
381
  peerId: this.ownId
299
382
  }, {
300
383
  F: __dxlog_file,
301
- L: 257,
384
+ L: 277,
302
385
  S: this,
303
386
  C: (f, a) => f(...a)
304
387
  });
305
- invariant(state !== this._state, "Already in this state.");
388
+ invariant(state !== this._state, "Already in this state.", {
389
+ F: __dxlog_file,
390
+ L: 278,
391
+ S: this,
392
+ A: [
393
+ "state !== this._state",
394
+ "'Already in this state.'"
395
+ ]
396
+ });
306
397
  this._state = state;
307
398
  this.stateChanged.emit(state);
308
399
  }
@@ -312,8 +403,8 @@ _ts_decorate([
312
403
  ], Connection.prototype, "close", null);
313
404
 
314
405
  // packages/core/mesh/network-manager/src/signal/swarm-messenger.ts
315
- import invariant2 from "tiny-invariant";
316
406
  import { Context as Context2 } from "@dxos/context";
407
+ import { invariant as invariant2 } from "@dxos/invariant";
317
408
  import { PublicKey as PublicKey2 } from "@dxos/keys";
318
409
  import { log as log2 } from "@dxos/log";
319
410
  import { schema } from "@dxos/protocols";
@@ -330,7 +421,6 @@ var SwarmMessenger = class {
330
421
  this._topic = topic;
331
422
  }
332
423
  async receiveMessage({ author, recipient, payload }) {
333
- var _a, _b, _c, _d;
334
424
  if (payload.type_url !== "dxos.mesh.swarm.SwarmMessage") {
335
425
  return;
336
426
  }
@@ -344,25 +434,25 @@ var SwarmMessenger = class {
344
434
  msg: message
345
435
  }, {
346
436
  F: __dxlog_file2,
347
- L: 70,
437
+ L: 69,
348
438
  S: this,
349
439
  C: (f, a) => f(...a)
350
440
  });
351
- if ((_a = message.data) == null ? void 0 : _a.offer) {
441
+ if (message.data?.offer) {
352
442
  await this._handleOffer({
353
443
  author,
354
444
  recipient,
355
445
  message
356
446
  });
357
- } else if ((_b = message.data) == null ? void 0 : _b.answer) {
447
+ } else if (message.data?.answer) {
358
448
  await this._resolveAnswers(message);
359
- } else if ((_c = message.data) == null ? void 0 : _c.signal) {
449
+ } else if (message.data?.signal) {
360
450
  await this._handleSignal({
361
451
  author,
362
452
  recipient,
363
453
  message
364
454
  });
365
- } else if ((_d = message.data) == null ? void 0 : _d.signalBatch) {
455
+ } else if (message.data?.signalBatch) {
366
456
  await this._handleSignal({
367
457
  author,
368
458
  recipient,
@@ -373,15 +463,22 @@ var SwarmMessenger = class {
373
463
  message
374
464
  }, {
375
465
  F: __dxlog_file2,
376
- L: 81,
466
+ L: 80,
377
467
  S: this,
378
468
  C: (f, a) => f(...a)
379
469
  });
380
470
  }
381
471
  }
382
472
  async signal(message) {
383
- var _a, _b;
384
- invariant2(((_a = message.data) == null ? void 0 : _a.signal) || ((_b = message.data) == null ? void 0 : _b.signalBatch), "Invalid message");
473
+ invariant2(message.data?.signal || message.data?.signalBatch, "Invalid message", {
474
+ F: __dxlog_file2,
475
+ L: 85,
476
+ S: this,
477
+ A: [
478
+ "message.data?.signal || message.data?.signalBatch",
479
+ "'Invalid message'"
480
+ ]
481
+ });
385
482
  await this._sendReliableMessage({
386
483
  author: message.author,
387
484
  recipient: message.recipient,
@@ -405,11 +502,10 @@ var SwarmMessenger = class {
405
502
  });
406
503
  }
407
504
  async _sendReliableMessage({ author, recipient, message }) {
408
- var _a;
409
505
  const networkMessage = {
410
506
  ...message,
411
507
  // Setting unique message_id if it not specified yet.
412
- messageId: (_a = message.messageId) != null ? _a : PublicKey2.random()
508
+ messageId: message.messageId ?? PublicKey2.random()
413
509
  };
414
510
  log2("sending", {
415
511
  from: author,
@@ -417,7 +513,7 @@ var SwarmMessenger = class {
417
513
  msg: networkMessage
418
514
  }, {
419
515
  F: __dxlog_file2,
420
- L: 124,
516
+ L: 123,
421
517
  S: this,
422
518
  C: (f, a) => f(...a)
423
519
  });
@@ -431,17 +527,32 @@ var SwarmMessenger = class {
431
527
  });
432
528
  }
433
529
  async _resolveAnswers(message) {
434
- var _a, _b, _c;
435
- invariant2((_b = (_a = message.data) == null ? void 0 : _a.answer) == null ? void 0 : _b.offerMessageId, "No offerMessageId");
530
+ invariant2(message.data?.answer?.offerMessageId, "No offerMessageId", {
531
+ F: __dxlog_file2,
532
+ L: 135,
533
+ S: this,
534
+ A: [
535
+ "message.data?.answer?.offerMessageId",
536
+ "'No offerMessageId'"
537
+ ]
538
+ });
436
539
  const offerRecord = this._offerRecords.get(message.data.answer.offerMessageId);
437
540
  if (offerRecord) {
438
541
  this._offerRecords.delete(message.data.answer.offerMessageId);
439
- invariant2((_c = message.data) == null ? void 0 : _c.answer, "No answer");
542
+ invariant2(message.data?.answer, "No answer", {
543
+ F: __dxlog_file2,
544
+ L: 139,
545
+ S: this,
546
+ A: [
547
+ "message.data?.answer",
548
+ "'No answer'"
549
+ ]
550
+ });
440
551
  log2("resolving", {
441
552
  answer: message.data.answer
442
553
  }, {
443
554
  F: __dxlog_file2,
444
- L: 141,
555
+ L: 140,
445
556
  S: this,
446
557
  C: (f, a) => f(...a)
447
558
  });
@@ -449,7 +560,15 @@ var SwarmMessenger = class {
449
560
  }
450
561
  }
451
562
  async _handleOffer({ author, recipient, message }) {
452
- invariant2(message.data.offer, "No offer");
563
+ invariant2(message.data.offer, "No offer", {
564
+ F: __dxlog_file2,
565
+ L: 154,
566
+ S: this,
567
+ A: [
568
+ "message.data.offer",
569
+ "'No offer'"
570
+ ]
571
+ });
453
572
  const offerMessage = {
454
573
  author,
455
574
  recipient,
@@ -477,15 +596,31 @@ var SwarmMessenger = class {
477
596
  err
478
597
  }, {
479
598
  F: __dxlog_file2,
480
- L: 175,
599
+ L: 174,
481
600
  S: this,
482
601
  C: (f, a) => f(...a)
483
602
  });
484
603
  }
485
604
  }
486
605
  async _handleSignal({ author, recipient, message }) {
487
- invariant2(message.messageId);
488
- invariant2(message.data.signal || message.data.signalBatch, "Invalid message");
606
+ invariant2(message.messageId, void 0, {
607
+ F: __dxlog_file2,
608
+ L: 187,
609
+ S: this,
610
+ A: [
611
+ "message.messageId",
612
+ ""
613
+ ]
614
+ });
615
+ invariant2(message.data.signal || message.data.signalBatch, "Invalid message", {
616
+ F: __dxlog_file2,
617
+ L: 188,
618
+ S: this,
619
+ A: [
620
+ "message.data.signal || message.data.signalBatch",
621
+ "'Invalid message'"
622
+ ]
623
+ });
489
624
  const signalMessage = {
490
625
  author,
491
626
  recipient,
@@ -500,19 +635,20 @@ var SwarmMessenger = class {
500
635
  };
501
636
 
502
637
  // packages/core/mesh/network-manager/src/swarm/swarm.ts
503
- import invariant4 from "tiny-invariant";
504
638
  import { Event as Event2, scheduleTask as scheduleTask2, sleep as sleep2, synchronized as synchronized3 } from "@dxos/async";
505
639
  import { Context as Context4 } from "@dxos/context";
506
640
  import { ErrorStream as ErrorStream2 } from "@dxos/debug";
641
+ import { invariant as invariant4 } from "@dxos/invariant";
507
642
  import { PublicKey as PublicKey4 } from "@dxos/keys";
508
643
  import { log as log4, logInfo } from "@dxos/log";
509
644
  import { trace as trace2 } from "@dxos/protocols";
510
645
  import { ComplexMap as ComplexMap2, isNotNullOrUndefined } from "@dxos/util";
511
646
 
512
647
  // packages/core/mesh/network-manager/src/swarm/peer.ts
513
- import invariant3 from "tiny-invariant";
514
648
  import { scheduleTask, synchronized as synchronized2 } from "@dxos/async";
515
649
  import { Context as Context3 } from "@dxos/context";
650
+ import { CancelledError as CancelledError2 } from "@dxos/errors";
651
+ import { invariant as invariant3 } from "@dxos/invariant";
516
652
  import { PublicKey as PublicKey3 } from "@dxos/keys";
517
653
  import { log as log3 } from "@dxos/log";
518
654
  function _ts_decorate2(decorators, target, key, desc) {
@@ -528,13 +664,15 @@ function _ts_decorate2(decorators, target, key, desc) {
528
664
  var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/peer.ts";
529
665
  var CONNECTION_COUNTS_STABLE_AFTER = 5e3;
530
666
  var Peer = class {
531
- constructor(id, topic, localPeerId, _signalMessaging, _protocolProvider, _transportFactory, _callbacks) {
667
+ // TODO(burdon): Convert to map?
668
+ constructor(id, topic, localPeerId, _signalMessaging, _protocolProvider, _transportFactory, _connectionLimiter, _callbacks) {
532
669
  this.id = id;
533
670
  this.topic = topic;
534
671
  this.localPeerId = localPeerId;
535
672
  this._signalMessaging = _signalMessaging;
536
673
  this._protocolProvider = _protocolProvider;
537
674
  this._transportFactory = _transportFactory;
675
+ this._connectionLimiter = _connectionLimiter;
538
676
  this._callbacks = _callbacks;
539
677
  this._availableAfter = 0;
540
678
  this.availableToConnect = true;
@@ -549,18 +687,19 @@ var Peer = class {
549
687
  const remoteId = message.author;
550
688
  if (this.connection || this.initiating) {
551
689
  if (remoteId.toHex() < this.localPeerId.toHex()) {
552
- log3("closing local connection and accepting remote peer's offer", {
553
- id: this.id,
690
+ log3("close local connection", {
691
+ localPeerId: this.id,
554
692
  topic: this.topic,
555
- peerId: this.localPeerId
693
+ remotePeerId: this.localPeerId,
694
+ sessionId: this.connection?.sessionId
556
695
  }, {
557
696
  F: __dxlog_file3,
558
- L: 105,
697
+ L: 108,
559
698
  S: this,
560
699
  C: (f, a) => f(...a)
561
700
  });
562
701
  if (this.connection) {
563
- await this.closeConnection();
702
+ await this.closeConnection(new Error("Connection displaced by remote initiator."));
564
703
  }
565
704
  } else {
566
705
  return {
@@ -570,23 +709,34 @@ var Peer = class {
570
709
  }
571
710
  if (await this._callbacks.onOffer(remoteId)) {
572
711
  if (!this.connection) {
573
- invariant3(message.sessionId);
712
+ invariant3(message.sessionId, void 0, {
713
+ F: __dxlog_file3,
714
+ L: 128,
715
+ S: this,
716
+ A: [
717
+ "message.sessionId",
718
+ ""
719
+ ]
720
+ });
574
721
  const connection = this._createConnection(false, message.sessionId);
575
722
  try {
576
- connection.openConnection();
723
+ await this._connectionLimiter.connecting(message.sessionId);
724
+ await connection.openConnection();
577
725
  } catch (err) {
578
- log3.warn("connection error", {
579
- topic: this.topic,
580
- peerId: this.localPeerId,
581
- remoteId: this.id,
582
- err
583
- }, {
584
- F: __dxlog_file3,
585
- L: 129,
586
- S: this,
587
- C: (f, a) => f(...a)
588
- });
589
- await this.closeConnection();
726
+ if (!(err instanceof CancelledError2)) {
727
+ log3.warn("connection error", {
728
+ topic: this.topic,
729
+ peerId: this.localPeerId,
730
+ remoteId: this.id,
731
+ err
732
+ }, {
733
+ F: __dxlog_file3,
734
+ L: 136,
735
+ S: this,
736
+ C: (f, a) => f(...a)
737
+ });
738
+ }
739
+ await this.closeConnection(err);
590
740
  }
591
741
  return {
592
742
  accept: true
@@ -601,8 +751,24 @@ var Peer = class {
601
751
  * Initiate a connection to the remote peer.
602
752
  */
603
753
  async initiateConnection() {
604
- invariant3(!this.initiating, "Initiation in progress.");
605
- invariant3(!this.connection, "Already connected.");
754
+ invariant3(!this.initiating, "Initiation in progress.", {
755
+ F: __dxlog_file3,
756
+ L: 153,
757
+ S: this,
758
+ A: [
759
+ "!this.initiating",
760
+ "'Initiation in progress.'"
761
+ ]
762
+ });
763
+ invariant3(!this.connection, "Already connected.", {
764
+ F: __dxlog_file3,
765
+ L: 154,
766
+ S: this,
767
+ A: [
768
+ "!this.connection",
769
+ "'Already connected.'"
770
+ ]
771
+ });
606
772
  const sessionId = PublicKey3.random();
607
773
  log3("initiating...", {
608
774
  id: this.id,
@@ -611,13 +777,14 @@ var Peer = class {
611
777
  sessionId
612
778
  }, {
613
779
  F: __dxlog_file3,
614
- L: 147,
780
+ L: 156,
615
781
  S: this,
616
782
  C: (f, a) => f(...a)
617
783
  });
618
784
  const connection = this._createConnection(true, sessionId);
619
785
  this.initiating = true;
620
786
  try {
787
+ await this._connectionLimiter.connecting(sessionId);
621
788
  const answer = await this._signalMessaging.offer({
622
789
  author: this.localPeerId,
623
790
  recipient: this.id,
@@ -634,14 +801,14 @@ var Peer = class {
634
801
  remoteId: this.id
635
802
  }, {
636
803
  F: __dxlog_file3,
637
- L: 159,
804
+ L: 171,
638
805
  S: this,
639
806
  C: (f, a) => f(...a)
640
807
  });
641
808
  if (connection.state !== ConnectionState.INITIAL) {
642
809
  log3("ignoring response", void 0, {
643
810
  F: __dxlog_file3,
644
- L: 161,
811
+ L: 173,
645
812
  S: this,
646
813
  C: (f, a) => f(...a)
647
814
  });
@@ -651,7 +818,7 @@ var Peer = class {
651
818
  this._callbacks.onRejected();
652
819
  return;
653
820
  }
654
- connection.openConnection();
821
+ await connection.openConnection();
655
822
  this._callbacks.onAccepted();
656
823
  } catch (err) {
657
824
  log3("initiation error", {
@@ -661,11 +828,11 @@ var Peer = class {
661
828
  remoteId: this.id
662
829
  }, {
663
830
  F: __dxlog_file3,
664
- L: 172,
831
+ L: 184,
665
832
  S: this,
666
833
  C: (f, a) => f(...a)
667
834
  });
668
- await this.closeConnection();
835
+ await this.closeConnection(err);
669
836
  throw err;
670
837
  } finally {
671
838
  this.initiating = false;
@@ -676,7 +843,6 @@ var Peer = class {
676
843
  * Either we're initiating a connection or creating one in response to an offer from the other peer.
677
844
  */
678
845
  _createConnection(initiator, sessionId) {
679
- var _a;
680
846
  log3("creating connection", {
681
847
  topic: this.topic,
682
848
  peerId: this.localPeerId,
@@ -685,11 +851,19 @@ var Peer = class {
685
851
  sessionId
686
852
  }, {
687
853
  F: __dxlog_file3,
688
- L: 186,
854
+ L: 198,
689
855
  S: this,
690
856
  C: (f, a) => f(...a)
691
857
  });
692
- invariant3(!this.connection, "Already connected.");
858
+ invariant3(!this.connection, "Already connected.", {
859
+ F: __dxlog_file3,
860
+ L: 205,
861
+ S: this,
862
+ A: [
863
+ "!this.connection",
864
+ "'Already connected.'"
865
+ ]
866
+ });
693
867
  const connection = new Connection(
694
868
  this.topic,
695
869
  this.localPeerId,
@@ -707,7 +881,7 @@ var Peer = class {
707
881
  this._transportFactory
708
882
  );
709
883
  this._callbacks.onInitiated(connection);
710
- void ((_a = this._connectionCtx) == null ? void 0 : _a.dispose());
884
+ void this._connectionCtx?.dispose();
711
885
  this._connectionCtx = this._ctx.derive();
712
886
  connection.stateChanged.on((state) => {
713
887
  switch (state) {
@@ -715,6 +889,19 @@ var Peer = class {
715
889
  this.availableToConnect = true;
716
890
  this._lastConnectionTime = Date.now();
717
891
  this._callbacks.onConnected();
892
+ this._connectionLimiter.doneConnecting(sessionId);
893
+ log3.trace("dxos.mesh.connection.connected", {
894
+ topic: this.topic,
895
+ localPeerId: this.localPeerId,
896
+ remotePeerId: this.id,
897
+ sessionId,
898
+ initiator
899
+ }, {
900
+ F: __dxlog_file3,
901
+ L: 231,
902
+ S: this,
903
+ C: (f, a) => f(...a)
904
+ });
718
905
  break;
719
906
  }
720
907
  case ConnectionState.CLOSED: {
@@ -725,11 +912,31 @@ var Peer = class {
725
912
  initiator
726
913
  }, {
727
914
  F: __dxlog_file3,
728
- L: 221,
915
+ L: 242,
916
+ S: this,
917
+ C: (f, a) => f(...a)
918
+ });
919
+ invariant3(this.connection === connection, "Connection mismatch (race condition).", {
920
+ F: __dxlog_file3,
921
+ L: 243,
922
+ S: this,
923
+ A: [
924
+ "this.connection === connection",
925
+ "'Connection mismatch (race condition).'"
926
+ ]
927
+ });
928
+ log3.trace("dxos.mesh.connection.closed", {
929
+ topic: this.topic,
930
+ localPeerId: this.localPeerId,
931
+ remotePeerId: this.id,
932
+ sessionId,
933
+ initiator
934
+ }, {
935
+ F: __dxlog_file3,
936
+ L: 245,
729
937
  S: this,
730
938
  C: (f, a) => f(...a)
731
939
  });
732
- invariant3(this.connection === connection, "Connection mismatch (race condition).");
733
940
  if (this._lastConnectionTime && this._lastConnectionTime + CONNECTION_COUNTS_STABLE_AFTER < Date.now()) {
734
941
  this._availableAfter = 0;
735
942
  } else {
@@ -738,6 +945,7 @@ var Peer = class {
738
945
  }
739
946
  this.connection = void 0;
740
947
  this._callbacks.onDisconnected();
948
+ this._connectionLimiter.doneConnecting(sessionId);
741
949
  scheduleTask(this._connectionCtx, () => {
742
950
  this.availableToConnect = true;
743
951
  this._callbacks.onPeerAvailable();
@@ -755,16 +963,29 @@ var Peer = class {
755
963
  err
756
964
  }, {
757
965
  F: __dxlog_file3,
758
- L: 249,
966
+ L: 279,
967
+ S: this,
968
+ C: (f, a) => f(...a)
969
+ });
970
+ log3.trace("dxos.mesh.connection.error", {
971
+ topic: this.topic,
972
+ localPeerId: this.localPeerId,
973
+ remotePeerId: this.id,
974
+ sessionId,
975
+ initiator,
976
+ err
977
+ }, {
978
+ F: __dxlog_file3,
979
+ L: 280,
759
980
  S: this,
760
981
  C: (f, a) => f(...a)
761
982
  });
762
- void this.closeConnection();
983
+ void this.closeConnection(err);
763
984
  });
764
985
  this.connection = connection;
765
986
  return connection;
766
987
  }
767
- async closeConnection() {
988
+ async closeConnection(err) {
768
989
  if (!this.connection) {
769
990
  return;
770
991
  }
@@ -774,17 +995,17 @@ var Peer = class {
774
995
  sessionId: connection.sessionId
775
996
  }, {
776
997
  F: __dxlog_file3,
777
- L: 265,
998
+ L: 303,
778
999
  S: this,
779
1000
  C: (f, a) => f(...a)
780
1001
  });
781
- await connection.close();
1002
+ await connection.close(err);
782
1003
  log3("closed", {
783
1004
  peerId: this.id,
784
1005
  sessionId: connection.sessionId
785
1006
  }, {
786
1007
  F: __dxlog_file3,
787
- L: 271,
1008
+ L: 309,
788
1009
  S: this,
789
1010
  C: (f, a) => f(...a)
790
1011
  });
@@ -795,7 +1016,7 @@ var Peer = class {
795
1016
  message
796
1017
  }, {
797
1018
  F: __dxlog_file3,
798
- L: 276,
1019
+ L: 314,
799
1020
  S: this,
800
1021
  C: (f, a) => f(...a)
801
1022
  });
@@ -804,18 +1025,17 @@ var Peer = class {
804
1025
  await this.connection.signal(message);
805
1026
  }
806
1027
  async destroy() {
807
- var _a;
808
1028
  await this._ctx.dispose();
809
1029
  log3("Destroying peer", {
810
1030
  peerId: this.id,
811
1031
  topic: this.topic
812
1032
  }, {
813
1033
  F: __dxlog_file3,
814
- L: 285,
1034
+ L: 324,
815
1035
  S: this,
816
1036
  C: (f, a) => f(...a)
817
1037
  });
818
- await ((_a = this == null ? void 0 : this.connection) == null ? void 0 : _a.close());
1038
+ await this?.connection?.close();
819
1039
  }
820
1040
  };
821
1041
  _ts_decorate2([
@@ -851,7 +1071,7 @@ var getClassName = (obj) => Object.getPrototypeOf(obj).constructor.name;
851
1071
  var Swarm = class {
852
1072
  // TODO(burdon): Swarm => Peer.create/destroy =< Connection.open/close
853
1073
  // TODO(burdon): Split up properties.
854
- constructor(_topic, _ownPeerId, _topology, _protocolProvider, _messenger, _transportFactory, _label) {
1074
+ constructor(_topic, _ownPeerId, _topology, _protocolProvider, _messenger, _transportFactory, _label, _connectionLimiter) {
855
1075
  this._topic = _topic;
856
1076
  this._ownPeerId = _ownPeerId;
857
1077
  this._topology = _topology;
@@ -859,9 +1079,10 @@ var Swarm = class {
859
1079
  this._messenger = _messenger;
860
1080
  this._transportFactory = _transportFactory;
861
1081
  this._label = _label;
862
- this._peers = new ComplexMap2(PublicKey4.hash);
1082
+ this._connectionLimiter = _connectionLimiter;
863
1083
  this._ctx = new Context4();
864
1084
  this._listeningHandle = void 0;
1085
+ this._peers = new ComplexMap2(PublicKey4.hash);
865
1086
  this._instanceId = PublicKey4.random().toHex();
866
1087
  this.connectionAdded = new Event2();
867
1088
  this.disconnected = new Event2();
@@ -875,7 +1096,7 @@ var Swarm = class {
875
1096
  }
876
1097
  }), {
877
1098
  F: __dxlog_file4,
878
- L: 86,
1099
+ L: 87,
879
1100
  S: this,
880
1101
  C: (f, a) => f(...a)
881
1102
  });
@@ -883,7 +1104,7 @@ var Swarm = class {
883
1104
  peerId: _ownPeerId
884
1105
  }, {
885
1106
  F: __dxlog_file4,
886
- L: 90,
1107
+ L: 91,
887
1108
  S: this,
888
1109
  C: (f, a) => f(...a)
889
1110
  });
@@ -898,7 +1119,7 @@ var Swarm = class {
898
1119
  id: this._instanceId
899
1120
  }), {
900
1121
  F: __dxlog_file4,
901
- L: 99,
1122
+ L: 100,
902
1123
  S: this,
903
1124
  C: (f, a) => f(...a)
904
1125
  });
@@ -919,7 +1140,15 @@ var Swarm = class {
919
1140
  return this._topic;
920
1141
  }
921
1142
  async open() {
922
- invariant4(!this._listeningHandle);
1143
+ invariant4(!this._listeningHandle, void 0, {
1144
+ F: __dxlog_file4,
1145
+ L: 127,
1146
+ S: this,
1147
+ A: [
1148
+ "!this._listeningHandle",
1149
+ ""
1150
+ ]
1151
+ });
923
1152
  this._listeningHandle = await this._messenger.listen({
924
1153
  peerId: this._ownPeerId,
925
1154
  payloadType: "dxos.mesh.swarm.SwarmMessage",
@@ -928,7 +1157,7 @@ var Swarm = class {
928
1157
  err
929
1158
  }, {
930
1159
  F: __dxlog_file4,
931
- L: 133,
1160
+ L: 134,
932
1161
  S: this,
933
1162
  C: (f, a) => f(...a)
934
1163
  }));
@@ -936,27 +1165,34 @@ var Swarm = class {
936
1165
  });
937
1166
  }
938
1167
  async destroy() {
939
- var _a;
940
1168
  log4("destroying...", void 0, {
941
1169
  F: __dxlog_file4,
942
- L: 139,
1170
+ L: 140,
943
1171
  S: this,
944
1172
  C: (f, a) => f(...a)
945
1173
  });
946
- await ((_a = this._listeningHandle) == null ? void 0 : _a.unsubscribe());
1174
+ await this._listeningHandle?.unsubscribe();
947
1175
  this._listeningHandle = void 0;
948
1176
  await this._ctx.dispose();
949
1177
  await this._topology.destroy();
950
1178
  await Promise.all(Array.from(this._peers.keys()).map((key) => this._destroyPeer(key)));
951
1179
  log4("destroyed", void 0, {
952
1180
  F: __dxlog_file4,
953
- L: 146,
1181
+ L: 147,
954
1182
  S: this,
955
1183
  C: (f, a) => f(...a)
956
1184
  });
957
1185
  }
958
1186
  async setTopology(topology) {
959
- invariant4(!this._ctx.disposed, "Swarm is offline");
1187
+ invariant4(!this._ctx.disposed, "Swarm is offline", {
1188
+ F: __dxlog_file4,
1189
+ L: 151,
1190
+ S: this,
1191
+ A: [
1192
+ "!this._ctx.disposed",
1193
+ "'Swarm is offline'"
1194
+ ]
1195
+ });
960
1196
  if (topology === this._topology) {
961
1197
  return;
962
1198
  }
@@ -965,7 +1201,7 @@ var Swarm = class {
965
1201
  topology: getClassName(topology)
966
1202
  }, {
967
1203
  F: __dxlog_file4,
968
- L: 154,
1204
+ L: 155,
969
1205
  S: this,
970
1206
  C: (f, a) => f(...a)
971
1207
  });
@@ -975,19 +1211,18 @@ var Swarm = class {
975
1211
  this._topology.update();
976
1212
  }
977
1213
  onSwarmEvent(swarmEvent) {
978
- var _a;
979
1214
  log4("swarm event", {
980
1215
  swarmEvent
981
1216
  }, {
982
1217
  F: __dxlog_file4,
983
- L: 167,
1218
+ L: 168,
984
1219
  S: this,
985
1220
  C: (f, a) => f(...a)
986
1221
  });
987
1222
  if (this._ctx.disposed) {
988
1223
  log4("swarm event ignored for disposed swarm", void 0, {
989
1224
  F: __dxlog_file4,
990
- L: 170,
1225
+ L: 171,
991
1226
  S: this,
992
1227
  C: (f, a) => f(...a)
993
1228
  });
@@ -999,7 +1234,7 @@ var Swarm = class {
999
1234
  peerId
1000
1235
  }, {
1001
1236
  F: __dxlog_file4,
1002
- L: 176,
1237
+ L: 177,
1003
1238
  S: this,
1004
1239
  C: (f, a) => f(...a)
1005
1240
  });
@@ -1011,10 +1246,10 @@ var Swarm = class {
1011
1246
  const peer = this._peers.get(PublicKey4.from(swarmEvent.peerLeft.peer));
1012
1247
  if (peer) {
1013
1248
  peer.advertizing = false;
1014
- if (((_a = peer.connection) == null ? void 0 : _a.state) !== ConnectionState.CONNECTED) {
1249
+ if (peer.connection?.state !== ConnectionState.CONNECTED) {
1015
1250
  void this._destroyPeer(peer.id).catch((err) => log4.catch(err, void 0, {
1016
1251
  F: __dxlog_file4,
1017
- L: 187,
1252
+ L: 188,
1018
1253
  S: this,
1019
1254
  C: (f, a) => f(...a)
1020
1255
  }));
@@ -1024,19 +1259,18 @@ var Swarm = class {
1024
1259
  this._topology.update();
1025
1260
  }
1026
1261
  async onOffer(message) {
1027
- var _a, _b;
1028
1262
  log4("offer", {
1029
1263
  message
1030
1264
  }, {
1031
1265
  F: __dxlog_file4,
1032
- L: 197,
1266
+ L: 198,
1033
1267
  S: this,
1034
1268
  C: (f, a) => f(...a)
1035
1269
  });
1036
1270
  if (this._ctx.disposed) {
1037
1271
  log4("ignored for disposed swarm", void 0, {
1038
1272
  F: __dxlog_file4,
1039
- L: 199,
1273
+ L: 200,
1040
1274
  S: this,
1041
1275
  C: (f, a) => f(...a)
1042
1276
  });
@@ -1044,13 +1278,21 @@ var Swarm = class {
1044
1278
  accept: false
1045
1279
  };
1046
1280
  }
1047
- invariant4(message.author);
1048
- if (!((_a = message.recipient) == null ? void 0 : _a.equals(this._ownPeerId))) {
1281
+ invariant4(message.author, void 0, {
1282
+ F: __dxlog_file4,
1283
+ L: 205,
1284
+ S: this,
1285
+ A: [
1286
+ "message.author",
1287
+ ""
1288
+ ]
1289
+ });
1290
+ if (!message.recipient?.equals(this._ownPeerId)) {
1049
1291
  log4("rejecting offer with incorrect peerId", {
1050
1292
  message
1051
1293
  }, {
1052
1294
  F: __dxlog_file4,
1053
- L: 206,
1295
+ L: 207,
1054
1296
  S: this,
1055
1297
  C: (f, a) => f(...a)
1056
1298
  });
@@ -1058,12 +1300,12 @@ var Swarm = class {
1058
1300
  accept: false
1059
1301
  };
1060
1302
  }
1061
- if (!((_b = message.topic) == null ? void 0 : _b.equals(this._topic))) {
1303
+ if (!message.topic?.equals(this._topic)) {
1062
1304
  log4("rejecting offer with incorrect topic", {
1063
1305
  message
1064
1306
  }, {
1065
1307
  F: __dxlog_file4,
1066
- L: 210,
1308
+ L: 211,
1067
1309
  S: this,
1068
1310
  C: (f, a) => f(...a)
1069
1311
  });
@@ -1077,7 +1319,6 @@ var Swarm = class {
1077
1319
  return answer;
1078
1320
  }
1079
1321
  async onSignal(message) {
1080
- var _a, _b;
1081
1322
  log4("signal", {
1082
1323
  message
1083
1324
  }, {
@@ -1095,9 +1336,33 @@ var Swarm = class {
1095
1336
  });
1096
1337
  return;
1097
1338
  }
1098
- invariant4((_a = message.recipient) == null ? void 0 : _a.equals(this._ownPeerId), `Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`);
1099
- invariant4((_b = message.topic) == null ? void 0 : _b.equals(this._topic));
1100
- invariant4(message.author);
1339
+ invariant4(message.recipient?.equals(this._ownPeerId), `Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`, {
1340
+ F: __dxlog_file4,
1341
+ L: 227,
1342
+ S: this,
1343
+ A: [
1344
+ "message.recipient?.equals(this._ownPeerId)",
1345
+ "`Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`"
1346
+ ]
1347
+ });
1348
+ invariant4(message.topic?.equals(this._topic), void 0, {
1349
+ F: __dxlog_file4,
1350
+ L: 231,
1351
+ S: this,
1352
+ A: [
1353
+ "message.topic?.equals(this._topic)",
1354
+ ""
1355
+ ]
1356
+ });
1357
+ invariant4(message.author, void 0, {
1358
+ F: __dxlog_file4,
1359
+ L: 232,
1360
+ S: this,
1361
+ A: [
1362
+ "message.author",
1363
+ ""
1364
+ ]
1365
+ });
1101
1366
  const peer = this._getOrCreatePeer(message.author);
1102
1367
  await peer.onSignal(message);
1103
1368
  }
@@ -1115,7 +1380,7 @@ var Swarm = class {
1115
1380
  _getOrCreatePeer(peerId) {
1116
1381
  let peer = this._peers.get(peerId);
1117
1382
  if (!peer) {
1118
- peer = new Peer(peerId, this._topic, this._ownPeerId, this._swarmMessenger, this._protocolProvider, this._transportFactory, {
1383
+ peer = new Peer(peerId, this._topic, this._ownPeerId, this._swarmMessenger, this._protocolProvider, this._transportFactory, this._connectionLimiter, {
1119
1384
  onInitiated: (connection) => {
1120
1385
  this.connectionAdded.emit(connection);
1121
1386
  },
@@ -1149,7 +1414,15 @@ var Swarm = class {
1149
1414
  return peer;
1150
1415
  }
1151
1416
  async _destroyPeer(peerId) {
1152
- invariant4(this._peers.has(peerId));
1417
+ invariant4(this._peers.has(peerId), void 0, {
1418
+ F: __dxlog_file4,
1419
+ L: 302,
1420
+ S: this,
1421
+ A: [
1422
+ "this._peers.has(peerId)",
1423
+ ""
1424
+ ]
1425
+ });
1153
1426
  await this._peers.get(peerId).destroy();
1154
1427
  this._peers.delete(peerId);
1155
1428
  }
@@ -1170,7 +1443,7 @@ var Swarm = class {
1170
1443
  } catch (err) {
1171
1444
  log4("initiation error", err, {
1172
1445
  F: __dxlog_file4,
1173
- L: 327,
1446
+ L: 328,
1174
1447
  S: this,
1175
1448
  C: (f, a) => f(...a)
1176
1449
  });
@@ -1198,7 +1471,7 @@ var Swarm = class {
1198
1471
  remoteId
1199
1472
  }, {
1200
1473
  F: __dxlog_file4,
1201
- L: 354,
1474
+ L: 355,
1202
1475
  S: this,
1203
1476
  C: (f, a) => f(...a)
1204
1477
  });
@@ -1215,7 +1488,7 @@ var Swarm = class {
1215
1488
  remoteId
1216
1489
  }, {
1217
1490
  F: __dxlog_file4,
1218
- L: 368,
1491
+ L: 369,
1219
1492
  S: this,
1220
1493
  C: (f, a) => f(...a)
1221
1494
  });
@@ -1225,7 +1498,7 @@ var Swarm = class {
1225
1498
  remoteId
1226
1499
  }, {
1227
1500
  F: __dxlog_file4,
1228
- L: 371,
1501
+ L: 372,
1229
1502
  S: this,
1230
1503
  C: (f, a) => f(...a)
1231
1504
  });
@@ -1253,9 +1526,6 @@ _ts_decorate3([
1253
1526
  _ts_decorate3([
1254
1527
  synchronized3
1255
1528
  ], Swarm.prototype, "onOffer", null);
1256
- _ts_decorate3([
1257
- synchronized3
1258
- ], Swarm.prototype, "onSignal", null);
1259
1529
  _ts_decorate3([
1260
1530
  synchronized3
1261
1531
  ], Swarm.prototype, "goOffline", null);
@@ -1287,8 +1557,7 @@ var SwarmMapper = class {
1287
1557
  }));
1288
1558
  }));
1289
1559
  this._subscriptions.add(_swarm.disconnected.on((peerId) => {
1290
- var _a;
1291
- (_a = this._connectionSubscriptions.get(peerId)) == null ? void 0 : _a();
1560
+ this._connectionSubscriptions.get(peerId)?.();
1292
1561
  this._connectionSubscriptions.delete(peerId);
1293
1562
  this._update();
1294
1563
  }));
@@ -1334,11 +1603,93 @@ var SwarmMapper = class {
1334
1603
  }
1335
1604
  };
1336
1605
 
1606
+ // packages/core/mesh/network-manager/src/swarm/connection-limiter.ts
1607
+ import { DeferredTask as DeferredTask2 } from "@dxos/async";
1608
+ import { Context as Context5 } from "@dxos/context";
1609
+ import { CancelledError as CancelledError3 } from "@dxos/errors";
1610
+ import { invariant as invariant5 } from "@dxos/invariant";
1611
+ import { PublicKey as PublicKey6 } from "@dxos/keys";
1612
+ import { log as log6 } from "@dxos/log";
1613
+ import { ComplexMap as ComplexMap4 } from "@dxos/util";
1614
+ var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/connection-limiter.ts";
1615
+ var MAX_CONCURRENT_INITIATING_CONNECTIONS = 10;
1616
+ var ConnectionLimiter = class {
1617
+ constructor({ maxConcurrentInitConnections = MAX_CONCURRENT_INITIATING_CONNECTIONS } = {}) {
1618
+ this._ctx = new Context5();
1619
+ /**
1620
+ * Queue of promises to resolve when initiating connections amount is below the limit.
1621
+ */
1622
+ this._waitingPromises = new ComplexMap4(PublicKey6.hash);
1623
+ this.resolveWaitingPromises = new DeferredTask2(this._ctx, async () => {
1624
+ Array.from(this._waitingPromises.values()).slice(0, this._maxConcurrentInitConnections).forEach(({ resolve }) => {
1625
+ resolve();
1626
+ });
1627
+ });
1628
+ this._maxConcurrentInitConnections = maxConcurrentInitConnections;
1629
+ }
1630
+ /**
1631
+ * @returns Promise that resolves in queue when connections amount with 'CONNECTING' state is below the limit.
1632
+ */
1633
+ async connecting(sessionId) {
1634
+ invariant5(!this._waitingPromises.has(sessionId), "Peer is already waiting for connection", {
1635
+ F: __dxlog_file6,
1636
+ L: 48,
1637
+ S: this,
1638
+ A: [
1639
+ "!this._waitingPromises.has(sessionId)",
1640
+ "'Peer is already waiting for connection'"
1641
+ ]
1642
+ });
1643
+ log6("waiting", {
1644
+ sessionId
1645
+ }, {
1646
+ F: __dxlog_file6,
1647
+ L: 49,
1648
+ S: this,
1649
+ C: (f, a) => f(...a)
1650
+ });
1651
+ await new Promise((resolve, reject) => {
1652
+ this._waitingPromises.set(sessionId, {
1653
+ resolve,
1654
+ reject
1655
+ });
1656
+ this.resolveWaitingPromises.schedule();
1657
+ });
1658
+ log6("allow", {
1659
+ sessionId
1660
+ }, {
1661
+ F: __dxlog_file6,
1662
+ L: 57,
1663
+ S: this,
1664
+ C: (f, a) => f(...a)
1665
+ });
1666
+ }
1667
+ /**
1668
+ * Rejects promise returned by `connecting` method.
1669
+ */
1670
+ doneConnecting(sessionId) {
1671
+ log6("done", {
1672
+ sessionId
1673
+ }, {
1674
+ F: __dxlog_file6,
1675
+ L: 64,
1676
+ S: this,
1677
+ C: (f, a) => f(...a)
1678
+ });
1679
+ if (!this._waitingPromises.has(sessionId)) {
1680
+ return;
1681
+ }
1682
+ this._waitingPromises.get(sessionId).reject(new CancelledError3());
1683
+ this._waitingPromises.delete(sessionId);
1684
+ this.resolveWaitingPromises.schedule();
1685
+ }
1686
+ };
1687
+
1337
1688
  // packages/core/mesh/network-manager/src/connection-log.ts
1338
1689
  import { Event as Event4 } from "@dxos/async";
1339
1690
  import { raise } from "@dxos/debug";
1340
- import { PublicKey as PublicKey6 } from "@dxos/keys";
1341
- import { ComplexMap as ComplexMap4 } from "@dxos/util";
1691
+ import { PublicKey as PublicKey7 } from "@dxos/keys";
1692
+ import { ComplexMap as ComplexMap5 } from "@dxos/util";
1342
1693
  var EventType;
1343
1694
  (function(EventType2) {
1344
1695
  EventType2["CONNECTION_STATE_CHANGED"] = "CONNECTION_STATE_CHANGED";
@@ -1352,30 +1703,29 @@ var ConnectionLog = class {
1352
1703
  /**
1353
1704
  * SwarmId => info
1354
1705
  */
1355
- this._swarms = new ComplexMap4(PublicKey6.hash);
1706
+ this._swarms = new ComplexMap5(PublicKey7.hash);
1356
1707
  this.update = new Event4();
1357
1708
  }
1358
1709
  getSwarmInfo(swarmId) {
1359
- var _a;
1360
- return (_a = this._swarms.get(swarmId)) != null ? _a : raise(new Error(`Swarm not found: ${swarmId}`));
1710
+ return this._swarms.get(swarmId) ?? raise(new Error(`Swarm not found: ${swarmId}`));
1361
1711
  }
1362
1712
  get swarms() {
1363
1713
  return Array.from(this._swarms.values());
1364
1714
  }
1365
1715
  joinedSwarm(swarm) {
1366
1716
  const info = {
1367
- id: PublicKey6.from(swarm._instanceId),
1717
+ id: PublicKey7.from(swarm._instanceId),
1368
1718
  topic: swarm.topic,
1369
1719
  isActive: true,
1370
1720
  label: swarm.label,
1371
1721
  connections: []
1372
1722
  };
1373
- this._swarms.set(PublicKey6.from(swarm._instanceId), info);
1723
+ this._swarms.set(PublicKey7.from(swarm._instanceId), info);
1374
1724
  this.update.emit();
1375
1725
  swarm.connectionAdded.on((connection) => {
1376
- var _a, _b;
1377
1726
  const connectionInfo = {
1378
1727
  state: ConnectionState.INITIAL,
1728
+ closeReason: connection.closeReason,
1379
1729
  remotePeerId: connection.remoteId,
1380
1730
  sessionId: connection.sessionId,
1381
1731
  transport: connection.transport && Object.getPrototypeOf(connection.transport).constructor.name,
@@ -1386,48 +1736,49 @@ var ConnectionLog = class {
1386
1736
  this.update.emit();
1387
1737
  connection.stateChanged.on((state) => {
1388
1738
  connectionInfo.state = state;
1739
+ connectionInfo.closeReason = connection.closeReason;
1389
1740
  connectionInfo.events.push({
1390
1741
  type: EventType.CONNECTION_STATE_CHANGED,
1391
1742
  newState: state
1392
1743
  });
1393
1744
  this.update.emit();
1394
1745
  });
1395
- (_b = (_a = connection.protocol) == null ? void 0 : _a.stats) == null ? void 0 : _b.on((stats) => {
1746
+ connection.protocol?.stats?.on((stats) => {
1396
1747
  connectionInfo.streams = stats.channels;
1397
1748
  this.update.emit();
1398
1749
  });
1399
1750
  });
1400
1751
  }
1401
1752
  leftSwarm(swarm) {
1402
- this.getSwarmInfo(PublicKey6.from(swarm._instanceId)).isActive = false;
1753
+ this.getSwarmInfo(PublicKey7.from(swarm._instanceId)).isActive = false;
1403
1754
  this.update.emit();
1404
1755
  }
1405
1756
  };
1406
1757
 
1407
1758
  // packages/core/mesh/network-manager/src/network-manager.ts
1408
- import invariant5 from "tiny-invariant";
1409
1759
  import { Event as Event5 } from "@dxos/async";
1410
- import { PublicKey as PublicKey7 } from "@dxos/keys";
1411
- import { log as log6 } from "@dxos/log";
1760
+ import { invariant as invariant6 } from "@dxos/invariant";
1761
+ import { PublicKey as PublicKey8 } from "@dxos/keys";
1762
+ import { log as log7 } from "@dxos/log";
1412
1763
  import { Messenger } from "@dxos/messaging";
1413
1764
  import { trace as trace3 } from "@dxos/protocols";
1414
1765
  import { ConnectionState as ConnectionState2 } from "@dxos/protocols/proto/dxos/client/services";
1415
- import { ComplexMap as ComplexMap5 } from "@dxos/util";
1416
- var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/network-manager.ts";
1766
+ import { ComplexMap as ComplexMap6 } from "@dxos/util";
1767
+ var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/network-manager.ts";
1417
1768
  var NetworkManager = class {
1418
1769
  constructor({ transportFactory, signalManager, log: log1 }) {
1419
- this._swarms = new ComplexMap5(PublicKey7.hash);
1420
- this._mappers = new ComplexMap5(PublicKey7.hash);
1770
+ /**
1771
+ * @internal
1772
+ */
1773
+ this._swarms = new ComplexMap6(PublicKey8.hash);
1774
+ this._mappers = new ComplexMap6(PublicKey8.hash);
1421
1775
  this._connectionState = ConnectionState2.ONLINE;
1422
1776
  this.connectionStateChanged = new Event5();
1423
1777
  this.topicsUpdated = new Event5();
1424
- this._instanceId = PublicKey7.random().toHex();
1778
+ this._instanceId = PublicKey8.random().toHex();
1425
1779
  this._transportFactory = transportFactory;
1426
1780
  this._signalManager = signalManager;
1427
- this._signalManager.swarmEvent.on(({ topic, swarmEvent: event }) => {
1428
- var _a;
1429
- return (_a = this._swarms.get(topic)) == null ? void 0 : _a.onSwarmEvent(event);
1430
- });
1781
+ this._signalManager.swarmEvent.on(({ topic, swarmEvent: event }) => this._swarms.get(topic)?.onSwarmEvent(event));
1431
1782
  this._messenger = new Messenger({
1432
1783
  signalManager: this._signalManager
1433
1784
  });
@@ -1435,6 +1786,7 @@ var NetworkManager = class {
1435
1786
  join: (opts) => this._signalManager.join(opts),
1436
1787
  leave: (opts) => this._signalManager.leave(opts)
1437
1788
  };
1789
+ this._connectionLimiter = new ConnectionLimiter();
1438
1790
  if (log1) {
1439
1791
  this._connectionLog = new ConnectionLog();
1440
1792
  }
@@ -1457,21 +1809,21 @@ var NetworkManager = class {
1457
1809
  return this._swarms.get(topic);
1458
1810
  }
1459
1811
  async open() {
1460
- log6.trace("dxos.mesh.network-manager.open", trace3.begin({
1812
+ log7.trace("dxos.mesh.network-manager.open", trace3.begin({
1461
1813
  id: this._instanceId
1462
1814
  }), {
1463
- F: __dxlog_file6,
1464
- L: 127,
1815
+ F: __dxlog_file7,
1816
+ L: 130,
1465
1817
  S: this,
1466
1818
  C: (f, a) => f(...a)
1467
1819
  });
1468
1820
  await this._messenger.open();
1469
1821
  await this._signalManager.open();
1470
- log6.trace("dxos.mesh.network-manager.open", trace3.end({
1822
+ log7.trace("dxos.mesh.network-manager.open", trace3.end({
1471
1823
  id: this._instanceId
1472
1824
  }), {
1473
- F: __dxlog_file6,
1474
- L: 130,
1825
+ F: __dxlog_file7,
1826
+ L: 133,
1475
1827
  S: this,
1476
1828
  C: (f, a) => f(...a)
1477
1829
  });
@@ -1479,9 +1831,9 @@ var NetworkManager = class {
1479
1831
  async close() {
1480
1832
  for (const topic of this._swarms.keys()) {
1481
1833
  await this.leaveSwarm(topic).catch((err) => {
1482
- log6(err, void 0, {
1483
- F: __dxlog_file6,
1484
- L: 136,
1834
+ log7(err, void 0, {
1835
+ F: __dxlog_file7,
1836
+ L: 139,
1485
1837
  S: this,
1486
1838
  C: (f, a) => f(...a)
1487
1839
  });
@@ -1494,31 +1846,62 @@ var NetworkManager = class {
1494
1846
  * Join the swarm.
1495
1847
  */
1496
1848
  async joinSwarm({ topic, peerId, topology, protocolProvider: protocol, label }) {
1497
- var _a;
1498
- invariant5(PublicKey7.isPublicKey(topic));
1499
- invariant5(PublicKey7.isPublicKey(peerId));
1500
- invariant5(topology);
1501
- invariant5(typeof protocol === "function");
1849
+ invariant6(PublicKey8.isPublicKey(topic), void 0, {
1850
+ F: __dxlog_file7,
1851
+ L: 157,
1852
+ S: this,
1853
+ A: [
1854
+ "PublicKey.isPublicKey(topic)",
1855
+ ""
1856
+ ]
1857
+ });
1858
+ invariant6(PublicKey8.isPublicKey(peerId), void 0, {
1859
+ F: __dxlog_file7,
1860
+ L: 158,
1861
+ S: this,
1862
+ A: [
1863
+ "PublicKey.isPublicKey(peerId)",
1864
+ ""
1865
+ ]
1866
+ });
1867
+ invariant6(topology, void 0, {
1868
+ F: __dxlog_file7,
1869
+ L: 159,
1870
+ S: this,
1871
+ A: [
1872
+ "topology",
1873
+ ""
1874
+ ]
1875
+ });
1876
+ invariant6(typeof protocol === "function", void 0, {
1877
+ F: __dxlog_file7,
1878
+ L: 160,
1879
+ S: this,
1880
+ A: [
1881
+ "typeof protocol === 'function'",
1882
+ ""
1883
+ ]
1884
+ });
1502
1885
  if (this._swarms.has(topic)) {
1503
- throw new Error(`Already connected to swarm: ${PublicKey7.from(topic)}`);
1886
+ throw new Error(`Already connected to swarm: ${PublicKey8.from(topic)}`);
1504
1887
  }
1505
- log6("joining", {
1506
- topic: PublicKey7.from(topic),
1888
+ log7("joining", {
1889
+ topic: PublicKey8.from(topic),
1507
1890
  peerId,
1508
1891
  topology: topology.toString()
1509
1892
  }, {
1510
- F: __dxlog_file6,
1511
- L: 162,
1893
+ F: __dxlog_file7,
1894
+ L: 165,
1512
1895
  S: this,
1513
1896
  C: (f, a) => f(...a)
1514
1897
  });
1515
- const swarm = new Swarm(topic, peerId, topology, protocol, this._messenger, this._transportFactory, label);
1898
+ const swarm = new Swarm(topic, peerId, topology, protocol, this._messenger, this._transportFactory, label, this._connectionLimiter);
1516
1899
  swarm.errors.handle((error) => {
1517
- log6("swarm error", {
1900
+ log7("swarm error", {
1518
1901
  error
1519
1902
  }, {
1520
- F: __dxlog_file6,
1521
- L: 165,
1903
+ F: __dxlog_file7,
1904
+ L: 178,
1522
1905
  S: this,
1523
1906
  C: (f, a) => f(...a)
1524
1907
  });
@@ -1529,20 +1912,20 @@ var NetworkManager = class {
1529
1912
  this._signalConnection.join({
1530
1913
  topic,
1531
1914
  peerId
1532
- }).catch((error) => log6.catch(error, void 0, {
1533
- F: __dxlog_file6,
1534
- L: 174,
1915
+ }).catch((error) => log7.catch(error, void 0, {
1916
+ F: __dxlog_file7,
1917
+ L: 187,
1535
1918
  S: this,
1536
1919
  C: (f, a) => f(...a)
1537
1920
  }));
1538
1921
  this.topicsUpdated.emit();
1539
- (_a = this._connectionLog) == null ? void 0 : _a.joinedSwarm(swarm);
1540
- log6("joined", {
1541
- topic: PublicKey7.from(topic),
1922
+ this._connectionLog?.joinedSwarm(swarm);
1923
+ log7("joined", {
1924
+ topic: PublicKey8.from(topic),
1542
1925
  count: this._swarms.size
1543
1926
  }, {
1544
- F: __dxlog_file6,
1545
- L: 178,
1927
+ F: __dxlog_file7,
1928
+ L: 191,
1546
1929
  S: this,
1547
1930
  C: (f, a) => f(...a)
1548
1931
  });
@@ -1554,15 +1937,14 @@ var NetworkManager = class {
1554
1937
  * Close the connection.
1555
1938
  */
1556
1939
  async leaveSwarm(topic) {
1557
- var _a;
1558
1940
  if (!this._swarms.has(topic)) {
1559
1941
  return;
1560
1942
  }
1561
- log6("leaving", {
1562
- topic: PublicKey7.from(topic)
1943
+ log7("leaving", {
1944
+ topic: PublicKey8.from(topic)
1563
1945
  }, {
1564
- F: __dxlog_file6,
1565
- L: 194,
1946
+ F: __dxlog_file7,
1947
+ L: 207,
1566
1948
  S: this,
1567
1949
  C: (f, a) => f(...a)
1568
1950
  });
@@ -1574,16 +1956,16 @@ var NetworkManager = class {
1574
1956
  const map = this._mappers.get(topic);
1575
1957
  map.destroy();
1576
1958
  this._mappers.delete(topic);
1577
- (_a = this._connectionLog) == null ? void 0 : _a.leftSwarm(swarm);
1959
+ this._connectionLog?.leftSwarm(swarm);
1578
1960
  await swarm.destroy();
1579
1961
  this._swarms.delete(topic);
1580
1962
  await this.topicsUpdated.emit();
1581
- log6("left", {
1582
- topic: PublicKey7.from(topic),
1963
+ log7("left", {
1964
+ topic: PublicKey8.from(topic),
1583
1965
  count: this._swarms.size
1584
1966
  }, {
1585
- F: __dxlog_file6,
1586
- L: 208,
1967
+ F: __dxlog_file7,
1968
+ L: 221,
1587
1969
  S: this,
1588
1970
  C: (f, a) => f(...a)
1589
1971
  });
@@ -1617,17 +1999,34 @@ var NetworkManager = class {
1617
1999
  };
1618
2000
 
1619
2001
  // packages/core/mesh/network-manager/src/topology/fully-connected-topology.ts
1620
- import invariant6 from "tiny-invariant";
2002
+ import { invariant as invariant7 } from "@dxos/invariant";
2003
+ var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/topology/fully-connected-topology.ts";
1621
2004
  var FullyConnectedTopology = class {
1622
2005
  toString() {
1623
2006
  return "FullyConnectedTopology";
1624
2007
  }
1625
2008
  init(controller) {
1626
- invariant6(!this._controller, "Already initialized");
2009
+ invariant7(!this._controller, "Already initialized", {
2010
+ F: __dxlog_file8,
2011
+ L: 18,
2012
+ S: this,
2013
+ A: [
2014
+ "!this._controller",
2015
+ "'Already initialized'"
2016
+ ]
2017
+ });
1627
2018
  this._controller = controller;
1628
2019
  }
1629
2020
  update() {
1630
- invariant6(this._controller, "Not initialized");
2021
+ invariant7(this._controller, "Not initialized", {
2022
+ F: __dxlog_file8,
2023
+ L: 23,
2024
+ S: this,
2025
+ A: [
2026
+ "this._controller",
2027
+ "'Not initialized'"
2028
+ ]
2029
+ });
1631
2030
  const { candidates: discovered } = this._controller.getState();
1632
2031
  for (const peer of discovered) {
1633
2032
  this._controller.connect(peer);
@@ -1641,10 +2040,10 @@ var FullyConnectedTopology = class {
1641
2040
  };
1642
2041
 
1643
2042
  // packages/core/mesh/network-manager/src/topology/mmst-topology.ts
1644
- import invariant7 from "tiny-invariant";
1645
2043
  import distance from "xor-distance";
1646
- import { log as log7 } from "@dxos/log";
1647
- var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/topology/mmst-topology.ts";
2044
+ import { invariant as invariant8 } from "@dxos/invariant";
2045
+ import { log as log8 } from "@dxos/log";
2046
+ var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/topology/mmst-topology.ts";
1648
2047
  var MMSTTopology = class {
1649
2048
  constructor({ originateConnections = 2, maxPeers = 4, sampleSize = 10 } = {}) {
1650
2049
  this._sampleCollected = false;
@@ -1653,15 +2052,31 @@ var MMSTTopology = class {
1653
2052
  this._sampleSize = sampleSize;
1654
2053
  }
1655
2054
  init(controller) {
1656
- invariant7(!this._controller, "Already initialized");
2055
+ invariant8(!this._controller, "Already initialized", {
2056
+ F: __dxlog_file9,
2057
+ L: 46,
2058
+ S: this,
2059
+ A: [
2060
+ "!this._controller",
2061
+ "'Already initialized'"
2062
+ ]
2063
+ });
1657
2064
  this._controller = controller;
1658
2065
  }
1659
2066
  update() {
1660
- invariant7(this._controller, "Not initialized");
2067
+ invariant8(this._controller, "Not initialized", {
2068
+ F: __dxlog_file9,
2069
+ L: 51,
2070
+ S: this,
2071
+ A: [
2072
+ "this._controller",
2073
+ "'Not initialized'"
2074
+ ]
2075
+ });
1661
2076
  const { connected, candidates } = this._controller.getState();
1662
2077
  if (this._sampleCollected || connected.length > this._maxPeers || candidates.length > 0) {
1663
- log7("Running the algorithm.", void 0, {
1664
- F: __dxlog_file7,
2078
+ log8("Running the algorithm.", void 0, {
2079
+ F: __dxlog_file9,
1665
2080
  L: 55,
1666
2081
  S: this,
1667
2082
  C: (f, a) => f(...a)
@@ -1671,11 +2086,19 @@ var MMSTTopology = class {
1671
2086
  }
1672
2087
  }
1673
2088
  async onOffer(peer) {
1674
- invariant7(this._controller, "Not initialized");
2089
+ invariant8(this._controller, "Not initialized", {
2090
+ F: __dxlog_file9,
2091
+ L: 62,
2092
+ S: this,
2093
+ A: [
2094
+ "this._controller",
2095
+ "'Not initialized'"
2096
+ ]
2097
+ });
1675
2098
  const { connected } = this._controller.getState();
1676
2099
  const accept = connected.length < this._maxPeers;
1677
- log7(`Offer ${peer} accept=${accept}`, void 0, {
1678
- F: __dxlog_file7,
2100
+ log8(`Offer ${peer} accept=${accept}`, void 0, {
2101
+ F: __dxlog_file9,
1679
2102
  L: 65,
1680
2103
  S: this,
1681
2104
  C: (f, a) => f(...a)
@@ -1685,13 +2108,21 @@ var MMSTTopology = class {
1685
2108
  async destroy() {
1686
2109
  }
1687
2110
  _runAlgorithm() {
1688
- invariant7(this._controller, "Not initialized");
2111
+ invariant8(this._controller, "Not initialized", {
2112
+ F: __dxlog_file9,
2113
+ L: 74,
2114
+ S: this,
2115
+ A: [
2116
+ "this._controller",
2117
+ "'Not initialized'"
2118
+ ]
2119
+ });
1689
2120
  const { connected, candidates, ownPeerId } = this._controller.getState();
1690
2121
  if (connected.length > this._maxPeers) {
1691
2122
  const sorted = sortByXorDistance(connected, ownPeerId).reverse().slice(0, this._maxPeers - connected.length);
1692
2123
  for (const peer of sorted) {
1693
- log7(`Disconnect ${peer}.`, void 0, {
1694
- F: __dxlog_file7,
2124
+ log8(`Disconnect ${peer}.`, void 0, {
2125
+ F: __dxlog_file9,
1695
2126
  L: 83,
1696
2127
  S: this,
1697
2128
  C: (f, a) => f(...a)
@@ -1702,8 +2133,8 @@ var MMSTTopology = class {
1702
2133
  const sample = candidates.sort(() => Math.random() - 0.5).slice(0, this._sampleSize);
1703
2134
  const sorted = sortByXorDistance(sample, ownPeerId).slice(0, this._originateConnections - connected.length);
1704
2135
  for (const peer of sorted) {
1705
- log7(`Connect ${peer}.`, void 0, {
1706
- F: __dxlog_file7,
2136
+ log8(`Connect ${peer}.`, void 0, {
2137
+ F: __dxlog_file9,
1707
2138
  L: 91,
1708
2139
  S: this,
1709
2140
  C: (f, a) => f(...a)
@@ -1719,9 +2150,9 @@ var MMSTTopology = class {
1719
2150
  var sortByXorDistance = (keys, reference) => keys.sort((a, b) => distance.gt(distance(a.asBuffer(), reference.asBuffer()), distance(b.asBuffer(), reference.asBuffer())));
1720
2151
 
1721
2152
  // packages/core/mesh/network-manager/src/topology/star-topology.ts
1722
- import invariant8 from "tiny-invariant";
1723
- import { log as log8 } from "@dxos/log";
1724
- var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/topology/star-topology.ts";
2153
+ import { invariant as invariant9 } from "@dxos/invariant";
2154
+ import { log as log9 } from "@dxos/log";
2155
+ var __dxlog_file10 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/topology/star-topology.ts";
1725
2156
  var StarTopology = class {
1726
2157
  // prettier-ignore
1727
2158
  constructor(_centralPeer) {
@@ -1731,26 +2162,42 @@ var StarTopology = class {
1731
2162
  return `StarTopology(${this._centralPeer.truncate()})`;
1732
2163
  }
1733
2164
  init(controller) {
1734
- invariant8(!this._controller, "Already initialized.");
2165
+ invariant9(!this._controller, "Already initialized.", {
2166
+ F: __dxlog_file10,
2167
+ L: 24,
2168
+ S: this,
2169
+ A: [
2170
+ "!this._controller",
2171
+ "'Already initialized.'"
2172
+ ]
2173
+ });
1735
2174
  this._controller = controller;
1736
2175
  }
1737
2176
  update() {
1738
- invariant8(this._controller, "Not initialized.");
2177
+ invariant9(this._controller, "Not initialized.", {
2178
+ F: __dxlog_file10,
2179
+ L: 29,
2180
+ S: this,
2181
+ A: [
2182
+ "this._controller",
2183
+ "'Not initialized.'"
2184
+ ]
2185
+ });
1739
2186
  const { candidates, connected, ownPeerId } = this._controller.getState();
1740
2187
  if (!ownPeerId.equals(this._centralPeer)) {
1741
- log8("leaf peer dropping all connections apart from central peer.", void 0, {
1742
- F: __dxlog_file8,
1743
- L: 33,
2188
+ log9("leaf peer dropping all connections apart from central peer.", void 0, {
2189
+ F: __dxlog_file10,
2190
+ L: 32,
1744
2191
  S: this,
1745
2192
  C: (f, a) => f(...a)
1746
2193
  });
1747
2194
  for (const peer of connected) {
1748
2195
  if (!peer.equals(this._centralPeer)) {
1749
- log8("dropping connection", {
2196
+ log9("dropping connection", {
1750
2197
  peer
1751
2198
  }, {
1752
- F: __dxlog_file8,
1753
- L: 38,
2199
+ F: __dxlog_file10,
2200
+ L: 37,
1754
2201
  S: this,
1755
2202
  C: (f, a) => f(...a)
1756
2203
  });
@@ -1760,11 +2207,11 @@ var StarTopology = class {
1760
2207
  }
1761
2208
  for (const peer of candidates) {
1762
2209
  if (peer.equals(this._centralPeer) || ownPeerId.equals(this._centralPeer)) {
1763
- log8("connecting to peer", {
2210
+ log9("connecting to peer", {
1764
2211
  peer
1765
2212
  }, {
1766
- F: __dxlog_file8,
1767
- L: 47,
2213
+ F: __dxlog_file10,
2214
+ L: 46,
1768
2215
  S: this,
1769
2216
  C: (f, a) => f(...a)
1770
2217
  });
@@ -1773,15 +2220,23 @@ var StarTopology = class {
1773
2220
  }
1774
2221
  }
1775
2222
  async onOffer(peer) {
1776
- invariant8(this._controller, "Not initialized.");
2223
+ invariant9(this._controller, "Not initialized.", {
2224
+ F: __dxlog_file10,
2225
+ L: 53,
2226
+ S: this,
2227
+ A: [
2228
+ "this._controller",
2229
+ "'Not initialized.'"
2230
+ ]
2231
+ });
1777
2232
  const { ownPeerId } = this._controller.getState();
1778
- log8("offer", {
2233
+ log9("offer", {
1779
2234
  peer,
1780
2235
  isCentral: peer.equals(this._centralPeer),
1781
2236
  isSelfCentral: ownPeerId.equals(this._centralPeer)
1782
2237
  }, {
1783
- F: __dxlog_file8,
1784
- L: 56,
2238
+ F: __dxlog_file10,
2239
+ L: 55,
1785
2240
  S: this,
1786
2241
  C: (f, a) => f(...a)
1787
2242
  });
@@ -1793,12 +2248,12 @@ var StarTopology = class {
1793
2248
 
1794
2249
  // packages/core/mesh/network-manager/src/transport/memory-transport.ts
1795
2250
  import { Transform } from "@dxos/node-std/stream";
1796
- import invariant9 from "tiny-invariant";
1797
2251
  import { Event as Event6, Trigger } from "@dxos/async";
1798
2252
  import { ErrorStream as ErrorStream3 } from "@dxos/debug";
1799
- import { PublicKey as PublicKey8 } from "@dxos/keys";
1800
- import { log as log9, logInfo as logInfo2 } from "@dxos/log";
1801
- import { ComplexMap as ComplexMap6 } from "@dxos/util";
2253
+ import { invariant as invariant10 } from "@dxos/invariant";
2254
+ import { PublicKey as PublicKey9 } from "@dxos/keys";
2255
+ import { log as log10, logInfo as logInfo2 } from "@dxos/log";
2256
+ import { ComplexMap as ComplexMap7 } from "@dxos/util";
1802
2257
  function _ts_decorate4(decorators, target, key, desc) {
1803
2258
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1804
2259
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -1809,7 +2264,7 @@ function _ts_decorate4(decorators, target, key, desc) {
1809
2264
  r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1810
2265
  return c > 3 && r && Object.defineProperty(target, key, r), r;
1811
2266
  }
1812
- var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/memory-transport.ts";
2267
+ var __dxlog_file11 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/memory-transport.ts";
1813
2268
  var MEMORY_TRANSPORT_DELAY = 1;
1814
2269
  var createStreamDelay = (delay) => {
1815
2270
  return new Transform({
@@ -1822,30 +2277,41 @@ var createStreamDelay = (delay) => {
1822
2277
  var MemoryTransportFactory = {
1823
2278
  createTransport: (params) => new MemoryTransport(params)
1824
2279
  };
1825
- var _MemoryTransport = class {
2280
+ var MemoryTransport = class _MemoryTransport {
2281
+ static {
2282
+ // TODO(burdon): Remove static properties (inject context into constructor).
2283
+ this._connections = new ComplexMap7(PublicKey9.hash);
2284
+ }
1826
2285
  constructor(options) {
1827
- var _a;
1828
2286
  this.options = options;
1829
2287
  this.closed = new Event6();
1830
2288
  this.connected = new Event6();
1831
2289
  this.errors = new ErrorStream3();
1832
- this._instanceId = PublicKey8.random();
2290
+ this._instanceId = PublicKey9.random();
1833
2291
  this._remote = new Trigger();
1834
2292
  this._outgoingDelay = createStreamDelay(MEMORY_TRANSPORT_DELAY);
1835
2293
  this._incomingDelay = createStreamDelay(MEMORY_TRANSPORT_DELAY);
1836
2294
  this._destroyed = false;
1837
- log9("creating", void 0, {
1838
- F: __dxlog_file9,
2295
+ log10("creating", void 0, {
2296
+ F: __dxlog_file11,
1839
2297
  L: 64,
1840
2298
  S: this,
1841
2299
  C: (f, a) => f(...a)
1842
2300
  });
1843
- invariant9(!_MemoryTransport._connections.has(this._instanceId), "Duplicate memory connection");
2301
+ invariant10(!_MemoryTransport._connections.has(this._instanceId), "Duplicate memory connection", {
2302
+ F: __dxlog_file11,
2303
+ L: 66,
2304
+ S: this,
2305
+ A: [
2306
+ "!MemoryTransport._connections.has(this._instanceId)",
2307
+ "'Duplicate memory connection'"
2308
+ ]
2309
+ });
1844
2310
  _MemoryTransport._connections.set(this._instanceId, this);
1845
2311
  if (this.options.initiator) {
1846
2312
  setTimeout(async () => {
1847
- log9("sending signal", void 0, {
1848
- F: __dxlog_file9,
2313
+ log10("sending signal", void 0, {
2314
+ F: __dxlog_file11,
1849
2315
  L: 73,
1850
2316
  S: this,
1851
2317
  C: (f, a) => f(...a)
@@ -1862,7 +2328,7 @@ var _MemoryTransport = class {
1862
2328
  });
1863
2329
  } else {
1864
2330
  this._remote.wait({
1865
- timeout: (_a = this.options.timeout) != null ? _a : 1e3
2331
+ timeout: this.options.timeout ?? 1e3
1866
2332
  }).then((remoteId) => {
1867
2333
  if (this._destroyed) {
1868
2334
  return;
@@ -1874,11 +2340,19 @@ var _MemoryTransport = class {
1874
2340
  this.closed.emit();
1875
2341
  return;
1876
2342
  }
1877
- invariant9(!this._remoteConnection._remoteConnection, `Remote already connected: ${this._remoteInstanceId}`);
2343
+ invariant10(!this._remoteConnection._remoteConnection, `Remote already connected: ${this._remoteInstanceId}`, {
2344
+ F: __dxlog_file11,
2345
+ L: 99,
2346
+ S: this,
2347
+ A: [
2348
+ "!this._remoteConnection._remoteConnection",
2349
+ "`Remote already connected: ${this._remoteInstanceId}`"
2350
+ ]
2351
+ });
1878
2352
  this._remoteConnection._remoteConnection = this;
1879
2353
  this._remoteConnection._remoteInstanceId = this._instanceId;
1880
- log9("connected", void 0, {
1881
- F: __dxlog_file9,
2354
+ log10("connected", void 0, {
2355
+ F: __dxlog_file11,
1882
2356
  L: 103,
1883
2357
  S: this,
1884
2358
  C: (f, a) => f(...a)
@@ -1895,8 +2369,8 @@ var _MemoryTransport = class {
1895
2369
  }
1896
2370
  }
1897
2371
  async destroy() {
1898
- log9("closing", void 0, {
1899
- F: __dxlog_file9,
2372
+ log10("closing", void 0, {
2373
+ F: __dxlog_file11,
1900
2374
  L: 124,
1901
2375
  S: this,
1902
2376
  C: (f, a) => f(...a)
@@ -1904,8 +2378,8 @@ var _MemoryTransport = class {
1904
2378
  this._destroyed = true;
1905
2379
  _MemoryTransport._connections.delete(this._instanceId);
1906
2380
  if (this._remoteConnection) {
1907
- log9("closing", void 0, {
1908
- F: __dxlog_file9,
2381
+ log10("closing", void 0, {
2382
+ F: __dxlog_file11,
1909
2383
  L: 129,
1910
2384
  S: this,
1911
2385
  C: (f, a) => f(...a)
@@ -1917,43 +2391,40 @@ var _MemoryTransport = class {
1917
2391
  this._remoteConnection.closed.emit();
1918
2392
  this._remoteConnection._remoteConnection = void 0;
1919
2393
  this._remoteConnection = void 0;
1920
- log9("closed", void 0, {
1921
- F: __dxlog_file9,
2394
+ log10("closed", void 0, {
2395
+ F: __dxlog_file11,
1922
2396
  L: 147,
1923
2397
  S: this,
1924
2398
  C: (f, a) => f(...a)
1925
2399
  });
1926
2400
  }
1927
2401
  this.closed.emit();
1928
- log9("closed", void 0, {
1929
- F: __dxlog_file9,
2402
+ log10("closed", void 0, {
2403
+ F: __dxlog_file11,
1930
2404
  L: 151,
1931
2405
  S: this,
1932
2406
  C: (f, a) => f(...a)
1933
2407
  });
1934
2408
  }
1935
2409
  signal({ payload }) {
1936
- log9("received signal", {
2410
+ log10("received signal", {
1937
2411
  payload
1938
2412
  }, {
1939
- F: __dxlog_file9,
2413
+ F: __dxlog_file11,
1940
2414
  L: 155,
1941
2415
  S: this,
1942
2416
  C: (f, a) => f(...a)
1943
2417
  });
1944
- if (!(payload == null ? void 0 : payload.transportId)) {
2418
+ if (!payload?.transportId) {
1945
2419
  return;
1946
2420
  }
1947
2421
  const transportId = payload.transportId;
1948
2422
  if (transportId) {
1949
- const remoteId = PublicKey8.fromHex(transportId);
2423
+ const remoteId = PublicKey9.fromHex(transportId);
1950
2424
  this._remote.wake(remoteId);
1951
2425
  }
1952
2426
  }
1953
2427
  };
1954
- var MemoryTransport = _MemoryTransport;
1955
- // TODO(burdon): Remove static properties (inject context into constructor).
1956
- MemoryTransport._connections = new ComplexMap6(PublicKey8.hash);
1957
2428
  _ts_decorate4([
1958
2429
  logInfo2
1959
2430
  ], MemoryTransport.prototype, "_instanceId", void 0);
@@ -1963,54 +2434,58 @@ _ts_decorate4([
1963
2434
 
1964
2435
  // packages/core/mesh/network-manager/src/transport/webrtc-transport.ts
1965
2436
  import SimplePeerConstructor from "simple-peer";
1966
- import invariant10 from "tiny-invariant";
1967
2437
  import { Event as Event7 } from "@dxos/async";
1968
2438
  import { ErrorStream as ErrorStream4, raise as raise2 } from "@dxos/debug";
1969
- import { PublicKey as PublicKey9 } from "@dxos/keys";
1970
- import { log as log10 } from "@dxos/log";
2439
+ import { invariant as invariant11 } from "@dxos/invariant";
2440
+ import { PublicKey as PublicKey10 } from "@dxos/keys";
2441
+ import { log as log11 } from "@dxos/log";
1971
2442
  import { trace as trace4 } from "@dxos/protocols";
1972
2443
 
1973
2444
  // packages/core/mesh/network-manager/src/transport/webrtc.ts
1974
2445
  var wrtc = null;
1975
2446
  try {
1976
2447
  wrtc = __require("@koush/wrtc");
1977
- } catch (e) {
2448
+ } catch {
1978
2449
  }
1979
2450
 
1980
2451
  // packages/core/mesh/network-manager/src/transport/webrtc-transport.ts
1981
- var __dxlog_file10 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc-transport.ts";
2452
+ var __dxlog_file12 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc-transport.ts";
1982
2453
  var WebRTCTransport = class {
1983
2454
  constructor(params) {
1984
- var _a;
1985
2455
  this.params = params;
2456
+ this._instanceId = PublicKey10.random().toHex();
1986
2457
  this._closed = false;
1987
2458
  this.closed = new Event7();
1988
2459
  this.connected = new Event7();
1989
2460
  this.errors = new ErrorStream4();
1990
- this._instanceId = PublicKey9.random().toHex();
1991
- log10.trace("dxos.mesh.webrtc-transport.constructor", trace4.begin({
2461
+ log11.trace("dxos.mesh.webrtc-transport.constructor", trace4.begin({
1992
2462
  id: this._instanceId
1993
2463
  }), {
1994
- F: __dxlog_file10,
1995
- L: 39,
2464
+ F: __dxlog_file12,
2465
+ L: 44,
1996
2466
  S: this,
1997
2467
  C: (f, a) => f(...a)
1998
2468
  });
1999
- log10("created connection", params, {
2000
- F: __dxlog_file10,
2001
- L: 40,
2469
+ log11("created connection", params, {
2470
+ F: __dxlog_file12,
2471
+ L: 45,
2002
2472
  S: this,
2003
2473
  C: (f, a) => f(...a)
2004
2474
  });
2005
2475
  this._peer = new SimplePeerConstructor({
2006
2476
  initiator: this.params.initiator,
2007
- wrtc: SimplePeerConstructor.WEBRTC_SUPPORT ? void 0 : (_a = wrtc) != null ? _a : raise2(new Error("wrtc not available")),
2008
- config: this.params.webrtcConfig
2477
+ config: this.params.webrtcConfig,
2478
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/createDataChannel
2479
+ channelConfig: {
2480
+ protocol: "dxos.mesh"
2481
+ },
2482
+ // Custom WebRTC implementation (for Node); otherwise get-browser-rtc.
2483
+ wrtc: SimplePeerConstructor.WEBRTC_SUPPORT ? void 0 : wrtc ?? raise2(new Error("wrtc not available"))
2009
2484
  });
2010
2485
  this._peer.on("signal", async (data) => {
2011
- log10("signal", data, {
2012
- F: __dxlog_file10,
2013
- L: 48,
2486
+ log11("signal", data, {
2487
+ F: __dxlog_file12,
2488
+ L: 62,
2014
2489
  S: this,
2015
2490
  C: (f, a) => f(...a)
2016
2491
  });
@@ -2021,9 +2496,9 @@ var WebRTCTransport = class {
2021
2496
  });
2022
2497
  });
2023
2498
  this._peer.on("connect", () => {
2024
- log10("connected", void 0, {
2025
- F: __dxlog_file10,
2026
- L: 53,
2499
+ log11("connected", void 0, {
2500
+ F: __dxlog_file12,
2501
+ L: 67,
2027
2502
  S: this,
2028
2503
  C: (f, a) => f(...a)
2029
2504
  });
@@ -2031,9 +2506,9 @@ var WebRTCTransport = class {
2031
2506
  this.connected.emit();
2032
2507
  });
2033
2508
  this._peer.on("close", async () => {
2034
- log10("closed", void 0, {
2035
- F: __dxlog_file10,
2036
- L: 59,
2509
+ log11("closed", void 0, {
2510
+ F: __dxlog_file12,
2511
+ L: 73,
2037
2512
  S: this,
2038
2513
  C: (f, a) => f(...a)
2039
2514
  });
@@ -2041,39 +2516,38 @@ var WebRTCTransport = class {
2041
2516
  this.closed.emit();
2042
2517
  });
2043
2518
  this._peer.on("error", async (err) => {
2044
- var _a2;
2045
2519
  this.errors.raise(err);
2046
2520
  try {
2047
- if (typeof ((_a2 = this._peer) == null ? void 0 : _a2._pc.getStats) === "function") {
2521
+ if (typeof this._peer?._pc.getStats === "function") {
2048
2522
  this._peer._pc.getStats().then((stats) => {
2049
- log10.warn("report after webrtc error", {
2523
+ log11.warn("report after webrtc error", {
2050
2524
  config: this.params.webrtcConfig,
2051
2525
  stats
2052
2526
  }, {
2053
- F: __dxlog_file10,
2054
- L: 71,
2527
+ F: __dxlog_file12,
2528
+ L: 85,
2055
2529
  S: this,
2056
2530
  C: (f, a) => f(...a)
2057
2531
  });
2058
2532
  });
2059
2533
  }
2060
- } catch (e) {
2534
+ } catch {
2061
2535
  }
2062
2536
  await this.destroy();
2063
2537
  });
2064
- log10.trace("dxos.mesh.webrtc-transport.constructor", trace4.end({
2538
+ log11.trace("dxos.mesh.webrtc-transport.constructor", trace4.end({
2065
2539
  id: this._instanceId
2066
2540
  }), {
2067
- F: __dxlog_file10,
2068
- L: 81,
2541
+ F: __dxlog_file12,
2542
+ L: 95,
2069
2543
  S: this,
2070
2544
  C: (f, a) => f(...a)
2071
2545
  });
2072
2546
  }
2073
2547
  async destroy() {
2074
- log10("closing...", void 0, {
2075
- F: __dxlog_file10,
2076
- L: 85,
2548
+ log11("closing...", void 0, {
2549
+ F: __dxlog_file12,
2550
+ L: 99,
2077
2551
  S: this,
2078
2552
  C: (f, a) => f(...a)
2079
2553
  });
@@ -2081,9 +2555,9 @@ var WebRTCTransport = class {
2081
2555
  await this._disconnectStreams();
2082
2556
  this._peer.destroy();
2083
2557
  this.closed.emit();
2084
- log10("closed", void 0, {
2085
- F: __dxlog_file10,
2086
- L: 90,
2558
+ log11("closed", void 0, {
2559
+ F: __dxlog_file12,
2560
+ L: 104,
2087
2561
  S: this,
2088
2562
  C: (f, a) => f(...a)
2089
2563
  });
@@ -2092,12 +2566,19 @@ var WebRTCTransport = class {
2092
2566
  if (this._closed) {
2093
2567
  return;
2094
2568
  }
2095
- invariant10(signal.payload.data, "Signal message must contain signal data.");
2569
+ invariant11(signal.payload.data, "Signal message must contain signal data.", {
2570
+ F: __dxlog_file12,
2571
+ L: 112,
2572
+ S: this,
2573
+ A: [
2574
+ "signal.payload.data",
2575
+ "'Signal message must contain signal data.'"
2576
+ ]
2577
+ });
2096
2578
  this._peer.signal(signal.payload.data);
2097
2579
  }
2098
2580
  async _disconnectStreams() {
2099
- var _a, _b, _c, _d;
2100
- (_d = (_c = (_b = (_a = this.params.stream).unpipe) == null ? void 0 : _b.call(_a, this._peer)) == null ? void 0 : _c.unpipe) == null ? void 0 : _d.call(_c, this.params.stream);
2581
+ this.params.stream.unpipe?.(this._peer)?.unpipe?.(this.params.stream);
2101
2582
  }
2102
2583
  };
2103
2584
  var createWebRTCTransportFactory = (webrtcConfig) => ({
@@ -2109,23 +2590,30 @@ var createWebRTCTransportFactory = (webrtcConfig) => ({
2109
2590
 
2110
2591
  // packages/core/mesh/network-manager/src/transport/webrtc-transport-service.ts
2111
2592
  import { Duplex } from "@dxos/node-std/stream";
2112
- import invariant11 from "tiny-invariant";
2113
2593
  import { Stream } from "@dxos/codec-protobuf";
2114
- import { PublicKey as PublicKey10 } from "@dxos/keys";
2115
- import { log as log11 } from "@dxos/log";
2594
+ import { invariant as invariant12 } from "@dxos/invariant";
2595
+ import { PublicKey as PublicKey11 } from "@dxos/keys";
2596
+ import { log as log12 } from "@dxos/log";
2116
2597
  import { ConnectionState as ConnectionState3 } from "@dxos/protocols/proto/dxos/mesh/bridge";
2117
- import { ComplexMap as ComplexMap7 } from "@dxos/util";
2118
- var __dxlog_file11 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc-transport-service.ts";
2598
+ import { ComplexMap as ComplexMap8 } from "@dxos/util";
2599
+ var __dxlog_file13 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc-transport-service.ts";
2119
2600
  var WebRTCTransportService = class {
2120
2601
  // prettier-ignore
2121
2602
  constructor(_webrtcConfig) {
2122
2603
  this._webrtcConfig = _webrtcConfig;
2123
- this.transports = new ComplexMap7(PublicKey10.hash);
2604
+ this.transports = new ComplexMap8(PublicKey11.hash);
2124
2605
  }
2125
2606
  open(request) {
2126
2607
  const rpcStream = new Stream(({ ready, next, close }) => {
2127
2608
  const duplex = new Duplex({
2128
2609
  read: () => {
2610
+ const callbacks = [
2611
+ ...transportState.writeCallbacks
2612
+ ];
2613
+ transportState.writeCallbacks.length = 0;
2614
+ for (const cb of callbacks) {
2615
+ cb();
2616
+ }
2129
2617
  },
2130
2618
  write: function(chunk, _, callback) {
2131
2619
  next({
@@ -2177,30 +2665,53 @@ var WebRTCTransportService = class {
2177
2665
  });
2178
2666
  close();
2179
2667
  });
2180
- ready();
2181
- this.transports.set(request.proxyId, {
2668
+ const transportState = {
2182
2669
  transport,
2183
- stream: duplex
2184
- });
2670
+ stream: duplex,
2671
+ writeCallbacks: []
2672
+ };
2673
+ ready();
2674
+ this.transports.set(request.proxyId, transportState);
2185
2675
  });
2186
2676
  return rpcStream;
2187
2677
  }
2188
2678
  async sendSignal({ proxyId, signal }) {
2189
- invariant11(this.transports.has(proxyId));
2679
+ invariant12(this.transports.has(proxyId), void 0, {
2680
+ F: __dxlog_file13,
2681
+ L: 113,
2682
+ S: this,
2683
+ A: [
2684
+ "this.transports.has(proxyId)",
2685
+ ""
2686
+ ]
2687
+ });
2190
2688
  await this.transports.get(proxyId).transport.signal(signal);
2191
2689
  }
2192
2690
  async sendData({ proxyId, payload }) {
2193
- invariant11(this.transports.has(proxyId));
2194
- await this.transports.get(proxyId).stream.push(payload);
2691
+ invariant12(this.transports.has(proxyId), void 0, {
2692
+ F: __dxlog_file13,
2693
+ L: 118,
2694
+ S: this,
2695
+ A: [
2696
+ "this.transports.has(proxyId)",
2697
+ ""
2698
+ ]
2699
+ });
2700
+ const state = this.transports.get(proxyId);
2701
+ const bufferHasSpace = state.stream.push(payload);
2702
+ if (!bufferHasSpace) {
2703
+ await new Promise((resolve) => {
2704
+ state.writeCallbacks.push(resolve);
2705
+ });
2706
+ }
2195
2707
  }
2196
2708
  async close({ proxyId }) {
2197
- var _a, _b;
2198
- await ((_a = this.transports.get(proxyId)) == null ? void 0 : _a.transport.destroy());
2199
- await ((_b = this.transports.get(proxyId)) == null ? void 0 : _b.stream.end());
2709
+ await this.transports.get(proxyId)?.transport.destroy();
2710
+ await this.transports.get(proxyId)?.stream.end();
2200
2711
  this.transports.delete(proxyId);
2201
- log11("Closed.", void 0, {
2202
- F: __dxlog_file11,
2203
- L: 109,
2712
+ log12("Closed.", void 0, {
2713
+ F: __dxlog_file13,
2714
+ L: 132,
2204
2715
  S: this,
2205
2716
  C: (f, a) => f(...a)
2206
2717
  });
@@ -2208,34 +2719,35 @@ var WebRTCTransportService = class {
2208
2719
  };
2209
2720
 
2210
2721
  // packages/core/mesh/network-manager/src/transport/webrtc-transport-proxy.ts
2211
- import invariant12 from "tiny-invariant";
2722
+ import { Writable } from "@dxos/node-std/stream";
2212
2723
  import { Event as Event8 } from "@dxos/async";
2213
- import { Context as Context5 } from "@dxos/context";
2724
+ import { Context as Context6 } from "@dxos/context";
2214
2725
  import { ErrorStream as ErrorStream5 } from "@dxos/debug";
2215
- import { PublicKey as PublicKey11 } from "@dxos/keys";
2216
- import { log as log12 } from "@dxos/log";
2726
+ import { invariant as invariant13 } from "@dxos/invariant";
2727
+ import { PublicKey as PublicKey12 } from "@dxos/keys";
2728
+ import { log as log13 } from "@dxos/log";
2217
2729
  import { ConnectionState as ConnectionState4 } from "@dxos/protocols/proto/dxos/mesh/bridge";
2218
2730
  import { arrayToBuffer } from "@dxos/util";
2219
- var __dxlog_file12 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc-transport-proxy.ts";
2731
+ var __dxlog_file14 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc-transport-proxy.ts";
2220
2732
  var WebRTCTransportProxy = class {
2221
2733
  // prettier-ignore
2222
2734
  constructor(_params) {
2223
2735
  this._params = _params;
2224
- this._proxyId = PublicKey11.random();
2225
- this._ctx = new Context5();
2736
+ this._proxyId = PublicKey12.random();
2737
+ this._ctx = new Context6();
2226
2738
  this.closed = new Event8();
2227
- this._closed = false;
2228
2739
  this.connected = new Event8();
2229
2740
  this.errors = new ErrorStream5();
2741
+ this._closed = false;
2230
2742
  this._serviceStream = this._params.bridgeService.open({
2231
2743
  proxyId: this._proxyId,
2232
2744
  initiator: this._params.initiator
2233
2745
  });
2234
2746
  this._serviceStream.waitUntilReady().then(() => {
2235
2747
  this._serviceStream.subscribe(async (event) => {
2236
- log12("WebRTCTransportProxy: event", event, {
2237
- F: __dxlog_file12,
2238
- L: 50,
2748
+ log13("WebRTCTransportProxy: event", event, {
2749
+ F: __dxlog_file14,
2750
+ L: 51,
2239
2751
  S: this,
2240
2752
  C: (f, a) => f(...a)
2241
2753
  });
@@ -2247,28 +2759,24 @@ var WebRTCTransportProxy = class {
2247
2759
  await this._handleSignal(event.signal);
2248
2760
  }
2249
2761
  });
2250
- const dataListener = async (data) => {
2251
- try {
2252
- await this._params.bridgeService.sendData({
2762
+ this._params.stream.pipe(new Writable({
2763
+ write: (chunk, _, callback) => {
2764
+ this._params.bridgeService.sendData({
2253
2765
  proxyId: this._proxyId,
2254
- payload: data
2255
- });
2256
- } catch (err) {
2257
- log12.catch(err, void 0, {
2258
- F: __dxlog_file12,
2259
- L: 67,
2260
- S: this,
2261
- C: (f, a) => f(...a)
2766
+ payload: chunk
2767
+ }).then(() => callback(), (err) => {
2768
+ log13.catch(err, void 0, {
2769
+ F: __dxlog_file14,
2770
+ L: 69,
2771
+ S: this,
2772
+ C: (f, a) => f(...a)
2773
+ });
2262
2774
  });
2263
2775
  }
2264
- };
2265
- this._params.stream.on("data", dataListener);
2266
- this._ctx.onDispose(() => {
2267
- this._params.stream.off("data", dataListener);
2268
- });
2269
- }, (error) => log12.catch(error, void 0, {
2270
- F: __dxlog_file12,
2271
- L: 73,
2776
+ }));
2777
+ }, (error) => log13.catch(error, void 0, {
2778
+ F: __dxlog_file14,
2779
+ L: 75,
2272
2780
  S: this,
2273
2781
  C: (f, a) => f(...a)
2274
2782
  }));
@@ -2306,15 +2814,15 @@ var WebRTCTransportProxy = class {
2306
2814
  if (this._closed) {
2307
2815
  return;
2308
2816
  }
2309
- this._serviceStream.close();
2817
+ await this._serviceStream.close();
2310
2818
  try {
2311
2819
  await this._params.bridgeService.close({
2312
2820
  proxyId: this._proxyId
2313
2821
  });
2314
2822
  } catch (err) {
2315
- log12.catch(err, void 0, {
2316
- F: __dxlog_file12,
2317
- L: 124,
2823
+ log13.catch(err, void 0, {
2824
+ F: __dxlog_file14,
2825
+ L: 126,
2318
2826
  S: this,
2319
2827
  C: (f, a) => f(...a)
2320
2828
  });
@@ -2327,7 +2835,7 @@ var WebRTCTransportProxy = class {
2327
2835
  */
2328
2836
  // TODO(burdon): Option on close method.
2329
2837
  forceClose() {
2330
- this._serviceStream.close();
2838
+ void this._serviceStream.close();
2331
2839
  this.closed.emit();
2332
2840
  this._closed = true;
2333
2841
  }
@@ -2348,7 +2856,15 @@ var WebRTCTransportProxyFactory = class {
2348
2856
  return this;
2349
2857
  }
2350
2858
  createTransport(options) {
2351
- invariant12(this._bridgeService, "WebRTCTransportProxyFactory is not ready to open connections");
2859
+ invariant13(this._bridgeService, "WebRTCTransportProxyFactory is not ready to open connections", {
2860
+ F: __dxlog_file14,
2861
+ L: 163,
2862
+ S: this,
2863
+ A: [
2864
+ "this._bridgeService",
2865
+ "'WebRTCTransportProxyFactory is not ready to open connections'"
2866
+ ]
2867
+ });
2352
2868
  const transport = new WebRTCTransportProxy({
2353
2869
  ...options,
2354
2870
  bridgeService: this._bridgeService
@@ -2383,6 +2899,8 @@ export {
2383
2899
  SwarmMessenger,
2384
2900
  Swarm,
2385
2901
  SwarmMapper,
2902
+ MAX_CONCURRENT_INITIATING_CONNECTIONS,
2903
+ ConnectionLimiter,
2386
2904
  EventType,
2387
2905
  ConnectionLog,
2388
2906
  NetworkManager,
@@ -2398,4 +2916,4 @@ export {
2398
2916
  WebRTCTransportProxyFactory,
2399
2917
  createTeleportProtocolFactory
2400
2918
  };
2401
- //# sourceMappingURL=chunk-MIYEP22D.mjs.map
2919
+ //# sourceMappingURL=chunk-BVDMMHEG.mjs.map