@orpc/shared 2.0.0-beta.3 → 2.0.0-beta.31

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.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { Promisable } from 'type-fest';
2
- export { IsEqual, PartialDeep, Promisable, Writable } from 'type-fest';
1
+ import { Arrayable, Promisable } from 'type-fest';
2
+ export { Arrayable, IsEqual, PartialDeep, Promisable, Writable } from 'type-fest';
3
3
  import { Tracer, TraceAPI, ContextAPI, PropagationAPI, SpanOptions, Context, Span, AttributeValue, Exception } from '@opentelemetry/api';
4
4
  import { AsyncIteratorClass } from '@standardserver/shared';
5
- export { AbortError, AsyncCleanupFn, AsyncIteratorClass, AsyncIteratorClassNextFn, SequentialIdGenerator, getOrBind, isAsyncIteratorObject, isTypescriptObject, parseEmptyableJSON, sleep, stringifyJSON, toArray } from '@standardserver/shared';
5
+ export { AbortError, AsyncCleanupFn, AsyncIteratorClass, AsyncIteratorClassNextFn, SequentialIdGenerator, getOrBind, isAsyncIteratorObject, isTypescriptObject, parseEmptyableJSON, sequential, sleep, stringifyJSON, toArray } from '@standardserver/shared';
6
6
 
7
7
  type MaybeOptionalOptions<TOptions> = object extends TOptions ? [options?: TOptions] : [options: TOptions];
8
8
  declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>): T;
@@ -14,13 +14,13 @@ declare function splitInHalf<T>(arr: readonly T[]): [T[], T[]];
14
14
  *
15
15
  * Prefers the newer `.bytes` method when available as it more efficient but not widely supported yet.
16
16
  */
17
- declare function loadBytes(source: Pick<Blob, 'arrayBuffer' | 'bytes'>): Promise<Uint8Array<ArrayBuffer>>;
17
+ declare function loadBytes(source: Pick<Blob, 'arrayBuffer' | 'bytes'>): ReturnType<Blob['bytes']>;
18
18
  /**
19
19
  * Normalize text or binary-like inputs to either:
20
20
  * - the original string value, or
21
21
  * - a Uint8Array view over the source bytes.
22
22
  */
23
- declare function toStringOrBytes(source: string | ArrayBuffer | Blob | Exclude<ConstructorParameters<typeof Blob>[0], undefined>[0][] | Pick<Uint8Array<ArrayBuffer>, 'buffer' | 'byteOffset' | 'byteLength'>): Promise<string | Uint8Array<ArrayBuffer>>;
23
+ declare function toStringOrBytes(source: Arrayable<string | ArrayBuffer | Pick<Uint8Array<ArrayBuffer>, 'buffer' | 'byteOffset' | 'byteLength'>>): string | Awaited<ReturnType<Blob['bytes']>>;
24
24
 
25
25
  declare function isDeepEqual(a: unknown, b: unknown): boolean;
26
26
 
@@ -41,6 +41,23 @@ declare function normalizeHttpPath(path: string): `/${string}`;
41
41
  declare function mergeHttpPath(a: `/${string}`, b: `/${string}`): `/${string}`;
42
42
  declare function matchesHttpPathPrefix(url: `/${string}`, prefix: `/${string}`): boolean;
43
43
  declare function matchesHttpPath(url: `/${string}`, path: `/${string}`): boolean;
44
+ /**
45
+ * Parse Accept-Encoding into each coding's q-value, where `0` means the coding is explicitly
46
+ * unacceptable. The `*` wildcard is kept under its own key, so a caller can honour it while
47
+ * still letting a specific coding take precedence over it.
48
+ *
49
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-accept-encoding
50
+ */
51
+ declare function parseAcceptEncodingQualities(header: string | undefined): Map<string, number>;
52
+ /**
53
+ * Add `accept-encoding` to a Vary header value. The encoding is chosen from the request, so a
54
+ * shared cache must key on it or it will hand a compressed body to a client that cannot decode it.
55
+ *
56
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-vary
57
+ */
58
+ declare function varyByAcceptEncoding(vary: string | undefined): string;
59
+ declare function isNoTransformCacheControl(cacheControl: string | undefined): boolean;
60
+ declare function isCompressibleContentType(contentType: string | null | undefined): boolean;
44
61
 
45
62
  /**
46
63
  * Compares two sequential IDs.
@@ -90,7 +107,10 @@ declare function onSuccess<T, TOptions extends {
90
107
  next: () => any;
91
108
  }, TRest extends any[]>(callback: NoInfer<(result: Awaited<ReturnType<TOptions['next']>>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
92
109
  /**
93
- * Can used for interceptors or middlewares
110
+ * Creates an interceptor or middleware that invokes a callback whenever an error
111
+ * is thrown. The error is rethrown after the callback completes.
112
+ *
113
+ * @see {@link https://orpc.dev/docs/adapters/fetch-api | Fetch API Adapter}
94
114
  */
95
115
  declare function onError<T, TOptions extends {
96
116
  next: () => any;
@@ -102,6 +122,30 @@ type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess
102
122
  declare function onFinish<T, TOptions extends {
103
123
  next: () => any;
104
124
  }, TRest extends any[]>(callback: NoInfer<(state: OnFinishState<Awaited<ReturnType<TOptions['next']>>, ReturnType<TOptions['next']> extends PromiseWithError<any, infer E> ? E : ThrowableError>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
125
+ /**
126
+ * Creates a middleware or interceptor that invokes a callback when the returned async
127
+ * iterator object throws an error while being consumed.
128
+ *
129
+ * This does not replace the `onError`. `onError` only fires on the
130
+ * initial call (before the interceptor returns the iterator), whereas this
131
+ * callback only fires while consuming the iterator. Use both together to
132
+ * catch all possible errors.
133
+ */
134
+ declare function onAsyncIteratorObjectError<T, TOptions extends {
135
+ next: () => any;
136
+ }, TRest extends any[]>(callback: NoInfer<(error: ThrowableError | (ReturnType<TOptions['next']> extends PromiseWithError<any, infer E> ? E : ThrowableError), options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
137
+ /**
138
+ * Creates an interceptor that invokes a callback when the returned readable
139
+ * stream errors while being consumed.
140
+ *
141
+ * This does not replace the `onError`. `onError` only fires on the
142
+ * initial call (before the interceptor returns the stream), whereas this
143
+ * callback only fires while consuming the stream. Use both together to catch
144
+ * all possible errors.
145
+ */
146
+ declare function onReadableStreamError<T, TOptions extends {
147
+ next: () => any;
148
+ }, TRest extends any[]>(callback: NoInfer<(error: ThrowableError | (ReturnType<TOptions['next']> extends PromiseWithError<any, infer E> ? E : ThrowableError), options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
105
149
  declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: undefined | Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
106
150
 
107
151
  /**
@@ -147,8 +191,8 @@ interface WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>
147
191
  */
148
192
  runWith?: <T>(run: () => Promise<T>) => Promise<T>;
149
193
  mapResult?: (result: IteratorResult<TYield, TReturn>) => Promisable<IteratorResult<TMappedYield, TMappedReturn>>;
150
- mapError?: (error: unknown) => Promisable<unknown>;
151
- onError?: (error: unknown) => Promisable<void>;
194
+ mapError?: (error: ThrowableError) => Promisable<ThrowableError>;
195
+ onError?: (error: ThrowableError) => Promisable<void>;
152
196
  /**
153
197
  * Execute after the stream finishes or is cancelled.
154
198
  */
@@ -157,6 +201,40 @@ interface WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>
157
201
  declare function wrapAsyncIterator<TYield, TReturn, TMappedYield = TYield, TMappedReturn = TReturn>(iterator: AsyncIterator<TYield, TReturn>, { runWith, mapResult, mapError, onError, onFinish }: WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>): NoInfer<AsyncIteratorClass<TMappedYield, TMappedReturn>>;
158
202
  declare function traceAsyncIterator<T, TReturn, TNext>(options: StartSpanOptions | string, iterator: AsyncIterator<T, TReturn, TNext>): AsyncIteratorClass<T, TReturn, TNext>;
159
203
  declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorClass<T, TReturn, TNext>)[];
204
+ interface ConsumeAsyncIteratorOptions<T, TReturn, TError> {
205
+ /**
206
+ * Called on each event
207
+ */
208
+ onEvent: (event: T) => void;
209
+ /**
210
+ * Called once error happens
211
+ */
212
+ onError?: (error: TError) => void;
213
+ /**
214
+ * Called once AsyncIteratorObject is done
215
+ *
216
+ * @remarks
217
+ * **Note**: If iterator is canceled, `undefined` can be passed on success
218
+ */
219
+ onSuccess?: (value: TReturn | undefined) => void;
220
+ /**
221
+ * Called once after onError or onSuccess
222
+ *
223
+ * @remarks
224
+ * **Note**: If iterator is canceled, `undefined` can be passed on success
225
+ */
226
+ onFinish?: (state: [error: TError, data: undefined, isSuccess: false] | [error: null, data: TReturn | undefined, isSuccess: true]) => void;
227
+ }
228
+ /**
229
+ * Consumes an AsyncIteratorObject with lifecycle callbacks.
230
+ *
231
+ * @remarks
232
+ * **Warning**: If no `onError` or `onFinish` is provided, errors are thrown into the unhandled rejection channel.
233
+ *
234
+ * @returns An unsubscribe callback that stops consuming and cleans up the iterator.
235
+ * @see {@link https://orpc.dev/docs/client/async-iterator-object#using-consumeasynciterator | AsyncIteratorObject in Client - Using consumeAsyncIterator}
236
+ */
237
+ declare function consumeAsyncIterator<T, TReturn, TError = ThrowableError>(iterator: AsyncIterator<T, TReturn> | PromiseWithError<AsyncIterator<T, TReturn>, TError>, options: ConsumeAsyncIteratorOptions<T, TReturn, TError | ThrowableError>): () => Promise<void>;
160
238
 
161
239
  type Segment = string | number;
162
240
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
@@ -168,16 +246,27 @@ declare function findDeepMatches(check: (value: unknown) => boolean, payload: un
168
246
  *
169
247
  */
170
248
  declare function getConstructor(value: unknown): Function | null | undefined;
249
+ declare function getConstructors(value: unknown): Generator<Function>;
171
250
  /**
172
251
  * Checks whether a value is a plain object, including objects created with
173
252
  * `Object.create(null)`.
174
253
  */
175
254
  declare function isPlainObject(value: unknown): value is Record<PropertyKey, unknown>;
255
+ /**
256
+ * Returns `object[key]` only when it is an own property, so keys like
257
+ * `toString` do not resolve through the prototype chain.
258
+ */
259
+ declare function getOwn<T extends object>(object: T, key: PropertyKey): T[keyof T] | undefined;
176
260
  declare function get(object: unknown, path: readonly PropertyKey[]): unknown;
177
261
  /**
178
262
  * Sets a value at the given path, creating plain objects for intermediate keys as needed.
179
263
  */
180
264
  declare function set(root: object, path: [PropertyKey, ...PropertyKey[]] | [...PropertyKey[], PropertyKey], value: unknown): void;
265
+ /**
266
+ * Merges two values by copying the second over the first, repeating the merge one level deeper for
267
+ * nested plain objects. Anything that is not a pair of plain objects is replaced by the second one.
268
+ */
269
+ declare function mergeTwoLevels(first: unknown, second: unknown): unknown;
181
270
  declare function omit<T extends object, K extends keyof T>(obj: T, keys: readonly K[]): Omit<T, K>;
182
271
  declare function clone<T>(value: T): T;
183
272
  declare function isPropertyKey(value: unknown): value is PropertyKey;
@@ -191,7 +280,9 @@ declare const NullProtoObj: ({
191
280
  * Methods are collected from both the object itself and its prototype chain
192
281
  * (excluding `Object.prototype` and the `constructor` property).
193
282
  */
194
- declare function bindMethods<T extends object>(obj: T): Pick<T, {
283
+ declare function bindMethods<T extends object>(obj: T, options?: {
284
+ unbound?: (keyof T)[];
285
+ }): Pick<T, {
195
286
  [K in keyof T]: T[K] extends AnyFunction ? K : never;
196
287
  }[keyof T]>;
197
288
 
@@ -257,6 +348,11 @@ declare class AsyncIdQueue<T> {
257
348
  * Returns a signal that aborts only after all provided signals are aborted.
258
349
  */
259
350
  declare function allAbortSignal(signals: readonly (AbortSignal | undefined)[]): AbortSignal | undefined;
351
+ /**
352
+ * Returns a signal that aborts as soon as any of the provided signals aborts,
353
+ * with the same abort reason.
354
+ */
355
+ declare function anyAbortSignal(signals: readonly (AbortSignal | undefined)[]): AbortSignal | undefined;
260
356
  declare function runWithSignal<T>(signal: AbortSignal | undefined, fn: () => Promise<T>): Promise<T>;
261
357
 
262
358
  declare function replicateReadableStream<T>(stream: ReadableStream<T>, count: number): ReadableStream<T>[];
@@ -265,7 +361,7 @@ type ReadableStreamReadResult<T> = {
265
361
  value: T;
266
362
  } | {
267
363
  done: true;
268
- value: undefined | T;
364
+ value?: undefined | T;
269
365
  };
270
366
  interface WrapReadableStreamOptions<T, TMapped> {
271
367
  /**
@@ -275,8 +371,8 @@ interface WrapReadableStreamOptions<T, TMapped> {
275
371
  */
276
372
  runWith?: <T>(run: () => Promise<T>) => Promise<T>;
277
373
  mapResult?: (result: ReadableStreamReadResult<T>) => Promisable<ReadableStreamReadResult<TMapped>>;
278
- mapError?: (error: unknown) => Promisable<unknown>;
279
- onError?: (error: unknown) => Promisable<void>;
374
+ mapError?: (error: ThrowableError) => Promisable<ThrowableError>;
375
+ onError?: (error: ThrowableError) => Promisable<void>;
280
376
  /**
281
377
  * Guaranteed to execute exactly once after the stream finishes or is cancelled.
282
378
  */
@@ -285,9 +381,11 @@ interface WrapReadableStreamOptions<T, TMapped> {
285
381
  declare function wrapReadableStream<T, TMapped = T>(stream: ReadableStream<T>, { runWith, mapResult, mapError, onError, onFinish }: WrapReadableStreamOptions<T, TMapped>): NoInfer<ReadableStream<TMapped>>;
286
382
  declare function traceReadableStream<T>(options: StartSpanOptions | string, stream: ReadableStream<T>): ReadableStream<T>;
287
383
  /**
288
- * Converts a `ReadableStream` into an `AsyncIteratorClass`.
384
+ * Converts a {@link ReadableStream} into an {@link AsyncIteratorClass}.
385
+ *
386
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk | AI SDK Integration}
289
387
  */
290
- declare function streamToAsyncIteratorClass<T>(stream: ReadableStream<T>, { signal }?: {
388
+ declare function streamToAsyncIteratorObject<T>(stream: ReadableStream<T>, { signal }?: {
291
389
  signal?: undefined | AbortSignal;
292
390
  }): AsyncIteratorClass<T>;
293
391
  /**
@@ -297,10 +395,12 @@ declare function asyncIteratorToStream<T>(iterator: AsyncIterator<T>): ReadableS
297
395
  /**
298
396
  * Converts an `AsyncIterator` into a `ReadableStream`, ensuring that
299
397
  * all emitted object values are *unproxied* before enqueuing.
398
+ *
399
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk | AI SDK Integration}
300
400
  */
301
401
  declare function asyncIteratorToUnproxiedDataStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
302
402
 
303
403
  declare function tryDecodeURIComponent(value: string): string;
304
404
 
305
- export { AsyncIdQueue, NullProtoObj, ORPC_NAME, allAbortSignal, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, bindMethods, clone, compareSequentialIds, defer, findDeepMatches, get, getConstructor, getOpenTelemetryConfig, intercept, isAbortError, isDeepEqual, isPlainObject, isPropertyKey, loadBytes, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, normalizeHttpPath, omit, onError, onFinish, onStart, onSuccess, once, override, pathToHttpPath, promiseWithResolvers, recordSpanError, replicateAsyncIterator, replicateReadableStream, resolveMaybeOptionalOptions, runInSpanContext, runWithSignal, runWithSpan, set, setOpenTelemetryConfig, setSpanAttributeIfDefined, sortPlugins, splitInHalf, startSpan, streamToAsyncIteratorClass, toOtelException, toSpanAttributeValue, toStringOrBytes, traceAsyncIterator, traceReadableStream, tryDecodeURIComponent, tryOrUndefined, value, wrapAsyncIterator, wrapReadableStream };
306
- export type { AnyFunction, AsyncIdQueueCloseOptions, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OnFinishState, OpenTelemetryConfig, OrderablePlugin, PromiseWithError, Public, ReadableStreamReadResult, Registry, RunWithSpanOptions, Segment, StartSpanOptions, ThrowableError, Value, WrapAsyncIteratorOptions, WrapReadableStreamOptions };
405
+ export { AsyncIdQueue, NullProtoObj, ORPC_NAME, allAbortSignal, anyAbortSignal, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, bindMethods, clone, compareSequentialIds, consumeAsyncIterator, defer, findDeepMatches, get, getConstructor, getConstructors, getOpenTelemetryConfig, getOwn, intercept, isAbortError, isCompressibleContentType, isDeepEqual, isNoTransformCacheControl, isPlainObject, isPropertyKey, loadBytes, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, mergeTwoLevels, normalizeHttpPath, omit, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, once, override, parseAcceptEncodingQualities, pathToHttpPath, promiseWithResolvers, recordSpanError, replicateAsyncIterator, replicateReadableStream, resolveMaybeOptionalOptions, runInSpanContext, runWithSignal, runWithSpan, set, setOpenTelemetryConfig, setSpanAttributeIfDefined, sortPlugins, splitInHalf, startSpan, streamToAsyncIteratorObject, toOtelException, toSpanAttributeValue, toStringOrBytes, traceAsyncIterator, traceReadableStream, tryDecodeURIComponent, tryOrUndefined, value, varyByAcceptEncoding, wrapAsyncIterator, wrapReadableStream };
406
+ export type { AnyFunction, AsyncIdQueueCloseOptions, ConsumeAsyncIteratorOptions, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OnFinishState, OpenTelemetryConfig, OrderablePlugin, PromiseWithError, Public, ReadableStreamReadResult, Registry, RunWithSpanOptions, Segment, StartSpanOptions, ThrowableError, Value, WrapAsyncIteratorOptions, WrapReadableStreamOptions };