capnweb 0.0.0-db952ec → 0.0.0-e3a41a3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,573 @@
1
+ import { IncomingMessage, OutgoingHttpHeader, OutgoingHttpHeaders, ServerResponse } from "node:http";
2
+ import { ServerWebSocket } from "bun";
3
+
4
+ //#region src/types.d.ts
5
+ // Copyright (c) 2025 Cloudflare, Inc.
6
+ // Licensed under the MIT license found in the LICENSE.txt file or at:
7
+ // https://opensource.org/license/mit
8
+ // This file borrows heavily from `types/defines/rpc.d.ts` in workerd.
9
+ // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s.
10
+ // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`.
11
+ // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to
12
+ // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape)
13
+ declare const __RPC_STUB_BRAND: '__RPC_STUB_BRAND';
14
+ declare const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND';
15
+ // Distinguishes mapper placeholders from regular values so param unwrapping can accept them.
16
+ declare const __RPC_MAP_VALUE_BRAND: unique symbol;
17
+ interface RpcTargetBranded {
18
+ [__RPC_TARGET_BRAND]: never;
19
+ }
20
+ // Types that can be used through `Stub`s
21
+ // `never[]` preserves compatibility with strongly-typed function signatures without introducing
22
+ // `any` into inference.
23
+ type Stubable = RpcTargetBranded | ((...args: never[]) => unknown);
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
26
+ // The reason for using a generic type here is to build the serializable subset of RPC-compatible
27
+ // composite types. This allows types defined with the "interface" keyword to pass the
28
+ // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
29
+ type RpcCompatible<T> = // Allow `unknown` as a leaf so records/interfaces with `unknown` fields remain compatible.
30
+ (IsUnknown<T> extends true ? unknown : never) // RPC-compatible base values
31
+ | BaseType // RPC-compatible composites
32
+ | 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
33
+ | Stub<Stubable> // Serialized as stubs, see `Stubify`
34
+ | Stubable;
35
+ // Base type for all RPC stubs, including common memory management methods.
36
+ // `T` is used as a marker type for unwrapping `Stub`s later.
37
+ interface StubBase<T = unknown> extends Disposable {
38
+ [__RPC_STUB_BRAND]: T;
39
+ dup(): this;
40
+ onRpcBroken(callback: (error: any) => void): void;
41
+ }
42
+ type Stub<T extends RpcCompatible<T>> = T extends object ? Provider<T> & StubBase<T> : StubBase<T>;
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
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>>`.
53
+ // prettier-ignore
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.
55
+ : T extends {
56
+ [key: string | number]: any;
57
+ } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
58
+ // Recursively rewrite all `Stub<T>`s with the corresponding `T`s.
59
+ // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:
60
+ // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.
61
+ // prettier-ignore
62
+ type UnstubifyInner<T> = // Preserve local RpcTarget acceptance, but avoid needless `Stub | Value` unions when the stub
63
+ // is already assignable to the value type (important for callback contextual typing).
64
+ 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 {
65
+ [key: string | number]: unknown;
66
+ } ? { [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.
67
+ // (This also covers RpcPromise, because it's defined as being a Promise.)
68
+ // Map placeholders are also allowed so primitive map callback inputs can be forwarded directly
69
+ // into RPC params.
70
+ //
71
+ // Keep raw non-stub members so generic assignability still works when UnstubifyInner<T> is deferred.
72
+ // Remove stub members from mixed unions so callback params don’t get both stub and unstubbed signatures.
73
+ // Marker carried by map() callback inputs. This lets primitive placeholders flow through params.
74
+ type Unstubify<T> = NonStubMembers<T> | UnstubifyInner<T> | Promise<UnstubifyInner<T>> | MapValuePlaceholder<UnstubifyInner<T>>;
75
+ type UnstubifyAll<A extends readonly unknown[]> = { [I in keyof A]: Unstubify<A[I]> };
76
+ interface MapValuePlaceholder<T> {
77
+ [__RPC_MAP_VALUE_BRAND]: T;
78
+ }
79
+ type NonStubMembers<T> = Exclude<T, StubBase<any>>; // Utility type for adding `Disposable`s to `object` types only.
80
+ // Note `unknown & T` is equivalent to `T`.
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
+ // Also used by the `RpcPromise` constructor signature (index.ts), which applies exactly this
96
+ // transformation so constructing from a promised stub matches the method-return type.
97
+ type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
98
+ // What the promise given to `new RpcPromise<T>(...)` may resolve to: the payload itself, or —
99
+ // for stubable payloads — a stub of it. `NoInfer` keeps the stub arm out of inference, so an
100
+ // inferred `T` is always the promise's own resolution type; the arm only matters when `T` is
101
+ // explicitly annotated (`new RpcPromise<Counter>(promiseOfStub)`). Stubs of non-stubable
102
+ // payloads are deliberately rejected: `ElideStub` wouldn't elide those, so accepting one would
103
+ // claim the promise awaits to a stubified record while the runtime resolves to a stub.
104
+ type PayloadOrStub<T> = T | NoInfer<Stub<Extract<T, Stubable>>>;
105
+ // Type for method return or property on an RPC interface.
106
+ // - Stubable types are replaced by stubs.
107
+ // - RpcCompatible types are passed by value, with stubable types replaced by stubs
108
+ // and a top-level `Disposer`.
109
+ // Everything else can't be passed over RPC.
110
+ // Technically, we use custom thenables here, but they quack like `Promise`s.
111
+ // Intersecting with `(Maybe)Provider` allows pipelining.
112
+ // prettier-ignore
113
+ type Result<R> = IsAny<R> extends true ? RpcPromise$2<unknown> // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
114
+ // `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
115
+ : R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
116
+ // here: anything matching our `StubBase` was produced by machinery that already enforced
117
+ // the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
118
+ // `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
119
+ // types.
120
+ : R extends StubBase<any> ? RpcPromise$2<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$2<R> : never;
121
+ type IsAny<T> = 0 extends (1 & T) ? true : false; // Type for method or property on an RPC interface.
122
+ // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
123
+ // Unwrapping `Stub`s allows calling with `Stubable` arguments.
124
+ // For properties, rewrite types to be `Result`s.
125
+ // In each case, unwrap `Promise`s.
126
+ 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.
127
+ // This is intersected with methods/properties.
128
+ type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
129
+ type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
130
+ type MapCallbackValue<T> = // `Omit` removes call signatures, so re-intersect callable provider behavior.
131
+ T extends unknown ? Omit<Result<T>, keyof Promise<unknown>> & MaybeCallableProvider<T> & MapValuePlaceholder<T> : never;
132
+ type InvalidNativePromiseInMapResult<T, Seen = never> = T extends unknown ? InvalidNativePromiseInMapResultImpl<T, Seen> : never;
133
+ type InvalidNativePromiseInMapResultImpl<T, Seen> = [T] extends [Seen] ? never // RpcPromise is modeled as Promise & StubBase, so allow promise-like stub values.
134
+ : T extends StubBase<any> ? never // Native thenables cannot be represented in map recordings, even when typed as PromiseLike.
135
+ : 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 {
136
+ [key: string | number]: unknown;
137
+ } ? InvalidNativePromiseInMapResult<T[Extract<keyof T, string | number>], Seen | T> : never;
138
+ type MapCallbackReturn<T> = InvalidNativePromiseInMapResult<T> extends never ? T : never;
139
+ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
140
+ map<V>(callback: (elem: MapCallbackValue<E>) => MapCallbackReturn<V>): Result<Array<V>>;
141
+ };
142
+ 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.
143
+ // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
144
+ // `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
145
+ // stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
146
+ // `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
147
+ 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]> } & {
148
+ map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
149
+ });
150
+ //#endregion
151
+ //#region src/core.d.ts
152
+ interface RpcTarget$1 {
153
+ [__RPC_TARGET_BRAND]: never;
154
+ }
155
+ declare let RpcTarget$1: any;
156
+ type PropertyPath = (string | number)[];
157
+ declare abstract class StubHook {
158
+ abstract call(path: PropertyPath, args: RpcPayload): StubHook;
159
+ stream(path: PropertyPath, args: RpcPayload): {
160
+ promise: Promise<void>;
161
+ size?: number;
162
+ };
163
+ abstract map(path: PropertyPath, captures: StubHook[], instructions: unknown[]): StubHook;
164
+ abstract get(path: PropertyPath): StubHook;
165
+ abstract dup(): StubHook;
166
+ abstract pull(): RpcPayload | Promise<RpcPayload>;
167
+ abstract ignoreUnhandledRejections(): void;
168
+ abstract dispose(): void;
169
+ abstract onBroken(callback: (error: any) => void): void;
170
+ }
171
+ declare let RAW_STUB: symbol;
172
+ interface RpcStub$1 extends Disposable {}
173
+ declare class RpcStub$1 extends RpcTarget$1 {
174
+ [RAW_STUB]: this;
175
+ constructor(hook: StubHook, pathIfPromise?: PropertyPath);
176
+ hook: StubHook;
177
+ pathIfPromise?: PropertyPath;
178
+ dup(): RpcStub$1;
179
+ onRpcBroken(callback: (error: any) => void): void;
180
+ map(func: (value: RpcPromise$1) => unknown): RpcPromise$1;
181
+ toString(): string;
182
+ }
183
+ declare class RpcPromise$1 extends RpcStub$1 {
184
+ constructor(hook: StubHook | PromiseLike<unknown>, pathIfPromise?: PropertyPath);
185
+ then(onfulfilled?: ((value: unknown) => unknown) | undefined | null, onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
186
+ catch(onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
187
+ finally(onfinally?: (() => void) | undefined | null): Promise<unknown>;
188
+ toString(): string;
189
+ }
190
+ type LocatedPromise = {
191
+ parent: object;
192
+ property: string | number;
193
+ promise: RpcPromise$1;
194
+ };
195
+ declare class RpcPayload {
196
+ value: unknown;
197
+ private source;
198
+ private hooks?;
199
+ private promises?;
200
+ static fromAppParams(value: unknown): RpcPayload;
201
+ static fromAppReturn(value: unknown): RpcPayload;
202
+ static fromArray(array: RpcPayload[]): RpcPayload;
203
+ static forEvaluate(hooks: StubHook[], promises: LocatedPromise[]): RpcPayload;
204
+ static deepCopyFrom(value: unknown, oldParent: object | undefined, owner: RpcPayload | null): RpcPayload;
205
+ private constructor();
206
+ private rpcTargets?;
207
+ getHookForRpcTarget(target: RpcTarget$1 | Function, parent: object | undefined, dupStubs?: boolean): StubHook;
208
+ getHookForWritableStream(stream: WritableStream, parent: object | undefined, dupStubs?: boolean): StubHook;
209
+ getHookForReadableStream(stream: ReadableStream, parent: object | undefined, dupStubs?: boolean): StubHook;
210
+ private deepCopy;
211
+ ensureDeepCopied(): void;
212
+ private deliverTo;
213
+ private static deliverRpcPromiseTo;
214
+ deliverCall(func: Function, thisArg: object | undefined): Promise<RpcPayload>;
215
+ deliverStreamWrite(writer: {
216
+ write(chunk: unknown): Promise<void>;
217
+ }): Promise<RpcPayload>;
218
+ deliverResolve(): Promise<unknown>;
219
+ dispose(): void;
220
+ private disposeImpl;
221
+ ignoreUnhandledRejections(): void;
222
+ private ignoreUnhandledRejectionsImpl;
223
+ }
224
+ //#endregion
225
+ //#region src/serialize.d.ts
226
+ /**
227
+ * Encoding levels determine what representation the RPC system hands to the transport.
228
+ * Each level names what the transport can assume about message values.
229
+ *
230
+ * - `"string"`: JSON string. Default, used by HTTP batch and WebSocket transports.
231
+ * - `"jsonCompatible"`: JSON-compatible JS value tree. For custom encoders.
232
+ * - `"jsonCompatibleWithBytes"`: Like `"jsonCompatible"` but Uint8Array stays raw.
233
+ * - `"structuredClonable"`: Structured-clonable native values pass through where possible.
234
+ *
235
+ * @example
236
+ * ```ts
237
+ * // What happens to Uint8Array([1, 2, 3]) at each level:
238
+ * "string" → '["bytes","AQID"]' // JSON string with base64
239
+ * "jsonCompatible" → ["bytes", "AQID"] // JS array with base64
240
+ * "jsonCompatibleWithBytes" → ["bytes", Uint8Array] // JS array with raw bytes
241
+ * "structuredClonable" → ["bytes", Uint8Array] // + Date, BigInt stay native
242
+ * ```
243
+ */
244
+ type EncodingLevel = "string" | "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
245
+ interface RpcLimits {
246
+ maxBigIntDigits: number;
247
+ maxDepth: number;
248
+ maxMessageSize: number;
249
+ }
250
+ declare const DEFAULT_MAX_DEPTH = 256;
251
+ declare const DEFAULT_LIMITS: RpcLimits;
252
+ /**
253
+ * Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
254
+ * RPC stubs, but it will support basic data types.
255
+ */
256
+ declare function serialize(value: unknown): string;
257
+ /**
258
+ * Deserialize a value serialized using serialize().
259
+ */
260
+ declare function deserialize(value: string): unknown;
261
+ //#endregion
262
+ //#region src/rpc.d.ts
263
+ /**
264
+ * Interface for a string-based RPC transport. This is the default transport type — no
265
+ * `encodingLevel` field is needed. Messages are JSON strings. Implement this interface if the
266
+ * built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
267
+ */
268
+ interface RpcTransport {
269
+ /**
270
+ * The encoding level this transport works with. For this interface it is always "string";
271
+ * it may be omitted. (See `RpcTransportWithCustomEncoding` for the other levels.)
272
+ */
273
+ readonly encodingLevel?: "string";
274
+ /**
275
+ * Sends a message to the other end. May optionally return a promise; if the promise rejects,
276
+ * the session is aborted.
277
+ */
278
+ send(message: string): void | Promise<void>;
279
+ /**
280
+ * Receives a message sent by the other end.
281
+ *
282
+ * If and when the transport becomes disconnected, this will reject. The thrown error will be
283
+ * propagated to all outstanding calls and future calls on any stubs associated with the session.
284
+ * If there are no outstanding calls (and none are made in the future), then the error does not
285
+ * propagate anywhere -- this is considered a "clean" shutdown.
286
+ */
287
+ receive(): Promise<string>;
288
+ /**
289
+ * Indicates that the RPC system has suffered an error that prevents the session from continuing.
290
+ * The transport should ideally try to send any queued messages if it can, and then close the
291
+ * connection. (It's not strictly necessary to deliver queued messages, but the last message sent
292
+ * before abort() is called is often an "abort" message, which communicates the error to the
293
+ * peer, so if that is dropped, the peer may have less information about what happened.)
294
+ */
295
+ abort?(reason: any): void;
296
+ }
297
+ /**
298
+ * Interface for a transport that receives partially encoded JS values instead of JSON strings.
299
+ * The selected `encodingLevel` describes what the transport can assume about message values.
300
+ */
301
+ interface RpcTransportWithCustomEncoding {
302
+ /**
303
+ * The encoding level this transport works with.
304
+ *
305
+ * - "jsonCompatible": JSON-compatible JS value tree; transport handles final serialization.
306
+ * - "jsonCompatibleWithBytes": Like "jsonCompatible" but Uint8Array values are left raw.
307
+ * - "structuredClonable": Structured-clonable native values pass through where possible.
308
+ */
309
+ readonly encodingLevel: "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
310
+ /**
311
+ * Encodes and sends a message to the other end. Returns the encoded byte size if known.
312
+ * If the size is unavailable, return void; Cap'n Web will estimate stream message sizes for
313
+ * flow control. Send errors should be propagated via `receive()` rejecting.
314
+ */
315
+ send(message: unknown): number | void;
316
+ /**
317
+ * Receives and decodes a message sent by the other end.
318
+ *
319
+ * If and when the transport becomes disconnected, this will reject. The thrown error will be
320
+ * propagated to all outstanding calls and future calls on any stubs associated with the session.
321
+ * If there are no outstanding calls (and none are made in the future), then the error does not
322
+ * propagate anywhere -- this is considered a "clean" shutdown.
323
+ */
324
+ receive(): Promise<unknown>;
325
+ /**
326
+ * Indicates that the RPC system has suffered an error that prevents the session from continuing.
327
+ * The transport should ideally try to send any queued messages if it can, and then close the
328
+ * connection. (It's not strictly necessary to deliver queued messages, but the last message sent
329
+ * before abort() is called is often an "abort" message, which communicates the error to the
330
+ * peer, so if that is dropped, the peer may have less information about what happened.)
331
+ */
332
+ abort?(reason: any): void;
333
+ }
334
+ /** Any supported transport type. */
335
+ type AnyRpcTransport = RpcTransport | RpcTransportWithCustomEncoding;
336
+ /**
337
+ * Options to customize behavior of an RPC session. All functions which start a session should
338
+ * optionally accept this.
339
+ */
340
+ type RpcSessionOptions = {
341
+ /**
342
+ * If provided, this function will be called whenever an `Error` object is serialized (for any
343
+ * reason, not just because it was thrown). This can be used to log errors, and also to redact
344
+ * them.
345
+ *
346
+ * If `onSendError` returns an Error object, than object will be substituted in place of the
347
+ * original. If it has a stack property, the stack will be sent to the client.
348
+ *
349
+ * If `onSendError` doesn't return anything (or is not provided at all), the default behavior is
350
+ * to serialize the error with the stack omitted.
351
+ */
352
+ onSendError?: (error: Error) => Error | void;
353
+ /**
354
+ * Overrides for the resource limits enforced while deserializing messages from the peer. Any
355
+ * field left unset falls back to `DEFAULT_LIMITS`. These guard against resource-exhaustion
356
+ * attacks from untrusted peers; see `RpcLimits` for the meaning and defaults of each field.
357
+ *
358
+ * Limits are a purely local, receiver-side decision -- the protocol has no negotiation step, so
359
+ * the peer never learns these values. A message that exceeds a limit is rejected, aborting the
360
+ * session.
361
+ */
362
+ limits?: Partial<RpcLimits>;
363
+ };
364
+ //#endregion
365
+ //#region src/websocket.d.ts
366
+ /**
367
+ * For use in Cloudflare Workers: Construct an HTTP response that starts a WebSocket RPC session
368
+ * with the given `localMain`.
369
+ */
370
+ declare function newWorkersWebSocketRpcResponse(request: Request, localMain?: any, options?: RpcSessionOptions): Response;
371
+ /**
372
+ * Generic WebSocket transport. Default `T = string` is backward-compatible and satisfies
373
+ * `RpcTransport`. Use `T = ArrayBuffer` as a building block for binary transports.
374
+ */
375
+ declare class WebSocketTransport<T extends string | ArrayBuffer = string> {
376
+ #private;
377
+ constructor(webSocket: WebSocket);
378
+ send(message: T): void;
379
+ receive(): Promise<T>;
380
+ abort(reason: any): void;
381
+ }
382
+ //#endregion
383
+ //#region src/batch.d.ts
384
+ /**
385
+ * Implements the server end of an HTTP batch session, using standard Fetch API types to represent
386
+ * HTTP requests and responses.
387
+ *
388
+ * @param request The request received from the client initiating the session.
389
+ * @param localMain The main stub or RpcTarget which the server wishes to expose to the client.
390
+ * @param options Optional RPC session options.
391
+ * @returns The HTTP response to return to the client. Note that the returned object has mutable
392
+ * headers, so you can modify them using e.g. `response.headers.set("Foo", "bar")`.
393
+ */
394
+ declare function newHttpBatchRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
395
+ /**
396
+ * Implements the server end of an HTTP batch session using traditional Node.js HTTP APIs.
397
+ *
398
+ * @param request The request received from the client initiating the session.
399
+ * @param response The response object, to which the response should be written.
400
+ * @param localMain The main stub or RpcTarget which the server wishes to expose to the client.
401
+ * @param options Optional RPC session options. You can also pass headers to set on the response.
402
+ */
403
+ declare function nodeHttpBatchRpcResponse(request: IncomingMessage, response: ServerResponse, localMain: any, options?: RpcSessionOptions & {
404
+ headers?: OutgoingHttpHeaders | OutgoingHttpHeader[];
405
+ }): Promise<void>;
406
+ //#endregion
407
+ //#region src/index.d.ts
408
+ /**
409
+ * Represents a reference to a remote object, on which methods may be remotely invoked via RPC.
410
+ *
411
+ * `RpcStub` can represent any interface (when using TypeScript, you pass the specific interface
412
+ * type as `T`, but this isn't known at runtime). The way this works is, `RpcStub` is actually a
413
+ * `Proxy`. It makes itself appear as if every possible method / property name is defined. You can
414
+ * invoke any method name, and the invocation will be sent to the server. If it turns out that no
415
+ * such method exists on the remote object, an exception is thrown back. But the client does not
416
+ * actually know, until that point, what methods exist.
417
+ */
418
+ type RpcStub<T extends RpcCompatible<T>> = Stub<T>;
419
+ declare const RpcStub: {
420
+ new <T extends RpcCompatible<T>>(value: T): RpcStub<T>;
421
+ };
422
+ /**
423
+ * Represents the result of an RPC call.
424
+ *
425
+ * Also used to represent properties. That is, `stub.foo` evaluates to an `RpcPromise` for the
426
+ * value of `foo`.
427
+ *
428
+ * This isn't actually a JavaScript `Promise`. It does, however, have `then()`, `catch()`, and
429
+ * `finally()` methods, like `Promise` does, and because it has a `then()` method, JavaScript will
430
+ * allow you to treat it like a promise, e.g. you can `await` it.
431
+ *
432
+ * An `RpcPromise` is also a proxy, just like `RpcStub`, where calling methods or awaiting
433
+ * properties will make a pipelined network request.
434
+ *
435
+ * Note that and `RpcPromise` is "lazy": the actual final result is not requested from the server
436
+ * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
437
+ * if you only intend to use the promise for pipelining and you never await it, then there's no
438
+ * need to transmit the resolution!
439
+ *
440
+ * You may also construct an `RpcPromise` yourself from a regular `Promise`, using
441
+ * `new RpcPromise(promise)`, allowing you to perform promise pipelining on a local promise. This
442
+ * is semantically identical to creating a local-loopback RPC that returns the promise, and then
443
+ * invoking it: pipelined calls wait until the promise resolves, then are delivered, in order, to
444
+ * the resolution. This is useful when you plan to obtain some stub in the future, but want to
445
+ * allow code to start queuing calls on it immediately. Note that the `RpcPromise` takes
446
+ * ownership of the resolution: disposing it disposes the resolution, so resolve the promise
447
+ * with a `dup()` if you also intend to keep the stub.
448
+ */
449
+ type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$2<T>;
450
+ declare const RpcPromise: {
451
+ new <T extends RpcCompatible<T>>(value: Promise<T>): RpcPromise$2<ElideStub<T>>;
452
+ new <T extends RpcCompatible<T>>(value: Promise<PayloadOrStub<T>>): RpcPromise$2<ElideStub<T>>;
453
+ };
454
+ /**
455
+ * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
456
+ *
457
+ * Most people won't use this. You only need it if you've implemented your own `RpcTransport`.
458
+ */
459
+ interface RpcSession<T extends RpcCompatible<T> = undefined> {
460
+ getRemoteMain(): RpcStub<T>;
461
+ getStats(): {
462
+ imports: number;
463
+ exports: number;
464
+ };
465
+ drain(): Promise<void>;
466
+ }
467
+ declare const RpcSession: {
468
+ new <T extends RpcCompatible<T> = undefined>(transport: AnyRpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
469
+ };
470
+ /**
471
+ * Classes which are intended to be passed by reference and called over RPC must extend
472
+ * `RpcTarget`. A class which does not extend `RpcTarget` (and which doesn't have built-in support
473
+ * from the RPC system) cannot be passed in an RPC message at all; an exception will be thrown.
474
+ *
475
+ * Note that on Cloudflare Workers, this `RpcTarget` is an alias for the one exported from the
476
+ * "cloudflare:workers" module, so they can be used interchangably.
477
+ */
478
+ interface RpcTarget extends RpcTargetBranded {}
479
+ declare const RpcTarget: {
480
+ new (): RpcTarget;
481
+ };
482
+ /**
483
+ * Empty interface used as default type parameter for sessions where the other side doesn't
484
+ * necessarily export a main interface.
485
+ */
486
+ interface Empty$1 {}
487
+ /**
488
+ * Start a WebSocket session given either an already-open WebSocket or a URL.
489
+ *
490
+ * @param webSocket Either the `wss://` URL to connect to, or an already-open WebSocket object to
491
+ * use.
492
+ * @param localMain The main RPC interface to expose to the peer. Returns a stub for the main
493
+ * interface exposed from the peer.
494
+ */
495
+ declare let newWebSocketRpcSession: <T extends RpcCompatible<T> = Empty$1>(webSocket: WebSocket | string, localMain?: any, options?: RpcSessionOptions) => RpcStub<T>;
496
+ /**
497
+ * Initiate an HTTP batch session from the client side.
498
+ *
499
+ * The parameters to this method have exactly the same signature as `fetch()`, but the return
500
+ * value is an RpcStub. You can customize anything about the request except for the method
501
+ * (it will always be set to POST) and the body (which the RPC system will fill in).
502
+ */
503
+ declare let newHttpBatchRpcSession: <T extends RpcCompatible<T>>(urlOrRequest: string | Request, options?: RpcSessionOptions) => RpcStub<T>;
504
+ /**
505
+ * Initiate an RPC session over a MessagePort, which is particularly useful for communicating
506
+ * between an iframe and its parent frame in a browser context. Each side should call this function
507
+ * on its own end of the MessageChannel.
508
+ */
509
+ declare let newMessagePortRpcSession: <T extends RpcCompatible<T> = Empty$1>(port: MessagePort, localMain?: any, options?: RpcSessionOptions) => RpcStub<T>;
510
+ /**
511
+ * Implements unified handling of HTTP-batch and WebSocket responses for the Cloudflare Workers
512
+ * Runtime.
513
+ *
514
+ * SECURITY WARNING: This function accepts cross-origin requests. If you do not want this, you
515
+ * should validate the `Origin` header before calling this, or use `newHttpBatchRpcSession()` and
516
+ * `newWebSocketRpcSession()` directly with appropriate security measures for each type of request.
517
+ * But if your API uses in-band authorization (i.e. it has an RPC method that takes the user's
518
+ * credentials as parameters and returns the authorized API), then cross-origin requests should
519
+ * be safe.
520
+ */
521
+ declare function newWorkersRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
522
+ //#endregion
523
+ //#region src/bun.d.ts
524
+ type WsData = {
525
+ __capnwebTransport: BunWebSocketTransport<WsData>;
526
+ __capnwebStub: RpcStub$1;
527
+ };
528
+ /**
529
+ * Create a Bun `WebSocketHandler` object that manages RPC sessions automatically.
530
+ *
531
+ * The returned object can be passed directly as the `websocket` option to `Bun.serve()`.
532
+ * A fresh `localMain` is created for each connection via the `createMain` callback.
533
+ * The transport is stored on `ws.data.__capnwebTransport`.
534
+ *
535
+ * @param createMain Called once per connection to create the main RPC interface for that client.
536
+ * @param options Optional RPC session options applied to every connection.
537
+ */
538
+ declare function newBunWebSocketRpcHandler(createMain: () => RpcTargetBranded, options?: RpcSessionOptions): {
539
+ open(ws: ServerWebSocket<WsData>): void;
540
+ message(ws: ServerWebSocket<WsData>, message: string | Buffer): void;
541
+ close(ws: ServerWebSocket<WsData>, code: number, reason: string): void;
542
+ error(ws: ServerWebSocket<WsData>, error: Error): void;
543
+ };
544
+ declare class BunWebSocketTransport<T = undefined> implements RpcTransport {
545
+ #private;
546
+ constructor(ws: ServerWebSocket<T>);
547
+ send(message: string): Promise<void>;
548
+ receive(): Promise<string>;
549
+ abort?(reason: any): void;
550
+ dispatchMessage(data: string | Buffer): void;
551
+ dispatchClose(code: number, reason: string): void;
552
+ dispatchError(error: Error): void;
553
+ }
554
+ //#endregion
555
+ //#region src/index-bun.d.ts
556
+ interface Empty {}
557
+ /**
558
+ * Start an RPC session over a Bun ServerWebSocket.
559
+ *
560
+ * Returns both the RPC stub and the transport. The transport exposes `dispatchMessage`,
561
+ * `dispatchClose`, and `dispatchError` methods that must be wired to Bun's `WebSocketHandler`
562
+ * callbacks. For a zero-wiring alternative, use `newBunWebSocketRpcHandler` instead.
563
+ *
564
+ * @param ws The Bun ServerWebSocket from the `open` callback.
565
+ * @param localMain The main RPC interface to expose to the peer.
566
+ */
567
+ declare let newBunWebSocketRpcSession: <T extends RpcCompatible<T> = Empty, D = undefined>(ws: ServerWebSocket<D>, localMain?: any, options?: RpcSessionOptions) => {
568
+ stub: RpcStub<T>;
569
+ transport: BunWebSocketTransport<D>;
570
+ };
571
+ //#endregion
572
+ 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 };
573
+ //# sourceMappingURL=index-bun.d.ts.map