capnweb 0.0.0-e3fa093 → 0.0.0-ee7ca6f

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