@schwarzdavid/anyrpc 0.0.2-alpha.1 → 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.
- package/LICENSE +373 -0
- package/README.md +115 -62
- package/dist/child-process.d.ts +62 -0
- package/dist/child-process.d.ts.map +1 -0
- package/dist/child-process.js +116 -128
- package/dist/child-process.js.map +1 -0
- package/dist/chunks/AbstractMessagePortInitiatorAdapter-1KLO-1xm.d.ts +83 -0
- package/dist/chunks/AbstractMessagePortInitiatorAdapter-1KLO-1xm.d.ts.map +1 -0
- package/dist/chunks/AbstractMessagePortInitiatorAdapter-DWJ29SLn.js +122 -0
- package/dist/chunks/AbstractMessagePortInitiatorAdapter-DWJ29SLn.js.map +1 -0
- package/dist/chunks/AbstractRpcAdapter-CzHpORlI.js +89 -0
- package/dist/chunks/AbstractRpcAdapter-CzHpORlI.js.map +1 -0
- package/dist/chunks/AbstractRpcAdapter-fNu6wvPV.d.ts +80 -0
- package/dist/chunks/AbstractRpcAdapter-fNu6wvPV.d.ts.map +1 -0
- package/dist/chunks/AbstractRpcHubAdapter-CM8YKvTy.js +25 -0
- package/dist/chunks/AbstractRpcHubAdapter-CM8YKvTy.js.map +1 -0
- package/dist/chunks/AbstractRpcHubAdapter-V9lRYzuv.d.ts +26 -0
- package/dist/chunks/AbstractRpcHubAdapter-V9lRYzuv.d.ts.map +1 -0
- package/dist/chunks/AbstractSocketAdapter-Bnd_0D3T.js +63 -0
- package/dist/chunks/AbstractSocketAdapter-Bnd_0D3T.js.map +1 -0
- package/dist/chunks/AbstractSocketAdapter-CGdtVMSQ.d.ts +19 -0
- package/dist/chunks/AbstractSocketAdapter-CGdtVMSQ.d.ts.map +1 -0
- package/dist/chunks/ControlProtocol-Dd9aHpa5.js +99 -0
- package/dist/chunks/ControlProtocol-Dd9aHpa5.js.map +1 -0
- package/dist/chunks/Heartbeat-GHewy9_w.d.ts +7 -0
- package/dist/chunks/Heartbeat-GHewy9_w.d.ts.map +1 -0
- package/dist/chunks/handshake-sA3m5TsG.js +43 -0
- package/dist/chunks/handshake-sA3m5TsG.js.map +1 -0
- package/dist/chunks/rpc-Biub1bBg.js +143 -0
- package/dist/chunks/rpc-Biub1bBg.js.map +1 -0
- package/dist/chunks/uuid-B8wYvn_A.js +7 -0
- package/dist/chunks/uuid-B8wYvn_A.js.map +1 -0
- package/dist/iframe.d.ts +34 -0
- package/dist/iframe.d.ts.map +1 -0
- package/dist/iframe.js +68 -72
- package/dist/iframe.js.map +1 -0
- package/dist/index.d.ts +112 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +485 -442
- package/dist/index.js.map +1 -0
- package/dist/message-port.d.ts +3 -0
- package/dist/message-port.js +1 -6
- package/dist/node-worker.d.ts +44 -0
- package/dist/node-worker.d.ts.map +1 -0
- package/dist/node-worker.js +92 -75
- package/dist/node-worker.js.map +1 -0
- package/dist/socket.d.ts +3 -0
- package/dist/socket.js +1 -66
- package/dist/web-worker.d.ts +57 -0
- package/dist/web-worker.d.ts.map +1 -0
- package/dist/web-worker.js +139 -150
- package/dist/web-worker.js.map +1 -0
- package/dist/websocket.d.ts +64 -0
- package/dist/websocket.d.ts.map +1 -0
- package/dist/websocket.js +103 -111
- package/dist/websocket.js.map +1 -0
- package/package.json +44 -39
- package/src/createRpcChannel.ts +87 -119
- package/src/createRpcHub.ts +79 -42
- package/src/index.ts +15 -3
- package/src/lib/ConnectionLifecycle.ts +32 -0
- package/src/lib/ControlProtocol.ts +44 -12
- package/src/lib/MessageQueue.ts +73 -0
- package/src/lib/PendingRequests.ts +38 -0
- package/src/lib/RpcError.ts +4 -2
- package/src/lib/adapter/AbstractRpcAdapter.ts +27 -28
- package/src/lib/adapter/AbstractRpcHubAdapter.ts +39 -22
- package/src/lib/adapter/child-process/ChildProcessClientAdapter.ts +1 -0
- package/src/lib/adapter/child-process/ChildProcessHostAdapter.ts +1 -0
- package/src/lib/adapter/iframe/IFrameClientAdapter.ts +4 -3
- package/src/lib/adapter/iframe/IFrameHostAdapter.ts +4 -3
- package/src/lib/adapter/message-port/AbstractMessagePortAdapter.ts +13 -35
- package/src/lib/adapter/message-port/{AbstractMessagePortClientAdapter.ts → AbstractMessagePortInitiatorAdapter.ts} +18 -8
- package/src/lib/adapter/message-port/{AbstractMessagePortHostAdapter.ts → AbstractMessagePortResponderAdapter.ts} +14 -8
- package/src/lib/adapter/message-port/index.ts +8 -2
- package/src/lib/adapter/node-worker/NodeWorkerClientAdapter.ts +4 -3
- package/src/lib/adapter/node-worker/NodeWorkerHostAdapter.ts +9 -3
- package/src/lib/adapter/socket/AbstractSocketAdapter.ts +8 -24
- package/src/lib/adapter/web-worker/SharedWorkerHubAdapter.ts +2 -2
- package/src/lib/adapter/web-worker/SharedWorkerPeerAdapter.ts +4 -12
- package/src/lib/adapter/web-worker/WebWorkerClientAdapter.ts +4 -3
- package/src/lib/adapter/web-worker/WebWorkerHostAdapter.ts +9 -3
- package/src/lib/adapter/websocket/WebSocketClientAdapter.ts +1 -0
- package/src/lib/adapter/websocket/WebSocketHubAdapter.ts +19 -11
- package/src/lib/adapter/websocket/WebSocketPeerAdapter.ts +3 -16
- package/src/lib/adapter/websocket/index.ts +7 -1
- package/src/types/ConnectionStatus.ts +1 -0
- package/src/types/EventEmitter.ts +1 -1
- package/src/types/Promisable.ts +1 -0
- package/src/types/RpcChannel.ts +13 -1
- package/src/types/RpcHub.ts +59 -25
- package/src/utils/abortable.ts +16 -0
- package/src/utils/rpc.ts +10 -8
- package/src/utils/withDefaults.ts +5 -0
- package/dist/child-process.cjs +0 -1
- package/dist/chunks/AbstractRpcAdapter-7gOLZtYD.js +0 -82
- package/dist/chunks/AbstractRpcAdapter-BPIitR0A.cjs +0 -1
- package/dist/chunks/AbstractRpcHubAdapter-BVPYUoL9.js +0 -26
- package/dist/chunks/AbstractRpcHubAdapter-Bqcrs7Mb.cjs +0 -1
- package/dist/chunks/ControlProtocol-0b5_21ZU.js +0 -82
- package/dist/chunks/ControlProtocol-BMvwQecN.cjs +0 -1
- package/dist/chunks/handshake-CWtm9Y59.cjs +0 -1
- package/dist/chunks/handshake-CZWqKvZe.js +0 -39
- package/dist/chunks/index-B_SfPYCc.js +0 -133
- package/dist/chunks/index-D5LbDuYg.cjs +0 -1
- package/dist/chunks/rpc-Brf2MoZo.cjs +0 -1
- package/dist/chunks/rpc-DeJEGj4-.js +0 -134
- package/dist/chunks/uuid-C2SCOpSM.cjs +0 -1
- package/dist/chunks/uuid-DTlgoKBw.js +0 -9
- package/dist/constants/JSON_RPC_ERRORS.d.ts +0 -19
- package/dist/constants/JSON_RPC_ERRORS.d.ts.map +0 -1
- package/dist/createRpcChannel.d.ts +0 -18
- package/dist/createRpcChannel.d.ts.map +0 -1
- package/dist/createRpcHub.d.ts +0 -7
- package/dist/createRpcHub.d.ts.map +0 -1
- package/dist/iframe.cjs +0 -1
- package/dist/index.cjs +0 -1
- package/dist/lib/ControlProtocol.d.ts +0 -20
- package/dist/lib/ControlProtocol.d.ts.map +0 -1
- package/dist/lib/EventEmitter.d.ts +0 -12
- package/dist/lib/EventEmitter.d.ts.map +0 -1
- package/dist/lib/HandlerRegistry.d.ts +0 -8
- package/dist/lib/HandlerRegistry.d.ts.map +0 -1
- package/dist/lib/Heartbeat.d.ts +0 -24
- package/dist/lib/Heartbeat.d.ts.map +0 -1
- package/dist/lib/Logger.d.ts +0 -13
- package/dist/lib/Logger.d.ts.map +0 -1
- package/dist/lib/RpcError.d.ts +0 -11
- package/dist/lib/RpcError.d.ts.map +0 -1
- package/dist/lib/RpcMessageError.d.ts +0 -15
- package/dist/lib/RpcMessageError.d.ts.map +0 -1
- package/dist/lib/adapter/AbstractRpcAdapter.d.ts +0 -28
- package/dist/lib/adapter/AbstractRpcAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/AbstractRpcHubAdapter.d.ts +0 -24
- package/dist/lib/adapter/AbstractRpcHubAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/child-process/ChildProcessClientAdapter.d.ts +0 -19
- package/dist/lib/adapter/child-process/ChildProcessClientAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/child-process/ChildProcessHostAdapter.d.ts +0 -43
- package/dist/lib/adapter/child-process/ChildProcessHostAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/child-process/constants/childProcessHandshake.d.ts +0 -3
- package/dist/lib/adapter/child-process/constants/childProcessHandshake.d.ts.map +0 -1
- package/dist/lib/adapter/child-process/index.d.ts +0 -4
- package/dist/lib/adapter/child-process/index.d.ts.map +0 -1
- package/dist/lib/adapter/child-process/utils/currentProcess.d.ts +0 -16
- package/dist/lib/adapter/child-process/utils/currentProcess.d.ts.map +0 -1
- package/dist/lib/adapter/child-process/utils/ipcEnvelope.d.ts +0 -7
- package/dist/lib/adapter/child-process/utils/ipcEnvelope.d.ts.map +0 -1
- package/dist/lib/adapter/iframe/IFrameClientAdapter.d.ts +0 -17
- package/dist/lib/adapter/iframe/IFrameClientAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/iframe/IFrameHostAdapter.d.ts +0 -20
- package/dist/lib/adapter/iframe/IFrameHostAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/iframe/constants/iframeHandshake.d.ts +0 -3
- package/dist/lib/adapter/iframe/constants/iframeHandshake.d.ts.map +0 -1
- package/dist/lib/adapter/iframe/index.d.ts +0 -5
- package/dist/lib/adapter/iframe/index.d.ts.map +0 -1
- package/dist/lib/adapter/iframe/utils/iframeOrigin.d.ts +0 -5
- package/dist/lib/adapter/iframe/utils/iframeOrigin.d.ts.map +0 -1
- package/dist/lib/adapter/message-port/AbstractMessagePortAdapter.d.ts +0 -38
- package/dist/lib/adapter/message-port/AbstractMessagePortAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/message-port/AbstractMessagePortClientAdapter.d.ts +0 -22
- package/dist/lib/adapter/message-port/AbstractMessagePortClientAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/message-port/AbstractMessagePortHostAdapter.d.ts +0 -20
- package/dist/lib/adapter/message-port/AbstractMessagePortHostAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/message-port/index.d.ts +0 -6
- package/dist/lib/adapter/message-port/index.d.ts.map +0 -1
- package/dist/lib/adapter/message-port/utils/handshake.d.ts +0 -13
- package/dist/lib/adapter/message-port/utils/handshake.d.ts.map +0 -1
- package/dist/lib/adapter/message-port/utils/messageData.d.ts +0 -2
- package/dist/lib/adapter/message-port/utils/messageData.d.ts.map +0 -1
- package/dist/lib/adapter/node-worker/NodeWorkerClientAdapter.d.ts +0 -12
- package/dist/lib/adapter/node-worker/NodeWorkerClientAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/node-worker/NodeWorkerHostAdapter.d.ts +0 -35
- package/dist/lib/adapter/node-worker/NodeWorkerHostAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/node-worker/constants/nodeWorkerHandshake.d.ts +0 -3
- package/dist/lib/adapter/node-worker/constants/nodeWorkerHandshake.d.ts.map +0 -1
- package/dist/lib/adapter/node-worker/index.d.ts +0 -4
- package/dist/lib/adapter/node-worker/index.d.ts.map +0 -1
- package/dist/lib/adapter/node-worker/utils/initEnvelope.d.ts +0 -13
- package/dist/lib/adapter/node-worker/utils/initEnvelope.d.ts.map +0 -1
- package/dist/lib/adapter/socket/AbstractSocketAdapter.d.ts +0 -23
- package/dist/lib/adapter/socket/AbstractSocketAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/socket/index.d.ts +0 -3
- package/dist/lib/adapter/socket/index.d.ts.map +0 -1
- package/dist/lib/adapter/socket/utils/parseObject.d.ts +0 -2
- package/dist/lib/adapter/socket/utils/parseObject.d.ts.map +0 -1
- package/dist/lib/adapter/web-worker/SharedWorkerHubAdapter.d.ts +0 -18
- package/dist/lib/adapter/web-worker/SharedWorkerHubAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/web-worker/SharedWorkerPeerAdapter.d.ts +0 -18
- package/dist/lib/adapter/web-worker/SharedWorkerPeerAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/web-worker/WebWorkerClientAdapter.d.ts +0 -10
- package/dist/lib/adapter/web-worker/WebWorkerClientAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/web-worker/WebWorkerHostAdapter.d.ts +0 -33
- package/dist/lib/adapter/web-worker/WebWorkerHostAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/web-worker/constants/webWorkerHandshake.d.ts +0 -3
- package/dist/lib/adapter/web-worker/constants/webWorkerHandshake.d.ts.map +0 -1
- package/dist/lib/adapter/web-worker/index.d.ts +0 -5
- package/dist/lib/adapter/web-worker/index.d.ts.map +0 -1
- package/dist/lib/adapter/web-worker/utils/describeWorkerError.d.ts +0 -3
- package/dist/lib/adapter/web-worker/utils/describeWorkerError.d.ts.map +0 -1
- package/dist/lib/adapter/web-worker/utils/globalScope.d.ts +0 -8
- package/dist/lib/adapter/web-worker/utils/globalScope.d.ts.map +0 -1
- package/dist/lib/adapter/websocket/WebSocketClientAdapter.d.ts +0 -27
- package/dist/lib/adapter/websocket/WebSocketClientAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/websocket/WebSocketHubAdapter.d.ts +0 -21
- package/dist/lib/adapter/websocket/WebSocketHubAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/websocket/WebSocketPeerAdapter.d.ts +0 -28
- package/dist/lib/adapter/websocket/WebSocketPeerAdapter.d.ts.map +0 -1
- package/dist/lib/adapter/websocket/constants/webSocket.d.ts +0 -5
- package/dist/lib/adapter/websocket/constants/webSocket.d.ts.map +0 -1
- package/dist/lib/adapter/websocket/index.d.ts +0 -5
- package/dist/lib/adapter/websocket/index.d.ts.map +0 -1
- package/dist/lib/adapter/websocket/utils/reconnectDelay.d.ts +0 -2
- package/dist/lib/adapter/websocket/utils/reconnectDelay.d.ts.map +0 -1
- package/dist/message-port.cjs +0 -1
- package/dist/node-worker.cjs +0 -1
- package/dist/socket.cjs +0 -1
- package/dist/types/ConnectionStatus.d.ts +0 -6
- package/dist/types/ConnectionStatus.d.ts.map +0 -1
- package/dist/types/EventEmitter.d.ts +0 -6
- package/dist/types/EventEmitter.d.ts.map +0 -1
- package/dist/types/LogLevel.d.ts +0 -9
- package/dist/types/LogLevel.d.ts.map +0 -1
- package/dist/types/MethodMap.d.ts +0 -5
- package/dist/types/MethodMap.d.ts.map +0 -1
- package/dist/types/MethodName.d.ts +0 -9
- package/dist/types/MethodName.d.ts.map +0 -1
- package/dist/types/RpcChannel.d.ts +0 -29
- package/dist/types/RpcChannel.d.ts.map +0 -1
- package/dist/types/RpcChannelEvents.d.ts +0 -9
- package/dist/types/RpcChannelEvents.d.ts.map +0 -1
- package/dist/types/RpcHub.d.ts +0 -36
- package/dist/types/RpcHub.d.ts.map +0 -1
- package/dist/types/RpcMessages.d.ts +0 -37
- package/dist/types/RpcMessages.d.ts.map +0 -1
- package/dist/utils/controlMessages.d.ts +0 -14
- package/dist/utils/controlMessages.d.ts.map +0 -1
- package/dist/utils/createMethodProxy.d.ts +0 -5
- package/dist/utils/createMethodProxy.d.ts.map +0 -1
- package/dist/utils/rpc.d.ts +0 -26
- package/dist/utils/rpc.d.ts.map +0 -1
- package/dist/utils/uuid.d.ts +0 -2
- package/dist/utils/uuid.d.ts.map +0 -1
- package/dist/web-worker.cjs +0 -1
- package/dist/websocket.cjs +0 -1
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
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
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
|
|
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 iframes, Web Workers, SharedWorkers, WebSockets, Node.js worker threads and Node.js child processes ship today, see [Adapters](#adapters), and you can [write your own](#custom-adapters).
|
|
6
6
|
|
|
7
7
|
```ts
|
|
8
8
|
// Call a function in another window and await its result. Fully typed.
|
|
@@ -26,7 +26,7 @@ anyrpc takes care of all of this. You describe both directions of communication
|
|
|
26
26
|
|
|
27
27
|
- 🔒 **End-to-end type safety.** Method names, parameters and return types are inferred from your interfaces.
|
|
28
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.
|
|
29
|
+
- ⏱️ **Timeouts and cancellation.** Every request rejects with an `RpcError` if no response arrives in time. Single calls can set their own timeout and be cancelled with an `AbortSignal`.
|
|
30
30
|
- 📬 **Optional request queue.** Calls made before the connection is established can be queued and sent once connected.
|
|
31
31
|
- 🧯 **Error propagation.** Errors thrown in a remote handler are returned as JSON-RPC error responses and rejected locally as `RpcError`.
|
|
32
32
|
- 🔌 **Pluggable transports.** Adapters implement a small abstract class (`connect`, `sendMessage`, `destroy`), see [Custom adapters](#custom-adapters).
|
|
@@ -55,8 +55,13 @@ anyrpc takes care of all of this. You describe both directions of communication
|
|
|
55
55
|
npm install @schwarzdavid/anyrpc
|
|
56
56
|
```
|
|
57
57
|
|
|
58
|
-
>
|
|
59
|
-
|
|
58
|
+
> The package is ESM only; CommonJS code can load it with `require()` on Node.js 22.12 or newer. The Node.js adapters and the WebSocket client need Node.js 22 or newer.
|
|
59
|
+
|
|
60
|
+
### Stability
|
|
61
|
+
|
|
62
|
+
Releases before 1.0.0 may change the API at any time. From 1.0.0 on, anyrpc follows [semantic versioning](https://semver.org/), and every change is listed in the [changelog](CHANGELOG.md).
|
|
63
|
+
|
|
64
|
+
Two entry points are excluded from that promise and marked as **unstable**: `@schwarzdavid/anyrpc/adapters/socket` and `@schwarzdavid/anyrpc/adapters/message-port`. They contain the base classes for writing your own adapters and may change in a minor release. Such changes are called out in the changelog. If you build on them, pin the minor version (`~1.0.0`). The ready-made adapters built on top of them are stable.
|
|
60
65
|
|
|
61
66
|
### 1. Define your API contract
|
|
62
67
|
|
|
@@ -126,19 +131,32 @@ Both adapters must use the same **name** (`'my-app'` above). This lets several i
|
|
|
126
131
|
|
|
127
132
|
### Channel API
|
|
128
133
|
|
|
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>.
|
|
133
|
-
| `channel
|
|
134
|
-
| `channel.$.
|
|
135
|
-
| `channel.$.on(
|
|
136
|
-
| `channel.$.on('rpc.
|
|
137
|
-
| `channel.$.
|
|
138
|
-
| `channel.$.
|
|
134
|
+
| Member | Description |
|
|
135
|
+
| ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
136
|
+
| `channel.<method>(...args)` | Calls a remote method (JSON-RPC request). Always returns a `Promise` of the method's return type. |
|
|
137
|
+
| `channel.<method>.with(options)(...args)` | Same call with a `timeout` and/or an `AbortSignal` of its own, see [Call options](#call-options). |
|
|
138
|
+
| `channel.<method>.notify(...args)` | Sends a JSON-RPC notification: fire-and-forget, returns `void`. Only available for methods returning `void` or `Promise<void>`. |
|
|
139
|
+
| `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. |
|
|
140
|
+
| `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. |
|
|
141
|
+
| `channel.$.on('rpc.connected' \| 'rpc.disconnected' \| 'rpc.status', fn)` | Listens for connection events. `rpc.status` receives the new `ConnectionStatus`. |
|
|
142
|
+
| `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. |
|
|
143
|
+
| `channel.$.status` | Current `ConnectionStatus`: `'connected'`, `'disconnected'` or `'destroyed'`, see [Connection status](#connection-status). |
|
|
144
|
+
| `channel.$.destroy()` | Closes the connection for good and sets the status to `'destroyed'`. 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
145
|
|
|
140
146
|
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
147
|
|
|
148
|
+
### Connection status
|
|
149
|
+
|
|
150
|
+
A channel is in one of three states, available as `channel.$.status` and reported through `rpc.status`:
|
|
151
|
+
|
|
152
|
+
| Status | Meaning |
|
|
153
|
+
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
154
|
+
| `'disconnected'` | Not connected yet, or the connection is interrupted. The adapter keeps trying, so the channel can become `'connected'` (again). Calls are queued or throw `-31002`, see `queueEnabled`. |
|
|
155
|
+
| `'connected'` | Calls and notifications are sent right away. |
|
|
156
|
+
| `'destroyed'` | Final. You called `channel.$.destroy()`, or the transport is gone for good (e.g. the worker or child process exited). Pending and queued calls reject with `-31003`, new calls throw `-31002`. |
|
|
157
|
+
|
|
158
|
+
A destroyed channel never connects again, and its adapter cannot be used for another channel. Create a new adapter and a new channel instead. `rpc.disconnected` is emitted whenever the channel leaves `connected`, also when it is destroyed.
|
|
159
|
+
|
|
142
160
|
### Requests, notifications and listeners
|
|
143
161
|
|
|
144
162
|
- **Requests** (`channel.ping()`) wait for a response. If no handler is registered on the other side, the promise rejects with `-32601` (method not found).
|
|
@@ -149,13 +167,32 @@ A remote method cannot be named `$`, `then`, `toJSON`, anything starting with `r
|
|
|
149
167
|
- 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
168
|
- `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
169
|
|
|
170
|
+
### Call options
|
|
171
|
+
|
|
172
|
+
A single call can deviate from the channel options. `with(options)` returns the method with the same parameters and return type:
|
|
173
|
+
|
|
174
|
+
```ts
|
|
175
|
+
const controller = new AbortController()
|
|
176
|
+
|
|
177
|
+
const report = await channel.buildReport.with({ timeout: 60_000, signal: controller.signal })(2026)
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
| Option | Description |
|
|
181
|
+
| --------- | -------------------------------------------------------------------------------------------------------------------- |
|
|
182
|
+
| `timeout` | Milliseconds to wait for the response of this call instead of the `timeout` of the channel. |
|
|
183
|
+
| `signal` | An `AbortSignal` that cancels the call. The promise rejects with the signal's `reason` (an `AbortError` by default). |
|
|
184
|
+
|
|
185
|
+
- A call whose signal is already aborted is not sent. A queued call that is aborted before the connection is established is not sent either.
|
|
186
|
+
- Aborting only stops waiting. The other side is not told, so a request that was already sent is still handled there and its response is ignored.
|
|
187
|
+
- Notifications have no response to wait for and therefore no options.
|
|
188
|
+
|
|
152
189
|
### Channel options
|
|
153
190
|
|
|
154
191
|
`createRpcChannel(adapter, options)` takes an optional second argument:
|
|
155
192
|
|
|
156
193
|
| Option | Default | Description |
|
|
157
194
|
| ------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
158
|
-
| `timeout` | `3000` | Milliseconds to wait for a response before rejecting with a timeout `RpcError`.
|
|
195
|
+
| `timeout` | `3000` | Milliseconds to wait for a response before rejecting with a timeout `RpcError`. Can be set per call, see [Call options](#call-options). |
|
|
159
196
|
| `queueEnabled` | `false` | Queue calls made while disconnected instead of rejecting them immediately. |
|
|
160
197
|
| `queueTimeout` | `10000` | Milliseconds a queued call may wait for a connection before it rejects. |
|
|
161
198
|
| `queueAwait` | `false` | Send queued calls one after another, waiting for each response, instead of all at once. |
|
|
@@ -249,8 +286,8 @@ import { createRpcHub } from '@schwarzdavid/anyrpc'
|
|
|
249
286
|
import { SharedWorkerHubAdapter } from '@schwarzdavid/anyrpc/adapters/web-worker'
|
|
250
287
|
import type { PageToWorker, WorkerToPage } from './messages'
|
|
251
288
|
|
|
252
|
-
//
|
|
253
|
-
const hub = createRpcHub<WorkerToPage, PageToWorker>(
|
|
289
|
+
// SharedWorkerHubAdapter<MethodsOfEveryPeer, MethodsICanHandle>
|
|
290
|
+
const hub = createRpcHub(new SharedWorkerHubAdapter<WorkerToPage, PageToWorker>('my-app'))
|
|
254
291
|
|
|
255
292
|
// Handlers and listeners receive the calling peer as first argument
|
|
256
293
|
hub.$.handle('getState', ({ peer }, key) => store.get(peer.id, key))
|
|
@@ -267,15 +304,18 @@ const fastest = await Promise.any(hub.getTitle())
|
|
|
267
304
|
| Member | Description |
|
|
268
305
|
| --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
269
306
|
| `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`, ... |
|
|
307
|
+
| `hub.<method>.with(options)(...args)` | Same broadcast with [call options](#call-options) that apply to the call of every peer. |
|
|
270
308
|
| `hub.<method>.notify(...args)` | Notifies every connected peer. A peer that cannot be notified is logged and skipped. |
|
|
271
309
|
| `hub.$.handle(name, (context, ...args) => result)` | Answers calls of `name` from every peer. `context.peer` is the calling peer. One handler per method. |
|
|
272
310
|
| `hub.$.on(name, (context, ...args) => void)` | Observes calls and notifications of `name` from every peer. |
|
|
273
311
|
| `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
|
|
312
|
+
| `hub.$.peers` / `hub.$.peer(id)` | The connected peers. Each peer has an `id`, its own `channel` to call it individually (`peer.channel.method()`) and a `context`. |
|
|
275
313
|
| `hub.$.destroy()` | Disconnects all peers and stops accepting new ones. |
|
|
276
314
|
|
|
277
315
|
- 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`.
|
|
316
|
+
- 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 channel is then `destroyed` and its pending calls reject with `-31003`. A peer that comes back is a new peer with a new id.
|
|
317
|
+
- `peer.context` holds what the transport knows about the peer: the upgrade request for [WebSockets](#websocket-adapter), `undefined` for SharedWorkers. The hub never changes it. For state of your own per peer, such as the user after a login call, keep a `WeakMap<RpcPeer, State>`.
|
|
318
|
+
- Write the type arguments on the hub adapter, as above, so that the type of `peer.context` is inferred. `createRpcHub<Methods, Events>(adapter)` works as well, but TypeScript cannot infer the remaining type then: for an adapter with a context, `peer.context` is `unknown` and the hub is an `RpcHub<Methods, Events, unknown>`.
|
|
279
319
|
- Promises of a broadcast that you never await do not cause unhandled rejections; failures are logged at `DEBUG` level.
|
|
280
320
|
- 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
321
|
|
|
@@ -332,7 +372,7 @@ const channel = createRpcChannel<WorkerToMain, MainToWorker>(new NodeWorkerClien
|
|
|
332
372
|
```
|
|
333
373
|
|
|
334
374
|
- 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 `
|
|
375
|
+
- Uncaught errors in the worker are logged. Once the worker exits, the channel is `destroyed`: in-flight and queued calls reject with `-31003`, and new calls throw `-31002`.
|
|
336
376
|
- 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
377
|
- Creating `NodeWorkerClientAdapter` outside of a worker thread throws an error that points you to `NodeWorkerHostAdapter`.
|
|
338
378
|
- 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`.
|
|
@@ -372,7 +412,7 @@ const channel = createRpcChannel<ChildToParent, ParentToChild>(new ChildProcessC
|
|
|
372
412
|
- Both sides must use the same **name**, so one child can serve several channels. Your own `process.send` messages are ignored.
|
|
373
413
|
- 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
414
|
- 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 `
|
|
415
|
+
- Once the child exits or disconnects its IPC channel (`process.disconnect()`), the channel is `destroyed`: in-flight and queued calls reject with `-31003`, and new calls throw `-31002`.
|
|
376
416
|
- When the child destroys its channel, the parent channel reconnects as soon as the child creates a new one.
|
|
377
417
|
- 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
418
|
- Errors from spawning the child are not handled by the adapter. Listen to `child.on('error', …)` yourself.
|
|
@@ -388,51 +428,22 @@ const channel = createRpcChannel<ChildToParent, ParentToChild>(new ChildProcessC
|
|
|
388
428
|
|
|
389
429
|
**`new ChildProcessClientAdapter(name?)`** has no options: the parent configures the connection.
|
|
390
430
|
|
|
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
431
|
### WebSocket adapter
|
|
425
432
|
|
|
426
433
|
`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
434
|
|
|
428
435
|
```ts
|
|
429
436
|
// server.ts
|
|
437
|
+
import type { IncomingMessage } from 'node:http'
|
|
430
438
|
import { WebSocketServer } from 'ws'
|
|
431
439
|
import { createRpcHub } from '@schwarzdavid/anyrpc'
|
|
432
440
|
import { WebSocketHubAdapter } from '@schwarzdavid/anyrpc/adapters/websocket'
|
|
433
441
|
|
|
434
442
|
const server = new WebSocketServer({ port: 8081 })
|
|
435
|
-
const hub = createRpcHub<ServerToClient, ClientToServer>(
|
|
443
|
+
const hub = createRpcHub(new WebSocketHubAdapter<ServerToClient, ClientToServer, IncomingMessage>(server))
|
|
444
|
+
|
|
445
|
+
// Every peer carries the HTTP request that opened its connection
|
|
446
|
+
hub.$.handle('getProfile', ({ peer }) => loadProfile(readSession(peer.context.request.headers.cookie)))
|
|
436
447
|
```
|
|
437
448
|
|
|
438
449
|
```ts
|
|
@@ -443,6 +454,8 @@ import { WebSocketClientAdapter } from '@schwarzdavid/anyrpc/adapters/websocket'
|
|
|
443
454
|
const channel = createRpcChannel<ClientToServer, ServerToClient>(new WebSocketClientAdapter('wss://example.com/rpc'))
|
|
444
455
|
```
|
|
445
456
|
|
|
457
|
+
- `peer.context.request` is the upgrade request of the peer, with its headers (cookies, `Authorization`), URL and remote address. The third type argument of `WebSocketHubAdapter` is its type; without it, the request is typed as `WebSocketRequestLike`, which only has `headers` and `url`. The server has to pass the request as second argument of its `connection` event, as `ws` does.
|
|
458
|
+
- anyrpc has no option to reject a connection. Do that before the connection becomes a peer, with the means of your server: `new WebSocketServer({ port, verifyClient: ({ req }) => isAllowed(req) })`, or `noServer` together with `handleUpgrade`.
|
|
446
459
|
- Only text frames are exchanged, binary frames are dropped.
|
|
447
460
|
- 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
461
|
- 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.
|
|
@@ -463,9 +476,42 @@ const channel = createRpcChannel<ClientToServer, ServerToClient>(new WebSocketCl
|
|
|
463
476
|
| ----------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
464
477
|
| `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
478
|
|
|
479
|
+
### Error handling
|
|
480
|
+
|
|
481
|
+
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`:
|
|
482
|
+
|
|
483
|
+
```ts
|
|
484
|
+
import { RpcError, RpcErrorCode } from '@schwarzdavid/anyrpc'
|
|
485
|
+
|
|
486
|
+
try {
|
|
487
|
+
await channel.getTitle()
|
|
488
|
+
} catch (err) {
|
|
489
|
+
// err.code: -32000 (server error), -32601 (method not found), -31001 (timeout), -31002 (not connected), -31003 (connection lost), ...
|
|
490
|
+
if (err instanceof RpcError && err.code === RpcErrorCode.TIMEOUT_ERROR) {
|
|
491
|
+
retryLater()
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
```
|
|
495
|
+
|
|
496
|
+
| Code | Origin | Meaning |
|
|
497
|
+
| -------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
498
|
+
| `-32700` | remote | The other side could not parse the message as JSON. `data.reason` explains why. |
|
|
499
|
+
| `-32600` | remote | The message is not a valid JSON-RPC request (e.g. `method` is not a string). `data.reason` explains why. |
|
|
500
|
+
| `-32601` | remote | No handler is registered for the called method, or the method name starts with `rpc.`. |
|
|
501
|
+
| `-32602` | remote | The call used named params (an object). Handlers only support positional params. |
|
|
502
|
+
| `-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`. |
|
|
503
|
+
| `-32000` | remote | The remote handler threw. The original error's `name` and `message` are in `data`. |
|
|
504
|
+
| `-31001` | local | No response arrived within `timeout`, or a queued call waited longer than `queueTimeout`. |
|
|
505
|
+
| `-31002` | local | The method was called while disconnected and the queue is disabled, or after the channel was destroyed. |
|
|
506
|
+
| `-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. |
|
|
507
|
+
|
|
508
|
+
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.
|
|
509
|
+
|
|
510
|
+
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.
|
|
511
|
+
|
|
466
512
|
### Custom adapters
|
|
467
513
|
|
|
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
|
|
514
|
+
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 current connection 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. Call `this.destroy()` when the transport can never connect again (e.g. the process on the other side exited): the status becomes `destroyed`, which is final, and the channel rejects everything that is still waiting. Status changes follow a small state machine: `disconnected` and `connected` can alternate, `destroyed` is never left, and a change to the current status is ignored. `connect()` may return a promise; if it rejects, the channel logs the error and stays `disconnected`. The channel wires itself to the adapter through `adapter.bind(...)`, you never call it yourself. Log messages of an adapter are prefixed with its `logName`; override it (`protected override readonly logName = 'MyWebSocketAdapter'`), because class names do not survive minification. An adapter instance serves exactly one channel, so `createRpcChannel` throws if the adapter is already in use or was destroyed.
|
|
469
515
|
|
|
470
516
|
```ts
|
|
471
517
|
import { AbstractRpcAdapter, ConnectionStatus, type MethodMap, type RpcMessage } from '@schwarzdavid/anyrpc'
|
|
@@ -494,13 +540,15 @@ class MyWebSocketAdapter<
|
|
|
494
540
|
|
|
495
541
|
This example only illustrates the contract; use `@schwarzdavid/anyrpc/adapters/websocket` for WebSockets in production.
|
|
496
542
|
|
|
543
|
+
> ⚠️ The two entry points described next, `@schwarzdavid/anyrpc/adapters/socket` and `@schwarzdavid/anyrpc/adapters/message-port`, are **unstable** and may change in a minor release, see [Stability](#stability). `AbstractRpcAdapter` and `AbstractRpcHubAdapter` from the package entry are stable.
|
|
544
|
+
|
|
497
545
|
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
546
|
|
|
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 `
|
|
547
|
+
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 `AbstractMessagePortInitiatorAdapter` for the side that starts the handshake and polls until it is answered, and `AbstractMessagePortResponderAdapter` for the side that answers it and creates the `MessageChannel`s. Both take one options object in their constructor: `initMethod` (the name of your handshake message), `name` (the channel name both sides share) and optionally `heartbeat`, plus `pollingInterval` for the initiator. 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
548
|
|
|
501
549
|
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
550
|
|
|
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.
|
|
551
|
+
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. To tell consumers something about a peer, declare its type as third type argument, `AbstractRpcHubAdapter<Methods, Events, Context>`, and pass the value with `this.addPeer(adapter, context)`; it becomes `peer.context`. The argument is only required if `Context` cannot be `undefined`. Give your adapter class a fixed context type rather than a type parameter with a default: `createRpcHub<Methods, Events>(new MyHubAdapter())` would infer such a parameter as `undefined` instead of using the default. A peer is removed as soon as its adapter is destroyed, so a peer adapter only has to call its own `destroy()` when the connection is gone. To remove a peer for another reason, call `this.removePeer(id)`.
|
|
504
552
|
|
|
505
553
|
`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
554
|
|
|
@@ -529,7 +577,7 @@ npm run coverage # Tests with coverage report
|
|
|
529
577
|
npm run check # TypeScript project build
|
|
530
578
|
npm run lint # ESLint
|
|
531
579
|
npm run format # Prettier check
|
|
532
|
-
npm run build # Build ESM
|
|
580
|
+
npm run build # Build the ESM bundles and type declarations into dist/
|
|
533
581
|
```
|
|
534
582
|
|
|
535
583
|
## Todo
|
|
@@ -541,11 +589,16 @@ npm run build # Build ESM + CJS bundles and type declarations into dist/
|
|
|
541
589
|
|
|
542
590
|
**Protocol and behavior**
|
|
543
591
|
|
|
544
|
-
- [
|
|
592
|
+
- [x] Support request cancellation (e.g. via `AbortSignal`)
|
|
593
|
+
- [x] Give hub peers a connection context (e.g. the upgrade request of a WebSocket)
|
|
545
594
|
- [x] Warn when `IFrameClientAdapter` allows any origin (`origin: true`)
|
|
546
595
|
|
|
547
596
|
**Project**
|
|
548
597
|
|
|
549
598
|
- [ ] Add API documentation and more examples
|
|
550
|
-
- [
|
|
551
|
-
- [
|
|
599
|
+
- [x] Set up CI (lint, type check, test, build)
|
|
600
|
+
- [x] Add a changelog
|
|
601
|
+
|
|
602
|
+
## License
|
|
603
|
+
|
|
604
|
+
[MPL-2.0](LICENSE). You can use anyrpc in open and closed source projects. Changes to the files of anyrpc itself have to be published under the same license.
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { n as HeartbeatOptions, t as HeartbeatOption } from "./chunks/Heartbeat-GHewy9_w.js";
|
|
2
|
+
import { v as MethodMap } from "./chunks/AbstractRpcAdapter-fNu6wvPV.js";
|
|
3
|
+
import { t as AbstractSocketAdapter } from "./chunks/AbstractSocketAdapter-CGdtVMSQ.js";
|
|
4
|
+
export interface ChildProcessHostAdapterOptions {
|
|
5
|
+
pollingInterval: number;
|
|
6
|
+
heartbeat: HeartbeatOption;
|
|
7
|
+
killOnDestroy: boolean;
|
|
8
|
+
}
|
|
9
|
+
export interface ChildProcessLike {
|
|
10
|
+
readonly connected: boolean;
|
|
11
|
+
send(message: unknown, callback: (error: Error | null) => void): boolean;
|
|
12
|
+
on(event: 'message', listener: (message: unknown) => void): unknown;
|
|
13
|
+
on(event: 'exit', listener: (code: number | null) => void): unknown;
|
|
14
|
+
on(event: 'disconnect', listener: () => void): unknown;
|
|
15
|
+
off(event: 'message', listener: (message: unknown) => void): unknown;
|
|
16
|
+
off(event: 'exit', listener: (code: number | null) => void): unknown;
|
|
17
|
+
off(event: 'disconnect', listener: () => void): unknown;
|
|
18
|
+
kill(): boolean;
|
|
19
|
+
}
|
|
20
|
+
export declare class ChildProcessHostAdapter<Methods extends MethodMap<Methods>, Events extends MethodMap<Events>> extends AbstractSocketAdapter<Methods, Events> {
|
|
21
|
+
private readonly child;
|
|
22
|
+
private readonly name;
|
|
23
|
+
protected readonly logName = "ChildProcessHostAdapter";
|
|
24
|
+
private readonly pollingInterval;
|
|
25
|
+
private readonly killOnDestroy;
|
|
26
|
+
private handshake;
|
|
27
|
+
private readonly onChildMessage;
|
|
28
|
+
private readonly onChildExit;
|
|
29
|
+
private readonly onChildDisconnect;
|
|
30
|
+
private readonly onSendResult;
|
|
31
|
+
constructor(child: ChildProcessLike, name?: string, options?: Partial<ChildProcessHostAdapterOptions>);
|
|
32
|
+
connect(): void;
|
|
33
|
+
protected send(message: object): void;
|
|
34
|
+
protected onRemoteGoodbye(): void;
|
|
35
|
+
destroy(): void;
|
|
36
|
+
private startHandshake;
|
|
37
|
+
private stopHandshake;
|
|
38
|
+
private handleChildMessage;
|
|
39
|
+
private handleChildExit;
|
|
40
|
+
private handleChildDisconnect;
|
|
41
|
+
private handleSendResult;
|
|
42
|
+
private stopListening;
|
|
43
|
+
}
|
|
44
|
+
export declare class ChildProcessClientAdapter<Methods extends MethodMap<Methods>, Events extends MethodMap<Events>> extends AbstractSocketAdapter<Methods, Events> {
|
|
45
|
+
private readonly name;
|
|
46
|
+
protected readonly logName = "ChildProcessClientAdapter";
|
|
47
|
+
private readonly ipc;
|
|
48
|
+
private answeredInitId;
|
|
49
|
+
private readonly onParentMessage;
|
|
50
|
+
private readonly onDisconnect;
|
|
51
|
+
private readonly onSendResult;
|
|
52
|
+
constructor(name?: string);
|
|
53
|
+
connect(): void;
|
|
54
|
+
protected send(message: object): void;
|
|
55
|
+
destroy(): void;
|
|
56
|
+
private handleSendResult;
|
|
57
|
+
private handleParentMessage;
|
|
58
|
+
private acceptInitRequest;
|
|
59
|
+
private stopListening;
|
|
60
|
+
}
|
|
61
|
+
export type { HeartbeatOption, HeartbeatOptions };
|
|
62
|
+
//# sourceMappingURL=child-process.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"child-process.d.ts","names":[],"sources":["../src/lib/adapter/child-process/ChildProcessHostAdapter.ts","../src/lib/adapter/child-process/ChildProcessClientAdapter.ts"],"mappings":";;;iBAOiB;EACb;EACA,WAAW;EACX;;iBAGa;WACJ;EACT,KAAK,kBAAkB,WAAW,OAAO;EACzC,GAAG,kBAAkB,WAAW;EAChC,GAAG,eAAe,WAAW;EAC7B,GAAG,qBAAqB;EACxB,IAAI,kBAAkB,WAAW;EACjC,IAAI,eAAe,WAAW;EAC9B,IAAI,qBAAqB;EACzB;;qBAQS,wBACT,gBAAgB,UAAU,UAC1B,eAAe,UAAU,iBACnB,sBAAsB,SAAS;mBAWhB;mBACA;qBAXO;mBACX;mBACA;UACT;mBACS;mBACA;mBACA;mBACA;EAGI,YAAA,OAAO,kBACP,eACjB,UAAU,QAAQ;EAOtB;YAYU,KAAK;YAMI;EAKV;UASD;UAWA;UAKA;UAcA;UAKA;UAKA;UAMA;;qBC/GC,0BACT,gBAAgB,UAAU,UAC1B,eAAe,UAAU,iBACnB,sBAAsB,SAAS;mBAQR;qBAPD;mBACX;UACT;mBACS;mBACA;mBACA;EAEY,YAAA;EAK7B;YAMU,KAAK;EAMN;UAKD;UAMA;UAaA;UAaA"}
|