capnweb 0.0.0-b2fcb34 → 0.0.0-bc4bc45

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/dist/index.d.ts CHANGED
@@ -1,176 +1,139 @@
1
- import { IncomingMessage, ServerResponse, OutgoingHttpHeaders, OutgoingHttpHeader } from 'node:http';
1
+ import { IncomingMessage, OutgoingHttpHeader, OutgoingHttpHeaders, ServerResponse } from "node:http";
2
2
 
3
+ //#region src/types.d.ts
3
4
  // Copyright (c) 2025 Cloudflare, Inc.
4
5
  // Licensed under the MIT license found in the LICENSE.txt file or at:
5
6
  // https://opensource.org/license/mit
6
-
7
7
  // This file borrows heavily from `types/defines/rpc.d.ts` in workerd.
8
-
9
8
  // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s.
10
9
  // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`.
11
10
  // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to
12
11
  // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape)
13
12
  declare const __RPC_STUB_BRAND: '__RPC_STUB_BRAND';
14
13
  declare const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND';
14
+ // Distinguishes mapper placeholders from regular values so param unwrapping can accept them.
15
+ declare const __RPC_MAP_VALUE_BRAND: unique symbol;
15
16
  interface RpcTargetBranded {
16
17
  [__RPC_TARGET_BRAND]: never;
17
18
  }
18
-
19
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
20
+ // `never[]` preserves compatibility with strongly-typed function signatures without introducing
21
+ // `any` into inference.
22
+ type Stubable = RpcTargetBranded | ((...args: never[]) => unknown);
23
+ type IsUnknown<T> = unknown extends T ? ([T] extends [unknown] ? true : false) : false; // Types that can be passed over RPC
24
+ // The reason for using a generic type here is to build the serializable subset of RPC-compatible
25
+ // composite types. This allows types defined with the "interface" keyword to pass the
25
26
  // 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
-
27
+ type RpcCompatible<T> = // Allow `unknown` as a leaf so records/interfaces with `unknown` fields remain compatible.
28
+ (IsUnknown<T> extends true ? unknown : never) // RPC-compatible base values
29
+ | BaseType // RPC-compatible composites
30
+ | Map<T extends Map<infer U, unknown> ? RpcCompatible<U> : never, T extends Map<unknown, infer U> ? RpcCompatible<U> : never> | Set<T extends Set<infer U> ? RpcCompatible<U> : never> | Array<T extends Array<infer U> ? RpcCompatible<U> : never> | ReadonlyArray<T extends ReadonlyArray<infer U> ? RpcCompatible<U> : never> | { [K in keyof T as K extends string | number ? K : never]: RpcCompatible<T[K]> } | Promise<T extends Promise<infer U> ? RpcCompatible<U> : never> // Special types
31
+ | Stub<Stubable> // Serialized as stubs, see `Stubify`
32
+ | Stubable;
46
33
  // Base type for all RPC stubs, including common memory management methods.
47
34
  // `T` is used as a marker type for unwrapping `Stub`s later.
48
- interface StubBase<T extends Serializable<T>> extends Disposable {
35
+ interface StubBase<T = unknown> extends Disposable {
49
36
  [__RPC_STUB_BRAND]: T;
50
37
  dup(): this;
51
38
  onRpcBroken(callback: (error: any) => void): void;
52
39
  }
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.
40
+ type Stub<T extends RpcCompatible<T>> = T extends object ? Provider<T> & StubBase<T> : StubBase<T>;
41
+ type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | BigUint64Array | BigInt64Array | Float32Array | Float64Array; // This represents all the types that can be sent as-is over an RPC boundary
42
+ type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | Blob | ReadableStream<any> // Chunk type can be any RPC-compatible type
43
+ | WritableStream<any> // Chunk type can be any RPC-compatible type
44
+ | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
90
45
  // 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
-
46
+ type Stubify<T> = T extends Stubable ? Stub<T> : T extends Promise<infer U> ? Stubify<U> : T extends StubBase<any> ? T : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>> : T extends Set<infer V> ? Set<Stubify<V>> : T extends [] ? [] : T extends [infer Head, ...infer Tail] ? [Stubify<Head>, ...Stubify<Tail>] : T extends readonly [] ? readonly [] : T extends readonly [infer Head, ...infer Tail] ? readonly [Stubify<Head>, ...Stubify<Tail>] : T extends Array<infer V> ? Array<Stubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>> : T extends BaseType ? T // When using "unknown" instead of "any", interfaces are not stubified.
47
+ : T extends {
48
+ [key: string | number]: any;
49
+ } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
104
50
  // Recursively rewrite all `Stub<T>`s with the corresponding `T`s.
105
51
  // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:
106
52
  // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.
107
53
  // 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.
54
+ type UnstubifyInner<T> = // Preserve local RpcTarget acceptance, but avoid needless `Stub | Value` unions when the stub
55
+ // is already assignable to the value type (important for callback contextual typing).
56
+ T extends StubBase<infer V> ? (T extends V ? UnstubifyInner<V> : (T | UnstubifyInner<V>)) : T extends Promise<infer U> ? UnstubifyInner<U> : T extends Map<infer K, infer V> ? Map<Unstubify<K>, Unstubify<V>> : T extends Set<infer V> ? Set<Unstubify<V>> : T extends [] ? [] : T extends [infer Head, ...infer Tail] ? [Unstubify<Head>, ...Unstubify<Tail>] : T extends readonly [] ? readonly [] : T extends readonly [infer Head, ...infer Tail] ? readonly [Unstubify<Head>, ...Unstubify<Tail>] : T extends Array<infer V> ? Array<Unstubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Unstubify<V>> : T extends BaseType ? T : T extends {
57
+ [key: string | number]: unknown;
58
+ } ? { [K in keyof T as K extends string | number ? K : never]: Unstubify<T[K]> } : T; // You can put promises anywhere in the params and they'll be resolved before delivery.
119
59
  // (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.
60
+ // Map placeholders are also allowed so primitive map callback inputs can be forwarded directly
61
+ // into RPC params.
62
+ //
63
+ // Keep raw non-stub members so generic assignability still works when UnstubifyInner<T> is deferred.
64
+ // Remove stub members from mixed unions so callback params don’t get both stub and unstubbed signatures.
65
+ // Marker carried by map() callback inputs. This lets primitive placeholders flow through params.
66
+ type Unstubify<T> = NonStubMembers<T> | UnstubifyInner<T> | Promise<UnstubifyInner<T>> | MapValuePlaceholder<UnstubifyInner<T>>;
67
+ type UnstubifyAll<A extends readonly unknown[]> = { [I in keyof A]: Unstubify<A[I]> };
68
+ interface MapValuePlaceholder<T> {
69
+ [__RPC_MAP_VALUE_BRAND]: T;
70
+ }
71
+ type NonStubMembers<T> = Exclude<T, StubBase<any>>; // Utility type for adding `Disposable`s to `object` types only.
125
72
  // 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.
73
+ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // Type for method return or property on an RPC interface.
129
74
  // - Stubable types are replaced by stubs.
130
- // - Serializable types are passed by value, with stubable types replaced by stubs
75
+ // - RpcCompatible types are passed by value, with stubable types replaced by stubs
131
76
  // and a top-level `Disposer`.
132
77
  // Everything else can't be passed over RPC.
133
78
  // Technically, we use custom thenables here, but they quack like `Promise`s.
134
79
  // Intersecting with `(Maybe)Provider` allows pipelining.
135
80
  // 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.
81
+ type Result<R> = IsAny<R> extends true ? UnknownResult : IsUnknown<R> extends true ? UnknownResult : R extends Stubable ? Promise<Stub<R>> & Provider<R> & StubBase<R> : R extends RpcCompatible<R> ? Promise<Stubify<R> & MaybeDisposable<R>> & Provider<R> & StubBase<R> : never;
82
+ type IsAny<T> = 0 extends (1 & T) ? true : false;
83
+ type UnknownResult = Promise<unknown> & Provider<unknown> & StubBase<unknown>; // Type for method or property on an RPC interface.
142
84
  // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
143
85
  // Unwrapping `Stub`s allows calling with `Stubable` arguments.
144
86
  // For properties, rewrite types to be `Result`s.
145
87
  // 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.
88
+ type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => IsAny<R> extends true ? UnknownResult : Result<Awaited<R>> : Result<Awaited<V>>; // Type for the callable part of an `Provider` if `T` is callable.
151
89
  // 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.
90
+ type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
91
+ type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
92
+ type MapCallbackValue<T> = // `Omit` removes call signatures, so re-intersect callable provider behavior.
93
+ T extends unknown ? Omit<Result<T>, keyof Promise<unknown>> & MaybeCallableProvider<T> & MapValuePlaceholder<T> : never;
94
+ type InvalidNativePromiseInMapResult<T, Seen = never> = T extends unknown ? InvalidNativePromiseInMapResultImpl<T, Seen> : never;
95
+ type InvalidNativePromiseInMapResultImpl<T, Seen> = [T] extends [Seen] ? never // RpcPromise is modeled as Promise & StubBase, so allow promise-like stub values.
96
+ : T extends StubBase<any> ? never // Native thenables cannot be represented in map recordings, even when typed as PromiseLike.
97
+ : T extends PromiseLike<unknown> ? T : T extends Map<infer K, infer V> ? InvalidNativePromiseInMapResult<K, Seen | T> | InvalidNativePromiseInMapResult<V, Seen | T> : T extends Set<infer V> ? InvalidNativePromiseInMapResult<V, Seen | T> : T extends readonly [] ? never : T extends readonly [infer Head, ...infer Tail] ? InvalidNativePromiseInMapResult<Head, Seen | T> | InvalidNativePromiseInMapResult<Tail[number], Seen | T> : T extends ReadonlyArray<infer V> ? InvalidNativePromiseInMapResult<V, Seen | T> : T extends {
98
+ [key: string | number]: unknown;
99
+ } ? InvalidNativePromiseInMapResult<T[Extract<keyof T, string | number>], Seen | T> : never;
100
+ type MapCallbackReturn<T> = InvalidNativePromiseInMapResult<T> extends never ? T : never;
101
+ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
102
+ map<V>(callback: (elem: MapCallbackValue<E>) => MapCallbackReturn<V>): Result<Array<V>>;
103
+ };
104
+ type TupleProvider<T extends ReadonlyArray<unknown>> = { [K in TupleIndexKeys<T>]: MethodOrProperty<T[K]> } & ArrayProvider<T[number]>; // Base type for all other types providing RPC-like interfaces.
157
105
  // 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
-
106
+ type Provider<T> = MaybeCallableProvider<T> & (T extends ReadonlyArray<unknown> ? number extends T["length"] ? ArrayProvider<T[number]> : TupleProvider<T> : { [K in Exclude<keyof T, symbol | keyof StubBase<never>>]: MethodOrProperty<T[K]> } & {
107
+ map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
108
+ });
109
+ //#endregion
110
+ //#region src/serialize.d.ts
111
+ /**
112
+ * Encoding levels determine what representation the RPC system hands to the transport.
113
+ * Each level names what the transport can assume about message values.
114
+ *
115
+ * - `"string"`: JSON string. Default, used by HTTP batch and WebSocket transports.
116
+ * - `"jsonCompatible"`: JSON-compatible JS value tree. For custom encoders.
117
+ * - `"jsonCompatibleWithBytes"`: Like `"jsonCompatible"` but Uint8Array stays raw.
118
+ * - `"structuredClonable"`: Structured-clonable native values pass through where possible.
119
+ *
120
+ * @example
121
+ * ```ts
122
+ * // What happens to Uint8Array([1, 2, 3]) at each level:
123
+ * "string" → '["bytes","AQID"]' // JSON string with base64
124
+ * "jsonCompatible" → ["bytes", "AQID"] // JS array with base64
125
+ * "jsonCompatibleWithBytes" → ["bytes", Uint8Array] // JS array with raw bytes
126
+ * "structuredClonable" → ["bytes", Uint8Array] // + Date, BigInt stay native
127
+ * ```
128
+ */
129
+ type EncodingLevel = "string" | "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
130
+ interface RpcLimits {
131
+ maxBigIntDigits: number;
132
+ maxDepth: number;
133
+ maxMessageSize: number;
134
+ }
135
+ declare const DEFAULT_MAX_DEPTH = 256;
136
+ declare const DEFAULT_LIMITS: RpcLimits;
174
137
  /**
175
138
  * Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
176
139
  * RPC stubs, but it will support basic data types.
@@ -180,59 +143,129 @@ declare function serialize(value: unknown): string;
180
143
  * Deserialize a value serialized using serialize().
181
144
  */
182
145
  declare function deserialize(value: string): unknown;
183
-
146
+ //#endregion
147
+ //#region src/rpc.d.ts
184
148
  /**
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.
149
+ * Interface for a string-based RPC transport. This is the default transport type — no
150
+ * `encodingLevel` field is needed. Messages are JSON strings. Implement this interface if the
151
+ * built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
187
152
  */
188
153
  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;
154
+ /**
155
+ * The encoding level this transport works with. For this interface it is always "string";
156
+ * it may be omitted. (See `RpcTransportWithCustomEncoding` for the other levels.)
157
+ */
158
+ readonly encodingLevel?: "string";
159
+ /**
160
+ * Sends a message to the other end. May optionally return a promise; if the promise rejects,
161
+ * the session is aborted.
162
+ */
163
+ send(message: string): void | Promise<void>;
164
+ /**
165
+ * Receives a message sent by the other end.
166
+ *
167
+ * If and when the transport becomes disconnected, this will reject. The thrown error will be
168
+ * propagated to all outstanding calls and future calls on any stubs associated with the session.
169
+ * If there are no outstanding calls (and none are made in the future), then the error does not
170
+ * propagate anywhere -- this is considered a "clean" shutdown.
171
+ */
172
+ receive(): Promise<string>;
173
+ /**
174
+ * Indicates that the RPC system has suffered an error that prevents the session from continuing.
175
+ * The transport should ideally try to send any queued messages if it can, and then close the
176
+ * connection. (It's not strictly necessary to deliver queued messages, but the last message sent
177
+ * before abort() is called is often an "abort" message, which communicates the error to the
178
+ * peer, so if that is dropped, the peer may have less information about what happened.)
179
+ */
180
+ abort?(reason: any): void;
181
+ }
182
+ /**
183
+ * Interface for a transport that receives partially encoded JS values instead of JSON strings.
184
+ * The selected `encodingLevel` describes what the transport can assume about message values.
185
+ */
186
+ interface RpcTransportWithCustomEncoding {
187
+ /**
188
+ * The encoding level this transport works with.
189
+ *
190
+ * - "jsonCompatible": JSON-compatible JS value tree; transport handles final serialization.
191
+ * - "jsonCompatibleWithBytes": Like "jsonCompatible" but Uint8Array values are left raw.
192
+ * - "structuredClonable": Structured-clonable native values pass through where possible.
193
+ */
194
+ readonly encodingLevel: "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
195
+ /**
196
+ * Encodes and sends a message to the other end. Returns the encoded byte size if known.
197
+ * If the size is unavailable, return void; Cap'n Web will estimate stream message sizes for
198
+ * flow control. Send errors should be propagated via `receive()` rejecting.
199
+ */
200
+ send(message: unknown): number | void;
201
+ /**
202
+ * Receives and decodes 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<unknown>;
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;
210
218
  }
219
+ /** Any supported transport type. */
220
+ type AnyRpcTransport = RpcTransport | RpcTransportWithCustomEncoding;
211
221
  /**
212
222
  * Options to customize behavior of an RPC session. All functions which start a session should
213
223
  * optionally accept this.
214
224
  */
215
225
  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;
226
+ /**
227
+ * If provided, this function will be called whenever an `Error` object is serialized (for any
228
+ * reason, not just because it was thrown). This can be used to log errors, and also to redact
229
+ * them.
230
+ *
231
+ * If `onSendError` returns an Error object, than object will be substituted in place of the
232
+ * original. If it has a stack property, the stack will be sent to the client.
233
+ *
234
+ * If `onSendError` doesn't return anything (or is not provided at all), the default behavior is
235
+ * to serialize the error with the stack omitted.
236
+ */
237
+ onSendError?: (error: Error) => Error | void;
238
+ /**
239
+ * Overrides for the resource limits enforced while deserializing messages from the peer. Any
240
+ * field left unset falls back to `DEFAULT_LIMITS`. These guard against resource-exhaustion
241
+ * attacks from untrusted peers; see `RpcLimits` for the meaning and defaults of each field.
242
+ *
243
+ * Limits are a purely local, receiver-side decision -- the protocol has no negotiation step, so
244
+ * the peer never learns these values. A message that exceeds a limit is rejected, aborting the
245
+ * session.
246
+ */
247
+ limits?: Partial<RpcLimits>;
228
248
  };
229
-
249
+ //#endregion
250
+ //#region src/websocket.d.ts
230
251
  /**
231
252
  * For use in Cloudflare Workers: Construct an HTTP response that starts a WebSocket RPC session
232
253
  * with the given `localMain`.
233
254
  */
234
255
  declare function newWorkersWebSocketRpcResponse(request: Request, localMain?: any, options?: RpcSessionOptions): Response;
235
-
256
+ /**
257
+ * Generic WebSocket transport. Default `T = string` is backward-compatible and satisfies
258
+ * `RpcTransport`. Use `T = ArrayBuffer` as a building block for binary transports.
259
+ */
260
+ declare class WebSocketTransport<T extends string | ArrayBuffer = string> {
261
+ #private;
262
+ constructor(webSocket: WebSocket);
263
+ send(message: T): void;
264
+ receive(): Promise<T>;
265
+ abort(reason: any): void;
266
+ }
267
+ //#endregion
268
+ //#region src/batch.d.ts
236
269
  /**
237
270
  * Implements the server end of an HTTP batch session, using standard Fetch API types to represent
238
271
  * HTTP requests and responses.
@@ -253,9 +286,10 @@ declare function newHttpBatchRpcResponse(request: Request, localMain: any, optio
253
286
  * @param options Optional RPC session options. You can also pass headers to set on the response.
254
287
  */
255
288
  declare function nodeHttpBatchRpcResponse(request: IncomingMessage, response: ServerResponse, localMain: any, options?: RpcSessionOptions & {
256
- headers?: OutgoingHttpHeaders | OutgoingHttpHeader[];
289
+ headers?: OutgoingHttpHeaders | OutgoingHttpHeader[];
257
290
  }): Promise<void>;
258
-
291
+ //#endregion
292
+ //#region src/index.d.ts
259
293
  /**
260
294
  * Represents a reference to a remote object, on which methods may be remotely invoked via RPC.
261
295
  *
@@ -266,9 +300,9 @@ declare function nodeHttpBatchRpcResponse(request: IncomingMessage, response: Se
266
300
  * such method exists on the remote object, an exception is thrown back. But the client does not
267
301
  * actually know, until that point, what methods exist.
268
302
  */
269
- type RpcStub<T extends Serializable<T>> = Stub<T>;
303
+ type RpcStub<T extends RpcCompatible<T>> = Stub<T>;
270
304
  declare const RpcStub: {
271
- new <T extends Serializable<T>>(value: T): RpcStub<T>;
305
+ new <T extends RpcCompatible<T>>(value: T): RpcStub<T>;
272
306
  };
273
307
  /**
274
308
  * Represents the result of an RPC call.
@@ -288,23 +322,23 @@ declare const RpcStub: {
288
322
  * if you only intend to use the promise for pipelining and you never await it, then there's no
289
323
  * need to transmit the resolution!
290
324
  */
291
- type RpcPromise<T extends Serializable<T>> = Stub<T> & Promise<Stubify<T>>;
325
+ type RpcPromise<T extends RpcCompatible<T>> = Stub<T> & Promise<Stubify<T>>;
292
326
  declare const RpcPromise: {};
293
327
  /**
294
328
  * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
295
329
  *
296
330
  * Most people won't use this. You only need it if you've implemented your own `RpcTransport`.
297
331
  */
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>;
332
+ interface RpcSession<T extends RpcCompatible<T> = undefined> {
333
+ getRemoteMain(): RpcStub<T>;
334
+ getStats(): {
335
+ imports: number;
336
+ exports: number;
337
+ };
338
+ drain(): Promise<void>;
305
339
  }
306
340
  declare const RpcSession: {
307
- new <T extends Serializable<T> = undefined>(transport: RpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
341
+ new <T extends RpcCompatible<T> = undefined>(transport: AnyRpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
308
342
  };
309
343
  /**
310
344
  * Classes which are intended to be passed by reference and called over RPC must extend
@@ -314,17 +348,15 @@ declare const RpcSession: {
314
348
  * Note that on Cloudflare Workers, this `RpcTarget` is an alias for the one exported from the
315
349
  * "cloudflare:workers" module, so they can be used interchangably.
316
350
  */
317
- interface RpcTarget extends RpcTargetBranded {
318
- }
351
+ interface RpcTarget extends RpcTargetBranded {}
319
352
  declare const RpcTarget: {
320
- new (): RpcTarget;
353
+ new (): RpcTarget;
321
354
  };
322
355
  /**
323
356
  * Empty interface used as default type parameter for sessions where the other side doesn't
324
357
  * necessarily export a main interface.
325
358
  */
326
- interface Empty {
327
- }
359
+ interface Empty {}
328
360
  /**
329
361
  * Start a WebSocket session given either an already-open WebSocket or a URL.
330
362
  *
@@ -333,7 +365,7 @@ interface Empty {
333
365
  * @param localMain The main RPC interface to expose to the peer. Returns a stub for the main
334
366
  * interface exposed from the peer.
335
367
  */
336
- declare let newWebSocketRpcSession: <T extends Serializable<T> = Empty>(webSocket: WebSocket | string, localMain?: any, options?: RpcSessionOptions) => RpcStub<T>;
368
+ declare let newWebSocketRpcSession: <T extends RpcCompatible<T> = Empty>(webSocket: WebSocket | string, localMain?: any, options?: RpcSessionOptions) => RpcStub<T>;
337
369
  /**
338
370
  * Initiate an HTTP batch session from the client side.
339
371
  *
@@ -341,13 +373,13 @@ declare let newWebSocketRpcSession: <T extends Serializable<T> = Empty>(webSocke
341
373
  * value is an RpcStub. You can customize anything about the request except for the method
342
374
  * (it will always be set to POST) and the body (which the RPC system will fill in).
343
375
  */
344
- declare let newHttpBatchRpcSession: <T extends Serializable<T>>(urlOrRequest: string | Request, init?: RequestInit) => RpcStub<T>;
376
+ declare let newHttpBatchRpcSession: <T extends RpcCompatible<T>>(urlOrRequest: string | Request, options?: RpcSessionOptions) => RpcStub<T>;
345
377
  /**
346
378
  * Initiate an RPC session over a MessagePort, which is particularly useful for communicating
347
379
  * between an iframe and its parent frame in a browser context. Each side should call this function
348
380
  * on its own end of the MessageChannel.
349
381
  */
350
- declare let newMessagePortRpcSession: <T extends Serializable<T> = Empty>(port: MessagePort, localMain?: any, options?: RpcSessionOptions) => RpcStub<T>;
382
+ declare let newMessagePortRpcSession: <T extends RpcCompatible<T> = Empty>(port: MessagePort, localMain?: any, options?: RpcSessionOptions) => RpcStub<T>;
351
383
  /**
352
384
  * Implements unified handling of HTTP-batch and WebSocket responses for the Cloudflare Workers
353
385
  * Runtime.
@@ -359,6 +391,7 @@ declare let newMessagePortRpcSession: <T extends Serializable<T> = Empty>(port:
359
391
  * credentials as parameters and returns the authorized API), then cross-origin requests should
360
392
  * be safe.
361
393
  */
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 };
394
+ declare function newWorkersRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
395
+ //#endregion
396
+ export { type AnyRpcTransport, DEFAULT_LIMITS, DEFAULT_MAX_DEPTH, type EncodingLevel, type RpcCompatible, type RpcLimits, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, type RpcTransportWithCustomEncoding, WebSocketTransport, deserialize, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
397
+ //# sourceMappingURL=index.d.ts.map