@dxos/network-manager 0.6.13 → 0.6.14-main.1366248

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 (164) hide show
  1. package/dist/lib/browser/{chunk-XYSYUN63.mjs → chunk-UEVA7BFW.mjs} +1323 -1102
  2. package/dist/lib/browser/chunk-UEVA7BFW.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +9 -19
  4. package/dist/lib/browser/meta.json +1 -1
  5. package/dist/lib/browser/testing/index.mjs +30 -37
  6. package/dist/lib/browser/testing/index.mjs.map +3 -3
  7. package/dist/lib/browser/transport/tcp/index.mjs +38 -0
  8. package/dist/lib/browser/transport/tcp/index.mjs.map +7 -0
  9. package/dist/lib/node/{chunk-4YAYC7WN.cjs → chunk-LK5D44SA.cjs} +1336 -1239
  10. package/dist/lib/node/chunk-LK5D44SA.cjs.map +7 -0
  11. package/dist/lib/node/index.cjs +27 -37
  12. package/dist/lib/node/index.cjs.map +2 -2
  13. package/dist/lib/node/meta.json +1 -1
  14. package/dist/lib/node/testing/index.cjs +34 -38
  15. package/dist/lib/node/testing/index.cjs.map +3 -3
  16. package/dist/lib/node/transport/tcp/index.cjs +191 -0
  17. package/dist/lib/node/transport/tcp/index.cjs.map +7 -0
  18. package/dist/lib/node-esm/chunk-Y5TD36KR.mjs +4413 -0
  19. package/dist/lib/node-esm/chunk-Y5TD36KR.mjs.map +7 -0
  20. package/dist/lib/node-esm/index.mjs +50 -0
  21. package/dist/lib/node-esm/index.mjs.map +7 -0
  22. package/dist/lib/node-esm/meta.json +1 -0
  23. package/dist/lib/node-esm/testing/index.mjs +285 -0
  24. package/dist/lib/node-esm/testing/index.mjs.map +7 -0
  25. package/dist/lib/node-esm/transport/tcp/index.mjs +159 -0
  26. package/dist/lib/node-esm/transport/tcp/index.mjs.map +7 -0
  27. package/dist/types/src/network-manager.d.ts +2 -1
  28. package/dist/types/src/network-manager.d.ts.map +1 -1
  29. package/dist/types/src/signal/ice.d.ts.map +1 -1
  30. package/dist/types/src/signal/integration.node.test.d.ts +2 -0
  31. package/dist/types/src/signal/integration.node.test.d.ts.map +1 -0
  32. package/dist/types/src/signal/swarm-messenger.node.test.d.ts +2 -0
  33. package/dist/types/src/signal/swarm-messenger.node.test.d.ts.map +1 -0
  34. package/dist/types/src/swarm/connection.d.ts.map +1 -1
  35. package/dist/types/src/swarm/peer.d.ts.map +1 -1
  36. package/dist/types/src/swarm/swarm.d.ts +2 -1
  37. package/dist/types/src/swarm/swarm.d.ts.map +1 -1
  38. package/dist/types/src/testing/test-builder.d.ts +2 -2
  39. package/dist/types/src/testing/test-builder.d.ts.map +1 -1
  40. package/dist/types/src/testing/test-wire-protocol.d.ts +1 -2
  41. package/dist/types/src/testing/test-wire-protocol.d.ts.map +1 -1
  42. package/dist/types/src/tests/basic-test-suite.d.ts.map +1 -1
  43. package/dist/types/src/tests/property-test-suite.d.ts.map +1 -1
  44. package/dist/types/src/tests/tcp-transport.node.test.d.ts +2 -0
  45. package/dist/types/src/tests/tcp-transport.node.test.d.ts.map +1 -0
  46. package/dist/types/src/tests/utils.d.ts.map +1 -1
  47. package/dist/types/src/transport/index.d.ts +1 -5
  48. package/dist/types/src/transport/index.d.ts.map +1 -1
  49. package/dist/types/src/transport/memory-transport.d.ts +2 -2
  50. package/dist/types/src/transport/memory-transport.d.ts.map +1 -1
  51. package/dist/types/src/transport/tcp/index.d.ts +2 -0
  52. package/dist/types/src/transport/tcp/index.d.ts.map +1 -0
  53. package/dist/types/src/transport/{tcp-transport.browser.d.ts → tcp/tcp-transport.browser.d.ts} +3 -3
  54. package/dist/types/src/transport/tcp/tcp-transport.browser.d.ts.map +1 -0
  55. package/dist/types/src/transport/{tcp-transport.d.ts → tcp/tcp-transport.d.ts} +3 -3
  56. package/dist/types/src/transport/tcp/tcp-transport.d.ts.map +1 -0
  57. package/dist/types/src/transport/transport.d.ts +7 -6
  58. package/dist/types/src/transport/transport.d.ts.map +1 -1
  59. package/dist/types/src/transport/webrtc/index.d.ts +4 -0
  60. package/dist/types/src/transport/webrtc/index.d.ts.map +1 -0
  61. package/dist/types/src/transport/webrtc/rtc-connection-factory.d.ts +14 -0
  62. package/dist/types/src/transport/webrtc/rtc-connection-factory.d.ts.map +1 -0
  63. package/dist/types/src/transport/webrtc/rtc-peer-connection.d.ts +68 -0
  64. package/dist/types/src/transport/webrtc/rtc-peer-connection.d.ts.map +1 -0
  65. package/dist/types/src/transport/webrtc/rtc-transport-channel.d.ts +33 -0
  66. package/dist/types/src/transport/webrtc/rtc-transport-channel.d.ts.map +1 -0
  67. package/dist/types/src/transport/webrtc/rtc-transport-channel.test.d.ts +2 -0
  68. package/dist/types/src/transport/webrtc/rtc-transport-channel.test.d.ts.map +1 -0
  69. package/dist/types/src/transport/webrtc/rtc-transport-factory.d.ts +4 -0
  70. package/dist/types/src/transport/webrtc/rtc-transport-factory.d.ts.map +1 -0
  71. package/dist/types/src/transport/{simplepeer-transport-proxy.d.ts → webrtc/rtc-transport-proxy.d.ts} +10 -12
  72. package/dist/types/src/transport/webrtc/rtc-transport-proxy.d.ts.map +1 -0
  73. package/dist/types/src/transport/webrtc/rtc-transport-proxy.test.d.ts +2 -0
  74. package/dist/types/src/transport/webrtc/rtc-transport-proxy.test.d.ts.map +1 -0
  75. package/dist/types/src/transport/{simplepeer-transport-service.d.ts → webrtc/rtc-transport-service.d.ts} +9 -7
  76. package/dist/types/src/transport/webrtc/rtc-transport-service.d.ts.map +1 -0
  77. package/dist/types/src/transport/webrtc/rtc-transport-stats.d.ts +4 -0
  78. package/dist/types/src/transport/webrtc/rtc-transport-stats.d.ts.map +1 -0
  79. package/dist/types/src/transport/webrtc/rtc-transport.test.d.ts +2 -0
  80. package/dist/types/src/transport/webrtc/rtc-transport.test.d.ts.map +1 -0
  81. package/dist/types/src/transport/webrtc/test-utils.d.ts +5 -0
  82. package/dist/types/src/transport/webrtc/test-utils.d.ts.map +1 -0
  83. package/dist/types/src/transport/webrtc/utils.d.ts +3 -0
  84. package/dist/types/src/transport/webrtc/utils.d.ts.map +1 -0
  85. package/package.json +53 -36
  86. package/src/network-manager.ts +5 -13
  87. package/src/signal/ice.test.ts +1 -3
  88. package/src/signal/ice.ts +6 -1
  89. package/src/signal/{integration.test.ts → integration.node.test.ts} +9 -15
  90. package/src/signal/{swarm-messenger.test.ts → swarm-messenger.node.test.ts} +13 -23
  91. package/src/swarm/connection-limiter.test.ts +3 -6
  92. package/src/swarm/connection.test.ts +63 -38
  93. package/src/swarm/connection.ts +7 -7
  94. package/src/swarm/peer.ts +4 -1
  95. package/src/swarm/swarm.test.ts +10 -12
  96. package/src/swarm/swarm.ts +16 -3
  97. package/src/testing/test-builder.ts +14 -29
  98. package/src/testing/test-wire-protocol.ts +7 -8
  99. package/src/tests/basic-test-suite.ts +32 -31
  100. package/src/tests/memory-transport.test.ts +40 -42
  101. package/src/tests/property-test-suite.ts +21 -22
  102. package/src/tests/tcp-transport.node.test.ts +65 -0
  103. package/src/tests/utils.ts +3 -2
  104. package/src/tests/webrtc-transport.test.ts +10 -10
  105. package/src/transport/index.ts +1 -5
  106. package/src/transport/memory-transport.ts +2 -0
  107. package/src/transport/tcp/index.ts +5 -0
  108. package/src/transport/{tcp-transport.browser.ts → tcp/tcp-transport.browser.ts} +7 -3
  109. package/src/transport/{tcp-transport.ts → tcp/tcp-transport.ts} +3 -1
  110. package/src/transport/transport.ts +8 -7
  111. package/src/transport/webrtc/index.ts +7 -0
  112. package/src/transport/webrtc/rtc-connection-factory.ts +82 -0
  113. package/src/transport/webrtc/rtc-peer-connection.ts +472 -0
  114. package/src/transport/webrtc/rtc-transport-channel.test.ts +176 -0
  115. package/src/transport/webrtc/rtc-transport-channel.ts +195 -0
  116. package/src/transport/webrtc/rtc-transport-factory.ts +28 -0
  117. package/src/transport/webrtc/rtc-transport-proxy.test.ts +413 -0
  118. package/src/transport/webrtc/rtc-transport-proxy.ts +264 -0
  119. package/src/transport/webrtc/rtc-transport-service.ts +192 -0
  120. package/src/transport/webrtc/rtc-transport-stats.ts +67 -0
  121. package/src/transport/webrtc/rtc-transport.test.ts +210 -0
  122. package/src/transport/webrtc/test-utils.ts +22 -0
  123. package/src/transport/webrtc/utils.ts +36 -0
  124. package/src/typings.d.ts +8 -2
  125. package/dist/lib/browser/chunk-XYSYUN63.mjs.map +0 -7
  126. package/dist/lib/node/chunk-4YAYC7WN.cjs.map +0 -7
  127. package/dist/types/src/signal/integration.test.d.ts +0 -2
  128. package/dist/types/src/signal/integration.test.d.ts.map +0 -1
  129. package/dist/types/src/signal/swarm-messenger.test.d.ts +0 -2
  130. package/dist/types/src/signal/swarm-messenger.test.d.ts.map +0 -1
  131. package/dist/types/src/tests/tcp-transport.test.d.ts +0 -2
  132. package/dist/types/src/tests/tcp-transport.test.d.ts.map +0 -1
  133. package/dist/types/src/transport/libdatachannel-transport.d.ts +0 -42
  134. package/dist/types/src/transport/libdatachannel-transport.d.ts.map +0 -1
  135. package/dist/types/src/transport/libdatachannel-transport.test.d.ts +0 -2
  136. package/dist/types/src/transport/libdatachannel-transport.test.d.ts.map +0 -1
  137. package/dist/types/src/transport/memory-transport.test.d.ts +0 -2
  138. package/dist/types/src/transport/memory-transport.test.d.ts.map +0 -1
  139. package/dist/types/src/transport/simplepeer-simple-peer.d.ts +0 -2
  140. package/dist/types/src/transport/simplepeer-simple-peer.d.ts.map +0 -1
  141. package/dist/types/src/transport/simplepeer-transport-proxy-test.d.ts +0 -2
  142. package/dist/types/src/transport/simplepeer-transport-proxy-test.d.ts.map +0 -1
  143. package/dist/types/src/transport/simplepeer-transport-proxy.d.ts.map +0 -1
  144. package/dist/types/src/transport/simplepeer-transport-service.d.ts.map +0 -1
  145. package/dist/types/src/transport/simplepeer-transport.d.ts +0 -36
  146. package/dist/types/src/transport/simplepeer-transport.d.ts.map +0 -1
  147. package/dist/types/src/transport/simplepeer-transport.test.d.ts +0 -2
  148. package/dist/types/src/transport/simplepeer-transport.test.d.ts.map +0 -1
  149. package/dist/types/src/transport/tcp-transport.browser.d.ts.map +0 -1
  150. package/dist/types/src/transport/tcp-transport.d.ts.map +0 -1
  151. package/dist/types/src/transport/webrtc.d.ts +0 -6
  152. package/dist/types/src/transport/webrtc.d.ts.map +0 -1
  153. package/src/globals.d.ts +0 -7
  154. package/src/tests/tcp-transport.test.ts +0 -67
  155. package/src/transport/libdatachannel-transport.test.ts +0 -100
  156. package/src/transport/libdatachannel-transport.ts +0 -376
  157. package/src/transport/memory-transport.test.ts +0 -74
  158. package/src/transport/simplepeer-simple-peer.ts +0 -26
  159. package/src/transport/simplepeer-transport-proxy-test.ts +0 -181
  160. package/src/transport/simplepeer-transport-proxy.ts +0 -246
  161. package/src/transport/simplepeer-transport-service.ts +0 -160
  162. package/src/transport/simplepeer-transport.test.ts +0 -61
  163. package/src/transport/simplepeer-transport.ts +0 -250
  164. package/src/transport/webrtc.ts +0 -15
@@ -26,37 +26,32 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
26
26
  mod
27
27
  ));
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var chunk_4YAYC7WN_exports = {};
30
- __export(chunk_4YAYC7WN_exports, {
29
+ var chunk_LK5D44SA_exports = {};
30
+ __export(chunk_LK5D44SA_exports, {
31
31
  Connection: () => Connection,
32
32
  ConnectionLimiter: () => ConnectionLimiter,
33
33
  ConnectionLog: () => ConnectionLog,
34
34
  ConnectionState: () => ConnectionState,
35
35
  EventType: () => EventType,
36
36
  FullyConnectedTopology: () => FullyConnectedTopology,
37
- LibDataChannelTransport: () => LibDataChannelTransport,
38
37
  MAX_CONCURRENT_INITIATING_CONNECTIONS: () => MAX_CONCURRENT_INITIATING_CONNECTIONS,
39
38
  MMSTTopology: () => MMSTTopology,
40
39
  MemoryTransport: () => MemoryTransport,
41
40
  MemoryTransportFactory: () => MemoryTransportFactory,
42
- SimplePeerTransport: () => SimplePeerTransport,
43
- SimplePeerTransportProxy: () => SimplePeerTransportProxy,
44
- SimplePeerTransportProxyFactory: () => SimplePeerTransportProxyFactory,
45
- SimplePeerTransportService: () => SimplePeerTransportService,
41
+ RtcTransportProxy: () => RtcTransportProxy,
42
+ RtcTransportProxyFactory: () => RtcTransportProxyFactory,
43
+ RtcTransportService: () => RtcTransportService,
46
44
  StarTopology: () => StarTopology,
47
45
  Swarm: () => Swarm,
48
46
  SwarmMapper: () => SwarmMapper,
49
47
  SwarmMessenger: () => SwarmMessenger,
50
48
  SwarmNetworkManager: () => SwarmNetworkManager,
51
- TcpTransport: () => TcpTransport,
52
- TcpTransportFactory: () => TcpTransportFactory,
53
49
  TransportKind: () => TransportKind,
54
50
  createIceProvider: () => createIceProvider,
55
- createLibDataChannelTransportFactory: () => createLibDataChannelTransportFactory,
56
- createSimplePeerTransportFactory: () => createSimplePeerTransportFactory,
51
+ createRtcTransportFactory: () => createRtcTransportFactory,
57
52
  createTeleportProtocolFactory: () => createTeleportProtocolFactory
58
53
  });
59
- module.exports = __toCommonJS(chunk_4YAYC7WN_exports);
54
+ module.exports = __toCommonJS(chunk_LK5D44SA_exports);
60
55
  var import_async = require("@dxos/async");
61
56
  var import_context = require("@dxos/context");
62
57
  var import_debug = require("@dxos/debug");
@@ -125,46 +120,37 @@ var import_invariant10 = require("@dxos/invariant");
125
120
  var import_keys9 = require("@dxos/keys");
126
121
  var import_log11 = require("@dxos/log");
127
122
  var import_util8 = require("@dxos/util");
128
- var import_simple_peer = __toESM(require("simple-peer"));
129
- var import_tiny_invariant = __toESM(require("tiny-invariant"));
130
123
  var import_async10 = require("@dxos/async");
131
- var import_debug5 = require("@dxos/debug");
132
- var import_keys10 = require("@dxos/keys");
124
+ var import_async11 = require("@dxos/async");
125
+ var import_invariant11 = require("@dxos/invariant");
133
126
  var import_log12 = require("@dxos/log");
134
127
  var import_protocols7 = require("@dxos/protocols");
128
+ var import_tracing = require("@dxos/tracing");
135
129
  var import_node_stream2 = require("node:stream");
136
- var import_codec_protobuf = require("@dxos/codec-protobuf");
137
- var import_invariant11 = require("@dxos/invariant");
138
- var import_keys11 = require("@dxos/keys");
130
+ var import_async12 = require("@dxos/async");
131
+ var import_context6 = require("@dxos/context");
132
+ var import_debug5 = require("@dxos/debug");
133
+ var import_invariant12 = require("@dxos/invariant");
139
134
  var import_log13 = require("@dxos/log");
140
- var import_bridge = require("@dxos/protocols/proto/dxos/mesh/bridge");
141
- var import_util9 = require("@dxos/util");
135
+ var import_protocols8 = require("@dxos/protocols");
142
136
  var import_node_stream3 = require("node:stream");
143
- var import_async11 = require("@dxos/async");
144
- var import_context6 = require("@dxos/context");
137
+ var import_async13 = require("@dxos/async");
138
+ var import_context7 = require("@dxos/context");
145
139
  var import_debug6 = require("@dxos/debug");
146
- var import_invariant12 = require("@dxos/invariant");
147
- var import_keys12 = require("@dxos/keys");
140
+ var import_invariant13 = require("@dxos/invariant");
141
+ var import_keys10 = require("@dxos/keys");
148
142
  var import_log14 = require("@dxos/log");
149
- var import_protocols8 = require("@dxos/protocols");
143
+ var import_protocols9 = require("@dxos/protocols");
144
+ var import_bridge = require("@dxos/protocols/proto/dxos/mesh/bridge");
145
+ var import_util9 = require("@dxos/util");
146
+ var import_node_stream4 = require("node:stream");
147
+ var import_codec_protobuf = require("@dxos/codec-protobuf");
148
+ var import_invariant14 = require("@dxos/invariant");
149
+ var import_keys11 = require("@dxos/keys");
150
+ var import_log15 = require("@dxos/log");
150
151
  var import_bridge2 = require("@dxos/protocols/proto/dxos/mesh/bridge");
151
152
  var import_util10 = require("@dxos/util");
152
- var import_stream = require("stream");
153
- var import_async12 = require("@dxos/async");
154
- var import_debug7 = require("@dxos/debug");
155
- var import_invariant13 = require("@dxos/invariant");
156
- var import_log15 = require("@dxos/log");
157
- var import_node_net = require("node:net");
158
- var import_async13 = require("@dxos/async");
159
- var import_debug8 = require("@dxos/debug");
160
- var import_log16 = require("@dxos/log");
161
153
  var import_teleport = require("@dxos/teleport");
162
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
163
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
164
- }) : x)(function(x) {
165
- if (typeof require !== "undefined") return require.apply(this, arguments);
166
- throw Error('Dynamic require of "' + x + '" is not supported');
167
- });
168
154
  function _ts_decorate(decorators, target, key, desc) {
169
155
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
170
156
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -200,11 +186,11 @@ var Connection = class {
200
186
  this._callbacks = _callbacks;
201
187
  this._ctx = new import_context.Context(void 0, {
202
188
  F: __dxlog_file,
203
- L: 101
189
+ L: 100
204
190
  });
205
191
  this.connectedTimeoutContext = new import_context.Context(void 0, {
206
192
  F: __dxlog_file,
207
- L: 102
193
+ L: 101
208
194
  });
209
195
  this._protocolClosed = new import_async.Trigger();
210
196
  this._transportClosed = new import_async.Trigger();
@@ -227,7 +213,7 @@ var Connection = class {
227
213
  initiator: this.initiator
228
214
  }, {
229
215
  F: __dxlog_file,
230
- L: 138,
216
+ L: 137,
231
217
  S: this,
232
218
  C: (f, a) => f(...a)
233
219
  });
@@ -250,7 +236,7 @@ var Connection = class {
250
236
  async openConnection() {
251
237
  (0, import_invariant.invariant)(this._state === "INITIAL", "Invalid state.", {
252
238
  F: __dxlog_file,
253
- L: 168,
239
+ L: 167,
254
240
  S: this,
255
241
  A: [
256
242
  "this._state === ConnectionState.INITIAL",
@@ -261,7 +247,7 @@ var Connection = class {
261
247
  id: this._instanceId
262
248
  }), {
263
249
  F: __dxlog_file,
264
- L: 169,
250
+ L: 168,
265
251
  S: this,
266
252
  C: (f, a) => f(...a)
267
253
  });
@@ -273,7 +259,7 @@ var Connection = class {
273
259
  initiator: this.initiator
274
260
  }, {
275
261
  F: __dxlog_file,
276
- L: 170,
262
+ L: 169,
277
263
  S: this,
278
264
  C: (f, a) => f(...a)
279
265
  });
@@ -284,7 +270,7 @@ var Connection = class {
284
270
  this._protocol.stream.on("close", () => {
285
271
  (0, import_log.log)("protocol stream closed", void 0, {
286
272
  F: __dxlog_file,
287
- L: 187,
273
+ L: 186,
288
274
  S: this,
289
275
  C: (f, a) => f(...a)
290
276
  });
@@ -294,7 +280,7 @@ var Connection = class {
294
280
  (0, import_async.scheduleTask)(this.connectedTimeoutContext, async () => {
295
281
  import_log.log.info(`timeout waiting ${TRANSPORT_CONNECTION_TIMEOUT / 1e3}s for transport to connect, aborting`, void 0, {
296
282
  F: __dxlog_file,
297
- L: 195,
283
+ L: 194,
298
284
  S: this,
299
285
  C: (f, a) => f(...a)
300
286
  });
@@ -302,7 +288,7 @@ var Connection = class {
302
288
  }, TRANSPORT_CONNECTION_TIMEOUT);
303
289
  (0, import_invariant.invariant)(!this._transport, void 0, {
304
290
  F: __dxlog_file,
305
- L: 203,
291
+ L: 202,
306
292
  S: this,
307
293
  A: [
308
294
  "!this._transport",
@@ -310,12 +296,14 @@ var Connection = class {
310
296
  ]
311
297
  });
312
298
  this._transport = this._transportFactory.createTransport({
299
+ ownPeerKey: this.localInfo.peerKey,
300
+ remotePeerKey: this.remoteInfo.peerKey,
301
+ topic: this.topic.toHex(),
313
302
  initiator: this.initiator,
314
303
  stream: this._protocol.stream,
315
304
  sendSignal: async (signal) => this._sendSignal(signal),
316
305
  sessionId: this.sessionId
317
306
  });
318
- await this._transport.open();
319
307
  this._transport.connected.once(async () => {
320
308
  this._changeState("CONNECTED");
321
309
  await this.connectedTimeoutContext.dispose();
@@ -352,7 +340,7 @@ var Connection = class {
352
340
  S: this,
353
341
  C: (f, a) => f(...a)
354
342
  });
355
- this.abort().catch((err2) => this.errors.raise(err2));
343
+ this.abort(err).catch((err2) => this.errors.raise(err2));
356
344
  } else if (err instanceof import_protocols.ConnectivityError) {
357
345
  import_log.log.info("aborting due to transport ConnectivityError", void 0, {
358
346
  F: __dxlog_file,
@@ -360,22 +348,14 @@ var Connection = class {
360
348
  S: this,
361
349
  C: (f, a) => f(...a)
362
350
  });
363
- this.abort().catch((err2) => this.errors.raise(err2));
364
- } else if (err instanceof import_protocols.UnknownProtocolError) {
365
- import_log.log.warn("unsure what to do with UnknownProtocolError, will keep on truckin", {
366
- err
367
- }, {
368
- F: __dxlog_file,
369
- L: 242,
370
- S: this,
371
- C: (f, a) => f(...a)
372
- });
351
+ this.abort(err).catch((err2) => this.errors.raise(err2));
373
352
  }
374
353
  if (this._state !== "CLOSED" && this._state !== "CLOSING") {
375
354
  await this.connectedTimeoutContext.dispose();
376
355
  this.errors.raise(err);
377
356
  }
378
357
  });
358
+ await this._transport.open();
379
359
  for (const signal of this._incomingSignalBuffer) {
380
360
  void this._transport.onSignal(signal);
381
361
  }
@@ -737,15 +717,20 @@ var createIceProvider = (iceProviders) => {
737
717
  }
738
718
  cachedIceServers = (await Promise.all(iceProviders.map(({ urls }) => (0, import_async2.asyncTimeout)(fetch(urls, {
739
719
  method: "GET"
740
- }), 1e4).then((response) => response.json()).catch((err) => import_log2.log.error("Failed to fetch ICE servers from provider", {
741
- urls,
742
- err
743
- }, {
744
- F: __dxlog_file2,
745
- L: 27,
746
- S: void 0,
747
- C: (f, a) => f(...a)
748
- }))))).filter(import_util.isNotNullOrUndefined).map(({ iceServers }) => iceServers).flat();
720
+ }), 1e4).then((response) => response.json()).catch((err) => {
721
+ const isDev = typeof window !== "undefined" && window.location.href.includes("localhost");
722
+ if (!isDev) {
723
+ import_log2.log.error("Failed to fetch ICE servers from provider", {
724
+ urls,
725
+ err
726
+ }, {
727
+ F: __dxlog_file2,
728
+ L: 30,
729
+ S: void 0,
730
+ C: (f, a) => f(...a)
731
+ });
732
+ }
733
+ })))).filter(import_util.isNotNullOrUndefined).map(({ iceServers }) => iceServers).flat();
749
734
  return cachedIceServers;
750
735
  }
751
736
  };
@@ -1308,21 +1293,22 @@ var Peer = class {
1308
1293
  });
1309
1294
  },
1310
1295
  onClosed: (err) => {
1311
- (0, import_log5.log)("connection closed", {
1296
+ const logMeta = {
1312
1297
  topic: this.topic,
1313
1298
  peerId: this.localInfo,
1314
1299
  remoteId: this.remoteInfo,
1315
1300
  initiator
1316
- }, {
1301
+ };
1302
+ (0, import_log5.log)("connection closed", logMeta, {
1317
1303
  F: __dxlog_file4,
1318
- L: 288,
1304
+ L: 289,
1319
1305
  S: this,
1320
1306
  C: (f, a) => f(...a)
1321
1307
  });
1322
1308
  this._connectionLimiter.doneConnecting(sessionId);
1323
1309
  (0, import_invariant4.invariant)(this.connection === connection, "Connection mismatch (race condition).", {
1324
1310
  F: __dxlog_file4,
1325
- L: 293,
1311
+ L: 294,
1326
1312
  S: this,
1327
1313
  A: [
1328
1314
  "this.connection === connection",
@@ -1337,7 +1323,7 @@ var Peer = class {
1337
1323
  initiator
1338
1324
  }, {
1339
1325
  F: __dxlog_file4,
1340
- L: 295,
1326
+ L: 296,
1341
1327
  S: this,
1342
1328
  C: (f, a) => f(...a)
1343
1329
  });
@@ -1352,6 +1338,12 @@ var Peer = class {
1352
1338
  }
1353
1339
  this._callbacks.onDisconnected();
1354
1340
  (0, import_async4.scheduleTask)(this._connectionCtx, () => {
1341
+ (0, import_log5.log)("peer became available", logMeta, {
1342
+ F: __dxlog_file4,
1343
+ L: 320,
1344
+ S: this,
1345
+ C: (f, a) => f(...a)
1346
+ });
1355
1347
  this.availableToConnect = true;
1356
1348
  this._callbacks.onPeerAvailable();
1357
1349
  }, this._availableAfter);
@@ -1372,7 +1364,7 @@ var Peer = class {
1372
1364
  err
1373
1365
  }, {
1374
1366
  F: __dxlog_file4,
1375
- L: 335,
1367
+ L: 338,
1376
1368
  S: this,
1377
1369
  C: (f, a) => f(...a)
1378
1370
  });
@@ -1385,7 +1377,7 @@ var Peer = class {
1385
1377
  err
1386
1378
  }, {
1387
1379
  F: __dxlog_file4,
1388
- L: 342,
1380
+ L: 345,
1389
1381
  S: this,
1390
1382
  C: (f, a) => f(...a)
1391
1383
  });
@@ -1404,7 +1396,7 @@ var Peer = class {
1404
1396
  sessionId: connection.sessionId
1405
1397
  }, {
1406
1398
  F: __dxlog_file4,
1407
- L: 367,
1399
+ L: 370,
1408
1400
  S: this,
1409
1401
  C: (f, a) => f(...a)
1410
1402
  });
@@ -1414,7 +1406,7 @@ var Peer = class {
1414
1406
  sessionId: connection.sessionId
1415
1407
  }, {
1416
1408
  F: __dxlog_file4,
1417
- L: 373,
1409
+ L: 376,
1418
1410
  S: this,
1419
1411
  C: (f, a) => f(...a)
1420
1412
  });
@@ -1425,7 +1417,7 @@ var Peer = class {
1425
1417
  message
1426
1418
  }, {
1427
1419
  F: __dxlog_file4,
1428
- L: 378,
1420
+ L: 381,
1429
1421
  S: this,
1430
1422
  C: (f, a) => f(...a)
1431
1423
  });
@@ -1440,7 +1432,7 @@ var Peer = class {
1440
1432
  topic: this.topic
1441
1433
  }, {
1442
1434
  F: __dxlog_file4,
1443
- L: 388,
1435
+ L: 391,
1444
1436
  S: this,
1445
1437
  C: (f, a) => f(...a)
1446
1438
  });
@@ -1656,10 +1648,16 @@ var Swarm = class {
1656
1648
  const peer = this._peers.get(swarmEvent.peerLeft.peer);
1657
1649
  if (peer) {
1658
1650
  peer.advertizing = false;
1659
- if (peer.connection?.state !== ConnectionState.CONNECTED) {
1651
+ if (this._isConnectionEstablishmentInProgress(peer)) {
1652
+ (0, import_log4.log)(`destroying peer, state: ${peer.connection?.state}`, void 0, {
1653
+ F: __dxlog_file5,
1654
+ L: 195,
1655
+ S: this,
1656
+ C: (f, a) => f(...a)
1657
+ });
1660
1658
  void this._destroyPeer(swarmEvent.peerLeft.peer, "peer left").catch((err) => import_log4.log.catch(err, void 0, {
1661
1659
  F: __dxlog_file5,
1662
- L: 194,
1660
+ L: 196,
1663
1661
  S: this,
1664
1662
  C: (f, a) => f(...a)
1665
1663
  }));
@@ -1669,7 +1667,7 @@ var Swarm = class {
1669
1667
  peer: swarmEvent.peerLeft.peer.peerKey
1670
1668
  }, {
1671
1669
  F: __dxlog_file5,
1672
- L: 197,
1670
+ L: 199,
1673
1671
  S: this,
1674
1672
  C: (f, a) => f(...a)
1675
1673
  });
@@ -1682,14 +1680,14 @@ var Swarm = class {
1682
1680
  message
1683
1681
  }, {
1684
1682
  F: __dxlog_file5,
1685
- L: 206,
1683
+ L: 208,
1686
1684
  S: this,
1687
1685
  C: (f, a) => f(...a)
1688
1686
  });
1689
1687
  if (this._ctx.disposed) {
1690
1688
  (0, import_log4.log)("ignored for disposed swarm", void 0, {
1691
1689
  F: __dxlog_file5,
1692
- L: 208,
1690
+ L: 210,
1693
1691
  S: this,
1694
1692
  C: (f, a) => f(...a)
1695
1693
  });
@@ -1699,7 +1697,7 @@ var Swarm = class {
1699
1697
  }
1700
1698
  (0, import_invariant3.invariant)(message.author, void 0, {
1701
1699
  F: __dxlog_file5,
1702
- L: 213,
1700
+ L: 215,
1703
1701
  S: this,
1704
1702
  A: [
1705
1703
  "message.author",
@@ -1711,7 +1709,7 @@ var Swarm = class {
1711
1709
  message
1712
1710
  }, {
1713
1711
  F: __dxlog_file5,
1714
- L: 215,
1712
+ L: 217,
1715
1713
  S: this,
1716
1714
  C: (f, a) => f(...a)
1717
1715
  });
@@ -1724,7 +1722,7 @@ var Swarm = class {
1724
1722
  message
1725
1723
  }, {
1726
1724
  F: __dxlog_file5,
1727
- L: 219,
1725
+ L: 221,
1728
1726
  S: this,
1729
1727
  C: (f, a) => f(...a)
1730
1728
  });
@@ -1742,14 +1740,14 @@ var Swarm = class {
1742
1740
  message
1743
1741
  }, {
1744
1742
  F: __dxlog_file5,
1745
- L: 230,
1743
+ L: 232,
1746
1744
  S: this,
1747
1745
  C: (f, a) => f(...a)
1748
1746
  });
1749
1747
  if (this._ctx.disposed) {
1750
1748
  import_log4.log.info("ignored for offline swarm", void 0, {
1751
1749
  F: __dxlog_file5,
1752
- L: 232,
1750
+ L: 234,
1753
1751
  S: this,
1754
1752
  C: (f, a) => f(...a)
1755
1753
  });
@@ -1757,7 +1755,7 @@ var Swarm = class {
1757
1755
  }
1758
1756
  (0, import_invariant3.invariant)(message.recipient.peerKey === this._ownPeer.peerKey, `Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`, {
1759
1757
  F: __dxlog_file5,
1760
- L: 235,
1758
+ L: 237,
1761
1759
  S: this,
1762
1760
  A: [
1763
1761
  "message.recipient.peerKey === this._ownPeer.peerKey",
@@ -1766,7 +1764,7 @@ var Swarm = class {
1766
1764
  });
1767
1765
  (0, import_invariant3.invariant)(message.topic?.equals(this._topic), void 0, {
1768
1766
  F: __dxlog_file5,
1769
- L: 239,
1767
+ L: 241,
1770
1768
  S: this,
1771
1769
  A: [
1772
1770
  "message.topic?.equals(this._topic)",
@@ -1775,7 +1773,7 @@ var Swarm = class {
1775
1773
  });
1776
1774
  (0, import_invariant3.invariant)(message.author, void 0, {
1777
1775
  F: __dxlog_file5,
1778
- L: 240,
1776
+ L: 242,
1779
1777
  S: this,
1780
1778
  A: [
1781
1779
  "message.author",
@@ -1796,13 +1794,13 @@ var Swarm = class {
1796
1794
  async goOnline() {
1797
1795
  this._ctx = new import_context3.Context(void 0, {
1798
1796
  F: __dxlog_file5,
1799
- L: 256
1797
+ L: 258
1800
1798
  });
1801
1799
  }
1802
1800
  _getOrCreatePeer(peerInfo) {
1803
1801
  (0, import_invariant3.invariant)(peerInfo.peerKey, "PeerInfo.peerKey is required", {
1804
1802
  F: __dxlog_file5,
1805
- L: 260,
1803
+ L: 262,
1806
1804
  S: this,
1807
1805
  A: [
1808
1806
  "peerInfo.peerKey",
@@ -1820,6 +1818,12 @@ var Swarm = class {
1820
1818
  },
1821
1819
  onDisconnected: async () => {
1822
1820
  if (this._isUnregistered(peer)) {
1821
+ import_log4.log.verbose("ignored onDisconnected for unregistered peer", void 0, {
1822
+ F: __dxlog_file5,
1823
+ L: 282,
1824
+ S: this,
1825
+ C: (f, a) => f(...a)
1826
+ });
1823
1827
  return;
1824
1828
  }
1825
1829
  if (!peer.advertizing) {
@@ -1834,7 +1838,7 @@ var Swarm = class {
1834
1838
  peerInfo
1835
1839
  }, {
1836
1840
  F: __dxlog_file5,
1837
- L: 293,
1841
+ L: 296,
1838
1842
  S: this,
1839
1843
  C: (f, a) => f(...a)
1840
1844
  });
@@ -1856,10 +1860,19 @@ var Swarm = class {
1856
1860
  return peer;
1857
1861
  }
1858
1862
  async _destroyPeer(peerInfo, reason) {
1863
+ (0, import_log4.log)("destroy peer", {
1864
+ peerKey: peerInfo.peerKey,
1865
+ reason
1866
+ }, {
1867
+ F: __dxlog_file5,
1868
+ L: 318,
1869
+ S: this,
1870
+ C: (f, a) => f(...a)
1871
+ });
1859
1872
  const peer = this._peers.get(peerInfo);
1860
1873
  (0, import_invariant3.invariant)(peer, void 0, {
1861
1874
  F: __dxlog_file5,
1862
- L: 316,
1875
+ L: 320,
1863
1876
  S: this,
1864
1877
  A: [
1865
1878
  "peer",
@@ -1889,7 +1902,7 @@ var Swarm = class {
1889
1902
  } catch (err) {
1890
1903
  (0, import_log4.log)("initiation error", err, {
1891
1904
  F: __dxlog_file5,
1892
- L: 343,
1905
+ L: 347,
1893
1906
  S: this,
1894
1907
  C: (f, a) => f(...a)
1895
1908
  });
@@ -1920,7 +1933,7 @@ var Swarm = class {
1920
1933
  remotePeer
1921
1934
  }, {
1922
1935
  F: __dxlog_file5,
1923
- L: 371,
1936
+ L: 375,
1924
1937
  S: this,
1925
1938
  C: (f, a) => f(...a)
1926
1939
  });
@@ -1939,7 +1952,7 @@ var Swarm = class {
1939
1952
  remotePeer
1940
1953
  }, {
1941
1954
  F: __dxlog_file5,
1942
- L: 387,
1955
+ L: 391,
1943
1956
  S: this,
1944
1957
  C: (f, a) => f(...a)
1945
1958
  });
@@ -1949,7 +1962,7 @@ var Swarm = class {
1949
1962
  remotePeer
1950
1963
  }, {
1951
1964
  F: __dxlog_file5,
1952
- L: 390,
1965
+ L: 394,
1953
1966
  S: this,
1954
1967
  C: (f, a) => f(...a)
1955
1968
  });
@@ -1961,6 +1974,16 @@ var Swarm = class {
1961
1974
  }
1962
1975
  await peer.closeConnection();
1963
1976
  }
1977
+ _isConnectionEstablishmentInProgress(peer) {
1978
+ if (!peer.connection) {
1979
+ return true;
1980
+ }
1981
+ return [
1982
+ ConnectionState.INITIAL,
1983
+ ConnectionState.CREATED,
1984
+ ConnectionState.CONNECTING
1985
+ ].includes(peer.connection.state);
1986
+ }
1964
1987
  _isUnregistered(peer) {
1965
1988
  return !peer || this._peers.get(peer.remoteInfo) !== peer;
1966
1989
  }
@@ -2294,52 +2317,37 @@ var SwarmNetworkManager = class {
2294
2317
  /**
2295
2318
  * Join the swarm.
2296
2319
  */
2297
- async joinSwarm({ topic, peerInfo, topology, protocolProvider: protocol, label }) {
2320
+ async joinSwarm({ topic, topology, protocolProvider: protocol, label }) {
2298
2321
  (0, import_invariant6.invariant)(import_keys8.PublicKey.isPublicKey(topic), void 0, {
2299
2322
  F: __dxlog_file8,
2300
- L: 161,
2323
+ L: 160,
2301
2324
  S: this,
2302
2325
  A: [
2303
2326
  "PublicKey.isPublicKey(topic)",
2304
2327
  ""
2305
2328
  ]
2306
2329
  });
2307
- if (!peerInfo) {
2308
- peerInfo = {
2309
- peerKey: this._peerInfo?.peerKey ?? import_keys8.PublicKey.random().toHex(),
2310
- identityKey: this._peerInfo?.identityKey ?? import_keys8.PublicKey.random().toHex()
2311
- };
2312
- }
2313
- (0, import_invariant6.invariant)(import_keys8.PublicKey.from(peerInfo.peerKey), void 0, {
2314
- F: __dxlog_file8,
2315
- L: 168,
2316
- S: this,
2317
- A: [
2318
- "PublicKey.from(peerInfo.peerKey)",
2319
- ""
2320
- ]
2321
- });
2322
- (0, import_invariant6.invariant)(import_keys8.PublicKey.from(peerInfo.identityKey), void 0, {
2330
+ (0, import_invariant6.invariant)(topology, void 0, {
2323
2331
  F: __dxlog_file8,
2324
- L: 169,
2332
+ L: 161,
2325
2333
  S: this,
2326
2334
  A: [
2327
- "PublicKey.from(peerInfo.identityKey!)",
2335
+ "topology",
2328
2336
  ""
2329
2337
  ]
2330
2338
  });
2331
- (0, import_invariant6.invariant)(topology, void 0, {
2339
+ (0, import_invariant6.invariant)(this._peerInfo, void 0, {
2332
2340
  F: __dxlog_file8,
2333
- L: 170,
2341
+ L: 162,
2334
2342
  S: this,
2335
2343
  A: [
2336
- "topology",
2344
+ "this._peerInfo",
2337
2345
  ""
2338
2346
  ]
2339
2347
  });
2340
2348
  (0, import_invariant6.invariant)(typeof protocol === "function", void 0, {
2341
2349
  F: __dxlog_file8,
2342
- L: 171,
2350
+ L: 163,
2343
2351
  S: this,
2344
2352
  A: [
2345
2353
  "typeof protocol === 'function'",
@@ -2351,21 +2359,21 @@ var SwarmNetworkManager = class {
2351
2359
  }
2352
2360
  (0, import_log8.log)("joining", {
2353
2361
  topic: import_keys8.PublicKey.from(topic),
2354
- peerInfo,
2362
+ peerInfo: this._peerInfo,
2355
2363
  topology: topology.toString()
2356
2364
  }, {
2357
2365
  F: __dxlog_file8,
2358
- L: 176,
2366
+ L: 168,
2359
2367
  S: this,
2360
2368
  C: (f, a) => f(...a)
2361
2369
  });
2362
- const swarm = new Swarm(topic, peerInfo, topology, protocol, this._messenger, this._transportFactory, label, this._connectionLimiter);
2370
+ const swarm = new Swarm(topic, this._peerInfo, topology, protocol, this._messenger, this._transportFactory, label, this._connectionLimiter);
2363
2371
  swarm.errors.handle((error) => {
2364
2372
  (0, import_log8.log)("swarm error", {
2365
2373
  error
2366
2374
  }, {
2367
2375
  F: __dxlog_file8,
2368
- L: 189,
2376
+ L: 181,
2369
2377
  S: this,
2370
2378
  C: (f, a) => f(...a)
2371
2379
  });
@@ -2375,10 +2383,10 @@ var SwarmNetworkManager = class {
2375
2383
  await swarm.open();
2376
2384
  this._signalConnection.join({
2377
2385
  topic,
2378
- peer: peerInfo
2386
+ peer: this._peerInfo
2379
2387
  }).catch((error) => import_log8.log.catch(error, void 0, {
2380
2388
  F: __dxlog_file8,
2381
- L: 198,
2389
+ L: 190,
2382
2390
  S: this,
2383
2391
  C: (f, a) => f(...a)
2384
2392
  }));
@@ -2389,7 +2397,7 @@ var SwarmNetworkManager = class {
2389
2397
  count: this._swarms.size
2390
2398
  }, {
2391
2399
  F: __dxlog_file8,
2392
- L: 202,
2400
+ L: 194,
2393
2401
  S: this,
2394
2402
  C: (f, a) => f(...a)
2395
2403
  });
@@ -2408,7 +2416,7 @@ var SwarmNetworkManager = class {
2408
2416
  topic: import_keys8.PublicKey.from(topic)
2409
2417
  }, {
2410
2418
  F: __dxlog_file8,
2411
- L: 219,
2419
+ L: 211,
2412
2420
  S: this,
2413
2421
  C: (f, a) => f(...a)
2414
2422
  });
@@ -2429,7 +2437,7 @@ var SwarmNetworkManager = class {
2429
2437
  count: this._swarms.size
2430
2438
  }, {
2431
2439
  F: __dxlog_file8,
2432
- L: 233,
2440
+ L: 225,
2433
2441
  S: this,
2434
2442
  C: (f, a) => f(...a)
2435
2443
  });
@@ -2912,11 +2920,12 @@ var MemoryTransport = class _MemoryTransport {
2912
2920
  this.errors.raise(err);
2913
2921
  });
2914
2922
  }
2923
+ return this;
2915
2924
  }
2916
2925
  async close() {
2917
2926
  (0, import_log11.log)("closing...", void 0, {
2918
2927
  F: __dxlog_file12,
2919
- L: 129,
2928
+ L: 130,
2920
2929
  S: this,
2921
2930
  C: (f, a) => f(...a)
2922
2931
  });
@@ -2937,17 +2946,18 @@ var MemoryTransport = class _MemoryTransport {
2937
2946
  this.closed.emit();
2938
2947
  (0, import_log11.log)("closed", void 0, {
2939
2948
  F: __dxlog_file12,
2940
- L: 157,
2949
+ L: 158,
2941
2950
  S: this,
2942
2951
  C: (f, a) => f(...a)
2943
2952
  });
2953
+ return this;
2944
2954
  }
2945
2955
  async onSignal({ payload }) {
2946
2956
  (0, import_log11.log)("received signal", {
2947
2957
  payload
2948
2958
  }, {
2949
2959
  F: __dxlog_file12,
2950
- L: 161,
2960
+ L: 163,
2951
2961
  S: this,
2952
2962
  C: (f, a) => f(...a)
2953
2963
  });
@@ -2981,1278 +2991,1370 @@ _ts_decorate5([
2981
2991
  var toError = (err) => err instanceof Error ? err : new Error(String(err));
2982
2992
  var TransportKind;
2983
2993
  (function(TransportKind2) {
2984
- TransportKind2["SIMPLE_PEER"] = "SIMPLE_PEER";
2985
- TransportKind2["SIMPLE_PEER_PROXY"] = "SIMPLE_PEER_PROXY";
2986
- TransportKind2["LIBDATACHANNEL"] = "LIBDATACHANNEL";
2994
+ TransportKind2["WEB_RTC"] = "WEB-RTC";
2995
+ TransportKind2["WEB_RTC_PROXY"] = "WEB-RTC_PROXY";
2987
2996
  TransportKind2["MEMORY"] = "MEMORY";
2988
2997
  TransportKind2["TCP"] = "TCP";
2989
2998
  })(TransportKind || (TransportKind = {}));
2990
- var wrtc = null;
2991
- try {
2992
- wrtc = __require("@koush/wrtc");
2993
- } catch {
2994
- }
2995
- function _ts_decorate6(decorators, target, key, desc) {
2996
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2997
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2998
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2999
- return c > 3 && r && Object.defineProperty(target, key, r), r;
3000
- }
3001
- var __dxlog_file13 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/simplepeer-transport.ts";
3002
- var createSimplePeerTransportFactory = (webrtcConfig, iceProvider) => ({
3003
- createTransport: (options) => new SimplePeerTransport({
3004
- ...options,
3005
- webrtcConfig,
3006
- iceProvider
3007
- })
3008
- });
3009
- var SimplePeerTransport = class {
3010
- get isOpen() {
3011
- return this._piped && !this._closed;
2999
+ var BrowserRtcConnectionFactory = class {
3000
+ async initialize() {
3012
3001
  }
3013
- /**
3014
- * @params opts.config formatted as per https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/RTCPeerConnection
3015
- */
3016
- constructor(_params) {
3017
- this._params = _params;
3018
- this._peer = void 0;
3019
- this._closed = false;
3020
- this._piped = false;
3021
- this.closed = new import_async10.Event();
3022
- this.connected = new import_async10.Event();
3023
- this.errors = new import_debug5.ErrorStream();
3024
- this._instanceId = import_keys10.PublicKey.random().toHex();
3002
+ async onConnectionDestroyed() {
3025
3003
  }
3026
- async getStats() {
3027
- const stats = await this._getStats();
3028
- if (!stats) {
3029
- return {
3030
- bytesSent: 0,
3031
- bytesReceived: 0,
3032
- packetsSent: 0,
3033
- packetsReceived: 0,
3034
- rawStats: {}
3035
- };
3036
- }
3037
- return {
3038
- bytesSent: stats.transport.bytesSent,
3039
- bytesReceived: stats.transport.bytesReceived,
3040
- packetsSent: stats.transport.packetsSent,
3041
- packetsReceived: stats.transport.packetsReceived,
3042
- rawStats: stats.raw
3043
- };
3004
+ async createConnection(config) {
3005
+ return new RTCPeerConnection(config);
3044
3006
  }
3045
- async _getStats() {
3046
- if (typeof this._peer?._pc?.getStats !== "function") {
3047
- return null;
3048
- }
3049
- return await this._peer._pc.getStats().then((stats) => {
3050
- const statsEntries = Array.from(stats.entries());
3051
- const transport = statsEntries.filter((s) => s[1].type === "transport")[0][1];
3052
- const candidatePair = statsEntries.filter((s) => s[0] === transport.selectedCandidatePairId);
3053
- let selectedCandidatePair;
3054
- let remoteCandidate;
3055
- if (candidatePair.length > 0) {
3056
- selectedCandidatePair = candidatePair[0][1];
3057
- remoteCandidate = statsEntries.filter((s) => s[0] === selectedCandidatePair.remoteCandidateId)[0][1];
3007
+ async initConnection(connection, info) {
3008
+ }
3009
+ };
3010
+ var NodeRtcConnectionFactory = class _NodeRtcConnectionFactory {
3011
+ static {
3012
+ this._createdConnections = 0;
3013
+ }
3014
+ static {
3015
+ this._cleanupMutex = new import_async10.Mutex();
3016
+ }
3017
+ // This should be inside the function to avoid triggering `eval` in the global scope.
3018
+ // eslint-disable-next-line no-new-func
3019
+ // TODO(burdon): Do imports here?
3020
+ async initialize() {
3021
+ }
3022
+ async onConnectionDestroyed() {
3023
+ return _NodeRtcConnectionFactory._cleanupMutex.executeSynchronized(async () => {
3024
+ if (--_NodeRtcConnectionFactory._createdConnections === 0) {
3025
+ (await import("#node-datachannel")).cleanup();
3058
3026
  }
3059
- return {
3060
- datachannel: statsEntries.filter((s) => s[1].type === "data-channel")[0][1],
3061
- transport,
3062
- selectedCandidatePair,
3063
- remoteCandidate,
3064
- raw: Object.fromEntries(stats.entries())
3065
- };
3066
3027
  });
3067
3028
  }
3068
- async getDetails() {
3069
- const stats = await this._getStats();
3070
- const rc = stats?.remoteCandidate;
3071
- if (!rc) {
3072
- return "unavailable";
3029
+ async createConnection(config) {
3030
+ return _NodeRtcConnectionFactory._cleanupMutex.executeSynchronized(async () => {
3031
+ const { RTCPeerConnection: RTCPeerConnection1 } = await import("#node-datachannel/polyfill");
3032
+ _NodeRtcConnectionFactory._createdConnections++;
3033
+ return new RTCPeerConnection1(config);
3034
+ });
3035
+ }
3036
+ async initConnection(connection, info) {
3037
+ if (info.initiator) {
3038
+ connection.onnegotiationneeded?.(null);
3073
3039
  }
3074
- if (rc.candidateType === "relay") {
3075
- return `${rc.ip}:${rc.port}/${rc.protocol} relay for ${rc.relatedAddress}:${rc.relatedPort}`;
3040
+ }
3041
+ };
3042
+ var getRtcConnectionFactory = () => {
3043
+ return typeof globalThis.RTCPeerConnection === "undefined" ? new NodeRtcConnectionFactory() : new BrowserRtcConnectionFactory();
3044
+ };
3045
+ var describeSelectedRemoteCandidate = async (connection) => {
3046
+ const stats = connection && await getRtcConnectionStats(connection);
3047
+ const rc = stats?.remoteCandidate;
3048
+ if (!rc) {
3049
+ return "unavailable";
3050
+ }
3051
+ if (rc.candidateType === "relay") {
3052
+ return `${rc.ip}:${rc.port} relay for ${rc.relatedAddress}:${rc.relatedPort}`;
3053
+ }
3054
+ return `${rc.ip}:${rc.port} ${rc.candidateType}`;
3055
+ };
3056
+ var createRtcTransportStats = async (connection, topic) => {
3057
+ const stats = connection && await getRtcConnectionStats(connection, topic);
3058
+ if (!stats) {
3059
+ return {
3060
+ bytesSent: 0,
3061
+ bytesReceived: 0,
3062
+ packetsSent: 0,
3063
+ packetsReceived: 0,
3064
+ rawStats: {}
3065
+ };
3066
+ }
3067
+ return {
3068
+ bytesSent: stats.dataChannel?.bytesSent,
3069
+ bytesReceived: stats.dataChannel?.bytesReceived,
3070
+ packetsSent: 0,
3071
+ packetsReceived: 0,
3072
+ rawStats: stats.raw
3073
+ };
3074
+ };
3075
+ var getRtcConnectionStats = async (connection, channelTopic) => {
3076
+ const stats = await connection.getStats();
3077
+ const statsEntries = Array.from(stats.entries());
3078
+ const transport = statsEntries.find(([_, entry]) => entry.type === "transport")?.[1];
3079
+ const selectedCandidatePair = transport && statsEntries.find(([entryId]) => entryId === transport.selectedCandidatePairId)?.[1];
3080
+ const remoteCandidate = selectedCandidatePair && statsEntries.find(([entryId]) => entryId === selectedCandidatePair.remoteCandidateId)?.[1];
3081
+ const dataChannel = channelTopic && statsEntries.find(([_, entry]) => entry.type === "data-channel" && entry.label === channelTopic)?.[1];
3082
+ return {
3083
+ transport,
3084
+ selectedCandidatePair,
3085
+ dataChannel,
3086
+ remoteCandidate,
3087
+ raw: Object.fromEntries(stats)
3088
+ };
3089
+ };
3090
+ var __dxlog_file13 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc/rtc-transport-channel.ts";
3091
+ var MAX_MESSAGE_SIZE = 64 * 1024;
3092
+ var MAX_BUFFERED_AMOUNT = 64 * 1024;
3093
+ var RtcTransportChannel = class extends import_context6.Resource {
3094
+ constructor(_connection, _options) {
3095
+ super();
3096
+ this._connection = _connection;
3097
+ this._options = _options;
3098
+ this.closed = new import_async12.Event();
3099
+ this.connected = new import_async12.Event();
3100
+ this.errors = new import_debug5.ErrorStream();
3101
+ this._streamDataFlushedCallback = null;
3102
+ this._isChannelCreationInProgress = false;
3103
+ }
3104
+ get isRtcChannelCreationInProgress() {
3105
+ return this._isChannelCreationInProgress;
3106
+ }
3107
+ onConnectionError(error) {
3108
+ if (this.isOpen) {
3109
+ this.errors.raise(error);
3076
3110
  }
3077
- return `${rc.ip}:${rc.port}/${rc.protocol} ${rc.candidateType}`;
3078
3111
  }
3079
- async open() {
3080
- import_log12.log.trace("dxos.mesh.webrtc-transport.open", import_protocols7.trace.begin({
3081
- id: this._instanceId
3082
- }), {
3112
+ async _open() {
3113
+ (0, import_invariant12.invariant)(!this._isChannelCreationInProgress, void 0, {
3083
3114
  F: __dxlog_file13,
3084
- L: 122,
3115
+ L: 56,
3085
3116
  S: this,
3086
- C: (f, a) => f(...a)
3117
+ A: [
3118
+ "!this._isChannelCreationInProgress",
3119
+ ""
3120
+ ]
3087
3121
  });
3088
- (0, import_log12.log)("created connection", {
3089
- params: this._params
3090
- }, {
3122
+ this._isChannelCreationInProgress = true;
3123
+ this._connection.createDataChannel(this._options.topic).then((channel) => {
3124
+ if (this.isOpen) {
3125
+ this._channel = channel;
3126
+ this._initChannel(this._channel);
3127
+ } else {
3128
+ this._safeCloseChannel(channel);
3129
+ }
3130
+ }).catch((err) => {
3131
+ if (this.isOpen) {
3132
+ this.errors.raise(new import_protocols8.ConnectivityError(`Failed to create a channel: ${err?.message ?? "unknown reason."}`));
3133
+ }
3134
+ }).finally(() => {
3135
+ this._isChannelCreationInProgress = false;
3136
+ });
3137
+ }
3138
+ async _close() {
3139
+ if (this._channel) {
3140
+ this._safeCloseChannel(this._channel);
3141
+ this._channel = void 0;
3142
+ this._stream = void 0;
3143
+ }
3144
+ this.closed.emit();
3145
+ (0, import_log13.log)("closed", void 0, {
3091
3146
  F: __dxlog_file13,
3092
- L: 123,
3147
+ L: 86,
3093
3148
  S: this,
3094
3149
  C: (f, a) => f(...a)
3095
3150
  });
3096
- const providedIceServers = await this._params.iceProvider?.getIceServers();
3097
- if (!this._params.webrtcConfig) {
3098
- this._params.webrtcConfig = {};
3099
- }
3100
- this._params.webrtcConfig.iceServers = [
3101
- ...this._params.webrtcConfig.iceServers ?? [],
3102
- ...providedIceServers ?? []
3103
- ];
3104
- this._peer = new import_simple_peer.default({
3105
- channelName: "dxos.mesh.transport",
3106
- initiator: this._params.initiator,
3107
- wrtc: import_simple_peer.default.WEBRTC_SUPPORT ? void 0 : wrtc ?? (0, import_debug5.raise)(new Error("wrtc not available")),
3108
- config: this._params.webrtcConfig
3109
- });
3110
- this._peer.on("signal", async (data) => {
3111
- (0, import_log12.log)("signal", data, {
3112
- F: __dxlog_file13,
3113
- L: 142,
3114
- S: this,
3115
- C: (f, a) => f(...a)
3116
- });
3117
- await this._params.sendSignal({
3118
- payload: {
3119
- data
3120
- }
3121
- });
3122
- });
3123
- this._peer.on("connect", () => {
3124
- (0, import_log12.log)("connected", void 0, {
3125
- F: __dxlog_file13,
3126
- L: 147,
3127
- S: this,
3128
- C: (f, a) => f(...a)
3129
- });
3130
- this._params.stream.pipe(this._peer).pipe(this._params.stream);
3131
- this._piped = true;
3132
- this.connected.emit();
3133
- });
3134
- this._peer.on("close", async () => {
3135
- (0, import_log12.log)("closed", void 0, {
3136
- F: __dxlog_file13,
3137
- L: 154,
3138
- S: this,
3139
- C: (f, a) => f(...a)
3140
- });
3141
- await this.close();
3142
- });
3143
- this._peer.on("error", async (err) => {
3144
- if (typeof RTCError !== "undefined" && err instanceof RTCError) {
3145
- if (err.errorDetail === "sctp-failure") {
3146
- this.errors.raise(new import_protocols7.ConnectionResetError("sctp-failure from RTCError", err));
3147
- } else {
3148
- import_log12.log.info("unknown RTCError", {
3149
- err
3151
+ }
3152
+ _initChannel(channel) {
3153
+ Object.assign(channel, {
3154
+ onopen: () => {
3155
+ if (!this.isOpen) {
3156
+ import_log13.log.warn("channel opened in a closed transport", {
3157
+ topic: this._options.topic
3150
3158
  }, {
3151
3159
  F: __dxlog_file13,
3152
- L: 165,
3160
+ L: 93,
3153
3161
  S: this,
3154
3162
  C: (f, a) => f(...a)
3155
3163
  });
3156
- this.errors.raise(new import_protocols7.UnknownProtocolError("unknown RTCError", err));
3164
+ this._safeCloseChannel(channel);
3165
+ return;
3157
3166
  }
3158
- } else if ("code" in err) {
3159
- import_log12.log.info("simple-peer error", err, {
3167
+ (0, import_log13.log)("onopen", void 0, {
3160
3168
  F: __dxlog_file13,
3161
- L: 170,
3169
+ L: 98,
3162
3170
  S: this,
3163
3171
  C: (f, a) => f(...a)
3164
3172
  });
3165
- switch (err.code) {
3166
- case "ERR_WEBRTC_SUPPORT":
3167
- this.errors.raise(new import_protocols7.ProtocolError("WebRTC not supported", err));
3168
- break;
3169
- case "ERR_SIGNALING":
3170
- this.errors.raise(new import_protocols7.ConnectivityError("signaling failure", err));
3171
- break;
3172
- case "ERR_ICE_CONNECTION_FAILURE":
3173
- case "ERR_DATA_CHANNEL":
3174
- case "ERR_CONNECTION_FAILURE":
3175
- this.errors.raise(new import_protocols7.ConnectivityError("unknown communication failure", err));
3176
- break;
3177
- // errors due to library issues or improper API usage
3178
- case "ERR_CREATE_OFFER":
3179
- case "ERR_CREATE_ANSWER":
3180
- case "ERR_SET_LOCAL_DESCRIPTION":
3181
- case "ERR_SET_REMOTE_DESCRIPTION":
3182
- case "ERR_ADD_ICE_CANDIDATE":
3183
- this.errors.raise(new import_protocols7.UnknownProtocolError("unknown simple-peer library failure", err));
3184
- break;
3185
- default:
3186
- this.errors.raise(new Error("unknown simple-peer error"));
3187
- break;
3188
- }
3189
- } else {
3190
- import_log12.log.info("unknown peer connection error", err, {
3173
+ const duplex = new import_node_stream2.Duplex({
3174
+ read: () => {
3175
+ },
3176
+ write: (chunk, encoding, callback) => {
3177
+ return this._handleChannelWrite(chunk, callback);
3178
+ }
3179
+ });
3180
+ duplex.pipe(this._options.stream).pipe(duplex);
3181
+ this._stream = duplex;
3182
+ this.connected.emit();
3183
+ },
3184
+ onclose: async () => {
3185
+ (0, import_log13.log)("onclose", void 0, {
3191
3186
  F: __dxlog_file13,
3192
- L: 196,
3187
+ L: 111,
3193
3188
  S: this,
3194
3189
  C: (f, a) => f(...a)
3195
3190
  });
3196
- this.errors.raise(err);
3197
- }
3198
- try {
3199
- if (typeof this._peer?._pc?.getStats === "function") {
3200
- this._peer._pc.getStats().then((stats) => {
3201
- import_log12.log.info("report after webrtc error", {
3202
- config: this._params.webrtcConfig,
3203
- stats: Object.fromEntries(stats.entries())
3204
- }, {
3205
- F: __dxlog_file13,
3206
- L: 204,
3207
- S: this,
3208
- C: (f, a) => f(...a)
3209
- });
3191
+ await this.close();
3192
+ },
3193
+ onmessage: (event) => {
3194
+ if (!this._stream) {
3195
+ import_log13.log.warn("ignoring message on a closed channel", void 0, {
3196
+ F: __dxlog_file13,
3197
+ L: 117,
3198
+ S: this,
3199
+ C: (f, a) => f(...a)
3210
3200
  });
3201
+ return;
3211
3202
  }
3212
- } catch (err2) {
3213
- import_log12.log.catch(err2, void 0, {
3214
- F: __dxlog_file13,
3215
- L: 211,
3216
- S: this,
3217
- C: (f, a) => f(...a)
3218
- });
3203
+ let data = event.data;
3204
+ if (data instanceof ArrayBuffer) {
3205
+ data = Buffer.from(data);
3206
+ }
3207
+ this._stream.push(data);
3208
+ },
3209
+ onerror: (event) => {
3210
+ if (this.isOpen) {
3211
+ const err = event.error instanceof Error ? event.error : new Error(`Datachannel error: ${event.type}.`);
3212
+ this.errors.raise(err);
3213
+ }
3214
+ },
3215
+ onbufferedamountlow: () => {
3216
+ const cb = this._streamDataFlushedCallback;
3217
+ this._streamDataFlushedCallback = null;
3218
+ cb?.();
3219
3219
  }
3220
- await this.close();
3221
- });
3222
- import_log12.log.trace("dxos.mesh.webrtc-transport.open", import_protocols7.trace.end({
3223
- id: this._instanceId
3224
- }), {
3225
- F: __dxlog_file13,
3226
- L: 217,
3227
- S: this,
3228
- C: (f, a) => f(...a)
3229
3220
  });
3230
3221
  }
3231
- async close() {
3232
- (0, import_log12.log)("closing...", void 0, {
3233
- F: __dxlog_file13,
3234
- L: 222,
3235
- S: this,
3236
- C: (f, a) => f(...a)
3237
- });
3238
- if (this._closed) {
3222
+ async _handleChannelWrite(chunk, callback) {
3223
+ if (!this._channel) {
3224
+ import_log13.log.warn("writing to a channel after a connection was closed", void 0, {
3225
+ F: __dxlog_file13,
3226
+ L: 145,
3227
+ S: this,
3228
+ C: (f, a) => f(...a)
3229
+ });
3239
3230
  return;
3240
3231
  }
3241
- this._disconnectStreams();
3242
- this._peer.destroy();
3243
- this._closed = true;
3244
- this.closed.emit();
3245
- (0, import_log12.log)("closed", void 0, {
3246
- F: __dxlog_file13,
3247
- L: 230,
3248
- S: this,
3249
- C: (f, a) => f(...a)
3250
- });
3251
- }
3252
- async onSignal(signal) {
3253
- if (this._closed) {
3232
+ if (chunk.length > MAX_MESSAGE_SIZE) {
3233
+ const error = new Error(`Message too large: ${chunk.length} > ${MAX_MESSAGE_SIZE}.`);
3234
+ this.errors.raise(error);
3235
+ callback();
3254
3236
  return;
3255
3237
  }
3256
- (0, import_tiny_invariant.default)(signal.payload.data, "Signal message must contain signal data.");
3257
- (0, import_tiny_invariant.default)(this._peer, "Peer must be initialized before receiving signals.");
3258
- this._peer.signal(signal.payload.data);
3259
- }
3260
- _disconnectStreams() {
3261
- if (this._piped) {
3262
- this._params.stream.unpipe?.(this._peer)?.unpipe?.(this._params.stream);
3238
+ try {
3239
+ this._channel.send(chunk);
3240
+ } catch (err) {
3241
+ this.errors.raise(err);
3242
+ callback();
3243
+ return;
3263
3244
  }
3264
- }
3265
- };
3266
- _ts_decorate6([
3267
- import_async10.synchronized
3268
- ], SimplePeerTransport.prototype, "open", null);
3269
- _ts_decorate6([
3270
- import_async10.synchronized
3271
- ], SimplePeerTransport.prototype, "close", null);
3272
- _ts_decorate6([
3273
- import_async10.synchronized
3274
- ], SimplePeerTransport.prototype, "onSignal", null);
3275
- var __dxlog_file14 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/simplepeer-transport-service.ts";
3276
- var SimplePeerTransportService = class {
3277
- constructor(_webrtcConfig, _iceProvider) {
3278
- this._webrtcConfig = _webrtcConfig;
3279
- this._iceProvider = _iceProvider;
3280
- this.transports = new import_util9.ComplexMap(import_keys11.PublicKey.hash);
3281
- }
3282
- open(request) {
3283
- const rpcStream = new import_codec_protobuf.Stream(({ ready, next, close }) => {
3284
- const duplex = new import_node_stream2.Duplex({
3285
- read: () => {
3286
- const callbacks = [
3287
- ...transportState.writeCallbacks
3288
- ];
3289
- transportState.writeCallbacks.length = 0;
3290
- for (const cb of callbacks) {
3291
- cb();
3292
- }
3293
- },
3294
- write: function(chunk, _, callback) {
3295
- next({
3296
- data: {
3297
- payload: chunk
3298
- }
3299
- });
3300
- callback();
3301
- }
3302
- });
3303
- const transport = new SimplePeerTransport({
3304
- initiator: request.initiator,
3305
- stream: duplex,
3306
- webrtcConfig: this._webrtcConfig,
3307
- sendSignal: async (signal) => {
3308
- next({
3309
- signal: {
3310
- payload: signal
3311
- }
3312
- });
3313
- },
3314
- iceProvider: this._iceProvider
3315
- });
3316
- void transport.open();
3317
- next({
3318
- connection: {
3319
- state: import_bridge.ConnectionState.CONNECTING
3320
- }
3321
- });
3322
- transport.connected.on(() => {
3323
- next({
3324
- connection: {
3325
- state: import_bridge.ConnectionState.CONNECTED
3326
- }
3327
- });
3328
- });
3329
- transport.errors.handle((err) => {
3330
- next({
3331
- connection: {
3332
- state: import_bridge.ConnectionState.CLOSED,
3333
- error: err.toString()
3334
- }
3335
- });
3336
- close(err);
3337
- });
3338
- transport.closed.on(() => {
3339
- next({
3340
- connection: {
3341
- state: import_bridge.ConnectionState.CLOSED
3342
- }
3245
+ if (this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {
3246
+ if (this._streamDataFlushedCallback !== null) {
3247
+ import_log13.log.error("consumer trying to write before we are ready for more data", void 0, {
3248
+ F: __dxlog_file13,
3249
+ L: 166,
3250
+ S: this,
3251
+ C: (f, a) => f(...a)
3343
3252
  });
3344
- close();
3253
+ }
3254
+ this._streamDataFlushedCallback = callback;
3255
+ } else {
3256
+ callback();
3257
+ }
3258
+ }
3259
+ _safeCloseChannel(channel) {
3260
+ try {
3261
+ channel.close();
3262
+ } catch (error) {
3263
+ import_log13.log.catch(error, void 0, {
3264
+ F: __dxlog_file13,
3265
+ L: 178,
3266
+ S: this,
3267
+ C: (f, a) => f(...a)
3345
3268
  });
3346
- const transportState = {
3347
- transport,
3348
- stream: duplex,
3349
- writeCallbacks: [],
3350
- state: "OPEN"
3351
- };
3352
- ready();
3353
- this.transports.set(request.proxyId, transportState);
3354
- });
3355
- return rpcStream;
3269
+ }
3356
3270
  }
3357
- async sendSignal({ proxyId, signal }) {
3358
- (0, import_invariant11.invariant)(this.transports.has(proxyId), void 0, {
3359
- F: __dxlog_file14,
3360
- L: 124,
3361
- S: this,
3362
- A: [
3363
- "this.transports.has(proxyId)",
3364
- ""
3365
- ]
3366
- });
3367
- await this.transports.get(proxyId).transport.onSignal(signal);
3271
+ onSignal(signal) {
3272
+ return this._connection.onSignal(signal);
3368
3273
  }
3369
- async getDetails({ proxyId }) {
3370
- (0, import_invariant11.invariant)(this.transports.has(proxyId), void 0, {
3371
- F: __dxlog_file14,
3372
- L: 129,
3373
- S: this,
3374
- A: [
3375
- "this.transports.has(proxyId)",
3376
- ""
3377
- ]
3378
- });
3379
- return {
3380
- details: await this.transports.get(proxyId).transport.getDetails()
3381
- };
3274
+ async getDetails() {
3275
+ return describeSelectedRemoteCandidate(this._connection.currentConnection);
3382
3276
  }
3383
- async getStats({ proxyId }) {
3384
- (0, import_invariant11.invariant)(this.transports.has(proxyId), void 0, {
3385
- F: __dxlog_file14,
3386
- L: 134,
3387
- S: this,
3388
- A: [
3389
- "this.transports.has(proxyId)",
3390
- ""
3391
- ]
3392
- });
3393
- return {
3394
- stats: await this.transports.get(proxyId).transport.getStats()
3395
- };
3277
+ async getStats() {
3278
+ return createRtcTransportStats(this._connection.currentConnection, this._options.topic);
3396
3279
  }
3397
- async sendData({ proxyId, payload }) {
3398
- if (this.transports.get(proxyId)?.state !== "OPEN") {
3399
- import_log13.log.debug("transport is closed", void 0, {
3280
+ };
3281
+ var chooseInitiatorPeer = (peer1Key, peer2Key) => peer1Key < peer2Key ? peer1Key : peer2Key;
3282
+ var areSdpEqual = (sdp1, sdp2) => {
3283
+ const sdp1Lines = deduplicatedSdpLines(sdp1);
3284
+ const sdp2Lines = deduplicatedSdpLines(sdp2);
3285
+ if (sdp1Lines.length !== sdp2Lines.length) {
3286
+ return false;
3287
+ }
3288
+ return sdp1Lines.every((line, idx) => line === sdp2Lines[idx]);
3289
+ };
3290
+ var deduplicatedSdpLines = (sdp) => {
3291
+ const deduplicatedLines = [];
3292
+ const seenLines = [];
3293
+ for (const line of sdp.split("\r\n")) {
3294
+ if (line.startsWith("m")) {
3295
+ seenLines.length = 0;
3296
+ }
3297
+ if (seenLines.includes(line)) {
3298
+ continue;
3299
+ }
3300
+ seenLines.push(line);
3301
+ deduplicatedLines.push(line);
3302
+ }
3303
+ return deduplicatedLines;
3304
+ };
3305
+ function _ts_decorate6(decorators, target, key, desc) {
3306
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3307
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
3308
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3309
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3310
+ }
3311
+ var __dxlog_file14 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc/rtc-peer-connection.ts";
3312
+ var RtcPeerConnection = class {
3313
+ constructor(_factory, _options) {
3314
+ this._factory = _factory;
3315
+ this._options = _options;
3316
+ this._channelCreatedCallbacks = /* @__PURE__ */ new Map();
3317
+ this._transportChannels = /* @__PURE__ */ new Map();
3318
+ this._dataChannels = /* @__PURE__ */ new Map();
3319
+ this._readyForCandidates = new import_async11.Trigger();
3320
+ this._offerProcessingMutex = new import_async11.Mutex();
3321
+ this._initiator = chooseInitiatorPeer(_options.ownPeerKey, _options.remotePeerKey) === _options.ownPeerKey;
3322
+ }
3323
+ get transportChannelCount() {
3324
+ return this._transportChannels.size;
3325
+ }
3326
+ get currentConnection() {
3327
+ return this._connection;
3328
+ }
3329
+ async createDataChannel(topic) {
3330
+ const connection = await this._openConnection();
3331
+ if (!this._transportChannels.has(topic)) {
3332
+ if (!this._transportChannels.size) {
3333
+ this._lockAndCloseConnection();
3334
+ }
3335
+ throw new Error("Transport closed while connection was being open");
3336
+ }
3337
+ if (this._initiator) {
3338
+ const channel = connection.createDataChannel(topic);
3339
+ this._dataChannels.set(topic, channel);
3340
+ return channel;
3341
+ } else {
3342
+ const existingChannel = this._dataChannels.get(topic);
3343
+ if (existingChannel) {
3344
+ return existingChannel;
3345
+ }
3346
+ (0, import_log12.log)("waiting for initiator-peer to open a data channel", void 0, {
3400
3347
  F: __dxlog_file14,
3401
- L: 140,
3348
+ L: 90,
3402
3349
  S: this,
3403
3350
  C: (f, a) => f(...a)
3404
3351
  });
3405
- }
3406
- (0, import_invariant11.invariant)(this.transports.has(proxyId), void 0, {
3407
- F: __dxlog_file14,
3408
- L: 142,
3409
- S: this,
3410
- A: [
3411
- "this.transports.has(proxyId)",
3412
- ""
3413
- ]
3414
- });
3415
- const state = this.transports.get(proxyId);
3416
- const bufferHasSpace = state.stream.push(payload);
3417
- if (!bufferHasSpace) {
3418
- await new Promise((resolve) => {
3419
- state.writeCallbacks.push(resolve);
3352
+ return new Promise((resolve, reject) => {
3353
+ this._channelCreatedCallbacks.set(topic, {
3354
+ resolve,
3355
+ reject
3356
+ });
3420
3357
  });
3421
3358
  }
3422
3359
  }
3423
- async close({ proxyId }) {
3424
- await this.transports.get(proxyId)?.transport.close();
3425
- await this.transports.get(proxyId)?.stream.end();
3426
- if (this.transports.get(proxyId)) {
3427
- this.transports.get(proxyId).state = "CLOSED";
3360
+ createTransportChannel(options) {
3361
+ const channel = new RtcTransportChannel(this, options);
3362
+ this._transportChannels.set(options.topic, channel);
3363
+ channel.closed.on(() => {
3364
+ this._transportChannels.delete(options.topic);
3365
+ if (this._transportChannels.size === 0) {
3366
+ this._lockAndCloseConnection();
3367
+ }
3368
+ });
3369
+ return channel;
3370
+ }
3371
+ async _openConnection() {
3372
+ if (this._connection) {
3373
+ return this._connection;
3428
3374
  }
3429
- (0, import_log13.log)("Closed.", void 0, {
3375
+ (0, import_log12.log)("initializing connection...", () => ({
3376
+ remotePeer: this._options.remotePeerKey
3377
+ }), {
3430
3378
  F: __dxlog_file14,
3431
- L: 158,
3379
+ L: 115,
3432
3380
  S: this,
3433
3381
  C: (f, a) => f(...a)
3434
3382
  });
3435
- }
3436
- };
3437
- var __dxlog_file15 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/simplepeer-transport-proxy.ts";
3438
- var RPC_TIMEOUT = 1e4;
3439
- var RESP_MIN_THRESHOLD = 500;
3440
- var TIMEOUT_THRESHOLD = 10;
3441
- var SimplePeerTransportProxy = class {
3442
- constructor(_options) {
3443
- this._options = _options;
3444
- this._proxyId = import_keys12.PublicKey.random();
3445
- this._ctx = new import_context6.Context(void 0, {
3446
- F: __dxlog_file15,
3447
- L: 37
3448
- });
3449
- this._timeoutCount = 0;
3450
- this.closed = new import_async11.Event();
3451
- this.connected = new import_async11.Event();
3452
- this.errors = new import_debug6.ErrorStream();
3453
- this._closed = false;
3454
- }
3455
- get isOpen() {
3456
- return !this._closed;
3457
- }
3458
- async open() {
3459
- this._serviceStream = this._options.bridgeService.open({
3460
- proxyId: this._proxyId,
3461
- initiator: this._options.initiator
3462
- }, {
3463
- timeout: RPC_TIMEOUT
3464
- });
3465
- this._serviceStream.waitUntilReady().then(() => {
3466
- this._serviceStream.subscribe(async (event) => {
3467
- (0, import_log14.log)("SimplePeerTransportProxy: event", event, {
3468
- F: __dxlog_file15,
3469
- L: 66,
3383
+ const config = await this._loadConnectionConfig();
3384
+ const connection = await this._factory.createConnection(config);
3385
+ const iceCandidateErrors = [];
3386
+ Object.assign(connection, {
3387
+ onnegotiationneeded: async () => {
3388
+ (0, import_invariant11.invariant)(this._initiator, void 0, {
3389
+ F: __dxlog_file14,
3390
+ L: 130,
3391
+ S: this,
3392
+ A: [
3393
+ "this._initiator",
3394
+ ""
3395
+ ]
3396
+ });
3397
+ if (connection !== this._connection) {
3398
+ this._onConnectionCallbackAfterClose("onnegotiationneeded", connection);
3399
+ return;
3400
+ }
3401
+ (0, import_log12.log)("onnegotiationneeded", void 0, {
3402
+ F: __dxlog_file14,
3403
+ L: 137,
3470
3404
  S: this,
3471
3405
  C: (f, a) => f(...a)
3472
3406
  });
3473
- if (event.connection) {
3474
- await this._handleConnection(event.connection);
3475
- } else if (event.data) {
3476
- this._handleData(event.data);
3477
- } else if (event.signal) {
3478
- await this._handleSignal(event.signal);
3407
+ try {
3408
+ const offer = await connection.createOffer();
3409
+ await connection.setLocalDescription(offer);
3410
+ await this._sendDescription(connection, offer);
3411
+ } catch (err) {
3412
+ this._lockAndAbort(connection, err);
3479
3413
  }
3480
- });
3481
- const proxyStream = new import_node_stream3.Writable({
3482
- write: (chunk, _, callback) => {
3483
- const then = performance.now();
3484
- this._options.bridgeService.sendData({
3485
- proxyId: this._proxyId,
3486
- payload: chunk
3414
+ },
3415
+ // When ICE candidate identified (should be sent to remote peer) and when ICE gathering finalized.
3416
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/icecandidate_event
3417
+ onicecandidate: async (event) => {
3418
+ if (connection !== this._connection) {
3419
+ this._onConnectionCallbackAfterClose("onicecandidate", connection);
3420
+ return;
3421
+ }
3422
+ if (event.candidate) {
3423
+ (0, import_log12.log)("onicecandidate", {
3424
+ candidate: event.candidate.candidate
3487
3425
  }, {
3488
- timeout: RPC_TIMEOUT
3489
- }).then(() => {
3490
- if (performance.now() - then > RESP_MIN_THRESHOLD) {
3491
- (0, import_log14.log)("slow response, delaying callback", void 0, {
3492
- F: __dxlog_file15,
3493
- L: 90,
3494
- S: this,
3495
- C: (f, a) => f(...a)
3496
- });
3497
- (0, import_async11.scheduleTask)(this._ctx, () => callback(), RESP_MIN_THRESHOLD);
3498
- } else {
3499
- callback();
3500
- }
3501
- this._timeoutCount = 0;
3502
- }, (err) => {
3503
- if (err instanceof import_protocols8.TimeoutError || err.constructor.name === "TimeoutError") {
3504
- if (this._timeoutCount++ > TIMEOUT_THRESHOLD) {
3505
- throw new import_protocols8.TimeoutError(`too many timeouts (${this._timeoutCount} > ${TIMEOUT_THRESHOLD}`);
3506
- } else {
3507
- (0, import_log14.log)("timeout error, but still invoking callback", void 0, {
3508
- F: __dxlog_file15,
3509
- L: 102,
3510
- S: this,
3511
- C: (f, a) => f(...a)
3512
- });
3513
- callback();
3514
- }
3515
- } else {
3516
- import_log14.log.catch(err, void 0, {
3517
- F: __dxlog_file15,
3518
- L: 106,
3519
- S: this,
3520
- C: (f, a) => f(...a)
3521
- });
3522
- }
3426
+ F: __dxlog_file14,
3427
+ L: 156,
3428
+ S: this,
3429
+ C: (f, a) => f(...a)
3430
+ });
3431
+ await this._sendIceCandidate(event.candidate);
3432
+ } else {
3433
+ (0, import_log12.log)("onicecandidate gathering complete", void 0, {
3434
+ F: __dxlog_file14,
3435
+ L: 159,
3436
+ S: this,
3437
+ C: (f, a) => f(...a)
3523
3438
  });
3524
3439
  }
3525
- });
3526
- proxyStream.on("error", (err) => {
3527
- (0, import_log14.log)("proxystream error", {
3528
- err
3440
+ },
3441
+ // When error occurs while performing ICE negotiations through a STUN or TURN server.
3442
+ // It's ok for some candidates to fail if a working pair is eventually found.
3443
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/icecandidateerror_event
3444
+ onicecandidateerror: (event) => {
3445
+ const { url, errorCode, errorText } = event;
3446
+ iceCandidateErrors.push({
3447
+ url,
3448
+ errorCode,
3449
+ errorText
3450
+ });
3451
+ },
3452
+ // When possible error during ICE gathering.
3453
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/iceconnectionstatechange_event
3454
+ oniceconnectionstatechange: () => {
3455
+ if (connection !== this._connection) {
3456
+ this._onConnectionCallbackAfterClose("oniceconnectionstatechange", connection);
3457
+ return;
3458
+ }
3459
+ (0, import_log12.log)("oniceconnectionstatechange", {
3460
+ state: connection.iceConnectionState
3529
3461
  }, {
3530
- F: __dxlog_file15,
3531
- L: 114,
3462
+ F: __dxlog_file14,
3463
+ L: 179,
3532
3464
  S: this,
3533
3465
  C: (f, a) => f(...a)
3534
3466
  });
3535
- });
3536
- this._options.stream.pipe(proxyStream);
3537
- }, (error) => import_log14.log.catch(error, void 0, {
3538
- F: __dxlog_file15,
3539
- L: 119,
3540
- S: this,
3541
- C: (f, a) => f(...a)
3542
- }));
3467
+ if (connection.iceConnectionState === "failed") {
3468
+ this._lockAndAbort(connection, createIceFailureError(iceCandidateErrors));
3469
+ }
3470
+ },
3471
+ // When new track (or channel) is added.
3472
+ // State: { new, connecting, connected, disconnected, failed, closed }
3473
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionstatechange_event
3474
+ onconnectionstatechange: () => {
3475
+ if (connection !== this._connection) {
3476
+ if (connection.connectionState !== "closed" && connection.connectionState !== "failed") {
3477
+ this._onConnectionCallbackAfterClose("onconnectionstatechange", connection);
3478
+ }
3479
+ return;
3480
+ }
3481
+ (0, import_log12.log)("onconnectionstatechange", {
3482
+ state: connection.connectionState
3483
+ }, {
3484
+ F: __dxlog_file14,
3485
+ L: 196,
3486
+ S: this,
3487
+ C: (f, a) => f(...a)
3488
+ });
3489
+ if (connection.connectionState === "failed") {
3490
+ this._lockAndAbort(connection, new Error("Connection failed."));
3491
+ }
3492
+ },
3493
+ onsignalingstatechange: () => {
3494
+ (0, import_log12.log)("onsignalingstatechange", {
3495
+ state: connection.signalingState
3496
+ }, {
3497
+ F: __dxlog_file14,
3498
+ L: 203,
3499
+ S: this,
3500
+ C: (f, a) => f(...a)
3501
+ });
3502
+ },
3503
+ // When channel is added to connection.
3504
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/datachannel_event
3505
+ ondatachannel: (event) => {
3506
+ (0, import_invariant11.invariant)(!this._initiator, "Initiator is expected to create data channels.", {
3507
+ F: __dxlog_file14,
3508
+ L: 209,
3509
+ S: this,
3510
+ A: [
3511
+ "!this._initiator",
3512
+ "'Initiator is expected to create data channels.'"
3513
+ ]
3514
+ });
3515
+ if (connection !== this._connection) {
3516
+ this._onConnectionCallbackAfterClose("ondatachannel", connection);
3517
+ return;
3518
+ }
3519
+ (0, import_log12.log)("ondatachannel", {
3520
+ label: event.channel.label
3521
+ }, {
3522
+ F: __dxlog_file14,
3523
+ L: 216,
3524
+ S: this,
3525
+ C: (f, a) => f(...a)
3526
+ });
3527
+ this._dataChannels.set(event.channel.label, event.channel);
3528
+ const pendingCallback = this._channelCreatedCallbacks.get(event.channel.label);
3529
+ if (pendingCallback) {
3530
+ this._channelCreatedCallbacks.delete(event.channel.label);
3531
+ pendingCallback.resolve(event.channel);
3532
+ }
3533
+ }
3534
+ });
3535
+ this._connection = connection;
3536
+ this._readyForCandidates.reset();
3537
+ await this._factory.initConnection(connection, {
3538
+ initiator: this._initiator
3539
+ });
3540
+ return this._connection;
3543
3541
  }
3544
- async close() {
3545
- await this._ctx.dispose();
3546
- if (this._closed) {
3547
- return;
3548
- }
3549
- await this._serviceStream.close();
3550
- try {
3551
- await this._options.bridgeService.close({
3552
- proxyId: this._proxyId
3542
+ _lockAndAbort(connection, error) {
3543
+ this._abortConnection(connection, error);
3544
+ }
3545
+ _abortConnection(connection, error) {
3546
+ if (connection !== this._connection) {
3547
+ import_log12.log.error("attempted to abort an inactive connection", {
3548
+ error
3553
3549
  }, {
3554
- timeout: RPC_TIMEOUT
3555
- });
3556
- } catch (err) {
3557
- import_log14.log.catch(err, void 0, {
3558
- F: __dxlog_file15,
3559
- L: 134,
3550
+ F: __dxlog_file14,
3551
+ L: 241,
3560
3552
  S: this,
3561
3553
  C: (f, a) => f(...a)
3562
3554
  });
3555
+ this._safeCloseConnection(connection);
3556
+ return;
3563
3557
  }
3564
- this.closed.emit();
3565
- this._closed = true;
3566
- }
3567
- async onSignal(signal) {
3568
- this._options.bridgeService.sendSignal({
3569
- proxyId: this._proxyId,
3570
- signal
3571
- }, {
3572
- timeout: RPC_TIMEOUT
3573
- }).catch((err) => this.errors.raise(decodeError(err)));
3574
- }
3575
- async _handleConnection(connectionEvent) {
3576
- if (connectionEvent.error) {
3577
- this.errors.raise(decodeError(connectionEvent.error));
3558
+ for (const [topic, pendingCallback] of this._channelCreatedCallbacks.entries()) {
3559
+ pendingCallback.reject(error);
3560
+ this._transportChannels.delete(topic);
3578
3561
  }
3579
- switch (connectionEvent.state) {
3580
- case import_bridge2.ConnectionState.CONNECTED: {
3581
- this.connected.emit();
3582
- break;
3583
- }
3584
- case import_bridge2.ConnectionState.CLOSED: {
3585
- await this.close();
3586
- break;
3587
- }
3562
+ this._channelCreatedCallbacks.clear();
3563
+ for (const channel of this._transportChannels.values()) {
3564
+ channel.onConnectionError(error);
3588
3565
  }
3589
- }
3590
- _handleData(dataEvent) {
3591
- this._options.stream.write((0, import_util10.arrayToBuffer)(dataEvent.payload));
3592
- }
3593
- async _handleSignal(signalEvent) {
3594
- await this._options.sendSignal(signalEvent.payload);
3595
- }
3596
- async getDetails() {
3597
- return (await this._options.bridgeService.getDetails({
3598
- proxyId: this._proxyId
3599
- }, {
3600
- timeout: RPC_TIMEOUT
3601
- })).details;
3602
- }
3603
- async getStats() {
3604
- return (await this._options.bridgeService.getStats({
3605
- proxyId: this._proxyId
3566
+ this._transportChannels.clear();
3567
+ this._safeCloseConnection();
3568
+ (0, import_log12.log)("connection aborted", {
3569
+ reason: error.message
3606
3570
  }, {
3607
- timeout: RPC_TIMEOUT
3608
- })).stats;
3609
- }
3610
- /**
3611
- * Called when underlying proxy service becomes unavailable.
3612
- */
3613
- // TODO(burdon): Option on close method.
3614
- forceClose() {
3615
- void this._serviceStream.close();
3616
- this.closed.emit();
3617
- this._closed = true;
3618
- }
3619
- };
3620
- var SimplePeerTransportProxyFactory = class {
3621
- constructor() {
3622
- this._connections = /* @__PURE__ */ new Set();
3623
- }
3624
- /**
3625
- * Sets the current BridgeService to be used to open connections.
3626
- * Calling this method will close any existing connections.
3627
- */
3628
- setBridgeService(bridgeService) {
3629
- this._bridgeService = bridgeService;
3630
- for (const connection of this._connections) {
3631
- connection.forceClose();
3632
- }
3633
- return this;
3571
+ F: __dxlog_file14,
3572
+ L: 255,
3573
+ S: this,
3574
+ C: (f, a) => f(...a)
3575
+ });
3634
3576
  }
3635
- createTransport(options) {
3636
- (0, import_invariant12.invariant)(this._bridgeService, "SimplePeerTransportProxyFactory is not ready to open connections", {
3637
- F: __dxlog_file15,
3638
- L: 218,
3577
+ _lockAndCloseConnection() {
3578
+ (0, import_invariant11.invariant)(this._transportChannels.size === 0, void 0, {
3579
+ F: __dxlog_file14,
3580
+ L: 260,
3639
3581
  S: this,
3640
3582
  A: [
3641
- "this._bridgeService",
3642
- "'SimplePeerTransportProxyFactory is not ready to open connections'"
3583
+ "this._transportChannels.size === 0",
3584
+ ""
3643
3585
  ]
3644
3586
  });
3645
- const transport = new SimplePeerTransportProxy({
3646
- ...options,
3647
- bridgeService: this._bridgeService
3648
- });
3649
- this._connections.add(transport);
3650
- transport.closed.on(() => this._connections.delete(transport));
3651
- return transport;
3652
- }
3653
- };
3654
- var decodeError = (err) => {
3655
- const message = typeof err === "string" ? err : err.message;
3656
- if (message.includes("CONNECTION_RESET")) {
3657
- return new import_protocols8.ConnectionResetError(message);
3658
- } else if (message.includes("TIMEOUT")) {
3659
- return new import_protocols8.TimeoutError(message);
3660
- } else if (message.includes("PROTOCOL_ERROR")) {
3661
- return new import_protocols8.ProtocolError(message);
3662
- } else if (message.includes("CONNECTIVITY_ERROR")) {
3663
- return new import_protocols8.ConnectivityError(message);
3664
- } else if (message.includes("UNKNOWN_PROTOCOL_ERROR")) {
3665
- return new import_protocols8.UnknownProtocolError(message);
3666
- } else {
3667
- return typeof err === "string" ? new Error(err) : err;
3668
- }
3669
- };
3670
- function _ts_decorate7(decorators, target, key, desc) {
3671
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3672
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
3673
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3674
- return c > 3 && r && Object.defineProperty(target, key, r), r;
3675
- }
3676
- var __dxlog_file16 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/libdatachannel-transport.ts";
3677
- var DATACHANNEL_LABEL = "dxos.mesh.transport";
3678
- var MAX_BUFFERED_AMOUNT = 64 * 1024;
3679
- var MAX_MESSAGE_SIZE = 64 * 1024;
3680
- var createLibDataChannelTransportFactory = (webrtcConfig, iceProvider) => {
3681
- return {
3682
- createTransport: (options) => new LibDataChannelTransport({
3683
- ...options,
3684
- webrtcConfig,
3685
- iceProvider
3686
- })
3687
- };
3688
- };
3689
- var LibDataChannelTransport = class _LibDataChannelTransport {
3690
- static {
3691
- this._instanceCount = 0;
3692
- }
3693
- constructor(_options) {
3694
- this._options = _options;
3695
- this._closed = false;
3696
- this._connected = false;
3697
- this._writeCallback = null;
3698
- this._readyForCandidates = new import_async12.Trigger();
3699
- this.closed = new import_async12.Event();
3700
- this.connected = new import_async12.Event();
3701
- this.errors = new import_debug7.ErrorStream();
3702
- }
3703
- get isOpen() {
3704
- return !!this._peer && !this._closed;
3705
- }
3706
- async open() {
3707
- if (this._closed) {
3708
- this.errors.raise(new Error("connection already closed"));
3709
- }
3710
- const { RTCPeerConnection } = (await importESM("node-datachannel/polyfill")).default;
3711
- const providedIceServers = await this._options.iceProvider?.getIceServers();
3712
- if (!this._options.webrtcConfig) {
3713
- this._options.webrtcConfig = {};
3714
- }
3715
- this._options.webrtcConfig.iceServers = [
3716
- ...this._options.webrtcConfig.iceServers ?? [],
3717
- ...providedIceServers ?? []
3718
- ];
3719
- this._peer = new RTCPeerConnection(this._options.webrtcConfig);
3720
- this._peer.onicecandidateerror = (event) => {
3721
- import_log15.log.error("peer.onicecandidateerror", {
3722
- event
3723
- }, {
3724
- F: __dxlog_file16,
3725
- L: 93,
3726
- S: this,
3727
- C: (f, a) => f(...a)
3728
- });
3729
- };
3730
- this._peer.onconnectionstatechange = (event) => {
3731
- import_log15.log.debug("peer.onconnectionstatechange", {
3732
- event,
3733
- peerConnectionState: this._peer?.connectionState,
3734
- transportConnectionState: this._connected
3735
- }, {
3736
- F: __dxlog_file16,
3737
- L: 97,
3587
+ if (this._connection) {
3588
+ this._safeCloseConnection();
3589
+ (0, import_log12.log)("connection closed", void 0, {
3590
+ F: __dxlog_file14,
3591
+ L: 263,
3738
3592
  S: this,
3739
3593
  C: (f, a) => f(...a)
3740
3594
  });
3741
- };
3742
- this._peer.onicecandidate = async (event) => {
3743
- import_log15.log.debug("peer.onicecandidate", {
3744
- event
3595
+ }
3596
+ }
3597
+ async onSignal(signal) {
3598
+ const connection = this._connection;
3599
+ if (!connection) {
3600
+ import_log12.log.warn("a signal ignored because the connection was closed", {
3601
+ type: signal.payload.data.type
3745
3602
  }, {
3746
- F: __dxlog_file16,
3747
- L: 107,
3603
+ F: __dxlog_file14,
3604
+ L: 271,
3748
3605
  S: this,
3749
3606
  C: (f, a) => f(...a)
3750
3607
  });
3751
- if (event.candidate) {
3752
- try {
3753
- await this._options.sendSignal({
3754
- payload: {
3755
- data: {
3756
- type: "candidate",
3757
- candidate: {
3758
- candidate: event.candidate.candidate,
3759
- // These fields never seem to be not null, but connecting to Chrome doesn't work if they are.
3760
- sdpMLineIndex: event.candidate.sdpMLineIndex ?? 0,
3761
- sdpMid: event.candidate.sdpMid ?? 0
3762
- }
3763
- }
3764
- }
3765
- });
3766
- } catch (err) {
3767
- import_log15.log.info("signaling error", {
3768
- err
3769
- }, {
3770
- F: __dxlog_file16,
3771
- L: 124,
3772
- S: this,
3773
- C: (f, a) => f(...a)
3774
- });
3775
- }
3608
+ return;
3609
+ }
3610
+ const data = signal.payload.data;
3611
+ switch (data.type) {
3612
+ case "offer": {
3613
+ await this._offerProcessingMutex.executeSynchronized(async () => {
3614
+ if (isRemoteDescriptionSet(connection, data)) {
3615
+ return;
3616
+ }
3617
+ if (connection.connectionState !== "new") {
3618
+ this._abortConnection(connection, new Error(`Received an offer in ${connection.connectionState}.`));
3619
+ return;
3620
+ }
3621
+ try {
3622
+ await connection.setRemoteDescription({
3623
+ type: data.type,
3624
+ sdp: data.sdp
3625
+ });
3626
+ const answer = await connection.createAnswer();
3627
+ await connection.setLocalDescription(answer);
3628
+ await this._sendDescription(connection, answer);
3629
+ this._onSessionNegotiated(connection);
3630
+ } catch (err) {
3631
+ this._abortConnection(connection, new Error("Error handling a remote offer.", {
3632
+ cause: err
3633
+ }));
3634
+ }
3635
+ });
3636
+ break;
3776
3637
  }
3777
- };
3778
- if (this._options.initiator) {
3779
- (0, import_invariant13.invariant)(this._peer, "not open", {
3780
- F: __dxlog_file16,
3781
- L: 130,
3782
- S: this,
3783
- A: [
3784
- "this._peer",
3785
- "'not open'"
3786
- ]
3787
- });
3788
- this._peer.createOffer().then(async (offer) => {
3789
- if (this._closed) {
3790
- return;
3791
- }
3792
- if (this._peer?.connectionState !== "connecting") {
3793
- import_log15.log.error("peer not connecting", {
3794
- peer: this._peer
3795
- }, {
3796
- F: __dxlog_file16,
3797
- L: 141,
3798
- S: this,
3799
- C: (f, a) => f(...a)
3800
- });
3801
- this.errors.raise(new Error("invalid state: peer is initiator, but other peer not in state connecting"));
3802
- }
3803
- import_log15.log.debug("creating offer", {
3804
- peer: this._peer,
3805
- offer
3638
+ case "answer":
3639
+ await this._offerProcessingMutex.executeSynchronized(async () => {
3640
+ try {
3641
+ if (isRemoteDescriptionSet(connection, data)) {
3642
+ return;
3643
+ }
3644
+ if (connection.signalingState !== "have-local-offer") {
3645
+ this._abortConnection(connection, new Error(`Unexpected answer from remote peer, signalingState was ${connection.signalingState}.`));
3646
+ return;
3647
+ }
3648
+ await connection.setRemoteDescription({
3649
+ type: data.type,
3650
+ sdp: data.sdp
3651
+ });
3652
+ this._onSessionNegotiated(connection);
3653
+ } catch (err) {
3654
+ this._abortConnection(connection, new Error("Error handling a remote answer.", {
3655
+ cause: err
3656
+ }));
3657
+ }
3658
+ });
3659
+ break;
3660
+ case "candidate":
3661
+ void this._processIceCandidate(connection, data.candidate);
3662
+ break;
3663
+ default:
3664
+ this._abortConnection(connection, new Error(`Unknown signal type ${data.type}.`));
3665
+ break;
3666
+ }
3667
+ (0, import_log12.log)("signal processed", {
3668
+ type: data.type
3669
+ }, {
3670
+ F: __dxlog_file14,
3671
+ L: 330,
3672
+ S: this,
3673
+ C: (f, a) => f(...a)
3674
+ });
3675
+ }
3676
+ async _processIceCandidate(connection, candidate) {
3677
+ try {
3678
+ await this._readyForCandidates.wait();
3679
+ if (connection === this._connection) {
3680
+ (0, import_log12.log)("adding ice candidate", {
3681
+ candidate
3806
3682
  }, {
3807
- F: __dxlog_file16,
3808
- L: 145,
3683
+ F: __dxlog_file14,
3684
+ L: 338,
3809
3685
  S: this,
3810
3686
  C: (f, a) => f(...a)
3811
3687
  });
3812
- await this._peer.setLocalDescription(offer);
3813
- await this._options.sendSignal({
3814
- payload: {
3815
- data: {
3816
- type: offer.type,
3817
- sdp: offer.sdp
3818
- }
3819
- }
3820
- });
3821
- }).catch((err) => {
3822
- this.errors.raise(err);
3688
+ await connection.addIceCandidate(candidate);
3689
+ }
3690
+ } catch (err) {
3691
+ import_log12.log.catch(err, void 0, {
3692
+ F: __dxlog_file14,
3693
+ L: 342,
3694
+ S: this,
3695
+ C: (f, a) => f(...a)
3823
3696
  });
3824
- this._handleChannel(this._peer.createDataChannel(DATACHANNEL_LABEL));
3825
- import_log15.log.debug("created data channel", void 0, {
3826
- F: __dxlog_file16,
3827
- L: 155,
3697
+ }
3698
+ }
3699
+ _onSessionNegotiated(connection) {
3700
+ if (connection === this._connection) {
3701
+ (0, import_log12.log)("ready to process ice candidates", void 0, {
3702
+ F: __dxlog_file14,
3703
+ L: 348,
3828
3704
  S: this,
3829
3705
  C: (f, a) => f(...a)
3830
3706
  });
3831
- this._peer.ondatachannel = () => {
3832
- this.errors.raise(new Error("unexpected ondatachannel event for initiator"));
3833
- };
3707
+ this._readyForCandidates.wake();
3834
3708
  } else {
3835
- this._peer.ondatachannel = (event) => {
3836
- import_log15.log.debug("peer.ondatachannel (non-initiator)", {
3837
- event
3838
- }, {
3839
- F: __dxlog_file16,
3840
- L: 161,
3841
- S: this,
3842
- C: (f, a) => f(...a)
3843
- });
3844
- if (event.channel.label !== DATACHANNEL_LABEL) {
3845
- this.errors.raise(new Error(`unexpected channel label ${event.channel.label}`));
3846
- }
3847
- this._handleChannel(event.channel);
3848
- };
3709
+ import_log12.log.warn("session was negotiated after connection became inactive", void 0, {
3710
+ F: __dxlog_file14,
3711
+ L: 351,
3712
+ S: this,
3713
+ C: (f, a) => f(...a)
3714
+ });
3849
3715
  }
3850
- _LibDataChannelTransport._instanceCount++;
3851
3716
  }
3852
- async close() {
3853
- await this._close();
3854
- if (--_LibDataChannelTransport._instanceCount === 0) {
3855
- (await importESM("node-datachannel")).cleanup();
3856
- }
3717
+ _onConnectionCallbackAfterClose(callback, connection) {
3718
+ import_log12.log.warn("callback invoked after a connection was destroyed, this is probably a bug", {
3719
+ callback,
3720
+ state: connection.connectionState
3721
+ }, {
3722
+ F: __dxlog_file14,
3723
+ L: 356,
3724
+ S: this,
3725
+ C: (f, a) => f(...a)
3726
+ });
3727
+ this._safeCloseConnection(connection);
3857
3728
  }
3858
- async _close() {
3859
- if (this._closed) {
3860
- return;
3861
- }
3862
- await this._disconnectStreams();
3729
+ _safeCloseConnection(connection = this._connection) {
3730
+ const resetFields = this._connection && connection === this._connection;
3863
3731
  try {
3864
- this._peer?.close();
3732
+ connection?.close();
3865
3733
  } catch (err) {
3866
- this.errors.raise(err);
3734
+ import_log12.log.catch(err, void 0, {
3735
+ F: __dxlog_file14,
3736
+ L: 368,
3737
+ S: this,
3738
+ C: (f, a) => f(...a)
3739
+ });
3740
+ }
3741
+ if (resetFields) {
3742
+ this._connection = void 0;
3743
+ this._dataChannels.clear();
3744
+ this._readyForCandidates.wake();
3745
+ void this._factory.onConnectionDestroyed().catch((err) => import_log12.log.catch(err, void 0, {
3746
+ F: __dxlog_file14,
3747
+ L: 374,
3748
+ S: this,
3749
+ C: (f, a) => f(...a)
3750
+ }));
3751
+ for (const [_, pendingCallback] of this._channelCreatedCallbacks.entries()) {
3752
+ pendingCallback.reject("Connection closed.");
3753
+ }
3754
+ this._channelCreatedCallbacks.clear();
3867
3755
  }
3868
- this._peer = void 0;
3869
- this._closed = true;
3870
- this.closed.emit();
3871
3756
  }
3872
- /**
3873
- * Handle data channel events.
3874
- */
3875
- _handleChannel(dataChannel) {
3876
- this._channel = dataChannel;
3877
- this._channel.onopen = () => {
3878
- import_log15.log.debug("channel.onopen", void 0, {
3879
- F: __dxlog_file16,
3880
- L: 206,
3757
+ async _loadConnectionConfig() {
3758
+ const config = {
3759
+ ...this._options.webrtcConfig
3760
+ };
3761
+ try {
3762
+ const providedIceServers = await this._options.iceProvider?.getIceServers() ?? [];
3763
+ if (providedIceServers.length > 0) {
3764
+ config.iceServers = [
3765
+ ...config.iceServers ?? [],
3766
+ ...providedIceServers
3767
+ ];
3768
+ }
3769
+ } catch (error) {
3770
+ import_log12.log.catch(error, void 0, {
3771
+ F: __dxlog_file14,
3772
+ L: 390,
3881
3773
  S: this,
3882
3774
  C: (f, a) => f(...a)
3883
3775
  });
3884
- const duplex = new import_stream.Duplex({
3885
- read: () => {
3886
- },
3887
- write: async (chunk, encoding, callback) => {
3888
- if (chunk.length > MAX_MESSAGE_SIZE) {
3889
- this.errors.raise(new Error(`message too large: ${chunk.length} > ${MAX_MESSAGE_SIZE}`));
3890
- }
3891
- try {
3892
- dataChannel.send(chunk);
3893
- } catch (err) {
3894
- this.errors.raise(err);
3895
- await this._close();
3896
- }
3897
- if (this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {
3898
- if (this._writeCallback !== null) {
3899
- import_log15.log.error("consumer trying to write before we are ready for more data", void 0, {
3900
- F: __dxlog_file16,
3901
- L: 223,
3902
- S: this,
3903
- C: (f, a) => f(...a)
3904
- });
3776
+ }
3777
+ return config;
3778
+ }
3779
+ async _sendIceCandidate(candidate) {
3780
+ try {
3781
+ await this._options.sendSignal({
3782
+ payload: {
3783
+ data: {
3784
+ type: "candidate",
3785
+ candidate: {
3786
+ candidate: candidate.candidate,
3787
+ // These fields never seem to be not null, but connecting to Chrome doesn't work if they are.
3788
+ sdpMLineIndex: candidate.sdpMLineIndex ?? "0",
3789
+ sdpMid: candidate.sdpMid ?? "0"
3905
3790
  }
3906
- this._writeCallback = callback;
3907
- } else {
3908
- callback();
3909
3791
  }
3910
3792
  }
3911
3793
  });
3912
- duplex.pipe(this._options.stream).pipe(duplex);
3913
- this._stream = duplex;
3914
- this._connected = true;
3915
- this.connected.emit();
3916
- };
3917
- this._channel.onclose = async (err) => {
3918
- import_log15.log.info("channel.onclose", {
3794
+ } catch (err) {
3795
+ import_log12.log.warn("signaling error", {
3919
3796
  err
3920
3797
  }, {
3921
- F: __dxlog_file16,
3922
- L: 239,
3798
+ F: __dxlog_file14,
3799
+ L: 411,
3923
3800
  S: this,
3924
3801
  C: (f, a) => f(...a)
3925
3802
  });
3926
- await this._close();
3803
+ }
3804
+ }
3805
+ async _sendDescription(connection, description) {
3806
+ if (connection !== this._connection) {
3807
+ return;
3808
+ }
3809
+ const data = {
3810
+ type: description.type,
3811
+ sdp: description.sdp
3927
3812
  };
3928
- this._channel.onerror = async (err) => {
3929
- this.errors.raise(new Error("channel error: " + err.toString()));
3930
- await this._close();
3813
+ await this._options.sendSignal({
3814
+ payload: {
3815
+ data
3816
+ }
3817
+ });
3818
+ }
3819
+ get _connectionInfo() {
3820
+ const connectionInfo = this._connection && {
3821
+ connectionState: this._connection.connectionState,
3822
+ iceConnectionState: this._connection.iceConnectionState,
3823
+ iceGatheringState: this._connection.iceGatheringState,
3824
+ signalingState: this._connection.signalingState,
3825
+ remoteDescription: this._connection.remoteDescription,
3826
+ localDescription: this._connection.localDescription
3931
3827
  };
3932
- this._channel.onbufferedamountlow = () => {
3933
- const cb = this._writeCallback;
3934
- this._writeCallback = null;
3935
- cb?.();
3828
+ return {
3829
+ ...connectionInfo,
3830
+ ts: Date.now(),
3831
+ remotePeerKey: this._options.remotePeerKey,
3832
+ channels: [
3833
+ ...this._transportChannels.keys()
3834
+ ].map((topic) => topic),
3835
+ config: this._connection?.getConfiguration()
3936
3836
  };
3937
- this._channel.onmessage = (event) => {
3938
- let data = event.data;
3939
- if (data instanceof ArrayBuffer) {
3940
- data = Buffer.from(data);
3941
- }
3942
- this._stream.push(data);
3837
+ }
3838
+ get _loggerContext() {
3839
+ return {
3840
+ ownPeerKey: this._options.ownPeerKey,
3841
+ remotePeerKey: this._options.remotePeerKey,
3842
+ initiator: this._initiator,
3843
+ channels: this._transportChannels.size
3943
3844
  };
3944
3845
  }
3945
- async onSignal(signal) {
3946
- (0, import_invariant13.invariant)(this._peer, "not open", {
3947
- F: __dxlog_file16,
3948
- L: 265,
3949
- S: this,
3950
- A: [
3951
- "this._peer",
3952
- "'not open'"
3953
- ]
3954
- });
3846
+ };
3847
+ _ts_decorate6([
3848
+ import_async11.synchronized
3849
+ ], RtcPeerConnection.prototype, "_openConnection", null);
3850
+ _ts_decorate6([
3851
+ import_async11.synchronized
3852
+ ], RtcPeerConnection.prototype, "_lockAndAbort", null);
3853
+ _ts_decorate6([
3854
+ import_async11.synchronized
3855
+ ], RtcPeerConnection.prototype, "_lockAndCloseConnection", null);
3856
+ _ts_decorate6([
3857
+ import_async11.synchronized
3858
+ ], RtcPeerConnection.prototype, "onSignal", null);
3859
+ _ts_decorate6([
3860
+ import_tracing.trace.info()
3861
+ ], RtcPeerConnection.prototype, "_connectionInfo", null);
3862
+ _ts_decorate6([
3863
+ import_log12.logInfo
3864
+ ], RtcPeerConnection.prototype, "_loggerContext", null);
3865
+ RtcPeerConnection = _ts_decorate6([
3866
+ import_tracing.trace.resource()
3867
+ ], RtcPeerConnection);
3868
+ var isRemoteDescriptionSet = (connection, data) => {
3869
+ if (!connection.remoteDescription?.type || connection.remoteDescription?.type !== data.type) {
3870
+ return false;
3871
+ }
3872
+ return areSdpEqual(connection.remoteDescription.sdp, data.sdp);
3873
+ };
3874
+ var createIceFailureError = (details) => {
3875
+ const candidateErrors = details.map(({ url, errorCode, errorText }) => `${errorCode} ${url}: ${errorText}`);
3876
+ return new import_protocols7.ConnectivityError(`ICE failed:
3877
+ ${candidateErrors.join("\n")}`);
3878
+ };
3879
+ var createRtcTransportFactory = (webrtcConfig, iceProvider) => {
3880
+ const connectionFactory = getRtcConnectionFactory();
3881
+ return {
3882
+ createTransport: (options) => {
3883
+ const connection = new RtcPeerConnection(connectionFactory, {
3884
+ ownPeerKey: options.ownPeerKey,
3885
+ remotePeerKey: options.remotePeerKey,
3886
+ sendSignal: options.sendSignal,
3887
+ webrtcConfig,
3888
+ iceProvider
3889
+ });
3890
+ return connection.createTransportChannel(options);
3891
+ }
3892
+ };
3893
+ };
3894
+ var __dxlog_file15 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc/rtc-transport-proxy.ts";
3895
+ var RPC_TIMEOUT = 1e4;
3896
+ var CLOSE_RPC_TIMEOUT = 3e3;
3897
+ var RESP_MIN_THRESHOLD = 500;
3898
+ var RtcTransportProxy = class extends import_context7.Resource {
3899
+ constructor(_options) {
3900
+ super();
3901
+ this._options = _options;
3902
+ this._proxyId = import_keys10.PublicKey.random();
3903
+ this.closed = new import_async13.Event();
3904
+ this.connected = new import_async13.Event();
3905
+ this.errors = new import_debug6.ErrorStream();
3906
+ }
3907
+ async _open() {
3908
+ let stream;
3955
3909
  try {
3956
- const data = signal.payload.data;
3957
- switch (data.type) {
3958
- case "offer": {
3959
- if (this._peer.connectionState !== "new") {
3960
- import_log15.log.error("received offer but peer not in state new", {
3961
- peer: this._peer
3962
- }, {
3963
- F: __dxlog_file16,
3964
- L: 272,
3965
- S: this,
3966
- C: (f, a) => f(...a)
3967
- });
3968
- this.errors.raise(new Error("invalid signalling state: received offer when peer is not in state new"));
3969
- break;
3970
- }
3971
- try {
3972
- await this._peer.setRemoteDescription({
3973
- type: data.type,
3974
- sdp: data.sdp
3975
- });
3976
- const answer = await this._peer.createAnswer();
3977
- await this._peer.setLocalDescription(answer);
3978
- await this._options.sendSignal({
3979
- payload: {
3980
- data: {
3981
- type: answer.type,
3982
- sdp: answer.sdp
3983
- }
3984
- }
3985
- });
3986
- this._readyForCandidates.wake();
3987
- } catch (err) {
3988
- import_log15.log.error("cannot handle offer from signalling server", {
3989
- err
3990
- }, {
3991
- F: __dxlog_file16,
3992
- L: 284,
3993
- S: this,
3994
- C: (f, a) => f(...a)
3995
- });
3996
- this.errors.raise(new Error("error handling offer"));
3997
- }
3998
- break;
3910
+ stream = this._options.bridgeService.open({
3911
+ proxyId: this._proxyId,
3912
+ remotePeerKey: this._options.remotePeerKey,
3913
+ ownPeerKey: this._options.ownPeerKey,
3914
+ topic: this._options.topic,
3915
+ initiator: this._options.initiator ?? false
3916
+ }, {
3917
+ timeout: RPC_TIMEOUT
3918
+ });
3919
+ } catch (error) {
3920
+ this.errors.raise(error);
3921
+ return;
3922
+ }
3923
+ this._serviceStream = stream;
3924
+ stream.waitUntilReady().then(() => {
3925
+ stream.subscribe(async (event) => {
3926
+ (0, import_log14.log)("rtc transport proxy event", event, {
3927
+ F: __dxlog_file15,
3928
+ L: 66,
3929
+ S: this,
3930
+ C: (f, a) => f(...a)
3931
+ });
3932
+ if (event.connection) {
3933
+ await this._handleConnection(event.connection);
3934
+ } else if (event.data) {
3935
+ this._handleData(event.data);
3936
+ } else if (event.signal) {
3937
+ await this._handleSignal(event.signal);
3999
3938
  }
4000
- case "answer":
4001
- try {
4002
- await this._peer.setRemoteDescription({
4003
- type: data.type,
4004
- sdp: data.sdp
4005
- });
4006
- this._readyForCandidates.wake();
4007
- } catch (err) {
4008
- import_log15.log.error("cannot handle answer from signalling server", {
4009
- err
4010
- }, {
4011
- F: __dxlog_file16,
4012
- L: 295,
4013
- S: this,
4014
- C: (f, a) => f(...a)
4015
- });
4016
- this.errors.raise(new Error("error handling answer"));
4017
- }
4018
- break;
4019
- case "candidate":
4020
- await this._readyForCandidates.wait();
4021
- await this._peer.addIceCandidate({
4022
- candidate: data.candidate.candidate
4023
- });
4024
- break;
4025
- default:
4026
- import_log15.log.error("unhandled signal type", {
4027
- type: data.type,
4028
- signal
3939
+ }, (err) => {
3940
+ (0, import_log14.log)("rtc bridge stream closed", {
3941
+ err
3942
+ }, {
3943
+ F: __dxlog_file15,
3944
+ L: 76,
3945
+ S: this,
3946
+ C: (f, a) => f(...a)
3947
+ });
3948
+ if (err) {
3949
+ this._raiseIfOpen(err);
3950
+ } else {
3951
+ void this.close();
3952
+ }
3953
+ });
3954
+ const connectorStream = new import_node_stream3.Writable({
3955
+ write: (chunk, _, callback) => {
3956
+ const sendStartMs = Date.now();
3957
+ this._options.bridgeService.sendData({
3958
+ proxyId: this._proxyId,
3959
+ payload: chunk
4029
3960
  }, {
4030
- F: __dxlog_file16,
4031
- L: 306,
4032
- S: this,
4033
- C: (f, a) => f(...a)
3961
+ timeout: RPC_TIMEOUT
3962
+ }).then(() => {
3963
+ if (Date.now() - sendStartMs > RESP_MIN_THRESHOLD) {
3964
+ (0, import_log14.log)("slow response, delaying callback", void 0, {
3965
+ F: __dxlog_file15,
3966
+ L: 93,
3967
+ S: this,
3968
+ C: (f, a) => f(...a)
3969
+ });
3970
+ (0, import_async13.scheduleTask)(this._ctx, () => callback(), RESP_MIN_THRESHOLD);
3971
+ } else {
3972
+ callback();
3973
+ }
3974
+ }, (err) => {
3975
+ callback();
3976
+ this._raiseIfOpen(err);
4034
3977
  });
4035
- this.errors.raise(new Error(`unhandled signal type ${data.type}`));
3978
+ }
3979
+ });
3980
+ connectorStream.on("error", (err) => {
3981
+ this._raiseIfOpen(err);
3982
+ });
3983
+ this._options.stream.pipe(connectorStream);
3984
+ }, (error) => {
3985
+ if (error) {
3986
+ this._raiseIfOpen(error);
3987
+ } else {
3988
+ void this.close();
4036
3989
  }
3990
+ });
3991
+ }
3992
+ async _close() {
3993
+ try {
3994
+ await this._serviceStream?.close();
3995
+ this._serviceStream = void 0;
4037
3996
  } catch (err) {
4038
- import_log15.log.catch(err, void 0, {
4039
- F: __dxlog_file16,
4040
- L: 310,
3997
+ import_log14.log.catch(err, void 0, {
3998
+ F: __dxlog_file15,
3999
+ L: 128,
4000
+ S: this,
4001
+ C: (f, a) => f(...a)
4002
+ });
4003
+ }
4004
+ try {
4005
+ await this._options.bridgeService.close({
4006
+ proxyId: this._proxyId
4007
+ }, {
4008
+ timeout: CLOSE_RPC_TIMEOUT
4009
+ });
4010
+ } catch (err) {
4011
+ import_log14.log.catch(err, void 0, {
4012
+ F: __dxlog_file15,
4013
+ L: 134,
4041
4014
  S: this,
4042
4015
  C: (f, a) => f(...a)
4043
4016
  });
4044
4017
  }
4018
+ this.closed.emit();
4045
4019
  }
4046
- async getDetails() {
4047
- const stats = await this._getStats();
4048
- const rc = stats?.remoteCandidate;
4049
- if (!rc) {
4050
- return "unavailable";
4020
+ async onSignal(signal) {
4021
+ this._options.bridgeService.sendSignal({
4022
+ proxyId: this._proxyId,
4023
+ signal
4024
+ }, {
4025
+ timeout: RPC_TIMEOUT
4026
+ }).catch((err) => this._raiseIfOpen(decodeError(err)));
4027
+ }
4028
+ async _handleConnection(connectionEvent) {
4029
+ if (connectionEvent.error) {
4030
+ this.errors.raise(decodeError(connectionEvent.error));
4031
+ return;
4032
+ }
4033
+ switch (connectionEvent.state) {
4034
+ case import_bridge.ConnectionState.CONNECTED: {
4035
+ this.connected.emit();
4036
+ break;
4037
+ }
4038
+ case import_bridge.ConnectionState.CLOSED: {
4039
+ await this.close();
4040
+ break;
4041
+ }
4042
+ }
4043
+ }
4044
+ _handleData(dataEvent) {
4045
+ try {
4046
+ this._options.stream.write((0, import_util9.arrayToBuffer)(dataEvent.payload));
4047
+ } catch (error) {
4048
+ this._raiseIfOpen(error);
4049
+ }
4050
+ }
4051
+ async _handleSignal(signalEvent) {
4052
+ try {
4053
+ await this._options.sendSignal(signalEvent.payload);
4054
+ } catch (error) {
4055
+ const type = signalEvent.payload.payload.data?.type;
4056
+ if (type === "offer" || type === "answer") {
4057
+ this._raiseIfOpen(new import_protocols9.ConnectivityError(`Session establishment failed: ${type} couldn't be sent.`));
4058
+ }
4051
4059
  }
4052
- if (rc.candidateType === "relay") {
4053
- return `${rc.ip}:${rc.port} relay for ${rc.relatedAddress}:${rc.relatedPort}`;
4060
+ }
4061
+ async getDetails() {
4062
+ try {
4063
+ const response = await this._options.bridgeService.getDetails({
4064
+ proxyId: this._proxyId
4065
+ }, {
4066
+ timeout: RPC_TIMEOUT
4067
+ });
4068
+ return response.details;
4069
+ } catch (err) {
4070
+ return "bridge-svc unreachable";
4054
4071
  }
4055
- return `${rc.ip}:${rc.port} ${rc.candidateType}`;
4056
4072
  }
4057
4073
  async getStats() {
4058
- const stats = await this._getStats();
4059
- if (!stats) {
4074
+ try {
4075
+ const response = await this._options.bridgeService.getStats({
4076
+ proxyId: this._proxyId
4077
+ }, {
4078
+ timeout: RPC_TIMEOUT
4079
+ });
4080
+ return response.stats;
4081
+ } catch (err) {
4060
4082
  return {
4061
4083
  bytesSent: 0,
4062
4084
  bytesReceived: 0,
4063
4085
  packetsSent: 0,
4064
4086
  packetsReceived: 0,
4065
- rawStats: {}
4087
+ rawStats: "bridge-svc unreachable"
4066
4088
  };
4067
4089
  }
4068
- return {
4069
- bytesSent: stats.transport.bytesSent,
4070
- bytesReceived: stats.transport.bytesReceived,
4071
- packetsSent: 0,
4072
- packetsReceived: 0,
4073
- rawStats: stats.raw
4074
- };
4075
4090
  }
4076
- async _getStats() {
4077
- (0, import_invariant13.invariant)(this._peer, "not open", {
4078
- F: __dxlog_file16,
4079
- L: 350,
4091
+ _raiseIfOpen(error) {
4092
+ if (this.isOpen) {
4093
+ this.errors.raise(error);
4094
+ } else {
4095
+ import_log14.log.info("error swallowed because transport was closed", {
4096
+ message: error.message
4097
+ }, {
4098
+ F: __dxlog_file15,
4099
+ L: 215,
4100
+ S: this,
4101
+ C: (f, a) => f(...a)
4102
+ });
4103
+ }
4104
+ }
4105
+ /**
4106
+ * Called when underlying proxy service becomes unavailable.
4107
+ */
4108
+ forceClose() {
4109
+ void this._serviceStream?.close();
4110
+ this.closed.emit();
4111
+ }
4112
+ };
4113
+ var RtcTransportProxyFactory = class {
4114
+ constructor() {
4115
+ this._connections = /* @__PURE__ */ new Set();
4116
+ }
4117
+ /**
4118
+ * Sets the current BridgeService to be used to open connections.
4119
+ * Calling this method will close any existing connections.
4120
+ */
4121
+ setBridgeService(bridgeService) {
4122
+ this._bridgeService = bridgeService;
4123
+ for (const connection of this._connections) {
4124
+ connection.forceClose();
4125
+ }
4126
+ return this;
4127
+ }
4128
+ createTransport(options) {
4129
+ (0, import_invariant13.invariant)(this._bridgeService, "RtcTransportProxyFactory is not ready to open connections", {
4130
+ F: __dxlog_file15,
4131
+ L: 245,
4080
4132
  S: this,
4081
4133
  A: [
4082
- "this._peer",
4083
- "'not open'"
4134
+ "this._bridgeService",
4135
+ "'RtcTransportProxyFactory is not ready to open connections'"
4084
4136
  ]
4085
4137
  });
4086
- const stats = await this._peer.getStats();
4087
- const statsEntries = Array.from(stats.entries());
4088
- const transport = statsEntries.filter((s) => s[1].type === "transport")[0][1];
4089
- const candidatePair = statsEntries.filter((s) => s[0] === transport.selectedCandidatePairId);
4090
- let selectedCandidatePair;
4091
- let remoteCandidate;
4092
- if (candidatePair.length > 0) {
4093
- selectedCandidatePair = candidatePair[0][1];
4094
- remoteCandidate = statsEntries.filter((s) => s[0] === selectedCandidatePair.remoteCandidateId)[0][1];
4095
- }
4096
- return {
4097
- transport,
4098
- selectedCandidatePair,
4099
- remoteCandidate,
4100
- raw: Object.fromEntries(stats)
4101
- };
4102
- }
4103
- async _disconnectStreams() {
4104
- this._options.stream.unpipe?.(this._stream)?.unpipe?.(this._options.stream);
4138
+ const transport = new RtcTransportProxy({
4139
+ ...options,
4140
+ bridgeService: this._bridgeService
4141
+ });
4142
+ this._connections.add(transport);
4143
+ transport.closed.on(() => this._connections.delete(transport));
4144
+ return transport;
4105
4145
  }
4106
4146
  };
4107
- _ts_decorate7([
4108
- import_async12.synchronized
4109
- ], LibDataChannelTransport.prototype, "_close", null);
4110
- var importESM = Function("path", "return import(path)");
4111
- var __dxlog_file17 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/tcp-transport.ts";
4112
- var TcpTransportFactory = {
4113
- createTransport: (options) => new TcpTransport(options)
4147
+ var decodeError = (err) => {
4148
+ const message = typeof err === "string" ? err : err.message;
4149
+ if (message.includes("CONNECTION_RESET")) {
4150
+ return new import_protocols9.ConnectionResetError(message);
4151
+ } else if (message.includes("TIMEOUT")) {
4152
+ return new import_protocols9.TimeoutError(message);
4153
+ } else if (message.includes("CONNECTIVITY_ERROR")) {
4154
+ return new import_protocols9.ConnectivityError(message);
4155
+ } else {
4156
+ return typeof err === "string" ? new Error(err) : err;
4157
+ }
4114
4158
  };
4115
- var TcpTransport = class {
4116
- constructor(options) {
4117
- this.options = options;
4118
- this._server = void 0;
4119
- this._socket = void 0;
4120
- this._connected = false;
4121
- this._closed = false;
4122
- this.closed = new import_async13.Event();
4123
- this.connected = new import_async13.Event();
4124
- this.errors = new import_debug8.ErrorStream();
4159
+ var __dxlog_file16 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc/rtc-transport-service.ts";
4160
+ var RtcTransportService = class {
4161
+ constructor(webrtcConfig, iceProvider, _transportFactory = createRtcTransportFactory(webrtcConfig, iceProvider)) {
4162
+ this._transportFactory = _transportFactory;
4163
+ this._openTransports = new import_util10.ComplexMap(import_keys11.PublicKey.hash);
4125
4164
  }
4126
- get isOpen() {
4127
- return this._connected && !this._closed;
4165
+ hasOpenTransports() {
4166
+ return this._openTransports.size > 0;
4128
4167
  }
4129
- async open() {
4130
- (0, import_log16.log)("opening", void 0, {
4131
- F: __dxlog_file17,
4132
- L: 39,
4133
- S: this,
4134
- C: (f, a) => f(...a)
4135
- });
4136
- if (this.options.initiator) {
4137
- setTimeout(async () => {
4138
- const { Server } = await import("node:net");
4139
- this._server = new Server((socket) => {
4140
- (0, import_log16.log)("new connection", void 0, {
4141
- F: __dxlog_file17,
4142
- L: 47,
4143
- S: this,
4144
- C: (f, a) => f(...a)
4145
- });
4146
- if (this._connected) {
4147
- socket.destroy();
4148
- }
4149
- this._handleSocket(socket);
4150
- });
4151
- this._server.on("listening", () => {
4152
- const { port } = this._server.address();
4153
- (0, import_log16.log)("listening", {
4154
- port
4155
- }, {
4156
- F: __dxlog_file17,
4157
- L: 56,
4158
- S: this,
4159
- C: (f, a) => f(...a)
4160
- });
4161
- void this.options.sendSignal({
4162
- payload: {
4163
- port
4168
+ open(request) {
4169
+ const existingTransport = this._openTransports.get(request.proxyId);
4170
+ if (existingTransport) {
4171
+ import_log15.log.error("requesting a new transport bridge for an existing proxy", void 0, {
4172
+ F: __dxlog_file16,
4173
+ L: 53,
4174
+ S: this,
4175
+ C: (f, a) => f(...a)
4176
+ });
4177
+ void this._safeCloseTransport(existingTransport);
4178
+ this._openTransports.delete(request.proxyId);
4179
+ }
4180
+ return new import_codec_protobuf.Stream(({ ready, next, close }) => {
4181
+ const pushNewState = createStateUpdater(next);
4182
+ const transportStream = new import_node_stream4.Duplex({
4183
+ read: () => {
4184
+ const callbacks = [
4185
+ ...transportState.writeProcessedCallbacks
4186
+ ];
4187
+ transportState.writeProcessedCallbacks.length = 0;
4188
+ callbacks.forEach((cb) => cb());
4189
+ },
4190
+ write: function(chunk, _, callback) {
4191
+ next({
4192
+ data: {
4193
+ payload: chunk
4164
4194
  }
4165
- }).catch((err) => {
4166
- if (!this._closed) {
4167
- this.errors.raise(err);
4195
+ });
4196
+ callback();
4197
+ }
4198
+ });
4199
+ const transport = this._transportFactory.createTransport({
4200
+ initiator: request.initiator,
4201
+ topic: request.topic,
4202
+ ownPeerKey: request.ownPeerKey,
4203
+ remotePeerKey: request.remotePeerKey,
4204
+ stream: transportStream,
4205
+ sendSignal: async (signal) => {
4206
+ next({
4207
+ signal: {
4208
+ payload: signal
4168
4209
  }
4169
4210
  });
4170
- });
4171
- this._server.on("error", (err) => {
4172
- this.errors.raise(err);
4173
- });
4174
- this._server.listen(0);
4211
+ }
4175
4212
  });
4176
- }
4213
+ const transportState = {
4214
+ proxyId: request.proxyId,
4215
+ transport,
4216
+ connectorStream: transportStream,
4217
+ writeProcessedCallbacks: []
4218
+ };
4219
+ pushNewState(import_bridge2.ConnectionState.CONNECTING);
4220
+ transport.connected.on(() => pushNewState(import_bridge2.ConnectionState.CONNECTED));
4221
+ transport.errors.handle(async (err) => {
4222
+ pushNewState(import_bridge2.ConnectionState.CLOSED, err);
4223
+ void this._safeCloseTransport(transportState);
4224
+ close(err);
4225
+ });
4226
+ transport.closed.on(async () => {
4227
+ pushNewState(import_bridge2.ConnectionState.CLOSED);
4228
+ void this._safeCloseTransport(transportState);
4229
+ close();
4230
+ });
4231
+ this._openTransports.set(request.proxyId, transportState);
4232
+ transport.open().catch(async (err) => {
4233
+ pushNewState(import_bridge2.ConnectionState.CLOSED, err);
4234
+ void this._safeCloseTransport(transportState);
4235
+ close(err);
4236
+ });
4237
+ ready();
4238
+ });
4177
4239
  }
4178
- async close() {
4179
- (0, import_log16.log)("closing", void 0, {
4180
- F: __dxlog_file17,
4181
- L: 78,
4240
+ async sendSignal({ proxyId, signal }) {
4241
+ const transport = this._openTransports.get(proxyId);
4242
+ (0, import_invariant14.invariant)(transport, void 0, {
4243
+ F: __dxlog_file16,
4244
+ L: 121,
4182
4245
  S: this,
4183
- C: (f, a) => f(...a)
4246
+ A: [
4247
+ "transport",
4248
+ ""
4249
+ ]
4184
4250
  });
4185
- this._socket?.destroy();
4186
- this._server?.close();
4187
- this._closed = true;
4251
+ await transport.transport.onSignal(signal);
4188
4252
  }
4189
- async onSignal({ payload }) {
4190
- (0, import_log16.log)("received signal", {
4191
- payload
4192
- }, {
4193
- F: __dxlog_file17,
4194
- L: 85,
4253
+ async getDetails({ proxyId }) {
4254
+ const transport = this._openTransports.get(proxyId);
4255
+ (0, import_invariant14.invariant)(transport, void 0, {
4256
+ F: __dxlog_file16,
4257
+ L: 128,
4195
4258
  S: this,
4196
- C: (f, a) => f(...a)
4197
- });
4198
- if (this.options.initiator || this._connected) {
4199
- return;
4200
- }
4201
- const socket = new import_node_net.Socket();
4202
- this._handleSocket(socket);
4203
- socket.connect({
4204
- port: payload.port,
4205
- host: "localhost"
4259
+ A: [
4260
+ "transport",
4261
+ ""
4262
+ ]
4206
4263
  });
4264
+ return {
4265
+ details: await transport.transport.getDetails()
4266
+ };
4207
4267
  }
4208
- async getDetails() {
4209
- if (this.options.initiator) {
4210
- const { port: port2, address: address2 } = this._server?.address();
4211
- return `LISTEN ${address2}:${port2}`;
4212
- }
4213
- const { port, address } = this._socket?.address();
4214
- return `ACCEPT ${address}:${port}`;
4215
- }
4216
- async getStats() {
4268
+ async getStats({ proxyId }) {
4269
+ const transport = this._openTransports.get(proxyId);
4270
+ (0, import_invariant14.invariant)(transport, void 0, {
4271
+ F: __dxlog_file16,
4272
+ L: 135,
4273
+ S: this,
4274
+ A: [
4275
+ "transport",
4276
+ ""
4277
+ ]
4278
+ });
4217
4279
  return {
4218
- bytesSent: 0,
4219
- bytesReceived: 0,
4220
- packetsSent: 0,
4221
- packetsReceived: 0
4280
+ stats: await transport.transport.getStats()
4222
4281
  };
4223
4282
  }
4224
- _handleSocket(socket) {
4225
- (0, import_log16.log)("handling socket", {
4226
- remotePort: socket.remotePort,
4227
- localPort: socket.localPort
4228
- }, {
4229
- F: __dxlog_file17,
4230
- L: 115,
4283
+ async sendData({ proxyId, payload }) {
4284
+ const transport = this._openTransports.get(proxyId);
4285
+ (0, import_invariant14.invariant)(transport, void 0, {
4286
+ F: __dxlog_file16,
4287
+ L: 142,
4231
4288
  S: this,
4232
- C: (f, a) => f(...a)
4289
+ A: [
4290
+ "transport",
4291
+ ""
4292
+ ]
4233
4293
  });
4234
- this._socket = socket;
4235
- this._socket.on("connect", () => {
4236
- (0, import_log16.log)("connected to", {
4237
- port: this._socket?.remotePort
4294
+ const bufferHasSpace = transport.connectorStream.push(payload);
4295
+ if (!bufferHasSpace) {
4296
+ await new Promise((resolve) => {
4297
+ transport.writeProcessedCallbacks.push(resolve);
4298
+ });
4299
+ }
4300
+ }
4301
+ async close({ proxyId }) {
4302
+ const transport = this._openTransports.get(proxyId);
4303
+ if (!transport) {
4304
+ return;
4305
+ }
4306
+ this._openTransports.delete(proxyId);
4307
+ await this._safeCloseTransport(transport);
4308
+ }
4309
+ async _safeCloseTransport(transport) {
4310
+ if (this._openTransports.get(transport.proxyId) === transport) {
4311
+ this._openTransports.delete(transport.proxyId);
4312
+ }
4313
+ transport.writeProcessedCallbacks.forEach((cb) => cb());
4314
+ try {
4315
+ await transport.transport.close();
4316
+ } catch (error) {
4317
+ import_log15.log.warn("transport close error", {
4318
+ message: error?.message
4238
4319
  }, {
4239
- F: __dxlog_file17,
4240
- L: 119,
4320
+ F: __dxlog_file16,
4321
+ L: 172,
4241
4322
  S: this,
4242
4323
  C: (f, a) => f(...a)
4243
4324
  });
4244
- this._connected = true;
4245
- });
4246
- this._socket.on("error", (err) => {
4247
- this.errors.raise(err);
4248
- });
4249
- this._socket.on("close", () => {
4250
- this.closed.emit();
4325
+ }
4326
+ try {
4327
+ transport.connectorStream.end();
4328
+ } catch (error) {
4329
+ import_log15.log.warn("connectorStream close error", {
4330
+ message: error?.message
4331
+ }, {
4332
+ F: __dxlog_file16,
4333
+ L: 177,
4334
+ S: this,
4335
+ C: (f, a) => f(...a)
4336
+ });
4337
+ }
4338
+ (0, import_log15.log)("closed", void 0, {
4339
+ F: __dxlog_file16,
4340
+ L: 179,
4341
+ S: this,
4342
+ C: (f, a) => f(...a)
4251
4343
  });
4252
- this.connected.emit();
4253
- this.options.stream.pipe(this._socket).pipe(this.options.stream);
4254
4344
  }
4255
4345
  };
4346
+ var createStateUpdater = (next) => {
4347
+ return (state, err) => {
4348
+ next({
4349
+ connection: {
4350
+ state,
4351
+ ...err ? {
4352
+ error: err.message
4353
+ } : void 0
4354
+ }
4355
+ });
4356
+ };
4357
+ };
4256
4358
  var createTeleportProtocolFactory = (onConnection, defaultParams) => {
4257
4359
  return (params) => {
4258
4360
  const teleport = new import_teleport.Teleport({
@@ -4282,26 +4384,21 @@ var createTeleportProtocolFactory = (onConnection, defaultParams) => {
4282
4384
  ConnectionState,
4283
4385
  EventType,
4284
4386
  FullyConnectedTopology,
4285
- LibDataChannelTransport,
4286
4387
  MAX_CONCURRENT_INITIATING_CONNECTIONS,
4287
4388
  MMSTTopology,
4288
4389
  MemoryTransport,
4289
4390
  MemoryTransportFactory,
4290
- SimplePeerTransport,
4291
- SimplePeerTransportProxy,
4292
- SimplePeerTransportProxyFactory,
4293
- SimplePeerTransportService,
4391
+ RtcTransportProxy,
4392
+ RtcTransportProxyFactory,
4393
+ RtcTransportService,
4294
4394
  StarTopology,
4295
4395
  Swarm,
4296
4396
  SwarmMapper,
4297
4397
  SwarmMessenger,
4298
4398
  SwarmNetworkManager,
4299
- TcpTransport,
4300
- TcpTransportFactory,
4301
4399
  TransportKind,
4302
4400
  createIceProvider,
4303
- createLibDataChannelTransportFactory,
4304
- createSimplePeerTransportFactory,
4401
+ createRtcTransportFactory,
4305
4402
  createTeleportProtocolFactory
4306
4403
  });
4307
- //# sourceMappingURL=chunk-4YAYC7WN.cjs.map
4404
+ //# sourceMappingURL=chunk-LK5D44SA.cjs.map