capnweb 0.0.0-79bc296 → 0.0.0-7a6e5da

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.
@@ -20,7 +20,8 @@ interface RpcTargetBranded {
20
20
  // `never[]` preserves compatibility with strongly-typed function signatures without introducing
21
21
  // `any` into inference.
22
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
23
+ // Note: also true for `any` (call sites that care check `IsAny` first).
24
+ type IsUnknown<T> = unknown extends T ? true : false; // Types that can be passed over RPC
24
25
  // The reason for using a generic type here is to build the serializable subset of RPC-compatible
25
26
  // composite types. This allows types defined with the "interface" keyword to pass the
26
27
  // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
@@ -39,10 +40,17 @@ interface StubBase<T = unknown> extends Disposable {
39
40
  }
40
41
  type Stub<T extends RpcCompatible<T>> = T extends object ? Provider<T> & StubBase<T> : StubBase<T>;
41
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
42
- 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
43
- | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
43
+ 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
44
+ | WritableStream<any> // Chunk type can be any RPC-compatible type
45
+ | URL | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
46
+ // Arm ordering matters here:
47
+ // - `Promise` must come before `StubBase`: `RpcPromise<T>` matches both, and must resolve
48
+ // through the Promise arm rather than pass through as-is.
49
+ // - `StubBase` must come before `Stubable`: `Stub<T>` of a callable `T` is itself callable, so
50
+ // it matches `Stubable`. Checking `StubBase` first keeps existing stubs as-is instead of
51
+ // double-wrapping them as `Stub<Stub<T>>`.
44
52
  // prettier-ignore
45
- 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.
53
+ 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.
46
54
  : T extends {
47
55
  [key: string | number]: any;
48
56
  } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
@@ -69,7 +77,31 @@ interface MapValuePlaceholder<T> {
69
77
  }
70
78
  type NonStubMembers<T> = Exclude<T, StubBase<any>>; // Utility type for adding `Disposable`s to `object` types only.
71
79
  // Note `unknown & T` is equivalent to `T`.
72
- type MaybeDisposable<T> = T extends object ? Disposable : unknown; // Type for method return or property on an RPC interface.
80
+ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // The type behind the public `RpcPromise` (re-exported with its `RpcCompatible` constraint from
81
+ // index.ts). Defined here so that `Result`'s arms below resolve to the exact same alias
82
+ // instantiation: when both sides of an assignability check are the same alias applied to the
83
+ // same type arguments, the checker short-circuits on identity instead of recursing through the
84
+ // full structural comparison of these mutually-recursive types.
85
+ type RpcPromise$1<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & StubBase<T> : Promise<Stubify<T> & MaybeDisposable<T>> & Provider<T> & StubBase<T>;
86
+ // The elision `Result` applies to a bare stub type: unwrap `Stub<T>` back to `T` when the
87
+ // payload is `Stubable`. Such stubs await back to a stub either way, so eliding keeps a
88
+ // declared `Promise<RpcStub<T>>` return interchangeable with a `Promise<T>` return.
89
+ // Plain-interface stubs are NOT elided: `RpcPromise<U>` only awaits to `Stub<U>` when
90
+ // `U extends Stubable`, so eliding those would change the awaited type from a stub to a
91
+ // stubified record. The payload check is deliberately non-distributive (`[U] extends [...]`).
92
+ // `Stub<any>` is not elided either: `[any] extends [Stubable]` is true, so without the `IsAny`
93
+ // guard an `any`-payload stub would lose its stub surface.
94
+ // Also used by the `RpcPromise` constructor signature (index.ts), which applies exactly this
95
+ // transformation so constructing from a promised stub matches the method-return type.
96
+ type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
97
+ // What the promise given to `new RpcPromise<T>(...)` may resolve to: the payload itself, or —
98
+ // for stubable payloads — a stub of it. `NoInfer` keeps the stub arm out of inference, so an
99
+ // inferred `T` is always the promise's own resolution type; the arm only matters when `T` is
100
+ // explicitly annotated (`new RpcPromise<Counter>(promiseOfStub)`). Stubs of non-stubable
101
+ // payloads are deliberately rejected: `ElideStub` wouldn't elide those, so accepting one would
102
+ // claim the promise awaits to a stubified record while the runtime resolves to a stub.
103
+ type PayloadOrStub<T> = T | NoInfer<Stub<Extract<T, Stubable>>>;
104
+ // Type for method return or property on an RPC interface.
73
105
  // - Stubable types are replaced by stubs.
74
106
  // - RpcCompatible types are passed by value, with stubable types replaced by stubs
75
107
  // and a top-level `Disposer`.
@@ -77,14 +109,20 @@ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // Type for m
77
109
  // Technically, we use custom thenables here, but they quack like `Promise`s.
78
110
  // Intersecting with `(Maybe)Provider` allows pipelining.
79
111
  // prettier-ignore
80
- 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;
81
- type IsAny<T> = 0 extends (1 & T) ? true : false;
82
- type UnknownResult = Promise<unknown> & Provider<unknown> & StubBase<unknown>; // Type for method or property on an RPC interface.
112
+ type Result<R> = IsAny<R> extends true ? RpcPromise$1<unknown> // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
113
+ // `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
114
+ : R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
115
+ // here: anything matching our `StubBase` was produced by machinery that already enforced
116
+ // the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
117
+ // `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
118
+ // types.
119
+ : R extends StubBase<any> ? RpcPromise$1<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$1<R> : never;
120
+ type IsAny<T> = 0 extends (1 & T) ? true : false; // Type for method or property on an RPC interface.
83
121
  // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
84
122
  // Unwrapping `Stub`s allows calling with `Stubable` arguments.
85
123
  // For properties, rewrite types to be `Result`s.
86
124
  // In each case, unwrap `Promise`s.
87
- 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.
125
+ 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.
88
126
  // This is intersected with methods/properties.
89
127
  type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
90
128
  type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
@@ -102,6 +140,9 @@ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
102
140
  };
103
141
  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.
104
142
  // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
143
+ // `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
144
+ // stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
145
+ // `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
105
146
  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]> } & {
106
147
  map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
107
148
  });
@@ -126,6 +167,13 @@ type Provider<T> = MaybeCallableProvider<T> & (T extends ReadonlyArray<unknown>
126
167
  * ```
127
168
  */
128
169
  type EncodingLevel = "string" | "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
170
+ interface RpcLimits {
171
+ maxBigIntDigits: number;
172
+ maxDepth: number;
173
+ maxMessageSize: number;
174
+ }
175
+ declare const DEFAULT_MAX_DEPTH = 256;
176
+ declare const DEFAULT_LIMITS: RpcLimits;
129
177
  /**
130
178
  * Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
131
179
  * RPC stubs, but it will support basic data types.
@@ -227,6 +275,16 @@ type RpcSessionOptions = {
227
275
  * to serialize the error with the stack omitted.
228
276
  */
229
277
  onSendError?: (error: Error) => Error | void;
278
+ /**
279
+ * Overrides for the resource limits enforced while deserializing messages from the peer. Any
280
+ * field left unset falls back to `DEFAULT_LIMITS`. These guard against resource-exhaustion
281
+ * attacks from untrusted peers; see `RpcLimits` for the meaning and defaults of each field.
282
+ *
283
+ * Limits are a purely local, receiver-side decision -- the protocol has no negotiation step, so
284
+ * the peer never learns these values. A message that exceeds a limit is rejected, aborting the
285
+ * session.
286
+ */
287
+ limits?: Partial<RpcLimits>;
230
288
  };
231
289
  //#endregion
232
290
  //#region src/websocket.d.ts
@@ -303,9 +361,21 @@ declare const RpcStub: {
303
361
  * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
304
362
  * if you only intend to use the promise for pipelining and you never await it, then there's no
305
363
  * need to transmit the resolution!
364
+ *
365
+ * You may also construct an `RpcPromise` yourself from a regular `Promise`, using
366
+ * `new RpcPromise(promise)`, allowing you to perform promise pipelining on a local promise. This
367
+ * is semantically identical to creating a local-loopback RPC that returns the promise, and then
368
+ * invoking it: pipelined calls wait until the promise resolves, then are delivered, in order, to
369
+ * the resolution. This is useful when you plan to obtain some stub in the future, but want to
370
+ * allow code to start queuing calls on it immediately. Note that the `RpcPromise` takes
371
+ * ownership of the resolution: disposing it disposes the resolution, so resolve the promise
372
+ * with a `dup()` if you also intend to keep the stub.
306
373
  */
307
- type RpcPromise<T extends RpcCompatible<T>> = Stub<T> & Promise<Stubify<T>>;
308
- declare const RpcPromise: {};
374
+ type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$1<T>;
375
+ declare const RpcPromise: {
376
+ new <T extends RpcCompatible<T>>(value: Promise<T>): RpcPromise$1<ElideStub<T>>;
377
+ new <T extends RpcCompatible<T>>(value: Promise<PayloadOrStub<T>>): RpcPromise$1<ElideStub<T>>;
378
+ };
309
379
  /**
310
380
  * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
311
381
  *
@@ -373,7 +443,7 @@ declare let newMessagePortRpcSession: <T extends RpcCompatible<T> = Empty>(port:
373
443
  * credentials as parameters and returns the authorized API), then cross-origin requests should
374
444
  * be safe.
375
445
  */
376
- declare function newWorkersRpcResponse(request: Request, localMain: any): Promise<Response>;
446
+ declare function newWorkersRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
377
447
  //#endregion
378
- export { type AnyRpcTransport, type EncodingLevel, type RpcCompatible, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, type RpcTransportWithCustomEncoding, WebSocketTransport, deserialize, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
448
+ 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 };
379
449
  //# sourceMappingURL=index-workers.d.cts.map
@@ -20,7 +20,8 @@ interface RpcTargetBranded {
20
20
  // `never[]` preserves compatibility with strongly-typed function signatures without introducing
21
21
  // `any` into inference.
22
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
23
+ // Note: also true for `any` (call sites that care check `IsAny` first).
24
+ type IsUnknown<T> = unknown extends T ? true : false; // Types that can be passed over RPC
24
25
  // The reason for using a generic type here is to build the serializable subset of RPC-compatible
25
26
  // composite types. This allows types defined with the "interface" keyword to pass the
26
27
  // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
@@ -39,10 +40,17 @@ interface StubBase<T = unknown> extends Disposable {
39
40
  }
40
41
  type Stub<T extends RpcCompatible<T>> = T extends object ? Provider<T> & StubBase<T> : StubBase<T>;
41
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
42
- 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
43
- | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
43
+ 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
44
+ | WritableStream<any> // Chunk type can be any RPC-compatible type
45
+ | URL | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
46
+ // Arm ordering matters here:
47
+ // - `Promise` must come before `StubBase`: `RpcPromise<T>` matches both, and must resolve
48
+ // through the Promise arm rather than pass through as-is.
49
+ // - `StubBase` must come before `Stubable`: `Stub<T>` of a callable `T` is itself callable, so
50
+ // it matches `Stubable`. Checking `StubBase` first keeps existing stubs as-is instead of
51
+ // double-wrapping them as `Stub<Stub<T>>`.
44
52
  // prettier-ignore
45
- 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.
53
+ 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.
46
54
  : T extends {
47
55
  [key: string | number]: any;
48
56
  } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
@@ -69,7 +77,31 @@ interface MapValuePlaceholder<T> {
69
77
  }
70
78
  type NonStubMembers<T> = Exclude<T, StubBase<any>>; // Utility type for adding `Disposable`s to `object` types only.
71
79
  // Note `unknown & T` is equivalent to `T`.
72
- type MaybeDisposable<T> = T extends object ? Disposable : unknown; // Type for method return or property on an RPC interface.
80
+ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // The type behind the public `RpcPromise` (re-exported with its `RpcCompatible` constraint from
81
+ // index.ts). Defined here so that `Result`'s arms below resolve to the exact same alias
82
+ // instantiation: when both sides of an assignability check are the same alias applied to the
83
+ // same type arguments, the checker short-circuits on identity instead of recursing through the
84
+ // full structural comparison of these mutually-recursive types.
85
+ type RpcPromise$1<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & StubBase<T> : Promise<Stubify<T> & MaybeDisposable<T>> & Provider<T> & StubBase<T>;
86
+ // The elision `Result` applies to a bare stub type: unwrap `Stub<T>` back to `T` when the
87
+ // payload is `Stubable`. Such stubs await back to a stub either way, so eliding keeps a
88
+ // declared `Promise<RpcStub<T>>` return interchangeable with a `Promise<T>` return.
89
+ // Plain-interface stubs are NOT elided: `RpcPromise<U>` only awaits to `Stub<U>` when
90
+ // `U extends Stubable`, so eliding those would change the awaited type from a stub to a
91
+ // stubified record. The payload check is deliberately non-distributive (`[U] extends [...]`).
92
+ // `Stub<any>` is not elided either: `[any] extends [Stubable]` is true, so without the `IsAny`
93
+ // guard an `any`-payload stub would lose its stub surface.
94
+ // Also used by the `RpcPromise` constructor signature (index.ts), which applies exactly this
95
+ // transformation so constructing from a promised stub matches the method-return type.
96
+ type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
97
+ // What the promise given to `new RpcPromise<T>(...)` may resolve to: the payload itself, or —
98
+ // for stubable payloads — a stub of it. `NoInfer` keeps the stub arm out of inference, so an
99
+ // inferred `T` is always the promise's own resolution type; the arm only matters when `T` is
100
+ // explicitly annotated (`new RpcPromise<Counter>(promiseOfStub)`). Stubs of non-stubable
101
+ // payloads are deliberately rejected: `ElideStub` wouldn't elide those, so accepting one would
102
+ // claim the promise awaits to a stubified record while the runtime resolves to a stub.
103
+ type PayloadOrStub<T> = T | NoInfer<Stub<Extract<T, Stubable>>>;
104
+ // Type for method return or property on an RPC interface.
73
105
  // - Stubable types are replaced by stubs.
74
106
  // - RpcCompatible types are passed by value, with stubable types replaced by stubs
75
107
  // and a top-level `Disposer`.
@@ -77,14 +109,20 @@ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // Type for m
77
109
  // Technically, we use custom thenables here, but they quack like `Promise`s.
78
110
  // Intersecting with `(Maybe)Provider` allows pipelining.
79
111
  // prettier-ignore
80
- 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;
81
- type IsAny<T> = 0 extends (1 & T) ? true : false;
82
- type UnknownResult = Promise<unknown> & Provider<unknown> & StubBase<unknown>; // Type for method or property on an RPC interface.
112
+ type Result<R> = IsAny<R> extends true ? RpcPromise$1<unknown> // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
113
+ // `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
114
+ : R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
115
+ // here: anything matching our `StubBase` was produced by machinery that already enforced
116
+ // the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
117
+ // `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
118
+ // types.
119
+ : R extends StubBase<any> ? RpcPromise$1<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$1<R> : never;
120
+ type IsAny<T> = 0 extends (1 & T) ? true : false; // Type for method or property on an RPC interface.
83
121
  // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
84
122
  // Unwrapping `Stub`s allows calling with `Stubable` arguments.
85
123
  // For properties, rewrite types to be `Result`s.
86
124
  // In each case, unwrap `Promise`s.
87
- 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.
125
+ 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.
88
126
  // This is intersected with methods/properties.
89
127
  type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
90
128
  type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
@@ -102,6 +140,9 @@ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
102
140
  };
103
141
  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.
104
142
  // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
143
+ // `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
144
+ // stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
145
+ // `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
105
146
  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]> } & {
106
147
  map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
107
148
  });
@@ -126,6 +167,13 @@ type Provider<T> = MaybeCallableProvider<T> & (T extends ReadonlyArray<unknown>
126
167
  * ```
127
168
  */
128
169
  type EncodingLevel = "string" | "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
170
+ interface RpcLimits {
171
+ maxBigIntDigits: number;
172
+ maxDepth: number;
173
+ maxMessageSize: number;
174
+ }
175
+ declare const DEFAULT_MAX_DEPTH = 256;
176
+ declare const DEFAULT_LIMITS: RpcLimits;
129
177
  /**
130
178
  * Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
131
179
  * RPC stubs, but it will support basic data types.
@@ -227,6 +275,16 @@ type RpcSessionOptions = {
227
275
  * to serialize the error with the stack omitted.
228
276
  */
229
277
  onSendError?: (error: Error) => Error | void;
278
+ /**
279
+ * Overrides for the resource limits enforced while deserializing messages from the peer. Any
280
+ * field left unset falls back to `DEFAULT_LIMITS`. These guard against resource-exhaustion
281
+ * attacks from untrusted peers; see `RpcLimits` for the meaning and defaults of each field.
282
+ *
283
+ * Limits are a purely local, receiver-side decision -- the protocol has no negotiation step, so
284
+ * the peer never learns these values. A message that exceeds a limit is rejected, aborting the
285
+ * session.
286
+ */
287
+ limits?: Partial<RpcLimits>;
230
288
  };
231
289
  //#endregion
232
290
  //#region src/websocket.d.ts
@@ -303,9 +361,21 @@ declare const RpcStub: {
303
361
  * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
304
362
  * if you only intend to use the promise for pipelining and you never await it, then there's no
305
363
  * need to transmit the resolution!
364
+ *
365
+ * You may also construct an `RpcPromise` yourself from a regular `Promise`, using
366
+ * `new RpcPromise(promise)`, allowing you to perform promise pipelining on a local promise. This
367
+ * is semantically identical to creating a local-loopback RPC that returns the promise, and then
368
+ * invoking it: pipelined calls wait until the promise resolves, then are delivered, in order, to
369
+ * the resolution. This is useful when you plan to obtain some stub in the future, but want to
370
+ * allow code to start queuing calls on it immediately. Note that the `RpcPromise` takes
371
+ * ownership of the resolution: disposing it disposes the resolution, so resolve the promise
372
+ * with a `dup()` if you also intend to keep the stub.
306
373
  */
307
- type RpcPromise<T extends RpcCompatible<T>> = Stub<T> & Promise<Stubify<T>>;
308
- declare const RpcPromise: {};
374
+ type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$1<T>;
375
+ declare const RpcPromise: {
376
+ new <T extends RpcCompatible<T>>(value: Promise<T>): RpcPromise$1<ElideStub<T>>;
377
+ new <T extends RpcCompatible<T>>(value: Promise<PayloadOrStub<T>>): RpcPromise$1<ElideStub<T>>;
378
+ };
309
379
  /**
310
380
  * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
311
381
  *
@@ -373,7 +443,7 @@ declare let newMessagePortRpcSession: <T extends RpcCompatible<T> = Empty>(port:
373
443
  * credentials as parameters and returns the authorized API), then cross-origin requests should
374
444
  * be safe.
375
445
  */
376
- declare function newWorkersRpcResponse(request: Request, localMain: any): Promise<Response>;
446
+ declare function newWorkersRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
377
447
  //#endregion
378
- export { type AnyRpcTransport, type EncodingLevel, type RpcCompatible, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, type RpcTransportWithCustomEncoding, WebSocketTransport, deserialize, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
448
+ 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 };
379
449
  //# sourceMappingURL=index-workers.d.ts.map