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.
@@ -1,6 +1,5 @@
1
1
  import { IncomingMessage, OutgoingHttpHeader, OutgoingHttpHeaders, ServerResponse } from "node:http";
2
2
  import { ServerWebSocket } from "bun";
3
-
4
3
  //#region src/types.d.ts
5
4
  // Copyright (c) 2025 Cloudflare, Inc.
6
5
  // Licensed under the MIT license found in the LICENSE.txt file or at:
@@ -21,16 +20,23 @@ interface RpcTargetBranded {
21
20
  // `never[]` preserves compatibility with strongly-typed function signatures without introducing
22
21
  // `any` into inference.
23
22
  type Stubable = RpcTargetBranded | ((...args: never[]) => unknown);
24
- type IsUnknown<T> = unknown extends T ? ([T] extends [unknown] ? true : false) : false; // Types that can be passed over RPC
23
+ // Note: also true for `any` (call sites that care check `IsAny` first).
24
+ type IsUnknown<T> = unknown extends T ? true : false;
25
+ // Types that can be passed over RPC
25
26
  // The reason for using a generic type here is to build the serializable subset of RPC-compatible
26
27
  // composite types. This allows types defined with the "interface" keyword to pass the
27
28
  // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
28
- type RpcCompatible<T> = // Allow `unknown` as a leaf so records/interfaces with `unknown` fields remain compatible.
29
- (IsUnknown<T> extends true ? unknown : never) // RPC-compatible base values
30
- | BaseType // RPC-compatible composites
31
- | 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
32
- | Stub<Stubable> // Serialized as stubs, see `Stubify`
33
- | Stubable;
29
+ type RpcCompatible<T> =
30
+ // Allow `unknown` as a leaf so records/interfaces with `unknown` fields remain compatible.
31
+ (IsUnknown<T> extends true ? unknown : never) |
32
+ // RPC-compatible base values
33
+ BaseType |
34
+ // RPC-compatible composites
35
+ 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> |
36
+ // Special types
37
+ Stub<Stubable> |
38
+ // Serialized as stubs, see `Stubify`
39
+ Stubable;
34
40
  // Base type for all RPC stubs, including common memory management methods.
35
41
  // `T` is used as a marker type for unwrapping `Stub`s later.
36
42
  interface StubBase<T = unknown> extends Disposable {
@@ -39,23 +45,35 @@ interface StubBase<T = unknown> extends Disposable {
39
45
  onRpcBroken(callback: (error: any) => void): void;
40
46
  }
41
47
  type Stub<T extends RpcCompatible<T>> = T extends object ? Provider<T> & StubBase<T> : StubBase<T>;
42
- 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
43
- type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | Blob | ReadableStream<Uint8Array> | 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.
48
+ type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | BigUint64Array | BigInt64Array | Float32Array | Float64Array;
49
+ // This represents all the types that can be sent as-is over an RPC boundary
50
+ 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
51
+ | WritableStream<any> // Chunk type can be any RPC-compatible type
52
+ | URL | Request | Response | Headers;
53
+ // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
54
+ // Arm ordering matters here:
55
+ // - `Promise` must come before `StubBase`: `RpcPromise<T>` matches both, and must resolve
56
+ // through the Promise arm rather than pass through as-is.
57
+ // - `StubBase` must come before `Stubable`: `Stub<T>` of a callable `T` is itself callable, so
58
+ // it matches `Stubable`. Checking `StubBase` first keeps existing stubs as-is instead of
59
+ // double-wrapping them as `Stub<Stub<T>>`.
45
60
  // prettier-ignore
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 {
61
+ type Stubify<T> = T extends Promise<infer U> ? Stubify<U> : T extends StubBase<any> ? T : T extends Stubable ? Stub<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 :
62
+ // When using "unknown" instead of "any", interfaces are not stubified.
63
+ T extends {
48
64
  [key: string | number]: any;
49
- } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
65
+ } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]>; } : T;
50
66
  // Recursively rewrite all `Stub<T>`s with the corresponding `T`s.
51
67
  // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:
52
68
  // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.
53
69
  // prettier-ignore
54
- type UnstubifyInner<T> = // Preserve local RpcTarget acceptance, but avoid needless `Stub | Value` unions when the stub
70
+ type UnstubifyInner<T> =
71
+ // Preserve local RpcTarget acceptance, but avoid needless `Stub | Value` unions when the stub
55
72
  // is already assignable to the value type (important for callback contextual typing).
56
73
  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
74
  [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.
75
+ } ? { [K in keyof T as K extends string | number ? K : never]: Unstubify<T[K]>; } : T;
76
+ // You can put promises anywhere in the params and they'll be resolved before delivery.
59
77
  // (This also covers RpcPromise, because it's defined as being a Promise.)
60
78
  // Map placeholders are also allowed so primitive map callback inputs can be forwarded directly
61
79
  // into RPC params.
@@ -64,13 +82,39 @@ T extends StubBase<infer V> ? (T extends V ? UnstubifyInner<V> : (T | UnstubifyI
64
82
  // Remove stub members from mixed unions so callback params don’t get both stub and unstubbed signatures.
65
83
  // Marker carried by map() callback inputs. This lets primitive placeholders flow through params.
66
84
  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]> };
85
+ type UnstubifyAll<A extends readonly unknown[]> = { [I in keyof A]: Unstubify<A[I]>; };
68
86
  interface MapValuePlaceholder<T> {
69
87
  [__RPC_MAP_VALUE_BRAND]: T;
70
88
  }
71
- type NonStubMembers<T> = Exclude<T, StubBase<any>>; // Utility type for adding `Disposable`s to `object` types only.
89
+ type NonStubMembers<T> = Exclude<T, StubBase<any>>;
90
+ // Utility type for adding `Disposable`s to `object` types only.
72
91
  // Note `unknown & T` is equivalent to `T`.
73
- type MaybeDisposable<T> = T extends object ? Disposable : unknown; // Type for method return or property on an RPC interface.
92
+ type MaybeDisposable<T> = T extends object ? Disposable : unknown;
93
+ // The type behind the public `RpcPromise` (re-exported with its `RpcCompatible` constraint from
94
+ // index.ts). Defined here so that `Result`'s arms below resolve to the exact same alias
95
+ // instantiation: when both sides of an assignability check are the same alias applied to the
96
+ // same type arguments, the checker short-circuits on identity instead of recursing through the
97
+ // full structural comparison of these mutually-recursive types.
98
+ type RpcPromise$2<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & StubBase<T> : Promise<Stubify<T> & MaybeDisposable<T>> & Provider<T> & StubBase<T>;
99
+ // The elision `Result` applies to a bare stub type: unwrap `Stub<T>` back to `T` when the
100
+ // payload is `Stubable`. Such stubs await back to a stub either way, so eliding keeps a
101
+ // declared `Promise<RpcStub<T>>` return interchangeable with a `Promise<T>` return.
102
+ // Plain-interface stubs are NOT elided: `RpcPromise<U>` only awaits to `Stub<U>` when
103
+ // `U extends Stubable`, so eliding those would change the awaited type from a stub to a
104
+ // stubified record. The payload check is deliberately non-distributive (`[U] extends [...]`).
105
+ // `Stub<any>` is not elided either: `[any] extends [Stubable]` is true, so without the `IsAny`
106
+ // guard an `any`-payload stub would lose its stub surface.
107
+ // Also used by the `RpcPromise` constructor signature (index.ts), which applies exactly this
108
+ // transformation so constructing from a promised stub matches the method-return type.
109
+ type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
110
+ // What the promise given to `new RpcPromise<T>(...)` may resolve to: the payload itself, or —
111
+ // for stubable payloads — a stub of it. `NoInfer` keeps the stub arm out of inference, so an
112
+ // inferred `T` is always the promise's own resolution type; the arm only matters when `T` is
113
+ // explicitly annotated (`new RpcPromise<Counter>(promiseOfStub)`). Stubs of non-stubable
114
+ // payloads are deliberately rejected: `ElideStub` wouldn't elide those, so accepting one would
115
+ // claim the promise awaits to a stubified record while the runtime resolves to a stub.
116
+ type PayloadOrStub<T> = T | NoInfer<Stub<Extract<T, Stubable>>>;
117
+ // Type for method return or property on an RPC interface.
74
118
  // - Stubable types are replaced by stubs.
75
119
  // - RpcCompatible types are passed by value, with stubable types replaced by stubs
76
120
  // and a top-level `Disposer`.
@@ -78,32 +122,49 @@ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // Type for m
78
122
  // Technically, we use custom thenables here, but they quack like `Promise`s.
79
123
  // Intersecting with `(Maybe)Provider` allows pipelining.
80
124
  // prettier-ignore
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;
125
+ type Result<R> = IsAny<R> extends true ? RpcPromise$2<unknown> :
126
+ // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
127
+ // `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
128
+ R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> :
129
+ // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
130
+ // here: anything matching our `StubBase` was produced by machinery that already enforced
131
+ // the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
132
+ // `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
133
+ // types.
134
+ R extends StubBase<any> ? RpcPromise$2<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$2<R> : never;
82
135
  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.
136
+ // Type for method or property on an RPC interface.
84
137
  // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
85
138
  // Unwrapping `Stub`s allows calling with `Stubable` arguments.
86
139
  // For properties, rewrite types to be `Result`s.
87
140
  // In each case, unwrap `Promise`s.
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.
141
+ type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>;
142
+ // Type for the callable part of an `Provider` if `T` is callable.
89
143
  // This is intersected with methods/properties.
90
144
  type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
91
145
  type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
92
- type MapCallbackValue<T> = // `Omit` removes call signatures, so re-intersect callable provider behavior.
146
+ type MapCallbackValue<T> =
147
+ // `Omit` removes call signatures, so re-intersect callable provider behavior.
93
148
  T extends unknown ? Omit<Result<T>, keyof Promise<unknown>> & MaybeCallableProvider<T> & MapValuePlaceholder<T> : never;
94
149
  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 {
150
+ type InvalidNativePromiseInMapResultImpl<T, Seen> = [T] extends [Seen] ? never :
151
+ // RpcPromise is modeled as Promise & StubBase, so allow promise-like stub values.
152
+ T extends StubBase<any> ? never :
153
+ // Native thenables cannot be represented in map recordings, even when typed as PromiseLike.
154
+ 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
155
  [key: string | number]: unknown;
99
156
  } ? InvalidNativePromiseInMapResult<T[Extract<keyof T, string | number>], Seen | T> : never;
100
157
  type MapCallbackReturn<T> = InvalidNativePromiseInMapResult<T> extends never ? T : never;
101
- type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
158
+ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E>; } & {
102
159
  map<V>(callback: (elem: MapCallbackValue<E>) => MapCallbackReturn<V>): Result<Array<V>>;
103
160
  };
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.
161
+ type TupleProvider<T extends ReadonlyArray<unknown>> = { [K in TupleIndexKeys<T>]: MethodOrProperty<T[K]>; } & ArrayProvider<T[number]>;
162
+ // Base type for all other types providing RPC-like interfaces.
105
163
  // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
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]> } & {
164
+ // `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
165
+ // stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
166
+ // `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
167
+ type Provider<T> = MaybeCallableProvider<T> & (T extends ReadonlyArray<unknown> ? number extends T["length"] ? ArrayProvider<T[number]> : TupleProvider<T> : Pick<{ [K in keyof T]: MethodOrProperty<T[K]>; }, Exclude<keyof T, symbol | keyof StubBase<never>>> & {
107
168
  map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
108
169
  });
109
170
  //#endregion
@@ -140,7 +201,7 @@ declare class RpcStub$1 extends RpcTarget$1 {
140
201
  toString(): string;
141
202
  }
142
203
  declare class RpcPromise$1 extends RpcStub$1 {
143
- constructor(hook: StubHook, pathIfPromise: PropertyPath);
204
+ constructor(hook: StubHook | PromiseLike<unknown>, pathIfPromise?: PropertyPath);
144
205
  then(onfulfilled?: ((value: unknown) => unknown) | undefined | null, onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
145
206
  catch(onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
146
207
  finally(onfinally?: (() => void) | undefined | null): Promise<unknown>;
@@ -171,6 +232,9 @@ declare class RpcPayload {
171
232
  private deliverTo;
172
233
  private static deliverRpcPromiseTo;
173
234
  deliverCall(func: Function, thisArg: object | undefined): Promise<RpcPayload>;
235
+ deliverStreamWrite(writer: {
236
+ write(chunk: unknown): Promise<void>;
237
+ }): Promise<RpcPayload>;
174
238
  deliverResolve(): Promise<unknown>;
175
239
  dispose(): void;
176
240
  private disposeImpl;
@@ -179,6 +243,32 @@ declare class RpcPayload {
179
243
  }
180
244
  //#endregion
181
245
  //#region src/serialize.d.ts
246
+ /**
247
+ * Encoding levels determine what representation the RPC system hands to the transport.
248
+ * Each level names what the transport can assume about message values.
249
+ *
250
+ * - `"string"`: JSON string. Default, used by HTTP batch and WebSocket transports.
251
+ * - `"jsonCompatible"`: JSON-compatible JS value tree. For custom encoders.
252
+ * - `"jsonCompatibleWithBytes"`: Like `"jsonCompatible"` but Uint8Array stays raw.
253
+ * - `"structuredClonable"`: Structured-clonable native values pass through where possible.
254
+ *
255
+ * @example
256
+ * ```ts
257
+ * // What happens to Uint8Array([1, 2, 3]) at each level:
258
+ * "string" → '["bytes","AQID"]' // JSON string with base64
259
+ * "jsonCompatible" → ["bytes", "AQID"] // JS array with base64
260
+ * "jsonCompatibleWithBytes" → ["bytes", Uint8Array] // JS array with raw bytes
261
+ * "structuredClonable" → ["bytes", Uint8Array] // + Date, BigInt stay native
262
+ * ```
263
+ */
264
+ type EncodingLevel = "string" | "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
265
+ interface RpcLimits {
266
+ maxBigIntDigits: number;
267
+ maxDepth: number;
268
+ maxMessageSize: number;
269
+ }
270
+ declare const DEFAULT_MAX_DEPTH = 256;
271
+ declare const DEFAULT_LIMITS: RpcLimits;
182
272
  /**
183
273
  * Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
184
274
  * RPC stubs, but it will support basic data types.
@@ -191,14 +281,21 @@ declare function deserialize(value: string): unknown;
191
281
  //#endregion
192
282
  //#region src/rpc.d.ts
193
283
  /**
194
- * Interface for an RPC transport, which is a simple bidirectional message stream. Implement this
195
- * interface if the built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
284
+ * Interface for a string-based RPC transport. This is the default transport type — no
285
+ * `encodingLevel` field is needed. Messages are JSON strings. Implement this interface if the
286
+ * built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
196
287
  */
197
288
  interface RpcTransport {
198
289
  /**
199
- * Sends a message to the other end.
290
+ * The encoding level this transport works with. For this interface it is always "string";
291
+ * it may be omitted. (See `RpcTransportWithCustomEncoding` for the other levels.)
200
292
  */
201
- send(message: string): Promise<void>;
293
+ readonly encodingLevel?: "string";
294
+ /**
295
+ * Sends a message to the other end. May optionally return a promise; if the promise rejects,
296
+ * the session is aborted.
297
+ */
298
+ send(message: string): void | Promise<void>;
202
299
  /**
203
300
  * Receives a message sent by the other end.
204
301
  *
@@ -217,6 +314,45 @@ interface RpcTransport {
217
314
  */
218
315
  abort?(reason: any): void;
219
316
  }
317
+ /**
318
+ * Interface for a transport that receives partially encoded JS values instead of JSON strings.
319
+ * The selected `encodingLevel` describes what the transport can assume about message values.
320
+ */
321
+ interface RpcTransportWithCustomEncoding {
322
+ /**
323
+ * The encoding level this transport works with.
324
+ *
325
+ * - "jsonCompatible": JSON-compatible JS value tree; transport handles final serialization.
326
+ * - "jsonCompatibleWithBytes": Like "jsonCompatible" but Uint8Array values are left raw.
327
+ * - "structuredClonable": Structured-clonable native values pass through where possible.
328
+ */
329
+ readonly encodingLevel: "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
330
+ /**
331
+ * Encodes and sends a message to the other end. Returns the encoded byte size if known.
332
+ * If the size is unavailable, return void; Cap'n Web will estimate stream message sizes for
333
+ * flow control. Send errors should be propagated via `receive()` rejecting.
334
+ */
335
+ send(message: unknown): number | void;
336
+ /**
337
+ * Receives and decodes a message sent by the other end.
338
+ *
339
+ * If and when the transport becomes disconnected, this will reject. The thrown error will be
340
+ * propagated to all outstanding calls and future calls on any stubs associated with the session.
341
+ * If there are no outstanding calls (and none are made in the future), then the error does not
342
+ * propagate anywhere -- this is considered a "clean" shutdown.
343
+ */
344
+ receive(): Promise<unknown>;
345
+ /**
346
+ * Indicates that the RPC system has suffered an error that prevents the session from continuing.
347
+ * The transport should ideally try to send any queued messages if it can, and then close the
348
+ * connection. (It's not strictly necessary to deliver queued messages, but the last message sent
349
+ * before abort() is called is often an "abort" message, which communicates the error to the
350
+ * peer, so if that is dropped, the peer may have less information about what happened.)
351
+ */
352
+ abort?(reason: any): void;
353
+ }
354
+ /** Any supported transport type. */
355
+ type AnyRpcTransport = RpcTransport | RpcTransportWithCustomEncoding;
220
356
  /**
221
357
  * Options to customize behavior of an RPC session. All functions which start a session should
222
358
  * optionally accept this.
@@ -234,6 +370,16 @@ type RpcSessionOptions = {
234
370
  * to serialize the error with the stack omitted.
235
371
  */
236
372
  onSendError?: (error: Error) => Error | void;
373
+ /**
374
+ * Overrides for the resource limits enforced while deserializing messages from the peer. Any
375
+ * field left unset falls back to `DEFAULT_LIMITS`. These guard against resource-exhaustion
376
+ * attacks from untrusted peers; see `RpcLimits` for the meaning and defaults of each field.
377
+ *
378
+ * Limits are a purely local, receiver-side decision -- the protocol has no negotiation step, so
379
+ * the peer never learns these values. A message that exceeds a limit is rejected, aborting the
380
+ * session.
381
+ */
382
+ limits?: Partial<RpcLimits>;
237
383
  };
238
384
  //#endregion
239
385
  //#region src/websocket.d.ts
@@ -242,6 +388,17 @@ type RpcSessionOptions = {
242
388
  * with the given `localMain`.
243
389
  */
244
390
  declare function newWorkersWebSocketRpcResponse(request: Request, localMain?: any, options?: RpcSessionOptions): Response;
391
+ /**
392
+ * Generic WebSocket transport. Default `T = string` is backward-compatible and satisfies
393
+ * `RpcTransport`. Use `T = ArrayBuffer` as a building block for binary transports.
394
+ */
395
+ declare class WebSocketTransport<T extends string | ArrayBuffer = string> {
396
+ #private;
397
+ constructor(webSocket: WebSocket);
398
+ send(message: T): void;
399
+ receive(): Promise<T>;
400
+ abort(reason: any): void;
401
+ }
245
402
  //#endregion
246
403
  //#region src/batch.d.ts
247
404
  /**
@@ -299,9 +456,21 @@ declare const RpcStub: {
299
456
  * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
300
457
  * if you only intend to use the promise for pipelining and you never await it, then there's no
301
458
  * need to transmit the resolution!
459
+ *
460
+ * You may also construct an `RpcPromise` yourself from a regular `Promise`, using
461
+ * `new RpcPromise(promise)`, allowing you to perform promise pipelining on a local promise. This
462
+ * is semantically identical to creating a local-loopback RPC that returns the promise, and then
463
+ * invoking it: pipelined calls wait until the promise resolves, then are delivered, in order, to
464
+ * the resolution. This is useful when you plan to obtain some stub in the future, but want to
465
+ * allow code to start queuing calls on it immediately. Note that the `RpcPromise` takes
466
+ * ownership of the resolution: disposing it disposes the resolution, so resolve the promise
467
+ * with a `dup()` if you also intend to keep the stub.
302
468
  */
303
- type RpcPromise<T extends RpcCompatible<T>> = Stub<T> & Promise<Stubify<T>>;
304
- declare const RpcPromise: {};
469
+ type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$2<T>;
470
+ declare const RpcPromise: {
471
+ new <T extends RpcCompatible<T>>(value: Promise<T>): RpcPromise$2<ElideStub<T>>;
472
+ new <T extends RpcCompatible<T>>(value: Promise<PayloadOrStub<T>>): RpcPromise$2<ElideStub<T>>;
473
+ };
305
474
  /**
306
475
  * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
307
476
  *
@@ -316,7 +485,7 @@ interface RpcSession<T extends RpcCompatible<T> = undefined> {
316
485
  drain(): Promise<void>;
317
486
  }
318
487
  declare const RpcSession: {
319
- new <T extends RpcCompatible<T> = undefined>(transport: RpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
488
+ new <T extends RpcCompatible<T> = undefined>(transport: AnyRpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
320
489
  };
321
490
  /**
322
491
  * Classes which are intended to be passed by reference and called over RPC must extend
@@ -369,7 +538,7 @@ declare let newMessagePortRpcSession: <T extends RpcCompatible<T> = Empty$1>(por
369
538
  * credentials as parameters and returns the authorized API), then cross-origin requests should
370
539
  * be safe.
371
540
  */
372
- declare function newWorkersRpcResponse(request: Request, localMain: any): Promise<Response>;
541
+ declare function newWorkersRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
373
542
  //#endregion
374
543
  //#region src/bun.d.ts
375
544
  type WsData = {
@@ -420,5 +589,5 @@ declare let newBunWebSocketRpcSession: <T extends RpcCompatible<T> = Empty, D =
420
589
  transport: BunWebSocketTransport<D>;
421
590
  };
422
591
  //#endregion
423
- export { BunWebSocketTransport, type RpcCompatible, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, deserialize, newBunWebSocketRpcHandler, newBunWebSocketRpcSession, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
592
+ export { type AnyRpcTransport, BunWebSocketTransport, DEFAULT_LIMITS, DEFAULT_MAX_DEPTH, type EncodingLevel, type RpcCompatible, type RpcLimits, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, type RpcTransportWithCustomEncoding, WebSocketTransport, deserialize, newBunWebSocketRpcHandler, newBunWebSocketRpcSession, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
424
593
  //# sourceMappingURL=index-bun.d.cts.map