capnweb 0.0.0-0d6b2ff → 0.0.0-143d13d
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/README.md +112 -695
- package/dist/index-bun.cjs +650 -185
- package/dist/index-bun.cjs.map +1 -1
- package/dist/index-bun.d.cts +208 -39
- package/dist/index-bun.d.ts +208 -39
- package/dist/index-bun.js +648 -185
- package/dist/index-bun.js.map +1 -1
- package/dist/index-workers.cjs +651 -185
- package/dist/index-workers.cjs.map +1 -1
- package/dist/index-workers.d.cts +204 -38
- package/dist/index-workers.d.ts +204 -38
- package/dist/index-workers.js +648 -185
- package/dist/index-workers.js.map +1 -1
- package/dist/index.cjs +650 -185
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +204 -38
- package/dist/index.d.ts +204 -38
- package/dist/index.js +648 -185
- package/dist/index.js.map +1 -1
- package/package.json +25 -21
package/README.md
CHANGED
|
@@ -1,29 +1,52 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
<!-- The banner precedes the h1 on purpose: it is the title, drawn. MD041 wants
|
|
2
|
+
the heading first, which is right everywhere else in this repository. -->
|
|
3
|
+
<!-- markdownlint-disable-next-line MD041 -->
|
|
4
|
+

|
|
5
|
+
|
|
6
|
+
<!-- markdownlint-disable-next-line MD033 -->
|
|
7
|
+
<h1 align="center">Cap'n Web: A JavaScript-native RPC system</h1>
|
|
8
|
+
|
|
9
|
+
Cap'n Web is a spiritual sibling to [Cap'n Proto](https://capnproto.org) (and is created by the
|
|
10
|
+
same author), but designed to play nice in the web stack. That means:
|
|
11
|
+
|
|
12
|
+
* Like Cap'n Proto, it is an **object-capability protocol**. ("Cap'n" is short for "capabilities
|
|
13
|
+
and.") It's incredibly powerful.
|
|
14
|
+
* Unlike Cap'n Proto, Cap'n Web has **no schemas**. In fact, it has almost no boilerplate
|
|
15
|
+
whatsoever. This means it works more like the
|
|
16
|
+
[JavaScript-native RPC system in Cloudflare Workers](https://blog.cloudflare.com/javascript-native-rpc/).
|
|
6
17
|
* That said, it integrates nicely with TypeScript.
|
|
7
|
-
* Also unlike Cap'n Proto, Cap'n Web's underlying serialization is human-readable
|
|
8
|
-
|
|
9
|
-
* It works
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
+
* Also unlike Cap'n Proto, Cap'n Web's underlying serialization is **human-readable**. It's just
|
|
19
|
+
JSON, with a little pre- and post-processing.
|
|
20
|
+
* It works over HTTP, WebSocket, and `postMessage()` out of the box, and can be extended to other
|
|
21
|
+
transports easily.
|
|
22
|
+
* It works in all major browsers, Cloudflare Workers, Node.js, Bun, Deno, and other modern
|
|
23
|
+
JavaScript runtimes.
|
|
24
|
+
|
|
25
|
+
The whole thing compresses (minify + gzip) to **under 16 kB with no dependencies**.
|
|
26
|
+
|
|
27
|
+
Cap'n Web is more expressive than almost every other RPC system, because it implements an
|
|
28
|
+
object-capability RPC model. That means it supports **bidirectional calling**, **passing functions
|
|
29
|
+
and objects by reference**, **promise pipelining** (chaining dependent calls into a single network
|
|
30
|
+
round trip), and **capability-based security patterns**, where holding a reference *is* the
|
|
31
|
+
permission to use it.
|
|
18
32
|
|
|
19
33
|
## Installation
|
|
20
34
|
|
|
21
35
|
[Cap'n Web is an npm package.](https://www.npmjs.com/package/capnweb)
|
|
22
36
|
|
|
23
|
-
```
|
|
37
|
+
```sh
|
|
24
38
|
npm i capnweb
|
|
25
39
|
```
|
|
26
40
|
|
|
41
|
+
There is no build step, no schema compiler, and no code generation.
|
|
42
|
+
|
|
43
|
+
```js
|
|
44
|
+
import { RpcTarget, newWebSocketRpcSession } from "capnweb";
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
To use `using` declarations, your `tsconfig.json` needs `"target": "esnext"` and matching `lib`s.
|
|
48
|
+
See [Installation](packages/docs/src/content/docs/start/installation.mdx).
|
|
49
|
+
|
|
27
50
|
## Example
|
|
28
51
|
|
|
29
52
|
A client looks like this:
|
|
@@ -54,7 +77,7 @@ class MyApiServer extends RpcTarget {
|
|
|
54
77
|
|
|
55
78
|
// Standard Cloudflare Workers HTTP handler.
|
|
56
79
|
//
|
|
57
|
-
// (Node and other runtimes are supported too
|
|
80
|
+
// (Node, Deno, Bun and other runtimes are supported too.)
|
|
58
81
|
export default {
|
|
59
82
|
fetch(request, env, ctx) {
|
|
60
83
|
// Parse URL for routing.
|
|
@@ -71,708 +94,102 @@ export default {
|
|
|
71
94
|
}
|
|
72
95
|
```
|
|
73
96
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
Here's an example that:
|
|
77
|
-
* Uses TypeScript
|
|
78
|
-
* Sends multiple calls, where the second call depends on the result of the first, in one round trip.
|
|
79
|
-
|
|
80
|
-
We declare our interface in a shared types file:
|
|
81
|
-
|
|
82
|
-
```ts
|
|
83
|
-
interface PublicApi {
|
|
84
|
-
// Authenticate the API token, and returned the authenticated API.
|
|
85
|
-
authenticate(apiToken: string): AuthedApi;
|
|
86
|
-
|
|
87
|
-
// Get a given user's public profile info. (Doesn't require authentication.)
|
|
88
|
-
getUserProfile(userId: string): Promise<UserProfile>;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
interface AuthedApi {
|
|
92
|
-
getUserId(): number;
|
|
93
|
-
|
|
94
|
-
// Get the user IDs of all the user's friends.
|
|
95
|
-
getFriendIds(): number[];
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
type UserProfile = {
|
|
99
|
-
name: string;
|
|
100
|
-
photoUrl: string;
|
|
101
|
-
}
|
|
102
|
-
```
|
|
103
|
-
|
|
104
|
-
(Note: you don't _have to_ declare your interface separately. The client could just use `import("./server").ApiServer` as the type.)
|
|
105
|
-
|
|
106
|
-
On the server, we implement the interface as an RpcTarget:
|
|
107
|
-
|
|
108
|
-
```ts
|
|
109
|
-
import { newWorkersRpcResponse, RpcTarget } from "capnweb";
|
|
110
|
-
|
|
111
|
-
class ApiServer extends RpcTarget implements PublicApi {
|
|
112
|
-
// ... implement PublicApi ...
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
export default {
|
|
116
|
-
async fetch(req, env, ctx) {
|
|
117
|
-
// ... same as previous example ...
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
```
|
|
121
|
-
|
|
122
|
-
On the client, we can use it in a batch request:
|
|
123
|
-
|
|
124
|
-
```ts
|
|
125
|
-
import { newHttpBatchRpcSession } from "capnweb";
|
|
126
|
-
|
|
127
|
-
let api = newHttpBatchRpcSession<PublicApi>("https://example.com/api");
|
|
128
|
-
|
|
129
|
-
// Call authenticate(), but don't await it. We can use the returned promise
|
|
130
|
-
// to make "pipelined" calls without waiting.
|
|
131
|
-
let authedApi: RpcPromise<AuthedApi> = api.authenticate(apiToken);
|
|
132
|
-
|
|
133
|
-
// Make a pipelined call to get the user's ID. Again, don't await it.
|
|
134
|
-
let userIdPromise: RpcPromise<number> = authedApi.getUserId();
|
|
135
|
-
|
|
136
|
-
// Make another pipelined call to fetch the user's public profile, based on
|
|
137
|
-
// the user ID. Notice how we can use `RpcPromise<T>` in the parameters of a
|
|
138
|
-
// call anywhere where T is expected. The promise will be replaced with its
|
|
139
|
-
// resolution before delivering the call.
|
|
140
|
-
let profilePromise = api.getUserProfile(userIdPromise);
|
|
141
|
-
|
|
142
|
-
// Make another call to get the user's friends.
|
|
143
|
-
let friendsPromise = authedApi.getFriendIds();
|
|
144
|
-
|
|
145
|
-
// That only returns an array of user IDs, but we want all the profile info
|
|
146
|
-
// too, so use the magic .map() function to get them, too! Still one round
|
|
147
|
-
// trip.
|
|
148
|
-
let friendProfilesPromise = friendsPromise.map((id: RpcPromise<number>) => {
|
|
149
|
-
return { id, profile: api.getUserProfile(id) };
|
|
150
|
-
});
|
|
151
|
-
|
|
152
|
-
// Now await the promises. The batch is sent at this point. It's important
|
|
153
|
-
// to simultaneously await all promises for which you actually want the
|
|
154
|
-
// result. If you don't actually await a promise before the batch is sent,
|
|
155
|
-
// the system detects this and doesn't actually ask the server to send the
|
|
156
|
-
// return value back!
|
|
157
|
-
let [profile, friendProfiles] =
|
|
158
|
-
await Promise.all([profilePromise, friendProfilesPromise]);
|
|
159
|
-
|
|
160
|
-
console.log(`Hello, ${profile.name}!`);
|
|
161
|
-
|
|
162
|
-
// Note that at this point, the `api` and `authedApi` stubs no longer work,
|
|
163
|
-
// because the batch is done. You must start a new batch.
|
|
164
|
-
```
|
|
165
|
-
|
|
166
|
-
Alternatively, for a long-running interactive application, we can set up a persistent WebSocket connection:
|
|
97
|
+
And here is the part that makes it interesting. Three dependent calls, one round trip:
|
|
167
98
|
|
|
168
99
|
```ts
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
// We declare `api` with `using` so that it'll be disposed at the end of the
|
|
172
|
-
// scope, which closes the connection. `using` is a fairly new JavaScript
|
|
173
|
-
// feature, part of the "explicit resource management" spec. Alternatively,
|
|
174
|
-
// we could declare `api` with `let` or `const` and make sure to call
|
|
175
|
-
// `api[Symbol.dispose]()` to dispose it and close the connection later.
|
|
176
|
-
using api = newWebSocketRpcSession<PublicApi>("wss://example.com/api");
|
|
177
|
-
|
|
178
|
-
// Usage is exactly the same, except we don't have to await all the promises
|
|
179
|
-
// at once.
|
|
100
|
+
using api = newHttpBatchRpcSession<Api>("https://example.com/api");
|
|
180
101
|
|
|
181
|
-
//
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
// but disposing it does release the `AuthedApi` object on the server side.
|
|
185
|
-
using authedApi: RpcPromise<AuthedApi> = api.authenticate(apiToken);
|
|
186
|
-
let userId: number = await authedApi.getUserId();
|
|
102
|
+
// No awaits, so no round trips yet.
|
|
103
|
+
using authed = api.authenticate(apiToken);
|
|
104
|
+
let friendIds = authed.getFriendIds();
|
|
187
105
|
|
|
188
|
-
//
|
|
106
|
+
// One await. One round trip. Everything above travelled together.
|
|
107
|
+
let friends = await friendIds.map(id => api.getUserProfile(id));
|
|
189
108
|
```
|
|
190
109
|
|
|
191
|
-
##
|
|
192
|
-
|
|
193
|
-
### Pass-by-value types
|
|
194
|
-
|
|
195
|
-
The following types can be passed over RPC (in arguments or return values), and will be passed "by value", meaning the content is serialized, producing a copy at the receiving end:
|
|
196
|
-
|
|
197
|
-
* Primitive values: strings, numbers, booleans, null, undefined
|
|
198
|
-
* Plain objects (e.g., from object literals)
|
|
199
|
-
* Arrays
|
|
200
|
-
* `bigint`
|
|
201
|
-
* `Date`
|
|
202
|
-
* `Uint8Array`
|
|
203
|
-
* `Error` and its well-known subclasses
|
|
204
|
-
* `Blob`
|
|
205
|
-
* `ReadableStream` and `WritableStream`, with automatic flow control.
|
|
206
|
-
* `Headers`, `Request`, and `Response` from the Fetch API.
|
|
207
|
-
|
|
208
|
-
The following types are not supported as of this writing, but may be added in the future:
|
|
209
|
-
* `Map` and `Set`
|
|
210
|
-
* `ArrayBuffer` and typed arrays other than `Uint8Array`
|
|
211
|
-
* `RegExp`
|
|
212
|
-
|
|
213
|
-
The following are intentionally NOT supported:
|
|
214
|
-
* Application-defined classes that do not extend `RpcTarget`.
|
|
215
|
-
* Cyclic values. Messages are serialized strictly as trees (like JSON).
|
|
216
|
-
|
|
217
|
-
### `RpcTarget`
|
|
218
|
-
|
|
219
|
-
To export an interface over RPC, you must write a class that `extends RpcTarget`. Extending `RpcTarget` tells the RPC system: instances of this class are _pass-by-reference_. When an instance is passed over RPC, the object should NOT be serialized. Instead, the RPC message will contain a "stub" that points back to the original target object. Invoking this stub calls back over RPC.
|
|
220
|
-
|
|
221
|
-
When you send someone an `RpcTarget` reference, they will be able to call any class method over RPC, including getters. They will not, however, be able to access "own" properties. In precise JavaScript terms, they can access prototype properties but not instance properties. This policy is intended to "do the right thing" for typical JavaScript code, where private members are typically stored as instance properties.
|
|
222
|
-
|
|
223
|
-
WARNING: If you are using TypeScript, note that declaring a method `private` does not hide it from RPC, because TypeScript annotations are "erased" at runtime, so cannot be enforced. To actually make methods private, you must prefix their names with `#`, which makes them private for JavaScript (not just TypeScript). Names prefixed with `#` are never available over RPC.
|
|
224
|
-
|
|
225
|
-
### Functions
|
|
226
|
-
|
|
227
|
-
When a plain function is passed over RPC, it will be treated similarly to an `RpcTarget`. The function will be replaced by a stub which, when invoked, calls back over RPC to the original function object.
|
|
110
|
+
## Documentation
|
|
228
111
|
|
|
229
|
-
|
|
112
|
+
**The [documentation site](packages/docs/) is the source of truth.** It is an Astro + Starlight site
|
|
113
|
+
under [`packages/docs/`](packages/docs/), and every page is readable as Markdown directly on GitHub.
|
|
230
114
|
|
|
231
|
-
|
|
115
|
+
Start here:
|
|
232
116
|
|
|
233
|
-
|
|
117
|
+
| Page | What it covers |
|
|
118
|
+
| --------------------------------------------------------------------------- | ---------------------------------------------------- |
|
|
119
|
+
| [Introduction](packages/docs/src/content/docs/start/introduction.mdx) | What Cap'n Web is and why object capabilities matter |
|
|
120
|
+
| [Quickstart](packages/docs/src/content/docs/start/quickstart.mdx) | A working client and server |
|
|
121
|
+
| [Pipelining tour](packages/docs/src/content/docs/start/pipelining-tour.mdx) | The part that makes it fast |
|
|
122
|
+
| [How it compares](packages/docs/src/content/docs/guides/comparisons.mdx) | Against tRPC, JSON-RPC, GraphQL and Cap'n Proto |
|
|
234
123
|
|
|
235
|
-
|
|
124
|
+
Core concepts:
|
|
125
|
+
[What can be passed](packages/docs/src/content/docs/concepts/values.mdx) ·
|
|
126
|
+
[RpcTarget](packages/docs/src/content/docs/concepts/rpc-target.mdx) ·
|
|
127
|
+
[RpcStub](packages/docs/src/content/docs/concepts/stubs.mdx) ·
|
|
128
|
+
[RpcPromise & pipelining](packages/docs/src/content/docs/concepts/promises.mdx) ·
|
|
129
|
+
[The magic `map()`](packages/docs/src/content/docs/concepts/map.mdx) ·
|
|
130
|
+
[Streaming](packages/docs/src/content/docs/concepts/streaming.mdx) ·
|
|
131
|
+
[Disposal](packages/docs/src/content/docs/concepts/disposal.mdx)
|
|
236
132
|
|
|
237
|
-
|
|
133
|
+
Transports:
|
|
134
|
+
[Overview](packages/docs/src/content/docs/transports/index.mdx) ·
|
|
135
|
+
[HTTP batch](packages/docs/src/content/docs/transports/http-batch.mdx) ·
|
|
136
|
+
[WebSocket](packages/docs/src/content/docs/transports/websocket.mdx) ·
|
|
137
|
+
[MessagePort](packages/docs/src/content/docs/transports/message-port.mdx) ·
|
|
138
|
+
[Custom](packages/docs/src/content/docs/transports/custom.mdx)
|
|
238
139
|
|
|
239
|
-
|
|
140
|
+
Server runtimes:
|
|
141
|
+
[Cloudflare Workers](packages/docs/src/content/docs/servers/workers.mdx) ·
|
|
142
|
+
[Node.js](packages/docs/src/content/docs/servers/node.mdx) ·
|
|
143
|
+
[Deno](packages/docs/src/content/docs/servers/deno.mdx) ·
|
|
144
|
+
[Bun](packages/docs/src/content/docs/servers/bun.mdx) ·
|
|
145
|
+
[Hono](packages/docs/src/content/docs/servers/hono.mdx) ·
|
|
146
|
+
[Other](packages/docs/src/content/docs/servers/other.mdx)
|
|
240
147
|
|
|
241
|
-
|
|
148
|
+
Guides and reference:
|
|
149
|
+
[Security considerations](packages/docs/src/content/docs/guides/security.mdx) ·
|
|
150
|
+
[Sessions & reconnection](packages/docs/src/content/docs/guides/sessions.mdx) ·
|
|
151
|
+
[Runtime validation](packages/docs/src/content/docs/guides/validation.mdx) ·
|
|
152
|
+
[Workers RPC interop](packages/docs/src/content/docs/guides/workers-rpc.mdx) ·
|
|
153
|
+
[Wire protocol](packages/docs/src/content/docs/reference/protocol.mdx) ·
|
|
154
|
+
[API cheat sheet](packages/docs/src/content/docs/reference/api.mdx)
|
|
242
155
|
|
|
243
|
-
|
|
156
|
+
To run the site locally, with both examples embedded as live in-browser playgrounds:
|
|
244
157
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
Calling an RPC method returns an `RpcPromise` rather than a regular `Promise`. You can use an `RpcPromise` in all the ways a regular `Promise` can be used, that is, you can `await` it, call `.then()`, pass it to `Promise.resolve()`, etc. (This is all possible because `RpcPromise` is a ["thenable"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables).)
|
|
248
|
-
|
|
249
|
-
However, you can do more with `RpcPromise`. `RpcPromise` supports _Promise Pipelining_:
|
|
250
|
-
|
|
251
|
-
1. An `RpcPromise` also acts as a _stub_ for the eventual result of the promise. That means, you can access properties and invoke methods on it, without awaiting the promise first.
|
|
252
|
-
|
|
253
|
-
```ts
|
|
254
|
-
// In a single round trip, authenticate the user, and fetch their notifications.
|
|
255
|
-
let user = api.authenticate(cookie);
|
|
256
|
-
let notifications = await user.getNotifications();
|
|
257
|
-
```
|
|
258
|
-
|
|
259
|
-
2. An `RpcPromise` (or its properties) can be passed as parameters to other RPC calls.
|
|
260
|
-
|
|
261
|
-
```ts
|
|
262
|
-
// In a single round trip, authenticate the user, and fetch their public profile
|
|
263
|
-
// given their ID.
|
|
264
|
-
let user = api.authenticate(cookie);
|
|
265
|
-
let profile = await api.getUserProfile(user.id);
|
|
266
|
-
```
|
|
267
|
-
|
|
268
|
-
Whenever an `RpcPromise` is passed in the parameters to an RPC, or returned as part of the result, the promise will be replaced with its resolution before delivery to the receiving application. So, you can use an `RpcPromise<T>` anywhere where a `T` is required!
|
|
269
|
-
|
|
270
|
-
### The magic `map()` method
|
|
271
|
-
|
|
272
|
-
Every RPC promise has a special method `.map()` which can be used to remotely transform a value, without pulling it back locally. Here's an example:
|
|
273
|
-
|
|
274
|
-
```ts
|
|
275
|
-
// Get a list of user IDs.
|
|
276
|
-
let idsPromise = api.listUserIds();
|
|
277
|
-
|
|
278
|
-
// Look up the username for each one.
|
|
279
|
-
let names = await idsPromise.map(id => [id, api.getUserName(id)]);
|
|
158
|
+
```sh
|
|
159
|
+
pnpm install && pnpm run dev:docs
|
|
280
160
|
```
|
|
281
161
|
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
**All this happens in a single network round trip!**
|
|
285
|
-
|
|
286
|
-
`promise.map(func)` transfers a representation of `func` to the server, where it is executed on the promise's result. Specifically:
|
|
287
|
-
|
|
288
|
-
* If the promise resolves to an array, the mapper function executes on each element of the array. The overall `.map()` operation returns a promise for an array of the results.
|
|
289
|
-
* If the promise resolves to `null` or `undefined`, the map function is not executed at all. The result is the same value.
|
|
290
|
-
* If the promise resolves to any other value, the map function executes once on that value, returning the result.
|
|
291
|
-
|
|
292
|
-
Thus, `map()` can be used both for handling arrays, and for handling nullable values.
|
|
293
|
-
|
|
294
|
-
There are some restrictions:
|
|
295
|
-
|
|
296
|
-
* The callback must have no side effects other than calling RPCs.
|
|
297
|
-
* The callback must be synchronous. It cannot await anything.
|
|
298
|
-
* The input to the callback is an `RpcPromise`, hence the callback cannot actually operate on it, other than to invoke its RPC methods, or to use it in the params of other RPC methods.
|
|
299
|
-
* Any stubs which you use in the callback -- and any parameters you pass to them -- will be sent to the peer. Be warned, a malicious peer can use these stubs for anything, not just calling your callback. Typically, it only makes sense to invoke stubs that came from the same peer originally, since this is what saves round-trips.
|
|
300
|
-
|
|
301
|
-
**How the heck does that work?**
|
|
302
|
-
|
|
303
|
-
Cap'n Web does NOT send arbitrary code over the wire!
|
|
304
|
-
|
|
305
|
-
The trick here is record-replay: On the calling side, Cap'n Web will invoke your callback once, in a special "recording" mode, passing in a special placeholder stub which records what you do with it. During the invocation, any RPCs invoked by the callback (on *any* stub) will not actually be executed, but will be recorded as an action the callback performs. Any stubs you use during the recording are "captured" as well. Once the callback returns, the recording and the capture list can then be sent to the peer, where the recording can then be replayed as needed to process individual results.
|
|
306
|
-
|
|
307
|
-
Since all of the not-yet-determined values seen by the callback are represented as `RpcPromise`s, the callback's behavior is deterministic. Any actual computation (arithmetic, branching, etc.) can't possibly use these promises as (meaningful) inputs, so would logically produce the same results for every invocation of the callback. Any such computation will actually end up being performed on the sending side, just once, with the results being imbued into the recording.
|
|
308
|
-
|
|
309
|
-
### Streaming with flow control
|
|
310
|
-
|
|
311
|
-
You may pass a `ReadableStream` or `WritableStream` over RPC. When doing so, the RPC system automatically creates an equivalent stream at the other end and pumps bytes (or arbitrarily-typed chunks) across. This is done in such a way as to ensure the available bandwidth is fully utilized while minimizing buffer bloat, by observing the bandwidth-delay product and applying backpressure when too much is written. Multiple streams can be sent across the same connection -- they will be multiplexed appropriately, similar to HTTP/2 stream multiplexing.
|
|
312
|
-
|
|
313
|
-
### Cloudflare Workers RPC interoperability
|
|
314
|
-
|
|
315
|
-
Cap'n Web works on any JavaScript platform. But, on Cloudflare Workers specifically, it's designed to play nicely with the [the built-in RPC system](https://blog.cloudflare.com/javascript-native-rpc/). The two have basically the same semantics, the only difference being that Workers RPC is a built-in API provided by the Workers Runtime, whereas Cap'n Web is implemented in pure JavaScript.
|
|
162
|
+
## Examples
|
|
316
163
|
|
|
317
|
-
|
|
318
|
-
* On Workers, the `RpcTarget` class exported by "capnweb" is just an alias of the built-in one, so you can use them interchangeably.
|
|
319
|
-
* RPC stubs and promises originating from one RPC system can be passed over the other. This will automatically set up proxying.
|
|
320
|
-
* You can also send Workers Service Bindings and Durable Object stubs over Cap'n Web -- again, this sets up proxying.
|
|
164
|
+
Runnable examples live in [`examples/`](examples/):
|
|
321
165
|
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
*
|
|
326
|
-
|
|
327
|
-
* Workers RPC does not yet support placing an `RpcPromise` into the parameters of a request, to be replaced by its resolution.
|
|
328
|
-
* Workers RPC does not yet support the magic `.map()` method.
|
|
329
|
-
|
|
330
|
-
## Resource Management and Disposal
|
|
331
|
-
|
|
332
|
-
Unfortunately, garbage collection does not work well when remote resources are involved, for two reasons:
|
|
333
|
-
|
|
334
|
-
1. Many JavaScript runtimes only run the garbage collector when they sense "memory pressure" -- if memory is not running low, then they figure there's no need to try to reclaim any. However, the runtime has no way to know if the other side of an RPC connection is suffering memory pressure.
|
|
335
|
-
|
|
336
|
-
2. Garbage collectors need to trace the full object graph in order to detect which objects are unreachable, especially when those objects contain cyclic references. However, the garbage collector can only see local objects; it has no ability to trace through the remote graph to discover cycles that may cross RPC connections.
|
|
337
|
-
|
|
338
|
-
Both of these problems might be solvable with sufficient work, but the problem seems exceedingly difficult. We make no attempt to solve it in this library.
|
|
339
|
-
|
|
340
|
-
Instead, you may choose one of two strategies:
|
|
341
|
-
|
|
342
|
-
1. Explicitly dispose stubs when you are done with them. This notifies the remote end that it can release the associated resources.
|
|
343
|
-
|
|
344
|
-
2. Use short-lived sessions. When the session ends, all stubs are implicitly disposed. In particular, when using HTTP batch request, there's generally no need to dispose stubs. When using long-lived WebSocket sessions, however, disposal may be important.
|
|
345
|
-
|
|
346
|
-
Note: We might extend Cap'n Web to use `FinalizationRegistry` to automatically dispose abandoned stubs in the future, but even if we do, it should not be relied upon, due to problems discussed above.
|
|
347
|
-
|
|
348
|
-
### How to dispose
|
|
349
|
-
|
|
350
|
-
Stubs integrate with JavaScript's [explicit resource management](https://v8.dev/features/explicit-resource-management), which became widely available in mid-2025 (and has been supported via transpilers and polyfills going back a few years earlier). In short:
|
|
351
|
-
|
|
352
|
-
* Disposable objects (including stubs) have a method `[Symbol.dispose]`. You can call this like `stub[Symbol.dispose]()`.
|
|
353
|
-
* You can arrange for a stub to be disposed automatically at the end of a function scope by assigning it to a `using` variable, like `using stub = api.getStub();`. The disposer will automatically be invoked when the variable goes out-of-scope.
|
|
354
|
-
|
|
355
|
-
### Automatic disposal
|
|
356
|
-
|
|
357
|
-
This library implements several rules to help make resource management more manageable. These rules may appear a bit complicated, but are intended to implement the behavior you would naturally expect.
|
|
358
|
-
|
|
359
|
-
The basic principle is: **The caller is responsible for disposing all stubs.** That is:
|
|
360
|
-
* Stubs passed in the params of a call remain property of the caller, and must be disposed by the caller, not by the callee.
|
|
361
|
-
* Stubs returned in the result of a call have their ownership transferred from the callee to the caller, and must be disposed by the caller.
|
|
362
|
-
|
|
363
|
-
In practice, though, the callee and caller do not actually share the same stubs. When stubs are passed over RPC, they are _duplicated_, and the target object is only disposed when all duplicates of the stub are disposed. Thus, to achieve the rule that only the caller needs to dispose stubs, the RPC system implicitly disposes the callee's duplicates of all stubs when the call completes. That is:
|
|
364
|
-
* Any stubs the callee receives in the parameters are implicitly disposed when the call completes.
|
|
365
|
-
* Any stubs returned in the results are implicitly disposed some time after the call completes. (Specifically, the RPC system will dispose them once it knows there will be no more pipelined calls.)
|
|
366
|
-
|
|
367
|
-
Some additional wonky details:
|
|
368
|
-
* Disposing an `RpcPromise` will automatically dispose the future result. (It may also cause the promise to be canceled and rejected, though this is not guaranteed.) If you don't intend to await an RPC promise, you should dispose it.
|
|
369
|
-
* Passing an `RpcPromise` in params or the return value of a call has the same ownership / disposal rules as passing an `RpcStub`.
|
|
370
|
-
* When you access a property of an `RpcStub` or `RpcPromise`, the result is itself an `RpcPromise`. However, this `RpcPromise` does not have its own disposer; you must dispose the stub or promise it came from. You can pass such properties in params or return values, but doing so will never lead to anything being implicitly disposed.
|
|
371
|
-
* The caller of an RPC may dispose any stubs used in the parameters immediately after initiating the RPC, without waiting for the RPC to complete. All stubs are duplicated at the moment of the call, so the callee is not responsible for keeping them alive.
|
|
372
|
-
* If the final result of an RPC returned to the caller is an object, it will always have a disposer. Disposing it will dispose all stubs found in that response. It's a good idea to always dispose return values even if you don't expect they contain any stubs, just in case the server changes the API in the future to add stubs to the result.
|
|
373
|
-
|
|
374
|
-
WARNING: The ownership behavior of calls differs from the original behavior in the native RPC implementation built into the Cloudflare Workers Runtime. In the original Workers behavior, the callee loses ownership of stubs passed in a call's parameters. We plan to change the Workers Runtime to match Cap'n Web's behavior, as the original behavior has proven more problematic than helpful.
|
|
375
|
-
|
|
376
|
-
### Duplicating stubs
|
|
377
|
-
|
|
378
|
-
Sometimes you need to pass a stub somewhere where it will be disposed, but also keep the stub for later use. To prevent the disposer from disabling your copy of the stub, you can duplicate the stub by calling `stub.dup()`. The stub's target will only be disposed when all duplicates of the stub have been disposed.
|
|
379
|
-
|
|
380
|
-
Hint: You can call `.dup()` on a property of a stub or promise, in order to create a stub backed by that property. This is particularly useful when you know in advance that the property is going to resolve to a stub: calling `.dup()` on it gives you a stub you can start using immediately, that otherwise behaves exactly the same as the eventual stub would if you awaited it.
|
|
381
|
-
|
|
382
|
-
### Listening for disposal
|
|
383
|
-
|
|
384
|
-
An `RpcTarget` may declare a `Symbol.dispose` method. If it does, the RPC system will automatically invoke it when a stub pointing at it (and all its duplicates) has been disposed.
|
|
385
|
-
|
|
386
|
-
Note that if you pass the same `RpcTarget` instance to RPC multiple times -- thus creating multiple stubs -- you will eventually get a separate dispose call for each one. To avoid this, you could use `new RpcStub(target)` to create a single stub upfront, and then pass that stub across multiple RPCs. In this case, you will receive only one call to the target's disposer when all stubs are disposed.
|
|
387
|
-
|
|
388
|
-
### Listening for disconnect
|
|
389
|
-
|
|
390
|
-
You can monitor any stub for "brokenness" with its `onRpcBroken()` method:
|
|
391
|
-
|
|
392
|
-
```ts
|
|
393
|
-
stub.onRpcBroken((error: any) => {
|
|
394
|
-
console.error(error);
|
|
395
|
-
});
|
|
396
|
-
```
|
|
166
|
+
* [`batch-pipelining`](examples/batch-pipelining/): three dependent calls in one HTTP round trip.
|
|
167
|
+
* [`worker-react`](examples/worker-react/): a React app against a Cap'n Web Worker, with runtime
|
|
168
|
+
validation at the RPC boundary.
|
|
169
|
+
* [`session-recovery`](examples/session-recovery/): a WebSocket session with a button that kills
|
|
170
|
+
it, showing what a disconnect destroys and what it takes to resume without a gap.
|
|
397
171
|
|
|
398
|
-
|
|
399
|
-
* The stub's underlying connection is lost.
|
|
400
|
-
* The stub is a promise, and the promise rejects.
|
|
172
|
+
## Related packages
|
|
401
173
|
|
|
402
|
-
|
|
174
|
+
* [`capnweb-validate`](packages/capnweb-validate/): generates runtime validators from your
|
|
175
|
+
TypeScript types at build time, since TypeScript types are erased and a malicious peer can send
|
|
176
|
+
anything.
|
|
403
177
|
|
|
404
|
-
|
|
178
|
+
## Security
|
|
405
179
|
|
|
406
|
-
|
|
180
|
+
Cap'n Web gives you strong authorization tools, but a few things are your responsibility:
|
|
181
|
+
authenticating in-band rather than with cookies, rate-limiting because pipelining is cheap for
|
|
182
|
+
attackers, setting transport payload limits, and validating types at runtime. Read
|
|
183
|
+
[Security considerations](packages/docs/src/content/docs/guides/security.mdx) before exposing a
|
|
184
|
+
service to untrusted peers.
|
|
407
185
|
|
|
408
|
-
|
|
186
|
+
To report a vulnerability, see [SECURITY.md](SECURITY.md).
|
|
409
187
|
|
|
410
|
-
##
|
|
188
|
+
## Contributing
|
|
411
189
|
|
|
412
|
-
|
|
190
|
+
Bug reports and pull requests are welcome. Note that `packages/docs/` is the source of truth for
|
|
191
|
+
user-facing documentation; behaviour changes should update the relevant page there.
|
|
413
192
|
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
**Cap'n Web has a magic trick:** The results of one call in the batch can be used in the parameters to later calls in the same batch, even though the entire batch is sent at once. If you simply take the Promise returned by one call and use it in the parameters to another call, the Promise will be replaced with its resolution before delivering it to the callee. **This is called Promise Pipelining.**
|
|
417
|
-
|
|
418
|
-
```ts
|
|
419
|
-
import { RpcTarget, RpcStub, newHttpBatchRpcSession } from "capnweb";
|
|
420
|
-
|
|
421
|
-
// Declare our RPC interface.
|
|
422
|
-
interface MyApi extends RpcTarget {
|
|
423
|
-
// Returns information about the logged-in user.
|
|
424
|
-
getUserInfo(): UserInfo;
|
|
425
|
-
|
|
426
|
-
// Returns a friendly greeting for a user with the given name.
|
|
427
|
-
greet(name: string): string;
|
|
428
|
-
};
|
|
429
|
-
|
|
430
|
-
// Start a batch request using this interface.
|
|
431
|
-
using stub: RpcStub<MyApi> = newHttpBatchRpcSession<MyApi>("https://example.com/api");
|
|
432
|
-
|
|
433
|
-
// The batch will be sent on the next I/O tick (i.e. using setTimeout(sendBatch, 0)). You have
|
|
434
|
-
// until then to add calls to the batch.
|
|
435
|
-
//
|
|
436
|
-
// We can make any number of calls as part of the batch, as long as we store the promises without
|
|
437
|
-
// awaiting them yet.
|
|
438
|
-
let promise1 = stub.greet("Alice");
|
|
439
|
-
let promise2 = stub.greet("Bob");
|
|
440
|
-
|
|
441
|
-
// Note that a promise returned by one call can be used in the input to another call. The first
|
|
442
|
-
// call's result will be substituted into the second call's parameters on the server side. If the
|
|
443
|
-
// first call returns an object, you can even specify a property of the object to pass to the
|
|
444
|
-
// second call, as shown here.
|
|
445
|
-
let userInfoPromise = stub.getUserInfo();
|
|
446
|
-
let promise3 = stub.greet(userInfoPromise.name);
|
|
447
|
-
|
|
448
|
-
// Use Promise.all() to wait on all the promises at once. NOTE: You don't necessarily have to
|
|
449
|
-
// use Promise.all(), but you must make sure you have explicitly awaited (or called `.then()` on)
|
|
450
|
-
// all promises before the batch is sent. The system will only ask the server to send back
|
|
451
|
-
// results for the promises you explicitly await. In this example, we have not awaited
|
|
452
|
-
// `userInfoPromise` -- we only used it as a parameter to another call -- so the result will
|
|
453
|
-
// not actually be returned.
|
|
454
|
-
let [greeting1, greeting2, greeting3] = await Promise.all([promise1, promise2, promise3]);
|
|
455
|
-
|
|
456
|
-
// Now we can do stuff with the results.
|
|
457
|
-
console.log(greeting1);
|
|
458
|
-
console.log(greeting2);
|
|
459
|
-
console.log(greeting3);
|
|
460
|
-
```
|
|
461
|
-
|
|
462
|
-
### WebSocket client
|
|
463
|
-
|
|
464
|
-
In WebSocket mode, the client forms a long-lived connection to the server, allowing us to make many calls over a long period of time. In this mode, the server can even make asynchronous calls back to the client.
|
|
465
|
-
|
|
466
|
-
```ts
|
|
467
|
-
import { RpcTarget, RpcStub, newWebSocketRpcSession } from "capnweb";
|
|
468
|
-
|
|
469
|
-
// Declare our RPC interface.
|
|
470
|
-
interface MyApi extends RpcTarget {
|
|
471
|
-
// Returns information about the logged-in user.
|
|
472
|
-
getUserInfo(): UserInfo;
|
|
473
|
-
|
|
474
|
-
// Returns a friendly greeting for a user with the given name.
|
|
475
|
-
greet(name: string): string;
|
|
476
|
-
};
|
|
477
|
-
|
|
478
|
-
// Start a WebSocket session.
|
|
479
|
-
//
|
|
480
|
-
// (Note that disposing the root stub will close the connection. Here we declare it with `using` so
|
|
481
|
-
// that the connection will be closed when the stub goes out of scope, but you can also call
|
|
482
|
-
// `stub[Symbol.dispose]()` directly.)
|
|
483
|
-
using stub: RpcStub<MyApi> = newWebSocketRpcSession<MyApi>("wss://example.com/api");
|
|
484
|
-
|
|
485
|
-
// With a WebSocket, we can freely make calls over time.
|
|
486
|
-
console.log(await stub.greet("Alice"));
|
|
487
|
-
console.log(await stub.greet("Bob"));
|
|
488
|
-
|
|
489
|
-
// But we can still use Promise Pipelining to reduce round trips. Note that we should use `using`
|
|
490
|
-
// with promises we don't intend to await so that the system knows when we don't need them anymore.
|
|
491
|
-
{
|
|
492
|
-
using userInfoPromise = stub.getUserInfo();
|
|
493
|
-
console.log(await stub.greet(userInfoPromise.name));
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
// Note that since we never awaited `userInfoPromise`, the server won't even bother sending the
|
|
497
|
-
// response back over the wire.
|
|
498
|
-
```
|
|
499
|
-
|
|
500
|
-
### HTTP server on Cloudflare Workers
|
|
501
|
-
|
|
502
|
-
The helper function `newWorkersRpcResponse()` makes it easy to implement an HTTP server that accepts both the HTTP batch and WebSocket APIs at once:
|
|
503
|
-
|
|
504
|
-
```ts
|
|
505
|
-
import { RpcTarget, newWorkersRpcResponse } from "capnweb";
|
|
506
|
-
|
|
507
|
-
// Define our server implementation.
|
|
508
|
-
class MyApiImpl extends RpcTarget implements MyApi {
|
|
509
|
-
constructor(private userInfo: UserInfo) {}
|
|
510
|
-
|
|
511
|
-
getUserInfo(): UserInfo {
|
|
512
|
-
return this.userInfo;
|
|
513
|
-
}
|
|
514
|
-
|
|
515
|
-
greet(name: string): string {
|
|
516
|
-
return `Hello, ${name}!`;
|
|
517
|
-
}
|
|
518
|
-
};
|
|
519
|
-
|
|
520
|
-
// Define our Worker HTTP handler.
|
|
521
|
-
export default {
|
|
522
|
-
fetch(request: Request, env, ctx) {
|
|
523
|
-
let userInfo: UserInfo = authenticateFromCookie(request);
|
|
524
|
-
let url = new URL(request.url);
|
|
525
|
-
|
|
526
|
-
// Serve API at `/api`.
|
|
527
|
-
if (url.pathname === "/api") {
|
|
528
|
-
return newWorkersRpcResponse(request, new MyApiImpl(userInfo));
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
return new Response("Not found", {status: 404});
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
```
|
|
535
|
-
|
|
536
|
-
#### Compatibility with Workers' built-in RPC
|
|
537
|
-
|
|
538
|
-
Cloudflare Workers has long featured [a built-in RPC system with semantics similar to Cap'n Web](https://developers.cloudflare.com/workers/runtime-apis/rpc/).
|
|
539
|
-
|
|
540
|
-
Cap'n Web is designed to be compatible with Workers RPC, meaning you can pass Cap'n Web RPC stubs over Workers RPC and vice versa. The system will automatically wrap one stub type in the other and arrange to proxy calls.
|
|
541
|
-
|
|
542
|
-
For best compatibility, make sure to set your [Workers compatibilty date](https://developers.cloudflare.com/workers/configuration/compatibility-dates/) to at least `2026-01-20`, or enable the [compatibility flag](https://developers.cloudflare.com/workers/configuration/compatibility-flags/) `rpc_params_dup_stubs`. (As of this writing, `2026-01-20` is in the future, so you will need to use the flag for now.)
|
|
543
|
-
|
|
544
|
-
### HTTP server on Node.js
|
|
545
|
-
|
|
546
|
-
A server on Node.js is a bit more involved, due to the awkward handling of WebSockets in Node's HTTP library.
|
|
547
|
-
|
|
548
|
-
```ts
|
|
549
|
-
import http from "node:http";
|
|
550
|
-
import { WebSocketServer } from 'ws'; // npm package
|
|
551
|
-
import { RpcTarget, newWebSocketRpcSession, nodeHttpBatchRpcResponse } from "capnweb";
|
|
552
|
-
|
|
553
|
-
class MyApiImpl extends RpcTarget implements MyApi {
|
|
554
|
-
// ... define API, same as above ...
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
// Run standard HTTP server on a port.
|
|
558
|
-
httpServer = http.createServer(async (request, response) => {
|
|
559
|
-
if (request.headers.upgrade?.toLowerCase() === 'websocket') {
|
|
560
|
-
// Ignore, should be handled by WebSocketServer instead.
|
|
561
|
-
return;
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
// Accept Cap'n Web requests at `/api`.
|
|
565
|
-
if (request.url === "/api") {
|
|
566
|
-
try {
|
|
567
|
-
await nodeHttpBatchRpcResponse(request, response, new MyApiImpl(), {
|
|
568
|
-
// If you are accepting WebSockets, then you might as well accept cross-origin HTTP, since
|
|
569
|
-
// WebSockets always permit cross-origin request anyway. But, see security considerations
|
|
570
|
-
// for further discussion.
|
|
571
|
-
headers: { "Access-Control-Allow-Origin": "*" }
|
|
572
|
-
});
|
|
573
|
-
} catch (err) {
|
|
574
|
-
response.writeHead(500, { 'content-type': 'text/plain' });
|
|
575
|
-
response.end(String(err?.stack || err));
|
|
576
|
-
}
|
|
577
|
-
return;
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
response.writeHead(404, { 'content-type': 'text/plain' });
|
|
581
|
-
response.end("Not Found");
|
|
582
|
-
});
|
|
583
|
-
|
|
584
|
-
// Arrange to handle WebSockets as well, using the `ws` package. You can skip this if you only
|
|
585
|
-
// want to handle HTTP batch requests.
|
|
586
|
-
wsServer = new WebSocketServer({ server: httpServer })
|
|
587
|
-
wsServer.on('connection', (ws) => {
|
|
588
|
-
// The `as any` here is because the `ws` module seems to have its own `WebSocket` type
|
|
589
|
-
// declaration that's incompatible with the standard one. In practice, though, they are
|
|
590
|
-
// compatible enough for Cap'n Web!
|
|
591
|
-
newWebSocketRpcSession(ws as any, new MyApiImpl());
|
|
592
|
-
})
|
|
593
|
-
|
|
594
|
-
// Accept requests on port 8080.
|
|
595
|
-
httpServer.listen(8080);
|
|
596
|
-
```
|
|
597
|
-
|
|
598
|
-
### HTTP server on Deno
|
|
599
|
-
```ts
|
|
600
|
-
import {
|
|
601
|
-
newHttpBatchRpcResponse,
|
|
602
|
-
newWebSocketRpcSession,
|
|
603
|
-
RpcTarget,
|
|
604
|
-
} from "npm:capnweb";
|
|
605
|
-
|
|
606
|
-
// This is the server implementation.
|
|
607
|
-
class MyApiImpl extends RpcTarget implements MyApi {
|
|
608
|
-
// ... define API, same as above ...
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
Deno.serve(async (req) => {
|
|
612
|
-
const url = new URL(req.url);
|
|
613
|
-
if (url.pathname === "/api") {
|
|
614
|
-
if (req.headers.get("upgrade") === "websocket") {
|
|
615
|
-
const { socket, response } = Deno.upgradeWebSocket(req);
|
|
616
|
-
socket.addEventListener("open", () => {
|
|
617
|
-
newWebSocketRpcSession(socket, new MyApiImpl());
|
|
618
|
-
});
|
|
619
|
-
return response;
|
|
620
|
-
} else {
|
|
621
|
-
const response = await newHttpBatchRpcResponse(req, new MyApiImpl());
|
|
622
|
-
// If you are accepting WebSockets, then you might as well accept cross-origin HTTP, since
|
|
623
|
-
// WebSockets always permit cross-origin request anyway. But, see security considerations
|
|
624
|
-
// for further discussion.
|
|
625
|
-
response.headers.set("Access-Control-Allow-Origin", "*");
|
|
626
|
-
return response;
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
|
-
|
|
630
|
-
return new Response("Not Found", { status: 404 });
|
|
631
|
-
});
|
|
632
|
-
```
|
|
633
|
-
|
|
634
|
-
### HTTP server on Bun
|
|
635
|
-
|
|
636
|
-
Bun's server-side WebSocket API uses [callback-based handlers](https://bun.sh/docs/runtime/http/websockets) instead of the standard `addEventListener` interface. Cap'n Web provides `newBunWebSocketRpcHandler()` which returns a handler object you can pass directly to `Bun.serve()`.
|
|
637
|
-
|
|
638
|
-
```ts
|
|
639
|
-
import { RpcTarget, newBunWebSocketRpcHandler, newHttpBatchRpcResponse } from "capnweb";
|
|
640
|
-
|
|
641
|
-
class MyApiImpl extends RpcTarget implements MyApi {
|
|
642
|
-
// ... define API, same as above ...
|
|
643
|
-
}
|
|
644
|
-
|
|
645
|
-
// Create a WebSocket handler that manages RPC sessions automatically.
|
|
646
|
-
// The callback is invoked once per connection to create a fresh API instance.
|
|
647
|
-
let rpcHandler = newBunWebSocketRpcHandler(() => new MyApiImpl());
|
|
648
|
-
|
|
649
|
-
Bun.serve({
|
|
650
|
-
async fetch(req, server) {
|
|
651
|
-
let url = new URL(req.url);
|
|
652
|
-
if (url.pathname === "/api") {
|
|
653
|
-
// Upgrade WebSocket requests.
|
|
654
|
-
if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
|
|
655
|
-
if (server.upgrade(req)) return;
|
|
656
|
-
return new Response("WebSocket upgrade failed", { status: 500 });
|
|
657
|
-
}
|
|
658
|
-
|
|
659
|
-
// Handle HTTP batch requests.
|
|
660
|
-
let response = await newHttpBatchRpcResponse(req, new MyApiImpl());
|
|
661
|
-
response.headers.set("Access-Control-Allow-Origin", "*");
|
|
662
|
-
return response;
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
return new Response("Not Found", { status: 404 });
|
|
666
|
-
},
|
|
667
|
-
|
|
668
|
-
// Pass the handler directly — no manual wiring needed.
|
|
669
|
-
websocket: rpcHandler,
|
|
670
|
-
});
|
|
671
|
-
```
|
|
672
|
-
|
|
673
|
-
### HTTP server on other runtimes
|
|
674
|
-
|
|
675
|
-
Every runtime does HTTP handling and WebSockets a little differently, although most modern runtimes use the standard `Request` and `Response` types from the Fetch API, as well as the standard `WebSocket` API. You should be able to use these two functions (exported by `capnweb`) to implement both HTTP batch and WebSocket handling on all platforms:
|
|
676
|
-
|
|
677
|
-
```ts
|
|
678
|
-
// Run a single HTTP batch.
|
|
679
|
-
function newHttpBatchRpcResponse(
|
|
680
|
-
request: Request, yourApi: RpcTarget, options?: RpcSessionOptions)
|
|
681
|
-
: Promise<Response>;
|
|
682
|
-
|
|
683
|
-
// Run a WebSocket session.
|
|
684
|
-
//
|
|
685
|
-
// This is actually the same function as is used on the client side! But on the
|
|
686
|
-
// server, you should pass in a `WebSocket` object representing the already-open
|
|
687
|
-
// connection, instead of a URL string, and you pass your API implementation as
|
|
688
|
-
// the second parameter.
|
|
689
|
-
//
|
|
690
|
-
// You can dispose the returned `Disposable` to close the connection, or just
|
|
691
|
-
// let it run until the client closes it.
|
|
692
|
-
function newWebSocketRpcSession(
|
|
693
|
-
webSocket: WebSocket, yourApi: RpcTarget, options?: RpcSessionOptions)
|
|
694
|
-
: Disposable;
|
|
695
|
-
```
|
|
696
|
-
|
|
697
|
-
### HTTP server using Hono
|
|
698
|
-
|
|
699
|
-
If your app is built on [Hono](https://hono.dev/) (on any runtime it supports), check out [`@hono/capnweb`](https://github.com/honojs/middleware/tree/main/packages/capnweb).
|
|
700
|
-
|
|
701
|
-
### MessagePort
|
|
702
|
-
|
|
703
|
-
Cap'n Web can also talk over MessagePorts. This can be used in a browser to talk to Web Workers, iframes, etc.
|
|
704
|
-
|
|
705
|
-
```ts
|
|
706
|
-
import { RpcTarget, RpcStub, newMessagePortRpcSession } from "capnweb";
|
|
707
|
-
|
|
708
|
-
// Declare our RPC interface.
|
|
709
|
-
class Greeter extends RpcTarget {
|
|
710
|
-
greet(name: string): string {
|
|
711
|
-
return `Hello, ${name}!`;
|
|
712
|
-
}
|
|
713
|
-
};
|
|
714
|
-
|
|
715
|
-
// Create a MessageChannel (pair of MessagePorts).
|
|
716
|
-
let channel = new MessageChannel()
|
|
717
|
-
|
|
718
|
-
// Initialize the server on port1.
|
|
719
|
-
newMessagePortRpcSession(channel.port1, new Greeter());
|
|
720
|
-
|
|
721
|
-
// Initialize the client on port2.
|
|
722
|
-
using stub: RpcStub<Greeter> = newMessagePortRpcSession<Greeter>(channel.port2);
|
|
723
|
-
|
|
724
|
-
// Now you can make calls.
|
|
725
|
-
console.log(await stub.greet("Alice"));
|
|
726
|
-
console.log(await stub.greet("Bob"));
|
|
727
|
-
```
|
|
728
|
-
|
|
729
|
-
Of course, in a real-world scenario, you'd probably want to send one of the two ports to another context. A `MessagePort` can itself be transferred to another context using `postMessage()`, e.g. `window.postMessage()`, `worker.postMessage()`, or even `port.postMessage()` on some other existing `MessagePort`.
|
|
730
|
-
|
|
731
|
-
Note that you should not use a `Window` object itself as a port for RPC -- you should always create a new `MessageChannel` and send one of the ports over. This is because anyone can `postMessage()` to a window, and the RPC system does not authenticate that messages came from the expected sender. You need to verify that you received the port itself from the expected sender first, then let the RPC system take over.
|
|
732
|
-
|
|
733
|
-
### Custom transports
|
|
734
|
-
|
|
735
|
-
You can implement a custom RPC transport across any bidirectional stream. To do so, implement the interface `RpcTransport`, which is defined as follows:
|
|
736
|
-
|
|
737
|
-
```ts
|
|
738
|
-
// Interface for an RPC transport, which is a simple bidirectional message stream.
|
|
739
|
-
export interface RpcTransport {
|
|
740
|
-
// Sends a message to the other end.
|
|
741
|
-
send(message: string): Promise<void>;
|
|
742
|
-
|
|
743
|
-
// Receives a message sent by the other end.
|
|
744
|
-
//
|
|
745
|
-
// If and when the transport becomes disconnected, this will reject. The thrown error will be
|
|
746
|
-
// propagated to all outstanding calls and future calls on any stubs associated with the session.
|
|
747
|
-
// If there are no outstanding calls (and none are made in the future), then the error does not
|
|
748
|
-
// propagate anywhere -- this is considered a "clean" shutdown.
|
|
749
|
-
receive(): Promise<string>;
|
|
750
|
-
|
|
751
|
-
// Indicates that the RPC system has suffered an error that prevents the session from continuing.
|
|
752
|
-
// The transport should ideally try to send any queued messages if it can, and then close the
|
|
753
|
-
// connection. (It's not strictly necessary to deliver queued messages, but the last message sent
|
|
754
|
-
// before abort() is called is often an "abort" message, which communicates the error to the
|
|
755
|
-
// peer, so if that is dropped, the peer may have less information about what happened.)
|
|
756
|
-
abort?(reason: any): void;
|
|
757
|
-
}
|
|
758
|
-
```
|
|
759
|
-
|
|
760
|
-
You can then set up a connection over it:
|
|
761
|
-
|
|
762
|
-
```ts
|
|
763
|
-
// Create the transport.
|
|
764
|
-
let transport: RpcTransport = new MyTransport();
|
|
765
|
-
|
|
766
|
-
// Create the main interface we will expose to the other end.
|
|
767
|
-
let localMain: RpcTarget = new MyMainInterface();
|
|
768
|
-
|
|
769
|
-
// Start the session.
|
|
770
|
-
let session = new RpcSession<RemoteMainInterface>(transport, localMain);
|
|
771
|
-
|
|
772
|
-
// Get a stub for the other end's main interface.
|
|
773
|
-
let stub: RemoteMainInterface = session.getRemoteMain();
|
|
774
|
-
|
|
775
|
-
// Now we can call methods on the stub.
|
|
776
|
-
```
|
|
193
|
+
## License
|
|
777
194
|
|
|
778
|
-
|
|
195
|
+
[MIT](LICENSE.txt)
|