capnweb 0.0.0-99ecb6b
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.txt +21 -0
- package/README.md +722 -0
- package/dist/index-workers.d.ts +2 -0
- package/dist/index-workers.js +2583 -0
- package/dist/index-workers.js.map +1 -0
- package/dist/index.d.ts +364 -0
- package/dist/index.js +2580 -0
- package/dist/index.js.map +1 -0
- package/package.json +55 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
import { IncomingMessage, ServerResponse, OutgoingHttpHeaders, OutgoingHttpHeader } from 'node:http';
|
|
2
|
+
|
|
3
|
+
// Copyright (c) 2025 Cloudflare, Inc.
|
|
4
|
+
// Licensed under the MIT license found in the LICENSE.txt file or at:
|
|
5
|
+
// https://opensource.org/license/mit
|
|
6
|
+
|
|
7
|
+
// This file borrows heavily from `types/defines/rpc.d.ts` in workerd.
|
|
8
|
+
|
|
9
|
+
// Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s.
|
|
10
|
+
// TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`.
|
|
11
|
+
// For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to
|
|
12
|
+
// accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape)
|
|
13
|
+
declare const __RPC_STUB_BRAND: '__RPC_STUB_BRAND';
|
|
14
|
+
declare const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND';
|
|
15
|
+
interface RpcTargetBranded {
|
|
16
|
+
[__RPC_TARGET_BRAND]: never;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Types that can be used through `Stub`s
|
|
20
|
+
type Stubable = RpcTargetBranded | ((...args: any[]) => any);
|
|
21
|
+
|
|
22
|
+
// Types that can be passed over RPC
|
|
23
|
+
// The reason for using a generic type here is to build a serializable subset of structured
|
|
24
|
+
// cloneable composite types. This allows types defined with the "interface" keyword to pass the
|
|
25
|
+
// serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
|
|
26
|
+
type Serializable<T> =
|
|
27
|
+
// Structured cloneables
|
|
28
|
+
| BaseType
|
|
29
|
+
// Structured cloneable composites
|
|
30
|
+
| Map<
|
|
31
|
+
T extends Map<infer U, unknown> ? Serializable<U> : never,
|
|
32
|
+
T extends Map<unknown, infer U> ? Serializable<U> : never
|
|
33
|
+
>
|
|
34
|
+
| Set<T extends Set<infer U> ? Serializable<U> : never>
|
|
35
|
+
| Array<T extends Array<infer U> ? Serializable<U> : never>
|
|
36
|
+
| ReadonlyArray<T extends ReadonlyArray<infer U> ? Serializable<U> : never>
|
|
37
|
+
| {
|
|
38
|
+
[K in keyof T]: K extends number | string ? Serializable<T[K]> : never;
|
|
39
|
+
}
|
|
40
|
+
| Promise<T extends Promise<infer U> ? Serializable<U> : never>
|
|
41
|
+
// Special types
|
|
42
|
+
| Stub<Stubable>
|
|
43
|
+
// Serialized as stubs, see `Stubify`
|
|
44
|
+
| Stubable;
|
|
45
|
+
|
|
46
|
+
// Base type for all RPC stubs, including common memory management methods.
|
|
47
|
+
// `T` is used as a marker type for unwrapping `Stub`s later.
|
|
48
|
+
interface StubBase<T extends Serializable<T>> extends Disposable {
|
|
49
|
+
[__RPC_STUB_BRAND]: T;
|
|
50
|
+
dup(): this;
|
|
51
|
+
onRpcBroken(callback: (error: any) => void): void;
|
|
52
|
+
}
|
|
53
|
+
type Stub<T extends Serializable<T>> =
|
|
54
|
+
T extends object ? Provider<T> & StubBase<T> : StubBase<T>;
|
|
55
|
+
|
|
56
|
+
type TypedArray =
|
|
57
|
+
| Uint8Array
|
|
58
|
+
| Uint8ClampedArray
|
|
59
|
+
| Uint16Array
|
|
60
|
+
| Uint32Array
|
|
61
|
+
| Int8Array
|
|
62
|
+
| Int16Array
|
|
63
|
+
| Int32Array
|
|
64
|
+
| BigUint64Array
|
|
65
|
+
| BigInt64Array
|
|
66
|
+
| Float32Array
|
|
67
|
+
| Float64Array;
|
|
68
|
+
|
|
69
|
+
// This represents all the types that can be sent as-is over an RPC boundary
|
|
70
|
+
type BaseType =
|
|
71
|
+
| void
|
|
72
|
+
| undefined
|
|
73
|
+
| null
|
|
74
|
+
| boolean
|
|
75
|
+
| number
|
|
76
|
+
| bigint
|
|
77
|
+
| string
|
|
78
|
+
| TypedArray
|
|
79
|
+
| ArrayBuffer
|
|
80
|
+
| DataView
|
|
81
|
+
| Date
|
|
82
|
+
| Error
|
|
83
|
+
| RegExp
|
|
84
|
+
| ReadableStream<Uint8Array>
|
|
85
|
+
| WritableStream<Uint8Array>
|
|
86
|
+
| Request
|
|
87
|
+
| Response
|
|
88
|
+
| Headers;
|
|
89
|
+
// Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
|
|
90
|
+
// prettier-ignore
|
|
91
|
+
type Stubify<T> =
|
|
92
|
+
T extends Stubable ? Stub<T>
|
|
93
|
+
: T extends Promise<infer U> ? Stubify<U>
|
|
94
|
+
: T extends StubBase<any> ? T
|
|
95
|
+
: T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>>
|
|
96
|
+
: T extends Set<infer V> ? Set<Stubify<V>>
|
|
97
|
+
: T extends Array<infer V> ? Array<Stubify<V>>
|
|
98
|
+
: T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>>
|
|
99
|
+
: T extends BaseType ? T
|
|
100
|
+
// When using "unknown" instead of "any", interfaces are not stubified.
|
|
101
|
+
: T extends { [key: string | number]: any } ? { [K in keyof T]: Stubify<T[K]> }
|
|
102
|
+
: T;
|
|
103
|
+
|
|
104
|
+
// Recursively rewrite all `Stub<T>`s with the corresponding `T`s.
|
|
105
|
+
// Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:
|
|
106
|
+
// `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.
|
|
107
|
+
// prettier-ignore
|
|
108
|
+
type UnstubifyInner<T> =
|
|
109
|
+
T extends StubBase<infer V> ? (T | V) // can provide either stub or local RpcTarget
|
|
110
|
+
: T extends Map<infer K, infer V> ? Map<Unstubify<K>, Unstubify<V>>
|
|
111
|
+
: T extends Set<infer V> ? Set<Unstubify<V>>
|
|
112
|
+
: T extends Array<infer V> ? Array<Unstubify<V>>
|
|
113
|
+
: T extends ReadonlyArray<infer V> ? ReadonlyArray<Unstubify<V>>
|
|
114
|
+
: T extends BaseType ? T
|
|
115
|
+
: T extends { [key: string | number]: unknown } ? { [K in keyof T]: Unstubify<T[K]> }
|
|
116
|
+
: T;
|
|
117
|
+
|
|
118
|
+
// You can put promises anywhere in the params and they'll be resolved before delivery.
|
|
119
|
+
// (This also covers RpcPromise, because it's defined as being a Promise.)
|
|
120
|
+
type Unstubify<T> = UnstubifyInner<T> | Promise<UnstubifyInner<T>>
|
|
121
|
+
|
|
122
|
+
type UnstubifyAll<A extends any[]> = { [I in keyof A]: Unstubify<A[I]> };
|
|
123
|
+
|
|
124
|
+
// Utility type for adding `Disposable`s to `object` types only.
|
|
125
|
+
// Note `unknown & T` is equivalent to `T`.
|
|
126
|
+
type MaybeDisposable<T> = T extends object ? Disposable : unknown;
|
|
127
|
+
|
|
128
|
+
// Type for method return or property on an RPC interface.
|
|
129
|
+
// - Stubable types are replaced by stubs.
|
|
130
|
+
// - Serializable types are passed by value, with stubable types replaced by stubs
|
|
131
|
+
// and a top-level `Disposer`.
|
|
132
|
+
// Everything else can't be passed over RPC.
|
|
133
|
+
// Technically, we use custom thenables here, but they quack like `Promise`s.
|
|
134
|
+
// Intersecting with `(Maybe)Provider` allows pipelining.
|
|
135
|
+
// prettier-ignore
|
|
136
|
+
type Result<R> =
|
|
137
|
+
R extends Stubable ? Promise<Stub<R>> & Provider<R> & StubBase<R>
|
|
138
|
+
: R extends Serializable<R> ? Promise<Stubify<R> & MaybeDisposable<R>> & Provider<R> & StubBase<R>
|
|
139
|
+
: never;
|
|
140
|
+
|
|
141
|
+
// Type for method or property on an RPC interface.
|
|
142
|
+
// For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
|
|
143
|
+
// Unwrapping `Stub`s allows calling with `Stubable` arguments.
|
|
144
|
+
// For properties, rewrite types to be `Result`s.
|
|
145
|
+
// In each case, unwrap `Promise`s.
|
|
146
|
+
type MethodOrProperty<V> = V extends (...args: infer P) => infer R
|
|
147
|
+
? (...args: UnstubifyAll<P>) => Result<Awaited<R>>
|
|
148
|
+
: Result<Awaited<V>>;
|
|
149
|
+
|
|
150
|
+
// Type for the callable part of an `Provider` if `T` is callable.
|
|
151
|
+
// This is intersected with methods/properties.
|
|
152
|
+
type MaybeCallableProvider<T> = T extends (...args: any[]) => any
|
|
153
|
+
? MethodOrProperty<T>
|
|
154
|
+
: unknown;
|
|
155
|
+
|
|
156
|
+
// Base type for all other types providing RPC-like interfaces.
|
|
157
|
+
// Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
|
|
158
|
+
type Provider<T> = MaybeCallableProvider<T> &
|
|
159
|
+
(T extends Array<infer U>
|
|
160
|
+
? {
|
|
161
|
+
[key: number]: MethodOrProperty<U>;
|
|
162
|
+
} & {
|
|
163
|
+
map<V>(callback: (elem: U) => V): Result<Array<V>>;
|
|
164
|
+
}
|
|
165
|
+
: {
|
|
166
|
+
[K in Exclude<
|
|
167
|
+
keyof T,
|
|
168
|
+
symbol | keyof StubBase<never>
|
|
169
|
+
>]: MethodOrProperty<T[K]>;
|
|
170
|
+
} & {
|
|
171
|
+
map<V>(callback: (value: NonNullable<T>) => V): Result<Array<V>>;
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
|
|
176
|
+
* RPC stubs, but it will support basic data types.
|
|
177
|
+
*/
|
|
178
|
+
declare function serialize(value: unknown): string;
|
|
179
|
+
/**
|
|
180
|
+
* Deserialize a value serialized using serialize().
|
|
181
|
+
*/
|
|
182
|
+
declare function deserialize(value: string): unknown;
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Interface for an RPC transport, which is a simple bidirectional message stream. Implement this
|
|
186
|
+
* interface if the built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
|
|
187
|
+
*/
|
|
188
|
+
interface RpcTransport {
|
|
189
|
+
/**
|
|
190
|
+
* Sends a message to the other end.
|
|
191
|
+
*/
|
|
192
|
+
send(message: string): Promise<void>;
|
|
193
|
+
/**
|
|
194
|
+
* Receives a message sent by the other end.
|
|
195
|
+
*
|
|
196
|
+
* If and when the transport becomes disconnected, this will reject. The thrown error will be
|
|
197
|
+
* propagated to all outstanding calls and future calls on any stubs associated with the session.
|
|
198
|
+
* If there are no outstanding calls (and none are made in the future), then the error does not
|
|
199
|
+
* propagate anywhere -- this is considered a "clean" shutdown.
|
|
200
|
+
*/
|
|
201
|
+
receive(): Promise<string>;
|
|
202
|
+
/**
|
|
203
|
+
* Indicates that the RPC system has suffered an error that prevents the session from continuing.
|
|
204
|
+
* The transport should ideally try to send any queued messages if it can, and then close the
|
|
205
|
+
* connection. (It's not strictly necessary to deliver queued messages, but the last message sent
|
|
206
|
+
* before abort() is called is often an "abort" message, which communicates the error to the
|
|
207
|
+
* peer, so if that is dropped, the peer may have less information about what happened.)
|
|
208
|
+
*/
|
|
209
|
+
abort?(reason: any): void;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Options to customize behavior of an RPC session. All functions which start a session should
|
|
213
|
+
* optionally accept this.
|
|
214
|
+
*/
|
|
215
|
+
type RpcSessionOptions = {
|
|
216
|
+
/**
|
|
217
|
+
* If provided, this function will be called whenever an `Error` object is serialized (for any
|
|
218
|
+
* reason, not just because it was thrown). This can be used to log errors, and also to redact
|
|
219
|
+
* them.
|
|
220
|
+
*
|
|
221
|
+
* If `onSendError` returns an Error object, than object will be substituted in place of the
|
|
222
|
+
* original. If it has a stack property, the stack will be sent to the client.
|
|
223
|
+
*
|
|
224
|
+
* If `onSendError` doesn't return anything (or is not provided at all), the default behavior is
|
|
225
|
+
* to serialize the error with the stack omitted.
|
|
226
|
+
*/
|
|
227
|
+
onSendError?: (error: Error) => Error | void;
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* For use in Cloudflare Workers: Construct an HTTP response that starts a WebSocket RPC session
|
|
232
|
+
* with the given `localMain`.
|
|
233
|
+
*/
|
|
234
|
+
declare function newWorkersWebSocketRpcResponse(request: Request, localMain?: any, options?: RpcSessionOptions): Response;
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Implements the server end of an HTTP batch session, using standard Fetch API types to represent
|
|
238
|
+
* HTTP requests and responses.
|
|
239
|
+
*
|
|
240
|
+
* @param request The request received from the client initiating the session.
|
|
241
|
+
* @param localMain The main stub or RpcTarget which the server wishes to expose to the client.
|
|
242
|
+
* @param options Optional RPC session options.
|
|
243
|
+
* @returns The HTTP response to return to the client. Note that the returned object has mutable
|
|
244
|
+
* headers, so you can modify them using e.g. `response.headers.set("Foo", "bar")`.
|
|
245
|
+
*/
|
|
246
|
+
declare function newHttpBatchRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
|
|
247
|
+
/**
|
|
248
|
+
* Implements the server end of an HTTP batch session using traditional Node.js HTTP APIs.
|
|
249
|
+
*
|
|
250
|
+
* @param request The request received from the client initiating the session.
|
|
251
|
+
* @param response The response object, to which the response should be written.
|
|
252
|
+
* @param localMain The main stub or RpcTarget which the server wishes to expose to the client.
|
|
253
|
+
* @param options Optional RPC session options. You can also pass headers to set on the response.
|
|
254
|
+
*/
|
|
255
|
+
declare function nodeHttpBatchRpcResponse(request: IncomingMessage, response: ServerResponse, localMain: any, options?: RpcSessionOptions & {
|
|
256
|
+
headers?: OutgoingHttpHeaders | OutgoingHttpHeader[];
|
|
257
|
+
}): Promise<void>;
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Represents a reference to a remote object, on which methods may be remotely invoked via RPC.
|
|
261
|
+
*
|
|
262
|
+
* `RpcStub` can represent any interface (when using TypeScript, you pass the specific interface
|
|
263
|
+
* type as `T`, but this isn't known at runtime). The way this works is, `RpcStub` is actually a
|
|
264
|
+
* `Proxy`. It makes itself appear as if every possible method / property name is defined. You can
|
|
265
|
+
* invoke any method name, and the invocation will be sent to the server. If it turns out that no
|
|
266
|
+
* such method exists on the remote object, an exception is thrown back. But the client does not
|
|
267
|
+
* actually know, until that point, what methods exist.
|
|
268
|
+
*/
|
|
269
|
+
type RpcStub<T extends Serializable<T>> = Stub<T>;
|
|
270
|
+
declare const RpcStub: {
|
|
271
|
+
new <T extends Serializable<T>>(value: T): RpcStub<T>;
|
|
272
|
+
};
|
|
273
|
+
/**
|
|
274
|
+
* Represents the result of an RPC call.
|
|
275
|
+
*
|
|
276
|
+
* Also used to represent properties. That is, `stub.foo` evaluates to an `RpcPromise` for the
|
|
277
|
+
* value of `foo`.
|
|
278
|
+
*
|
|
279
|
+
* This isn't actually a JavaScript `Promise`. It does, however, have `then()`, `catch()`, and
|
|
280
|
+
* `finally()` methods, like `Promise` does, and because it has a `then()` method, JavaScript will
|
|
281
|
+
* allow you to treat it like a promise, e.g. you can `await` it.
|
|
282
|
+
*
|
|
283
|
+
* An `RpcPromise` is also a proxy, just like `RpcStub`, where calling methods or awaiting
|
|
284
|
+
* properties will make a pipelined network request.
|
|
285
|
+
*
|
|
286
|
+
* Note that and `RpcPromise` is "lazy": the actual final result is not requested from the server
|
|
287
|
+
* until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
|
|
288
|
+
* if you only intend to use the promise for pipelining and you never await it, then there's no
|
|
289
|
+
* need to transmit the resolution!
|
|
290
|
+
*/
|
|
291
|
+
type RpcPromise<T extends Serializable<T>> = Stub<T> & Promise<Stubify<T>>;
|
|
292
|
+
declare const RpcPromise: {};
|
|
293
|
+
/**
|
|
294
|
+
* Use to construct an `RpcSession` on top of a custom `RpcTransport`.
|
|
295
|
+
*
|
|
296
|
+
* Most people won't use this. You only need it if you've implemented your own `RpcTransport`.
|
|
297
|
+
*/
|
|
298
|
+
interface RpcSession<T extends Serializable<T> = undefined> {
|
|
299
|
+
getRemoteMain(): RpcStub<T>;
|
|
300
|
+
getStats(): {
|
|
301
|
+
imports: number;
|
|
302
|
+
exports: number;
|
|
303
|
+
};
|
|
304
|
+
drain(): Promise<void>;
|
|
305
|
+
}
|
|
306
|
+
declare const RpcSession: {
|
|
307
|
+
new <T extends Serializable<T> = undefined>(transport: RpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
|
|
308
|
+
};
|
|
309
|
+
/**
|
|
310
|
+
* Classes which are intended to be passed by reference and called over RPC must extend
|
|
311
|
+
* `RpcTarget`. A class which does not extend `RpcTarget` (and which doesn't have built-in support
|
|
312
|
+
* from the RPC system) cannot be passed in an RPC message at all; an exception will be thrown.
|
|
313
|
+
*
|
|
314
|
+
* Note that on Cloudflare Workers, this `RpcTarget` is an alias for the one exported from the
|
|
315
|
+
* "cloudflare:workers" module, so they can be used interchangably.
|
|
316
|
+
*/
|
|
317
|
+
interface RpcTarget extends RpcTargetBranded {
|
|
318
|
+
}
|
|
319
|
+
declare const RpcTarget: {
|
|
320
|
+
new (): RpcTarget;
|
|
321
|
+
};
|
|
322
|
+
/**
|
|
323
|
+
* Empty interface used as default type parameter for sessions where the other side doesn't
|
|
324
|
+
* necessarily export a main interface.
|
|
325
|
+
*/
|
|
326
|
+
interface Empty {
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Start a WebSocket session given either an already-open WebSocket or a URL.
|
|
330
|
+
*
|
|
331
|
+
* @param webSocket Either the `wss://` URL to connect to, or an already-open WebSocket object to
|
|
332
|
+
* use.
|
|
333
|
+
* @param localMain The main RPC interface to expose to the peer. Returns a stub for the main
|
|
334
|
+
* interface exposed from the peer.
|
|
335
|
+
*/
|
|
336
|
+
declare let newWebSocketRpcSession: <T extends Serializable<T> = Empty>(webSocket: WebSocket | string, localMain?: any, options?: RpcSessionOptions) => RpcStub<T>;
|
|
337
|
+
/**
|
|
338
|
+
* Initiate an HTTP batch session from the client side.
|
|
339
|
+
*
|
|
340
|
+
* The parameters to this method have exactly the same signature as `fetch()`, but the return
|
|
341
|
+
* value is an RpcStub. You can customize anything about the request except for the method
|
|
342
|
+
* (it will always be set to POST) and the body (which the RPC system will fill in).
|
|
343
|
+
*/
|
|
344
|
+
declare let newHttpBatchRpcSession: <T extends Serializable<T>>(urlOrRequest: string | Request, init?: RequestInit) => RpcStub<T>;
|
|
345
|
+
/**
|
|
346
|
+
* Initiate an RPC session over a MessagePort, which is particularly useful for communicating
|
|
347
|
+
* between an iframe and its parent frame in a browser context. Each side should call this function
|
|
348
|
+
* on its own end of the MessageChannel.
|
|
349
|
+
*/
|
|
350
|
+
declare let newMessagePortRpcSession: <T extends Serializable<T> = Empty>(port: MessagePort, localMain?: any, options?: RpcSessionOptions) => RpcStub<T>;
|
|
351
|
+
/**
|
|
352
|
+
* Implements unified handling of HTTP-batch and WebSocket responses for the Cloudflare Workers
|
|
353
|
+
* Runtime.
|
|
354
|
+
*
|
|
355
|
+
* SECURITY WARNING: This function accepts cross-origin requests. If you do not want this, you
|
|
356
|
+
* should validate the `Origin` header before calling this, or use `newHttpBatchRpcSession()` and
|
|
357
|
+
* `newWebSocketRpcSession()` directly with appropriate security measures for each type of request.
|
|
358
|
+
* But if your API uses in-band authorization (i.e. it has an RPC method that takes the user's
|
|
359
|
+
* credentials as parameters and returns the authorized API), then cross-origin requests should
|
|
360
|
+
* be safe.
|
|
361
|
+
*/
|
|
362
|
+
declare function newWorkersRpcResponse(request: Request, localMain: any): Promise<Response>;
|
|
363
|
+
|
|
364
|
+
export { RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, deserialize, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
|