capnweb 0.11.0 → 0.12.0

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.
package/dist/index.d.cts CHANGED
@@ -20,7 +20,8 @@ interface RpcTargetBranded {
20
20
  // `never[]` preserves compatibility with strongly-typed function signatures without introducing
21
21
  // `any` into inference.
22
22
  type Stubable = RpcTargetBranded | ((...args: never[]) => unknown);
23
- type IsUnknown<T> = unknown extends T ? ([T] extends [unknown] ? true : false) : false; // Types that can be passed over RPC
23
+ // Note: also true for `any` (call sites that care check `IsAny` first).
24
+ type IsUnknown<T> = unknown extends T ? true : false; // Types that can be passed over RPC
24
25
  // The reason for using a generic type here is to build the serializable subset of RPC-compatible
25
26
  // composite types. This allows types defined with the "interface" keyword to pass the
26
27
  // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
@@ -42,8 +43,14 @@ type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | I
42
43
  type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | Blob | ReadableStream<any> // Chunk type can be any RPC-compatible type
43
44
  | WritableStream<any> // Chunk type can be any RPC-compatible type
44
45
  | URL | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
46
+ // Arm ordering matters here:
47
+ // - `Promise` must come before `StubBase`: `RpcPromise<T>` matches both, and must resolve
48
+ // through the Promise arm rather than pass through as-is.
49
+ // - `StubBase` must come before `Stubable`: `Stub<T>` of a callable `T` is itself callable, so
50
+ // it matches `Stubable`. Checking `StubBase` first keeps existing stubs as-is instead of
51
+ // double-wrapping them as `Stub<Stub<T>>`.
45
52
  // 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.
53
+ type Stubify<T> = T extends Promise<infer U> ? Stubify<U> : T extends StubBase<any> ? T : T extends Stubable ? Stub<T> : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>> : T extends Set<infer V> ? Set<Stubify<V>> : T extends [] ? [] : T extends [infer Head, ...infer Tail] ? [Stubify<Head>, ...Stubify<Tail>] : T extends readonly [] ? readonly [] : T extends readonly [infer Head, ...infer Tail] ? readonly [Stubify<Head>, ...Stubify<Tail>] : T extends Array<infer V> ? Array<Stubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>> : T extends BaseType ? T // When using "unknown" instead of "any", interfaces are not stubified.
47
54
  : T extends {
48
55
  [key: string | number]: any;
49
56
  } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
@@ -76,6 +83,24 @@ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // The type b
76
83
  // same type arguments, the checker short-circuits on identity instead of recursing through the
77
84
  // full structural comparison of these mutually-recursive types.
78
85
  type RpcPromise$1<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & StubBase<T> : Promise<Stubify<T> & MaybeDisposable<T>> & Provider<T> & StubBase<T>;
86
+ // The elision `Result` applies to a bare stub type: unwrap `Stub<T>` back to `T` when the
87
+ // payload is `Stubable`. Such stubs await back to a stub either way, so eliding keeps a
88
+ // declared `Promise<RpcStub<T>>` return interchangeable with a `Promise<T>` return.
89
+ // Plain-interface stubs are NOT elided: `RpcPromise<U>` only awaits to `Stub<U>` when
90
+ // `U extends Stubable`, so eliding those would change the awaited type from a stub to a
91
+ // stubified record. The payload check is deliberately non-distributive (`[U] extends [...]`).
92
+ // `Stub<any>` is not elided either: `[any] extends [Stubable]` is true, so without the `IsAny`
93
+ // guard an `any`-payload stub would lose its stub surface.
94
+ // Also used by the `RpcPromise` constructor signature (index.ts), which applies exactly this
95
+ // transformation so constructing from a promised stub matches the method-return type.
96
+ type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
97
+ // What the promise given to `new RpcPromise<T>(...)` may resolve to: the payload itself, or —
98
+ // for stubable payloads — a stub of it. `NoInfer` keeps the stub arm out of inference, so an
99
+ // inferred `T` is always the promise's own resolution type; the arm only matters when `T` is
100
+ // explicitly annotated (`new RpcPromise<Counter>(promiseOfStub)`). Stubs of non-stubable
101
+ // payloads are deliberately rejected: `ElideStub` wouldn't elide those, so accepting one would
102
+ // claim the promise awaits to a stubified record while the runtime resolves to a stub.
103
+ type PayloadOrStub<T> = T | NoInfer<Stub<Extract<T, Stubable>>>;
79
104
  // Type for method return or property on an RPC interface.
80
105
  // - Stubable types are replaced by stubs.
81
106
  // - RpcCompatible types are passed by value, with stubable types replaced by stubs
@@ -84,14 +109,20 @@ type RpcPromise$1<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & Stu
84
109
  // Technically, we use custom thenables here, but they quack like `Promise`s.
85
110
  // Intersecting with `(Maybe)Provider` allows pipelining.
86
111
  // prettier-ignore
87
- type Result<R> = IsAny<R> extends true ? UnknownResult : IsUnknown<R> extends true ? UnknownResult : R extends Stubable ? RpcPromise$1<R> : R extends RpcCompatible<R> ? RpcPromise$1<R> : never;
88
- type IsAny<T> = 0 extends (1 & T) ? true : false;
89
- type UnknownResult = Promise<unknown> & Provider<unknown> & StubBase<unknown>; // Type for method or property on an RPC interface.
112
+ type Result<R> = IsAny<R> extends true ? RpcPromise$1<unknown> // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
113
+ // `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
114
+ : R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
115
+ // here: anything matching our `StubBase` was produced by machinery that already enforced
116
+ // the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
117
+ // `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
118
+ // types.
119
+ : R extends StubBase<any> ? RpcPromise$1<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$1<R> : never;
120
+ type IsAny<T> = 0 extends (1 & T) ? true : false; // Type for method or property on an RPC interface.
90
121
  // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
91
122
  // Unwrapping `Stub`s allows calling with `Stubable` arguments.
92
123
  // For properties, rewrite types to be `Result`s.
93
124
  // In each case, unwrap `Promise`s.
94
- type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => IsAny<R> extends true ? UnknownResult : Result<Awaited<R>> : Result<Awaited<V>>; // Type for the callable part of an `Provider` if `T` is callable.
125
+ type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>; // Type for the callable part of an `Provider` if `T` is callable.
95
126
  // This is intersected with methods/properties.
96
127
  type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
97
128
  type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
@@ -109,6 +140,9 @@ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
109
140
  };
110
141
  type TupleProvider<T extends ReadonlyArray<unknown>> = { [K in TupleIndexKeys<T>]: MethodOrProperty<T[K]> } & ArrayProvider<T[number]>; // Base type for all other types providing RPC-like interfaces.
111
142
  // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
143
+ // `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
144
+ // stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
145
+ // `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
112
146
  type Provider<T> = MaybeCallableProvider<T> & (T extends ReadonlyArray<unknown> ? number extends T["length"] ? ArrayProvider<T[number]> : TupleProvider<T> : { [K in Exclude<keyof T, symbol | keyof StubBase<never>>]: MethodOrProperty<T[K]> } & {
113
147
  map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
114
148
  });
@@ -327,9 +361,21 @@ declare const RpcStub: {
327
361
  * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
328
362
  * if you only intend to use the promise for pipelining and you never await it, then there's no
329
363
  * need to transmit the resolution!
364
+ *
365
+ * You may also construct an `RpcPromise` yourself from a regular `Promise`, using
366
+ * `new RpcPromise(promise)`, allowing you to perform promise pipelining on a local promise. This
367
+ * is semantically identical to creating a local-loopback RPC that returns the promise, and then
368
+ * invoking it: pipelined calls wait until the promise resolves, then are delivered, in order, to
369
+ * the resolution. This is useful when you plan to obtain some stub in the future, but want to
370
+ * allow code to start queuing calls on it immediately. Note that the `RpcPromise` takes
371
+ * ownership of the resolution: disposing it disposes the resolution, so resolve the promise
372
+ * with a `dup()` if you also intend to keep the stub.
330
373
  */
331
374
  type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$1<T>;
332
- declare const RpcPromise: {};
375
+ declare const RpcPromise: {
376
+ new <T extends RpcCompatible<T>>(value: Promise<T>): RpcPromise$1<ElideStub<T>>;
377
+ new <T extends RpcCompatible<T>>(value: Promise<PayloadOrStub<T>>): RpcPromise$1<ElideStub<T>>;
378
+ };
333
379
  /**
334
380
  * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
335
381
  *
package/dist/index.d.ts CHANGED
@@ -20,7 +20,8 @@ interface RpcTargetBranded {
20
20
  // `never[]` preserves compatibility with strongly-typed function signatures without introducing
21
21
  // `any` into inference.
22
22
  type Stubable = RpcTargetBranded | ((...args: never[]) => unknown);
23
- type IsUnknown<T> = unknown extends T ? ([T] extends [unknown] ? true : false) : false; // Types that can be passed over RPC
23
+ // Note: also true for `any` (call sites that care check `IsAny` first).
24
+ type IsUnknown<T> = unknown extends T ? true : false; // Types that can be passed over RPC
24
25
  // The reason for using a generic type here is to build the serializable subset of RPC-compatible
25
26
  // composite types. This allows types defined with the "interface" keyword to pass the
26
27
  // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
@@ -42,8 +43,14 @@ type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | I
42
43
  type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | Blob | ReadableStream<any> // Chunk type can be any RPC-compatible type
43
44
  | WritableStream<any> // Chunk type can be any RPC-compatible type
44
45
  | URL | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
46
+ // Arm ordering matters here:
47
+ // - `Promise` must come before `StubBase`: `RpcPromise<T>` matches both, and must resolve
48
+ // through the Promise arm rather than pass through as-is.
49
+ // - `StubBase` must come before `Stubable`: `Stub<T>` of a callable `T` is itself callable, so
50
+ // it matches `Stubable`. Checking `StubBase` first keeps existing stubs as-is instead of
51
+ // double-wrapping them as `Stub<Stub<T>>`.
45
52
  // 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.
53
+ type Stubify<T> = T extends Promise<infer U> ? Stubify<U> : T extends StubBase<any> ? T : T extends Stubable ? Stub<T> : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>> : T extends Set<infer V> ? Set<Stubify<V>> : T extends [] ? [] : T extends [infer Head, ...infer Tail] ? [Stubify<Head>, ...Stubify<Tail>] : T extends readonly [] ? readonly [] : T extends readonly [infer Head, ...infer Tail] ? readonly [Stubify<Head>, ...Stubify<Tail>] : T extends Array<infer V> ? Array<Stubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>> : T extends BaseType ? T // When using "unknown" instead of "any", interfaces are not stubified.
47
54
  : T extends {
48
55
  [key: string | number]: any;
49
56
  } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
@@ -76,6 +83,24 @@ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // The type b
76
83
  // same type arguments, the checker short-circuits on identity instead of recursing through the
77
84
  // full structural comparison of these mutually-recursive types.
78
85
  type RpcPromise$1<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & StubBase<T> : Promise<Stubify<T> & MaybeDisposable<T>> & Provider<T> & StubBase<T>;
86
+ // The elision `Result` applies to a bare stub type: unwrap `Stub<T>` back to `T` when the
87
+ // payload is `Stubable`. Such stubs await back to a stub either way, so eliding keeps a
88
+ // declared `Promise<RpcStub<T>>` return interchangeable with a `Promise<T>` return.
89
+ // Plain-interface stubs are NOT elided: `RpcPromise<U>` only awaits to `Stub<U>` when
90
+ // `U extends Stubable`, so eliding those would change the awaited type from a stub to a
91
+ // stubified record. The payload check is deliberately non-distributive (`[U] extends [...]`).
92
+ // `Stub<any>` is not elided either: `[any] extends [Stubable]` is true, so without the `IsAny`
93
+ // guard an `any`-payload stub would lose its stub surface.
94
+ // Also used by the `RpcPromise` constructor signature (index.ts), which applies exactly this
95
+ // transformation so constructing from a promised stub matches the method-return type.
96
+ type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
97
+ // What the promise given to `new RpcPromise<T>(...)` may resolve to: the payload itself, or —
98
+ // for stubable payloads — a stub of it. `NoInfer` keeps the stub arm out of inference, so an
99
+ // inferred `T` is always the promise's own resolution type; the arm only matters when `T` is
100
+ // explicitly annotated (`new RpcPromise<Counter>(promiseOfStub)`). Stubs of non-stubable
101
+ // payloads are deliberately rejected: `ElideStub` wouldn't elide those, so accepting one would
102
+ // claim the promise awaits to a stubified record while the runtime resolves to a stub.
103
+ type PayloadOrStub<T> = T | NoInfer<Stub<Extract<T, Stubable>>>;
79
104
  // Type for method return or property on an RPC interface.
80
105
  // - Stubable types are replaced by stubs.
81
106
  // - RpcCompatible types are passed by value, with stubable types replaced by stubs
@@ -84,14 +109,20 @@ type RpcPromise$1<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & Stu
84
109
  // Technically, we use custom thenables here, but they quack like `Promise`s.
85
110
  // Intersecting with `(Maybe)Provider` allows pipelining.
86
111
  // prettier-ignore
87
- type Result<R> = IsAny<R> extends true ? UnknownResult : IsUnknown<R> extends true ? UnknownResult : R extends Stubable ? RpcPromise$1<R> : R extends RpcCompatible<R> ? RpcPromise$1<R> : never;
88
- type IsAny<T> = 0 extends (1 & T) ? true : false;
89
- type UnknownResult = Promise<unknown> & Provider<unknown> & StubBase<unknown>; // Type for method or property on an RPC interface.
112
+ type Result<R> = IsAny<R> extends true ? RpcPromise$1<unknown> // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
113
+ // `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
114
+ : R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
115
+ // here: anything matching our `StubBase` was produced by machinery that already enforced
116
+ // the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
117
+ // `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
118
+ // types.
119
+ : R extends StubBase<any> ? RpcPromise$1<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$1<R> : never;
120
+ type IsAny<T> = 0 extends (1 & T) ? true : false; // Type for method or property on an RPC interface.
90
121
  // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
91
122
  // Unwrapping `Stub`s allows calling with `Stubable` arguments.
92
123
  // For properties, rewrite types to be `Result`s.
93
124
  // In each case, unwrap `Promise`s.
94
- type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => IsAny<R> extends true ? UnknownResult : Result<Awaited<R>> : Result<Awaited<V>>; // Type for the callable part of an `Provider` if `T` is callable.
125
+ type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>; // Type for the callable part of an `Provider` if `T` is callable.
95
126
  // This is intersected with methods/properties.
96
127
  type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
97
128
  type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
@@ -109,6 +140,9 @@ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
109
140
  };
110
141
  type TupleProvider<T extends ReadonlyArray<unknown>> = { [K in TupleIndexKeys<T>]: MethodOrProperty<T[K]> } & ArrayProvider<T[number]>; // Base type for all other types providing RPC-like interfaces.
111
142
  // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
143
+ // `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
144
+ // stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
145
+ // `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
112
146
  type Provider<T> = MaybeCallableProvider<T> & (T extends ReadonlyArray<unknown> ? number extends T["length"] ? ArrayProvider<T[number]> : TupleProvider<T> : { [K in Exclude<keyof T, symbol | keyof StubBase<never>>]: MethodOrProperty<T[K]> } & {
113
147
  map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
114
148
  });
@@ -327,9 +361,21 @@ declare const RpcStub: {
327
361
  * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
328
362
  * if you only intend to use the promise for pipelining and you never await it, then there's no
329
363
  * need to transmit the resolution!
364
+ *
365
+ * You may also construct an `RpcPromise` yourself from a regular `Promise`, using
366
+ * `new RpcPromise(promise)`, allowing you to perform promise pipelining on a local promise. This
367
+ * is semantically identical to creating a local-loopback RPC that returns the promise, and then
368
+ * invoking it: pipelined calls wait until the promise resolves, then are delivered, in order, to
369
+ * the resolution. This is useful when you plan to obtain some stub in the future, but want to
370
+ * allow code to start queuing calls on it immediately. Note that the `RpcPromise` takes
371
+ * ownership of the resolution: disposing it disposes the resolution, so resolve the promise
372
+ * with a `dup()` if you also intend to keep the stub.
330
373
  */
331
374
  type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$1<T>;
332
- declare const RpcPromise: {};
375
+ declare const RpcPromise: {
376
+ new <T extends RpcCompatible<T>>(value: Promise<T>): RpcPromise$1<ElideStub<T>>;
377
+ new <T extends RpcCompatible<T>>(value: Promise<PayloadOrStub<T>>): RpcPromise$1<ElideStub<T>>;
378
+ };
333
379
  /**
334
380
  * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
335
381
  *
package/dist/index.js CHANGED
@@ -90,7 +90,14 @@ let streamImpl = {
90
90
  };
91
91
  var StubHook = class {
92
92
  stream(path, args) {
93
- let pulled = this.call(path, args).pull();
93
+ let hook = this.call(path, args);
94
+ let pulled;
95
+ try {
96
+ pulled = hook.pull();
97
+ } catch (err) {
98
+ hook.dispose();
99
+ throw err;
100
+ }
94
101
  let promise;
95
102
  if (pulled instanceof Promise) promise = pulled.then((p) => {
96
103
  p.dispose();
@@ -109,9 +116,11 @@ var ErrorStubHook = class extends StubHook {
109
116
  this.error = error;
110
117
  }
111
118
  call(path, args) {
119
+ args.dispose();
112
120
  return this;
113
121
  }
114
122
  map(path, captures, instructions) {
123
+ for (let cap of captures) cap.dispose();
115
124
  return this;
116
125
  }
117
126
  get(path) {
@@ -235,7 +244,25 @@ var RpcStub$1 = class RpcStub$1 extends RpcTarget$1 {
235
244
  };
236
245
  var RpcPromise$1 = class extends RpcStub$1 {
237
246
  constructor(hook, pathIfPromise) {
238
- super(hook, pathIfPromise);
247
+ if (hook instanceof StubHook) super(hook, pathIfPromise ?? []);
248
+ else {
249
+ if (pathIfPromise !== void 0) throw new TypeError("RpcPromise constructor expected one argument, received two.");
250
+ let kind = typeForRpc(hook);
251
+ if (kind === "rpc-promise") {
252
+ let raw = unwrapStubAndPath(hook);
253
+ if (raw.pathIfPromise.length > 0) super(raw.hook, raw.pathIfPromise);
254
+ else {
255
+ let adopted = raw.hook;
256
+ raw.hook = DISPOSED_HOOK;
257
+ super(adopted, []);
258
+ }
259
+ } else if (kind === "rpc-thenable") super(TargetStubHook.create(hook, void 0), []);
260
+ else {
261
+ let promiseHook = new PromiseStubHook(Promise.resolve(hook).then((value) => new PayloadStubHook(RpcPayload.fromAppReturn(value))));
262
+ promiseHook.ignoreUnhandledRejections();
263
+ super(promiseHook, []);
264
+ }
265
+ }
239
266
  }
240
267
  then(onfulfilled, onrejected) {
241
268
  return pullPromise(this).then(...arguments);
@@ -775,17 +802,22 @@ function followPath(value, parent, path, owner) {
775
802
  }
776
803
  var ValueStubHook = class extends StubHook {
777
804
  call(path, args) {
805
+ let followResult;
778
806
  try {
779
807
  let { value, owner } = this.getValue();
780
- let followResult = followPath(value, void 0, path, owner);
781
- if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
782
- if (typeof followResult.value != "function") throw new TypeError(`'${path.join(".")}' is not a function.`);
783
- return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {
784
- return new PayloadStubHook(payload);
785
- }));
808
+ followResult = followPath(value, void 0, path, owner);
786
809
  } catch (err) {
810
+ args.dispose();
787
811
  return new ErrorStubHook(err);
788
812
  }
813
+ if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
814
+ if (typeof followResult.value != "function") {
815
+ args.dispose();
816
+ return new ErrorStubHook(/* @__PURE__ */ new TypeError(`'${path.join(".")}' is not a function.`));
817
+ }
818
+ return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {
819
+ return new PayloadStubHook(payload);
820
+ }));
789
821
  }
790
822
  map(path, captures, instructions) {
791
823
  try {
@@ -806,7 +838,10 @@ var ValueStubHook = class extends StubHook {
806
838
  get(path) {
807
839
  try {
808
840
  let { value, owner } = this.getValue();
809
- if (path.length === 0 && owner === null) throw new Error("Can't dup an RpcTarget stub as a promise.");
841
+ if (path.length === 0 && owner === null) {
842
+ if (value instanceof Object && "then" in value) return this.dup();
843
+ throw new Error("Can't dup an RpcTarget stub as a promise.");
844
+ }
810
845
  let followResult = followPath(value, void 0, path, owner);
811
846
  if (followResult.hook) return followResult.hook.get(followResult.remainingPath);
812
847
  return new PayloadStubHook(RpcPayload.deepCopyFrom(followResult.value, followResult.parent, followResult.owner));
@@ -909,7 +944,10 @@ var TargetStubHook = class TargetStubHook extends ValueStubHook {
909
944
  this.target = void 0;
910
945
  }
911
946
  }
912
- onBroken(callback) {}
947
+ onBroken(callback) {
948
+ let target = this.target;
949
+ if (target && "then" in target) Promise.resolve(target).then(() => {}, callback);
950
+ }
913
951
  };
914
952
  var PromiseStubHook = class PromiseStubHook extends StubHook {
915
953
  promise;
@@ -923,12 +961,16 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
923
961
  }
924
962
  call(path, args) {
925
963
  args.ensureDeepCopied();
926
- return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));
964
+ return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args), (err) => {
965
+ args.dispose();
966
+ throw err;
967
+ }));
927
968
  }
928
969
  stream(path, args) {
929
970
  args.ensureDeepCopied();
930
- return { promise: this.promise.then((hook) => {
931
- return hook.stream(path, args).promise;
971
+ return { promise: this.promise.then((hook) => hook.stream(path, args).promise, (err) => {
972
+ args.dispose();
973
+ throw err;
932
974
  }) };
933
975
  }
934
976
  map(path, captures, instructions) {
@@ -955,10 +997,7 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
955
997
  }, (err) => {});
956
998
  }
957
999
  dispose() {
958
- if (this.resolution) this.resolution.dispose();
959
- else this.promise.then((hook) => {
960
- hook.dispose();
961
- }, (err) => {});
1000
+ this.promise.then((hook) => hook.dispose(), () => {});
962
1001
  }
963
1002
  onBroken(callback) {
964
1003
  if (this.resolution) this.resolution.onBroken(callback);
@@ -1787,24 +1826,28 @@ var RpcImportHook = class RpcImportHook extends StubHook {
1787
1826
  if (this.entry) return this.entry;
1788
1827
  else throw new Error("This RpcImportHook was already disposed.");
1789
1828
  }
1829
+ getEntryTakingOwnership(disposeOwned) {
1830
+ try {
1831
+ return this.getEntry();
1832
+ } catch (err) {
1833
+ disposeOwned();
1834
+ throw err;
1835
+ }
1836
+ }
1790
1837
  call(path, args) {
1791
- let entry = this.getEntry();
1838
+ let entry = this.getEntryTakingOwnership(() => args.dispose());
1792
1839
  if (entry.resolution) return entry.resolution.call(path, args);
1793
1840
  else return entry.session.sendCall(entry.importId, path, args);
1794
1841
  }
1795
1842
  stream(path, args) {
1796
- let entry = this.getEntry();
1843
+ let entry = this.getEntryTakingOwnership(() => args.dispose());
1797
1844
  if (entry.resolution) return entry.resolution.stream(path, args);
1798
1845
  else return entry.session.sendStream(entry.importId, path, args);
1799
1846
  }
1800
1847
  map(path, captures, instructions) {
1801
- let entry;
1802
- try {
1803
- entry = this.getEntry();
1804
- } catch (err) {
1848
+ let entry = this.getEntryTakingOwnership(() => {
1805
1849
  for (let cap of captures) cap.dispose();
1806
- throw err;
1807
- }
1850
+ });
1808
1851
  if (entry.resolution) return entry.resolution.map(path, captures, instructions);
1809
1852
  else return entry.session.sendMap(entry.importId, path, captures, instructions);
1810
1853
  }
@@ -2065,14 +2108,23 @@ var RpcSessionImpl = class {
2065
2108
  }
2066
2109
  }
2067
2110
  sendCall(id, path, args) {
2068
- if (this.abortReason) throw this.abortReason;
2111
+ if (this.abortReason) {
2112
+ args?.dispose();
2113
+ throw this.abortReason;
2114
+ }
2069
2115
  let value = [
2070
2116
  "pipeline",
2071
2117
  id,
2072
2118
  path
2073
2119
  ];
2074
2120
  if (args) {
2075
- let devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2121
+ let devalue;
2122
+ try {
2123
+ devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2124
+ } catch (err) {
2125
+ args.dispose();
2126
+ throw err;
2127
+ }
2076
2128
  value.push(devalue[0]);
2077
2129
  }
2078
2130
  this.send(["push", value]);
@@ -2081,13 +2133,22 @@ var RpcSessionImpl = class {
2081
2133
  return new RpcImportHook(true, entry);
2082
2134
  }
2083
2135
  sendStream(id, path, args) {
2084
- if (this.abortReason) throw this.abortReason;
2136
+ if (this.abortReason) {
2137
+ args.dispose();
2138
+ throw this.abortReason;
2139
+ }
2085
2140
  let value = [
2086
2141
  "pipeline",
2087
2142
  id,
2088
2143
  path
2089
2144
  ];
2090
- let devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2145
+ let devalue;
2146
+ try {
2147
+ devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2148
+ } catch (err) {
2149
+ args.dispose();
2150
+ throw err;
2151
+ }
2091
2152
  value.push(devalue[0]);
2092
2153
  let msg = ["stream", value];
2093
2154
  let size = this.send(msg);
@@ -2308,7 +2369,7 @@ var RpcSession$1 = class {
2308
2369
 
2309
2370
  //#endregion
2310
2371
  //#region src/websocket.ts
2311
- /** Close-frame reason max UTF-8 bytes: 125 payload − 2-byte status (RFC 6455 §5.5). */
2372
+ /** Close-frame reason max UTF-8 bytes: 125 payload - 2-byte status (RFC 6455 section 5.5). */
2312
2373
  const MAX_CLOSE_REASON_BYTES = 123;
2313
2374
  function newWebSocketRpcSession$1(webSocket, localMain, options) {
2314
2375
  if (typeof webSocket === "string") webSocket = new WebSocket(webSocket);
@@ -2718,9 +2779,11 @@ var MapVariableHook = class extends StubHook {
2718
2779
  else throwMapperBuilderUseError();
2719
2780
  }
2720
2781
  call(path, args) {
2782
+ args.dispose();
2721
2783
  throwMapperBuilderUseError();
2722
2784
  }
2723
2785
  map(path, captures, instructions) {
2786
+ for (let cap of captures) cap.dispose();
2724
2787
  throwMapperBuilderUseError();
2725
2788
  }
2726
2789
  pull() {
@@ -2831,13 +2894,11 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2831
2894
  let state = this.getState();
2832
2895
  if (path.length !== 1 || typeof path[0] !== "string") throw new Error("WritableStream stub only supports direct method calls");
2833
2896
  const method = path[0];
2834
- if (method !== "write" && method !== "close" && method !== "abort") {
2835
- args.dispose();
2836
- throw new Error(`Unknown WritableStream method: ${method}`);
2837
- }
2897
+ if (method !== "write" && method !== "close" && method !== "abort") throw new Error(`Unknown WritableStream method: ${method}`);
2838
2898
  if (method === "close" || method === "abort") state.closed = true;
2839
2899
  return new PromiseStubHook((method === "write" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer)).then((payload) => new PayloadStubHook(payload)));
2840
2900
  } catch (err) {
2901
+ args.dispose();
2841
2902
  return new ErrorStubHook(err);
2842
2903
  }
2843
2904
  }