@dxos/network-manager 0.6.13 → 0.6.14-main.2b6a0f3

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-GW3YM55A.mjs +14 -0
  2. package/dist/lib/browser/chunk-GW3YM55A.mjs.map +7 -0
  3. package/dist/lib/browser/{chunk-XYSYUN63.mjs → chunk-V3IRGRVX.mjs} +1501 -1655
  4. package/dist/lib/browser/chunk-V3IRGRVX.mjs.map +7 -0
  5. package/dist/lib/browser/index.mjs +347 -22
  6. package/dist/lib/browser/index.mjs.map +4 -4
  7. package/dist/lib/browser/meta.json +1 -1
  8. package/dist/lib/browser/testing/index.mjs +22 -32
  9. package/dist/lib/browser/testing/index.mjs.map +3 -3
  10. package/dist/lib/browser/transport/tcp/index.mjs +39 -0
  11. package/dist/lib/browser/transport/tcp/index.mjs.map +7 -0
  12. package/dist/lib/node/{chunk-4YAYC7WN.cjs → chunk-4TTFBX3M.cjs} +1504 -1782
  13. package/dist/lib/node/chunk-4TTFBX3M.cjs.map +7 -0
  14. package/dist/lib/node/index.cjs +356 -37
  15. package/dist/lib/node/index.cjs.map +4 -4
  16. package/dist/lib/node/meta.json +1 -1
  17. package/dist/lib/node/testing/index.cjs +24 -34
  18. package/dist/lib/node/testing/index.cjs.map +3 -3
  19. package/dist/lib/node/transport/tcp/index.cjs +191 -0
  20. package/dist/lib/node/transport/tcp/index.cjs.map +7 -0
  21. package/dist/lib/node-esm/chunk-6MN5JVRP.mjs +4035 -0
  22. package/dist/lib/node-esm/chunk-6MN5JVRP.mjs.map +7 -0
  23. package/dist/lib/node-esm/index.mjs +382 -0
  24. package/dist/lib/node-esm/index.mjs.map +7 -0
  25. package/dist/lib/node-esm/meta.json +1 -0
  26. package/dist/lib/node-esm/testing/index.mjs +279 -0
  27. package/dist/lib/node-esm/testing/index.mjs.map +7 -0
  28. package/dist/lib/node-esm/transport/tcp/index.mjs +159 -0
  29. package/dist/lib/node-esm/transport/tcp/index.mjs.map +7 -0
  30. package/dist/types/src/network-manager.d.ts +2 -1
  31. package/dist/types/src/network-manager.d.ts.map +1 -1
  32. package/dist/types/src/signal/ice.d.ts.map +1 -1
  33. package/dist/types/src/signal/integration.node.test.d.ts +2 -0
  34. package/dist/types/src/signal/integration.node.test.d.ts.map +1 -0
  35. package/dist/types/src/signal/swarm-messenger.node.test.d.ts +2 -0
  36. package/dist/types/src/signal/swarm-messenger.node.test.d.ts.map +1 -0
  37. package/dist/types/src/swarm/connection.d.ts.map +1 -1
  38. package/dist/types/src/swarm/swarm.d.ts +1 -1
  39. package/dist/types/src/testing/test-builder.d.ts +2 -2
  40. package/dist/types/src/testing/test-builder.d.ts.map +1 -1
  41. package/dist/types/src/testing/test-wire-protocol.d.ts +1 -2
  42. package/dist/types/src/testing/test-wire-protocol.d.ts.map +1 -1
  43. package/dist/types/src/tests/basic-test-suite.d.ts.map +1 -1
  44. package/dist/types/src/tests/property-test-suite.d.ts.map +1 -1
  45. package/dist/types/src/tests/tcp-transport.node.test.d.ts +2 -0
  46. package/dist/types/src/tests/tcp-transport.node.test.d.ts.map +1 -0
  47. package/dist/types/src/tests/utils.d.ts.map +1 -1
  48. package/dist/types/src/transport/index.d.ts +1 -5
  49. package/dist/types/src/transport/index.d.ts.map +1 -1
  50. package/dist/types/src/transport/memory-transport.d.ts +2 -2
  51. package/dist/types/src/transport/memory-transport.d.ts.map +1 -1
  52. package/dist/types/src/transport/tcp/index.d.ts +2 -0
  53. package/dist/types/src/transport/tcp/index.d.ts.map +1 -0
  54. package/dist/types/src/transport/{tcp-transport.browser.d.ts → tcp/tcp-transport.browser.d.ts} +3 -3
  55. package/dist/types/src/transport/tcp/tcp-transport.browser.d.ts.map +1 -0
  56. package/dist/types/src/transport/{tcp-transport.d.ts → tcp/tcp-transport.d.ts} +3 -3
  57. package/dist/types/src/transport/tcp/tcp-transport.d.ts.map +1 -0
  58. package/dist/types/src/transport/transport.d.ts +7 -6
  59. package/dist/types/src/transport/transport.d.ts.map +1 -1
  60. package/dist/types/src/transport/webrtc/index.d.ts +4 -0
  61. package/dist/types/src/transport/webrtc/index.d.ts.map +1 -0
  62. package/dist/types/src/transport/webrtc/rtc-connection-factory.d.ts +14 -0
  63. package/dist/types/src/transport/webrtc/rtc-connection-factory.d.ts.map +1 -0
  64. package/dist/types/src/transport/webrtc/rtc-peer-connection.d.ts +68 -0
  65. package/dist/types/src/transport/webrtc/rtc-peer-connection.d.ts.map +1 -0
  66. package/dist/types/src/transport/webrtc/rtc-transport-channel.d.ts +33 -0
  67. package/dist/types/src/transport/webrtc/rtc-transport-channel.d.ts.map +1 -0
  68. package/dist/types/src/transport/webrtc/rtc-transport-channel.test.d.ts +2 -0
  69. package/dist/types/src/transport/webrtc/rtc-transport-channel.test.d.ts.map +1 -0
  70. package/dist/types/src/transport/webrtc/rtc-transport-factory.d.ts +4 -0
  71. package/dist/types/src/transport/webrtc/rtc-transport-factory.d.ts.map +1 -0
  72. package/dist/types/src/transport/{simplepeer-transport-proxy.d.ts → webrtc/rtc-transport-proxy.d.ts} +10 -12
  73. package/dist/types/src/transport/webrtc/rtc-transport-proxy.d.ts.map +1 -0
  74. package/dist/types/src/transport/webrtc/rtc-transport-proxy.test.d.ts +2 -0
  75. package/dist/types/src/transport/webrtc/rtc-transport-proxy.test.d.ts.map +1 -0
  76. package/dist/types/src/transport/{simplepeer-transport-service.d.ts → webrtc/rtc-transport-service.d.ts} +9 -7
  77. package/dist/types/src/transport/webrtc/rtc-transport-service.d.ts.map +1 -0
  78. package/dist/types/src/transport/webrtc/rtc-transport-stats.d.ts +4 -0
  79. package/dist/types/src/transport/webrtc/rtc-transport-stats.d.ts.map +1 -0
  80. package/dist/types/src/transport/webrtc/rtc-transport.test.d.ts +2 -0
  81. package/dist/types/src/transport/webrtc/rtc-transport.test.d.ts.map +1 -0
  82. package/dist/types/src/transport/webrtc/test-utils.d.ts +5 -0
  83. package/dist/types/src/transport/webrtc/test-utils.d.ts.map +1 -0
  84. package/dist/types/src/transport/webrtc/utils.d.ts +3 -0
  85. package/dist/types/src/transport/webrtc/utils.d.ts.map +1 -0
  86. package/package.json +56 -30
  87. package/src/network-manager.ts +5 -13
  88. package/src/signal/ice.test.ts +1 -3
  89. package/src/signal/ice.ts +6 -1
  90. package/src/signal/{integration.test.ts → integration.node.test.ts} +9 -15
  91. package/src/signal/{swarm-messenger.test.ts → swarm-messenger.node.test.ts} +13 -23
  92. package/src/swarm/connection-limiter.test.ts +3 -6
  93. package/src/swarm/connection.test.ts +63 -38
  94. package/src/swarm/connection.ts +5 -5
  95. package/src/swarm/swarm.test.ts +10 -12
  96. package/src/swarm/swarm.ts +1 -1
  97. package/src/testing/test-builder.ts +13 -29
  98. package/src/testing/test-wire-protocol.ts +1 -4
  99. package/src/tests/basic-test-suite.ts +34 -33
  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 +9 -9
  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 +198 -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,29 @@ 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_4TTFBX3M_exports = {};
30
+ __export(chunk_4TTFBX3M_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
- MMSTTopology: () => MMSTTopology,
40
38
  MemoryTransport: () => MemoryTransport,
41
39
  MemoryTransportFactory: () => MemoryTransportFactory,
42
- SimplePeerTransport: () => SimplePeerTransport,
43
- SimplePeerTransportProxy: () => SimplePeerTransportProxy,
44
- SimplePeerTransportProxyFactory: () => SimplePeerTransportProxyFactory,
45
- SimplePeerTransportService: () => SimplePeerTransportService,
46
- StarTopology: () => StarTopology,
40
+ RtcTransportProxy: () => RtcTransportProxy,
41
+ RtcTransportProxyFactory: () => RtcTransportProxyFactory,
42
+ RtcTransportService: () => RtcTransportService,
47
43
  Swarm: () => Swarm,
48
44
  SwarmMapper: () => SwarmMapper,
49
45
  SwarmMessenger: () => SwarmMessenger,
50
46
  SwarmNetworkManager: () => SwarmNetworkManager,
51
- TcpTransport: () => TcpTransport,
52
- TcpTransportFactory: () => TcpTransportFactory,
53
47
  TransportKind: () => TransportKind,
54
- createIceProvider: () => createIceProvider,
55
- createLibDataChannelTransportFactory: () => createLibDataChannelTransportFactory,
56
- createSimplePeerTransportFactory: () => createSimplePeerTransportFactory,
48
+ createRtcTransportFactory: () => createRtcTransportFactory,
57
49
  createTeleportProtocolFactory: () => createTeleportProtocolFactory
58
50
  });
59
- module.exports = __toCommonJS(chunk_4YAYC7WN_exports);
51
+ module.exports = __toCommonJS(chunk_4TTFBX3M_exports);
60
52
  var import_async = require("@dxos/async");
61
53
  var import_context = require("@dxos/context");
62
54
  var import_debug = require("@dxos/debug");
@@ -64,107 +56,91 @@ var import_invariant = require("@dxos/invariant");
64
56
  var import_keys = require("@dxos/keys");
65
57
  var import_log = require("@dxos/log");
66
58
  var import_protocols = require("@dxos/protocols");
67
- var import_async2 = require("@dxos/async");
68
- var import_log2 = require("@dxos/log");
69
- var import_util = require("@dxos/util");
70
59
  var import_context2 = require("@dxos/context");
71
60
  var import_invariant2 = require("@dxos/invariant");
72
61
  var import_keys2 = require("@dxos/keys");
73
- var import_log3 = require("@dxos/log");
62
+ var import_log2 = require("@dxos/log");
74
63
  var import_protocols2 = require("@dxos/protocols");
75
64
  var import_proto = require("@dxos/protocols/proto");
76
- var import_util2 = require("@dxos/util");
77
- var import_async3 = require("@dxos/async");
65
+ var import_util = require("@dxos/util");
66
+ var import_async2 = require("@dxos/async");
78
67
  var import_context3 = require("@dxos/context");
79
68
  var import_debug2 = require("@dxos/debug");
80
69
  var import_invariant3 = require("@dxos/invariant");
81
70
  var import_keys3 = require("@dxos/keys");
82
- var import_log4 = require("@dxos/log");
71
+ var import_log3 = require("@dxos/log");
83
72
  var import_messaging = require("@dxos/messaging");
84
73
  var import_protocols3 = require("@dxos/protocols");
85
- var import_util3 = require("@dxos/util");
86
- var import_async4 = require("@dxos/async");
74
+ var import_util2 = require("@dxos/util");
75
+ var import_async3 = require("@dxos/async");
87
76
  var import_context4 = require("@dxos/context");
88
77
  var import_invariant4 = require("@dxos/invariant");
89
78
  var import_keys4 = require("@dxos/keys");
90
- var import_log5 = require("@dxos/log");
79
+ var import_log4 = require("@dxos/log");
91
80
  var import_protocols4 = require("@dxos/protocols");
92
- var import_async5 = require("@dxos/async");
81
+ var import_async4 = require("@dxos/async");
93
82
  var import_keys5 = require("@dxos/keys");
94
- var import_log6 = require("@dxos/log");
83
+ var import_log5 = require("@dxos/log");
95
84
  var import_messaging2 = require("@dxos/messaging");
96
- var import_util4 = require("@dxos/util");
97
- var import_async6 = require("@dxos/async");
85
+ var import_util3 = require("@dxos/util");
86
+ var import_async5 = require("@dxos/async");
98
87
  var import_context5 = require("@dxos/context");
99
88
  var import_invariant5 = require("@dxos/invariant");
100
89
  var import_keys6 = require("@dxos/keys");
101
- var import_log7 = require("@dxos/log");
90
+ var import_log6 = require("@dxos/log");
102
91
  var import_protocols5 = require("@dxos/protocols");
103
- var import_util5 = require("@dxos/util");
104
- var import_async7 = require("@dxos/async");
92
+ var import_util4 = require("@dxos/util");
93
+ var import_async6 = require("@dxos/async");
105
94
  var import_debug3 = require("@dxos/debug");
106
95
  var import_keys7 = require("@dxos/keys");
107
- var import_util6 = require("@dxos/util");
108
- var import_async8 = require("@dxos/async");
96
+ var import_util5 = require("@dxos/util");
97
+ var import_async7 = require("@dxos/async");
109
98
  var import_invariant6 = require("@dxos/invariant");
110
99
  var import_keys8 = require("@dxos/keys");
111
- var import_log8 = require("@dxos/log");
100
+ var import_log7 = require("@dxos/log");
112
101
  var import_messaging3 = require("@dxos/messaging");
113
102
  var import_protocols6 = require("@dxos/protocols");
114
103
  var import_services = require("@dxos/protocols/proto/dxos/client/services");
115
- var import_util7 = require("@dxos/util");
104
+ var import_util6 = require("@dxos/util");
116
105
  var import_invariant7 = require("@dxos/invariant");
117
- var import_invariant8 = require("@dxos/invariant");
118
- var import_log9 = require("@dxos/log");
119
- var import_invariant9 = require("@dxos/invariant");
120
- var import_log10 = require("@dxos/log");
121
106
  var import_node_stream = require("node:stream");
122
- var import_async9 = require("@dxos/async");
107
+ var import_async8 = require("@dxos/async");
123
108
  var import_debug4 = require("@dxos/debug");
124
- var import_invariant10 = require("@dxos/invariant");
109
+ var import_invariant8 = require("@dxos/invariant");
125
110
  var import_keys9 = require("@dxos/keys");
126
- var import_log11 = require("@dxos/log");
127
- var import_util8 = require("@dxos/util");
128
- var import_simple_peer = __toESM(require("simple-peer"));
129
- var import_tiny_invariant = __toESM(require("tiny-invariant"));
111
+ var import_log8 = require("@dxos/log");
112
+ var import_util7 = require("@dxos/util");
113
+ var import_async9 = require("@dxos/async");
130
114
  var import_async10 = require("@dxos/async");
131
- var import_debug5 = require("@dxos/debug");
132
- var import_keys10 = require("@dxos/keys");
133
- var import_log12 = require("@dxos/log");
115
+ var import_invariant9 = require("@dxos/invariant");
116
+ var import_log9 = require("@dxos/log");
134
117
  var import_protocols7 = require("@dxos/protocols");
118
+ var import_tracing = require("@dxos/tracing");
135
119
  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");
139
- var import_log13 = require("@dxos/log");
140
- var import_bridge = require("@dxos/protocols/proto/dxos/mesh/bridge");
141
- var import_util9 = require("@dxos/util");
142
- var import_node_stream3 = require("node:stream");
143
120
  var import_async11 = require("@dxos/async");
144
121
  var import_context6 = require("@dxos/context");
122
+ var import_debug5 = require("@dxos/debug");
123
+ var import_invariant10 = require("@dxos/invariant");
124
+ var import_log10 = require("@dxos/log");
125
+ var import_protocols8 = require("@dxos/protocols");
126
+ var import_node_stream3 = require("node:stream");
127
+ var import_async12 = require("@dxos/async");
128
+ var import_context7 = require("@dxos/context");
145
129
  var import_debug6 = require("@dxos/debug");
130
+ var import_invariant11 = require("@dxos/invariant");
131
+ var import_keys10 = require("@dxos/keys");
132
+ var import_log11 = require("@dxos/log");
133
+ var import_protocols9 = require("@dxos/protocols");
134
+ var import_bridge = require("@dxos/protocols/proto/dxos/mesh/bridge");
135
+ var import_util8 = require("@dxos/util");
136
+ var import_node_stream4 = require("node:stream");
137
+ var import_codec_protobuf = require("@dxos/codec-protobuf");
146
138
  var import_invariant12 = require("@dxos/invariant");
147
- var import_keys12 = require("@dxos/keys");
148
- var import_log14 = require("@dxos/log");
149
- var import_protocols8 = require("@dxos/protocols");
139
+ var import_keys11 = require("@dxos/keys");
140
+ var import_log12 = require("@dxos/log");
150
141
  var import_bridge2 = require("@dxos/protocols/proto/dxos/mesh/bridge");
151
- 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");
142
+ var import_util9 = require("@dxos/util");
161
143
  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
144
  function _ts_decorate(decorators, target, key, desc) {
169
145
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
170
146
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -200,11 +176,11 @@ var Connection = class {
200
176
  this._callbacks = _callbacks;
201
177
  this._ctx = new import_context.Context(void 0, {
202
178
  F: __dxlog_file,
203
- L: 101
179
+ L: 100
204
180
  });
205
181
  this.connectedTimeoutContext = new import_context.Context(void 0, {
206
182
  F: __dxlog_file,
207
- L: 102
183
+ L: 101
208
184
  });
209
185
  this._protocolClosed = new import_async.Trigger();
210
186
  this._transportClosed = new import_async.Trigger();
@@ -227,7 +203,7 @@ var Connection = class {
227
203
  initiator: this.initiator
228
204
  }, {
229
205
  F: __dxlog_file,
230
- L: 138,
206
+ L: 137,
231
207
  S: this,
232
208
  C: (f, a) => f(...a)
233
209
  });
@@ -250,7 +226,7 @@ var Connection = class {
250
226
  async openConnection() {
251
227
  (0, import_invariant.invariant)(this._state === "INITIAL", "Invalid state.", {
252
228
  F: __dxlog_file,
253
- L: 168,
229
+ L: 167,
254
230
  S: this,
255
231
  A: [
256
232
  "this._state === ConnectionState.INITIAL",
@@ -261,7 +237,7 @@ var Connection = class {
261
237
  id: this._instanceId
262
238
  }), {
263
239
  F: __dxlog_file,
264
- L: 169,
240
+ L: 168,
265
241
  S: this,
266
242
  C: (f, a) => f(...a)
267
243
  });
@@ -273,7 +249,7 @@ var Connection = class {
273
249
  initiator: this.initiator
274
250
  }, {
275
251
  F: __dxlog_file,
276
- L: 170,
252
+ L: 169,
277
253
  S: this,
278
254
  C: (f, a) => f(...a)
279
255
  });
@@ -284,7 +260,7 @@ var Connection = class {
284
260
  this._protocol.stream.on("close", () => {
285
261
  (0, import_log.log)("protocol stream closed", void 0, {
286
262
  F: __dxlog_file,
287
- L: 187,
263
+ L: 186,
288
264
  S: this,
289
265
  C: (f, a) => f(...a)
290
266
  });
@@ -294,7 +270,7 @@ var Connection = class {
294
270
  (0, import_async.scheduleTask)(this.connectedTimeoutContext, async () => {
295
271
  import_log.log.info(`timeout waiting ${TRANSPORT_CONNECTION_TIMEOUT / 1e3}s for transport to connect, aborting`, void 0, {
296
272
  F: __dxlog_file,
297
- L: 195,
273
+ L: 194,
298
274
  S: this,
299
275
  C: (f, a) => f(...a)
300
276
  });
@@ -302,7 +278,7 @@ var Connection = class {
302
278
  }, TRANSPORT_CONNECTION_TIMEOUT);
303
279
  (0, import_invariant.invariant)(!this._transport, void 0, {
304
280
  F: __dxlog_file,
305
- L: 203,
281
+ L: 202,
306
282
  S: this,
307
283
  A: [
308
284
  "!this._transport",
@@ -310,12 +286,14 @@ var Connection = class {
310
286
  ]
311
287
  });
312
288
  this._transport = this._transportFactory.createTransport({
289
+ ownPeerKey: this.localInfo.peerKey,
290
+ remotePeerKey: this.remoteInfo.peerKey,
291
+ topic: this.topic.toHex(),
313
292
  initiator: this.initiator,
314
293
  stream: this._protocol.stream,
315
294
  sendSignal: async (signal) => this._sendSignal(signal),
316
295
  sessionId: this.sessionId
317
296
  });
318
- await this._transport.open();
319
297
  this._transport.connected.once(async () => {
320
298
  this._changeState("CONNECTED");
321
299
  await this.connectedTimeoutContext.dispose();
@@ -361,21 +339,13 @@ var Connection = class {
361
339
  C: (f, a) => f(...a)
362
340
  });
363
341
  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
- });
373
342
  }
374
343
  if (this._state !== "CLOSED" && this._state !== "CLOSING") {
375
344
  await this.connectedTimeoutContext.dispose();
376
345
  this.errors.raise(err);
377
346
  }
378
347
  });
348
+ await this._transport.open();
379
349
  for (const signal of this._incomingSignalBuffer) {
380
350
  void this._transport.onSignal(signal);
381
351
  }
@@ -727,38 +697,15 @@ _ts_decorate([
727
697
  _ts_decorate([
728
698
  import_async.synchronized
729
699
  ], Connection.prototype, "close", null);
730
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/signal/ice.ts";
731
- var createIceProvider = (iceProviders) => {
732
- let cachedIceServers;
733
- return {
734
- getIceServers: async () => {
735
- if (cachedIceServers) {
736
- return cachedIceServers;
737
- }
738
- cachedIceServers = (await Promise.all(iceProviders.map(({ urls }) => (0, import_async2.asyncTimeout)(fetch(urls, {
739
- 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();
749
- return cachedIceServers;
750
- }
751
- };
752
- };
753
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/signal/swarm-messenger.ts";
700
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/signal/swarm-messenger.ts";
754
701
  var SwarmMessage = import_proto.schema.getCodecForType("dxos.mesh.swarm.SwarmMessage");
755
702
  var SwarmMessenger = class {
756
703
  constructor({ sendMessage, onSignal, onOffer, topic }) {
757
704
  this._ctx = new import_context2.Context(void 0, {
758
- F: __dxlog_file3,
705
+ F: __dxlog_file2,
759
706
  L: 35
760
707
  });
761
- this._offerRecords = new import_util2.ComplexMap((key) => key.toHex());
708
+ this._offerRecords = new import_util.ComplexMap((key) => key.toHex());
762
709
  this._sendMessage = sendMessage;
763
710
  this._onSignal = onSignal;
764
711
  this._onOffer = onOffer;
@@ -772,12 +719,12 @@ var SwarmMessenger = class {
772
719
  if (!this._topic.equals(message.topic)) {
773
720
  return;
774
721
  }
775
- (0, import_log3.log)("received", {
722
+ (0, import_log2.log)("received", {
776
723
  from: author,
777
724
  to: recipient,
778
725
  msg: message
779
726
  }, {
780
- F: __dxlog_file3,
727
+ F: __dxlog_file2,
781
728
  L: 71,
782
729
  S: this,
783
730
  C: (f, a) => f(...a)
@@ -803,10 +750,10 @@ var SwarmMessenger = class {
803
750
  message
804
751
  });
805
752
  } else {
806
- import_log3.log.warn("unknown message", {
753
+ import_log2.log.warn("unknown message", {
807
754
  message
808
755
  }, {
809
- F: __dxlog_file3,
756
+ F: __dxlog_file2,
810
757
  L: 82,
811
758
  S: this,
812
759
  C: (f, a) => f(...a)
@@ -815,7 +762,7 @@ var SwarmMessenger = class {
815
762
  }
816
763
  async signal(message) {
817
764
  (0, import_invariant2.invariant)(message.data?.signal || message.data?.signalBatch, "Invalid message", {
818
- F: __dxlog_file3,
765
+ F: __dxlog_file2,
819
766
  L: 87,
820
767
  S: this,
821
768
  A: [
@@ -851,12 +798,12 @@ var SwarmMessenger = class {
851
798
  // Setting unique message_id if it not specified yet.
852
799
  messageId: message.messageId ?? import_keys2.PublicKey.random()
853
800
  };
854
- (0, import_log3.log)("sending", {
801
+ (0, import_log2.log)("sending", {
855
802
  from: author,
856
803
  to: recipient,
857
804
  msg: networkMessage
858
805
  }, {
859
- F: __dxlog_file3,
806
+ F: __dxlog_file2,
860
807
  L: 125,
861
808
  S: this,
862
809
  C: (f, a) => f(...a)
@@ -872,7 +819,7 @@ var SwarmMessenger = class {
872
819
  }
873
820
  async _resolveAnswers(message) {
874
821
  (0, import_invariant2.invariant)(message.data?.answer?.offerMessageId, "No offerMessageId", {
875
- F: __dxlog_file3,
822
+ F: __dxlog_file2,
876
823
  L: 137,
877
824
  S: this,
878
825
  A: [
@@ -884,7 +831,7 @@ var SwarmMessenger = class {
884
831
  if (offerRecord) {
885
832
  this._offerRecords.delete(message.data.answer.offerMessageId);
886
833
  (0, import_invariant2.invariant)(message.data?.answer, "No answer", {
887
- F: __dxlog_file3,
834
+ F: __dxlog_file2,
888
835
  L: 141,
889
836
  S: this,
890
837
  A: [
@@ -892,10 +839,10 @@ var SwarmMessenger = class {
892
839
  "'No answer'"
893
840
  ]
894
841
  });
895
- (0, import_log3.log)("resolving", {
842
+ (0, import_log2.log)("resolving", {
896
843
  answer: message.data.answer
897
844
  }, {
898
- F: __dxlog_file3,
845
+ F: __dxlog_file2,
899
846
  L: 142,
900
847
  S: this,
901
848
  C: (f, a) => f(...a)
@@ -905,7 +852,7 @@ var SwarmMessenger = class {
905
852
  }
906
853
  async _handleOffer({ author, recipient, message }) {
907
854
  (0, import_invariant2.invariant)(message.data.offer, "No offer", {
908
- F: __dxlog_file3,
855
+ F: __dxlog_file2,
909
856
  L: 156,
910
857
  S: this,
911
858
  A: [
@@ -937,19 +884,19 @@ var SwarmMessenger = class {
937
884
  });
938
885
  } catch (err) {
939
886
  if (err instanceof import_protocols2.TimeoutError) {
940
- import_log3.log.info("timeout sending answer to offer", {
887
+ import_log2.log.info("timeout sending answer to offer", {
941
888
  err
942
889
  }, {
943
- F: __dxlog_file3,
890
+ F: __dxlog_file2,
944
891
  L: 177,
945
892
  S: this,
946
893
  C: (f, a) => f(...a)
947
894
  });
948
895
  } else {
949
- import_log3.log.info("error sending answer to offer", {
896
+ import_log2.log.info("error sending answer to offer", {
950
897
  err
951
898
  }, {
952
- F: __dxlog_file3,
899
+ F: __dxlog_file2,
953
900
  L: 179,
954
901
  S: this,
955
902
  C: (f, a) => f(...a)
@@ -959,7 +906,7 @@ var SwarmMessenger = class {
959
906
  }
960
907
  async _handleSignal({ author, recipient, message }) {
961
908
  (0, import_invariant2.invariant)(message.messageId, void 0, {
962
- F: __dxlog_file3,
909
+ F: __dxlog_file2,
963
910
  L: 193,
964
911
  S: this,
965
912
  A: [
@@ -968,7 +915,7 @@ var SwarmMessenger = class {
968
915
  ]
969
916
  });
970
917
  (0, import_invariant2.invariant)(message.data.signal || message.data.signalBatch, "Invalid message", {
971
- F: __dxlog_file3,
918
+ F: __dxlog_file2,
972
919
  L: 194,
973
920
  S: this,
974
921
  A: [
@@ -994,7 +941,7 @@ function _ts_decorate2(decorators, target, key, desc) {
994
941
  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;
995
942
  return c > 3 && r && Object.defineProperty(target, key, r), r;
996
943
  }
997
- var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/peer.ts";
944
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/peer.ts";
998
945
  var ConnectionDisplacedError = class extends import_protocols4.SystemError {
999
946
  constructor() {
1000
947
  super("Connection displaced by remote initiator.");
@@ -1014,12 +961,12 @@ var Peer = class {
1014
961
  this._availableAfter = 0;
1015
962
  this.availableToConnect = true;
1016
963
  this._ctx = new import_context4.Context(void 0, {
1017
- F: __dxlog_file4,
964
+ F: __dxlog_file3,
1018
965
  L: 80
1019
966
  });
1020
967
  this.advertizing = false;
1021
968
  this.initiating = false;
1022
- this.connectionDisplaced = new import_async4.Event();
969
+ this.connectionDisplaced = new import_async3.Event();
1023
970
  }
1024
971
  /**
1025
972
  * Respond to remote offer.
@@ -1031,8 +978,8 @@ var Peer = class {
1031
978
  ConnectionState.INITIAL,
1032
979
  ConnectionState.CONNECTING
1033
980
  ].includes(this.connection.state)) {
1034
- import_log5.log.info(`received offer when connection already in ${this.connection.state} state`, void 0, {
1035
- F: __dxlog_file4,
981
+ import_log4.log.info(`received offer when connection already in ${this.connection.state} state`, void 0, {
982
+ F: __dxlog_file3,
1036
983
  L: 115,
1037
984
  S: this,
1038
985
  C: (f, a) => f(...a)
@@ -1043,13 +990,13 @@ var Peer = class {
1043
990
  }
1044
991
  if (this.connection || this.initiating) {
1045
992
  if (remote.peerKey < this.localInfo.peerKey) {
1046
- (0, import_log5.log)("close local connection", {
993
+ (0, import_log4.log)("close local connection", {
1047
994
  localPeer: this.localInfo,
1048
995
  topic: this.topic,
1049
996
  remotePeer: this.remoteInfo,
1050
997
  sessionId: this.connection?.sessionId
1051
998
  }, {
1052
- F: __dxlog_file4,
999
+ F: __dxlog_file3,
1053
1000
  L: 124,
1054
1001
  S: this,
1055
1002
  C: (f, a) => f(...a)
@@ -1066,7 +1013,7 @@ var Peer = class {
1066
1013
  if (await this._callbacks.onOffer(remote)) {
1067
1014
  if (!this.connection) {
1068
1015
  (0, import_invariant4.invariant)(message.sessionId, void 0, {
1069
- F: __dxlog_file4,
1016
+ F: __dxlog_file3,
1070
1017
  L: 144,
1071
1018
  S: this,
1072
1019
  A: [
@@ -1081,13 +1028,13 @@ var Peer = class {
1081
1028
  await connection.openConnection();
1082
1029
  } catch (err) {
1083
1030
  if (!(err instanceof import_protocols4.CancelledError)) {
1084
- import_log5.log.info("connection error", {
1031
+ import_log4.log.info("connection error", {
1085
1032
  topic: this.topic,
1086
1033
  peerId: this.localInfo,
1087
1034
  remoteId: this.remoteInfo,
1088
1035
  err
1089
1036
  }, {
1090
- F: __dxlog_file4,
1037
+ F: __dxlog_file3,
1091
1038
  L: 154,
1092
1039
  S: this,
1093
1040
  C: (f, a) => f(...a)
@@ -1109,7 +1056,7 @@ var Peer = class {
1109
1056
  */
1110
1057
  async initiateConnection() {
1111
1058
  (0, import_invariant4.invariant)(!this.initiating, "Initiation in progress.", {
1112
- F: __dxlog_file4,
1059
+ F: __dxlog_file3,
1113
1060
  L: 171,
1114
1061
  S: this,
1115
1062
  A: [
@@ -1118,7 +1065,7 @@ var Peer = class {
1118
1065
  ]
1119
1066
  });
1120
1067
  (0, import_invariant4.invariant)(!this.connection, "Already connected.", {
1121
- F: __dxlog_file4,
1068
+ F: __dxlog_file3,
1122
1069
  L: 172,
1123
1070
  S: this,
1124
1071
  A: [
@@ -1127,13 +1074,13 @@ var Peer = class {
1127
1074
  ]
1128
1075
  });
1129
1076
  const sessionId = import_keys4.PublicKey.random();
1130
- (0, import_log5.log)("initiating...", {
1077
+ (0, import_log4.log)("initiating...", {
1131
1078
  local: this.localInfo,
1132
1079
  topic: this.topic,
1133
1080
  remote: this.remoteInfo,
1134
1081
  sessionId
1135
1082
  }, {
1136
- F: __dxlog_file4,
1083
+ F: __dxlog_file3,
1137
1084
  L: 174,
1138
1085
  S: this,
1139
1086
  C: (f, a) => f(...a)
@@ -1153,20 +1100,20 @@ var Peer = class {
1153
1100
  offer: {}
1154
1101
  }
1155
1102
  });
1156
- (0, import_log5.log)("received", {
1103
+ (0, import_log4.log)("received", {
1157
1104
  answer,
1158
1105
  topic: this.topic,
1159
1106
  local: this.localInfo,
1160
1107
  remote: this.remoteInfo
1161
1108
  }, {
1162
- F: __dxlog_file4,
1109
+ F: __dxlog_file3,
1163
1110
  L: 191,
1164
1111
  S: this,
1165
1112
  C: (f, a) => f(...a)
1166
1113
  });
1167
1114
  if (connection.state !== ConnectionState.INITIAL) {
1168
- (0, import_log5.log)("ignoring response", void 0, {
1169
- F: __dxlog_file4,
1115
+ (0, import_log4.log)("ignoring response", void 0, {
1116
+ F: __dxlog_file3,
1170
1117
  L: 193,
1171
1118
  S: this,
1172
1119
  C: (f, a) => f(...a)
@@ -1174,13 +1121,13 @@ var Peer = class {
1174
1121
  return;
1175
1122
  }
1176
1123
  } catch (err) {
1177
- (0, import_log5.log)("initiation error: send offer", {
1124
+ (0, import_log4.log)("initiation error: send offer", {
1178
1125
  err,
1179
1126
  topic: this.topic,
1180
1127
  local: this.localInfo,
1181
1128
  remote: this.remoteInfo
1182
1129
  }, {
1183
- F: __dxlog_file4,
1130
+ F: __dxlog_file3,
1184
1131
  L: 197,
1185
1132
  S: this,
1186
1133
  C: (f, a) => f(...a)
@@ -1196,13 +1143,13 @@ var Peer = class {
1196
1143
  return;
1197
1144
  }
1198
1145
  } catch (err) {
1199
- (0, import_log5.log)("initiation error: accept answer", {
1146
+ (0, import_log4.log)("initiation error: accept answer", {
1200
1147
  err,
1201
1148
  topic: this.topic,
1202
1149
  local: this.localInfo,
1203
1150
  remote: this.remoteInfo
1204
1151
  }, {
1205
- F: __dxlog_file4,
1152
+ F: __dxlog_file3,
1206
1153
  L: 210,
1207
1154
  S: this,
1208
1155
  C: (f, a) => f(...a)
@@ -1213,8 +1160,8 @@ var Peer = class {
1213
1160
  this.initiating = false;
1214
1161
  }
1215
1162
  try {
1216
- (0, import_log5.log)("opening connection as initiator", void 0, {
1217
- F: __dxlog_file4,
1163
+ (0, import_log4.log)("opening connection as initiator", void 0, {
1164
+ F: __dxlog_file3,
1218
1165
  L: 223,
1219
1166
  S: this,
1220
1167
  C: (f, a) => f(...a)
@@ -1222,21 +1169,21 @@ var Peer = class {
1222
1169
  await connection.openConnection();
1223
1170
  this._callbacks.onAccepted();
1224
1171
  } catch (err) {
1225
- (0, import_log5.log)("initiation error: open connection", {
1172
+ (0, import_log4.log)("initiation error: open connection", {
1226
1173
  err,
1227
1174
  topic: this.topic,
1228
1175
  local: this.localInfo,
1229
1176
  remote: this.remoteInfo
1230
1177
  }, {
1231
- F: __dxlog_file4,
1178
+ F: __dxlog_file3,
1232
1179
  L: 227,
1233
1180
  S: this,
1234
1181
  C: (f, a) => f(...a)
1235
1182
  });
1236
- import_log5.log.warn("closing connection due to unhandled error on openConnection", {
1183
+ import_log4.log.warn("closing connection due to unhandled error on openConnection", {
1237
1184
  err
1238
1185
  }, {
1239
- F: __dxlog_file4,
1186
+ F: __dxlog_file3,
1240
1187
  L: 234,
1241
1188
  S: this,
1242
1189
  C: (f, a) => f(...a)
@@ -1252,20 +1199,20 @@ var Peer = class {
1252
1199
  * Either we're initiating a connection or creating one in response to an offer from the other peer.
1253
1200
  */
1254
1201
  _createConnection(initiator, sessionId) {
1255
- (0, import_log5.log)("creating connection", {
1202
+ (0, import_log4.log)("creating connection", {
1256
1203
  topic: this.topic,
1257
1204
  peerId: this.localInfo,
1258
1205
  remoteId: this.remoteInfo,
1259
1206
  initiator,
1260
1207
  sessionId
1261
1208
  }, {
1262
- F: __dxlog_file4,
1209
+ F: __dxlog_file3,
1263
1210
  L: 248,
1264
1211
  S: this,
1265
1212
  C: (f, a) => f(...a)
1266
1213
  });
1267
1214
  (0, import_invariant4.invariant)(!this.connection, "Already connected.", {
1268
- F: __dxlog_file4,
1215
+ F: __dxlog_file3,
1269
1216
  L: 255,
1270
1217
  S: this,
1271
1218
  A: [
@@ -1294,34 +1241,34 @@ var Peer = class {
1294
1241
  this._lastConnectionTime = Date.now();
1295
1242
  this._callbacks.onConnected();
1296
1243
  this._connectionLimiter.doneConnecting(sessionId);
1297
- import_log5.log.trace("dxos.mesh.connection.connected", {
1244
+ import_log4.log.trace("dxos.mesh.connection.connected", {
1298
1245
  topic: this.topic,
1299
1246
  localPeerId: this.localInfo,
1300
1247
  remotePeerId: this.remoteInfo,
1301
1248
  sessionId,
1302
1249
  initiator
1303
1250
  }, {
1304
- F: __dxlog_file4,
1251
+ F: __dxlog_file3,
1305
1252
  L: 279,
1306
1253
  S: this,
1307
1254
  C: (f, a) => f(...a)
1308
1255
  });
1309
1256
  },
1310
1257
  onClosed: (err) => {
1311
- (0, import_log5.log)("connection closed", {
1258
+ (0, import_log4.log)("connection closed", {
1312
1259
  topic: this.topic,
1313
1260
  peerId: this.localInfo,
1314
1261
  remoteId: this.remoteInfo,
1315
1262
  initiator
1316
1263
  }, {
1317
- F: __dxlog_file4,
1264
+ F: __dxlog_file3,
1318
1265
  L: 288,
1319
1266
  S: this,
1320
1267
  C: (f, a) => f(...a)
1321
1268
  });
1322
1269
  this._connectionLimiter.doneConnecting(sessionId);
1323
1270
  (0, import_invariant4.invariant)(this.connection === connection, "Connection mismatch (race condition).", {
1324
- F: __dxlog_file4,
1271
+ F: __dxlog_file3,
1325
1272
  L: 293,
1326
1273
  S: this,
1327
1274
  A: [
@@ -1329,14 +1276,14 @@ var Peer = class {
1329
1276
  "'Connection mismatch (race condition).'"
1330
1277
  ]
1331
1278
  });
1332
- import_log5.log.trace("dxos.mesh.connection.closed", {
1279
+ import_log4.log.trace("dxos.mesh.connection.closed", {
1333
1280
  topic: this.topic,
1334
1281
  localPeerId: this.localInfo,
1335
1282
  remotePeerId: this.remoteInfo,
1336
1283
  sessionId,
1337
1284
  initiator
1338
1285
  }, {
1339
- F: __dxlog_file4,
1286
+ F: __dxlog_file3,
1340
1287
  L: 295,
1341
1288
  S: this,
1342
1289
  C: (f, a) => f(...a)
@@ -1351,7 +1298,7 @@ var Peer = class {
1351
1298
  this._availableAfter = increaseInterval(this._availableAfter);
1352
1299
  }
1353
1300
  this._callbacks.onDisconnected();
1354
- (0, import_async4.scheduleTask)(this._connectionCtx, () => {
1301
+ (0, import_async3.scheduleTask)(this._connectionCtx, () => {
1355
1302
  this.availableToConnect = true;
1356
1303
  this._callbacks.onPeerAvailable();
1357
1304
  }, this._availableAfter);
@@ -1364,19 +1311,19 @@ var Peer = class {
1364
1311
  void this._connectionCtx?.dispose();
1365
1312
  this._connectionCtx = this._ctx.derive();
1366
1313
  connection.errors.handle((err) => {
1367
- import_log5.log.info("connection error, closing", {
1314
+ import_log4.log.info("connection error, closing", {
1368
1315
  topic: this.topic,
1369
1316
  peerId: this.localInfo,
1370
1317
  remoteId: this.remoteInfo,
1371
1318
  initiator,
1372
1319
  err
1373
1320
  }, {
1374
- F: __dxlog_file4,
1321
+ F: __dxlog_file3,
1375
1322
  L: 335,
1376
1323
  S: this,
1377
1324
  C: (f, a) => f(...a)
1378
1325
  });
1379
- import_log5.log.trace("dxos.mesh.connection.error", {
1326
+ import_log4.log.trace("dxos.mesh.connection.error", {
1380
1327
  topic: this.topic,
1381
1328
  localPeerId: this.localInfo,
1382
1329
  remotePeerId: this.remoteInfo,
@@ -1384,7 +1331,7 @@ var Peer = class {
1384
1331
  initiator,
1385
1332
  err
1386
1333
  }, {
1387
- F: __dxlog_file4,
1334
+ F: __dxlog_file3,
1388
1335
  L: 342,
1389
1336
  S: this,
1390
1337
  C: (f, a) => f(...a)
@@ -1399,21 +1346,21 @@ var Peer = class {
1399
1346
  return;
1400
1347
  }
1401
1348
  const connection = this.connection;
1402
- (0, import_log5.log)("closing...", {
1349
+ (0, import_log4.log)("closing...", {
1403
1350
  peerId: this.remoteInfo,
1404
1351
  sessionId: connection.sessionId
1405
1352
  }, {
1406
- F: __dxlog_file4,
1353
+ F: __dxlog_file3,
1407
1354
  L: 367,
1408
1355
  S: this,
1409
1356
  C: (f, a) => f(...a)
1410
1357
  });
1411
1358
  await connection.close(err);
1412
- (0, import_log5.log)("closed", {
1359
+ (0, import_log4.log)("closed", {
1413
1360
  peerId: this.remoteInfo,
1414
1361
  sessionId: connection.sessionId
1415
1362
  }, {
1416
- F: __dxlog_file4,
1363
+ F: __dxlog_file3,
1417
1364
  L: 373,
1418
1365
  S: this,
1419
1366
  C: (f, a) => f(...a)
@@ -1421,10 +1368,10 @@ var Peer = class {
1421
1368
  }
1422
1369
  async onSignal(message) {
1423
1370
  if (!this.connection) {
1424
- (0, import_log5.log)("dropping signal message for non-existent connection", {
1371
+ (0, import_log4.log)("dropping signal message for non-existent connection", {
1425
1372
  message
1426
1373
  }, {
1427
- F: __dxlog_file4,
1374
+ F: __dxlog_file3,
1428
1375
  L: 378,
1429
1376
  S: this,
1430
1377
  C: (f, a) => f(...a)
@@ -1435,11 +1382,11 @@ var Peer = class {
1435
1382
  }
1436
1383
  async safeDestroy(reason) {
1437
1384
  await this._ctx.dispose();
1438
- (0, import_log5.log)("Destroying peer", {
1385
+ (0, import_log4.log)("Destroying peer", {
1439
1386
  peerId: this.remoteInfo,
1440
1387
  topic: this.topic
1441
1388
  }, {
1442
- F: __dxlog_file4,
1389
+ F: __dxlog_file3,
1443
1390
  L: 388,
1444
1391
  S: this,
1445
1392
  C: (f, a) => f(...a)
@@ -1448,7 +1395,7 @@ var Peer = class {
1448
1395
  }
1449
1396
  };
1450
1397
  _ts_decorate2([
1451
- import_async4.synchronized
1398
+ import_async3.synchronized
1452
1399
  ], Peer.prototype, "safeDestroy", null);
1453
1400
  var increaseInterval = (interval) => {
1454
1401
  if (interval === 0) {
@@ -1468,7 +1415,7 @@ function _ts_decorate3(decorators, target, key, desc) {
1468
1415
  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;
1469
1416
  return c > 3 && r && Object.defineProperty(target, key, r), r;
1470
1417
  }
1471
- var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm.ts";
1418
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm.ts";
1472
1419
  var INITIATION_DELAY = 100;
1473
1420
  var getClassName = (obj) => Object.getPrototypeOf(obj).constructor.name;
1474
1421
  var Swarm = class {
@@ -1485,32 +1432,32 @@ var Swarm = class {
1485
1432
  this._connectionLimiter = _connectionLimiter;
1486
1433
  this._initiationDelay = _initiationDelay;
1487
1434
  this._ctx = new import_context3.Context(void 0, {
1488
- F: __dxlog_file5,
1435
+ F: __dxlog_file4,
1489
1436
  L: 38
1490
1437
  });
1491
1438
  this._listeningHandle = void 0;
1492
- this._peers = new import_util3.ComplexMap(import_messaging.PeerInfoHash);
1439
+ this._peers = new import_util2.ComplexMap(import_messaging.PeerInfoHash);
1493
1440
  this._instanceId = import_keys3.PublicKey.random().toHex();
1494
- this.connectionAdded = new import_async3.Event();
1495
- this.disconnected = new import_async3.Event();
1496
- this.connected = new import_async3.Event();
1441
+ this.connectionAdded = new import_async2.Event();
1442
+ this.disconnected = new import_async2.Event();
1443
+ this.connected = new import_async2.Event();
1497
1444
  this.errors = new import_debug2.ErrorStream();
1498
- import_log4.log.trace("dxos.mesh.swarm.constructor", import_protocols3.trace.begin({
1445
+ import_log3.log.trace("dxos.mesh.swarm.constructor", import_protocols3.trace.begin({
1499
1446
  id: this._instanceId,
1500
1447
  data: {
1501
1448
  topic: this._topic.toHex(),
1502
1449
  peer: this._ownPeer
1503
1450
  }
1504
1451
  }), {
1505
- F: __dxlog_file5,
1452
+ F: __dxlog_file4,
1506
1453
  L: 88,
1507
1454
  S: this,
1508
1455
  C: (f, a) => f(...a)
1509
1456
  });
1510
- (0, import_log4.log)("creating swarm", {
1457
+ (0, import_log3.log)("creating swarm", {
1511
1458
  peerId: _ownPeer
1512
1459
  }, {
1513
- F: __dxlog_file5,
1460
+ F: __dxlog_file4,
1514
1461
  L: 92,
1515
1462
  S: this,
1516
1463
  C: (f, a) => f(...a)
@@ -1522,17 +1469,17 @@ var Swarm = class {
1522
1469
  onOffer: async (msg) => await this.onOffer(msg),
1523
1470
  topic: this._topic
1524
1471
  });
1525
- import_log4.log.trace("dxos.mesh.swarm.constructor", import_protocols3.trace.end({
1472
+ import_log3.log.trace("dxos.mesh.swarm.constructor", import_protocols3.trace.end({
1526
1473
  id: this._instanceId
1527
1474
  }), {
1528
- F: __dxlog_file5,
1475
+ F: __dxlog_file4,
1529
1476
  L: 101,
1530
1477
  S: this,
1531
1478
  C: (f, a) => f(...a)
1532
1479
  });
1533
1480
  }
1534
1481
  get connections() {
1535
- return Array.from(this._peers.values()).map((peer) => peer.connection).filter(import_util3.isNotNullOrUndefined);
1482
+ return Array.from(this._peers.values()).map((peer) => peer.connection).filter(import_util2.isNotNullOrUndefined);
1536
1483
  }
1537
1484
  get ownPeerId() {
1538
1485
  return import_keys3.PublicKey.from(this._ownPeer.peerKey);
@@ -1551,7 +1498,7 @@ var Swarm = class {
1551
1498
  }
1552
1499
  async open() {
1553
1500
  (0, import_invariant3.invariant)(!this._listeningHandle, void 0, {
1554
- F: __dxlog_file5,
1501
+ F: __dxlog_file4,
1555
1502
  L: 132,
1556
1503
  S: this,
1557
1504
  A: [
@@ -1563,10 +1510,10 @@ var Swarm = class {
1563
1510
  peer: this._ownPeer,
1564
1511
  payloadType: "dxos.mesh.swarm.SwarmMessage",
1565
1512
  onMessage: async (message) => {
1566
- await this._swarmMessenger.receiveMessage(message).catch((err) => import_log4.log.info("Error while receiving message", {
1513
+ await this._swarmMessenger.receiveMessage(message).catch((err) => import_log3.log.info("Error while receiving message", {
1567
1514
  err
1568
1515
  }, {
1569
- F: __dxlog_file5,
1516
+ F: __dxlog_file4,
1570
1517
  L: 140,
1571
1518
  S: this,
1572
1519
  C: (f, a) => f(...a)
@@ -1575,8 +1522,8 @@ var Swarm = class {
1575
1522
  });
1576
1523
  }
1577
1524
  async destroy() {
1578
- (0, import_log4.log)("destroying...", void 0, {
1579
- F: __dxlog_file5,
1525
+ (0, import_log3.log)("destroying...", void 0, {
1526
+ F: __dxlog_file4,
1580
1527
  L: 146,
1581
1528
  S: this,
1582
1529
  C: (f, a) => f(...a)
@@ -1586,8 +1533,8 @@ var Swarm = class {
1586
1533
  await this._ctx.dispose();
1587
1534
  await this._topology.destroy();
1588
1535
  await Promise.all(Array.from(this._peers.keys()).map((key) => this._destroyPeer(key, "swarm destroyed")));
1589
- (0, import_log4.log)("destroyed", void 0, {
1590
- F: __dxlog_file5,
1536
+ (0, import_log3.log)("destroyed", void 0, {
1537
+ F: __dxlog_file4,
1591
1538
  L: 153,
1592
1539
  S: this,
1593
1540
  C: (f, a) => f(...a)
@@ -1595,7 +1542,7 @@ var Swarm = class {
1595
1542
  }
1596
1543
  async setTopology(topology) {
1597
1544
  (0, import_invariant3.invariant)(!this._ctx.disposed, "Swarm is offline", {
1598
- F: __dxlog_file5,
1545
+ F: __dxlog_file4,
1599
1546
  L: 157,
1600
1547
  S: this,
1601
1548
  A: [
@@ -1606,11 +1553,11 @@ var Swarm = class {
1606
1553
  if (topology === this._topology) {
1607
1554
  return;
1608
1555
  }
1609
- (0, import_log4.log)("setting topology", {
1556
+ (0, import_log3.log)("setting topology", {
1610
1557
  previous: getClassName(this._topology),
1611
1558
  topology: getClassName(topology)
1612
1559
  }, {
1613
- F: __dxlog_file5,
1560
+ F: __dxlog_file4,
1614
1561
  L: 161,
1615
1562
  S: this,
1616
1563
  C: (f, a) => f(...a)
@@ -1621,17 +1568,17 @@ var Swarm = class {
1621
1568
  this._topology.update();
1622
1569
  }
1623
1570
  onSwarmEvent(swarmEvent) {
1624
- (0, import_log4.log)("swarm event", {
1571
+ (0, import_log3.log)("swarm event", {
1625
1572
  swarmEvent
1626
1573
  }, {
1627
- F: __dxlog_file5,
1574
+ F: __dxlog_file4,
1628
1575
  L: 174,
1629
1576
  S: this,
1630
1577
  C: (f, a) => f(...a)
1631
1578
  });
1632
1579
  if (this._ctx.disposed) {
1633
- (0, import_log4.log)("swarm event ignored for disposed swarm", void 0, {
1634
- F: __dxlog_file5,
1580
+ (0, import_log3.log)("swarm event ignored for disposed swarm", void 0, {
1581
+ F: __dxlog_file4,
1635
1582
  L: 177,
1636
1583
  S: this,
1637
1584
  C: (f, a) => f(...a)
@@ -1641,10 +1588,10 @@ var Swarm = class {
1641
1588
  if (swarmEvent.peerAvailable) {
1642
1589
  const peerId = swarmEvent.peerAvailable.peer.peerKey;
1643
1590
  if (peerId !== this._ownPeer.peerKey) {
1644
- (0, import_log4.log)("new peer", {
1591
+ (0, import_log3.log)("new peer", {
1645
1592
  peerId
1646
1593
  }, {
1647
- F: __dxlog_file5,
1594
+ F: __dxlog_file4,
1648
1595
  L: 184,
1649
1596
  S: this,
1650
1597
  C: (f, a) => f(...a)
@@ -1657,18 +1604,18 @@ var Swarm = class {
1657
1604
  if (peer) {
1658
1605
  peer.advertizing = false;
1659
1606
  if (peer.connection?.state !== ConnectionState.CONNECTED) {
1660
- void this._destroyPeer(swarmEvent.peerLeft.peer, "peer left").catch((err) => import_log4.log.catch(err, void 0, {
1661
- F: __dxlog_file5,
1607
+ void this._destroyPeer(swarmEvent.peerLeft.peer, "peer left").catch((err) => import_log3.log.catch(err, void 0, {
1608
+ F: __dxlog_file4,
1662
1609
  L: 194,
1663
1610
  S: this,
1664
1611
  C: (f, a) => f(...a)
1665
1612
  }));
1666
1613
  }
1667
1614
  } else {
1668
- (0, import_log4.log)("received peerLeft but no peer found", {
1615
+ (0, import_log3.log)("received peerLeft but no peer found", {
1669
1616
  peer: swarmEvent.peerLeft.peer.peerKey
1670
1617
  }, {
1671
- F: __dxlog_file5,
1618
+ F: __dxlog_file4,
1672
1619
  L: 197,
1673
1620
  S: this,
1674
1621
  C: (f, a) => f(...a)
@@ -1678,17 +1625,17 @@ var Swarm = class {
1678
1625
  this._topology.update();
1679
1626
  }
1680
1627
  async onOffer(message) {
1681
- (0, import_log4.log)("offer", {
1628
+ (0, import_log3.log)("offer", {
1682
1629
  message
1683
1630
  }, {
1684
- F: __dxlog_file5,
1631
+ F: __dxlog_file4,
1685
1632
  L: 206,
1686
1633
  S: this,
1687
1634
  C: (f, a) => f(...a)
1688
1635
  });
1689
1636
  if (this._ctx.disposed) {
1690
- (0, import_log4.log)("ignored for disposed swarm", void 0, {
1691
- F: __dxlog_file5,
1637
+ (0, import_log3.log)("ignored for disposed swarm", void 0, {
1638
+ F: __dxlog_file4,
1692
1639
  L: 208,
1693
1640
  S: this,
1694
1641
  C: (f, a) => f(...a)
@@ -1698,7 +1645,7 @@ var Swarm = class {
1698
1645
  };
1699
1646
  }
1700
1647
  (0, import_invariant3.invariant)(message.author, void 0, {
1701
- F: __dxlog_file5,
1648
+ F: __dxlog_file4,
1702
1649
  L: 213,
1703
1650
  S: this,
1704
1651
  A: [
@@ -1707,10 +1654,10 @@ var Swarm = class {
1707
1654
  ]
1708
1655
  });
1709
1656
  if (message.recipient.peerKey !== this._ownPeer.peerKey) {
1710
- (0, import_log4.log)("rejecting offer with incorrect peerId", {
1657
+ (0, import_log3.log)("rejecting offer with incorrect peerId", {
1711
1658
  message
1712
1659
  }, {
1713
- F: __dxlog_file5,
1660
+ F: __dxlog_file4,
1714
1661
  L: 215,
1715
1662
  S: this,
1716
1663
  C: (f, a) => f(...a)
@@ -1720,10 +1667,10 @@ var Swarm = class {
1720
1667
  };
1721
1668
  }
1722
1669
  if (!message.topic?.equals(this._topic)) {
1723
- (0, import_log4.log)("rejecting offer with incorrect topic", {
1670
+ (0, import_log3.log)("rejecting offer with incorrect topic", {
1724
1671
  message
1725
1672
  }, {
1726
- F: __dxlog_file5,
1673
+ F: __dxlog_file4,
1727
1674
  L: 219,
1728
1675
  S: this,
1729
1676
  C: (f, a) => f(...a)
@@ -1738,17 +1685,17 @@ var Swarm = class {
1738
1685
  return answer;
1739
1686
  }
1740
1687
  async onSignal(message) {
1741
- (0, import_log4.log)("signal", {
1688
+ (0, import_log3.log)("signal", {
1742
1689
  message
1743
1690
  }, {
1744
- F: __dxlog_file5,
1691
+ F: __dxlog_file4,
1745
1692
  L: 230,
1746
1693
  S: this,
1747
1694
  C: (f, a) => f(...a)
1748
1695
  });
1749
1696
  if (this._ctx.disposed) {
1750
- import_log4.log.info("ignored for offline swarm", void 0, {
1751
- F: __dxlog_file5,
1697
+ import_log3.log.info("ignored for offline swarm", void 0, {
1698
+ F: __dxlog_file4,
1752
1699
  L: 232,
1753
1700
  S: this,
1754
1701
  C: (f, a) => f(...a)
@@ -1756,7 +1703,7 @@ var Swarm = class {
1756
1703
  return;
1757
1704
  }
1758
1705
  (0, import_invariant3.invariant)(message.recipient.peerKey === this._ownPeer.peerKey, `Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`, {
1759
- F: __dxlog_file5,
1706
+ F: __dxlog_file4,
1760
1707
  L: 235,
1761
1708
  S: this,
1762
1709
  A: [
@@ -1765,7 +1712,7 @@ var Swarm = class {
1765
1712
  ]
1766
1713
  });
1767
1714
  (0, import_invariant3.invariant)(message.topic?.equals(this._topic), void 0, {
1768
- F: __dxlog_file5,
1715
+ F: __dxlog_file4,
1769
1716
  L: 239,
1770
1717
  S: this,
1771
1718
  A: [
@@ -1774,7 +1721,7 @@ var Swarm = class {
1774
1721
  ]
1775
1722
  });
1776
1723
  (0, import_invariant3.invariant)(message.author, void 0, {
1777
- F: __dxlog_file5,
1724
+ F: __dxlog_file4,
1778
1725
  L: 240,
1779
1726
  S: this,
1780
1727
  A: [
@@ -1795,13 +1742,13 @@ var Swarm = class {
1795
1742
  // For debug purposes
1796
1743
  async goOnline() {
1797
1744
  this._ctx = new import_context3.Context(void 0, {
1798
- F: __dxlog_file5,
1745
+ F: __dxlog_file4,
1799
1746
  L: 256
1800
1747
  });
1801
1748
  }
1802
1749
  _getOrCreatePeer(peerInfo) {
1803
1750
  (0, import_invariant3.invariant)(peerInfo.peerKey, "PeerInfo.peerKey is required", {
1804
- F: __dxlog_file5,
1751
+ F: __dxlog_file4,
1805
1752
  L: 260,
1806
1753
  S: this,
1807
1754
  A: [
@@ -1830,10 +1777,10 @@ var Swarm = class {
1830
1777
  },
1831
1778
  onRejected: () => {
1832
1779
  if (!this._isUnregistered(peer)) {
1833
- (0, import_log4.log)("peer rejected connection", {
1780
+ (0, import_log3.log)("peer rejected connection", {
1834
1781
  peerInfo
1835
1782
  }, {
1836
- F: __dxlog_file5,
1783
+ F: __dxlog_file4,
1837
1784
  L: 293,
1838
1785
  S: this,
1839
1786
  C: (f, a) => f(...a)
@@ -1858,7 +1805,7 @@ var Swarm = class {
1858
1805
  async _destroyPeer(peerInfo, reason) {
1859
1806
  const peer = this._peers.get(peerInfo);
1860
1807
  (0, import_invariant3.invariant)(peer, void 0, {
1861
- F: __dxlog_file5,
1808
+ F: __dxlog_file4,
1862
1809
  L: 316,
1863
1810
  S: this,
1864
1811
  A: [
@@ -1881,14 +1828,14 @@ var Swarm = class {
1881
1828
  if (this._ctx.disposed) {
1882
1829
  return;
1883
1830
  }
1884
- (0, import_async3.scheduleTask)(this._ctx, async () => {
1831
+ (0, import_async2.scheduleTask)(this._ctx, async () => {
1885
1832
  try {
1886
1833
  await this._initiateConnection({
1887
1834
  peerKey: peer.toHex()
1888
1835
  });
1889
1836
  } catch (err) {
1890
- (0, import_log4.log)("initiation error", err, {
1891
- F: __dxlog_file5,
1837
+ (0, import_log3.log)("initiation error", err, {
1838
+ F: __dxlog_file4,
1892
1839
  L: 343,
1893
1840
  S: this,
1894
1841
  C: (f, a) => f(...a)
@@ -1900,7 +1847,7 @@ var Swarm = class {
1900
1847
  if (this._ctx.disposed) {
1901
1848
  return;
1902
1849
  }
1903
- (0, import_async3.scheduleTask)(this._ctx, async () => {
1850
+ (0, import_async2.scheduleTask)(this._ctx, async () => {
1904
1851
  await this._closeConnection({
1905
1852
  peerKey: peer.toHex()
1906
1853
  });
@@ -1916,15 +1863,15 @@ var Swarm = class {
1916
1863
  const ctx = this._ctx;
1917
1864
  const peer = this._getOrCreatePeer(remotePeer);
1918
1865
  if (remotePeer.peerKey < this._ownPeer.peerKey) {
1919
- (0, import_log4.log)("initiation delay", {
1866
+ (0, import_log3.log)("initiation delay", {
1920
1867
  remotePeer
1921
1868
  }, {
1922
- F: __dxlog_file5,
1869
+ F: __dxlog_file4,
1923
1870
  L: 371,
1924
1871
  S: this,
1925
1872
  C: (f, a) => f(...a)
1926
1873
  });
1927
- await (0, import_async3.sleep)(this._initiationDelay);
1874
+ await (0, import_async2.sleep)(this._initiationDelay);
1928
1875
  }
1929
1876
  if (ctx.disposed) {
1930
1877
  return;
@@ -1935,20 +1882,20 @@ var Swarm = class {
1935
1882
  if (peer.connection) {
1936
1883
  return;
1937
1884
  }
1938
- (0, import_log4.log)("initiating connection...", {
1885
+ (0, import_log3.log)("initiating connection...", {
1939
1886
  remotePeer
1940
1887
  }, {
1941
- F: __dxlog_file5,
1888
+ F: __dxlog_file4,
1942
1889
  L: 387,
1943
1890
  S: this,
1944
1891
  C: (f, a) => f(...a)
1945
1892
  });
1946
1893
  await peer.initiateConnection();
1947
1894
  this._topology.update();
1948
- (0, import_log4.log)("initiated", {
1895
+ (0, import_log3.log)("initiated", {
1949
1896
  remotePeer
1950
1897
  }, {
1951
- F: __dxlog_file5,
1898
+ F: __dxlog_file4,
1952
1899
  L: 390,
1953
1900
  S: this,
1954
1901
  C: (f, a) => f(...a)
@@ -1966,37 +1913,37 @@ var Swarm = class {
1966
1913
  }
1967
1914
  };
1968
1915
  _ts_decorate3([
1969
- import_log4.logInfo
1916
+ import_log3.logInfo
1970
1917
  ], Swarm.prototype, "_instanceId", void 0);
1971
1918
  _ts_decorate3([
1972
- import_log4.logInfo
1919
+ import_log3.logInfo
1973
1920
  ], Swarm.prototype, "ownPeer", null);
1974
1921
  _ts_decorate3([
1975
- import_log4.logInfo
1922
+ import_log3.logInfo
1976
1923
  ], Swarm.prototype, "topic", null);
1977
1924
  _ts_decorate3([
1978
- import_async3.synchronized
1925
+ import_async2.synchronized
1979
1926
  ], Swarm.prototype, "onSwarmEvent", null);
1980
1927
  _ts_decorate3([
1981
- import_async3.synchronized
1928
+ import_async2.synchronized
1982
1929
  ], Swarm.prototype, "onOffer", null);
1983
1930
  _ts_decorate3([
1984
- import_async3.synchronized
1931
+ import_async2.synchronized
1985
1932
  ], Swarm.prototype, "goOffline", null);
1986
1933
  _ts_decorate3([
1987
- import_async3.synchronized
1934
+ import_async2.synchronized
1988
1935
  ], Swarm.prototype, "goOnline", null);
1989
- var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm-mapper.ts";
1936
+ var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm-mapper.ts";
1990
1937
  var SwarmMapper = class {
1991
1938
  get peers() {
1992
1939
  return Array.from(this._peers.values());
1993
1940
  }
1994
1941
  constructor(_swarm) {
1995
1942
  this._swarm = _swarm;
1996
- this._subscriptions = new import_async5.EventSubscriptions();
1997
- this._connectionSubscriptions = new import_util4.ComplexMap(import_messaging2.PeerInfoHash);
1998
- this._peers = new import_util4.ComplexMap(import_messaging2.PeerInfoHash);
1999
- this.mapUpdated = new import_async5.Event();
1943
+ this._subscriptions = new import_async4.EventSubscriptions();
1944
+ this._connectionSubscriptions = new import_util3.ComplexMap(import_messaging2.PeerInfoHash);
1945
+ this._peers = new import_util3.ComplexMap(import_messaging2.PeerInfoHash);
1946
+ this.mapUpdated = new import_async4.Event();
2000
1947
  this._subscriptions.add(_swarm.connectionAdded.on((connection) => {
2001
1948
  this._update();
2002
1949
  this._connectionSubscriptions.set(connection.remoteInfo, connection.stateChanged.on(() => {
@@ -2011,8 +1958,8 @@ var SwarmMapper = class {
2011
1958
  this._update();
2012
1959
  }
2013
1960
  _update() {
2014
- (0, import_log6.log)("updating swarm", void 0, {
2015
- F: __dxlog_file6,
1961
+ (0, import_log5.log)("updating swarm", void 0, {
1962
+ F: __dxlog_file5,
2016
1963
  L: 73,
2017
1964
  S: this,
2018
1965
  C: (f, a) => f(...a)
@@ -2032,11 +1979,11 @@ var SwarmMapper = class {
2032
1979
  ]
2033
1980
  });
2034
1981
  }
2035
- (0, import_log6.log)("graph changed", {
1982
+ (0, import_log5.log)("graph changed", {
2036
1983
  directConnections: this._swarm.connections.length,
2037
1984
  totalPeersInSwarm: this._peers.size
2038
1985
  }, {
2039
- F: __dxlog_file6,
1986
+ F: __dxlog_file5,
2040
1987
  L: 114,
2041
1988
  S: this,
2042
1989
  C: (f, a) => f(...a)
@@ -2049,16 +1996,16 @@ var SwarmMapper = class {
2049
1996
  this._subscriptions.clear();
2050
1997
  }
2051
1998
  };
2052
- var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/connection-limiter.ts";
1999
+ var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/connection-limiter.ts";
2053
2000
  var MAX_CONCURRENT_INITIATING_CONNECTIONS = 50;
2054
2001
  var ConnectionLimiter = class {
2055
2002
  constructor({ maxConcurrentInitConnections = MAX_CONCURRENT_INITIATING_CONNECTIONS } = {}) {
2056
2003
  this._ctx = new import_context5.Context(void 0, {
2057
- F: __dxlog_file7,
2004
+ F: __dxlog_file6,
2058
2005
  L: 23
2059
2006
  });
2060
- this._waitingPromises = new import_util5.ComplexMap(import_keys6.PublicKey.hash);
2061
- this.resolveWaitingPromises = new import_async6.DeferredTask(this._ctx, async () => {
2007
+ this._waitingPromises = new import_util4.ComplexMap(import_keys6.PublicKey.hash);
2008
+ this.resolveWaitingPromises = new import_async5.DeferredTask(this._ctx, async () => {
2062
2009
  Array.from(this._waitingPromises.values()).slice(0, this._maxConcurrentInitConnections).forEach(({ resolve }) => {
2063
2010
  resolve();
2064
2011
  });
@@ -2070,7 +2017,7 @@ var ConnectionLimiter = class {
2070
2017
  */
2071
2018
  async connecting(sessionId) {
2072
2019
  (0, import_invariant5.invariant)(!this._waitingPromises.has(sessionId), "Peer is already waiting for connection", {
2073
- F: __dxlog_file7,
2020
+ F: __dxlog_file6,
2074
2021
  L: 48,
2075
2022
  S: this,
2076
2023
  A: [
@@ -2078,10 +2025,10 @@ var ConnectionLimiter = class {
2078
2025
  "'Peer is already waiting for connection'"
2079
2026
  ]
2080
2027
  });
2081
- (0, import_log7.log)("waiting", {
2028
+ (0, import_log6.log)("waiting", {
2082
2029
  sessionId
2083
2030
  }, {
2084
- F: __dxlog_file7,
2031
+ F: __dxlog_file6,
2085
2032
  L: 49,
2086
2033
  S: this,
2087
2034
  C: (f, a) => f(...a)
@@ -2093,10 +2040,10 @@ var ConnectionLimiter = class {
2093
2040
  });
2094
2041
  this.resolveWaitingPromises.schedule();
2095
2042
  });
2096
- (0, import_log7.log)("allow", {
2043
+ (0, import_log6.log)("allow", {
2097
2044
  sessionId
2098
2045
  }, {
2099
- F: __dxlog_file7,
2046
+ F: __dxlog_file6,
2100
2047
  L: 57,
2101
2048
  S: this,
2102
2049
  C: (f, a) => f(...a)
@@ -2106,10 +2053,10 @@ var ConnectionLimiter = class {
2106
2053
  * Rejects promise returned by `connecting` method.
2107
2054
  */
2108
2055
  doneConnecting(sessionId) {
2109
- (0, import_log7.log)("done", {
2056
+ (0, import_log6.log)("done", {
2110
2057
  sessionId
2111
2058
  }, {
2112
- F: __dxlog_file7,
2059
+ F: __dxlog_file6,
2113
2060
  L: 64,
2114
2061
  S: this,
2115
2062
  C: (f, a) => f(...a)
@@ -2133,8 +2080,8 @@ var EventType;
2133
2080
  })(EventType || (EventType = {}));
2134
2081
  var ConnectionLog = class {
2135
2082
  constructor() {
2136
- this._swarms = new import_util6.ComplexMap(import_keys7.PublicKey.hash);
2137
- this.update = new import_async7.Event();
2083
+ this._swarms = new import_util5.ComplexMap(import_keys7.PublicKey.hash);
2084
+ this.update = new import_async6.Event();
2138
2085
  }
2139
2086
  getSwarmInfo(swarmId) {
2140
2087
  return this._swarms.get(swarmId) ?? (0, import_debug3.raise)(new Error(`Swarm not found: ${swarmId}`));
@@ -2211,16 +2158,16 @@ function _ts_decorate4(decorators, target, key, desc) {
2211
2158
  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;
2212
2159
  return c > 3 && r && Object.defineProperty(target, key, r), r;
2213
2160
  }
2214
- var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/network-manager.ts";
2161
+ var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/network-manager.ts";
2215
2162
  var SwarmNetworkManager = class {
2216
2163
  constructor({ transportFactory, signalManager, enableDevtoolsLogging, peerInfo }) {
2217
- this._swarms = new import_util7.ComplexMap(import_keys8.PublicKey.hash);
2218
- this._mappers = new import_util7.ComplexMap(import_keys8.PublicKey.hash);
2164
+ this._swarms = new import_util6.ComplexMap(import_keys8.PublicKey.hash);
2165
+ this._mappers = new import_util6.ComplexMap(import_keys8.PublicKey.hash);
2219
2166
  this._instanceId = import_keys8.PublicKey.random().toHex();
2220
2167
  this._peerInfo = void 0;
2221
2168
  this._connectionState = import_services.ConnectionState.ONLINE;
2222
- this.connectionStateChanged = new import_async8.Event();
2223
- this.topicsUpdated = new import_async8.Event();
2169
+ this.connectionStateChanged = new import_async7.Event();
2170
+ this.topicsUpdated = new import_async7.Event();
2224
2171
  this._transportFactory = transportFactory;
2225
2172
  this._signalManager = signalManager;
2226
2173
  this._signalManager.swarmEvent.on((event) => this._swarms.get(event.topic)?.onSwarmEvent(event));
@@ -2258,20 +2205,20 @@ var SwarmNetworkManager = class {
2258
2205
  this._peerInfo = peerInfo;
2259
2206
  }
2260
2207
  async open() {
2261
- import_log8.log.trace("dxos.mesh.network-manager.open", import_protocols6.trace.begin({
2208
+ import_log7.log.trace("dxos.mesh.network-manager.open", import_protocols6.trace.begin({
2262
2209
  id: this._instanceId
2263
2210
  }), {
2264
- F: __dxlog_file8,
2211
+ F: __dxlog_file7,
2265
2212
  L: 133,
2266
2213
  S: this,
2267
2214
  C: (f, a) => f(...a)
2268
2215
  });
2269
2216
  await this._messenger.open();
2270
2217
  await this._signalManager.open();
2271
- import_log8.log.trace("dxos.mesh.network-manager.open", import_protocols6.trace.end({
2218
+ import_log7.log.trace("dxos.mesh.network-manager.open", import_protocols6.trace.end({
2272
2219
  id: this._instanceId
2273
2220
  }), {
2274
- F: __dxlog_file8,
2221
+ F: __dxlog_file7,
2275
2222
  L: 136,
2276
2223
  S: this,
2277
2224
  C: (f, a) => f(...a)
@@ -2280,8 +2227,8 @@ var SwarmNetworkManager = class {
2280
2227
  async close() {
2281
2228
  for (const topic of this._swarms.keys()) {
2282
2229
  await this.leaveSwarm(topic).catch((err) => {
2283
- (0, import_log8.log)(err, void 0, {
2284
- F: __dxlog_file8,
2230
+ (0, import_log7.log)(err, void 0, {
2231
+ F: __dxlog_file7,
2285
2232
  L: 142,
2286
2233
  S: this,
2287
2234
  C: (f, a) => f(...a)
@@ -2294,52 +2241,37 @@ var SwarmNetworkManager = class {
2294
2241
  /**
2295
2242
  * Join the swarm.
2296
2243
  */
2297
- async joinSwarm({ topic, peerInfo, topology, protocolProvider: protocol, label }) {
2244
+ async joinSwarm({ topic, topology, protocolProvider: protocol, label }) {
2298
2245
  (0, import_invariant6.invariant)(import_keys8.PublicKey.isPublicKey(topic), void 0, {
2299
- F: __dxlog_file8,
2300
- L: 161,
2246
+ F: __dxlog_file7,
2247
+ L: 160,
2301
2248
  S: this,
2302
2249
  A: [
2303
2250
  "PublicKey.isPublicKey(topic)",
2304
2251
  ""
2305
2252
  ]
2306
2253
  });
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, {
2323
- F: __dxlog_file8,
2324
- L: 169,
2254
+ (0, import_invariant6.invariant)(topology, void 0, {
2255
+ F: __dxlog_file7,
2256
+ L: 161,
2325
2257
  S: this,
2326
2258
  A: [
2327
- "PublicKey.from(peerInfo.identityKey!)",
2259
+ "topology",
2328
2260
  ""
2329
2261
  ]
2330
2262
  });
2331
- (0, import_invariant6.invariant)(topology, void 0, {
2332
- F: __dxlog_file8,
2333
- L: 170,
2263
+ (0, import_invariant6.invariant)(this._peerInfo, void 0, {
2264
+ F: __dxlog_file7,
2265
+ L: 162,
2334
2266
  S: this,
2335
2267
  A: [
2336
- "topology",
2268
+ "this._peerInfo",
2337
2269
  ""
2338
2270
  ]
2339
2271
  });
2340
2272
  (0, import_invariant6.invariant)(typeof protocol === "function", void 0, {
2341
- F: __dxlog_file8,
2342
- L: 171,
2273
+ F: __dxlog_file7,
2274
+ L: 163,
2343
2275
  S: this,
2344
2276
  A: [
2345
2277
  "typeof protocol === 'function'",
@@ -2349,23 +2281,23 @@ var SwarmNetworkManager = class {
2349
2281
  if (this._swarms.has(topic)) {
2350
2282
  throw new Error(`Already connected to swarm: ${import_keys8.PublicKey.from(topic)}`);
2351
2283
  }
2352
- (0, import_log8.log)("joining", {
2284
+ (0, import_log7.log)("joining", {
2353
2285
  topic: import_keys8.PublicKey.from(topic),
2354
- peerInfo,
2286
+ peerInfo: this._peerInfo,
2355
2287
  topology: topology.toString()
2356
2288
  }, {
2357
- F: __dxlog_file8,
2358
- L: 176,
2289
+ F: __dxlog_file7,
2290
+ L: 168,
2359
2291
  S: this,
2360
2292
  C: (f, a) => f(...a)
2361
2293
  });
2362
- const swarm = new Swarm(topic, peerInfo, topology, protocol, this._messenger, this._transportFactory, label, this._connectionLimiter);
2294
+ const swarm = new Swarm(topic, this._peerInfo, topology, protocol, this._messenger, this._transportFactory, label, this._connectionLimiter);
2363
2295
  swarm.errors.handle((error) => {
2364
- (0, import_log8.log)("swarm error", {
2296
+ (0, import_log7.log)("swarm error", {
2365
2297
  error
2366
2298
  }, {
2367
- F: __dxlog_file8,
2368
- L: 189,
2299
+ F: __dxlog_file7,
2300
+ L: 181,
2369
2301
  S: this,
2370
2302
  C: (f, a) => f(...a)
2371
2303
  });
@@ -2375,21 +2307,21 @@ var SwarmNetworkManager = class {
2375
2307
  await swarm.open();
2376
2308
  this._signalConnection.join({
2377
2309
  topic,
2378
- peer: peerInfo
2379
- }).catch((error) => import_log8.log.catch(error, void 0, {
2380
- F: __dxlog_file8,
2381
- L: 198,
2310
+ peer: this._peerInfo
2311
+ }).catch((error) => import_log7.log.catch(error, void 0, {
2312
+ F: __dxlog_file7,
2313
+ L: 190,
2382
2314
  S: this,
2383
2315
  C: (f, a) => f(...a)
2384
2316
  }));
2385
2317
  this.topicsUpdated.emit();
2386
2318
  this._connectionLog?.joinedSwarm(swarm);
2387
- (0, import_log8.log)("joined", {
2319
+ (0, import_log7.log)("joined", {
2388
2320
  topic: import_keys8.PublicKey.from(topic),
2389
2321
  count: this._swarms.size
2390
2322
  }, {
2391
- F: __dxlog_file8,
2392
- L: 202,
2323
+ F: __dxlog_file7,
2324
+ L: 194,
2393
2325
  S: this,
2394
2326
  C: (f, a) => f(...a)
2395
2327
  });
@@ -2404,11 +2336,11 @@ var SwarmNetworkManager = class {
2404
2336
  if (!this._swarms.has(topic)) {
2405
2337
  return;
2406
2338
  }
2407
- (0, import_log8.log)("leaving", {
2339
+ (0, import_log7.log)("leaving", {
2408
2340
  topic: import_keys8.PublicKey.from(topic)
2409
2341
  }, {
2410
- F: __dxlog_file8,
2411
- L: 219,
2342
+ F: __dxlog_file7,
2343
+ L: 211,
2412
2344
  S: this,
2413
2345
  C: (f, a) => f(...a)
2414
2346
  });
@@ -2424,12 +2356,12 @@ var SwarmNetworkManager = class {
2424
2356
  await swarm.destroy();
2425
2357
  this._swarms.delete(topic);
2426
2358
  this.topicsUpdated.emit();
2427
- (0, import_log8.log)("left", {
2359
+ (0, import_log7.log)("left", {
2428
2360
  topic: import_keys8.PublicKey.from(topic),
2429
2361
  count: this._swarms.size
2430
2362
  }, {
2431
- F: __dxlog_file8,
2432
- L: 233,
2363
+ F: __dxlog_file7,
2364
+ L: 225,
2433
2365
  S: this,
2434
2366
  C: (f, a) => f(...a)
2435
2367
  });
@@ -2462,19 +2394,19 @@ var SwarmNetworkManager = class {
2462
2394
  }
2463
2395
  };
2464
2396
  _ts_decorate4([
2465
- import_async8.synchronized
2397
+ import_async7.synchronized
2466
2398
  ], SwarmNetworkManager.prototype, "joinSwarm", null);
2467
2399
  _ts_decorate4([
2468
- import_async8.synchronized
2400
+ import_async7.synchronized
2469
2401
  ], SwarmNetworkManager.prototype, "leaveSwarm", null);
2470
- var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/topology/fully-connected-topology.ts";
2402
+ var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/topology/fully-connected-topology.ts";
2471
2403
  var FullyConnectedTopology = class {
2472
2404
  toString() {
2473
2405
  return "FullyConnectedTopology";
2474
2406
  }
2475
2407
  init(controller) {
2476
2408
  (0, import_invariant7.invariant)(!this._controller, "Already initialized", {
2477
- F: __dxlog_file9,
2409
+ F: __dxlog_file8,
2478
2410
  L: 18,
2479
2411
  S: this,
2480
2412
  A: [
@@ -2486,7 +2418,7 @@ var FullyConnectedTopology = class {
2486
2418
  }
2487
2419
  update() {
2488
2420
  (0, import_invariant7.invariant)(this._controller, "Not initialized", {
2489
- F: __dxlog_file9,
2421
+ F: __dxlog_file8,
2490
2422
  L: 23,
2491
2423
  S: this,
2492
2424
  A: [
@@ -2505,307 +2437,13 @@ var FullyConnectedTopology = class {
2505
2437
  async destroy() {
2506
2438
  }
2507
2439
  };
2508
- var __dxlog_file10 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/topology/mmst-topology.ts";
2509
- var MIN_UPDATE_INTERVAL = 1e3 * 10;
2510
- var MAX_CHANGES_PER_UPDATE = 1;
2511
- var MMSTTopology = class {
2512
- constructor({ originateConnections = 2, maxPeers = 4, sampleSize = 10 } = {}) {
2513
- this._sampleCollected = false;
2514
- this._lastAction = /* @__PURE__ */ new Date(0);
2515
- this._originateConnections = originateConnections;
2516
- this._maxPeers = maxPeers;
2517
- this._sampleSize = sampleSize;
2518
- }
2519
- init(controller) {
2520
- (0, import_invariant8.invariant)(!this._controller, "Already initialized", {
2521
- F: __dxlog_file10,
2522
- L: 49,
2523
- S: this,
2524
- A: [
2525
- "!this._controller",
2526
- "'Already initialized'"
2527
- ]
2528
- });
2529
- this._controller = controller;
2530
- }
2531
- update() {
2532
- (0, import_invariant8.invariant)(this._controller, "Not initialized", {
2533
- F: __dxlog_file10,
2534
- L: 54,
2535
- S: this,
2536
- A: [
2537
- "this._controller",
2538
- "'Not initialized'"
2539
- ]
2540
- });
2541
- const { connected, candidates } = this._controller.getState();
2542
- if (this._sampleCollected || connected.length > this._maxPeers || candidates.length > 0) {
2543
- (0, import_log9.log)("Running the algorithm.", void 0, {
2544
- F: __dxlog_file10,
2545
- L: 58,
2546
- S: this,
2547
- C: (f, a) => f(...a)
2548
- });
2549
- this._sampleCollected = true;
2550
- this._runAlgorithm();
2551
- }
2552
- }
2553
- forceUpdate() {
2554
- this._lastAction = /* @__PURE__ */ new Date(0);
2555
- this.update();
2556
- }
2557
- async onOffer(peer) {
2558
- (0, import_invariant8.invariant)(this._controller, "Not initialized", {
2559
- F: __dxlog_file10,
2560
- L: 70,
2561
- S: this,
2562
- A: [
2563
- "this._controller",
2564
- "'Not initialized'"
2565
- ]
2566
- });
2567
- const { connected } = this._controller.getState();
2568
- const accept = connected.length < this._maxPeers;
2569
- (0, import_log9.log)(`Offer ${peer} accept=${accept}`, void 0, {
2570
- F: __dxlog_file10,
2571
- L: 73,
2572
- S: this,
2573
- C: (f, a) => f(...a)
2574
- });
2575
- return accept;
2576
- }
2577
- async destroy() {
2578
- }
2579
- _runAlgorithm() {
2580
- (0, import_invariant8.invariant)(this._controller, "Not initialized", {
2581
- F: __dxlog_file10,
2582
- L: 82,
2583
- S: this,
2584
- A: [
2585
- "this._controller",
2586
- "'Not initialized'"
2587
- ]
2588
- });
2589
- const { connected, candidates, ownPeerId } = this._controller.getState();
2590
- if (connected.length > this._maxPeers) {
2591
- (0, import_log9.log)(`disconnect ${connected.length - this._maxPeers} peers.`, void 0, {
2592
- F: __dxlog_file10,
2593
- L: 88,
2594
- S: this,
2595
- C: (f, a) => f(...a)
2596
- });
2597
- const sorted = sortByXorDistance(connected, ownPeerId).reverse().slice(0, this._maxPeers - connected.length);
2598
- (0, import_invariant8.invariant)(sorted.length === 0, void 0, {
2599
- F: __dxlog_file10,
2600
- L: 92,
2601
- S: this,
2602
- A: [
2603
- "sorted.length === 0",
2604
- ""
2605
- ]
2606
- });
2607
- if (sorted.length > MAX_CHANGES_PER_UPDATE) {
2608
- (0, import_log9.log)(`want to disconnect ${sorted.length} peers but limited to ${MAX_CHANGES_PER_UPDATE}`, void 0, {
2609
- F: __dxlog_file10,
2610
- L: 95,
2611
- S: this,
2612
- C: (f, a) => f(...a)
2613
- });
2614
- }
2615
- if (Date.now() - this._lastAction.getTime() > MIN_UPDATE_INTERVAL) {
2616
- for (const peer of sorted.slice(0, MAX_CHANGES_PER_UPDATE)) {
2617
- (0, import_log9.log)(`Disconnect ${peer}.`, void 0, {
2618
- F: __dxlog_file10,
2619
- L: 100,
2620
- S: this,
2621
- C: (f, a) => f(...a)
2622
- });
2623
- this._controller.disconnect(peer);
2624
- }
2625
- this._lastAction = /* @__PURE__ */ new Date();
2626
- } else {
2627
- (0, import_log9.log)("rate limited disconnect", void 0, {
2628
- F: __dxlog_file10,
2629
- L: 105,
2630
- S: this,
2631
- C: (f, a) => f(...a)
2632
- });
2633
- }
2634
- } else if (connected.length < this._originateConnections) {
2635
- (0, import_log9.log)(`connect ${this._originateConnections - connected.length} peers.`, void 0, {
2636
- F: __dxlog_file10,
2637
- L: 109,
2638
- S: this,
2639
- C: (f, a) => f(...a)
2640
- });
2641
- const sample = candidates.sort(() => Math.random() - 0.5).slice(0, this._sampleSize);
2642
- const sorted = sortByXorDistance(sample, ownPeerId).slice(0, this._originateConnections - connected.length);
2643
- if (sorted.length > MAX_CHANGES_PER_UPDATE) {
2644
- (0, import_log9.log)(`want to connect ${sorted.length} peers but limited to ${MAX_CHANGES_PER_UPDATE}`, void 0, {
2645
- F: __dxlog_file10,
2646
- L: 114,
2647
- S: this,
2648
- C: (f, a) => f(...a)
2649
- });
2650
- }
2651
- if (Date.now() - this._lastAction.getTime() > MIN_UPDATE_INTERVAL) {
2652
- for (const peer of sorted.slice(0, MAX_CHANGES_PER_UPDATE)) {
2653
- (0, import_log9.log)(`Connect ${peer}.`, void 0, {
2654
- F: __dxlog_file10,
2655
- L: 118,
2656
- S: this,
2657
- C: (f, a) => f(...a)
2658
- });
2659
- this._controller.connect(peer);
2660
- }
2661
- this._lastAction = /* @__PURE__ */ new Date();
2662
- } else {
2663
- (0, import_log9.log)("rate limited connect", void 0, {
2664
- F: __dxlog_file10,
2665
- L: 123,
2666
- S: this,
2667
- C: (f, a) => f(...a)
2668
- });
2669
- }
2670
- }
2671
- }
2672
- toString() {
2673
- return "MMSTTopology";
2674
- }
2675
- };
2676
- var sortByXorDistance = (keys, reference) => {
2677
- const sorted = keys.sort((a, b) => {
2678
- return compareXor(distXor(a.asBuffer(), reference.asBuffer()), distXor(b.asBuffer(), reference.asBuffer()));
2679
- });
2680
- (0, import_log9.log)("Sorted keys", {
2681
- keys,
2682
- reference,
2683
- sorted
2684
- }, {
2685
- F: __dxlog_file10,
2686
- L: 137,
2687
- S: void 0,
2688
- C: (f, a) => f(...a)
2689
- });
2690
- return sorted;
2691
- };
2692
- var distXor = (a, b) => {
2693
- const maxLength = Math.max(a.length, b.length);
2694
- const result = Buffer.allocUnsafe(maxLength);
2695
- for (let i = 0; i < maxLength; i++) {
2696
- result[i] = (a[i] || 0) ^ (b[i] || 0);
2697
- }
2698
- return result;
2699
- };
2700
- var compareXor = (a, b) => {
2701
- const maxLength = Math.max(a.length, b.length);
2702
- for (let i = 0; i < maxLength; i++) {
2703
- if ((a[i] || 0) === (b[i] || 0)) {
2704
- continue;
2705
- }
2706
- return (a[i] || 0) < (b[i] || 0) ? -1 : 1;
2707
- }
2708
- return 0;
2709
- };
2710
- var __dxlog_file11 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/topology/star-topology.ts";
2711
- var StarTopology = class {
2712
- constructor(_centralPeer) {
2713
- this._centralPeer = _centralPeer;
2714
- }
2715
- toString() {
2716
- return `StarTopology(${this._centralPeer.truncate()})`;
2717
- }
2718
- init(controller) {
2719
- (0, import_invariant9.invariant)(!this._controller, "Already initialized.", {
2720
- F: __dxlog_file11,
2721
- L: 21,
2722
- S: this,
2723
- A: [
2724
- "!this._controller",
2725
- "'Already initialized.'"
2726
- ]
2727
- });
2728
- this._controller = controller;
2729
- }
2730
- update() {
2731
- (0, import_invariant9.invariant)(this._controller, "Not initialized.", {
2732
- F: __dxlog_file11,
2733
- L: 26,
2734
- S: this,
2735
- A: [
2736
- "this._controller",
2737
- "'Not initialized.'"
2738
- ]
2739
- });
2740
- const { candidates, connected, ownPeerId } = this._controller.getState();
2741
- if (!ownPeerId.equals(this._centralPeer)) {
2742
- (0, import_log10.log)("leaf peer dropping all connections apart from central peer.", void 0, {
2743
- F: __dxlog_file11,
2744
- L: 29,
2745
- S: this,
2746
- C: (f, a) => f(...a)
2747
- });
2748
- for (const peer of connected) {
2749
- if (!peer.equals(this._centralPeer)) {
2750
- (0, import_log10.log)("dropping connection", {
2751
- peer
2752
- }, {
2753
- F: __dxlog_file11,
2754
- L: 34,
2755
- S: this,
2756
- C: (f, a) => f(...a)
2757
- });
2758
- this._controller.disconnect(peer);
2759
- }
2760
- }
2761
- }
2762
- for (const peer of candidates) {
2763
- if (peer.equals(this._centralPeer) || ownPeerId.equals(this._centralPeer)) {
2764
- (0, import_log10.log)("connecting to peer", {
2765
- peer
2766
- }, {
2767
- F: __dxlog_file11,
2768
- L: 43,
2769
- S: this,
2770
- C: (f, a) => f(...a)
2771
- });
2772
- this._controller.connect(peer);
2773
- }
2774
- }
2775
- }
2776
- async onOffer(peer) {
2777
- (0, import_invariant9.invariant)(this._controller, "Not initialized.", {
2778
- F: __dxlog_file11,
2779
- L: 50,
2780
- S: this,
2781
- A: [
2782
- "this._controller",
2783
- "'Not initialized.'"
2784
- ]
2785
- });
2786
- const { ownPeerId } = this._controller.getState();
2787
- (0, import_log10.log)("offer", {
2788
- peer,
2789
- isCentral: peer.equals(this._centralPeer),
2790
- isSelfCentral: ownPeerId.equals(this._centralPeer)
2791
- }, {
2792
- F: __dxlog_file11,
2793
- L: 52,
2794
- S: this,
2795
- C: (f, a) => f(...a)
2796
- });
2797
- return ownPeerId.equals(this._centralPeer) || peer.equals(this._centralPeer);
2798
- }
2799
- async destroy() {
2800
- }
2801
- };
2802
2440
  function _ts_decorate5(decorators, target, key, desc) {
2803
2441
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2804
2442
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2805
2443
  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;
2806
2444
  return c > 3 && r && Object.defineProperty(target, key, r), r;
2807
2445
  }
2808
- var __dxlog_file12 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/memory-transport.ts";
2446
+ var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/memory-transport.ts";
2809
2447
  var MEMORY_TRANSPORT_DELAY = 1;
2810
2448
  var createStreamDelay = (delay) => {
2811
2449
  return new import_node_stream.Transform({
@@ -2820,20 +2458,20 @@ var MemoryTransportFactory = {
2820
2458
  };
2821
2459
  var MemoryTransport = class _MemoryTransport {
2822
2460
  static {
2823
- this._connections = new import_util8.ComplexMap(import_keys9.PublicKey.hash);
2461
+ this._connections = new import_util7.ComplexMap(import_keys9.PublicKey.hash);
2824
2462
  }
2825
2463
  constructor(_options) {
2826
2464
  this._options = _options;
2827
2465
  this._instanceId = import_keys9.PublicKey.random();
2828
- this._remote = new import_async9.Trigger();
2466
+ this._remote = new import_async8.Trigger();
2829
2467
  this._outgoingDelay = createStreamDelay(MEMORY_TRANSPORT_DELAY);
2830
2468
  this._incomingDelay = createStreamDelay(MEMORY_TRANSPORT_DELAY);
2831
2469
  this._closed = false;
2832
- this.closed = new import_async9.Event();
2833
- this.connected = new import_async9.Event();
2470
+ this.closed = new import_async8.Event();
2471
+ this.connected = new import_async8.Event();
2834
2472
  this.errors = new import_debug4.ErrorStream();
2835
- (0, import_invariant10.invariant)(!_MemoryTransport._connections.has(this._instanceId), "Duplicate memory connection", {
2836
- F: __dxlog_file12,
2473
+ (0, import_invariant8.invariant)(!_MemoryTransport._connections.has(this._instanceId), "Duplicate memory connection", {
2474
+ F: __dxlog_file9,
2837
2475
  L: 64,
2838
2476
  S: this,
2839
2477
  A: [
@@ -2847,15 +2485,15 @@ var MemoryTransport = class _MemoryTransport {
2847
2485
  return !this._closed;
2848
2486
  }
2849
2487
  async open() {
2850
- (0, import_log11.log)("opening...", void 0, {
2851
- F: __dxlog_file12,
2488
+ (0, import_log8.log)("opening...", void 0, {
2489
+ F: __dxlog_file9,
2852
2490
  L: 74,
2853
2491
  S: this,
2854
2492
  C: (f, a) => f(...a)
2855
2493
  });
2856
2494
  if (this._options.initiator) {
2857
- (0, import_log11.log)("sending signal", void 0, {
2858
- F: __dxlog_file12,
2495
+ (0, import_log8.log)("sending signal", void 0, {
2496
+ F: __dxlog_file9,
2859
2497
  L: 78,
2860
2498
  S: this,
2861
2499
  C: (f, a) => f(...a)
@@ -2885,8 +2523,8 @@ var MemoryTransport = class _MemoryTransport {
2885
2523
  this.closed.emit();
2886
2524
  return;
2887
2525
  }
2888
- (0, import_invariant10.invariant)(!this._remoteConnection._remoteConnection, `Remote already connected: ${this._remoteInstanceId}`, {
2889
- F: __dxlog_file12,
2526
+ (0, import_invariant8.invariant)(!this._remoteConnection._remoteConnection, `Remote already connected: ${this._remoteInstanceId}`, {
2527
+ F: __dxlog_file9,
2890
2528
  L: 104,
2891
2529
  S: this,
2892
2530
  A: [
@@ -2896,8 +2534,8 @@ var MemoryTransport = class _MemoryTransport {
2896
2534
  });
2897
2535
  this._remoteConnection._remoteConnection = this;
2898
2536
  this._remoteConnection._remoteInstanceId = this._instanceId;
2899
- (0, import_log11.log)("connected", void 0, {
2900
- F: __dxlog_file12,
2537
+ (0, import_log8.log)("connected", void 0, {
2538
+ F: __dxlog_file9,
2901
2539
  L: 108,
2902
2540
  S: this,
2903
2541
  C: (f, a) => f(...a)
@@ -2912,11 +2550,12 @@ var MemoryTransport = class _MemoryTransport {
2912
2550
  this.errors.raise(err);
2913
2551
  });
2914
2552
  }
2553
+ return this;
2915
2554
  }
2916
2555
  async close() {
2917
- (0, import_log11.log)("closing...", void 0, {
2918
- F: __dxlog_file12,
2919
- L: 129,
2556
+ (0, import_log8.log)("closing...", void 0, {
2557
+ F: __dxlog_file9,
2558
+ L: 130,
2920
2559
  S: this,
2921
2560
  C: (f, a) => f(...a)
2922
2561
  });
@@ -2935,19 +2574,20 @@ var MemoryTransport = class _MemoryTransport {
2935
2574
  this._remoteConnection = void 0;
2936
2575
  }
2937
2576
  this.closed.emit();
2938
- (0, import_log11.log)("closed", void 0, {
2939
- F: __dxlog_file12,
2940
- L: 157,
2577
+ (0, import_log8.log)("closed", void 0, {
2578
+ F: __dxlog_file9,
2579
+ L: 158,
2941
2580
  S: this,
2942
2581
  C: (f, a) => f(...a)
2943
2582
  });
2583
+ return this;
2944
2584
  }
2945
2585
  async onSignal({ payload }) {
2946
- (0, import_log11.log)("received signal", {
2586
+ (0, import_log8.log)("received signal", {
2947
2587
  payload
2948
2588
  }, {
2949
- F: __dxlog_file12,
2950
- L: 161,
2589
+ F: __dxlog_file9,
2590
+ L: 163,
2951
2591
  S: this,
2952
2592
  C: (f, a) => f(...a)
2953
2593
  });
@@ -2973,1286 +2613,1376 @@ var MemoryTransport = class _MemoryTransport {
2973
2613
  }
2974
2614
  };
2975
2615
  _ts_decorate5([
2976
- import_log11.logInfo
2616
+ import_log8.logInfo
2977
2617
  ], MemoryTransport.prototype, "_instanceId", void 0);
2978
2618
  _ts_decorate5([
2979
- import_log11.logInfo
2619
+ import_log8.logInfo
2980
2620
  ], MemoryTransport.prototype, "_remoteInstanceId", void 0);
2981
2621
  var toError = (err) => err instanceof Error ? err : new Error(String(err));
2982
2622
  var TransportKind;
2983
2623
  (function(TransportKind2) {
2984
- TransportKind2["SIMPLE_PEER"] = "SIMPLE_PEER";
2985
- TransportKind2["SIMPLE_PEER_PROXY"] = "SIMPLE_PEER_PROXY";
2986
- TransportKind2["LIBDATACHANNEL"] = "LIBDATACHANNEL";
2624
+ TransportKind2["WEB_RTC"] = "WEB-RTC";
2625
+ TransportKind2["WEB_RTC_PROXY"] = "WEB-RTC_PROXY";
2987
2626
  TransportKind2["MEMORY"] = "MEMORY";
2988
2627
  TransportKind2["TCP"] = "TCP";
2989
2628
  })(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;
2629
+ var BrowserRtcConnectionFactory = class {
2630
+ async initialize() {
3012
2631
  }
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();
2632
+ async onConnectionDestroyed() {
3025
2633
  }
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
- };
2634
+ async createConnection(config) {
2635
+ return new RTCPeerConnection(config);
3044
2636
  }
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];
2637
+ async initConnection(connection, info) {
2638
+ }
2639
+ };
2640
+ var NodeRtcConnectionFactory = class _NodeRtcConnectionFactory {
2641
+ static {
2642
+ this._createdConnections = 0;
2643
+ }
2644
+ static {
2645
+ this._cleanupMutex = new import_async9.Mutex();
2646
+ }
2647
+ // This should be inside the function to avoid triggering `eval` in the global scope.
2648
+ // eslint-disable-next-line no-new-func
2649
+ // TODO(burdon): Do imports here?
2650
+ async initialize() {
2651
+ }
2652
+ async onConnectionDestroyed() {
2653
+ return _NodeRtcConnectionFactory._cleanupMutex.executeSynchronized(async () => {
2654
+ if (--_NodeRtcConnectionFactory._createdConnections === 0) {
2655
+ (await import("#node-datachannel")).cleanup();
3058
2656
  }
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
2657
  });
3067
2658
  }
3068
- async getDetails() {
3069
- const stats = await this._getStats();
3070
- const rc = stats?.remoteCandidate;
3071
- if (!rc) {
3072
- return "unavailable";
3073
- }
3074
- if (rc.candidateType === "relay") {
3075
- return `${rc.ip}:${rc.port}/${rc.protocol} relay for ${rc.relatedAddress}:${rc.relatedPort}`;
2659
+ async createConnection(config) {
2660
+ return _NodeRtcConnectionFactory._cleanupMutex.executeSynchronized(async () => {
2661
+ const { RTCPeerConnection: RTCPeerConnection1 } = await import("#node-datachannel/polyfill");
2662
+ _NodeRtcConnectionFactory._createdConnections++;
2663
+ return new RTCPeerConnection1(config);
2664
+ });
2665
+ }
2666
+ async initConnection(connection, info) {
2667
+ if (info.initiator) {
2668
+ connection.onnegotiationneeded?.(null);
3076
2669
  }
3077
- return `${rc.ip}:${rc.port}/${rc.protocol} ${rc.candidateType}`;
3078
2670
  }
3079
- async open() {
3080
- import_log12.log.trace("dxos.mesh.webrtc-transport.open", import_protocols7.trace.begin({
3081
- id: this._instanceId
3082
- }), {
3083
- F: __dxlog_file13,
3084
- L: 122,
2671
+ };
2672
+ var getRtcConnectionFactory = () => {
2673
+ return typeof globalThis.RTCPeerConnection === "undefined" ? new NodeRtcConnectionFactory() : new BrowserRtcConnectionFactory();
2674
+ };
2675
+ var describeSelectedRemoteCandidate = async (connection) => {
2676
+ const stats = connection && await getRtcConnectionStats(connection);
2677
+ const rc = stats?.remoteCandidate;
2678
+ if (!rc) {
2679
+ return "unavailable";
2680
+ }
2681
+ if (rc.candidateType === "relay") {
2682
+ return `${rc.ip}:${rc.port} relay for ${rc.relatedAddress}:${rc.relatedPort}`;
2683
+ }
2684
+ return `${rc.ip}:${rc.port} ${rc.candidateType}`;
2685
+ };
2686
+ var createRtcTransportStats = async (connection, topic) => {
2687
+ const stats = connection && await getRtcConnectionStats(connection, topic);
2688
+ if (!stats) {
2689
+ return {
2690
+ bytesSent: 0,
2691
+ bytesReceived: 0,
2692
+ packetsSent: 0,
2693
+ packetsReceived: 0,
2694
+ rawStats: {}
2695
+ };
2696
+ }
2697
+ return {
2698
+ bytesSent: stats.dataChannel?.bytesSent,
2699
+ bytesReceived: stats.dataChannel?.bytesReceived,
2700
+ packetsSent: 0,
2701
+ packetsReceived: 0,
2702
+ rawStats: stats.raw
2703
+ };
2704
+ };
2705
+ var getRtcConnectionStats = async (connection, channelTopic) => {
2706
+ const stats = await connection.getStats();
2707
+ const statsEntries = Array.from(stats.entries());
2708
+ const transport = statsEntries.find(([_, entry]) => entry.type === "transport")?.[1];
2709
+ const selectedCandidatePair = transport && statsEntries.find(([entryId]) => entryId === transport.selectedCandidatePairId)?.[1];
2710
+ const remoteCandidate = selectedCandidatePair && statsEntries.find(([entryId]) => entryId === selectedCandidatePair.remoteCandidateId)?.[1];
2711
+ const dataChannel = channelTopic && statsEntries.find(([_, entry]) => entry.type === "data-channel" && entry.label === channelTopic)?.[1];
2712
+ return {
2713
+ transport,
2714
+ selectedCandidatePair,
2715
+ dataChannel,
2716
+ remoteCandidate,
2717
+ raw: Object.fromEntries(stats)
2718
+ };
2719
+ };
2720
+ var __dxlog_file10 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc/rtc-transport-channel.ts";
2721
+ var MAX_MESSAGE_SIZE = 64 * 1024;
2722
+ var MAX_BUFFERED_AMOUNT = 64 * 1024;
2723
+ var RtcTransportChannel = class extends import_context6.Resource {
2724
+ constructor(_connection, _options) {
2725
+ super();
2726
+ this._connection = _connection;
2727
+ this._options = _options;
2728
+ this.closed = new import_async11.Event();
2729
+ this.connected = new import_async11.Event();
2730
+ this.errors = new import_debug5.ErrorStream();
2731
+ this._streamDataFlushedCallback = null;
2732
+ this._isChannelCreationInProgress = false;
2733
+ }
2734
+ get isRtcChannelCreationInProgress() {
2735
+ return this._isChannelCreationInProgress;
2736
+ }
2737
+ onConnectionError(error) {
2738
+ if (this.isOpen) {
2739
+ this.errors.raise(error);
2740
+ }
2741
+ }
2742
+ async _open() {
2743
+ (0, import_invariant10.invariant)(!this._isChannelCreationInProgress, void 0, {
2744
+ F: __dxlog_file10,
2745
+ L: 56,
3085
2746
  S: this,
3086
- C: (f, a) => f(...a)
2747
+ A: [
2748
+ "!this._isChannelCreationInProgress",
2749
+ ""
2750
+ ]
3087
2751
  });
3088
- (0, import_log12.log)("created connection", {
3089
- params: this._params
3090
- }, {
3091
- F: __dxlog_file13,
3092
- L: 123,
3093
- S: this,
3094
- C: (f, a) => f(...a)
2752
+ this._isChannelCreationInProgress = true;
2753
+ this._connection.createDataChannel(this._options.topic).then((channel) => {
2754
+ if (this.isOpen) {
2755
+ this._channel = channel;
2756
+ this._initChannel(this._channel);
2757
+ } else {
2758
+ this._safeCloseChannel(channel);
2759
+ }
2760
+ }).catch((err) => {
2761
+ if (this.isOpen) {
2762
+ this.errors.raise(new import_protocols8.ConnectivityError(`Failed to create a channel: ${err?.message ?? "unknown reason."}`));
2763
+ }
2764
+ }).finally(() => {
2765
+ this._isChannelCreationInProgress = false;
3095
2766
  });
3096
- const providedIceServers = await this._params.iceProvider?.getIceServers();
3097
- if (!this._params.webrtcConfig) {
3098
- this._params.webrtcConfig = {};
2767
+ }
2768
+ async _close() {
2769
+ if (this._channel) {
2770
+ this._safeCloseChannel(this._channel);
2771
+ this._channel = void 0;
2772
+ this._stream = void 0;
3099
2773
  }
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();
2774
+ this.closed.emit();
2775
+ (0, import_log10.log)("closed", void 0, {
2776
+ F: __dxlog_file10,
2777
+ L: 86,
2778
+ S: this,
2779
+ C: (f, a) => f(...a)
3142
2780
  });
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
2781
+ }
2782
+ _initChannel(channel) {
2783
+ Object.assign(channel, {
2784
+ onopen: () => {
2785
+ if (!this.isOpen) {
2786
+ import_log10.log.warn("channel opened in a closed transport", {
2787
+ topic: this._options.topic
3150
2788
  }, {
3151
- F: __dxlog_file13,
3152
- L: 165,
2789
+ F: __dxlog_file10,
2790
+ L: 93,
3153
2791
  S: this,
3154
2792
  C: (f, a) => f(...a)
3155
2793
  });
3156
- this.errors.raise(new import_protocols7.UnknownProtocolError("unknown RTCError", err));
2794
+ this._safeCloseChannel(channel);
2795
+ return;
3157
2796
  }
3158
- } else if ("code" in err) {
3159
- import_log12.log.info("simple-peer error", err, {
3160
- F: __dxlog_file13,
3161
- L: 170,
2797
+ (0, import_log10.log)("onopen", void 0, {
2798
+ F: __dxlog_file10,
2799
+ L: 98,
3162
2800
  S: this,
3163
2801
  C: (f, a) => f(...a)
3164
2802
  });
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, {
3191
- F: __dxlog_file13,
3192
- L: 196,
2803
+ const duplex = new import_node_stream2.Duplex({
2804
+ read: () => {
2805
+ },
2806
+ write: (chunk, encoding, callback) => {
2807
+ return this._handleChannelWrite(chunk, callback);
2808
+ }
2809
+ });
2810
+ duplex.pipe(this._options.stream).pipe(duplex);
2811
+ this._stream = duplex;
2812
+ this.connected.emit();
2813
+ },
2814
+ onclose: async () => {
2815
+ (0, import_log10.log)("onclose", void 0, {
2816
+ F: __dxlog_file10,
2817
+ L: 111,
3193
2818
  S: this,
3194
2819
  C: (f, a) => f(...a)
3195
2820
  });
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
- });
2821
+ await this.close();
2822
+ },
2823
+ onmessage: (event) => {
2824
+ if (!this._stream) {
2825
+ import_log10.log.warn("ignoring message on a closed channel", void 0, {
2826
+ F: __dxlog_file10,
2827
+ L: 117,
2828
+ S: this,
2829
+ C: (f, a) => f(...a)
3210
2830
  });
2831
+ return;
3211
2832
  }
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
- });
2833
+ let data = event.data;
2834
+ if (data instanceof ArrayBuffer) {
2835
+ data = Buffer.from(data);
2836
+ }
2837
+ this._stream.push(data);
2838
+ },
2839
+ onerror: (event) => {
2840
+ if (this.isOpen) {
2841
+ const err = event.error instanceof Error ? event.error : new Error(`Datachannel error: ${event.type}.`);
2842
+ this.errors.raise(err);
2843
+ }
2844
+ },
2845
+ onbufferedamountlow: () => {
2846
+ const cb = this._streamDataFlushedCallback;
2847
+ this._streamDataFlushedCallback = null;
2848
+ cb?.();
3219
2849
  }
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
2850
  });
3230
2851
  }
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) {
2852
+ async _handleChannelWrite(chunk, callback) {
2853
+ if (!this._channel) {
2854
+ import_log10.log.warn("writing to a channel after a connection was closed", void 0, {
2855
+ F: __dxlog_file10,
2856
+ L: 145,
2857
+ S: this,
2858
+ C: (f, a) => f(...a)
2859
+ });
3239
2860
  return;
3240
2861
  }
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) {
2862
+ if (chunk.length > MAX_MESSAGE_SIZE) {
2863
+ const error = new Error(`Message too large: ${chunk.length} > ${MAX_MESSAGE_SIZE}.`);
2864
+ this.errors.raise(error);
2865
+ callback();
3254
2866
  return;
3255
2867
  }
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);
2868
+ try {
2869
+ this._channel.send(chunk);
2870
+ } catch (err) {
2871
+ this.errors.raise(err);
2872
+ callback();
2873
+ return;
3263
2874
  }
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
- }
2875
+ if (this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {
2876
+ if (this._streamDataFlushedCallback !== null) {
2877
+ import_log10.log.error("consumer trying to write before we are ready for more data", void 0, {
2878
+ F: __dxlog_file10,
2879
+ L: 166,
2880
+ S: this,
2881
+ C: (f, a) => f(...a)
3343
2882
  });
3344
- close();
2883
+ }
2884
+ this._streamDataFlushedCallback = callback;
2885
+ } else {
2886
+ callback();
2887
+ }
2888
+ }
2889
+ _safeCloseChannel(channel) {
2890
+ try {
2891
+ channel.close();
2892
+ } catch (error) {
2893
+ import_log10.log.catch(error, void 0, {
2894
+ F: __dxlog_file10,
2895
+ L: 178,
2896
+ S: this,
2897
+ C: (f, a) => f(...a)
3345
2898
  });
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;
2899
+ }
3356
2900
  }
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);
2901
+ onSignal(signal) {
2902
+ return this._connection.onSignal(signal);
3368
2903
  }
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
- };
2904
+ async getDetails() {
2905
+ return describeSelectedRemoteCandidate(this._connection.currentConnection);
3382
2906
  }
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
- };
2907
+ async getStats() {
2908
+ return createRtcTransportStats(this._connection.currentConnection, this._options.topic);
3396
2909
  }
3397
- async sendData({ proxyId, payload }) {
3398
- if (this.transports.get(proxyId)?.state !== "OPEN") {
3399
- import_log13.log.debug("transport is closed", void 0, {
3400
- F: __dxlog_file14,
3401
- L: 140,
2910
+ };
2911
+ var chooseInitiatorPeer = (peer1Key, peer2Key) => peer1Key < peer2Key ? peer1Key : peer2Key;
2912
+ var areSdpEqual = (sdp1, sdp2) => {
2913
+ const sdp1Lines = deduplicatedSdpLines(sdp1);
2914
+ const sdp2Lines = deduplicatedSdpLines(sdp2);
2915
+ if (sdp1Lines.length !== sdp2Lines.length) {
2916
+ return false;
2917
+ }
2918
+ return sdp1Lines.every((line, idx) => line === sdp2Lines[idx]);
2919
+ };
2920
+ var deduplicatedSdpLines = (sdp) => {
2921
+ const deduplicatedLines = [];
2922
+ const seenLines = [];
2923
+ for (const line of sdp.split("\r\n")) {
2924
+ if (line.startsWith("m")) {
2925
+ seenLines.length = 0;
2926
+ }
2927
+ if (seenLines.includes(line)) {
2928
+ continue;
2929
+ }
2930
+ seenLines.push(line);
2931
+ deduplicatedLines.push(line);
2932
+ }
2933
+ return deduplicatedLines;
2934
+ };
2935
+ function _ts_decorate6(decorators, target, key, desc) {
2936
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2937
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2938
+ 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;
2939
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2940
+ }
2941
+ var __dxlog_file11 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc/rtc-peer-connection.ts";
2942
+ var RtcPeerConnection = class {
2943
+ constructor(_factory, _options) {
2944
+ this._factory = _factory;
2945
+ this._options = _options;
2946
+ this._channelCreatedCallbacks = /* @__PURE__ */ new Map();
2947
+ this._transportChannels = /* @__PURE__ */ new Map();
2948
+ this._dataChannels = /* @__PURE__ */ new Map();
2949
+ this._readyForCandidates = new import_async10.Trigger();
2950
+ this._offerProcessingMutex = new import_async10.Mutex();
2951
+ this._initiator = chooseInitiatorPeer(_options.ownPeerKey, _options.remotePeerKey) === _options.ownPeerKey;
2952
+ }
2953
+ get transportChannelCount() {
2954
+ return this._transportChannels.size;
2955
+ }
2956
+ get currentConnection() {
2957
+ return this._connection;
2958
+ }
2959
+ async createDataChannel(topic) {
2960
+ const connection = await this._openConnection();
2961
+ if (!this._transportChannels.has(topic)) {
2962
+ if (!this._transportChannels.size) {
2963
+ this._lockAndCloseConnection();
2964
+ }
2965
+ throw new Error("Transport closed while connection was being open");
2966
+ }
2967
+ if (this._initiator) {
2968
+ const channel = connection.createDataChannel(topic);
2969
+ this._dataChannels.set(topic, channel);
2970
+ return channel;
2971
+ } else {
2972
+ const existingChannel = this._dataChannels.get(topic);
2973
+ if (existingChannel) {
2974
+ return existingChannel;
2975
+ }
2976
+ (0, import_log9.log)("waiting for initiator-peer to open a data channel", void 0, {
2977
+ F: __dxlog_file11,
2978
+ L: 90,
3402
2979
  S: this,
3403
2980
  C: (f, a) => f(...a)
3404
2981
  });
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);
2982
+ return new Promise((resolve, reject) => {
2983
+ this._channelCreatedCallbacks.set(topic, {
2984
+ resolve,
2985
+ reject
2986
+ });
3420
2987
  });
3421
2988
  }
3422
2989
  }
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";
2990
+ createTransportChannel(options) {
2991
+ const channel = new RtcTransportChannel(this, options);
2992
+ this._transportChannels.set(options.topic, channel);
2993
+ channel.closed.on(() => {
2994
+ this._transportChannels.delete(options.topic);
2995
+ if (this._transportChannels.size === 0) {
2996
+ this._lockAndCloseConnection();
2997
+ }
2998
+ });
2999
+ return channel;
3000
+ }
3001
+ async _openConnection() {
3002
+ if (this._connection) {
3003
+ return this._connection;
3428
3004
  }
3429
- (0, import_log13.log)("Closed.", void 0, {
3430
- F: __dxlog_file14,
3431
- L: 158,
3005
+ (0, import_log9.log)("initializing connection...", () => ({
3006
+ remotePeer: this._options.remotePeerKey
3007
+ }), {
3008
+ F: __dxlog_file11,
3009
+ L: 115,
3432
3010
  S: this,
3433
3011
  C: (f, a) => f(...a)
3434
3012
  });
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,
3013
+ const config = await this._loadConnectionConfig();
3014
+ const connection = await this._factory.createConnection(config);
3015
+ const iceCandidateErrors = [];
3016
+ Object.assign(connection, {
3017
+ onnegotiationneeded: async () => {
3018
+ (0, import_invariant9.invariant)(this._initiator, void 0, {
3019
+ F: __dxlog_file11,
3020
+ L: 130,
3021
+ S: this,
3022
+ A: [
3023
+ "this._initiator",
3024
+ ""
3025
+ ]
3026
+ });
3027
+ if (connection !== this._connection) {
3028
+ this._onConnectionCallbackAfterClose("onnegotiationneeded", connection);
3029
+ return;
3030
+ }
3031
+ (0, import_log9.log)("onnegotiationneeded", void 0, {
3032
+ F: __dxlog_file11,
3033
+ L: 137,
3470
3034
  S: this,
3471
3035
  C: (f, a) => f(...a)
3472
3036
  });
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);
3037
+ try {
3038
+ const offer = await connection.createOffer();
3039
+ await connection.setLocalDescription(offer);
3040
+ await this._sendDescription(connection, offer);
3041
+ } catch (err) {
3042
+ this._lockAndAbort(connection, err);
3479
3043
  }
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
3044
+ },
3045
+ // When ICE candidate identified (should be sent to remote peer) and when ICE gathering finalized.
3046
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/icecandidate_event
3047
+ onicecandidate: async (event) => {
3048
+ if (connection !== this._connection) {
3049
+ this._onConnectionCallbackAfterClose("onicecandidate", connection);
3050
+ return;
3051
+ }
3052
+ if (event.candidate) {
3053
+ (0, import_log9.log)("onicecandidate", {
3054
+ candidate: event.candidate.candidate
3487
3055
  }, {
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
- }
3056
+ F: __dxlog_file11,
3057
+ L: 156,
3058
+ S: this,
3059
+ C: (f, a) => f(...a)
3060
+ });
3061
+ await this._sendIceCandidate(event.candidate);
3062
+ } else {
3063
+ (0, import_log9.log)("onicecandidate gathering complete", void 0, {
3064
+ F: __dxlog_file11,
3065
+ L: 159,
3066
+ S: this,
3067
+ C: (f, a) => f(...a)
3523
3068
  });
3524
3069
  }
3525
- });
3526
- proxyStream.on("error", (err) => {
3527
- (0, import_log14.log)("proxystream error", {
3528
- err
3070
+ },
3071
+ // When error occurs while performing ICE negotiations through a STUN or TURN server.
3072
+ // It's ok for some candidates to fail if a working pair is eventually found.
3073
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/icecandidateerror_event
3074
+ onicecandidateerror: (event) => {
3075
+ const { url, errorCode, errorText } = event;
3076
+ iceCandidateErrors.push({
3077
+ url,
3078
+ errorCode,
3079
+ errorText
3080
+ });
3081
+ },
3082
+ // When possible error during ICE gathering.
3083
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/iceconnectionstatechange_event
3084
+ oniceconnectionstatechange: () => {
3085
+ if (connection !== this._connection) {
3086
+ this._onConnectionCallbackAfterClose("oniceconnectionstatechange", connection);
3087
+ return;
3088
+ }
3089
+ (0, import_log9.log)("oniceconnectionstatechange", {
3090
+ state: connection.iceConnectionState
3529
3091
  }, {
3530
- F: __dxlog_file15,
3531
- L: 114,
3092
+ F: __dxlog_file11,
3093
+ L: 179,
3532
3094
  S: this,
3533
3095
  C: (f, a) => f(...a)
3534
3096
  });
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
- }));
3097
+ if (connection.iceConnectionState === "failed") {
3098
+ this._lockAndAbort(connection, createIceFailureError(iceCandidateErrors));
3099
+ }
3100
+ },
3101
+ // When new track (or channel) is added.
3102
+ // State: { new, connecting, connected, disconnected, failed, closed }
3103
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionstatechange_event
3104
+ onconnectionstatechange: () => {
3105
+ if (connection !== this._connection) {
3106
+ if (connection.connectionState !== "closed" && connection.connectionState !== "failed") {
3107
+ this._onConnectionCallbackAfterClose("onconnectionstatechange", connection);
3108
+ }
3109
+ return;
3110
+ }
3111
+ (0, import_log9.log)("onconnectionstatechange", {
3112
+ state: connection.connectionState
3113
+ }, {
3114
+ F: __dxlog_file11,
3115
+ L: 196,
3116
+ S: this,
3117
+ C: (f, a) => f(...a)
3118
+ });
3119
+ if (connection.connectionState === "failed") {
3120
+ this._lockAndAbort(connection, new Error("Connection failed."));
3121
+ }
3122
+ },
3123
+ onsignalingstatechange: () => {
3124
+ (0, import_log9.log)("onsignalingstatechange", {
3125
+ state: connection.signalingState
3126
+ }, {
3127
+ F: __dxlog_file11,
3128
+ L: 203,
3129
+ S: this,
3130
+ C: (f, a) => f(...a)
3131
+ });
3132
+ },
3133
+ // When channel is added to connection.
3134
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/datachannel_event
3135
+ ondatachannel: (event) => {
3136
+ (0, import_invariant9.invariant)(!this._initiator, "Initiator is expected to create data channels.", {
3137
+ F: __dxlog_file11,
3138
+ L: 209,
3139
+ S: this,
3140
+ A: [
3141
+ "!this._initiator",
3142
+ "'Initiator is expected to create data channels.'"
3143
+ ]
3144
+ });
3145
+ if (connection !== this._connection) {
3146
+ this._onConnectionCallbackAfterClose("ondatachannel", connection);
3147
+ return;
3148
+ }
3149
+ (0, import_log9.log)("ondatachannel", {
3150
+ label: event.channel.label
3151
+ }, {
3152
+ F: __dxlog_file11,
3153
+ L: 216,
3154
+ S: this,
3155
+ C: (f, a) => f(...a)
3156
+ });
3157
+ this._dataChannels.set(event.channel.label, event.channel);
3158
+ const pendingCallback = this._channelCreatedCallbacks.get(event.channel.label);
3159
+ if (pendingCallback) {
3160
+ this._channelCreatedCallbacks.delete(event.channel.label);
3161
+ pendingCallback.resolve(event.channel);
3162
+ }
3163
+ }
3164
+ });
3165
+ this._connection = connection;
3166
+ this._readyForCandidates.reset();
3167
+ await this._factory.initConnection(connection, {
3168
+ initiator: this._initiator
3169
+ });
3170
+ return this._connection;
3543
3171
  }
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
3172
+ _lockAndAbort(connection, error) {
3173
+ this._abortConnection(connection, error);
3174
+ }
3175
+ _abortConnection(connection, error) {
3176
+ if (connection !== this._connection) {
3177
+ import_log9.log.error("attempted to abort an inactive connection", {
3178
+ error
3553
3179
  }, {
3554
- timeout: RPC_TIMEOUT
3555
- });
3556
- } catch (err) {
3557
- import_log14.log.catch(err, void 0, {
3558
- F: __dxlog_file15,
3559
- L: 134,
3180
+ F: __dxlog_file11,
3181
+ L: 241,
3560
3182
  S: this,
3561
3183
  C: (f, a) => f(...a)
3562
3184
  });
3185
+ this._safeCloseConnection(connection);
3186
+ return;
3563
3187
  }
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));
3188
+ for (const [topic, pendingCallback] of this._channelCreatedCallbacks.entries()) {
3189
+ pendingCallback.reject(error);
3190
+ this._transportChannels.delete(topic);
3578
3191
  }
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
- }
3192
+ this._channelCreatedCallbacks.clear();
3193
+ for (const channel of this._transportChannels.values()) {
3194
+ channel.onConnectionError(error);
3588
3195
  }
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
3196
+ this._transportChannels.clear();
3197
+ this._safeCloseConnection();
3198
+ (0, import_log9.log)("connection aborted", {
3199
+ reason: error.message
3606
3200
  }, {
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;
3634
- }
3635
- createTransport(options) {
3636
- (0, import_invariant12.invariant)(this._bridgeService, "SimplePeerTransportProxyFactory is not ready to open connections", {
3637
- F: __dxlog_file15,
3638
- L: 218,
3201
+ F: __dxlog_file11,
3202
+ L: 255,
3639
3203
  S: this,
3640
- A: [
3641
- "this._bridgeService",
3642
- "'SimplePeerTransportProxyFactory is not ready to open connections'"
3643
- ]
3644
- });
3645
- const transport = new SimplePeerTransportProxy({
3646
- ...options,
3647
- bridgeService: this._bridgeService
3204
+ C: (f, a) => f(...a)
3648
3205
  });
3649
- this._connections.add(transport);
3650
- transport.closed.on(() => this._connections.delete(transport));
3651
- return transport;
3652
3206
  }
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,
3207
+ _lockAndCloseConnection() {
3208
+ (0, import_invariant9.invariant)(this._transportChannels.size === 0, void 0, {
3209
+ F: __dxlog_file11,
3210
+ L: 260,
3211
+ S: this,
3212
+ A: [
3213
+ "this._transportChannels.size === 0",
3214
+ ""
3215
+ ]
3216
+ });
3217
+ if (this._connection) {
3218
+ this._safeCloseConnection();
3219
+ (0, import_log9.log)("connection closed", void 0, {
3220
+ F: __dxlog_file11,
3221
+ L: 263,
3738
3222
  S: this,
3739
3223
  C: (f, a) => f(...a)
3740
3224
  });
3741
- };
3742
- this._peer.onicecandidate = async (event) => {
3743
- import_log15.log.debug("peer.onicecandidate", {
3744
- event
3225
+ }
3226
+ }
3227
+ async onSignal(signal) {
3228
+ const connection = this._connection;
3229
+ if (!connection) {
3230
+ import_log9.log.warn("a signal ignored because the connection was closed", {
3231
+ type: signal.payload.data.type
3745
3232
  }, {
3746
- F: __dxlog_file16,
3747
- L: 107,
3233
+ F: __dxlog_file11,
3234
+ L: 271,
3748
3235
  S: this,
3749
3236
  C: (f, a) => f(...a)
3750
3237
  });
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
- }
3238
+ return;
3239
+ }
3240
+ const data = signal.payload.data;
3241
+ switch (data.type) {
3242
+ case "offer": {
3243
+ await this._offerProcessingMutex.executeSynchronized(async () => {
3244
+ if (isRemoteDescriptionSet(connection, data)) {
3245
+ return;
3246
+ }
3247
+ if (connection.connectionState !== "new") {
3248
+ this._abortConnection(connection, new Error(`Received an offer in ${connection.connectionState}.`));
3249
+ return;
3250
+ }
3251
+ try {
3252
+ await connection.setRemoteDescription({
3253
+ type: data.type,
3254
+ sdp: data.sdp
3255
+ });
3256
+ const answer = await connection.createAnswer();
3257
+ await connection.setLocalDescription(answer);
3258
+ await this._sendDescription(connection, answer);
3259
+ this._onSessionNegotiated(connection);
3260
+ } catch (err) {
3261
+ this._abortConnection(connection, new Error("Error handling a remote offer.", {
3262
+ cause: err
3263
+ }));
3264
+ }
3265
+ });
3266
+ break;
3776
3267
  }
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
3268
+ case "answer":
3269
+ await this._offerProcessingMutex.executeSynchronized(async () => {
3270
+ try {
3271
+ if (isRemoteDescriptionSet(connection, data)) {
3272
+ return;
3273
+ }
3274
+ if (connection.signalingState !== "have-local-offer") {
3275
+ this._abortConnection(connection, new Error(`Unexpected answer from remote peer, signalingState was ${connection.signalingState}.`));
3276
+ return;
3277
+ }
3278
+ await connection.setRemoteDescription({
3279
+ type: data.type,
3280
+ sdp: data.sdp
3281
+ });
3282
+ this._onSessionNegotiated(connection);
3283
+ } catch (err) {
3284
+ this._abortConnection(connection, new Error("Error handling a remote answer.", {
3285
+ cause: err
3286
+ }));
3287
+ }
3288
+ });
3289
+ break;
3290
+ case "candidate":
3291
+ void this._processIceCandidate(connection, data.candidate);
3292
+ break;
3293
+ default:
3294
+ this._abortConnection(connection, new Error(`Unknown signal type ${data.type}.`));
3295
+ break;
3296
+ }
3297
+ (0, import_log9.log)("signal processed", void 0, {
3298
+ F: __dxlog_file11,
3299
+ L: 330,
3300
+ S: this,
3301
+ C: (f, a) => f(...a)
3302
+ });
3303
+ }
3304
+ async _processIceCandidate(connection, candidate) {
3305
+ try {
3306
+ await this._readyForCandidates.wait();
3307
+ if (connection === this._connection) {
3308
+ (0, import_log9.log)("adding ice candidate", {
3309
+ candidate
3806
3310
  }, {
3807
- F: __dxlog_file16,
3808
- L: 145,
3311
+ F: __dxlog_file11,
3312
+ L: 338,
3809
3313
  S: this,
3810
3314
  C: (f, a) => f(...a)
3811
3315
  });
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);
3316
+ await connection.addIceCandidate(candidate);
3317
+ }
3318
+ } catch (err) {
3319
+ import_log9.log.catch(err, void 0, {
3320
+ F: __dxlog_file11,
3321
+ L: 342,
3322
+ S: this,
3323
+ C: (f, a) => f(...a)
3823
3324
  });
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,
3325
+ }
3326
+ }
3327
+ _onSessionNegotiated(connection) {
3328
+ if (connection === this._connection) {
3329
+ (0, import_log9.log)("ready to process ice candidates", void 0, {
3330
+ F: __dxlog_file11,
3331
+ L: 348,
3828
3332
  S: this,
3829
3333
  C: (f, a) => f(...a)
3830
3334
  });
3831
- this._peer.ondatachannel = () => {
3832
- this.errors.raise(new Error("unexpected ondatachannel event for initiator"));
3833
- };
3335
+ this._readyForCandidates.wake();
3834
3336
  } 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
- };
3337
+ import_log9.log.warn("session was negotiated after connection became inactive", void 0, {
3338
+ F: __dxlog_file11,
3339
+ L: 351,
3340
+ S: this,
3341
+ C: (f, a) => f(...a)
3342
+ });
3849
3343
  }
3850
- _LibDataChannelTransport._instanceCount++;
3851
3344
  }
3852
- async close() {
3853
- await this._close();
3854
- if (--_LibDataChannelTransport._instanceCount === 0) {
3855
- (await importESM("node-datachannel")).cleanup();
3856
- }
3345
+ _onConnectionCallbackAfterClose(callback, connection) {
3346
+ import_log9.log.warn("callback invoked after a connection was destroyed, this is probably a bug", {
3347
+ callback,
3348
+ state: connection.connectionState
3349
+ }, {
3350
+ F: __dxlog_file11,
3351
+ L: 356,
3352
+ S: this,
3353
+ C: (f, a) => f(...a)
3354
+ });
3355
+ this._safeCloseConnection(connection);
3857
3356
  }
3858
- async _close() {
3859
- if (this._closed) {
3860
- return;
3861
- }
3862
- await this._disconnectStreams();
3357
+ _safeCloseConnection(connection = this._connection) {
3358
+ const resetFields = this._connection && connection === this._connection;
3863
3359
  try {
3864
- this._peer?.close();
3360
+ connection?.close();
3865
3361
  } catch (err) {
3866
- this.errors.raise(err);
3362
+ import_log9.log.catch(err, void 0, {
3363
+ F: __dxlog_file11,
3364
+ L: 368,
3365
+ S: this,
3366
+ C: (f, a) => f(...a)
3367
+ });
3368
+ }
3369
+ if (resetFields) {
3370
+ this._connection = void 0;
3371
+ this._dataChannels.clear();
3372
+ this._readyForCandidates.wake();
3373
+ void this._factory.onConnectionDestroyed().catch((err) => import_log9.log.catch(err, void 0, {
3374
+ F: __dxlog_file11,
3375
+ L: 374,
3376
+ S: this,
3377
+ C: (f, a) => f(...a)
3378
+ }));
3379
+ for (const [_, pendingCallback] of this._channelCreatedCallbacks.entries()) {
3380
+ pendingCallback.reject("Connection closed.");
3381
+ }
3382
+ this._channelCreatedCallbacks.clear();
3867
3383
  }
3868
- this._peer = void 0;
3869
- this._closed = true;
3870
- this.closed.emit();
3871
3384
  }
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,
3385
+ async _loadConnectionConfig() {
3386
+ const config = {
3387
+ ...this._options.webrtcConfig
3388
+ };
3389
+ try {
3390
+ const providedIceServers = await this._options.iceProvider?.getIceServers() ?? [];
3391
+ if (providedIceServers.length > 0) {
3392
+ config.iceServers = [
3393
+ ...config.iceServers ?? [],
3394
+ ...providedIceServers
3395
+ ];
3396
+ }
3397
+ } catch (error) {
3398
+ import_log9.log.catch(error, void 0, {
3399
+ F: __dxlog_file11,
3400
+ L: 390,
3881
3401
  S: this,
3882
3402
  C: (f, a) => f(...a)
3883
3403
  });
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
- });
3404
+ }
3405
+ return config;
3406
+ }
3407
+ async _sendIceCandidate(candidate) {
3408
+ try {
3409
+ await this._options.sendSignal({
3410
+ payload: {
3411
+ data: {
3412
+ type: "candidate",
3413
+ candidate: {
3414
+ candidate: candidate.candidate,
3415
+ // These fields never seem to be not null, but connecting to Chrome doesn't work if they are.
3416
+ sdpMLineIndex: candidate.sdpMLineIndex ?? "0",
3417
+ sdpMid: candidate.sdpMid ?? "0"
3905
3418
  }
3906
- this._writeCallback = callback;
3907
- } else {
3908
- callback();
3909
3419
  }
3910
3420
  }
3911
3421
  });
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", {
3422
+ } catch (err) {
3423
+ import_log9.log.warn("signaling error", {
3919
3424
  err
3920
3425
  }, {
3921
- F: __dxlog_file16,
3922
- L: 239,
3426
+ F: __dxlog_file11,
3427
+ L: 411,
3923
3428
  S: this,
3924
3429
  C: (f, a) => f(...a)
3925
3430
  });
3926
- await this._close();
3431
+ }
3432
+ }
3433
+ async _sendDescription(connection, description) {
3434
+ if (connection !== this._connection) {
3435
+ return;
3436
+ }
3437
+ const data = {
3438
+ type: description.type,
3439
+ sdp: description.sdp
3927
3440
  };
3928
- this._channel.onerror = async (err) => {
3929
- this.errors.raise(new Error("channel error: " + err.toString()));
3930
- await this._close();
3441
+ await this._options.sendSignal({
3442
+ payload: {
3443
+ data
3444
+ }
3445
+ });
3446
+ }
3447
+ get _connectionInfo() {
3448
+ const connectionInfo = this._connection && {
3449
+ connectionState: this._connection.connectionState,
3450
+ iceConnectionState: this._connection.iceConnectionState,
3451
+ iceGatheringState: this._connection.iceGatheringState,
3452
+ signalingState: this._connection.signalingState,
3453
+ remoteDescription: this._connection.remoteDescription,
3454
+ localDescription: this._connection.localDescription
3931
3455
  };
3932
- this._channel.onbufferedamountlow = () => {
3933
- const cb = this._writeCallback;
3934
- this._writeCallback = null;
3935
- cb?.();
3456
+ return {
3457
+ ...connectionInfo,
3458
+ ts: Date.now(),
3459
+ remotePeerKey: this._options.remotePeerKey,
3460
+ channels: [
3461
+ ...this._transportChannels.keys()
3462
+ ].map((topic) => topic),
3463
+ config: this._connection?.getConfiguration()
3936
3464
  };
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);
3465
+ }
3466
+ get _loggerContext() {
3467
+ return {
3468
+ ownPeerKey: this._options.ownPeerKey,
3469
+ remotePeerKey: this._options.remotePeerKey,
3470
+ initiator: this._initiator,
3471
+ channels: this._transportChannels.size
3943
3472
  };
3944
3473
  }
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
- });
3474
+ };
3475
+ _ts_decorate6([
3476
+ import_async10.synchronized
3477
+ ], RtcPeerConnection.prototype, "_openConnection", null);
3478
+ _ts_decorate6([
3479
+ import_async10.synchronized
3480
+ ], RtcPeerConnection.prototype, "_lockAndAbort", null);
3481
+ _ts_decorate6([
3482
+ import_async10.synchronized
3483
+ ], RtcPeerConnection.prototype, "_lockAndCloseConnection", null);
3484
+ _ts_decorate6([
3485
+ import_async10.synchronized
3486
+ ], RtcPeerConnection.prototype, "onSignal", null);
3487
+ _ts_decorate6([
3488
+ import_tracing.trace.info()
3489
+ ], RtcPeerConnection.prototype, "_connectionInfo", null);
3490
+ _ts_decorate6([
3491
+ import_log9.logInfo
3492
+ ], RtcPeerConnection.prototype, "_loggerContext", null);
3493
+ RtcPeerConnection = _ts_decorate6([
3494
+ import_tracing.trace.resource()
3495
+ ], RtcPeerConnection);
3496
+ var isRemoteDescriptionSet = (connection, data) => {
3497
+ if (!connection.remoteDescription?.type || connection.remoteDescription?.type !== data.type) {
3498
+ return false;
3499
+ }
3500
+ return areSdpEqual(connection.remoteDescription.sdp, data.sdp);
3501
+ };
3502
+ var createIceFailureError = (details) => {
3503
+ const candidateErrors = details.map(({ url, errorCode, errorText }) => `${errorCode} ${url}: ${errorText}`);
3504
+ return new import_protocols7.ConnectivityError(`ICE failed:
3505
+ ${candidateErrors.join("\n")}`);
3506
+ };
3507
+ var createRtcTransportFactory = (webrtcConfig, iceProvider) => {
3508
+ const connectionFactory = getRtcConnectionFactory();
3509
+ return {
3510
+ createTransport: (options) => {
3511
+ const connection = new RtcPeerConnection(connectionFactory, {
3512
+ ownPeerKey: options.ownPeerKey,
3513
+ remotePeerKey: options.remotePeerKey,
3514
+ sendSignal: options.sendSignal,
3515
+ webrtcConfig,
3516
+ iceProvider
3517
+ });
3518
+ return connection.createTransportChannel(options);
3519
+ }
3520
+ };
3521
+ };
3522
+ var __dxlog_file12 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc/rtc-transport-proxy.ts";
3523
+ var RPC_TIMEOUT = 1e4;
3524
+ var CLOSE_RPC_TIMEOUT = 3e3;
3525
+ var RESP_MIN_THRESHOLD = 500;
3526
+ var RtcTransportProxy = class extends import_context7.Resource {
3527
+ constructor(_options) {
3528
+ super();
3529
+ this._options = _options;
3530
+ this._proxyId = import_keys10.PublicKey.random();
3531
+ this.closed = new import_async12.Event();
3532
+ this.connected = new import_async12.Event();
3533
+ this.errors = new import_debug6.ErrorStream();
3534
+ }
3535
+ async _open() {
3536
+ let stream;
3955
3537
  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;
3538
+ stream = this._options.bridgeService.open({
3539
+ proxyId: this._proxyId,
3540
+ remotePeerKey: this._options.remotePeerKey,
3541
+ ownPeerKey: this._options.ownPeerKey,
3542
+ topic: this._options.topic,
3543
+ initiator: this._options.initiator ?? false
3544
+ }, {
3545
+ timeout: RPC_TIMEOUT
3546
+ });
3547
+ } catch (error) {
3548
+ this.errors.raise(error);
3549
+ return;
3550
+ }
3551
+ this._serviceStream = stream;
3552
+ stream.waitUntilReady().then(() => {
3553
+ stream.subscribe(async (event) => {
3554
+ (0, import_log11.log)("rtc transport proxy event", event, {
3555
+ F: __dxlog_file12,
3556
+ L: 66,
3557
+ S: this,
3558
+ C: (f, a) => f(...a)
3559
+ });
3560
+ if (event.connection) {
3561
+ await this._handleConnection(event.connection);
3562
+ } else if (event.data) {
3563
+ this._handleData(event.data);
3564
+ } else if (event.signal) {
3565
+ await this._handleSignal(event.signal);
3999
3566
  }
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
3567
+ }, (err) => {
3568
+ (0, import_log11.log)("rtc bridge stream closed", {
3569
+ err
3570
+ }, {
3571
+ F: __dxlog_file12,
3572
+ L: 76,
3573
+ S: this,
3574
+ C: (f, a) => f(...a)
3575
+ });
3576
+ if (err) {
3577
+ this._raiseIfOpen(err);
3578
+ } else {
3579
+ void this.close();
3580
+ }
3581
+ });
3582
+ const connectorStream = new import_node_stream3.Writable({
3583
+ write: (chunk, _, callback) => {
3584
+ const sendStartMs = Date.now();
3585
+ this._options.bridgeService.sendData({
3586
+ proxyId: this._proxyId,
3587
+ payload: chunk
4029
3588
  }, {
4030
- F: __dxlog_file16,
4031
- L: 306,
4032
- S: this,
4033
- C: (f, a) => f(...a)
3589
+ timeout: RPC_TIMEOUT
3590
+ }).then(() => {
3591
+ if (Date.now() - sendStartMs > RESP_MIN_THRESHOLD) {
3592
+ (0, import_log11.log)("slow response, delaying callback", void 0, {
3593
+ F: __dxlog_file12,
3594
+ L: 93,
3595
+ S: this,
3596
+ C: (f, a) => f(...a)
3597
+ });
3598
+ (0, import_async12.scheduleTask)(this._ctx, () => callback(), RESP_MIN_THRESHOLD);
3599
+ } else {
3600
+ callback();
3601
+ }
3602
+ }, (err) => {
3603
+ callback();
3604
+ this._raiseIfOpen(err);
4034
3605
  });
4035
- this.errors.raise(new Error(`unhandled signal type ${data.type}`));
3606
+ }
3607
+ });
3608
+ connectorStream.on("error", (err) => {
3609
+ this._raiseIfOpen(err);
3610
+ });
3611
+ this._options.stream.pipe(connectorStream);
3612
+ }, (error) => {
3613
+ if (error) {
3614
+ this._raiseIfOpen(error);
3615
+ } else {
3616
+ void this.close();
4036
3617
  }
3618
+ });
3619
+ }
3620
+ async _close() {
3621
+ try {
3622
+ await this._serviceStream?.close();
3623
+ this._serviceStream = void 0;
3624
+ } catch (err) {
3625
+ import_log11.log.catch(err, void 0, {
3626
+ F: __dxlog_file12,
3627
+ L: 128,
3628
+ S: this,
3629
+ C: (f, a) => f(...a)
3630
+ });
3631
+ }
3632
+ try {
3633
+ await this._options.bridgeService.close({
3634
+ proxyId: this._proxyId
3635
+ }, {
3636
+ timeout: CLOSE_RPC_TIMEOUT
3637
+ });
4037
3638
  } catch (err) {
4038
- import_log15.log.catch(err, void 0, {
4039
- F: __dxlog_file16,
4040
- L: 310,
3639
+ import_log11.log.catch(err, void 0, {
3640
+ F: __dxlog_file12,
3641
+ L: 134,
4041
3642
  S: this,
4042
3643
  C: (f, a) => f(...a)
4043
3644
  });
4044
3645
  }
3646
+ this.closed.emit();
4045
3647
  }
4046
- async getDetails() {
4047
- const stats = await this._getStats();
4048
- const rc = stats?.remoteCandidate;
4049
- if (!rc) {
4050
- return "unavailable";
3648
+ async onSignal(signal) {
3649
+ this._options.bridgeService.sendSignal({
3650
+ proxyId: this._proxyId,
3651
+ signal
3652
+ }, {
3653
+ timeout: RPC_TIMEOUT
3654
+ }).catch((err) => this._raiseIfOpen(decodeError(err)));
3655
+ }
3656
+ async _handleConnection(connectionEvent) {
3657
+ if (connectionEvent.error) {
3658
+ this.errors.raise(decodeError(connectionEvent.error));
3659
+ return;
3660
+ }
3661
+ switch (connectionEvent.state) {
3662
+ case import_bridge.ConnectionState.CONNECTED: {
3663
+ this.connected.emit();
3664
+ break;
3665
+ }
3666
+ case import_bridge.ConnectionState.CLOSED: {
3667
+ await this.close();
3668
+ break;
3669
+ }
3670
+ }
3671
+ }
3672
+ _handleData(dataEvent) {
3673
+ try {
3674
+ this._options.stream.write((0, import_util8.arrayToBuffer)(dataEvent.payload));
3675
+ } catch (error) {
3676
+ this._raiseIfOpen(error);
3677
+ }
3678
+ }
3679
+ async _handleSignal(signalEvent) {
3680
+ try {
3681
+ await this._options.sendSignal(signalEvent.payload);
3682
+ } catch (error) {
3683
+ const type = signalEvent.payload.payload.data?.type;
3684
+ if (type === "offer" || type === "answer") {
3685
+ this._raiseIfOpen(new import_protocols9.ConnectivityError(`Session establishment failed: ${type} couldn't be sent.`));
3686
+ }
4051
3687
  }
4052
- if (rc.candidateType === "relay") {
4053
- return `${rc.ip}:${rc.port} relay for ${rc.relatedAddress}:${rc.relatedPort}`;
3688
+ }
3689
+ async getDetails() {
3690
+ try {
3691
+ const response = await this._options.bridgeService.getDetails({
3692
+ proxyId: this._proxyId
3693
+ }, {
3694
+ timeout: RPC_TIMEOUT
3695
+ });
3696
+ return response.details;
3697
+ } catch (err) {
3698
+ return "bridge-svc unreachable";
4054
3699
  }
4055
- return `${rc.ip}:${rc.port} ${rc.candidateType}`;
4056
3700
  }
4057
3701
  async getStats() {
4058
- const stats = await this._getStats();
4059
- if (!stats) {
3702
+ try {
3703
+ const response = await this._options.bridgeService.getStats({
3704
+ proxyId: this._proxyId
3705
+ }, {
3706
+ timeout: RPC_TIMEOUT
3707
+ });
3708
+ return response.stats;
3709
+ } catch (err) {
4060
3710
  return {
4061
3711
  bytesSent: 0,
4062
3712
  bytesReceived: 0,
4063
3713
  packetsSent: 0,
4064
3714
  packetsReceived: 0,
4065
- rawStats: {}
3715
+ rawStats: "bridge-svc unreachable"
4066
3716
  };
4067
3717
  }
4068
- return {
4069
- bytesSent: stats.transport.bytesSent,
4070
- bytesReceived: stats.transport.bytesReceived,
4071
- packetsSent: 0,
4072
- packetsReceived: 0,
4073
- rawStats: stats.raw
4074
- };
4075
3718
  }
4076
- async _getStats() {
4077
- (0, import_invariant13.invariant)(this._peer, "not open", {
4078
- F: __dxlog_file16,
4079
- L: 350,
3719
+ _raiseIfOpen(error) {
3720
+ if (this.isOpen) {
3721
+ this.errors.raise(error);
3722
+ } else {
3723
+ import_log11.log.info("error swallowed because transport was closed", {
3724
+ message: error.message
3725
+ }, {
3726
+ F: __dxlog_file12,
3727
+ L: 215,
3728
+ S: this,
3729
+ C: (f, a) => f(...a)
3730
+ });
3731
+ }
3732
+ }
3733
+ /**
3734
+ * Called when underlying proxy service becomes unavailable.
3735
+ */
3736
+ forceClose() {
3737
+ void this._serviceStream?.close();
3738
+ this.closed.emit();
3739
+ }
3740
+ };
3741
+ var RtcTransportProxyFactory = class {
3742
+ constructor() {
3743
+ this._connections = /* @__PURE__ */ new Set();
3744
+ }
3745
+ /**
3746
+ * Sets the current BridgeService to be used to open connections.
3747
+ * Calling this method will close any existing connections.
3748
+ */
3749
+ setBridgeService(bridgeService) {
3750
+ this._bridgeService = bridgeService;
3751
+ for (const connection of this._connections) {
3752
+ connection.forceClose();
3753
+ }
3754
+ return this;
3755
+ }
3756
+ createTransport(options) {
3757
+ (0, import_invariant11.invariant)(this._bridgeService, "RtcTransportProxyFactory is not ready to open connections", {
3758
+ F: __dxlog_file12,
3759
+ L: 245,
4080
3760
  S: this,
4081
3761
  A: [
4082
- "this._peer",
4083
- "'not open'"
3762
+ "this._bridgeService",
3763
+ "'RtcTransportProxyFactory is not ready to open connections'"
4084
3764
  ]
4085
3765
  });
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);
3766
+ const transport = new RtcTransportProxy({
3767
+ ...options,
3768
+ bridgeService: this._bridgeService
3769
+ });
3770
+ this._connections.add(transport);
3771
+ transport.closed.on(() => this._connections.delete(transport));
3772
+ return transport;
4105
3773
  }
4106
3774
  };
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)
3775
+ var decodeError = (err) => {
3776
+ const message = typeof err === "string" ? err : err.message;
3777
+ if (message.includes("CONNECTION_RESET")) {
3778
+ return new import_protocols9.ConnectionResetError(message);
3779
+ } else if (message.includes("TIMEOUT")) {
3780
+ return new import_protocols9.TimeoutError(message);
3781
+ } else if (message.includes("CONNECTIVITY_ERROR")) {
3782
+ return new import_protocols9.ConnectivityError(message);
3783
+ } else {
3784
+ return typeof err === "string" ? new Error(err) : err;
3785
+ }
4114
3786
  };
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();
3787
+ var __dxlog_file13 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc/rtc-transport-service.ts";
3788
+ var RtcTransportService = class {
3789
+ constructor(webrtcConfig, iceProvider, _transportFactory = createRtcTransportFactory(webrtcConfig, iceProvider)) {
3790
+ this._transportFactory = _transportFactory;
3791
+ this._openTransports = new import_util9.ComplexMap(import_keys11.PublicKey.hash);
4125
3792
  }
4126
- get isOpen() {
4127
- return this._connected && !this._closed;
3793
+ hasOpenTransports() {
3794
+ return this._openTransports.size > 0;
4128
3795
  }
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
3796
+ open(request) {
3797
+ const existingTransport = this._openTransports.get(request.proxyId);
3798
+ if (existingTransport) {
3799
+ import_log12.log.error("requesting a new transport bridge for an existing proxy", void 0, {
3800
+ F: __dxlog_file13,
3801
+ L: 53,
3802
+ S: this,
3803
+ C: (f, a) => f(...a)
3804
+ });
3805
+ void this._safeCloseTransport(existingTransport);
3806
+ this._openTransports.delete(request.proxyId);
3807
+ }
3808
+ return new import_codec_protobuf.Stream(({ ready, next, close }) => {
3809
+ const pushNewState = createStateUpdater(next);
3810
+ const transportStream = new import_node_stream4.Duplex({
3811
+ read: () => {
3812
+ const callbacks = [
3813
+ ...transportState.writeProcessedCallbacks
3814
+ ];
3815
+ transportState.writeProcessedCallbacks.length = 0;
3816
+ callbacks.forEach((cb) => cb());
3817
+ },
3818
+ write: function(chunk, _, callback) {
3819
+ next({
3820
+ data: {
3821
+ payload: chunk
4164
3822
  }
4165
- }).catch((err) => {
4166
- if (!this._closed) {
4167
- this.errors.raise(err);
3823
+ });
3824
+ callback();
3825
+ }
3826
+ });
3827
+ const transport = this._transportFactory.createTransport({
3828
+ initiator: request.initiator,
3829
+ topic: request.topic,
3830
+ ownPeerKey: request.ownPeerKey,
3831
+ remotePeerKey: request.remotePeerKey,
3832
+ stream: transportStream,
3833
+ sendSignal: async (signal) => {
3834
+ next({
3835
+ signal: {
3836
+ payload: signal
4168
3837
  }
4169
3838
  });
4170
- });
4171
- this._server.on("error", (err) => {
4172
- this.errors.raise(err);
4173
- });
4174
- this._server.listen(0);
3839
+ }
4175
3840
  });
4176
- }
3841
+ const transportState = {
3842
+ proxyId: request.proxyId,
3843
+ transport,
3844
+ connectorStream: transportStream,
3845
+ writeProcessedCallbacks: []
3846
+ };
3847
+ pushNewState(import_bridge2.ConnectionState.CONNECTING);
3848
+ transport.connected.on(() => pushNewState(import_bridge2.ConnectionState.CONNECTED));
3849
+ transport.errors.handle(async (err) => {
3850
+ pushNewState(import_bridge2.ConnectionState.CLOSED, err);
3851
+ void this._safeCloseTransport(transportState);
3852
+ close(err);
3853
+ });
3854
+ transport.closed.on(async () => {
3855
+ pushNewState(import_bridge2.ConnectionState.CLOSED);
3856
+ void this._safeCloseTransport(transportState);
3857
+ close();
3858
+ });
3859
+ this._openTransports.set(request.proxyId, transportState);
3860
+ transport.open().catch(async (err) => {
3861
+ pushNewState(import_bridge2.ConnectionState.CLOSED, err);
3862
+ void this._safeCloseTransport(transportState);
3863
+ close(err);
3864
+ });
3865
+ ready();
3866
+ });
4177
3867
  }
4178
- async close() {
4179
- (0, import_log16.log)("closing", void 0, {
4180
- F: __dxlog_file17,
4181
- L: 78,
3868
+ async sendSignal({ proxyId, signal }) {
3869
+ const transport = this._openTransports.get(proxyId);
3870
+ (0, import_invariant12.invariant)(transport, void 0, {
3871
+ F: __dxlog_file13,
3872
+ L: 121,
4182
3873
  S: this,
4183
- C: (f, a) => f(...a)
3874
+ A: [
3875
+ "transport",
3876
+ ""
3877
+ ]
4184
3878
  });
4185
- this._socket?.destroy();
4186
- this._server?.close();
4187
- this._closed = true;
3879
+ await transport.transport.onSignal(signal);
4188
3880
  }
4189
- async onSignal({ payload }) {
4190
- (0, import_log16.log)("received signal", {
4191
- payload
4192
- }, {
4193
- F: __dxlog_file17,
4194
- L: 85,
3881
+ async getDetails({ proxyId }) {
3882
+ const transport = this._openTransports.get(proxyId);
3883
+ (0, import_invariant12.invariant)(transport, void 0, {
3884
+ F: __dxlog_file13,
3885
+ L: 128,
4195
3886
  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"
3887
+ A: [
3888
+ "transport",
3889
+ ""
3890
+ ]
4206
3891
  });
3892
+ return {
3893
+ details: await transport.transport.getDetails()
3894
+ };
4207
3895
  }
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() {
3896
+ async getStats({ proxyId }) {
3897
+ const transport = this._openTransports.get(proxyId);
3898
+ (0, import_invariant12.invariant)(transport, void 0, {
3899
+ F: __dxlog_file13,
3900
+ L: 135,
3901
+ S: this,
3902
+ A: [
3903
+ "transport",
3904
+ ""
3905
+ ]
3906
+ });
4217
3907
  return {
4218
- bytesSent: 0,
4219
- bytesReceived: 0,
4220
- packetsSent: 0,
4221
- packetsReceived: 0
3908
+ stats: await transport.transport.getStats()
4222
3909
  };
4223
3910
  }
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,
3911
+ async sendData({ proxyId, payload }) {
3912
+ const transport = this._openTransports.get(proxyId);
3913
+ (0, import_invariant12.invariant)(transport, void 0, {
3914
+ F: __dxlog_file13,
3915
+ L: 142,
4231
3916
  S: this,
4232
- C: (f, a) => f(...a)
3917
+ A: [
3918
+ "transport",
3919
+ ""
3920
+ ]
4233
3921
  });
4234
- this._socket = socket;
4235
- this._socket.on("connect", () => {
4236
- (0, import_log16.log)("connected to", {
4237
- port: this._socket?.remotePort
3922
+ const bufferHasSpace = transport.connectorStream.push(payload);
3923
+ if (!bufferHasSpace) {
3924
+ await new Promise((resolve) => {
3925
+ transport.writeProcessedCallbacks.push(resolve);
3926
+ });
3927
+ }
3928
+ }
3929
+ async close({ proxyId }) {
3930
+ const transport = this._openTransports.get(proxyId);
3931
+ if (!transport) {
3932
+ return;
3933
+ }
3934
+ this._openTransports.delete(proxyId);
3935
+ await this._safeCloseTransport(transport);
3936
+ }
3937
+ async _safeCloseTransport(transport) {
3938
+ if (this._openTransports.get(transport.proxyId) === transport) {
3939
+ this._openTransports.delete(transport.proxyId);
3940
+ }
3941
+ transport.writeProcessedCallbacks.forEach((cb) => cb());
3942
+ try {
3943
+ await transport.transport.close();
3944
+ } catch (error) {
3945
+ import_log12.log.warn("transport close error", {
3946
+ message: error?.message
4238
3947
  }, {
4239
- F: __dxlog_file17,
4240
- L: 119,
3948
+ F: __dxlog_file13,
3949
+ L: 172,
4241
3950
  S: this,
4242
3951
  C: (f, a) => f(...a)
4243
3952
  });
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();
3953
+ }
3954
+ try {
3955
+ transport.connectorStream.end();
3956
+ } catch (error) {
3957
+ import_log12.log.warn("connectorStream close error", {
3958
+ message: error?.message
3959
+ }, {
3960
+ F: __dxlog_file13,
3961
+ L: 177,
3962
+ S: this,
3963
+ C: (f, a) => f(...a)
3964
+ });
3965
+ }
3966
+ (0, import_log12.log)("closed", void 0, {
3967
+ F: __dxlog_file13,
3968
+ L: 179,
3969
+ S: this,
3970
+ C: (f, a) => f(...a)
4251
3971
  });
4252
- this.connected.emit();
4253
- this.options.stream.pipe(this._socket).pipe(this.options.stream);
4254
3972
  }
4255
3973
  };
3974
+ var createStateUpdater = (next) => {
3975
+ return (state, err) => {
3976
+ next({
3977
+ connection: {
3978
+ state,
3979
+ ...err ? {
3980
+ error: err.message
3981
+ } : void 0
3982
+ }
3983
+ });
3984
+ };
3985
+ };
4256
3986
  var createTeleportProtocolFactory = (onConnection, defaultParams) => {
4257
3987
  return (params) => {
4258
3988
  const teleport = new import_teleport.Teleport({
@@ -4282,26 +4012,18 @@ var createTeleportProtocolFactory = (onConnection, defaultParams) => {
4282
4012
  ConnectionState,
4283
4013
  EventType,
4284
4014
  FullyConnectedTopology,
4285
- LibDataChannelTransport,
4286
4015
  MAX_CONCURRENT_INITIATING_CONNECTIONS,
4287
- MMSTTopology,
4288
4016
  MemoryTransport,
4289
4017
  MemoryTransportFactory,
4290
- SimplePeerTransport,
4291
- SimplePeerTransportProxy,
4292
- SimplePeerTransportProxyFactory,
4293
- SimplePeerTransportService,
4294
- StarTopology,
4018
+ RtcTransportProxy,
4019
+ RtcTransportProxyFactory,
4020
+ RtcTransportService,
4295
4021
  Swarm,
4296
4022
  SwarmMapper,
4297
4023
  SwarmMessenger,
4298
4024
  SwarmNetworkManager,
4299
- TcpTransport,
4300
- TcpTransportFactory,
4301
4025
  TransportKind,
4302
- createIceProvider,
4303
- createLibDataChannelTransportFactory,
4304
- createSimplePeerTransportFactory,
4026
+ createRtcTransportFactory,
4305
4027
  createTeleportProtocolFactory
4306
4028
  });
4307
- //# sourceMappingURL=chunk-4YAYC7WN.cjs.map
4029
+ //# sourceMappingURL=chunk-4TTFBX3M.cjs.map