@dxos/network-manager 0.1.56-main.f3d4052 → 0.1.56-next.71eb10c

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