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