capnweb 0.0.0-952a541 → 0.0.0-9751a4e

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.
@@ -21,7 +21,8 @@ interface RpcTargetBranded {
21
21
  // `never[]` preserves compatibility with strongly-typed function signatures without introducing
22
22
  // `any` into inference.
23
23
  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
24
+ // Note: also true for `any` (call sites that care check `IsAny` first).
25
+ type IsUnknown<T> = unknown extends T ? true : false; // 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.
@@ -40,10 +41,17 @@ interface StubBase<T = unknown> extends Disposable {
40
41
  }
41
42
  type Stub<T extends RpcCompatible<T>> = T extends object ? Provider<T> & StubBase<T> : StubBase<T>;
42
43
  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.
44
+ 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
45
+ | WritableStream<any> // Chunk type can be any RPC-compatible type
46
+ | URL | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
47
+ // Arm ordering matters here:
48
+ // - `Promise` must come before `StubBase`: `RpcPromise<T>` matches both, and must resolve
49
+ // through the Promise arm rather than pass through as-is.
50
+ // - `StubBase` must come before `Stubable`: `Stub<T>` of a callable `T` is itself callable, so
51
+ // it matches `Stubable`. Checking `StubBase` first keeps existing stubs as-is instead of
52
+ // double-wrapping them as `Stub<Stub<T>>`.
45
53
  // 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.
54
+ 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 // When using "unknown" instead of "any", interfaces are not stubified.
47
55
  : T extends {
48
56
  [key: string | number]: any;
49
57
  } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
@@ -70,7 +78,22 @@ interface MapValuePlaceholder<T> {
70
78
  }
71
79
  type NonStubMembers<T> = Exclude<T, StubBase<any>>; // Utility type for adding `Disposable`s to `object` types only.
72
80
  // 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.
81
+ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // The type behind the public `RpcPromise` (re-exported with its `RpcCompatible` constraint from
82
+ // index.ts). Defined here so that `Result`'s arms below resolve to the exact same alias
83
+ // instantiation: when both sides of an assignability check are the same alias applied to the
84
+ // same type arguments, the checker short-circuits on identity instead of recursing through the
85
+ // full structural comparison of these mutually-recursive types.
86
+ type RpcPromise$2<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & StubBase<T> : Promise<Stubify<T> & MaybeDisposable<T>> & Provider<T> & StubBase<T>;
87
+ // The elision `Result` applies to a bare stub type: unwrap `Stub<T>` back to `T` when the
88
+ // payload is `Stubable`. Such stubs await back to a stub either way, so eliding keeps a
89
+ // declared `Promise<RpcStub<T>>` return interchangeable with a `Promise<T>` return.
90
+ // Plain-interface stubs are NOT elided: `RpcPromise<U>` only awaits to `Stub<U>` when
91
+ // `U extends Stubable`, so eliding those would change the awaited type from a stub to a
92
+ // stubified record. The payload check is deliberately non-distributive (`[U] extends [...]`).
93
+ // `Stub<any>` is not elided either: `[any] extends [Stubable]` is true, so without the `IsAny`
94
+ // guard an `any`-payload stub would lose its stub surface.
95
+ type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
96
+ // Type for method return or property on an RPC interface.
74
97
  // - Stubable types are replaced by stubs.
75
98
  // - RpcCompatible types are passed by value, with stubable types replaced by stubs
76
99
  // and a top-level `Disposer`.
@@ -78,14 +101,20 @@ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // Type for m
78
101
  // Technically, we use custom thenables here, but they quack like `Promise`s.
79
102
  // Intersecting with `(Maybe)Provider` allows pipelining.
80
103
  // 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;
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.
104
+ type Result<R> = IsAny<R> extends true ? RpcPromise$2<unknown> // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
105
+ // `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
106
+ : R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
107
+ // here: anything matching our `StubBase` was produced by machinery that already enforced
108
+ // the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
109
+ // `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
110
+ // types.
111
+ : R extends StubBase<any> ? RpcPromise$2<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$2<R> : never;
112
+ type IsAny<T> = 0 extends (1 & T) ? true : false; // Type for method or property on an RPC interface.
84
113
  // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
85
114
  // Unwrapping `Stub`s allows calling with `Stubable` arguments.
86
115
  // For properties, rewrite types to be `Result`s.
87
116
  // 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.
117
+ type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>; // Type for the callable part of an `Provider` if `T` is callable.
89
118
  // This is intersected with methods/properties.
90
119
  type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
91
120
  type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
@@ -103,6 +132,9 @@ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
103
132
  };
104
133
  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.
105
134
  // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
135
+ // `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
136
+ // stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
137
+ // `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
106
138
  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
139
  map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
108
140
  });
@@ -140,7 +172,7 @@ declare class RpcStub$1 extends RpcTarget$1 {
140
172
  toString(): string;
141
173
  }
142
174
  declare class RpcPromise$1 extends RpcStub$1 {
143
- constructor(hook: StubHook, pathIfPromise: PropertyPath);
175
+ constructor(hook: StubHook | PromiseLike<unknown>, pathIfPromise?: PropertyPath);
144
176
  then(onfulfilled?: ((value: unknown) => unknown) | undefined | null, onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
145
177
  catch(onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
146
178
  finally(onfinally?: (() => void) | undefined | null): Promise<unknown>;
@@ -171,6 +203,9 @@ declare class RpcPayload {
171
203
  private deliverTo;
172
204
  private static deliverRpcPromiseTo;
173
205
  deliverCall(func: Function, thisArg: object | undefined): Promise<RpcPayload>;
206
+ deliverStreamWrite(writer: {
207
+ write(chunk: unknown): Promise<void>;
208
+ }): Promise<RpcPayload>;
174
209
  deliverResolve(): Promise<unknown>;
175
210
  dispose(): void;
176
211
  private disposeImpl;
@@ -179,6 +214,32 @@ declare class RpcPayload {
179
214
  }
180
215
  //#endregion
181
216
  //#region src/serialize.d.ts
217
+ /**
218
+ * Encoding levels determine what representation the RPC system hands to the transport.
219
+ * Each level names what the transport can assume about message values.
220
+ *
221
+ * - `"string"`: JSON string. Default, used by HTTP batch and WebSocket transports.
222
+ * - `"jsonCompatible"`: JSON-compatible JS value tree. For custom encoders.
223
+ * - `"jsonCompatibleWithBytes"`: Like `"jsonCompatible"` but Uint8Array stays raw.
224
+ * - `"structuredClonable"`: Structured-clonable native values pass through where possible.
225
+ *
226
+ * @example
227
+ * ```ts
228
+ * // What happens to Uint8Array([1, 2, 3]) at each level:
229
+ * "string" → '["bytes","AQID"]' // JSON string with base64
230
+ * "jsonCompatible" → ["bytes", "AQID"] // JS array with base64
231
+ * "jsonCompatibleWithBytes" → ["bytes", Uint8Array] // JS array with raw bytes
232
+ * "structuredClonable" → ["bytes", Uint8Array] // + Date, BigInt stay native
233
+ * ```
234
+ */
235
+ type EncodingLevel = "string" | "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
236
+ interface RpcLimits {
237
+ maxBigIntDigits: number;
238
+ maxDepth: number;
239
+ maxMessageSize: number;
240
+ }
241
+ declare const DEFAULT_MAX_DEPTH = 256;
242
+ declare const DEFAULT_LIMITS: RpcLimits;
182
243
  /**
183
244
  * Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
184
245
  * RPC stubs, but it will support basic data types.
@@ -191,14 +252,21 @@ declare function deserialize(value: string): unknown;
191
252
  //#endregion
192
253
  //#region src/rpc.d.ts
193
254
  /**
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.
255
+ * Interface for a string-based RPC transport. This is the default transport type — no
256
+ * `encodingLevel` field is needed. Messages are JSON strings. Implement this interface if the
257
+ * built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
196
258
  */
197
259
  interface RpcTransport {
198
260
  /**
199
- * Sends a message to the other end.
261
+ * The encoding level this transport works with. For this interface it is always "string";
262
+ * it may be omitted. (See `RpcTransportWithCustomEncoding` for the other levels.)
200
263
  */
201
- send(message: string): Promise<void>;
264
+ readonly encodingLevel?: "string";
265
+ /**
266
+ * Sends a message to the other end. May optionally return a promise; if the promise rejects,
267
+ * the session is aborted.
268
+ */
269
+ send(message: string): void | Promise<void>;
202
270
  /**
203
271
  * Receives a message sent by the other end.
204
272
  *
@@ -217,6 +285,45 @@ interface RpcTransport {
217
285
  */
218
286
  abort?(reason: any): void;
219
287
  }
288
+ /**
289
+ * Interface for a transport that receives partially encoded JS values instead of JSON strings.
290
+ * The selected `encodingLevel` describes what the transport can assume about message values.
291
+ */
292
+ interface RpcTransportWithCustomEncoding {
293
+ /**
294
+ * The encoding level this transport works with.
295
+ *
296
+ * - "jsonCompatible": JSON-compatible JS value tree; transport handles final serialization.
297
+ * - "jsonCompatibleWithBytes": Like "jsonCompatible" but Uint8Array values are left raw.
298
+ * - "structuredClonable": Structured-clonable native values pass through where possible.
299
+ */
300
+ readonly encodingLevel: "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
301
+ /**
302
+ * Encodes and sends a message to the other end. Returns the encoded byte size if known.
303
+ * If the size is unavailable, return void; Cap'n Web will estimate stream message sizes for
304
+ * flow control. Send errors should be propagated via `receive()` rejecting.
305
+ */
306
+ send(message: unknown): number | void;
307
+ /**
308
+ * Receives and decodes a message sent by the other end.
309
+ *
310
+ * If and when the transport becomes disconnected, this will reject. The thrown error will be
311
+ * propagated to all outstanding calls and future calls on any stubs associated with the session.
312
+ * If there are no outstanding calls (and none are made in the future), then the error does not
313
+ * propagate anywhere -- this is considered a "clean" shutdown.
314
+ */
315
+ receive(): Promise<unknown>;
316
+ /**
317
+ * Indicates that the RPC system has suffered an error that prevents the session from continuing.
318
+ * The transport should ideally try to send any queued messages if it can, and then close the
319
+ * connection. (It's not strictly necessary to deliver queued messages, but the last message sent
320
+ * before abort() is called is often an "abort" message, which communicates the error to the
321
+ * peer, so if that is dropped, the peer may have less information about what happened.)
322
+ */
323
+ abort?(reason: any): void;
324
+ }
325
+ /** Any supported transport type. */
326
+ type AnyRpcTransport = RpcTransport | RpcTransportWithCustomEncoding;
220
327
  /**
221
328
  * Options to customize behavior of an RPC session. All functions which start a session should
222
329
  * optionally accept this.
@@ -234,6 +341,16 @@ type RpcSessionOptions = {
234
341
  * to serialize the error with the stack omitted.
235
342
  */
236
343
  onSendError?: (error: Error) => Error | void;
344
+ /**
345
+ * Overrides for the resource limits enforced while deserializing messages from the peer. Any
346
+ * field left unset falls back to `DEFAULT_LIMITS`. These guard against resource-exhaustion
347
+ * attacks from untrusted peers; see `RpcLimits` for the meaning and defaults of each field.
348
+ *
349
+ * Limits are a purely local, receiver-side decision -- the protocol has no negotiation step, so
350
+ * the peer never learns these values. A message that exceeds a limit is rejected, aborting the
351
+ * session.
352
+ */
353
+ limits?: Partial<RpcLimits>;
237
354
  };
238
355
  //#endregion
239
356
  //#region src/websocket.d.ts
@@ -242,6 +359,17 @@ type RpcSessionOptions = {
242
359
  * with the given `localMain`.
243
360
  */
244
361
  declare function newWorkersWebSocketRpcResponse(request: Request, localMain?: any, options?: RpcSessionOptions): Response;
362
+ /**
363
+ * Generic WebSocket transport. Default `T = string` is backward-compatible and satisfies
364
+ * `RpcTransport`. Use `T = ArrayBuffer` as a building block for binary transports.
365
+ */
366
+ declare class WebSocketTransport<T extends string | ArrayBuffer = string> {
367
+ #private;
368
+ constructor(webSocket: WebSocket);
369
+ send(message: T): void;
370
+ receive(): Promise<T>;
371
+ abort(reason: any): void;
372
+ }
245
373
  //#endregion
246
374
  //#region src/batch.d.ts
247
375
  /**
@@ -299,9 +427,20 @@ declare const RpcStub: {
299
427
  * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
300
428
  * if you only intend to use the promise for pipelining and you never await it, then there's no
301
429
  * need to transmit the resolution!
430
+ *
431
+ * You may also construct an `RpcPromise` yourself from a regular `Promise`, using
432
+ * `new RpcPromise(promise)`, allowing you to perform promise pipelining on a local promise. This
433
+ * is semantically identical to creating a local-loopback RPC that returns the promise, and then
434
+ * invoking it: pipelined calls wait until the promise resolves, then are delivered, in order, to
435
+ * the resolution. This is useful when you plan to obtain some stub in the future, but want to
436
+ * allow code to start queuing calls on it immediately. Note that the `RpcPromise` takes
437
+ * ownership of the resolution: disposing it disposes the resolution, so resolve the promise
438
+ * with a `dup()` if you also intend to keep the stub.
302
439
  */
303
- type RpcPromise<T extends RpcCompatible<T>> = Stub<T> & Promise<Stubify<T>>;
304
- declare const RpcPromise: {};
440
+ type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$2<T>;
441
+ declare const RpcPromise: {
442
+ new <T extends RpcCompatible<T>>(value: Promise<T | Stub<T>>): RpcPromise<T>;
443
+ };
305
444
  /**
306
445
  * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
307
446
  *
@@ -316,7 +455,7 @@ interface RpcSession<T extends RpcCompatible<T> = undefined> {
316
455
  drain(): Promise<void>;
317
456
  }
318
457
  declare const RpcSession: {
319
- new <T extends RpcCompatible<T> = undefined>(transport: RpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
458
+ new <T extends RpcCompatible<T> = undefined>(transport: AnyRpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
320
459
  };
321
460
  /**
322
461
  * Classes which are intended to be passed by reference and called over RPC must extend
@@ -369,7 +508,7 @@ declare let newMessagePortRpcSession: <T extends RpcCompatible<T> = Empty$1>(por
369
508
  * credentials as parameters and returns the authorized API), then cross-origin requests should
370
509
  * be safe.
371
510
  */
372
- declare function newWorkersRpcResponse(request: Request, localMain: any): Promise<Response>;
511
+ declare function newWorkersRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
373
512
  //#endregion
374
513
  //#region src/bun.d.ts
375
514
  type WsData = {
@@ -420,5 +559,5 @@ declare let newBunWebSocketRpcSession: <T extends RpcCompatible<T> = Empty, D =
420
559
  transport: BunWebSocketTransport<D>;
421
560
  };
422
561
  //#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 };
562
+ 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
563
  //# sourceMappingURL=index-bun.d.cts.map
@@ -21,7 +21,8 @@ interface RpcTargetBranded {
21
21
  // `never[]` preserves compatibility with strongly-typed function signatures without introducing
22
22
  // `any` into inference.
23
23
  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
24
+ // Note: also true for `any` (call sites that care check `IsAny` first).
25
+ type IsUnknown<T> = unknown extends T ? true : false; // 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.
@@ -40,10 +41,17 @@ interface StubBase<T = unknown> extends Disposable {
40
41
  }
41
42
  type Stub<T extends RpcCompatible<T>> = T extends object ? Provider<T> & StubBase<T> : StubBase<T>;
42
43
  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.
44
+ 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
45
+ | WritableStream<any> // Chunk type can be any RPC-compatible type
46
+ | URL | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
47
+ // Arm ordering matters here:
48
+ // - `Promise` must come before `StubBase`: `RpcPromise<T>` matches both, and must resolve
49
+ // through the Promise arm rather than pass through as-is.
50
+ // - `StubBase` must come before `Stubable`: `Stub<T>` of a callable `T` is itself callable, so
51
+ // it matches `Stubable`. Checking `StubBase` first keeps existing stubs as-is instead of
52
+ // double-wrapping them as `Stub<Stub<T>>`.
45
53
  // 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.
54
+ 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 // When using "unknown" instead of "any", interfaces are not stubified.
47
55
  : T extends {
48
56
  [key: string | number]: any;
49
57
  } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
@@ -70,7 +78,22 @@ interface MapValuePlaceholder<T> {
70
78
  }
71
79
  type NonStubMembers<T> = Exclude<T, StubBase<any>>; // Utility type for adding `Disposable`s to `object` types only.
72
80
  // 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.
81
+ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // The type behind the public `RpcPromise` (re-exported with its `RpcCompatible` constraint from
82
+ // index.ts). Defined here so that `Result`'s arms below resolve to the exact same alias
83
+ // instantiation: when both sides of an assignability check are the same alias applied to the
84
+ // same type arguments, the checker short-circuits on identity instead of recursing through the
85
+ // full structural comparison of these mutually-recursive types.
86
+ type RpcPromise$2<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & StubBase<T> : Promise<Stubify<T> & MaybeDisposable<T>> & Provider<T> & StubBase<T>;
87
+ // The elision `Result` applies to a bare stub type: unwrap `Stub<T>` back to `T` when the
88
+ // payload is `Stubable`. Such stubs await back to a stub either way, so eliding keeps a
89
+ // declared `Promise<RpcStub<T>>` return interchangeable with a `Promise<T>` return.
90
+ // Plain-interface stubs are NOT elided: `RpcPromise<U>` only awaits to `Stub<U>` when
91
+ // `U extends Stubable`, so eliding those would change the awaited type from a stub to a
92
+ // stubified record. The payload check is deliberately non-distributive (`[U] extends [...]`).
93
+ // `Stub<any>` is not elided either: `[any] extends [Stubable]` is true, so without the `IsAny`
94
+ // guard an `any`-payload stub would lose its stub surface.
95
+ type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
96
+ // Type for method return or property on an RPC interface.
74
97
  // - Stubable types are replaced by stubs.
75
98
  // - RpcCompatible types are passed by value, with stubable types replaced by stubs
76
99
  // and a top-level `Disposer`.
@@ -78,14 +101,20 @@ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // Type for m
78
101
  // Technically, we use custom thenables here, but they quack like `Promise`s.
79
102
  // Intersecting with `(Maybe)Provider` allows pipelining.
80
103
  // 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;
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.
104
+ type Result<R> = IsAny<R> extends true ? RpcPromise$2<unknown> // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
105
+ // `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
106
+ : R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
107
+ // here: anything matching our `StubBase` was produced by machinery that already enforced
108
+ // the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
109
+ // `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
110
+ // types.
111
+ : R extends StubBase<any> ? RpcPromise$2<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$2<R> : never;
112
+ type IsAny<T> = 0 extends (1 & T) ? true : false; // Type for method or property on an RPC interface.
84
113
  // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
85
114
  // Unwrapping `Stub`s allows calling with `Stubable` arguments.
86
115
  // For properties, rewrite types to be `Result`s.
87
116
  // 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.
117
+ type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>; // Type for the callable part of an `Provider` if `T` is callable.
89
118
  // This is intersected with methods/properties.
90
119
  type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
91
120
  type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
@@ -103,6 +132,9 @@ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
103
132
  };
104
133
  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.
105
134
  // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
135
+ // `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
136
+ // stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
137
+ // `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
106
138
  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
139
  map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
108
140
  });
@@ -140,7 +172,7 @@ declare class RpcStub$1 extends RpcTarget$1 {
140
172
  toString(): string;
141
173
  }
142
174
  declare class RpcPromise$1 extends RpcStub$1 {
143
- constructor(hook: StubHook, pathIfPromise: PropertyPath);
175
+ constructor(hook: StubHook | PromiseLike<unknown>, pathIfPromise?: PropertyPath);
144
176
  then(onfulfilled?: ((value: unknown) => unknown) | undefined | null, onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
145
177
  catch(onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
146
178
  finally(onfinally?: (() => void) | undefined | null): Promise<unknown>;
@@ -171,6 +203,9 @@ declare class RpcPayload {
171
203
  private deliverTo;
172
204
  private static deliverRpcPromiseTo;
173
205
  deliverCall(func: Function, thisArg: object | undefined): Promise<RpcPayload>;
206
+ deliverStreamWrite(writer: {
207
+ write(chunk: unknown): Promise<void>;
208
+ }): Promise<RpcPayload>;
174
209
  deliverResolve(): Promise<unknown>;
175
210
  dispose(): void;
176
211
  private disposeImpl;
@@ -179,6 +214,32 @@ declare class RpcPayload {
179
214
  }
180
215
  //#endregion
181
216
  //#region src/serialize.d.ts
217
+ /**
218
+ * Encoding levels determine what representation the RPC system hands to the transport.
219
+ * Each level names what the transport can assume about message values.
220
+ *
221
+ * - `"string"`: JSON string. Default, used by HTTP batch and WebSocket transports.
222
+ * - `"jsonCompatible"`: JSON-compatible JS value tree. For custom encoders.
223
+ * - `"jsonCompatibleWithBytes"`: Like `"jsonCompatible"` but Uint8Array stays raw.
224
+ * - `"structuredClonable"`: Structured-clonable native values pass through where possible.
225
+ *
226
+ * @example
227
+ * ```ts
228
+ * // What happens to Uint8Array([1, 2, 3]) at each level:
229
+ * "string" → '["bytes","AQID"]' // JSON string with base64
230
+ * "jsonCompatible" → ["bytes", "AQID"] // JS array with base64
231
+ * "jsonCompatibleWithBytes" → ["bytes", Uint8Array] // JS array with raw bytes
232
+ * "structuredClonable" → ["bytes", Uint8Array] // + Date, BigInt stay native
233
+ * ```
234
+ */
235
+ type EncodingLevel = "string" | "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
236
+ interface RpcLimits {
237
+ maxBigIntDigits: number;
238
+ maxDepth: number;
239
+ maxMessageSize: number;
240
+ }
241
+ declare const DEFAULT_MAX_DEPTH = 256;
242
+ declare const DEFAULT_LIMITS: RpcLimits;
182
243
  /**
183
244
  * Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
184
245
  * RPC stubs, but it will support basic data types.
@@ -191,14 +252,21 @@ declare function deserialize(value: string): unknown;
191
252
  //#endregion
192
253
  //#region src/rpc.d.ts
193
254
  /**
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.
255
+ * Interface for a string-based RPC transport. This is the default transport type — no
256
+ * `encodingLevel` field is needed. Messages are JSON strings. Implement this interface if the
257
+ * built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
196
258
  */
197
259
  interface RpcTransport {
198
260
  /**
199
- * Sends a message to the other end.
261
+ * The encoding level this transport works with. For this interface it is always "string";
262
+ * it may be omitted. (See `RpcTransportWithCustomEncoding` for the other levels.)
200
263
  */
201
- send(message: string): Promise<void>;
264
+ readonly encodingLevel?: "string";
265
+ /**
266
+ * Sends a message to the other end. May optionally return a promise; if the promise rejects,
267
+ * the session is aborted.
268
+ */
269
+ send(message: string): void | Promise<void>;
202
270
  /**
203
271
  * Receives a message sent by the other end.
204
272
  *
@@ -217,6 +285,45 @@ interface RpcTransport {
217
285
  */
218
286
  abort?(reason: any): void;
219
287
  }
288
+ /**
289
+ * Interface for a transport that receives partially encoded JS values instead of JSON strings.
290
+ * The selected `encodingLevel` describes what the transport can assume about message values.
291
+ */
292
+ interface RpcTransportWithCustomEncoding {
293
+ /**
294
+ * The encoding level this transport works with.
295
+ *
296
+ * - "jsonCompatible": JSON-compatible JS value tree; transport handles final serialization.
297
+ * - "jsonCompatibleWithBytes": Like "jsonCompatible" but Uint8Array values are left raw.
298
+ * - "structuredClonable": Structured-clonable native values pass through where possible.
299
+ */
300
+ readonly encodingLevel: "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
301
+ /**
302
+ * Encodes and sends a message to the other end. Returns the encoded byte size if known.
303
+ * If the size is unavailable, return void; Cap'n Web will estimate stream message sizes for
304
+ * flow control. Send errors should be propagated via `receive()` rejecting.
305
+ */
306
+ send(message: unknown): number | void;
307
+ /**
308
+ * Receives and decodes a message sent by the other end.
309
+ *
310
+ * If and when the transport becomes disconnected, this will reject. The thrown error will be
311
+ * propagated to all outstanding calls and future calls on any stubs associated with the session.
312
+ * If there are no outstanding calls (and none are made in the future), then the error does not
313
+ * propagate anywhere -- this is considered a "clean" shutdown.
314
+ */
315
+ receive(): Promise<unknown>;
316
+ /**
317
+ * Indicates that the RPC system has suffered an error that prevents the session from continuing.
318
+ * The transport should ideally try to send any queued messages if it can, and then close the
319
+ * connection. (It's not strictly necessary to deliver queued messages, but the last message sent
320
+ * before abort() is called is often an "abort" message, which communicates the error to the
321
+ * peer, so if that is dropped, the peer may have less information about what happened.)
322
+ */
323
+ abort?(reason: any): void;
324
+ }
325
+ /** Any supported transport type. */
326
+ type AnyRpcTransport = RpcTransport | RpcTransportWithCustomEncoding;
220
327
  /**
221
328
  * Options to customize behavior of an RPC session. All functions which start a session should
222
329
  * optionally accept this.
@@ -234,6 +341,16 @@ type RpcSessionOptions = {
234
341
  * to serialize the error with the stack omitted.
235
342
  */
236
343
  onSendError?: (error: Error) => Error | void;
344
+ /**
345
+ * Overrides for the resource limits enforced while deserializing messages from the peer. Any
346
+ * field left unset falls back to `DEFAULT_LIMITS`. These guard against resource-exhaustion
347
+ * attacks from untrusted peers; see `RpcLimits` for the meaning and defaults of each field.
348
+ *
349
+ * Limits are a purely local, receiver-side decision -- the protocol has no negotiation step, so
350
+ * the peer never learns these values. A message that exceeds a limit is rejected, aborting the
351
+ * session.
352
+ */
353
+ limits?: Partial<RpcLimits>;
237
354
  };
238
355
  //#endregion
239
356
  //#region src/websocket.d.ts
@@ -242,6 +359,17 @@ type RpcSessionOptions = {
242
359
  * with the given `localMain`.
243
360
  */
244
361
  declare function newWorkersWebSocketRpcResponse(request: Request, localMain?: any, options?: RpcSessionOptions): Response;
362
+ /**
363
+ * Generic WebSocket transport. Default `T = string` is backward-compatible and satisfies
364
+ * `RpcTransport`. Use `T = ArrayBuffer` as a building block for binary transports.
365
+ */
366
+ declare class WebSocketTransport<T extends string | ArrayBuffer = string> {
367
+ #private;
368
+ constructor(webSocket: WebSocket);
369
+ send(message: T): void;
370
+ receive(): Promise<T>;
371
+ abort(reason: any): void;
372
+ }
245
373
  //#endregion
246
374
  //#region src/batch.d.ts
247
375
  /**
@@ -299,9 +427,20 @@ declare const RpcStub: {
299
427
  * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
300
428
  * if you only intend to use the promise for pipelining and you never await it, then there's no
301
429
  * need to transmit the resolution!
430
+ *
431
+ * You may also construct an `RpcPromise` yourself from a regular `Promise`, using
432
+ * `new RpcPromise(promise)`, allowing you to perform promise pipelining on a local promise. This
433
+ * is semantically identical to creating a local-loopback RPC that returns the promise, and then
434
+ * invoking it: pipelined calls wait until the promise resolves, then are delivered, in order, to
435
+ * the resolution. This is useful when you plan to obtain some stub in the future, but want to
436
+ * allow code to start queuing calls on it immediately. Note that the `RpcPromise` takes
437
+ * ownership of the resolution: disposing it disposes the resolution, so resolve the promise
438
+ * with a `dup()` if you also intend to keep the stub.
302
439
  */
303
- type RpcPromise<T extends RpcCompatible<T>> = Stub<T> & Promise<Stubify<T>>;
304
- declare const RpcPromise: {};
440
+ type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$2<T>;
441
+ declare const RpcPromise: {
442
+ new <T extends RpcCompatible<T>>(value: Promise<T | Stub<T>>): RpcPromise<T>;
443
+ };
305
444
  /**
306
445
  * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
307
446
  *
@@ -316,7 +455,7 @@ interface RpcSession<T extends RpcCompatible<T> = undefined> {
316
455
  drain(): Promise<void>;
317
456
  }
318
457
  declare const RpcSession: {
319
- new <T extends RpcCompatible<T> = undefined>(transport: RpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
458
+ new <T extends RpcCompatible<T> = undefined>(transport: AnyRpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
320
459
  };
321
460
  /**
322
461
  * Classes which are intended to be passed by reference and called over RPC must extend
@@ -369,7 +508,7 @@ declare let newMessagePortRpcSession: <T extends RpcCompatible<T> = Empty$1>(por
369
508
  * credentials as parameters and returns the authorized API), then cross-origin requests should
370
509
  * be safe.
371
510
  */
372
- declare function newWorkersRpcResponse(request: Request, localMain: any): Promise<Response>;
511
+ declare function newWorkersRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
373
512
  //#endregion
374
513
  //#region src/bun.d.ts
375
514
  type WsData = {
@@ -420,5 +559,5 @@ declare let newBunWebSocketRpcSession: <T extends RpcCompatible<T> = Empty, D =
420
559
  transport: BunWebSocketTransport<D>;
421
560
  };
422
561
  //#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 };
562
+ 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
563
  //# sourceMappingURL=index-bun.d.ts.map