capnweb 0.0.0-25baebf → 0.0.0-2cb51eb

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,82 +1,380 @@
1
- import { _ as __RPC_TARGET_BRAND, R as RpcTransport, a as RpcTargetBranded, b as RpcSessionOptions, c as RpcCompatible, d as RpcStub$1 } from './index-workers-CiDKhXAE.js';
2
- export { e as RpcPromise, f as RpcSession, g as RpcTarget, h as deserialize, n as newHttpBatchRpcResponse, i as newHttpBatchRpcSession, j as newMessagePortRpcSession, k as newWebSocketRpcSession, l as newWorkersRpcResponse, m as newWorkersWebSocketRpcResponse, o as nodeHttpBatchRpcResponse, s as serialize } from './index-workers-CiDKhXAE.js';
3
- import { ServerWebSocket } from 'bun';
4
- import 'node:http';
1
+ import { IncomingMessage, OutgoingHttpHeader, OutgoingHttpHeaders, ServerResponse } from "node:http";
2
+ import { ServerWebSocket } from "bun";
5
3
 
6
- interface RpcTarget {
7
- [__RPC_TARGET_BRAND]: never;
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;
8
19
  }
9
- declare let RpcTarget: any;
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;
10
115
  type PropertyPath = (string | number)[];
11
116
  declare abstract class StubHook {
12
- abstract call(path: PropertyPath, args: RpcPayload): StubHook;
13
- stream(path: PropertyPath, args: RpcPayload): {
14
- promise: Promise<void>;
15
- size?: number;
16
- };
17
- abstract map(path: PropertyPath, captures: StubHook[], instructions: unknown[]): StubHook;
18
- abstract get(path: PropertyPath): StubHook;
19
- abstract dup(): StubHook;
20
- abstract pull(): RpcPayload | Promise<RpcPayload>;
21
- abstract ignoreUnhandledRejections(): void;
22
- abstract dispose(): void;
23
- abstract onBroken(callback: (error: any) => void): void;
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;
24
129
  }
25
130
  declare let RAW_STUB: symbol;
26
- interface RpcStub extends Disposable {
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;
27
141
  }
28
- declare class RpcStub extends RpcTarget {
29
- [RAW_STUB]: this;
30
- constructor(hook: StubHook, pathIfPromise?: PropertyPath);
31
- hook: StubHook;
32
- pathIfPromise?: PropertyPath;
33
- dup(): RpcStub;
34
- onRpcBroken(callback: (error: any) => void): void;
35
- map(func: (value: RpcPromise) => unknown): RpcPromise;
36
- toString(): string;
37
- }
38
- declare class RpcPromise extends RpcStub {
39
- constructor(hook: StubHook, pathIfPromise: PropertyPath);
40
- then(onfulfilled?: ((value: unknown) => unknown) | undefined | null, onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
41
- catch(onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
42
- finally(onfinally?: (() => void) | undefined | null): Promise<unknown>;
43
- toString(): string;
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;
44
148
  }
45
149
  type LocatedPromise = {
46
- parent: object;
47
- property: string | number;
48
- promise: RpcPromise;
150
+ parent: object;
151
+ property: string | number;
152
+ promise: RpcPromise$1;
49
153
  };
50
154
  declare class RpcPayload {
51
- value: unknown;
52
- private source;
53
- private hooks?;
54
- private promises?;
55
- static fromAppParams(value: unknown): RpcPayload;
56
- static fromAppReturn(value: unknown): RpcPayload;
57
- static fromArray(array: RpcPayload[]): RpcPayload;
58
- static forEvaluate(hooks: StubHook[], promises: LocatedPromise[]): RpcPayload;
59
- static deepCopyFrom(value: unknown, oldParent: object | undefined, owner: RpcPayload | null): RpcPayload;
60
- private constructor();
61
- private rpcTargets?;
62
- getHookForRpcTarget(target: RpcTarget | Function, parent: object | undefined, dupStubs?: boolean): StubHook;
63
- getHookForWritableStream(stream: WritableStream, parent: object | undefined, dupStubs?: boolean): StubHook;
64
- getHookForReadableStream(stream: ReadableStream, parent: object | undefined, dupStubs?: boolean): StubHook;
65
- private deepCopy;
66
- ensureDeepCopied(): void;
67
- private deliverTo;
68
- private static deliverRpcPromiseTo;
69
- deliverCall(func: Function, thisArg: object | undefined): Promise<RpcPayload>;
70
- deliverResolve(): Promise<unknown>;
71
- dispose(): void;
72
- private disposeImpl;
73
- ignoreUnhandledRejections(): void;
74
- private ignoreUnhandledRejectionsImpl;
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;
75
179
  }
76
-
180
+ //#endregion
181
+ //#region src/serialize.d.ts
182
+ /**
183
+ * Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
184
+ * RPC stubs, but it will support basic data types.
185
+ */
186
+ declare function serialize(value: unknown): string;
187
+ /**
188
+ * Deserialize a value serialized using serialize().
189
+ */
190
+ declare function deserialize(value: string): unknown;
191
+ //#endregion
192
+ //#region src/rpc.d.ts
193
+ /**
194
+ * Interface for an RPC transport, which is a simple bidirectional message stream. Implement this
195
+ * interface if the built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
196
+ */
197
+ interface RpcTransport {
198
+ /**
199
+ * Sends a message to the other end.
200
+ */
201
+ send(message: string): Promise<void>;
202
+ /**
203
+ * Receives a message sent by the other end.
204
+ *
205
+ * If and when the transport becomes disconnected, this will reject. The thrown error will be
206
+ * propagated to all outstanding calls and future calls on any stubs associated with the session.
207
+ * If there are no outstanding calls (and none are made in the future), then the error does not
208
+ * propagate anywhere -- this is considered a "clean" shutdown.
209
+ */
210
+ receive(): Promise<string>;
211
+ /**
212
+ * Indicates that the RPC system has suffered an error that prevents the session from continuing.
213
+ * The transport should ideally try to send any queued messages if it can, and then close the
214
+ * connection. (It's not strictly necessary to deliver queued messages, but the last message sent
215
+ * before abort() is called is often an "abort" message, which communicates the error to the
216
+ * peer, so if that is dropped, the peer may have less information about what happened.)
217
+ */
218
+ abort?(reason: any): void;
219
+ }
220
+ /**
221
+ * Options to customize behavior of an RPC session. All functions which start a session should
222
+ * optionally accept this.
223
+ */
224
+ type RpcSessionOptions = {
225
+ /**
226
+ * If provided, this function will be called whenever an `Error` object is serialized (for any
227
+ * reason, not just because it was thrown). This can be used to log errors, and also to redact
228
+ * them.
229
+ *
230
+ * If `onSendError` returns an Error object, than object will be substituted in place of the
231
+ * original. If it has a stack property, the stack will be sent to the client.
232
+ *
233
+ * If `onSendError` doesn't return anything (or is not provided at all), the default behavior is
234
+ * to serialize the error with the stack omitted.
235
+ */
236
+ onSendError?: (error: Error) => Error | void;
237
+ };
238
+ //#endregion
239
+ //#region src/websocket.d.ts
240
+ /**
241
+ * For use in Cloudflare Workers: Construct an HTTP response that starts a WebSocket RPC session
242
+ * with the given `localMain`.
243
+ */
244
+ declare function newWorkersWebSocketRpcResponse(request: Request, localMain?: any, options?: RpcSessionOptions): Response;
245
+ //#endregion
246
+ //#region src/batch.d.ts
247
+ /**
248
+ * Implements the server end of an HTTP batch session, using standard Fetch API types to represent
249
+ * HTTP requests and responses.
250
+ *
251
+ * @param request The request received from the client initiating the session.
252
+ * @param localMain The main stub or RpcTarget which the server wishes to expose to the client.
253
+ * @param options Optional RPC session options.
254
+ * @returns The HTTP response to return to the client. Note that the returned object has mutable
255
+ * headers, so you can modify them using e.g. `response.headers.set("Foo", "bar")`.
256
+ */
257
+ declare function newHttpBatchRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
258
+ /**
259
+ * Implements the server end of an HTTP batch session using traditional Node.js HTTP APIs.
260
+ *
261
+ * @param request The request received from the client initiating the session.
262
+ * @param response The response object, to which the response should be written.
263
+ * @param localMain The main stub or RpcTarget which the server wishes to expose to the client.
264
+ * @param options Optional RPC session options. You can also pass headers to set on the response.
265
+ */
266
+ declare function nodeHttpBatchRpcResponse(request: IncomingMessage, response: ServerResponse, localMain: any, options?: RpcSessionOptions & {
267
+ headers?: OutgoingHttpHeaders | OutgoingHttpHeader[];
268
+ }): Promise<void>;
269
+ //#endregion
270
+ //#region src/index.d.ts
271
+ /**
272
+ * Represents a reference to a remote object, on which methods may be remotely invoked via RPC.
273
+ *
274
+ * `RpcStub` can represent any interface (when using TypeScript, you pass the specific interface
275
+ * type as `T`, but this isn't known at runtime). The way this works is, `RpcStub` is actually a
276
+ * `Proxy`. It makes itself appear as if every possible method / property name is defined. You can
277
+ * invoke any method name, and the invocation will be sent to the server. If it turns out that no
278
+ * such method exists on the remote object, an exception is thrown back. But the client does not
279
+ * actually know, until that point, what methods exist.
280
+ */
281
+ type RpcStub<T extends RpcCompatible<T>> = Stub<T>;
282
+ declare const RpcStub: {
283
+ new <T extends RpcCompatible<T>>(value: T): RpcStub<T>;
284
+ };
285
+ /**
286
+ * Represents the result of an RPC call.
287
+ *
288
+ * Also used to represent properties. That is, `stub.foo` evaluates to an `RpcPromise` for the
289
+ * value of `foo`.
290
+ *
291
+ * This isn't actually a JavaScript `Promise`. It does, however, have `then()`, `catch()`, and
292
+ * `finally()` methods, like `Promise` does, and because it has a `then()` method, JavaScript will
293
+ * allow you to treat it like a promise, e.g. you can `await` it.
294
+ *
295
+ * An `RpcPromise` is also a proxy, just like `RpcStub`, where calling methods or awaiting
296
+ * properties will make a pipelined network request.
297
+ *
298
+ * Note that and `RpcPromise` is "lazy": the actual final result is not requested from the server
299
+ * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
300
+ * if you only intend to use the promise for pipelining and you never await it, then there's no
301
+ * need to transmit the resolution!
302
+ */
303
+ type RpcPromise<T extends RpcCompatible<T>> = Stub<T> & Promise<Stubify<T>>;
304
+ declare const RpcPromise: {};
305
+ /**
306
+ * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
307
+ *
308
+ * Most people won't use this. You only need it if you've implemented your own `RpcTransport`.
309
+ */
310
+ interface RpcSession<T extends RpcCompatible<T> = undefined> {
311
+ getRemoteMain(): RpcStub<T>;
312
+ getStats(): {
313
+ imports: number;
314
+ exports: number;
315
+ };
316
+ drain(): Promise<void>;
317
+ }
318
+ declare const RpcSession: {
319
+ new <T extends RpcCompatible<T> = undefined>(transport: RpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
320
+ };
321
+ /**
322
+ * Classes which are intended to be passed by reference and called over RPC must extend
323
+ * `RpcTarget`. A class which does not extend `RpcTarget` (and which doesn't have built-in support
324
+ * from the RPC system) cannot be passed in an RPC message at all; an exception will be thrown.
325
+ *
326
+ * Note that on Cloudflare Workers, this `RpcTarget` is an alias for the one exported from the
327
+ * "cloudflare:workers" module, so they can be used interchangably.
328
+ */
329
+ interface RpcTarget extends RpcTargetBranded {}
330
+ declare const RpcTarget: {
331
+ new (): RpcTarget;
332
+ };
333
+ /**
334
+ * Empty interface used as default type parameter for sessions where the other side doesn't
335
+ * necessarily export a main interface.
336
+ */
337
+ interface Empty$1 {}
338
+ /**
339
+ * Start a WebSocket session given either an already-open WebSocket or a URL.
340
+ *
341
+ * @param webSocket Either the `wss://` URL to connect to, or an already-open WebSocket object to
342
+ * use.
343
+ * @param localMain The main RPC interface to expose to the peer. Returns a stub for the main
344
+ * interface exposed from the peer.
345
+ */
346
+ declare let newWebSocketRpcSession: <T extends RpcCompatible<T> = Empty$1>(webSocket: WebSocket | string, localMain?: any, options?: RpcSessionOptions) => RpcStub<T>;
347
+ /**
348
+ * Initiate an HTTP batch session from the client side.
349
+ *
350
+ * The parameters to this method have exactly the same signature as `fetch()`, but the return
351
+ * value is an RpcStub. You can customize anything about the request except for the method
352
+ * (it will always be set to POST) and the body (which the RPC system will fill in).
353
+ */
354
+ declare let newHttpBatchRpcSession: <T extends RpcCompatible<T>>(urlOrRequest: string | Request, options?: RpcSessionOptions) => RpcStub<T>;
355
+ /**
356
+ * Initiate an RPC session over a MessagePort, which is particularly useful for communicating
357
+ * between an iframe and its parent frame in a browser context. Each side should call this function
358
+ * on its own end of the MessageChannel.
359
+ */
360
+ declare let newMessagePortRpcSession: <T extends RpcCompatible<T> = Empty$1>(port: MessagePort, localMain?: any, options?: RpcSessionOptions) => RpcStub<T>;
361
+ /**
362
+ * Implements unified handling of HTTP-batch and WebSocket responses for the Cloudflare Workers
363
+ * Runtime.
364
+ *
365
+ * SECURITY WARNING: This function accepts cross-origin requests. If you do not want this, you
366
+ * should validate the `Origin` header before calling this, or use `newHttpBatchRpcSession()` and
367
+ * `newWebSocketRpcSession()` directly with appropriate security measures for each type of request.
368
+ * But if your API uses in-band authorization (i.e. it has an RPC method that takes the user's
369
+ * credentials as parameters and returns the authorized API), then cross-origin requests should
370
+ * be safe.
371
+ */
372
+ declare function newWorkersRpcResponse(request: Request, localMain: any): Promise<Response>;
373
+ //#endregion
374
+ //#region src/bun.d.ts
77
375
  type WsData = {
78
- __capnwebTransport: BunWebSocketTransport<WsData>;
79
- __capnwebStub: RpcStub;
376
+ __capnwebTransport: BunWebSocketTransport<WsData>;
377
+ __capnwebStub: RpcStub$1;
80
378
  };
81
379
  /**
82
380
  * Create a Bun `WebSocketHandler` object that manages RPC sessions automatically.
@@ -89,24 +387,24 @@ type WsData = {
89
387
  * @param options Optional RPC session options applied to every connection.
90
388
  */
91
389
  declare function newBunWebSocketRpcHandler(createMain: () => RpcTargetBranded, options?: RpcSessionOptions): {
92
- open(ws: ServerWebSocket<WsData>): void;
93
- message(ws: ServerWebSocket<WsData>, message: string | Buffer): void;
94
- close(ws: ServerWebSocket<WsData>, code: number, reason: string): void;
95
- error(ws: ServerWebSocket<WsData>, error: Error): void;
390
+ open(ws: ServerWebSocket<WsData>): void;
391
+ message(ws: ServerWebSocket<WsData>, message: string | Buffer): void;
392
+ close(ws: ServerWebSocket<WsData>, code: number, reason: string): void;
393
+ error(ws: ServerWebSocket<WsData>, error: Error): void;
96
394
  };
97
395
  declare class BunWebSocketTransport<T = undefined> implements RpcTransport {
98
- #private;
99
- constructor(ws: ServerWebSocket<T>);
100
- send(message: string): Promise<void>;
101
- receive(): Promise<string>;
102
- abort?(reason: any): void;
103
- dispatchMessage(data: string | Buffer): void;
104
- dispatchClose(code: number, reason: string): void;
105
- dispatchError(error: Error): void;
106
- }
107
-
108
- interface Empty {
396
+ #private;
397
+ constructor(ws: ServerWebSocket<T>);
398
+ send(message: string): Promise<void>;
399
+ receive(): Promise<string>;
400
+ abort?(reason: any): void;
401
+ dispatchMessage(data: string | Buffer): void;
402
+ dispatchClose(code: number, reason: string): void;
403
+ dispatchError(error: Error): void;
109
404
  }
405
+ //#endregion
406
+ //#region src/index-bun.d.ts
407
+ interface Empty {}
110
408
  /**
111
409
  * Start an RPC session over a Bun ServerWebSocket.
112
410
  *
@@ -118,8 +416,9 @@ interface Empty {
118
416
  * @param localMain The main RPC interface to expose to the peer.
119
417
  */
120
418
  declare let newBunWebSocketRpcSession: <T extends RpcCompatible<T> = Empty, D = undefined>(ws: ServerWebSocket<D>, localMain?: any, options?: RpcSessionOptions) => {
121
- stub: RpcStub$1<T>;
122
- transport: BunWebSocketTransport<D>;
419
+ stub: RpcStub<T>;
420
+ transport: BunWebSocketTransport<D>;
123
421
  };
124
-
125
- export { BunWebSocketTransport, RpcCompatible, RpcSessionOptions, RpcStub$1 as RpcStub, RpcTransport, newBunWebSocketRpcHandler, newBunWebSocketRpcSession };
422
+ //#endregion
423
+ export { BunWebSocketTransport, type RpcCompatible, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, deserialize, newBunWebSocketRpcHandler, newBunWebSocketRpcSession, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
424
+ //# sourceMappingURL=index-bun.d.ts.map