@schwarzdavid/anyrpc 0.0.1-alpha.0 → 1.0.0-rc.0

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 (244) hide show
  1. package/LICENSE +373 -0
  2. package/README.md +115 -62
  3. package/dist/child-process.d.ts +62 -0
  4. package/dist/child-process.d.ts.map +1 -0
  5. package/dist/child-process.js +116 -128
  6. package/dist/child-process.js.map +1 -0
  7. package/dist/chunks/AbstractMessagePortInitiatorAdapter-1KLO-1xm.d.ts +83 -0
  8. package/dist/chunks/AbstractMessagePortInitiatorAdapter-1KLO-1xm.d.ts.map +1 -0
  9. package/dist/chunks/AbstractMessagePortInitiatorAdapter-DWJ29SLn.js +122 -0
  10. package/dist/chunks/AbstractMessagePortInitiatorAdapter-DWJ29SLn.js.map +1 -0
  11. package/dist/chunks/AbstractRpcAdapter-CzHpORlI.js +89 -0
  12. package/dist/chunks/AbstractRpcAdapter-CzHpORlI.js.map +1 -0
  13. package/dist/chunks/AbstractRpcAdapter-fNu6wvPV.d.ts +80 -0
  14. package/dist/chunks/AbstractRpcAdapter-fNu6wvPV.d.ts.map +1 -0
  15. package/dist/chunks/AbstractRpcHubAdapter-CM8YKvTy.js +25 -0
  16. package/dist/chunks/AbstractRpcHubAdapter-CM8YKvTy.js.map +1 -0
  17. package/dist/chunks/AbstractRpcHubAdapter-V9lRYzuv.d.ts +26 -0
  18. package/dist/chunks/AbstractRpcHubAdapter-V9lRYzuv.d.ts.map +1 -0
  19. package/dist/chunks/AbstractSocketAdapter-Bnd_0D3T.js +63 -0
  20. package/dist/chunks/AbstractSocketAdapter-Bnd_0D3T.js.map +1 -0
  21. package/dist/chunks/AbstractSocketAdapter-CGdtVMSQ.d.ts +19 -0
  22. package/dist/chunks/AbstractSocketAdapter-CGdtVMSQ.d.ts.map +1 -0
  23. package/dist/chunks/ControlProtocol-Dd9aHpa5.js +99 -0
  24. package/dist/chunks/ControlProtocol-Dd9aHpa5.js.map +1 -0
  25. package/dist/chunks/Heartbeat-GHewy9_w.d.ts +7 -0
  26. package/dist/chunks/Heartbeat-GHewy9_w.d.ts.map +1 -0
  27. package/dist/chunks/handshake-sA3m5TsG.js +43 -0
  28. package/dist/chunks/handshake-sA3m5TsG.js.map +1 -0
  29. package/dist/chunks/rpc-Biub1bBg.js +143 -0
  30. package/dist/chunks/rpc-Biub1bBg.js.map +1 -0
  31. package/dist/chunks/uuid-B8wYvn_A.js +7 -0
  32. package/dist/chunks/uuid-B8wYvn_A.js.map +1 -0
  33. package/dist/iframe.d.ts +34 -0
  34. package/dist/iframe.d.ts.map +1 -0
  35. package/dist/iframe.js +68 -72
  36. package/dist/iframe.js.map +1 -0
  37. package/dist/index.d.ts +112 -13
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +485 -442
  40. package/dist/index.js.map +1 -0
  41. package/dist/message-port.d.ts +3 -0
  42. package/dist/message-port.js +1 -6
  43. package/dist/node-worker.d.ts +44 -0
  44. package/dist/node-worker.d.ts.map +1 -0
  45. package/dist/node-worker.js +92 -75
  46. package/dist/node-worker.js.map +1 -0
  47. package/dist/socket.d.ts +3 -0
  48. package/dist/socket.js +1 -66
  49. package/dist/web-worker.d.ts +57 -0
  50. package/dist/web-worker.d.ts.map +1 -0
  51. package/dist/web-worker.js +139 -150
  52. package/dist/web-worker.js.map +1 -0
  53. package/dist/websocket.d.ts +64 -0
  54. package/dist/websocket.d.ts.map +1 -0
  55. package/dist/websocket.js +103 -111
  56. package/dist/websocket.js.map +1 -0
  57. package/package.json +44 -39
  58. package/src/createRpcChannel.ts +87 -119
  59. package/src/createRpcHub.ts +79 -42
  60. package/src/index.ts +15 -3
  61. package/src/lib/ConnectionLifecycle.ts +32 -0
  62. package/src/lib/ControlProtocol.ts +44 -12
  63. package/src/lib/MessageQueue.ts +73 -0
  64. package/src/lib/PendingRequests.ts +38 -0
  65. package/src/lib/RpcError.ts +4 -2
  66. package/src/lib/adapter/AbstractRpcAdapter.ts +27 -28
  67. package/src/lib/adapter/AbstractRpcHubAdapter.ts +39 -22
  68. package/src/lib/adapter/child-process/ChildProcessClientAdapter.ts +1 -0
  69. package/src/lib/adapter/child-process/ChildProcessHostAdapter.ts +1 -0
  70. package/src/lib/adapter/iframe/IFrameClientAdapter.ts +4 -3
  71. package/src/lib/adapter/iframe/IFrameHostAdapter.ts +4 -3
  72. package/src/lib/adapter/message-port/AbstractMessagePortAdapter.ts +13 -35
  73. package/src/lib/adapter/message-port/{AbstractMessagePortClientAdapter.ts → AbstractMessagePortInitiatorAdapter.ts} +18 -8
  74. package/src/lib/adapter/message-port/{AbstractMessagePortHostAdapter.ts → AbstractMessagePortResponderAdapter.ts} +14 -8
  75. package/src/lib/adapter/message-port/index.ts +8 -2
  76. package/src/lib/adapter/node-worker/NodeWorkerClientAdapter.ts +4 -3
  77. package/src/lib/adapter/node-worker/NodeWorkerHostAdapter.ts +9 -3
  78. package/src/lib/adapter/socket/AbstractSocketAdapter.ts +8 -24
  79. package/src/lib/adapter/web-worker/SharedWorkerHubAdapter.ts +2 -2
  80. package/src/lib/adapter/web-worker/SharedWorkerPeerAdapter.ts +4 -12
  81. package/src/lib/adapter/web-worker/WebWorkerClientAdapter.ts +4 -3
  82. package/src/lib/adapter/web-worker/WebWorkerHostAdapter.ts +9 -3
  83. package/src/lib/adapter/websocket/WebSocketClientAdapter.ts +1 -0
  84. package/src/lib/adapter/websocket/WebSocketHubAdapter.ts +19 -11
  85. package/src/lib/adapter/websocket/WebSocketPeerAdapter.ts +3 -16
  86. package/src/lib/adapter/websocket/index.ts +7 -1
  87. package/src/types/ConnectionStatus.ts +1 -0
  88. package/src/types/EventEmitter.ts +1 -1
  89. package/src/types/Promisable.ts +1 -0
  90. package/src/types/RpcChannel.ts +13 -1
  91. package/src/types/RpcHub.ts +59 -25
  92. package/src/utils/abortable.ts +16 -0
  93. package/src/utils/rpc.ts +10 -8
  94. package/src/utils/withDefaults.ts +5 -0
  95. package/dist/child-process.cjs +0 -1
  96. package/dist/chunks/AbstractRpcAdapter-7gOLZtYD.js +0 -82
  97. package/dist/chunks/AbstractRpcAdapter-BPIitR0A.cjs +0 -1
  98. package/dist/chunks/AbstractRpcHubAdapter-BVPYUoL9.js +0 -26
  99. package/dist/chunks/AbstractRpcHubAdapter-Bqcrs7Mb.cjs +0 -1
  100. package/dist/chunks/ControlProtocol-0b5_21ZU.js +0 -82
  101. package/dist/chunks/ControlProtocol-BMvwQecN.cjs +0 -1
  102. package/dist/chunks/handshake-CWtm9Y59.cjs +0 -1
  103. package/dist/chunks/handshake-CZWqKvZe.js +0 -39
  104. package/dist/chunks/index-B_SfPYCc.js +0 -133
  105. package/dist/chunks/index-D5LbDuYg.cjs +0 -1
  106. package/dist/chunks/rpc-Brf2MoZo.cjs +0 -1
  107. package/dist/chunks/rpc-DeJEGj4-.js +0 -134
  108. package/dist/chunks/uuid-C2SCOpSM.cjs +0 -1
  109. package/dist/chunks/uuid-DTlgoKBw.js +0 -9
  110. package/dist/constants/JSON_RPC_ERRORS.d.ts +0 -19
  111. package/dist/constants/JSON_RPC_ERRORS.d.ts.map +0 -1
  112. package/dist/createRpcChannel.d.ts +0 -18
  113. package/dist/createRpcChannel.d.ts.map +0 -1
  114. package/dist/createRpcHub.d.ts +0 -7
  115. package/dist/createRpcHub.d.ts.map +0 -1
  116. package/dist/iframe.cjs +0 -1
  117. package/dist/index.cjs +0 -1
  118. package/dist/lib/ControlProtocol.d.ts +0 -20
  119. package/dist/lib/ControlProtocol.d.ts.map +0 -1
  120. package/dist/lib/EventEmitter.d.ts +0 -12
  121. package/dist/lib/EventEmitter.d.ts.map +0 -1
  122. package/dist/lib/HandlerRegistry.d.ts +0 -8
  123. package/dist/lib/HandlerRegistry.d.ts.map +0 -1
  124. package/dist/lib/Heartbeat.d.ts +0 -24
  125. package/dist/lib/Heartbeat.d.ts.map +0 -1
  126. package/dist/lib/Logger.d.ts +0 -13
  127. package/dist/lib/Logger.d.ts.map +0 -1
  128. package/dist/lib/RpcError.d.ts +0 -11
  129. package/dist/lib/RpcError.d.ts.map +0 -1
  130. package/dist/lib/RpcMessageError.d.ts +0 -15
  131. package/dist/lib/RpcMessageError.d.ts.map +0 -1
  132. package/dist/lib/adapter/AbstractRpcAdapter.d.ts +0 -28
  133. package/dist/lib/adapter/AbstractRpcAdapter.d.ts.map +0 -1
  134. package/dist/lib/adapter/AbstractRpcHubAdapter.d.ts +0 -24
  135. package/dist/lib/adapter/AbstractRpcHubAdapter.d.ts.map +0 -1
  136. package/dist/lib/adapter/child-process/ChildProcessClientAdapter.d.ts +0 -19
  137. package/dist/lib/adapter/child-process/ChildProcessClientAdapter.d.ts.map +0 -1
  138. package/dist/lib/adapter/child-process/ChildProcessHostAdapter.d.ts +0 -43
  139. package/dist/lib/adapter/child-process/ChildProcessHostAdapter.d.ts.map +0 -1
  140. package/dist/lib/adapter/child-process/constants/childProcessHandshake.d.ts +0 -3
  141. package/dist/lib/adapter/child-process/constants/childProcessHandshake.d.ts.map +0 -1
  142. package/dist/lib/adapter/child-process/index.d.ts +0 -4
  143. package/dist/lib/adapter/child-process/index.d.ts.map +0 -1
  144. package/dist/lib/adapter/child-process/utils/currentProcess.d.ts +0 -16
  145. package/dist/lib/adapter/child-process/utils/currentProcess.d.ts.map +0 -1
  146. package/dist/lib/adapter/child-process/utils/ipcEnvelope.d.ts +0 -7
  147. package/dist/lib/adapter/child-process/utils/ipcEnvelope.d.ts.map +0 -1
  148. package/dist/lib/adapter/iframe/IFrameClientAdapter.d.ts +0 -17
  149. package/dist/lib/adapter/iframe/IFrameClientAdapter.d.ts.map +0 -1
  150. package/dist/lib/adapter/iframe/IFrameHostAdapter.d.ts +0 -20
  151. package/dist/lib/adapter/iframe/IFrameHostAdapter.d.ts.map +0 -1
  152. package/dist/lib/adapter/iframe/constants/iframeHandshake.d.ts +0 -3
  153. package/dist/lib/adapter/iframe/constants/iframeHandshake.d.ts.map +0 -1
  154. package/dist/lib/adapter/iframe/index.d.ts +0 -5
  155. package/dist/lib/adapter/iframe/index.d.ts.map +0 -1
  156. package/dist/lib/adapter/iframe/utils/iframeOrigin.d.ts +0 -5
  157. package/dist/lib/adapter/iframe/utils/iframeOrigin.d.ts.map +0 -1
  158. package/dist/lib/adapter/message-port/AbstractMessagePortAdapter.d.ts +0 -38
  159. package/dist/lib/adapter/message-port/AbstractMessagePortAdapter.d.ts.map +0 -1
  160. package/dist/lib/adapter/message-port/AbstractMessagePortClientAdapter.d.ts +0 -22
  161. package/dist/lib/adapter/message-port/AbstractMessagePortClientAdapter.d.ts.map +0 -1
  162. package/dist/lib/adapter/message-port/AbstractMessagePortHostAdapter.d.ts +0 -20
  163. package/dist/lib/adapter/message-port/AbstractMessagePortHostAdapter.d.ts.map +0 -1
  164. package/dist/lib/adapter/message-port/index.d.ts +0 -6
  165. package/dist/lib/adapter/message-port/index.d.ts.map +0 -1
  166. package/dist/lib/adapter/message-port/utils/handshake.d.ts +0 -13
  167. package/dist/lib/adapter/message-port/utils/handshake.d.ts.map +0 -1
  168. package/dist/lib/adapter/message-port/utils/messageData.d.ts +0 -2
  169. package/dist/lib/adapter/message-port/utils/messageData.d.ts.map +0 -1
  170. package/dist/lib/adapter/node-worker/NodeWorkerClientAdapter.d.ts +0 -12
  171. package/dist/lib/adapter/node-worker/NodeWorkerClientAdapter.d.ts.map +0 -1
  172. package/dist/lib/adapter/node-worker/NodeWorkerHostAdapter.d.ts +0 -35
  173. package/dist/lib/adapter/node-worker/NodeWorkerHostAdapter.d.ts.map +0 -1
  174. package/dist/lib/adapter/node-worker/constants/nodeWorkerHandshake.d.ts +0 -3
  175. package/dist/lib/adapter/node-worker/constants/nodeWorkerHandshake.d.ts.map +0 -1
  176. package/dist/lib/adapter/node-worker/index.d.ts +0 -4
  177. package/dist/lib/adapter/node-worker/index.d.ts.map +0 -1
  178. package/dist/lib/adapter/node-worker/utils/initEnvelope.d.ts +0 -13
  179. package/dist/lib/adapter/node-worker/utils/initEnvelope.d.ts.map +0 -1
  180. package/dist/lib/adapter/socket/AbstractSocketAdapter.d.ts +0 -23
  181. package/dist/lib/adapter/socket/AbstractSocketAdapter.d.ts.map +0 -1
  182. package/dist/lib/adapter/socket/index.d.ts +0 -3
  183. package/dist/lib/adapter/socket/index.d.ts.map +0 -1
  184. package/dist/lib/adapter/socket/utils/parseObject.d.ts +0 -2
  185. package/dist/lib/adapter/socket/utils/parseObject.d.ts.map +0 -1
  186. package/dist/lib/adapter/web-worker/SharedWorkerHubAdapter.d.ts +0 -18
  187. package/dist/lib/adapter/web-worker/SharedWorkerHubAdapter.d.ts.map +0 -1
  188. package/dist/lib/adapter/web-worker/SharedWorkerPeerAdapter.d.ts +0 -18
  189. package/dist/lib/adapter/web-worker/SharedWorkerPeerAdapter.d.ts.map +0 -1
  190. package/dist/lib/adapter/web-worker/WebWorkerClientAdapter.d.ts +0 -10
  191. package/dist/lib/adapter/web-worker/WebWorkerClientAdapter.d.ts.map +0 -1
  192. package/dist/lib/adapter/web-worker/WebWorkerHostAdapter.d.ts +0 -33
  193. package/dist/lib/adapter/web-worker/WebWorkerHostAdapter.d.ts.map +0 -1
  194. package/dist/lib/adapter/web-worker/constants/webWorkerHandshake.d.ts +0 -3
  195. package/dist/lib/adapter/web-worker/constants/webWorkerHandshake.d.ts.map +0 -1
  196. package/dist/lib/adapter/web-worker/index.d.ts +0 -5
  197. package/dist/lib/adapter/web-worker/index.d.ts.map +0 -1
  198. package/dist/lib/adapter/web-worker/utils/describeWorkerError.d.ts +0 -3
  199. package/dist/lib/adapter/web-worker/utils/describeWorkerError.d.ts.map +0 -1
  200. package/dist/lib/adapter/web-worker/utils/globalScope.d.ts +0 -8
  201. package/dist/lib/adapter/web-worker/utils/globalScope.d.ts.map +0 -1
  202. package/dist/lib/adapter/websocket/WebSocketClientAdapter.d.ts +0 -27
  203. package/dist/lib/adapter/websocket/WebSocketClientAdapter.d.ts.map +0 -1
  204. package/dist/lib/adapter/websocket/WebSocketHubAdapter.d.ts +0 -21
  205. package/dist/lib/adapter/websocket/WebSocketHubAdapter.d.ts.map +0 -1
  206. package/dist/lib/adapter/websocket/WebSocketPeerAdapter.d.ts +0 -28
  207. package/dist/lib/adapter/websocket/WebSocketPeerAdapter.d.ts.map +0 -1
  208. package/dist/lib/adapter/websocket/constants/webSocket.d.ts +0 -5
  209. package/dist/lib/adapter/websocket/constants/webSocket.d.ts.map +0 -1
  210. package/dist/lib/adapter/websocket/index.d.ts +0 -5
  211. package/dist/lib/adapter/websocket/index.d.ts.map +0 -1
  212. package/dist/lib/adapter/websocket/utils/reconnectDelay.d.ts +0 -2
  213. package/dist/lib/adapter/websocket/utils/reconnectDelay.d.ts.map +0 -1
  214. package/dist/message-port.cjs +0 -1
  215. package/dist/node-worker.cjs +0 -1
  216. package/dist/socket.cjs +0 -1
  217. package/dist/types/ConnectionStatus.d.ts +0 -6
  218. package/dist/types/ConnectionStatus.d.ts.map +0 -1
  219. package/dist/types/EventEmitter.d.ts +0 -6
  220. package/dist/types/EventEmitter.d.ts.map +0 -1
  221. package/dist/types/LogLevel.d.ts +0 -9
  222. package/dist/types/LogLevel.d.ts.map +0 -1
  223. package/dist/types/MethodMap.d.ts +0 -5
  224. package/dist/types/MethodMap.d.ts.map +0 -1
  225. package/dist/types/MethodName.d.ts +0 -9
  226. package/dist/types/MethodName.d.ts.map +0 -1
  227. package/dist/types/RpcChannel.d.ts +0 -29
  228. package/dist/types/RpcChannel.d.ts.map +0 -1
  229. package/dist/types/RpcChannelEvents.d.ts +0 -9
  230. package/dist/types/RpcChannelEvents.d.ts.map +0 -1
  231. package/dist/types/RpcHub.d.ts +0 -36
  232. package/dist/types/RpcHub.d.ts.map +0 -1
  233. package/dist/types/RpcMessages.d.ts +0 -37
  234. package/dist/types/RpcMessages.d.ts.map +0 -1
  235. package/dist/utils/controlMessages.d.ts +0 -14
  236. package/dist/utils/controlMessages.d.ts.map +0 -1
  237. package/dist/utils/createMethodProxy.d.ts +0 -5
  238. package/dist/utils/createMethodProxy.d.ts.map +0 -1
  239. package/dist/utils/rpc.d.ts +0 -26
  240. package/dist/utils/rpc.d.ts.map +0 -1
  241. package/dist/utils/uuid.d.ts +0 -2
  242. package/dist/utils/uuid.d.ts.map +0 -1
  243. package/dist/web-worker.cjs +0 -1
  244. package/dist/websocket.cjs +0 -1
package/dist/index.js CHANGED
@@ -1,447 +1,490 @@
1
- import { p as se, R as W, a as h, b as g, i as ce, c as ie, d as A, e as ae, f as M } from "./chunks/rpc-DeJEGj4-.js";
2
- import { u as ue } from "./chunks/uuid-DTlgoKBw.js";
3
- import { a as G, L as Y, C as T } from "./chunks/AbstractRpcAdapter-7gOLZtYD.js";
4
- import { A as ye } from "./chunks/AbstractRpcAdapter-7gOLZtYD.js";
5
- import { A as Ne } from "./chunks/AbstractRpcHubAdapter-BVPYUoL9.js";
6
- class F {
7
- constructor(i) {
8
- this.onListenerError = i;
9
- }
10
- listeners = /* @__PURE__ */ new Map();
11
- on(i, a) {
12
- const o = this.listeners.get(i) ?? /* @__PURE__ */ new Set();
13
- return o.add(a), this.listeners.set(i, o), () => {
14
- o.delete(a);
15
- };
16
- }
17
- emit(i, a) {
18
- for (const o of [...this.listeners.get(i) ?? []])
19
- this.callListener(i, o, a);
20
- }
21
- callListener(i, a, o) {
22
- const l = (w) => this.onListenerError(w, i);
23
- try {
24
- const w = a(...o);
25
- w instanceof Promise && w.catch(l);
26
- } catch (w) {
27
- l(w);
28
- }
29
- }
1
+ import { a as e, c as t, i as n, l as r, n as i, o as a, r as o, s, t as c } from "./chunks/rpc-Biub1bBg.js";
2
+ import { t as l } from "./chunks/uuid-B8wYvn_A.js";
3
+ import { i as u, n as d, r as f, t as p } from "./chunks/AbstractRpcAdapter-CzHpORlI.js";
4
+ import { t as m } from "./chunks/AbstractRpcHubAdapter-CM8YKvTy.js";
5
+ // src/lib/EventEmitter.ts
6
+ var h = class {
7
+ onListenerError;
8
+ listeners = /* @__PURE__ */ new Map();
9
+ constructor(e) {
10
+ this.onListenerError = e;
11
+ }
12
+ on(e, t) {
13
+ let n = this.listeners.get(e) ?? /* @__PURE__ */ new Set();
14
+ return n.add(t), this.listeners.set(e, n), () => {
15
+ n.delete(t);
16
+ };
17
+ }
18
+ emit(e, t) {
19
+ for (let n of [...this.listeners.get(e) ?? []]) this.callListener(e, n, t);
20
+ }
21
+ callListener(e, t, n) {
22
+ let r = (t) => this.onListenerError(t, e);
23
+ try {
24
+ let e = t(...n);
25
+ e instanceof Promise && e.catch(r);
26
+ } catch (e) {
27
+ r(e);
28
+ }
29
+ }
30
+ }, g = class {
31
+ handlers = /* @__PURE__ */ new Map();
32
+ register(e, t) {
33
+ if (this.handlers.has(e)) throw Error(`A handler for "${String(e)}" is already registered. Call the function returned by the previous handle() before registering a new handler.`);
34
+ return this.handlers.set(e, t), () => {
35
+ this.handlers.get(e) === t && this.handlers.delete(e);
36
+ };
37
+ }
38
+ get(e) {
39
+ return this.handlers.get(e);
40
+ }
41
+ }, _ = class {
42
+ options;
43
+ entries = [];
44
+ isDraining = !1;
45
+ constructor(e) {
46
+ this.options = e;
47
+ }
48
+ enqueue(e) {
49
+ let t = {
50
+ message: e,
51
+ timeoutId: setTimeout(() => {
52
+ this.entries.splice(this.entries.indexOf(t), 1), e.expire();
53
+ }, this.options.timeout)
54
+ };
55
+ this.entries.push(t);
56
+ }
57
+ async drain(e, t) {
58
+ if (!this.isDraining) {
59
+ this.isDraining = !0;
60
+ try {
61
+ for (; e();) {
62
+ let e = this.take();
63
+ if (!e) break;
64
+ let t = e.send();
65
+ this.options.awaitEach && await t;
66
+ }
67
+ } finally {
68
+ this.isDraining = !1;
69
+ }
70
+ t();
71
+ }
72
+ }
73
+ discardAll() {
74
+ this.entries.splice(0).forEach(({ message: e, timeoutId: t }) => {
75
+ clearTimeout(t), e.discard();
76
+ });
77
+ }
78
+ take() {
79
+ let e = this.entries.shift();
80
+ if (e) return clearTimeout(e.timeoutId), e.message;
81
+ }
82
+ }, v = class {
83
+ pending = /* @__PURE__ */ new Map();
84
+ track(e, t, n) {
85
+ let i;
86
+ return new Promise((a, o) => {
87
+ i = setTimeout(() => o(new s(r.TIMEOUT_ERROR)), n), this.pending.set(e, {
88
+ resolve: a,
89
+ reject: o
90
+ }), t();
91
+ }).finally(() => {
92
+ clearTimeout(i), this.pending.delete(e);
93
+ });
94
+ }
95
+ resolve(e, t) {
96
+ this.pending.get(String(e))?.resolve(t);
97
+ }
98
+ reject(e, t) {
99
+ this.pending.get(String(e))?.reject(t);
100
+ }
101
+ rejectAll(e) {
102
+ this.pending.forEach((t) => t.reject(e));
103
+ }
104
+ }, y = /* @__PURE__ */ new Set(["then", "toJSON"]);
105
+ function b(e, t) {
106
+ return new Proxy({ $: e }, { get(e, n) {
107
+ if (n in e) return e[n];
108
+ if (!(typeof n == "symbol" || y.has(n))) return t(n);
109
+ } });
30
110
  }
31
- class z {
32
- handlers = /* @__PURE__ */ new Map();
33
- register(i, a) {
34
- if (this.handlers.has(i))
35
- throw new Error(
36
- `A handler for "${String(i)}" is already registered. Call the function returned by the previous handle() before registering a new handler.`
37
- );
38
- return this.handlers.set(i, a), () => {
39
- this.handlers.get(i) === a && this.handlers.delete(i);
40
- };
41
- }
42
- get(i) {
43
- return this.handlers.get(i);
44
- }
111
+ // src/utils/withDefaults.ts
112
+ function x(e, t) {
113
+ let n = Object.entries(t).filter(([, e]) => e !== void 0);
114
+ return {
115
+ ...e,
116
+ ...Object.fromEntries(n)
117
+ };
45
118
  }
46
- const de = /* @__PURE__ */ new Set(["then", "toJSON"]);
47
- function K(s, i) {
48
- const a = { $: s };
49
- return new Proxy(a, {
50
- get(o, l) {
51
- if (l in o)
52
- return o[l];
53
- if (!(typeof l == "symbol" || de.has(l)))
54
- return i(l);
55
- }
56
- });
119
+ // src/utils/abortable.ts
120
+ function S(e, t) {
121
+ if (!e) return t();
122
+ if (e.aborted) return Promise.reject(e.reason);
123
+ let n = t();
124
+ return new Promise((t, r) => {
125
+ let i = () => r(e.reason);
126
+ e.addEventListener("abort", i, { once: !0 }), n.then(t, r).finally(() => e.removeEventListener("abort", i));
127
+ });
57
128
  }
58
- const Q = /* @__PURE__ */ new WeakSet();
59
- function le(s, i = {}) {
60
- if (Q.has(s))
61
- throw new Error(
62
- "The adapter is already used by another channel. Create a separate adapter instance for each channel."
63
- );
64
- Q.add(s);
65
- const a = Object.assign(
66
- {
67
- timeout: 3e3,
68
- queueEnabled: !1,
69
- queueTimeout: 1e4,
70
- queueAwait: !1,
71
- errorIncludeStack: !1,
72
- logLevel: G.INFO,
73
- autoConnect: !0,
74
- unhandledRequests: "reject"
75
- },
76
- i
77
- ), o = new Y("RpcChannel", a.logLevel), l = (e, t) => {
78
- o.error(`Listener for "${String(t)}" threw an error`, e);
79
- }, w = new F(l), f = new F(l), N = new z(), y = {}, O = [];
80
- let b = !1, S = !1;
81
- const v = {
82
- get status() {
83
- return s.connectionStatus;
84
- },
85
- handle(e, t) {
86
- return M(e, "handle"), N.register(e, t);
87
- },
88
- on(e, t) {
89
- const c = t;
90
- return P(e) ? f.on(e, c) : w.on(e, c);
91
- },
92
- destroy() {
93
- S || (S = !0, Q.delete(s), s.destroy(), te());
94
- }
95
- };
96
- s.initLogger(a.logLevel), s.messageHandler = async function(t) {
97
- let c;
98
- try {
99
- c = se(t);
100
- } catch (k) {
101
- $(k, t);
102
- return;
103
- }
104
- const { type: E, message: C } = c;
105
- if (E === W.RESPONSE) {
106
- D(C);
107
- return;
108
- }
109
- if (E === W.REQUEST) {
110
- await q(C);
111
- return;
112
- }
113
- await n(C);
114
- }, s.connectionHandler = async function(t) {
115
- if (o.debug(`Connection status changed to ${t}`), f.emit("rpc.status", [t]), t === T.CONNECTED) {
116
- await re();
117
- return;
118
- }
119
- f.emit("rpc.disconnected", []);
120
- }, s.connectionLostHandler = function() {
121
- p(new h(g.CONNECTION_LOST));
122
- }, a.autoConnect && L();
123
- async function L() {
124
- try {
125
- await s.connect();
126
- } catch (e) {
127
- o.error("The adapter could not connect", e);
128
- }
129
- }
130
- function m() {
131
- if (S)
132
- throw new h({ code: g.NOT_CONNECTED, message: "The channel was destroyed" });
133
- }
134
- function P(e) {
135
- return A(e);
136
- }
137
- function $(e, t) {
138
- o.warn(`Received an invalid message: ${e.reason}`, t), f.emit("rpc.error", [e]), e.isResponse || s.sendMessage({ jsonrpc: "2.0", id: e.requestId, error: e.toJSON() });
139
- }
140
- function D(e) {
141
- if (ce(e)) {
142
- j(e);
143
- return;
144
- }
145
- o.debug("Received successful response", e), y[String(e.id)]?.resolve(e.result);
146
- }
147
- function j(e) {
148
- const t = new h(e.error);
149
- if (e.id === null) {
150
- o.warn("Received an error response that cannot be assigned to a request", t), f.emit("rpc.error", [t]);
151
- return;
152
- }
153
- o.debug("Received error response", e), y[e.id]?.reject(t);
154
- }
155
- async function q(e) {
156
- const t = await x(e);
157
- try {
158
- s.sendMessage(t);
159
- } catch (c) {
160
- o.error(`Could not send the response to "${String(e.method)}"`, c), s.sendMessage(R(e, _(g.INTERNAL_ERROR, c)));
161
- }
162
- }
163
- function _(e, t) {
164
- return new h(
165
- { code: e, message: ie[e], data: t },
166
- a.errorIncludeStack
167
- );
168
- }
169
- async function x(e) {
170
- if (A(e.method))
171
- return R(e, new h(g.METHOD_NOT_FOUND));
172
- const t = N.get(e.method);
173
- if (!t && a.unhandledRequests === "reject")
174
- return R(e, new h(g.METHOD_NOT_FOUND));
175
- if (!Array.isArray(e.params))
176
- return R(e, new h(g.INVALID_PARAMS));
177
- if (w.emit(e.method, e.params), !t)
178
- return R(e, new h(g.METHOD_NOT_FOUND));
179
- try {
180
- const c = await t(...e.params);
181
- return { jsonrpc: "2.0", id: e.id, result: c ?? null };
182
- } catch (c) {
183
- return R(e, B(c));
184
- }
185
- }
186
- function R(e, t) {
187
- return { jsonrpc: "2.0", id: e.id, error: t.toJSON() };
188
- }
189
- function B(e) {
190
- return e instanceof h && ae(e.code) ? e : _(g.SERVER_ERROR, e);
191
- }
192
- async function n(e) {
193
- const t = String(e.method);
194
- if (A(e.method)) {
195
- o.debug(`Ignoring notification "${t}": method names starting with "rpc." are reserved`);
196
- return;
197
- }
198
- if (!Array.isArray(e.params)) {
199
- o.warn(`Ignoring notification "${t}": named params are not supported`);
200
- return;
201
- }
202
- w.emit(e.method, e.params);
203
- try {
204
- await N.get(e.method)?.(...e.params);
205
- } catch (c) {
206
- o.error(`Handler for notification "${t}" threw an error`, c);
207
- }
208
- }
209
- function r(e, t) {
210
- if (M(e, "call"), m(), s.connectionStatus === T.CONNECTED)
211
- return u(e, t);
212
- if (a.queueEnabled)
213
- return Z(e, t);
214
- throw new h(g.NOT_CONNECTED);
215
- }
216
- function d(e, t) {
217
- if (M(e, "notify"), m(), s.connectionStatus === T.CONNECTED) {
218
- I(e, t);
219
- return;
220
- }
221
- if (a.queueEnabled) {
222
- ee(e, t);
223
- return;
224
- }
225
- throw new h(g.NOT_CONNECTED);
226
- }
227
- function u(e, t) {
228
- const c = ue(), E = {
229
- id: c,
230
- method: e,
231
- params: t,
232
- jsonrpc: "2.0"
233
- };
234
- let C;
235
- return new Promise((k, V) => {
236
- C = setTimeout(() => V(new h(g.TIMEOUT_ERROR)), a.timeout), y[c] = { resolve: k, reject: V }, s.sendMessage(E);
237
- }).finally(() => {
238
- clearTimeout(C), delete y[c];
239
- });
240
- }
241
- function p(e) {
242
- Object.values(y).forEach((t) => t.reject(e));
243
- }
244
- async function H(e, t) {
245
- return await u(e, t);
246
- }
247
- function I(e, t) {
248
- s.sendMessage({ jsonrpc: "2.0", method: e, params: t });
249
- }
250
- function X(e, t) {
251
- try {
252
- I(e, t);
253
- } catch (c) {
254
- o.error(`Could not send the queued notification "${String(e)}"`, c);
255
- }
256
- }
257
- function Z(e, t) {
258
- return new Promise((c, E) => {
259
- J({
260
- send: () => H(e, t).then(c, E),
261
- expire: () => E(new h(g.TIMEOUT_ERROR)),
262
- discard: () => E(new h(g.CONNECTION_LOST))
263
- });
264
- });
265
- }
266
- function ee(e, t) {
267
- const c = String(e);
268
- J({
269
- send: () => (X(e, t), Promise.resolve()),
270
- expire: () => o.warn(`Dropped notification "${c}": no connection within queueTimeout`),
271
- discard: () => o.warn(`Dropped notification "${c}": the channel was destroyed`)
272
- });
273
- }
274
- function J(e) {
275
- const t = {
276
- message: e,
277
- timeoutId: setTimeout(() => {
278
- O.splice(O.indexOf(t), 1), e.expire();
279
- }, a.queueTimeout)
280
- };
281
- O.push(t);
282
- }
283
- function ne() {
284
- const e = O.shift();
285
- if (e)
286
- return clearTimeout(e.timeoutId), e.message;
287
- }
288
- function te() {
289
- O.splice(0).forEach(({ message: e, timeoutId: t }) => {
290
- clearTimeout(t), e.discard();
291
- });
292
- }
293
- async function re() {
294
- if (!b) {
295
- b = !0;
296
- try {
297
- for (; s.connectionStatus === T.CONNECTED; ) {
298
- const e = ne();
299
- if (!e)
300
- break;
301
- const t = e.send();
302
- a.queueAwait && await t;
303
- }
304
- } finally {
305
- b = !1;
306
- }
307
- s.connectionStatus === T.CONNECTED && f.emit("rpc.connected", []);
308
- }
309
- }
310
- function oe(e) {
311
- return Object.assign((...E) => r(e, E), { notify: (...E) => {
312
- d(e, E);
313
- } });
314
- }
315
- return K(v, (e) => oe(e));
129
+ // src/createRpcChannel.ts
130
+ var C = {
131
+ timeout: 3e3,
132
+ queueEnabled: !1,
133
+ queueTimeout: 1e4,
134
+ queueAwait: !1,
135
+ errorIncludeStack: !1,
136
+ logLevel: f.INFO,
137
+ autoConnect: !0,
138
+ unhandledRequests: "reject"
139
+ }, w = /* @__PURE__ */ new WeakSet();
140
+ function T(e) {
141
+ return x(C, e);
316
142
  }
317
- const U = /* @__PURE__ */ new WeakSet();
318
- function we(s, i = {}) {
319
- if (U.has(s))
320
- throw new Error(
321
- "The hub adapter is already used by another hub. Create a separate hub adapter instance for each hub."
322
- );
323
- U.add(s);
324
- const a = i.logLevel ?? G.INFO, o = new Y("RpcHub", a), l = new F((n, r) => {
325
- o.error(`Listener for "${r}" threw an error`, n);
326
- }), w = new z(), f = /* @__PURE__ */ new Map(), N = /* @__PURE__ */ new Set();
327
- let y = !1;
328
- s.initLogger(a), s.peerHandler = (n) => void b(n), s.peerLostHandler = L, (i.autoConnect ?? !0) && O();
329
- async function O() {
330
- try {
331
- await s.connect();
332
- } catch (n) {
333
- o.error("The hub adapter could not connect", n);
334
- }
335
- }
336
- async function b({ id: n, adapter: r }) {
337
- if (y) {
338
- o.warn(`Rejected peer "${n}": the hub was destroyed`), r.destroy();
339
- return;
340
- }
341
- const d = le(
342
- r,
343
- { ...i, autoConnect: !1 }
344
- ), u = { peer: { id: n, channel: d }, detachments: /* @__PURE__ */ new Map(), joined: !1 };
345
- f.set(n, u), N.forEach((p) => P(u, p)), d.$.on("rpc.connected", () => v(u)), await S(r), d.$.status === T.CONNECTED && v(u);
346
- }
347
- async function S(n) {
348
- try {
349
- await n.connect();
350
- } catch (r) {
351
- o.error("A peer adapter could not connect", r);
352
- }
353
- }
354
- function v(n) {
355
- n.joined || (n.joined = !0, o.debug(`Peer "${n.peer.id}" connected`), l.emit("rpc.peer.connected", [n.peer]));
356
- }
357
- function L(n) {
358
- const r = f.get(n);
359
- r && (f.delete(n), r.peer.channel.$.destroy(), r.joined && (o.debug(`Peer "${n}" disconnected`), l.emit("rpc.peer.disconnected", [r.peer])));
360
- }
361
- function m() {
362
- return [...f.values()].filter((n) => n.joined).map((n) => n.peer);
363
- }
364
- function P(n, r) {
365
- n.detachments.set(r, r(n.peer));
366
- }
367
- function $(n) {
368
- return N.add(n), f.forEach((r) => P(r, n)), () => {
369
- N.delete(n), f.forEach((r) => {
370
- r.detachments.get(n)?.(), r.detachments.delete(n);
371
- });
372
- };
373
- }
374
- function D() {
375
- if (y)
376
- throw new h({ code: g.NOT_CONNECTED, message: "The hub was destroyed" });
377
- }
378
- function j(n, r) {
379
- return Reflect.get(n.channel, r);
380
- }
381
- function q(n, r, d) {
382
- try {
383
- return j(n, r)(...d);
384
- } catch (u) {
385
- return Promise.reject(u);
386
- }
387
- }
388
- function _(n, r, d) {
389
- const u = q(n, r, d);
390
- return u.catch((p) => {
391
- o.debug(`Broadcast of "${r}" to peer "${n.id}" failed`, p);
392
- }), Object.assign(u, { peer: n });
393
- }
394
- function x(n, r, d) {
395
- try {
396
- j(n, r).notify(...d);
397
- } catch (u) {
398
- o.warn(`Could not notify peer "${n.id}" of "${r}"`, u);
399
- }
400
- }
401
- function R(n) {
402
- return Object.assign((...u) => (M(n, "call"), D(), m().map((p) => _(p, n, u))), { notify: (...u) => {
403
- M(n, "notify"), D(), m().forEach((p) => x(p, n, u));
404
- } });
405
- }
406
- return K({
407
- get peers() {
408
- return m();
409
- },
410
- peer(n) {
411
- const r = f.get(n);
412
- return r?.joined ? r.peer : void 0;
413
- },
414
- handle(n, r) {
415
- M(n, "handle");
416
- const d = r, u = w.register(n, r), p = $(
417
- (H) => H.channel.$.handle(n, ((...I) => d({ peer: H }, ...I)))
418
- );
419
- return () => {
420
- p(), u();
421
- };
422
- },
423
- on(n, r) {
424
- return A(n) ? l.on(n, r) : $(
425
- (d) => d.channel.$.on(n, (...u) => r({ peer: d }, ...u))
426
- );
427
- },
428
- destroy() {
429
- if (!y) {
430
- y = !0, U.delete(s);
431
- for (const n of [...f.keys()])
432
- L(n);
433
- s.destroy();
434
- }
435
- }
436
- }, R);
143
+ function E(f, p = {}) {
144
+ if (f.connectionStatus === u.DESTROYED) throw Error("The adapter was destroyed. Create a new adapter instance for the channel.");
145
+ if (w.has(f)) throw Error("The adapter is already used by another channel. Create a separate adapter instance for each channel.");
146
+ w.add(f);
147
+ let m = T(p), y = new d("RpcChannel", m.logLevel), x = (e, t) => {
148
+ y.error(`Listener for "${String(t)}" threw an error`, e);
149
+ }, C = new h(x), E = new h(x), D = new g(), O = new v(), k = new _({
150
+ timeout: m.queueTimeout,
151
+ awaitEach: m.queueAwait
152
+ }), A = f.connectionStatus, j = !1, M = {
153
+ get status() {
154
+ return f.connectionStatus;
155
+ },
156
+ handle(e, t) {
157
+ return i(e, "handle"), D.register(e, t);
158
+ },
159
+ on(e, t) {
160
+ let n = t;
161
+ return B(e) ? E.on(e, n) : C.on(e, n);
162
+ },
163
+ destroy() {
164
+ j || (L(), f.destroy());
165
+ }
166
+ };
167
+ async function N(e) {
168
+ let t;
169
+ try {
170
+ t = a(e);
171
+ } catch (t) {
172
+ ee(t, e);
173
+ return;
174
+ }
175
+ let { type: n, message: r } = t;
176
+ n === c.RESPONSE ? te(r) : n === c.REQUEST ? await H(r) : await q(r);
177
+ }
178
+ async function P(e) {
179
+ let t = A === u.CONNECTED;
180
+ A = e, y.debug(`Connection status changed to ${e}`), e === u.DESTROYED && L(), E.emit("rpc.status", [e]), e === u.CONNECTED ? await ae() : t && E.emit("rpc.disconnected", []);
181
+ }
182
+ function F() {
183
+ O.rejectAll(new s(r.CONNECTION_LOST));
184
+ }
185
+ f.bind({
186
+ onMessage: N,
187
+ onStatusChange: P,
188
+ onConnectionLost: F,
189
+ logLevel: m.logLevel
190
+ }), m.autoConnect && I();
191
+ async function I() {
192
+ try {
193
+ await f.connect();
194
+ } catch (e) {
195
+ y.error("The adapter could not connect", e);
196
+ }
197
+ }
198
+ function L() {
199
+ j = !0, k.discardAll();
200
+ }
201
+ function R() {
202
+ return f.connectionStatus === u.CONNECTED;
203
+ }
204
+ function z() {
205
+ if (j) throw new s({
206
+ code: r.NOT_CONNECTED,
207
+ message: "The channel was destroyed"
208
+ });
209
+ }
210
+ function B(e) {
211
+ return n(e);
212
+ }
213
+ function ee(e, t) {
214
+ y.warn(`Received an invalid message: ${e.reason}`, t), E.emit("rpc.error", [e]), e.isResponse || f.sendMessage({
215
+ jsonrpc: "2.0",
216
+ id: e.requestId,
217
+ error: e.toJSON()
218
+ });
219
+ }
220
+ function te(t) {
221
+ e(t) ? V(t) : (y.debug("Received successful response", t), O.resolve(t.id, t.result));
222
+ }
223
+ function V(e) {
224
+ let t = new s(e.error);
225
+ e.id === null ? (y.warn("Received an error response that cannot be assigned to a request", t), E.emit("rpc.error", [t])) : (y.debug("Received error response", e), O.reject(e.id, t));
226
+ }
227
+ async function H(e) {
228
+ let t = await W(e);
229
+ try {
230
+ f.sendMessage(t);
231
+ } catch (t) {
232
+ y.error(`Could not send the response to "${String(e.method)}"`, t), f.sendMessage(G(e, U(r.INTERNAL_ERROR, t)));
233
+ }
234
+ }
235
+ function U(e, n) {
236
+ return new s({
237
+ code: e,
238
+ message: t[e],
239
+ data: n
240
+ }, m.errorIncludeStack);
241
+ }
242
+ async function W(e) {
243
+ if (n(e.method)) return G(e, new s(r.METHOD_NOT_FOUND));
244
+ let t = D.get(e.method);
245
+ if (!t && m.unhandledRequests === "reject") return G(e, new s(r.METHOD_NOT_FOUND));
246
+ if (!Array.isArray(e.params)) return G(e, new s(r.INVALID_PARAMS));
247
+ if (C.emit(e.method, e.params), !t) return G(e, new s(r.METHOD_NOT_FOUND));
248
+ try {
249
+ let n = await t(...e.params);
250
+ return {
251
+ jsonrpc: "2.0",
252
+ id: e.id,
253
+ result: n ?? null
254
+ };
255
+ } catch (t) {
256
+ return G(e, K(t));
257
+ }
258
+ }
259
+ function G(e, t) {
260
+ return {
261
+ jsonrpc: "2.0",
262
+ id: e.id,
263
+ error: t.toJSON()
264
+ };
265
+ }
266
+ function K(e) {
267
+ return e instanceof s && o(e.code) ? e : U(r.SERVER_ERROR, e);
268
+ }
269
+ async function q(e) {
270
+ let t = String(e.method);
271
+ if (n(e.method)) y.debug(`Ignoring notification "${t}": method names starting with "rpc." are reserved`);
272
+ else if (!Array.isArray(e.params)) y.warn(`Ignoring notification "${t}": named params are not supported`);
273
+ else {
274
+ C.emit(e.method, e.params);
275
+ try {
276
+ await D.get(e.method)?.(...e.params);
277
+ } catch (e) {
278
+ y.error(`Handler for notification "${t}" threw an error`, e);
279
+ }
280
+ }
281
+ }
282
+ function J(e, t, n) {
283
+ return i(e, "call"), z(), S(n.signal, () => Y(e, t, n));
284
+ }
285
+ function Y(e, t, n) {
286
+ if (R()) return Z(e, t, n);
287
+ if (m.queueEnabled) return $(e, t, n);
288
+ throw new s(r.NOT_CONNECTED);
289
+ }
290
+ function X(e, t) {
291
+ if (i(e, "notify"), z(), R()) Q(e, t);
292
+ else if (m.queueEnabled) ie(e, t);
293
+ else throw new s(r.NOT_CONNECTED);
294
+ }
295
+ function Z(e, t, n) {
296
+ let r = l(), i = {
297
+ id: r,
298
+ method: e,
299
+ params: t,
300
+ jsonrpc: "2.0"
301
+ };
302
+ return O.track(r, () => f.sendMessage(i), n.timeout ?? m.timeout);
303
+ }
304
+ async function ne(e, t, n) {
305
+ return n.signal?.throwIfAborted(), await Z(e, t, n);
306
+ }
307
+ function Q(e, t) {
308
+ f.sendMessage({
309
+ jsonrpc: "2.0",
310
+ method: e,
311
+ params: t
312
+ });
313
+ }
314
+ function re(e, t) {
315
+ try {
316
+ Q(e, t);
317
+ } catch (t) {
318
+ y.error(`Could not send the queued notification "${String(e)}"`, t);
319
+ }
320
+ }
321
+ function $(e, t, n) {
322
+ return new Promise((i, a) => {
323
+ k.enqueue({
324
+ send: () => ne(e, t, n).then(i, a),
325
+ expire: () => a(new s(r.TIMEOUT_ERROR)),
326
+ discard: () => a(new s(r.CONNECTION_LOST))
327
+ });
328
+ });
329
+ }
330
+ function ie(e, t) {
331
+ let n = String(e);
332
+ k.enqueue({
333
+ send: () => (re(e, t), Promise.resolve()),
334
+ expire: () => y.warn(`Dropped notification "${n}": no connection within queueTimeout`),
335
+ discard: () => y.warn(`Dropped notification "${n}": the channel was destroyed`)
336
+ });
337
+ }
338
+ async function ae() {
339
+ await k.drain(R, oe);
340
+ }
341
+ function oe() {
342
+ R() && E.emit("rpc.connected", []);
343
+ }
344
+ function se(e) {
345
+ let t = (t) => (...n) => J(e, n, t);
346
+ return Object.assign(t({}), {
347
+ notify: (...t) => {
348
+ X(e, t);
349
+ },
350
+ with: t
351
+ });
352
+ }
353
+ return b(M, (e) => se(e));
437
354
  }
438
- export {
439
- ye as AbstractRpcAdapter,
440
- Ne as AbstractRpcHubAdapter,
441
- T as ConnectionStatus,
442
- G as LogLevel,
443
- h as RpcError,
444
- g as RpcErrorCode,
445
- le as createRpcChannel,
446
- we as createRpcHub
447
- };
355
+ // src/createRpcHub.ts
356
+ var D = /* @__PURE__ */ new WeakSet();
357
+ function O(e, t = {}) {
358
+ if (D.has(e)) throw Error("The hub adapter is already used by another hub. Create a separate hub adapter instance for each hub.");
359
+ D.add(e);
360
+ let a = T(t), o = new d("RpcHub", a.logLevel), c = new h((e, t) => {
361
+ o.error(`Listener for "${t}" threw an error`, e);
362
+ }), l = new g(), f = /* @__PURE__ */ new Map(), p = /* @__PURE__ */ new Set(), m = !1;
363
+ e.bind({
364
+ onPeer: (e) => void v(e),
365
+ onPeerLost: S,
366
+ logLevel: a.logLevel
367
+ }), a.autoConnect && _();
368
+ async function _() {
369
+ try {
370
+ await e.connect();
371
+ } catch (e) {
372
+ o.error("The hub adapter could not connect", e);
373
+ }
374
+ }
375
+ async function v({ id: e, adapter: t, context: n }) {
376
+ if (m) {
377
+ o.warn(`Rejected peer "${e}": the hub was destroyed`), t.destroy();
378
+ return;
379
+ }
380
+ let r = E(t, {
381
+ ...a,
382
+ autoConnect: !1
383
+ }), i = {
384
+ peer: {
385
+ id: e,
386
+ channel: r,
387
+ context: n
388
+ },
389
+ detachments: /* @__PURE__ */ new Map(),
390
+ joined: !1
391
+ };
392
+ f.set(e, i), p.forEach((e) => w(i, e)), r.$.on("rpc.connected", () => x(i)), r.$.on("rpc.status", (t) => {
393
+ t === u.DESTROYED && S(e);
394
+ }), await y(t), r.$.status === u.CONNECTED && x(i);
395
+ }
396
+ async function y(e) {
397
+ try {
398
+ await e.connect();
399
+ } catch (e) {
400
+ o.error("A peer adapter could not connect", e);
401
+ }
402
+ }
403
+ function x(e) {
404
+ e.joined || (e.joined = !0, o.debug(`Peer "${e.peer.id}" connected`), c.emit("rpc.peer.connected", [e.peer]));
405
+ }
406
+ function S(e) {
407
+ let t = f.get(e);
408
+ t && (f.delete(e), t.peer.channel.$.destroy(), t.joined && (o.debug(`Peer "${e}" disconnected`), c.emit("rpc.peer.disconnected", [t.peer])));
409
+ }
410
+ function C() {
411
+ return [...f.values()].filter((e) => e.joined).map((e) => e.peer);
412
+ }
413
+ function w(e, t) {
414
+ e.detachments.set(t, t(e.peer));
415
+ }
416
+ function O(e) {
417
+ return p.add(e), f.forEach((t) => w(t, e)), () => {
418
+ p.delete(e), f.forEach((t) => {
419
+ t.detachments.get(e)?.(), t.detachments.delete(e);
420
+ });
421
+ };
422
+ }
423
+ function k() {
424
+ if (m) throw new s({
425
+ code: r.NOT_CONNECTED,
426
+ message: "The hub was destroyed"
427
+ });
428
+ }
429
+ function A(e, t) {
430
+ return Reflect.get(e.channel, t);
431
+ }
432
+ function j(e, t, n, r) {
433
+ try {
434
+ return A(e, t).with(r)(...n);
435
+ } catch (e) {
436
+ return Promise.reject(e);
437
+ }
438
+ }
439
+ function M(e, t, n, r) {
440
+ let i = j(e, t, n, r);
441
+ return i.catch((n) => {
442
+ o.debug(`Broadcast of "${t}" to peer "${e.id}" failed`, n);
443
+ }), Object.assign(i, { peer: e });
444
+ }
445
+ function N(e, t, n) {
446
+ try {
447
+ A(e, t).notify(...n);
448
+ } catch (n) {
449
+ o.warn(`Could not notify peer "${e.id}" of "${t}"`, n);
450
+ }
451
+ }
452
+ function P(e) {
453
+ let t = (t) => (...n) => (i(e, "call"), k(), C().map((r) => M(r, e, n, t)));
454
+ return Object.assign(t({}), {
455
+ notify: (...t) => {
456
+ i(e, "notify"), k(), C().forEach((n) => N(n, e, t));
457
+ },
458
+ with: t
459
+ });
460
+ }
461
+ return b({
462
+ get peers() {
463
+ return C();
464
+ },
465
+ peer(e) {
466
+ let t = f.get(e);
467
+ return t?.joined ? t.peer : void 0;
468
+ },
469
+ handle(e, t) {
470
+ i(e, "handle");
471
+ let n = t, r = l.register(e, t), a = O((t) => t.channel.$.handle(e, ((...e) => n({ peer: t }, ...e))));
472
+ return () => {
473
+ a(), r();
474
+ };
475
+ },
476
+ on(e, t) {
477
+ return n(e) ? c.on(e, t) : O((n) => n.channel.$.on(e, (...e) => t({ peer: n }, ...e)));
478
+ },
479
+ destroy() {
480
+ if (!m) {
481
+ m = !0, D.delete(e);
482
+ for (let e of [...f.keys()]) S(e);
483
+ e.destroy();
484
+ }
485
+ }
486
+ }, P);
487
+ }
488
+ export { p as AbstractRpcAdapter, m as AbstractRpcHubAdapter, u as ConnectionStatus, f as LogLevel, s as RpcError, r as RpcErrorCode, E as createRpcChannel, O as createRpcHub };
489
+
490
+ //# sourceMappingURL=index.js.map