@schwarzdavid/anyrpc 0.0.0-stage → 0.0.2-alpha.1

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 (227) hide show
  1. package/README.md +551 -3
  2. package/dist/child-process.cjs +1 -0
  3. package/dist/child-process.js +134 -0
  4. package/dist/chunks/AbstractRpcAdapter-7gOLZtYD.js +82 -0
  5. package/dist/chunks/AbstractRpcAdapter-BPIitR0A.cjs +1 -0
  6. package/dist/chunks/AbstractRpcHubAdapter-BVPYUoL9.js +26 -0
  7. package/dist/chunks/AbstractRpcHubAdapter-Bqcrs7Mb.cjs +1 -0
  8. package/dist/chunks/ControlProtocol-0b5_21ZU.js +82 -0
  9. package/dist/chunks/ControlProtocol-BMvwQecN.cjs +1 -0
  10. package/dist/chunks/handshake-CWtm9Y59.cjs +1 -0
  11. package/dist/chunks/handshake-CZWqKvZe.js +39 -0
  12. package/dist/chunks/index-B_SfPYCc.js +133 -0
  13. package/dist/chunks/index-D5LbDuYg.cjs +1 -0
  14. package/dist/chunks/rpc-Brf2MoZo.cjs +1 -0
  15. package/dist/chunks/rpc-DeJEGj4-.js +134 -0
  16. package/dist/chunks/uuid-C2SCOpSM.cjs +1 -0
  17. package/dist/chunks/uuid-DTlgoKBw.js +9 -0
  18. package/dist/constants/JSON_RPC_ERRORS.d.ts +19 -0
  19. package/dist/constants/JSON_RPC_ERRORS.d.ts.map +1 -0
  20. package/dist/createRpcChannel.d.ts +18 -0
  21. package/dist/createRpcChannel.d.ts.map +1 -0
  22. package/dist/createRpcHub.d.ts +7 -0
  23. package/dist/createRpcHub.d.ts.map +1 -0
  24. package/dist/iframe.cjs +1 -0
  25. package/dist/iframe.js +80 -0
  26. package/dist/index.cjs +1 -0
  27. package/dist/index.d.ts +14 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +447 -0
  30. package/dist/lib/ControlProtocol.d.ts +20 -0
  31. package/dist/lib/ControlProtocol.d.ts.map +1 -0
  32. package/dist/lib/EventEmitter.d.ts +12 -0
  33. package/dist/lib/EventEmitter.d.ts.map +1 -0
  34. package/dist/lib/HandlerRegistry.d.ts +8 -0
  35. package/dist/lib/HandlerRegistry.d.ts.map +1 -0
  36. package/dist/lib/Heartbeat.d.ts +24 -0
  37. package/dist/lib/Heartbeat.d.ts.map +1 -0
  38. package/dist/lib/Logger.d.ts +13 -0
  39. package/dist/lib/Logger.d.ts.map +1 -0
  40. package/dist/lib/RpcError.d.ts +11 -0
  41. package/dist/lib/RpcError.d.ts.map +1 -0
  42. package/dist/lib/RpcMessageError.d.ts +15 -0
  43. package/dist/lib/RpcMessageError.d.ts.map +1 -0
  44. package/dist/lib/adapter/AbstractRpcAdapter.d.ts +28 -0
  45. package/dist/lib/adapter/AbstractRpcAdapter.d.ts.map +1 -0
  46. package/dist/lib/adapter/AbstractRpcHubAdapter.d.ts +24 -0
  47. package/dist/lib/adapter/AbstractRpcHubAdapter.d.ts.map +1 -0
  48. package/dist/lib/adapter/child-process/ChildProcessClientAdapter.d.ts +19 -0
  49. package/dist/lib/adapter/child-process/ChildProcessClientAdapter.d.ts.map +1 -0
  50. package/dist/lib/adapter/child-process/ChildProcessHostAdapter.d.ts +43 -0
  51. package/dist/lib/adapter/child-process/ChildProcessHostAdapter.d.ts.map +1 -0
  52. package/dist/lib/adapter/child-process/constants/childProcessHandshake.d.ts +3 -0
  53. package/dist/lib/adapter/child-process/constants/childProcessHandshake.d.ts.map +1 -0
  54. package/dist/lib/adapter/child-process/index.d.ts +4 -0
  55. package/dist/lib/adapter/child-process/index.d.ts.map +1 -0
  56. package/dist/lib/adapter/child-process/utils/currentProcess.d.ts +16 -0
  57. package/dist/lib/adapter/child-process/utils/currentProcess.d.ts.map +1 -0
  58. package/dist/lib/adapter/child-process/utils/ipcEnvelope.d.ts +7 -0
  59. package/dist/lib/adapter/child-process/utils/ipcEnvelope.d.ts.map +1 -0
  60. package/dist/lib/adapter/iframe/IFrameClientAdapter.d.ts +17 -0
  61. package/dist/lib/adapter/iframe/IFrameClientAdapter.d.ts.map +1 -0
  62. package/dist/lib/adapter/iframe/IFrameHostAdapter.d.ts +20 -0
  63. package/dist/lib/adapter/iframe/IFrameHostAdapter.d.ts.map +1 -0
  64. package/dist/lib/adapter/iframe/constants/iframeHandshake.d.ts +3 -0
  65. package/dist/lib/adapter/iframe/constants/iframeHandshake.d.ts.map +1 -0
  66. package/dist/lib/adapter/iframe/index.d.ts +5 -0
  67. package/dist/lib/adapter/iframe/index.d.ts.map +1 -0
  68. package/dist/lib/adapter/iframe/utils/iframeOrigin.d.ts +5 -0
  69. package/dist/lib/adapter/iframe/utils/iframeOrigin.d.ts.map +1 -0
  70. package/dist/lib/adapter/message-port/AbstractMessagePortAdapter.d.ts +38 -0
  71. package/dist/lib/adapter/message-port/AbstractMessagePortAdapter.d.ts.map +1 -0
  72. package/dist/lib/adapter/message-port/AbstractMessagePortClientAdapter.d.ts +22 -0
  73. package/dist/lib/adapter/message-port/AbstractMessagePortClientAdapter.d.ts.map +1 -0
  74. package/dist/lib/adapter/message-port/AbstractMessagePortHostAdapter.d.ts +20 -0
  75. package/dist/lib/adapter/message-port/AbstractMessagePortHostAdapter.d.ts.map +1 -0
  76. package/dist/lib/adapter/message-port/index.d.ts +6 -0
  77. package/dist/lib/adapter/message-port/index.d.ts.map +1 -0
  78. package/dist/lib/adapter/message-port/utils/handshake.d.ts +13 -0
  79. package/dist/lib/adapter/message-port/utils/handshake.d.ts.map +1 -0
  80. package/dist/lib/adapter/message-port/utils/messageData.d.ts +2 -0
  81. package/dist/lib/adapter/message-port/utils/messageData.d.ts.map +1 -0
  82. package/dist/lib/adapter/node-worker/NodeWorkerClientAdapter.d.ts +12 -0
  83. package/dist/lib/adapter/node-worker/NodeWorkerClientAdapter.d.ts.map +1 -0
  84. package/dist/lib/adapter/node-worker/NodeWorkerHostAdapter.d.ts +35 -0
  85. package/dist/lib/adapter/node-worker/NodeWorkerHostAdapter.d.ts.map +1 -0
  86. package/dist/lib/adapter/node-worker/constants/nodeWorkerHandshake.d.ts +3 -0
  87. package/dist/lib/adapter/node-worker/constants/nodeWorkerHandshake.d.ts.map +1 -0
  88. package/dist/lib/adapter/node-worker/index.d.ts +4 -0
  89. package/dist/lib/adapter/node-worker/index.d.ts.map +1 -0
  90. package/dist/lib/adapter/node-worker/utils/initEnvelope.d.ts +13 -0
  91. package/dist/lib/adapter/node-worker/utils/initEnvelope.d.ts.map +1 -0
  92. package/dist/lib/adapter/socket/AbstractSocketAdapter.d.ts +23 -0
  93. package/dist/lib/adapter/socket/AbstractSocketAdapter.d.ts.map +1 -0
  94. package/dist/lib/adapter/socket/index.d.ts +3 -0
  95. package/dist/lib/adapter/socket/index.d.ts.map +1 -0
  96. package/dist/lib/adapter/socket/utils/parseObject.d.ts +2 -0
  97. package/dist/lib/adapter/socket/utils/parseObject.d.ts.map +1 -0
  98. package/dist/lib/adapter/web-worker/SharedWorkerHubAdapter.d.ts +18 -0
  99. package/dist/lib/adapter/web-worker/SharedWorkerHubAdapter.d.ts.map +1 -0
  100. package/dist/lib/adapter/web-worker/SharedWorkerPeerAdapter.d.ts +18 -0
  101. package/dist/lib/adapter/web-worker/SharedWorkerPeerAdapter.d.ts.map +1 -0
  102. package/dist/lib/adapter/web-worker/WebWorkerClientAdapter.d.ts +10 -0
  103. package/dist/lib/adapter/web-worker/WebWorkerClientAdapter.d.ts.map +1 -0
  104. package/dist/lib/adapter/web-worker/WebWorkerHostAdapter.d.ts +33 -0
  105. package/dist/lib/adapter/web-worker/WebWorkerHostAdapter.d.ts.map +1 -0
  106. package/dist/lib/adapter/web-worker/constants/webWorkerHandshake.d.ts +3 -0
  107. package/dist/lib/adapter/web-worker/constants/webWorkerHandshake.d.ts.map +1 -0
  108. package/dist/lib/adapter/web-worker/index.d.ts +5 -0
  109. package/dist/lib/adapter/web-worker/index.d.ts.map +1 -0
  110. package/dist/lib/adapter/web-worker/utils/describeWorkerError.d.ts +3 -0
  111. package/dist/lib/adapter/web-worker/utils/describeWorkerError.d.ts.map +1 -0
  112. package/dist/lib/adapter/web-worker/utils/globalScope.d.ts +8 -0
  113. package/dist/lib/adapter/web-worker/utils/globalScope.d.ts.map +1 -0
  114. package/dist/lib/adapter/websocket/WebSocketClientAdapter.d.ts +27 -0
  115. package/dist/lib/adapter/websocket/WebSocketClientAdapter.d.ts.map +1 -0
  116. package/dist/lib/adapter/websocket/WebSocketHubAdapter.d.ts +21 -0
  117. package/dist/lib/adapter/websocket/WebSocketHubAdapter.d.ts.map +1 -0
  118. package/dist/lib/adapter/websocket/WebSocketPeerAdapter.d.ts +28 -0
  119. package/dist/lib/adapter/websocket/WebSocketPeerAdapter.d.ts.map +1 -0
  120. package/dist/lib/adapter/websocket/constants/webSocket.d.ts +5 -0
  121. package/dist/lib/adapter/websocket/constants/webSocket.d.ts.map +1 -0
  122. package/dist/lib/adapter/websocket/index.d.ts +5 -0
  123. package/dist/lib/adapter/websocket/index.d.ts.map +1 -0
  124. package/dist/lib/adapter/websocket/utils/reconnectDelay.d.ts +2 -0
  125. package/dist/lib/adapter/websocket/utils/reconnectDelay.d.ts.map +1 -0
  126. package/dist/message-port.cjs +1 -0
  127. package/dist/message-port.js +6 -0
  128. package/dist/node-worker.cjs +1 -0
  129. package/dist/node-worker.js +80 -0
  130. package/dist/socket.cjs +1 -0
  131. package/dist/socket.js +66 -0
  132. package/dist/types/ConnectionStatus.d.ts +6 -0
  133. package/dist/types/ConnectionStatus.d.ts.map +1 -0
  134. package/dist/types/EventEmitter.d.ts +6 -0
  135. package/dist/types/EventEmitter.d.ts.map +1 -0
  136. package/dist/types/LogLevel.d.ts +9 -0
  137. package/dist/types/LogLevel.d.ts.map +1 -0
  138. package/dist/types/MethodMap.d.ts +5 -0
  139. package/dist/types/MethodMap.d.ts.map +1 -0
  140. package/dist/types/MethodName.d.ts +9 -0
  141. package/dist/types/MethodName.d.ts.map +1 -0
  142. package/dist/types/RpcChannel.d.ts +29 -0
  143. package/dist/types/RpcChannel.d.ts.map +1 -0
  144. package/dist/types/RpcChannelEvents.d.ts +9 -0
  145. package/dist/types/RpcChannelEvents.d.ts.map +1 -0
  146. package/dist/types/RpcHub.d.ts +36 -0
  147. package/dist/types/RpcHub.d.ts.map +1 -0
  148. package/dist/types/RpcMessages.d.ts +37 -0
  149. package/dist/types/RpcMessages.d.ts.map +1 -0
  150. package/dist/utils/controlMessages.d.ts +14 -0
  151. package/dist/utils/controlMessages.d.ts.map +1 -0
  152. package/dist/utils/createMethodProxy.d.ts +5 -0
  153. package/dist/utils/createMethodProxy.d.ts.map +1 -0
  154. package/dist/utils/rpc.d.ts +26 -0
  155. package/dist/utils/rpc.d.ts.map +1 -0
  156. package/dist/utils/uuid.d.ts +2 -0
  157. package/dist/utils/uuid.d.ts.map +1 -0
  158. package/dist/web-worker.cjs +1 -0
  159. package/dist/web-worker.js +159 -0
  160. package/dist/websocket.cjs +1 -0
  161. package/dist/websocket.js +113 -0
  162. package/package.json +104 -6
  163. package/src/constants/JSON_RPC_ERRORS.ts +33 -0
  164. package/src/createRpcChannel.ts +478 -0
  165. package/src/createRpcHub.ts +242 -0
  166. package/src/index.ts +33 -0
  167. package/src/lib/ControlProtocol.ts +62 -0
  168. package/src/lib/EventEmitter.ts +42 -0
  169. package/src/lib/HandlerRegistry.ts +26 -0
  170. package/src/lib/Heartbeat.ts +55 -0
  171. package/src/lib/Logger.ts +44 -0
  172. package/src/lib/RpcError.ts +41 -0
  173. package/src/lib/RpcMessageError.ts +25 -0
  174. package/src/lib/adapter/AbstractRpcAdapter.ts +63 -0
  175. package/src/lib/adapter/AbstractRpcHubAdapter.ts +49 -0
  176. package/src/lib/adapter/child-process/ChildProcessClientAdapter.ts +89 -0
  177. package/src/lib/adapter/child-process/ChildProcessHostAdapter.ts +136 -0
  178. package/src/lib/adapter/child-process/constants/childProcessHandshake.ts +3 -0
  179. package/src/lib/adapter/child-process/index.ts +3 -0
  180. package/src/lib/adapter/child-process/utils/currentProcess.ts +27 -0
  181. package/src/lib/adapter/child-process/utils/ipcEnvelope.ts +19 -0
  182. package/src/lib/adapter/iframe/IFrameClientAdapter.ts +62 -0
  183. package/src/lib/adapter/iframe/IFrameHostAdapter.ts +55 -0
  184. package/src/lib/adapter/iframe/constants/iframeHandshake.ts +3 -0
  185. package/src/lib/adapter/iframe/index.ts +4 -0
  186. package/src/lib/adapter/iframe/utils/iframeOrigin.ts +48 -0
  187. package/src/lib/adapter/message-port/AbstractMessagePortAdapter.ts +130 -0
  188. package/src/lib/adapter/message-port/AbstractMessagePortClientAdapter.ts +88 -0
  189. package/src/lib/adapter/message-port/AbstractMessagePortHostAdapter.ts +75 -0
  190. package/src/lib/adapter/message-port/index.ts +11 -0
  191. package/src/lib/adapter/message-port/utils/handshake.ts +60 -0
  192. package/src/lib/adapter/message-port/utils/messageData.ts +3 -0
  193. package/src/lib/adapter/node-worker/NodeWorkerClientAdapter.ts +46 -0
  194. package/src/lib/adapter/node-worker/NodeWorkerHostAdapter.ts +89 -0
  195. package/src/lib/adapter/node-worker/constants/nodeWorkerHandshake.ts +3 -0
  196. package/src/lib/adapter/node-worker/index.ts +3 -0
  197. package/src/lib/adapter/node-worker/utils/initEnvelope.ts +38 -0
  198. package/src/lib/adapter/socket/AbstractSocketAdapter.ts +99 -0
  199. package/src/lib/adapter/socket/index.ts +2 -0
  200. package/src/lib/adapter/socket/utils/parseObject.ts +8 -0
  201. package/src/lib/adapter/web-worker/SharedWorkerHubAdapter.ts +90 -0
  202. package/src/lib/adapter/web-worker/SharedWorkerPeerAdapter.ts +41 -0
  203. package/src/lib/adapter/web-worker/WebWorkerClientAdapter.ts +45 -0
  204. package/src/lib/adapter/web-worker/WebWorkerHostAdapter.ts +97 -0
  205. package/src/lib/adapter/web-worker/constants/webWorkerHandshake.ts +3 -0
  206. package/src/lib/adapter/web-worker/index.ts +4 -0
  207. package/src/lib/adapter/web-worker/utils/describeWorkerError.ts +13 -0
  208. package/src/lib/adapter/web-worker/utils/globalScope.ts +15 -0
  209. package/src/lib/adapter/websocket/WebSocketClientAdapter.ts +109 -0
  210. package/src/lib/adapter/websocket/WebSocketHubAdapter.ts +45 -0
  211. package/src/lib/adapter/websocket/WebSocketPeerAdapter.ts +76 -0
  212. package/src/lib/adapter/websocket/constants/webSocket.ts +7 -0
  213. package/src/lib/adapter/websocket/index.ts +4 -0
  214. package/src/lib/adapter/websocket/utils/reconnectDelay.ts +5 -0
  215. package/src/types/ConnectionStatus.ts +6 -0
  216. package/src/types/EventEmitter.ts +8 -0
  217. package/src/types/LogLevel.ts +9 -0
  218. package/src/types/MethodMap.ts +6 -0
  219. package/src/types/MethodName.ts +13 -0
  220. package/src/types/RpcChannel.ts +53 -0
  221. package/src/types/RpcChannelEvents.ts +9 -0
  222. package/src/types/RpcHub.ts +69 -0
  223. package/src/types/RpcMessages.ts +64 -0
  224. package/src/utils/controlMessages.ts +30 -0
  225. package/src/utils/createMethodProxy.ts +24 -0
  226. package/src/utils/rpc.ts +186 -0
  227. package/src/utils/uuid.ts +10 -0
package/README.md CHANGED
@@ -1,3 +1,551 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # anyrpc
2
+
3
+ A small, fully typed, transport-agnostic RPC library for TypeScript. Define your API as plain TypeScript interfaces and call remote functions as if they were local, with `Promise`-based return values, timeouts, error propagation and connection handling built in.
4
+
5
+ Messages follow the [JSON-RPC 2.0](https://www.jsonrpc.org/specification) format (batch requests are not supported, see [JSON-RPC compliance](#json-rpc-compliance)). The transport is pluggable through adapters. Adapters for **iframe ↔ host page** and **page ↔ Web Worker** communication ship today, and more are planned.
6
+
7
+ ```ts
8
+ // Call a function in another window and await its result. Fully typed.
9
+ const size = await channel.getSize()
10
+ ```
11
+
12
+ ## Why anyrpc?
13
+
14
+ Talking to another JavaScript context, such as an iframe, a worker or a socket, usually means working with `postMessage` directly:
15
+
16
+ - **No request/response pairing.** `postMessage` is fire-and-forget. To get an answer back you have to generate message IDs, keep a map of pending promises, match replies to requests and clean up afterwards.
17
+ - **No type safety.** Payloads are `any`. Message names are stringly typed, so typos and signature mismatches between both sides show up only at runtime.
18
+ - **No error semantics.** An exception thrown on the remote side is lost unless you serialize it and send it back by hand.
19
+ - **No timeouts.** If the other side never answers, your promise never settles.
20
+ - **Connection handshake boilerplate.** An iframe may not be loaded yet when the host wants to talk to it. You need a handshake, retries, origin checks and a way to know when the other side is ready.
21
+ - **Messages from everyone.** `window.onmessage` receives messages from every frame and browser extension on the page, so you end up writing a lot of filtering code.
22
+
23
+ anyrpc takes care of all of this. You describe both directions of communication as TypeScript interfaces and get back a typed proxy object. Calling a method sends a request, and the remote handler's return value (or thrown error) comes back as the resolved (or rejected) promise.
24
+
25
+ ## Features
26
+
27
+ - 🔒 **End-to-end type safety.** Method names, parameters and return types are inferred from your interfaces.
28
+ - 🔁 **Bidirectional.** Both sides can call methods on each other over the same channel.
29
+ - ⏱️ **Timeouts.** Every request rejects with an `RpcError` if no response arrives in time.
30
+ - 📬 **Optional request queue.** Calls made before the connection is established can be queued and sent once connected.
31
+ - 🧯 **Error propagation.** Errors thrown in a remote handler are returned as JSON-RPC error responses and rejected locally as `RpcError`.
32
+ - 🔌 **Pluggable transports.** Adapters implement a small abstract class (`connect`, `sendMessage`, `destroy`), see [Custom adapters](#custom-adapters).
33
+ - 📡 **Connection events.** Listen for `rpc.connected`, `rpc.disconnected` and `rpc.status`. Pending calls reject immediately when the connection is lost.
34
+ - 📣 **Notifications.** Fire-and-forget calls for `void` methods via `channel.method.notify(...)`, observable by any number of listeners.
35
+ - 🕸️ **One-to-many hubs.** `createRpcHub` serves any number of peers (e.g. every tab connected to a `SharedWorker`) with one set of handlers, and calls or notifies all of them at once. See [Hubs](#hubs-one-to-many).
36
+
37
+ ## Adapters
38
+
39
+ - [x] **iframe** (`@schwarzdavid/anyrpc/adapters/iframe`). Uses a dedicated `MessageChannel` after a handshake, with origin allow-listing on both sides, optional heartbeat and automatic reconnects (e.g. after the iframe reloads).
40
+ - [x] **Web Worker** (`@schwarzdavid/anyrpc/adapters/web-worker`). Dedicated workers with a `MessageChannel` per channel, optional heartbeat and error logging.
41
+ - [x] **SharedWorker** (`@schwarzdavid/anyrpc/adapters/web-worker`). Every connected page becomes a peer of a [hub](#hubs-one-to-many) inside the worker, with a heartbeat that removes closed tabs.
42
+ - [ ] `ServiceWorker`
43
+ - [ ] `BroadcastChannel` (cross-tab)
44
+ - [ ] `window.open` / popup
45
+ - [x] **WebSocket** (`@schwarzdavid/anyrpc/adapters/websocket`). A client adapter with automatic reconnects for browsers and Node.js, and a hub adapter for `ws`-compatible servers, both with an optional heartbeat.
46
+ - [ ] WebRTC
47
+ - [x] **Node.js worker threads** (`@schwarzdavid/anyrpc/adapters/node-worker`). A `MessageChannel` per channel, optional heartbeat, errors of the worker are logged and its exit disconnects the channel.
48
+ - [x] **Node.js child processes** (`@schwarzdavid/anyrpc/adapters/child-process`). Uses the IPC channel of `child_process.fork()`, several channels per process, optional heartbeat, the child's exit or IPC disconnect closes the channel.
49
+
50
+ ## Getting started
51
+
52
+ ### Installation
53
+
54
+ ```bash
55
+ npm install @schwarzdavid/anyrpc
56
+ ```
57
+
58
+ > anyrpc has not been published to npm yet. Until it is, install it straight from GitHub:
59
+ > `npm install github:schwarzdavid/anyrpc`
60
+
61
+ ### 1. Define your API contract
62
+
63
+ Create a shared file that describes what each side can call on the other:
64
+
65
+ ```ts
66
+ // messages.ts
67
+ export interface HostToIFrame {
68
+ ping(): void
69
+ getTitle(): string
70
+ }
71
+
72
+ export interface IFrameToHost {
73
+ pong(): void
74
+ size(width: number, height: number): void
75
+ }
76
+ ```
77
+
78
+ ### 2. Set up the host page
79
+
80
+ ```ts
81
+ // host.ts
82
+ import { createRpcChannel } from '@schwarzdavid/anyrpc'
83
+ import { IFrameHostAdapter } from '@schwarzdavid/anyrpc/adapters/iframe'
84
+ import type { HostToIFrame, IFrameToHost } from './messages'
85
+
86
+ const iframe = document.querySelector('iframe')!
87
+
88
+ // createRpcChannel<MethodsICanCall, MethodsICanHandle>
89
+ const channel = createRpcChannel<HostToIFrame, IFrameToHost>(new IFrameHostAdapter(iframe, 'my-app'))
90
+
91
+ // Answer calls coming from the iframe
92
+ channel.$.handle('pong', () => console.log('pong received'))
93
+
94
+ // Observe calls and notifications coming from the iframe
95
+ channel.$.on('size', (width, height) => {
96
+ console.log(`iframe is ${width}x${height}`)
97
+ })
98
+
99
+ // Call methods inside the iframe
100
+ channel.$.on('rpc.connected', async () => {
101
+ await channel.ping()
102
+ const title = await channel.getTitle() // typed as string
103
+ })
104
+ ```
105
+
106
+ ### 3. Set up the iframe
107
+
108
+ ```ts
109
+ // iframe.ts
110
+ import { createRpcChannel } from '@schwarzdavid/anyrpc'
111
+ import { IFrameClientAdapter } from '@schwarzdavid/anyrpc/adapters/iframe'
112
+ import type { HostToIFrame, IFrameToHost } from './messages'
113
+
114
+ const channel = createRpcChannel<IFrameToHost, HostToIFrame>(
115
+ new IFrameClientAdapter('my-app', { origin: 'https://host.example.com' }),
116
+ )
117
+
118
+ channel.$.handle('ping', () => console.log('ping received'))
119
+ channel.$.handle('getTitle', () => document.title) // return value is sent back to the caller
120
+
121
+ await channel.pong() // request: resolves once the host has handled it
122
+ channel.size.notify(window.innerWidth, window.innerHeight) // notification: fire-and-forget, no response
123
+ ```
124
+
125
+ Both adapters must use the same **name** (`'my-app'` above). This lets several independent channels share one page.
126
+
127
+ ### Channel API
128
+
129
+ | Member | Description |
130
+ | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
131
+ | `channel.<method>(...args)` | Calls a remote method (JSON-RPC request). Always returns a `Promise` of the method's return type. |
132
+ | `channel.<method>.notify(...args)` | Sends a JSON-RPC notification: fire-and-forget, returns `void`. Only available for methods returning `void` or `Promise<void>`. |
133
+ | `channel.$.handle(name, fn)` | Answers incoming calls of `name`. Only **one** handler per method; its return value is the response. Returns a function that removes the handler. |
134
+ | `channel.$.on(name, fn)` | Observes incoming calls and notifications of `name`. Any number of listeners; return values are ignored. Returns a function that removes the listener. |
135
+ | `channel.$.on('rpc.connected' \| 'rpc.disconnected' \| 'rpc.status', fn)` | Listens for connection events. `rpc.status` receives the new `ConnectionStatus`. |
136
+ | `channel.$.on('rpc.error', fn)` | Receives an `RpcError` for every invalid incoming message and for error responses the other side could not assign to a request (`id: null`). Useful for monitoring. |
137
+ | `channel.$.status` | Current `ConnectionStatus` (`'connected'` or `'disconnected'`). |
138
+ | `channel.$.destroy()` | Closes the connection, notifies the other side if the transport supports it, rejects pending and queued calls with `-31003`, drops queued notifications and removes all listeners from the transport. Calls made afterwards throw `-31002`. |
139
+
140
+ A remote method cannot be named `$`, `then`, `toJSON`, anything starting with `rpc.` (reserved by JSON-RPC 2.0, used here for channel events) or a member of `Object.prototype` such as `toString`, `valueOf` or `hasOwnProperty`. The runtime and many libraries probe objects for exactly these names (string coercion, `JSON.stringify`, `await`, duck typing), so a proxy method that sends a request would get called by accident. `createRpcChannel` therefore rejects interfaces on either side that declare one of them with a type error naming the offending methods (`ForbiddenMethodNames<"toString">`). At runtime the proxy returns the built-in for these names, or `undefined` for `then` and `toJSON`, instead of sending a request.
141
+
142
+ ### Requests, notifications and listeners
143
+
144
+ - **Requests** (`channel.ping()`) wait for a response. If no handler is registered on the other side, the promise rejects with `-32601` (method not found).
145
+ - **Notifications** (`channel.size.notify(...)`) never get a response. On the receiving side, the handler (if any) and all `on`-listeners run; errors are only logged. Use them for events where the caller does not need a result or an acknowledgement.
146
+ - **Listeners** registered with `$.on` run for every incoming call, before the handler. Each listener is isolated: if one throws, the error is logged and neither other listeners nor the response are affected.
147
+ - For **requests without a handler**, listeners do not run by default, because the call failed for the caller. Set `unhandledRequests: 'observe'` to run them anyway (the caller still receives `-32601`).
148
+ - When the queue is enabled, notifications made while disconnected are queued as well. If no connection is established within `queueTimeout`, they are dropped with a warning.
149
+ - Queued calls survive a lost connection and are sent once the next connection is established. `channel.$.destroy()` rejects them with `-31003`. If the connection drops while the queue is being sent, the remaining calls stay queued.
150
+ - `rpc.status` is emitted as soon as the adapter reports a change. `rpc.connected` follows once the queued calls have been sent (with `queueAwait`, once they have been answered), so calls made in a `rpc.connected` listener go out after the queued ones. `rpc.disconnected` is emitted right after `rpc.status`.
151
+
152
+ ### Channel options
153
+
154
+ `createRpcChannel(adapter, options)` takes an optional second argument:
155
+
156
+ | Option | Default | Description |
157
+ | ------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
158
+ | `timeout` | `3000` | Milliseconds to wait for a response before rejecting with a timeout `RpcError`. |
159
+ | `queueEnabled` | `false` | Queue calls made while disconnected instead of rejecting them immediately. |
160
+ | `queueTimeout` | `10000` | Milliseconds a queued call may wait for a connection before it rejects. |
161
+ | `queueAwait` | `false` | Send queued calls one after another, waiting for each response, instead of all at once. |
162
+ | `autoConnect` | `true` | Call `adapter.connect()` automatically when the channel is created. |
163
+ | `errorIncludeStack` | `false` | Include the stack trace of errors thrown in your handlers in the error response sent to the caller. |
164
+ | `unhandledRequests` | `'reject'` | `'reject'`: requests without a handler are answered with `-32601` and listeners do not run. `'observe'`: listeners run, the response is still `-32601`. |
165
+ | `logLevel` | `INFO` | Log verbosity (`DEBUG`, `INFO`, `WARN`, `ERROR`, `NONE`). |
166
+
167
+ ### iframe adapter options
168
+
169
+ **`new IFrameHostAdapter(iframe, name?, options?)`**
170
+
171
+ | Option | Default | Description |
172
+ | ----------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
173
+ | `origin` | `'*'` | Allowed iframe origin(s): a string, `RegExp`, an array of both, a predicate function, or `true` or `'*'` to allow any origin. |
174
+ | `reconnect` | `true` | Keep listening for new handshakes, e.g. after the iframe navigates or reloads. |
175
+ | `heartbeat` | `false` | `true` or `{ interval?, timeout? }` to ping the iframe. Defaults: ping every `5000` ms, report `disconnected` if a ping is not answered within `10000` ms. |
176
+
177
+ **`new IFrameClientAdapter(name?, options?)`**
178
+
179
+ | Option | Default | Description |
180
+ | ----------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------- |
181
+ | `origin` | `true` | Allowed parent origin(s): a string, `RegExp`, an array of both, a predicate function, or `true` or `'*'` to allow any origin. |
182
+ | `pollingInterval` | `1000` | Milliseconds between handshake attempts until the host answers. |
183
+
184
+ > ⚠️ For production use, set `origin` on the iframe side to the host's origin. The iframe adapter logs a warning while it accepts any origin. Setting `origin` on the host as well protects against pages the iframe navigates to on its own. Both adapters log every handshake message they ignore because of the origin. String origins are compared as URL origins, so casing, a trailing slash or a default port do not matter.
185
+
186
+ **Connection lifecycle**
187
+
188
+ - The host reports `connected` only once the iframe has accepted the handshake (it answers a ping on the control port). An iframe that rejects the host's origin keeps repeating its handshake request, which the host logs, and the host stays `disconnected`.
189
+ - When one side calls `channel.$.destroy()`, the other side is told right away: it switches to `disconnected` and rejects its pending calls with `-31003`. The iframe side then starts a new handshake, so a new host channel connects automatically.
190
+ - When the iframe reloads, the host emits `rpc.disconnected` followed by `rpc.connected`, and calls that were still waiting for the old document are rejected with `-31003`.
191
+ - If two host adapters with the same name answer the handshake, the iframe keeps the first connection and ignores the second. That host stays `disconnected`.
192
+ - An iframe that navigates to a page without anyrpc cannot say goodbye. Enable the `heartbeat` to detect this: the host reports the channel as `disconnected` once the iframe stops answering pings, see the notes on the [Web Worker heartbeat](#web-worker-adapter) for how in-flight calls behave.
193
+
194
+ ### Web Worker adapter
195
+
196
+ The page creates the worker and passes it to `WebWorkerHostAdapter`. Inside the worker, `WebWorkerClientAdapter` accepts the connection. Both come from the same entry point, and bundlers drop the side you do not import. Creating `WebWorkerClientAdapter` outside of a dedicated worker throws an error that points you to the right adapter.
197
+
198
+ ```ts
199
+ // main.ts
200
+ import { createRpcChannel } from '@schwarzdavid/anyrpc'
201
+ import { WebWorkerHostAdapter } from '@schwarzdavid/anyrpc/adapters/web-worker'
202
+ import type { MainToWorker, WorkerToMain } from './messages'
203
+
204
+ const worker = new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' })
205
+ const channel = createRpcChannel<MainToWorker, WorkerToMain>(new WebWorkerHostAdapter(worker, 'my-app'))
206
+
207
+ const result = await channel.compute(42)
208
+ ```
209
+
210
+ ```ts
211
+ // worker.ts
212
+ import { createRpcChannel } from '@schwarzdavid/anyrpc'
213
+ import { WebWorkerClientAdapter } from '@schwarzdavid/anyrpc/adapters/web-worker'
214
+ import type { MainToWorker, WorkerToMain } from './messages'
215
+
216
+ const channel = createRpcChannel<WorkerToMain, MainToWorker>(new WebWorkerClientAdapter('my-app'))
217
+
218
+ channel.$.handle('compute', (input) => expensiveCalculation(input))
219
+ ```
220
+
221
+ As with iframes, both sides must use the same **name**, so one worker can serve several independent channels. Messages the worker exchanges with `postMessage` outside of anyrpc are ignored. `WebWorkerHostAdapter` also accepts a `SharedWorker`, see [SharedWorker adapter](#sharedworker-adapter).
222
+
223
+ **Connection lifecycle**
224
+
225
+ - The page starts the handshake and repeats it every `pollingInterval` until the worker answers, so it does not matter which side is ready first. The worker reports `connected` once the page has answered a ping on the control port.
226
+ - When one side calls `channel.$.destroy()`, the other side is told right away: it switches to `disconnected` and rejects its pending calls with `-31003`. A page whose worker channel was destroyed starts a new handshake on its own, and the worker accepts new handshakes as long as its channel exists.
227
+ - Use one host adapter per name and worker. A second page channel with the same name takes over the worker's connection; the first one is not told and its calls time out.
228
+ - `worker.terminate()` and `self.close()` cannot be observed directly. Enable the `heartbeat` to detect them: the page pings the worker and reports it as `disconnected` if it does not answer within `timeout`. Calls that are still in flight are not rejected by the heartbeat; they fail with `-31001` once their own `timeout` expires.
229
+ - A worker that is busy with a long synchronous task cannot answer pings either. It is reported as `disconnected` as well, and as `connected` again as soon as it answers. In the meantime, in-flight calls keep waiting for their response, and new calls are queued or throw `-31002` as usual.
230
+ - Uncaught errors in the worker are logged by the page adapter. A worker that fails to load (e.g. a wrong script URL) is logged as well, and the page stops its handshake attempts, since that worker will never answer.
231
+
232
+ **`new WebWorkerHostAdapter(worker, name?, options?)`**
233
+
234
+ | Option | Default | Description |
235
+ | -------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
236
+ | `pollingInterval` | `1000` | Milliseconds between handshake attempts until the worker answers. |
237
+ | `heartbeat` | `false` | `true` or `{ interval?, timeout? }` to ping the worker. Defaults: ping every `5000` ms, report `disconnected` if a ping is not answered within `10000` ms. |
238
+ | `terminateOnDestroy` | `false` | Call `worker.terminate()` when the channel is destroyed. Not available for a `SharedWorker`. |
239
+
240
+ **`new WebWorkerClientAdapter(name?)`** has no options: the page configures the connection.
241
+
242
+ ### Hubs (one-to-many)
243
+
244
+ Some transports connect one side to many peers: a `SharedWorker` serves every tab that opens it, a WebSocket server serves every client. `createRpcHub(hubAdapter, options?)` handles this side. It creates a regular channel for every peer, so timeouts, queueing and error handling work exactly as described above, and it registers your handlers on all of them. The hub looks like a channel: calling a method calls it on **every** connected peer, and everything else lives under `$`.
245
+
246
+ ```ts
247
+ // shared-worker.ts
248
+ import { createRpcHub } from '@schwarzdavid/anyrpc'
249
+ import { SharedWorkerHubAdapter } from '@schwarzdavid/anyrpc/adapters/web-worker'
250
+ import type { PageToWorker, WorkerToPage } from './messages'
251
+
252
+ // createRpcHub<MethodsOfEveryPeer, MethodsICanHandle>
253
+ const hub = createRpcHub<WorkerToPage, PageToWorker>(new SharedWorkerHubAdapter('my-app'))
254
+
255
+ // Handlers and listeners receive the calling peer as first argument
256
+ hub.$.handle('getState', ({ peer }, key) => store.get(peer.id, key))
257
+ hub.$.on('rpc.peer.connected', (peer) => peer.channel.welcome.notify())
258
+
259
+ // Notify every peer
260
+ hub.stateChanged.notify(diff)
261
+
262
+ // Call every peer: one promise per peer, each with a .peer property
263
+ const titles = await Promise.all(hub.getTitle())
264
+ const fastest = await Promise.any(hub.getTitle())
265
+ ```
266
+
267
+ | Member | Description |
268
+ | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
269
+ | `hub.<method>(...args)` | Calls the method on every connected peer and returns an array with one promise per peer. Each promise has a `peer` property. Decide yourself how to wait: `Promise.all`, `Promise.any`, `Promise.allSettled`, ... |
270
+ | `hub.<method>.notify(...args)` | Notifies every connected peer. A peer that cannot be notified is logged and skipped. |
271
+ | `hub.$.handle(name, (context, ...args) => result)` | Answers calls of `name` from every peer. `context.peer` is the calling peer. One handler per method. |
272
+ | `hub.$.on(name, (context, ...args) => void)` | Observes calls and notifications of `name` from every peer. |
273
+ | `hub.$.on('rpc.peer.connected' \| 'rpc.peer.disconnected', fn)` | Called with the peer when it connects or leaves. |
274
+ | `hub.$.peers` / `hub.$.peer(id)` | The connected peers. Each peer has an `id` and its own `channel` to call it individually: `peer.channel.method()`. |
275
+ | `hub.$.destroy()` | Disconnects all peers and stops accepting new ones. |
276
+
277
+ - A peer appears in `hub.$.peers` and `rpc.peer.connected` once its channel is connected, so you can call it right away. It stays a peer while its connection briefly drops and recovers.
278
+ - A peer leaves when its side destroys the channel, or when the hub adapter detects that it is gone (e.g. a missed heartbeat). Its pending calls reject with `-31003`.
279
+ - Promises of a broadcast that you never await do not cause unhandled rejections; failures are logged at `DEBUG` level.
280
+ - The hub accepts the same options as `createRpcChannel` and applies them to every peer channel. `autoConnect` controls whether the hub adapter starts accepting peers right away.
281
+
282
+ ### SharedWorker adapter
283
+
284
+ Each page creates the `SharedWorker` and passes it to the same `WebWorkerHostAdapter` it would use for a dedicated worker. Inside the worker, `SharedWorkerHubAdapter` accepts all pages as peers of a [hub](#hubs-one-to-many).
285
+
286
+ ```ts
287
+ // page.ts
288
+ import { createRpcChannel } from '@schwarzdavid/anyrpc'
289
+ import { WebWorkerHostAdapter } from '@schwarzdavid/anyrpc/adapters/web-worker'
290
+ import type { PageToWorker, WorkerToPage } from './messages'
291
+
292
+ const worker = new SharedWorker(new URL('./shared-worker.ts', import.meta.url), { type: 'module' })
293
+ const channel = createRpcChannel<PageToWorker, WorkerToPage>(new WebWorkerHostAdapter(worker, 'my-app'))
294
+
295
+ channel.$.handle('getTitle', () => document.title)
296
+ ```
297
+
298
+ The worker side is shown in [Hubs](#hubs-one-to-many). Both sides must use the same **name**.
299
+
300
+ - Every page gets its own pair of `MessagePort`s, so peers never see each other's messages.
301
+ - A tab that is closed cannot say goodbye. The hub pings every page (on by default) and removes a page that misses the heartbeat. The page receives a goodbye and connects again on its own if it was only frozen.
302
+ - When a page destroys its channel, the hub removes it right away. When the hub drops a peer, the page starts a new handshake automatically.
303
+ - The page adapter takes the same `pollingInterval` and `heartbeat` options as for a dedicated worker.
304
+ - `WebWorkerClientAdapter` throws inside a shared worker and points you to `SharedWorkerHubAdapter`; `SharedWorkerHubAdapter` throws outside of one.
305
+
306
+ **`new SharedWorkerHubAdapter(name?, options?)`**
307
+
308
+ | Option | Default | Description |
309
+ | ----------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
310
+ | `heartbeat` | `true` | `true` or `{ interval?, timeout? }` to ping every page, `false` to disable. Defaults: ping every `5000` ms, remove a page that does not answer within `10000` ms. |
311
+
312
+ ### Node.js worker adapter
313
+
314
+ The thread that starts the worker passes it to `NodeWorkerHostAdapter`. Inside the worker, `NodeWorkerClientAdapter` accepts the connection. The entry point imports `node:worker_threads`, so it only works in Node.js (and runtimes compatible with it).
315
+
316
+ ```ts
317
+ // main.ts
318
+ import { Worker } from 'node:worker_threads'
319
+ import { createRpcChannel } from '@schwarzdavid/anyrpc'
320
+ import { NodeWorkerHostAdapter } from '@schwarzdavid/anyrpc/adapters/node-worker'
321
+
322
+ const worker = new Worker(new URL('./worker.js', import.meta.url))
323
+ const channel = createRpcChannel<MainToWorker, WorkerToMain>(new NodeWorkerHostAdapter(worker, 'my-app'))
324
+ ```
325
+
326
+ ```ts
327
+ // worker.ts
328
+ import { createRpcChannel } from '@schwarzdavid/anyrpc'
329
+ import { NodeWorkerClientAdapter } from '@schwarzdavid/anyrpc/adapters/node-worker'
330
+
331
+ const channel = createRpcChannel<WorkerToMain, MainToWorker>(new NodeWorkerClientAdapter('my-app'))
332
+ ```
333
+
334
+ - Both sides must use the same **name**, so one worker can serve several channels. Messages the worker posts outside of anyrpc are ignored.
335
+ - Uncaught errors in the worker are logged. Once the worker exits, the channel is `disconnected`, in-flight calls reject with `-31003` and the adapter does not reconnect. Calls still in the queue (see `queueEnabled`) are not rejected by the exit: they fail with `-31001` once `queueTimeout` expires, or with `-31003` right away when you destroy the channel.
336
+ - A running worker keeps the Node.js process alive. Terminate it yourself when you are done, or set `terminateOnDestroy` so that destroying the channel terminates it as well.
337
+ - Creating `NodeWorkerClientAdapter` outside of a worker thread throws an error that points you to `NodeWorkerHostAdapter`.
338
+ - Inside the worker, the connection is established only once the main thread answers the worker's first ping on the control channel. A handler that calls the main thread before that fails with `-31002` (the main side then sees that error as a server error), so enable `queueEnabled` or wait for `rpc.connected`.
339
+
340
+ **`new NodeWorkerHostAdapter(worker, name?, options?)`**
341
+
342
+ | Option | Default | Description |
343
+ | -------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
344
+ | `pollingInterval` | `1000` | Milliseconds between handshake attempts until the worker answers. |
345
+ | `heartbeat` | `false` | `true` or `{ interval?, timeout? }` to ping the worker. Defaults: ping every `5000` ms, report `disconnected` if a ping is not answered within `10000` ms. |
346
+ | `terminateOnDestroy` | `false` | Terminate the worker when the channel is destroyed. |
347
+
348
+ **`new NodeWorkerClientAdapter(name?)`** has no options: the main thread configures the connection.
349
+
350
+ ### Node.js child process adapter
351
+
352
+ The process that forks the child passes it to `ChildProcessHostAdapter`. Inside the child, `ChildProcessClientAdapter` accepts the connection. The entry point only works in Node.js (and runtimes compatible with it), since the child uses the global `process`.
353
+
354
+ ```ts
355
+ // main.ts
356
+ import { fork } from 'node:child_process'
357
+ import { createRpcChannel } from '@schwarzdavid/anyrpc'
358
+ import { ChildProcessHostAdapter } from '@schwarzdavid/anyrpc/adapters/child-process'
359
+
360
+ const child = fork('./child.js')
361
+ const channel = createRpcChannel<ParentToChild, ChildToParent>(new ChildProcessHostAdapter(child, 'my-app'))
362
+ ```
363
+
364
+ ```ts
365
+ // child.ts
366
+ import { createRpcChannel } from '@schwarzdavid/anyrpc'
367
+ import { ChildProcessClientAdapter } from '@schwarzdavid/anyrpc/adapters/child-process'
368
+
369
+ const channel = createRpcChannel<ChildToParent, ParentToChild>(new ChildProcessClientAdapter('my-app'))
370
+ ```
371
+
372
+ - Both sides must use the same **name**, so one child can serve several channels. Your own `process.send` messages are ignored.
373
+ - The child must be started with `fork()` (or with `stdio: ['ipc', …]`). Creating `ChildProcessClientAdapter` in a process without an IPC channel throws an error that points you to `ChildProcessHostAdapter`.
374
+ - A `message` listener keeps the child process alive until its channel is destroyed.
375
+ - Once the child exits or disconnects its IPC channel (`process.disconnect()`), the channel is `disconnected`, in-flight calls reject with `-31003` and the adapter does not reconnect. Calls still in the queue (see `queueEnabled`) are not rejected by this: they fail with `-31001` once `queueTimeout` expires, or with `-31003` right away when you destroy the channel.
376
+ - When the child destroys its channel, the parent channel reconnects as soon as the child creates a new one.
377
+ - Destroying the parent channel without `killOnDestroy` keeps both processes alive: the child's adapter keeps listening and the open IPC channel keeps the parent running. Set `killOnDestroy`, call `child.disconnect()`, or let the child destroy its own channel.
378
+ - Errors from spawning the child are not handled by the adapter. Listen to `child.on('error', …)` yourself.
379
+ - Messages travel through Node's JSON serialization, so only JSON values can be sent.
380
+
381
+ **`new ChildProcessHostAdapter(child, name?, options?)`**
382
+
383
+ | Option | Default | Description |
384
+ | ----------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
385
+ | `pollingInterval` | `1000` | Milliseconds between handshake attempts until the child answers. |
386
+ | `heartbeat` | `false` | `true` or `{ interval?, timeout? }` to ping the child. Defaults: ping every `5000` ms, report `disconnected` if a ping is not answered within `10000` ms. |
387
+ | `killOnDestroy` | `false` | Kill the child when the channel is destroyed. |
388
+
389
+ **`new ChildProcessClientAdapter(name?)`** has no options: the parent configures the connection.
390
+
391
+ ### Error handling
392
+
393
+ Errors thrown in a remote handler reject the caller's promise with an `RpcError`. The `RpcError` has a JSON-RPC `code`, a `message` and the original error details in `data`:
394
+
395
+ ```ts
396
+ import { RpcError, RpcErrorCode } from '@schwarzdavid/anyrpc'
397
+
398
+ try {
399
+ await channel.getTitle()
400
+ } catch (err) {
401
+ // err.code: -32000 (server error), -32601 (method not found), -31001 (timeout), -31002 (not connected), -31003 (connection lost), ...
402
+ if (err instanceof RpcError && err.code === RpcErrorCode.TIMEOUT_ERROR) {
403
+ retryLater()
404
+ }
405
+ }
406
+ ```
407
+
408
+ | Code | Origin | Meaning |
409
+ | -------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
410
+ | `-32700` | remote | The other side could not parse the message as JSON. `data.reason` explains why. |
411
+ | `-32600` | remote | The message is not a valid JSON-RPC request (e.g. `method` is not a string). `data.reason` explains why. |
412
+ | `-32601` | remote | No handler is registered for the called method, or the method name starts with `rpc.`. |
413
+ | `-32602` | remote | The call used named params (an object). Handlers only support positional params. |
414
+ | `-32603` | remote | The handler succeeded, but its result could not be sent (e.g. a function or DOM node that `postMessage` cannot clone). The original error is in `data`. |
415
+ | `-32000` | remote | The remote handler threw. The original error's `name` and `message` are in `data`. |
416
+ | `-31001` | local | No response arrived within `timeout`, or a queued call waited longer than `queueTimeout`. |
417
+ | `-31002` | local | The method was called while disconnected and the queue is disabled, or after the channel was destroyed. |
418
+ | `-31003` | local | The connection was closed before the response arrived: one side called `destroy()` or the other side established a new connection. A heartbeat timeout does not trigger this. |
419
+
420
+ The local codes lie outside the range JSON-RPC reserves for protocol and server errors (`-32768` to `-32000`) and are never sent over the wire. If a handler throws an `RpcError` with an application-defined code (any code outside that range, except the local codes), the caller receives it unchanged. Every other error is wrapped in a `-32000` server error. Thrown `Error` instances are serialized to their `name` and `message` (plus `stack` with `errorIncludeStack`); other properties are dropped. Thrown values that are no errors, such as strings, are sent as `data` unchanged.
421
+
422
+ If the transport cannot send a request at all, for example because an argument is a function that `postMessage` cannot clone, the call rejects with the transport's own error (a `DataCloneError` in browsers) instead of an `RpcError`, and `notify()` throws it synchronously. A queued notification that cannot be sent is logged and dropped.
423
+
424
+ ### WebSocket adapter
425
+
426
+ `WebSocketHubAdapter` serves every connection of a `ws`-compatible server as a peer of a [hub](#hubs-one-to-many). `WebSocketClientAdapter` connects from a browser or Node.js and reconnects automatically. The entry point works in both environments and does not depend on `ws`, any object with the same shape as `WebSocketServer` and `WebSocket` is accepted.
427
+
428
+ ```ts
429
+ // server.ts
430
+ import { WebSocketServer } from 'ws'
431
+ import { createRpcHub } from '@schwarzdavid/anyrpc'
432
+ import { WebSocketHubAdapter } from '@schwarzdavid/anyrpc/adapters/websocket'
433
+
434
+ const server = new WebSocketServer({ port: 8081 })
435
+ const hub = createRpcHub<ServerToClient, ClientToServer>(new WebSocketHubAdapter(server))
436
+ ```
437
+
438
+ ```ts
439
+ // client.ts
440
+ import { createRpcChannel } from '@schwarzdavid/anyrpc'
441
+ import { WebSocketClientAdapter } from '@schwarzdavid/anyrpc/adapters/websocket'
442
+
443
+ const channel = createRpcChannel<ClientToServer, ServerToClient>(new WebSocketClientAdapter('wss://example.com/rpc'))
444
+ ```
445
+
446
+ - Only text frames are exchanged, binary frames are dropped.
447
+ - The client reconnects with a backoff from 1 s up to 30 s when the connection drops, when the server closes it or when the server says goodbye. Socket errors on the server side are logged.
448
+ - The heartbeat is off for the client and on for the hub. If the other side does not run anyrpc, leave the heartbeat of the client off. The hub removes clients that do not answer `anyrpc::ping`, so set `heartbeat: false` on the hub when its clients do not run anyrpc.
449
+ - If the server is an anyrpc hub, enable `heartbeat` on the client. Without it, a silently dropped connection (sleep, Wi-Fi switch, half-open connection) stays `connected` and calls time out; with it, the drop is detected and the client reconnects.
450
+ - One hub serves one server. To serve several hubs, create several `WebSocketServer` instances with `noServer` and a `path` each.
451
+ - The server belongs to you: `hub.$.destroy()` does not close it.
452
+
453
+ **`new WebSocketClientAdapter(url, options?)`**
454
+
455
+ | Option | Default | Description |
456
+ | ----------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
457
+ | `reconnect` | `true` | Reconnect with a backoff of 1 s up to 30 s after the connection was lost. |
458
+ | `heartbeat` | `false` | `true` or `{ interval?, timeout? }` to ping the server. Defaults: ping every `5000` ms, report `disconnected` if a ping is not answered within `10000` ms. |
459
+
460
+ **`new WebSocketHubAdapter(server, options?)`**
461
+
462
+ | Option | Default | Description |
463
+ | ----------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
464
+ | `heartbeat` | `true` | `true` or `{ interval?, timeout? }` to ping every client, `false` to disable. Defaults: ping every `5000` ms, remove a client that does not answer within `10000` ms. |
465
+
466
+ ### Custom adapters
467
+
468
+ Everything a transport needs is exported from `@schwarzdavid/anyrpc`. Extend `AbstractRpcAdapter`, implement `connect()` and `sendMessage()`, hand incoming messages to `this.onMessage()`, report the state through `this.connectionStatus`, and call `this.closeConnection()` once the transport is definitively gone. The latter rejects in-flight calls with `-31003`; a plain status change does not, so a transport that is merely unresponsive can still deliver late responses. `connect()` may return a promise; if it rejects, the channel logs the error and stays `disconnected`. An adapter instance serves exactly one channel, so `createRpcChannel` throws if the adapter is already in use, until that channel is destroyed.
469
+
470
+ ```ts
471
+ import { AbstractRpcAdapter, ConnectionStatus, type MethodMap, type RpcMessage } from '@schwarzdavid/anyrpc'
472
+
473
+ class MyWebSocketAdapter<
474
+ Methods extends MethodMap<Methods>,
475
+ Events extends MethodMap<Events>,
476
+ > extends AbstractRpcAdapter<Methods, Events> {
477
+ constructor(private readonly socket: WebSocket) {
478
+ super()
479
+ }
480
+
481
+ connect(): void {
482
+ this.socket.addEventListener('open', () => {
483
+ this.connectionStatus = ConnectionStatus.CONNECTED
484
+ })
485
+ this.socket.addEventListener('message', (event) => void this.onMessage(event.data as string))
486
+ this.socket.addEventListener('close', () => this.closeConnection())
487
+ }
488
+
489
+ sendMessage(message: RpcMessage<Methods, Events>): void {
490
+ this.socket.send(JSON.stringify(message))
491
+ }
492
+ }
493
+ ```
494
+
495
+ This example only illustrates the contract; use `@schwarzdavid/anyrpc/adapters/websocket` for WebSockets in production.
496
+
497
+ For transports with a single bidirectional channel (TCP, IPC, …) extend `AbstractSocketAdapter` from `@schwarzdavid/anyrpc/adapters/socket`. Implement `connect()` and `send(message)`, call `this.opened()` and `this.closed()` when the transport opens and closes, and pass incoming strings or objects to `this.receive(data)`. Heartbeat and goodbye messages travel in-band. `receive()` ignores data until `opened()` was called, so handle a handshake before passing data to `receive()` and answer it via `this.send(...)` directly. `send()` is called for RPC messages regardless of the connection state, so it must ignore writes to a closed transport itself; control messages are only sent while the transport is open.
498
+
499
+ Transports that hand over `MessagePort`s after a handshake, like the iframe and Web Worker adapters, build on `@schwarzdavid/anyrpc/adapters/message-port` instead. Extend `AbstractMessagePortClientAdapter` for the side that starts the handshake and polls until it is answered, and `AbstractMessagePortHostAdapter` for the side that answers it and creates the `MessageChannel`s. Implement only how handshake messages are listened for and posted; ports, heartbeat, goodbye notifications and reconnects come with the base classes. Which side starts the handshake depends on the transport: an iframe asks its parent, because the parent cannot know when the iframe has loaded, while a page asks its worker. The answering side reports `connected` only after the other side answered the first ping on the control port.
500
+
501
+ The base classes accept any port that matches `MessagePortLike` (`postMessage`, `addEventListener`, `start`, `close`), including Node.js `worker_threads` ports. Transports that cannot deliver the handshake ports as `event.ports`, such as Node.js workers that only transfer ports inside the message itself, pass them to `this.acceptInitResponseData(data, ports)` instead of calling `this.acceptInitResponse(event)`. Implementations may declare `transfer` in `postInitResponse` as their transport's own type, e.g. `Transferable[]` in the browser or `MessagePort[]` from `node:worker_threads`.
502
+
503
+ For one-to-many transports, extend `AbstractRpcHubAdapter` instead. Implement `connect()` and `destroy()`, and for every new peer create a regular adapter for its connection and pass it to `this.addPeer(adapter)`, which returns the peer's id. The hub connects that adapter and wraps it in a channel. Call `this.removePeer(id)` once the peer is gone.
504
+
505
+ `ConnectionStatus`, `LogLevel` and `RpcErrorCode` are plain `as const` objects with a same-named union type, so `status === 'connected'` and `code === -31001` type-check as well.
506
+
507
+ ### JSON-RPC compliance
508
+
509
+ - **Batch requests are not supported.** anyrpc never sends batches, and an incoming array of requests is answered with `-32600` (invalid request).
510
+ - **Invalid incoming messages are answered with an error response.** Unparsable JSON gets `-32700`, a structurally invalid request or notification gets `-32600`, both with a `data.reason`. The response carries the message's `id` if it could be read, otherwise `id: null`. Invalid messages that look like responses (they contain `result` or `error`) are never answered, so two peers cannot end up in an error loop. Every invalid message is logged as a warning and emitted as `rpc.error`.
511
+ - Error responses with `id: null` cannot be matched to a request. They are logged and emitted as `rpc.error`; the affected request rejects with a timeout.
512
+ - Messages the transport receives from unrelated sources (e.g. other frames or browser extensions posting to `window`) are filtered by the adapter before they reach the channel and are never answered.
513
+ - Handlers that return `undefined` (e.g. `void` methods) respond with `result: null`, because `undefined` is not a JSON value. The caller receives `null`, and the channel types reflect this: a method declared as `find(): string | undefined` resolves to `string | null`, and one declared as `probe(): undefined` resolves to `null`.
514
+ - `params` must be omitted or be an array or an object. A message that carries `params: undefined` as an own property (possible through structured cloning) is rejected with `-32600`.
515
+ - Method names starting with `rpc.` are reserved by the specification. Calling them throws, and incoming calls to them are answered with `-32601`.
516
+ - A channel is never a thenable and has no `toJSON`, so it can safely be returned from `async` functions and passed to `JSON.stringify` (which yields the connection status). Interface members named `then` or `toJSON` are rejected by the types.
517
+
518
+ ## Development
519
+
520
+ ```bash
521
+ npm install
522
+ npx playwright install chromium # once, for the browser tests
523
+ npm run dev # Vite dev server. Open /examples/iframe/, /examples/web-worker/ or /examples/shared-worker/ for the live demos
524
+ node examples/node-worker/main.ts # Node.js worker demo, run npm run build first
525
+ node examples/child-process/main.ts # child process demo, run npm run build first
526
+ node examples/websocket/server.ts # WebSocket demo server, run npm run build first; open /examples/websocket/
527
+ npm test # Unit, type and browser tests (Vitest). Also checks the built package in dist/ once npm run build was run
528
+ npm run coverage # Tests with coverage report
529
+ npm run check # TypeScript project build
530
+ npm run lint # ESLint
531
+ npm run format # Prettier check
532
+ npm run build # Build ESM + CJS bundles and type declarations into dist/
533
+ ```
534
+
535
+ ## Todo
536
+
537
+ **Public API**
538
+
539
+ - [x] Export `AbstractRpcAdapter` so users can write custom adapters
540
+ - [x] Export `RpcError`, `RpcErrorCode`, `LogLevel` and `ConnectionStatus` from the package entry point
541
+
542
+ **Protocol and behavior**
543
+
544
+ - [ ] Support request cancellation (e.g. via `AbortSignal`)
545
+ - [x] Warn when `IFrameClientAdapter` allows any origin (`origin: true`)
546
+
547
+ **Project**
548
+
549
+ - [ ] Add API documentation and more examples
550
+ - [ ] Set up CI (lint, type check, test, build)
551
+ - [ ] Add a changelog
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("./socket.cjs"),r=require("./chunks/ControlProtocol-BMvwQecN.cjs"),n=require("./chunks/handshake-CWtm9Y59.cjs"),o="anyrpc::child-process-init",d="anyrpc-child-process-adapter";function c(s,e){return{anyrpc:s,message:e}}function a(s,e){if(typeof s!="object"||s===null||!("anyrpc"in s)||!("message"in s)||s.anyrpc!==e)return;const{message:t}=s;return typeof t=="object"&&t!==null?t:void 0}class l extends h.AbstractSocketAdapter{constructor(e,t=d,i){super(r.resolveHeartbeatOptions(i?.heartbeat??!1)),this.child=e,this.name=t,this.pollingInterval=i?.pollingInterval??1e3,this.killOnDestroy=i?.killOnDestroy??!1}pollingInterval;killOnDestroy;handshake;onChildMessage=e=>this.handleChildMessage(e);onChildExit=e=>this.handleChildExit(e);onChildDisconnect=()=>this.handleChildDisconnect();onSendResult=e=>this.handleSendResult(e);connect(){if(this.stopListening(),!this.child.connected){this.handleChildDisconnect();return}this.child.on("message",this.onChildMessage),this.child.on("exit",this.onChildExit),this.child.on("disconnect",this.onChildDisconnect),this.startHandshake()}send(e){this.child.connected&&this.child.send(c(this.name,e),this.onSendResult)}onRemoteGoodbye(){super.onRemoteGoodbye(),this.startHandshake()}destroy(){this.stopHandshake(),super.destroy(),this.stopListening(),this.killOnDestroy&&this.child.kill()}startHandshake(){this.stopHandshake();const e=n.createInitRequest(o,this.name);this.handshake={request:e,pollingIntervalId:setInterval(()=>this.send(e),this.pollingInterval)},this.send(e)}stopHandshake(){clearInterval(this.handshake?.pollingIntervalId),this.handshake=void 0}handleChildMessage(e){const t=a(e,this.name);if(t){if(this.handshake&&n.isInitResponse(t,this.handshake.request.id)){this.stopHandshake(),this.opened();return}this.receive(t)}}handleChildExit(e){this.logger?.info(`The child process exited with code ${String(e)}, so the channel will not reconnect`),this.destroy()}handleChildDisconnect(){this.logger?.info("The IPC channel to the child process is closed, so the channel will not reconnect"),this.destroy()}handleSendResult(e){e&&this.logger?.debug("Could not send a message to the child process",e)}stopListening(){this.child.off("message",this.onChildMessage),this.child.off("exit",this.onChildExit),this.child.off("disconnect",this.onChildDisconnect)}}function p(){return process}function g(s){return typeof s.send=="function"}function u(){const s=p();if(!g(s))throw new Error("ChildProcessClientAdapter must be created in a process with an IPC channel, e.g. one started with child_process.fork(). Use ChildProcessHostAdapter in the parent process.");return s}class f extends h.AbstractSocketAdapter{constructor(e=d){super(),this.name=e,this.ipc=u()}ipc;answeredInitId;onParentMessage=e=>this.handleParentMessage(e);onDisconnect=()=>this.closed();onSendResult=e=>this.handleSendResult(e);connect(){this.stopListening(),this.ipc.on("message",this.onParentMessage),this.ipc.on("disconnect",this.onDisconnect)}send(e){this.ipc.connected&&this.ipc.send(c(this.name,e),void 0,void 0,this.onSendResult)}destroy(){super.destroy(),this.stopListening()}handleSendResult(e){e&&this.logger?.debug("Could not send a message to the parent process",e)}handleParentMessage(e){const t=a(e,this.name);if(t){if(n.isInitRequest(t,o,this.name)){this.acceptInitRequest(t);return}this.receive(t)}}acceptInitRequest(e){if(e.id===this.answeredInitId){this.logger?.debug("Ignored a repeated handshake request that was already answered");return}this.answeredInitId!==void 0&&this.closed(),this.answeredInitId=e.id,this.send(n.createInitResponse(e)),this.opened()}stopListening(){this.ipc.off("message",this.onParentMessage),this.ipc.off("disconnect",this.onDisconnect)}}exports.ChildProcessClientAdapter=f;exports.ChildProcessHostAdapter=l;