@temporary-name/shared 1.9.3-alpha.f9f5ce625d5edee78250b87b3a64f1d9760c2244 → 1.9.3-alpha.fb7e3a67f82deaeffad5063e136b2f3c03c4b5b3

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.mts CHANGED
@@ -1,156 +1,95 @@
1
- import { MaybeOptionalOptions as MaybeOptionalOptions$1, ThrowableError as ThrowableError$1 } from '@temporary-name/shared';
2
1
  import { Tracer, TraceAPI, ContextAPI, PropagationAPI, SpanOptions, Context, Span, AttributeValue, Exception } from '@opentelemetry/api';
3
2
  export { group, guard, mapEntries, mapValues, omit, retry, sleep } from 'radash';
3
+ export { OpenAPIV3_1 as OpenAPI } from 'openapi-types';
4
4
 
5
- type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
5
+ type MaybeOptionalOptions<TOptions> = object extends TOptions ? [options?: TOptions] : [options: TOptions];
6
+ type OptionalIfEmpty<TOptions> = {} extends TOptions ? [options?: TOptions] : [options: TOptions];
6
7
  declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>): T;
7
8
 
8
9
  declare function toArray<T>(value: T): T extends readonly any[] ? T : Exclude<T, undefined | null>[];
9
- declare function splitInHalf<T>(arr: readonly T[]): [T[], T[]];
10
10
 
11
- /**
12
- * Converts Request/Response/Blob/File/.. to a buffer (ArrayBuffer or Uint8Array).
13
- *
14
- * Prefers the newer `.bytes` method when available as it more efficient but not widely supported yet.
15
- */
16
- declare function readAsBuffer(source: Pick<Blob, 'arrayBuffer' | 'bytes'>): Promise<ArrayBuffer | Uint8Array>;
17
-
18
- type AnyFunction = (...args: any[]) => any;
19
- declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
20
- declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
21
- /**
22
- * Executes the callback function after the current call stack has been cleared.
23
- */
24
- declare function defer(callback: () => void): void;
25
-
26
- type OmitChainMethodDeep<T extends object, K extends keyof any> = {
27
- [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? (...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K> : T[P];
11
+ type StandardBody = undefined | unknown | Blob | URLSearchParams | FormData | AsyncIterator<unknown | void, unknown | void, undefined>;
12
+ interface StandardRequest {
13
+ method: string;
14
+ url: URL;
15
+ headers: Headers;
16
+ /**
17
+ * The body has been parsed based on the content-type header.
18
+ */
19
+ body: StandardBody;
20
+ signal: AbortSignal | undefined;
21
+ }
22
+ interface StandardLazyRequest extends Omit<StandardRequest, 'body'> {
23
+ /**
24
+ * The body has been parsed based on the content-type header.
25
+ * This method can safely call multiple times (cached).
26
+ */
27
+ body: () => Promise<StandardBody>;
28
+ }
29
+ interface StandardResponse {
30
+ status: number;
31
+ headers: Headers;
32
+ /**
33
+ * The body has been parsed based on the content-type header.
34
+ */
35
+ body: StandardBody;
36
+ }
37
+ interface StandardLazyResponse extends Omit<StandardResponse, 'body'> {
38
+ /**
39
+ * The body has been parsed based on the content-type header.
40
+ * This method can safely call multiple times (cached).
41
+ */
42
+ body: () => Promise<StandardBody>;
43
+ }
44
+ type HTTPPath = `/${string}`;
45
+ declare const HTTPMethods: readonly ["HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"];
46
+ type HTTPMethod = (typeof HTTPMethods)[number];
47
+ type HTTPEndpoint = `${HTTPMethod} ${HTTPPath}`;
48
+ type ClientContext = object;
49
+ interface ClientOptions<T extends ClientContext> {
50
+ request?: StandardLazyRequest;
51
+ signal?: AbortSignal;
52
+ lastEventId?: string | undefined;
53
+ context: T;
54
+ }
55
+ type FriendlyClientOptions<T extends ClientContext> = Omit<ClientOptions<T>, 'context'> & (object extends T ? {
56
+ context?: T;
57
+ } : {
58
+ context: T;
59
+ });
60
+ type ClientRest<TClientContext extends ClientContext, TInput> = object extends TClientContext ? undefined extends TInput ? [
61
+ input?: TInput,
62
+ options?: FriendlyClientOptions<TClientContext>
63
+ ] : [input: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options: FriendlyClientOptions<TClientContext>];
64
+ interface Client<TClientContext extends ClientContext, TInput, TOutput> {
65
+ (...rest: ClientRest<TClientContext, TInput>): Promise<TOutput>;
66
+ }
67
+ type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any> | {
68
+ [k: string]: NestedClient<TClientContext>;
28
69
  };
70
+ type InferClientContext<T extends NestedClient<any>> = T extends NestedClient<infer U> ? U : never;
71
+ interface ClientLink<TClientContext extends ClientContext> {
72
+ call: (path: readonly string[], input: unknown, options: ClientOptions<TClientContext>) => Promise<unknown>;
73
+ }
74
+ type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
75
+ type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
76
+ type InferAsyncIterableYield<T> = T extends AsyncIterable<infer U> ? U : never;
77
+ type IsEqual<A, B> = (<G>() => G extends (A & G) | G ? 1 : 2) extends <G>() => G extends (B & G) | G ? 1 : 2 ? true : false;
78
+ type Promisable<T> = T | PromiseLike<T>;
79
+
80
+ type OutputStructure = 'compact' | 'detailed';
81
+ interface ContractConfig {
82
+ defaultMethod: HTTPMethod;
83
+ defaultSuccessStatus: number;
84
+ defaultSuccessDescription: string;
85
+ defaultOutputStructure: OutputStructure;
86
+ }
87
+ declare function fallbackContractConfig<T extends keyof ContractConfig>(key: T, value: ContractConfig[T] | undefined): ContractConfig[T];
29
88
 
30
89
  declare const ORPC_NAME = "orpc";
31
90
  declare const ORPC_SHARED_PACKAGE_NAME = "@temporary-name/shared";
32
- declare const ORPC_SHARED_PACKAGE_VERSION = "1.9.3-alpha.f9f5ce625d5edee78250b87b3a64f1d9760c2244";
91
+ declare const ORPC_SHARED_PACKAGE_VERSION = "1.9.3-alpha.fb7e3a67f82deaeffad5063e136b2f3c03c4b5b3";
33
92
 
34
- declare const ORPC_CLIENT_PACKAGE_NAME = "__ORPC_CLIENT_PACKAGE_NAME_PLACEHOLDER__";
35
- declare const ORPC_CLIENT_PACKAGE_VERSION = "__ORPC_CLIENT_PACKAGE_VERSION_PLACEHOLDER__";
36
- declare const COMMON_ORPC_ERROR_DEFS: {
37
- readonly BAD_REQUEST: {
38
- readonly status: 400;
39
- readonly message: "Bad Request";
40
- };
41
- readonly UNAUTHORIZED: {
42
- readonly status: 401;
43
- readonly message: "Unauthorized";
44
- };
45
- readonly FORBIDDEN: {
46
- readonly status: 403;
47
- readonly message: "Forbidden";
48
- };
49
- readonly NOT_FOUND: {
50
- readonly status: 404;
51
- readonly message: "Not Found";
52
- };
53
- readonly METHOD_NOT_SUPPORTED: {
54
- readonly status: 405;
55
- readonly message: "Method Not Supported";
56
- };
57
- readonly NOT_ACCEPTABLE: {
58
- readonly status: 406;
59
- readonly message: "Not Acceptable";
60
- };
61
- readonly TIMEOUT: {
62
- readonly status: 408;
63
- readonly message: "Request Timeout";
64
- };
65
- readonly CONFLICT: {
66
- readonly status: 409;
67
- readonly message: "Conflict";
68
- };
69
- readonly PRECONDITION_FAILED: {
70
- readonly status: 412;
71
- readonly message: "Precondition Failed";
72
- };
73
- readonly PAYLOAD_TOO_LARGE: {
74
- readonly status: 413;
75
- readonly message: "Payload Too Large";
76
- };
77
- readonly UNSUPPORTED_MEDIA_TYPE: {
78
- readonly status: 415;
79
- readonly message: "Unsupported Media Type";
80
- };
81
- readonly UNPROCESSABLE_CONTENT: {
82
- readonly status: 422;
83
- readonly message: "Unprocessable Content";
84
- };
85
- readonly TOO_MANY_REQUESTS: {
86
- readonly status: 429;
87
- readonly message: "Too Many Requests";
88
- };
89
- readonly CLIENT_CLOSED_REQUEST: {
90
- readonly status: 499;
91
- readonly message: "Client Closed Request";
92
- };
93
- readonly INTERNAL_SERVER_ERROR: {
94
- readonly status: 500;
95
- readonly message: "Internal Server Error";
96
- };
97
- readonly NOT_IMPLEMENTED: {
98
- readonly status: 501;
99
- readonly message: "Not Implemented";
100
- };
101
- readonly BAD_GATEWAY: {
102
- readonly status: 502;
103
- readonly message: "Bad Gateway";
104
- };
105
- readonly SERVICE_UNAVAILABLE: {
106
- readonly status: 503;
107
- readonly message: "Service Unavailable";
108
- };
109
- readonly GATEWAY_TIMEOUT: {
110
- readonly status: 504;
111
- readonly message: "Gateway Timeout";
112
- };
113
- };
114
- type CommonORPCErrorCode = keyof typeof COMMON_ORPC_ERROR_DEFS;
115
- type ORPCErrorCode = CommonORPCErrorCode | (string & {});
116
- declare function fallbackORPCErrorStatus(code: ORPCErrorCode, status: number | undefined): number;
117
- declare function fallbackORPCErrorMessage(code: ORPCErrorCode, message: string | undefined): string;
118
- type ORPCErrorOptions<TData> = ErrorOptions & {
119
- defined?: boolean;
120
- status?: number;
121
- message?: string;
122
- } & (undefined extends TData ? {
123
- data?: TData;
124
- } : {
125
- data: TData;
126
- });
127
- declare class ORPCError<TCode extends ORPCErrorCode, TData> extends Error {
128
- readonly defined: boolean;
129
- readonly code: TCode;
130
- readonly status: number;
131
- readonly data: TData;
132
- constructor(code: TCode, ...rest: MaybeOptionalOptions$1<ORPCErrorOptions<TData>>);
133
- toJSON(): ORPCErrorJSON<TCode, TData>;
134
- /**
135
- * Workaround for Next.js where different contexts use separate
136
- * dependency graphs, causing multiple ORPCError constructors existing and breaking
137
- * `instanceof` checks across contexts.
138
- *
139
- * This is particularly problematic with "Optimized SSR", where orpc-client
140
- * executes in one context but is invoked from another. When an error is thrown
141
- * in the execution context, `instanceof ORPCError` checks fail in the
142
- * invocation context due to separate class constructors.
143
- *
144
- * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
145
- */
146
- static [Symbol.hasInstance](instance: unknown): boolean;
147
- }
148
- type ORPCErrorJSON<TCode extends string, TData> = Pick<ORPCError<TCode, TData>, 'defined' | 'code' | 'status' | 'message' | 'data'>;
149
- declare function isDefinedError<T>(error: T): error is Extract<T, ORPCError<any, any>>;
150
- declare function toORPCError(error: unknown): ORPCError<any, any>;
151
- declare function isORPCErrorStatus(status: number): boolean;
152
- declare function isORPCErrorJson(json: unknown): json is ORPCErrorJSON<ORPCErrorCode, unknown>;
153
- declare function createORPCErrorFromJson<TCode extends ORPCErrorCode, TData>(json: ORPCErrorJSON<TCode, TData>, options?: ErrorOptions): ORPCError<TCode, TData>;
154
93
  /**
155
94
  * Error thrown when an operation is aborted.
156
95
  * Uses the standardized 'AbortError' name for consistency with JavaScript APIs.
@@ -218,104 +157,14 @@ declare class EventPublisher<T extends Record<PropertyKey, any>> {
218
157
  subscribe<K extends keyof T>(event: K, options?: EventPublisherSubscribeIteratorOptions): AsyncGenerator<T[K]> & AsyncIteratorObject<T[K]>;
219
158
  }
220
159
 
221
- declare class SequentialIdGenerator {
222
- private index;
223
- generate(): string;
224
- }
225
-
226
- interface StandardHeaders {
227
- [key: string]: string | string[] | undefined;
228
- }
229
- type StandardBody = undefined | unknown | Blob | URLSearchParams | FormData | AsyncIterator<unknown | void, unknown | void, undefined>;
230
- interface StandardRequest {
231
- method: string;
232
- url: URL;
233
- headers: StandardHeaders;
234
- /**
235
- * The body has been parsed based on the content-type header.
236
- */
237
- body: StandardBody;
238
- signal: AbortSignal | undefined;
239
- }
240
- interface StandardLazyRequest extends Omit<StandardRequest, 'body'> {
241
- /**
242
- * The body has been parsed based on the content-type header.
243
- * This method can safely call multiple times (cached).
244
- */
245
- body: () => Promise<StandardBody>;
246
- }
247
- interface StandardResponse {
248
- status: number;
249
- headers: StandardHeaders;
250
- /**
251
- * The body has been parsed based on the content-type header.
252
- */
253
- body: StandardBody;
254
- }
255
- interface StandardLazyResponse extends Omit<StandardResponse, 'body'> {
256
- /**
257
- * The body has been parsed based on the content-type header.
258
- * This method can safely call multiple times (cached).
259
- */
260
- body: () => Promise<StandardBody>;
261
- }
262
- type HTTPPath = `/${string}`;
263
- declare const HTTPMethods: readonly ["HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"];
264
- type HTTPMethod = (typeof HTTPMethods)[number];
265
- type HTTPEndpoint = `${HTTPMethod} ${HTTPPath}`;
266
- type ClientContext = Record<PropertyKey, any>;
267
- interface ClientOptions<T extends ClientContext> {
268
- request?: StandardLazyRequest;
269
- signal?: AbortSignal;
270
- lastEventId?: string | undefined;
271
- context: T;
272
- }
273
- type FriendlyClientOptions<T extends ClientContext> = Omit<ClientOptions<T>, 'context'> & (Record<never, never> extends T ? {
274
- context?: T;
275
- } : {
276
- context: T;
277
- });
278
- type ClientRest<TClientContext extends ClientContext, TInput> = Record<never, never> extends TClientContext ? undefined extends TInput ? [
279
- input?: TInput,
280
- options?: FriendlyClientOptions<TClientContext>
281
- ] : [input: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options: FriendlyClientOptions<TClientContext>];
282
- type ClientPromiseResult<TOutput, TError> = PromiseWithError<TOutput, TError>;
283
- interface Client<TClientContext extends ClientContext, TInput, TOutput, TError> {
284
- (...rest: ClientRest<TClientContext, TInput>): ClientPromiseResult<TOutput, TError>;
285
- }
286
- type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | {
287
- [k: string]: NestedClient<TClientContext>;
288
- };
289
- type InferClientContext<T extends NestedClient<any>> = T extends NestedClient<infer U> ? U : never;
290
- interface ClientLink<TClientContext extends ClientContext> {
291
- call: (path: readonly string[], input: unknown, options: ClientOptions<TClientContext>) => Promise<unknown>;
292
- }
293
- type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
294
- type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
295
- type PromiseWithError<T, TError> = Promise<T> & {
296
- __error?: {
297
- type: TError;
298
- };
299
- };
160
+ type AnyFunction = (...args: any[]) => any;
161
+ declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
162
+ declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
300
163
  /**
301
- * The place where you can config the orpc types.
302
- *
303
- * - `throwableError` the error type that represent throwable errors should be `Error` or `null | undefined | {}` if you want more strict.
164
+ * Executes the callback function after the current call stack has been cleared.
304
165
  */
305
- interface Registry {
306
- }
307
- type ThrowableError = Registry extends {
308
- throwableError: infer T;
309
- } ? T : Error;
310
- type InferAsyncIterableYield<T> = T extends AsyncIterable<infer U> ? U : never;
311
- type IsEqual<A, B> = (<G>() => G extends (A & G) | G ? 1 : 2) extends <G>() => G extends (B & G) | G ? 1 : 2 ? true : false;
312
- type Promisable<T> = T | PromiseLike<T>;
166
+ declare function defer(callback: () => void): void;
313
167
 
314
- type InterceptableOptions = Record<string, any>;
315
- type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
316
- next(options?: TOptions): TResult;
317
- };
318
- type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult;
319
168
  /**
320
169
  * Can used for interceptors or middlewares
321
170
  */
@@ -333,15 +182,14 @@ declare function onSuccess<T, TOptions extends {
333
182
  */
334
183
  declare function onError<T, TOptions extends {
335
184
  next(): any;
336
- }, TRest extends any[]>(callback: NoInfer<(error: 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']>>>;
185
+ }, TRest extends any[]>(callback: NoInfer<(error: Error, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
337
186
  type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess: false] | [error: null, data: TResult, isSuccess: true];
338
187
  /**
339
188
  * Can used for interceptors or middlewares
340
189
  */
341
190
  declare function onFinish<T, TOptions extends {
342
191
  next(): any;
343
- }, 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']>>>;
344
- declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
192
+ }, TRest extends any[]>(callback: NoInfer<(state: OnFinishState<Awaited<ReturnType<TOptions['next']>>, Error>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
345
193
 
346
194
  /**
347
195
  * Only import types from @opentelemetry/api to avoid runtime dependencies.
@@ -473,17 +321,7 @@ declare const NullProtoObj: {
473
321
 
474
322
  type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
475
323
  declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
476
- /**
477
- * Returns the value if it is defined, otherwise returns the fallback
478
- */
479
- declare function fallback<T>(value: T | undefined, fallback: T): T;
480
324
 
481
- /**
482
- * Prevents objects from being awaitable by intercepting the `then` method
483
- * when called by the native await mechanism. This is useful for preventing
484
- * accidental awaiting of objects that aren't meant to be promises.
485
- */
486
- declare function preventNativeAwait<T extends object>(target: T): T;
487
325
  /**
488
326
  * Create a proxy that overlays one object (`overlay`) on top of another (`target`).
489
327
  *
@@ -519,30 +357,9 @@ declare function asyncIteratorToStream<T>(iterator: AsyncIterator<T>): ReadableS
519
357
 
520
358
  declare function tryDecodeURIComponent(value: string): string;
521
359
 
522
- type SafeResult<TOutput, TError> = ([error: null, data: TOutput, isDefined: false, isSuccess: true] & {
523
- error: null;
524
- data: TOutput;
525
- isDefined: false;
526
- isSuccess: true;
527
- }) | ([error: Exclude<TError, ORPCError<any, any>>, data: undefined, isDefined: false, isSuccess: false] & {
528
- error: Exclude<TError, ORPCError<any, any>>;
529
- data: undefined;
530
- isDefined: false;
531
- isSuccess: false;
532
- }) | ([error: Extract<TError, ORPCError<any, any>>, data: undefined, isDefined: true, isSuccess: false] & {
533
- error: Extract<TError, ORPCError<any, any>>;
534
- data: undefined;
535
- isDefined: true;
536
- isSuccess: false;
537
- });
538
- /**
539
- * Works like try/catch, but can infer error types.
540
- *
541
- * @info support both tuple `[error, data, isDefined, isSuccess]` and object `{ error, data, isDefined, isSuccess }` styles.
542
- * @see {@link https://orpc.unnoq.com/docs/client/error-handling Client Error Handling Docs}
543
- */
544
- declare function safe<TOutput, TError = ThrowableError$1>(promise: ClientPromiseResult<TOutput, TError>): Promise<SafeResult<TOutput, TError>>;
545
360
  declare function toHttpPath(path: readonly string[]): HTTPPath;
361
+ declare function splitFirst(str: string, separator: string): [string, string];
362
+ declare function assertNever(value: never, message?: string): never;
546
363
 
547
- export { AbortError, AsyncIdQueue, AsyncIteratorClass, COMMON_ORPC_ERROR_DEFS, EventPublisher, HTTPMethods, NullProtoObj, ORPCError, ORPC_CLIENT_PACKAGE_NAME, ORPC_CLIENT_PACKAGE_VERSION, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorWithSpan, clone, createORPCErrorFromJson, defer, fallback, fallbackORPCErrorMessage, fallbackORPCErrorStatus, findDeepMatches, get, getConstructor, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isDefinedError, isORPCErrorJson, isORPCErrorStatus, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, overlayProxy, parseEmptyableJSON, preventNativeAwait, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, safe, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitInHalf, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toHttpPath, toORPCError, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };
548
- export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, AsyncIteratorWithSpanOptions, Client, ClientContext, ClientLink, ClientOptions, ClientPromiseResult, ClientRest, CommonORPCErrorCode, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, FriendlyClientOptions, HTTPEndpoint, HTTPMethod, HTTPPath, InferAsyncIterableYield, InferClientContext, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, IsEqual, MaybeOptionalOptions, NestedClient, ORPCErrorCode, ORPCErrorJSON, ORPCErrorOptions, OmitChainMethodDeep, OnFinishState, OtelConfig, Promisable, PromiseWithError, Registry, RunWithSpanOptions, SafeResult, Segment, SetOptional, SetSpanErrorOptions, StandardBody, StandardHeaders, StandardLazyRequest, StandardLazyResponse, StandardRequest, StandardResponse, ThrowableError, Value };
364
+ export { AbortError, AsyncIdQueue, AsyncIteratorClass, EventPublisher, HTTPMethods, NullProtoObj, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, assertNever, asyncIteratorToStream, asyncIteratorWithSpan, clone, defer, fallbackContractConfig, findDeepMatches, get, getConstructor, getGlobalOtelConfig, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, overlayProxy, parseEmptyableJSON, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitFirst, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toHttpPath, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };
365
+ export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, AsyncIteratorWithSpanOptions, Client, ClientContext, ClientLink, ClientOptions, ClientRest, ContractConfig, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, FriendlyClientOptions, HTTPEndpoint, HTTPMethod, HTTPPath, InferAsyncIterableYield, InferClientContext, IntersectPick, IsEqual, MaybeOptionalOptions, NestedClient, OnFinishState, OptionalIfEmpty, OtelConfig, OutputStructure, Promisable, RunWithSpanOptions, Segment, SetOptional, SetSpanErrorOptions, StandardBody, StandardLazyRequest, StandardLazyResponse, StandardRequest, StandardResponse, Value };
package/dist/index.d.ts CHANGED
@@ -1,156 +1,95 @@
1
- import { MaybeOptionalOptions as MaybeOptionalOptions$1, ThrowableError as ThrowableError$1 } from '@temporary-name/shared';
2
1
  import { Tracer, TraceAPI, ContextAPI, PropagationAPI, SpanOptions, Context, Span, AttributeValue, Exception } from '@opentelemetry/api';
3
2
  export { group, guard, mapEntries, mapValues, omit, retry, sleep } from 'radash';
3
+ export { OpenAPIV3_1 as OpenAPI } from 'openapi-types';
4
4
 
5
- type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
5
+ type MaybeOptionalOptions<TOptions> = object extends TOptions ? [options?: TOptions] : [options: TOptions];
6
+ type OptionalIfEmpty<TOptions> = {} extends TOptions ? [options?: TOptions] : [options: TOptions];
6
7
  declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>): T;
7
8
 
8
9
  declare function toArray<T>(value: T): T extends readonly any[] ? T : Exclude<T, undefined | null>[];
9
- declare function splitInHalf<T>(arr: readonly T[]): [T[], T[]];
10
10
 
11
- /**
12
- * Converts Request/Response/Blob/File/.. to a buffer (ArrayBuffer or Uint8Array).
13
- *
14
- * Prefers the newer `.bytes` method when available as it more efficient but not widely supported yet.
15
- */
16
- declare function readAsBuffer(source: Pick<Blob, 'arrayBuffer' | 'bytes'>): Promise<ArrayBuffer | Uint8Array>;
17
-
18
- type AnyFunction = (...args: any[]) => any;
19
- declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
20
- declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
21
- /**
22
- * Executes the callback function after the current call stack has been cleared.
23
- */
24
- declare function defer(callback: () => void): void;
25
-
26
- type OmitChainMethodDeep<T extends object, K extends keyof any> = {
27
- [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? (...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K> : T[P];
11
+ type StandardBody = undefined | unknown | Blob | URLSearchParams | FormData | AsyncIterator<unknown | void, unknown | void, undefined>;
12
+ interface StandardRequest {
13
+ method: string;
14
+ url: URL;
15
+ headers: Headers;
16
+ /**
17
+ * The body has been parsed based on the content-type header.
18
+ */
19
+ body: StandardBody;
20
+ signal: AbortSignal | undefined;
21
+ }
22
+ interface StandardLazyRequest extends Omit<StandardRequest, 'body'> {
23
+ /**
24
+ * The body has been parsed based on the content-type header.
25
+ * This method can safely call multiple times (cached).
26
+ */
27
+ body: () => Promise<StandardBody>;
28
+ }
29
+ interface StandardResponse {
30
+ status: number;
31
+ headers: Headers;
32
+ /**
33
+ * The body has been parsed based on the content-type header.
34
+ */
35
+ body: StandardBody;
36
+ }
37
+ interface StandardLazyResponse extends Omit<StandardResponse, 'body'> {
38
+ /**
39
+ * The body has been parsed based on the content-type header.
40
+ * This method can safely call multiple times (cached).
41
+ */
42
+ body: () => Promise<StandardBody>;
43
+ }
44
+ type HTTPPath = `/${string}`;
45
+ declare const HTTPMethods: readonly ["HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"];
46
+ type HTTPMethod = (typeof HTTPMethods)[number];
47
+ type HTTPEndpoint = `${HTTPMethod} ${HTTPPath}`;
48
+ type ClientContext = object;
49
+ interface ClientOptions<T extends ClientContext> {
50
+ request?: StandardLazyRequest;
51
+ signal?: AbortSignal;
52
+ lastEventId?: string | undefined;
53
+ context: T;
54
+ }
55
+ type FriendlyClientOptions<T extends ClientContext> = Omit<ClientOptions<T>, 'context'> & (object extends T ? {
56
+ context?: T;
57
+ } : {
58
+ context: T;
59
+ });
60
+ type ClientRest<TClientContext extends ClientContext, TInput> = object extends TClientContext ? undefined extends TInput ? [
61
+ input?: TInput,
62
+ options?: FriendlyClientOptions<TClientContext>
63
+ ] : [input: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options: FriendlyClientOptions<TClientContext>];
64
+ interface Client<TClientContext extends ClientContext, TInput, TOutput> {
65
+ (...rest: ClientRest<TClientContext, TInput>): Promise<TOutput>;
66
+ }
67
+ type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any> | {
68
+ [k: string]: NestedClient<TClientContext>;
28
69
  };
70
+ type InferClientContext<T extends NestedClient<any>> = T extends NestedClient<infer U> ? U : never;
71
+ interface ClientLink<TClientContext extends ClientContext> {
72
+ call: (path: readonly string[], input: unknown, options: ClientOptions<TClientContext>) => Promise<unknown>;
73
+ }
74
+ type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
75
+ type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
76
+ type InferAsyncIterableYield<T> = T extends AsyncIterable<infer U> ? U : never;
77
+ type IsEqual<A, B> = (<G>() => G extends (A & G) | G ? 1 : 2) extends <G>() => G extends (B & G) | G ? 1 : 2 ? true : false;
78
+ type Promisable<T> = T | PromiseLike<T>;
79
+
80
+ type OutputStructure = 'compact' | 'detailed';
81
+ interface ContractConfig {
82
+ defaultMethod: HTTPMethod;
83
+ defaultSuccessStatus: number;
84
+ defaultSuccessDescription: string;
85
+ defaultOutputStructure: OutputStructure;
86
+ }
87
+ declare function fallbackContractConfig<T extends keyof ContractConfig>(key: T, value: ContractConfig[T] | undefined): ContractConfig[T];
29
88
 
30
89
  declare const ORPC_NAME = "orpc";
31
90
  declare const ORPC_SHARED_PACKAGE_NAME = "@temporary-name/shared";
32
- declare const ORPC_SHARED_PACKAGE_VERSION = "1.9.3-alpha.f9f5ce625d5edee78250b87b3a64f1d9760c2244";
91
+ declare const ORPC_SHARED_PACKAGE_VERSION = "1.9.3-alpha.fb7e3a67f82deaeffad5063e136b2f3c03c4b5b3";
33
92
 
34
- declare const ORPC_CLIENT_PACKAGE_NAME = "__ORPC_CLIENT_PACKAGE_NAME_PLACEHOLDER__";
35
- declare const ORPC_CLIENT_PACKAGE_VERSION = "__ORPC_CLIENT_PACKAGE_VERSION_PLACEHOLDER__";
36
- declare const COMMON_ORPC_ERROR_DEFS: {
37
- readonly BAD_REQUEST: {
38
- readonly status: 400;
39
- readonly message: "Bad Request";
40
- };
41
- readonly UNAUTHORIZED: {
42
- readonly status: 401;
43
- readonly message: "Unauthorized";
44
- };
45
- readonly FORBIDDEN: {
46
- readonly status: 403;
47
- readonly message: "Forbidden";
48
- };
49
- readonly NOT_FOUND: {
50
- readonly status: 404;
51
- readonly message: "Not Found";
52
- };
53
- readonly METHOD_NOT_SUPPORTED: {
54
- readonly status: 405;
55
- readonly message: "Method Not Supported";
56
- };
57
- readonly NOT_ACCEPTABLE: {
58
- readonly status: 406;
59
- readonly message: "Not Acceptable";
60
- };
61
- readonly TIMEOUT: {
62
- readonly status: 408;
63
- readonly message: "Request Timeout";
64
- };
65
- readonly CONFLICT: {
66
- readonly status: 409;
67
- readonly message: "Conflict";
68
- };
69
- readonly PRECONDITION_FAILED: {
70
- readonly status: 412;
71
- readonly message: "Precondition Failed";
72
- };
73
- readonly PAYLOAD_TOO_LARGE: {
74
- readonly status: 413;
75
- readonly message: "Payload Too Large";
76
- };
77
- readonly UNSUPPORTED_MEDIA_TYPE: {
78
- readonly status: 415;
79
- readonly message: "Unsupported Media Type";
80
- };
81
- readonly UNPROCESSABLE_CONTENT: {
82
- readonly status: 422;
83
- readonly message: "Unprocessable Content";
84
- };
85
- readonly TOO_MANY_REQUESTS: {
86
- readonly status: 429;
87
- readonly message: "Too Many Requests";
88
- };
89
- readonly CLIENT_CLOSED_REQUEST: {
90
- readonly status: 499;
91
- readonly message: "Client Closed Request";
92
- };
93
- readonly INTERNAL_SERVER_ERROR: {
94
- readonly status: 500;
95
- readonly message: "Internal Server Error";
96
- };
97
- readonly NOT_IMPLEMENTED: {
98
- readonly status: 501;
99
- readonly message: "Not Implemented";
100
- };
101
- readonly BAD_GATEWAY: {
102
- readonly status: 502;
103
- readonly message: "Bad Gateway";
104
- };
105
- readonly SERVICE_UNAVAILABLE: {
106
- readonly status: 503;
107
- readonly message: "Service Unavailable";
108
- };
109
- readonly GATEWAY_TIMEOUT: {
110
- readonly status: 504;
111
- readonly message: "Gateway Timeout";
112
- };
113
- };
114
- type CommonORPCErrorCode = keyof typeof COMMON_ORPC_ERROR_DEFS;
115
- type ORPCErrorCode = CommonORPCErrorCode | (string & {});
116
- declare function fallbackORPCErrorStatus(code: ORPCErrorCode, status: number | undefined): number;
117
- declare function fallbackORPCErrorMessage(code: ORPCErrorCode, message: string | undefined): string;
118
- type ORPCErrorOptions<TData> = ErrorOptions & {
119
- defined?: boolean;
120
- status?: number;
121
- message?: string;
122
- } & (undefined extends TData ? {
123
- data?: TData;
124
- } : {
125
- data: TData;
126
- });
127
- declare class ORPCError<TCode extends ORPCErrorCode, TData> extends Error {
128
- readonly defined: boolean;
129
- readonly code: TCode;
130
- readonly status: number;
131
- readonly data: TData;
132
- constructor(code: TCode, ...rest: MaybeOptionalOptions$1<ORPCErrorOptions<TData>>);
133
- toJSON(): ORPCErrorJSON<TCode, TData>;
134
- /**
135
- * Workaround for Next.js where different contexts use separate
136
- * dependency graphs, causing multiple ORPCError constructors existing and breaking
137
- * `instanceof` checks across contexts.
138
- *
139
- * This is particularly problematic with "Optimized SSR", where orpc-client
140
- * executes in one context but is invoked from another. When an error is thrown
141
- * in the execution context, `instanceof ORPCError` checks fail in the
142
- * invocation context due to separate class constructors.
143
- *
144
- * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
145
- */
146
- static [Symbol.hasInstance](instance: unknown): boolean;
147
- }
148
- type ORPCErrorJSON<TCode extends string, TData> = Pick<ORPCError<TCode, TData>, 'defined' | 'code' | 'status' | 'message' | 'data'>;
149
- declare function isDefinedError<T>(error: T): error is Extract<T, ORPCError<any, any>>;
150
- declare function toORPCError(error: unknown): ORPCError<any, any>;
151
- declare function isORPCErrorStatus(status: number): boolean;
152
- declare function isORPCErrorJson(json: unknown): json is ORPCErrorJSON<ORPCErrorCode, unknown>;
153
- declare function createORPCErrorFromJson<TCode extends ORPCErrorCode, TData>(json: ORPCErrorJSON<TCode, TData>, options?: ErrorOptions): ORPCError<TCode, TData>;
154
93
  /**
155
94
  * Error thrown when an operation is aborted.
156
95
  * Uses the standardized 'AbortError' name for consistency with JavaScript APIs.
@@ -218,104 +157,14 @@ declare class EventPublisher<T extends Record<PropertyKey, any>> {
218
157
  subscribe<K extends keyof T>(event: K, options?: EventPublisherSubscribeIteratorOptions): AsyncGenerator<T[K]> & AsyncIteratorObject<T[K]>;
219
158
  }
220
159
 
221
- declare class SequentialIdGenerator {
222
- private index;
223
- generate(): string;
224
- }
225
-
226
- interface StandardHeaders {
227
- [key: string]: string | string[] | undefined;
228
- }
229
- type StandardBody = undefined | unknown | Blob | URLSearchParams | FormData | AsyncIterator<unknown | void, unknown | void, undefined>;
230
- interface StandardRequest {
231
- method: string;
232
- url: URL;
233
- headers: StandardHeaders;
234
- /**
235
- * The body has been parsed based on the content-type header.
236
- */
237
- body: StandardBody;
238
- signal: AbortSignal | undefined;
239
- }
240
- interface StandardLazyRequest extends Omit<StandardRequest, 'body'> {
241
- /**
242
- * The body has been parsed based on the content-type header.
243
- * This method can safely call multiple times (cached).
244
- */
245
- body: () => Promise<StandardBody>;
246
- }
247
- interface StandardResponse {
248
- status: number;
249
- headers: StandardHeaders;
250
- /**
251
- * The body has been parsed based on the content-type header.
252
- */
253
- body: StandardBody;
254
- }
255
- interface StandardLazyResponse extends Omit<StandardResponse, 'body'> {
256
- /**
257
- * The body has been parsed based on the content-type header.
258
- * This method can safely call multiple times (cached).
259
- */
260
- body: () => Promise<StandardBody>;
261
- }
262
- type HTTPPath = `/${string}`;
263
- declare const HTTPMethods: readonly ["HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"];
264
- type HTTPMethod = (typeof HTTPMethods)[number];
265
- type HTTPEndpoint = `${HTTPMethod} ${HTTPPath}`;
266
- type ClientContext = Record<PropertyKey, any>;
267
- interface ClientOptions<T extends ClientContext> {
268
- request?: StandardLazyRequest;
269
- signal?: AbortSignal;
270
- lastEventId?: string | undefined;
271
- context: T;
272
- }
273
- type FriendlyClientOptions<T extends ClientContext> = Omit<ClientOptions<T>, 'context'> & (Record<never, never> extends T ? {
274
- context?: T;
275
- } : {
276
- context: T;
277
- });
278
- type ClientRest<TClientContext extends ClientContext, TInput> = Record<never, never> extends TClientContext ? undefined extends TInput ? [
279
- input?: TInput,
280
- options?: FriendlyClientOptions<TClientContext>
281
- ] : [input: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options: FriendlyClientOptions<TClientContext>];
282
- type ClientPromiseResult<TOutput, TError> = PromiseWithError<TOutput, TError>;
283
- interface Client<TClientContext extends ClientContext, TInput, TOutput, TError> {
284
- (...rest: ClientRest<TClientContext, TInput>): ClientPromiseResult<TOutput, TError>;
285
- }
286
- type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | {
287
- [k: string]: NestedClient<TClientContext>;
288
- };
289
- type InferClientContext<T extends NestedClient<any>> = T extends NestedClient<infer U> ? U : never;
290
- interface ClientLink<TClientContext extends ClientContext> {
291
- call: (path: readonly string[], input: unknown, options: ClientOptions<TClientContext>) => Promise<unknown>;
292
- }
293
- type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
294
- type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
295
- type PromiseWithError<T, TError> = Promise<T> & {
296
- __error?: {
297
- type: TError;
298
- };
299
- };
160
+ type AnyFunction = (...args: any[]) => any;
161
+ declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
162
+ declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
300
163
  /**
301
- * The place where you can config the orpc types.
302
- *
303
- * - `throwableError` the error type that represent throwable errors should be `Error` or `null | undefined | {}` if you want more strict.
164
+ * Executes the callback function after the current call stack has been cleared.
304
165
  */
305
- interface Registry {
306
- }
307
- type ThrowableError = Registry extends {
308
- throwableError: infer T;
309
- } ? T : Error;
310
- type InferAsyncIterableYield<T> = T extends AsyncIterable<infer U> ? U : never;
311
- type IsEqual<A, B> = (<G>() => G extends (A & G) | G ? 1 : 2) extends <G>() => G extends (B & G) | G ? 1 : 2 ? true : false;
312
- type Promisable<T> = T | PromiseLike<T>;
166
+ declare function defer(callback: () => void): void;
313
167
 
314
- type InterceptableOptions = Record<string, any>;
315
- type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
316
- next(options?: TOptions): TResult;
317
- };
318
- type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult;
319
168
  /**
320
169
  * Can used for interceptors or middlewares
321
170
  */
@@ -333,15 +182,14 @@ declare function onSuccess<T, TOptions extends {
333
182
  */
334
183
  declare function onError<T, TOptions extends {
335
184
  next(): any;
336
- }, TRest extends any[]>(callback: NoInfer<(error: 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']>>>;
185
+ }, TRest extends any[]>(callback: NoInfer<(error: Error, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
337
186
  type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess: false] | [error: null, data: TResult, isSuccess: true];
338
187
  /**
339
188
  * Can used for interceptors or middlewares
340
189
  */
341
190
  declare function onFinish<T, TOptions extends {
342
191
  next(): any;
343
- }, 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']>>>;
344
- declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
192
+ }, TRest extends any[]>(callback: NoInfer<(state: OnFinishState<Awaited<ReturnType<TOptions['next']>>, Error>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
345
193
 
346
194
  /**
347
195
  * Only import types from @opentelemetry/api to avoid runtime dependencies.
@@ -473,17 +321,7 @@ declare const NullProtoObj: {
473
321
 
474
322
  type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
475
323
  declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
476
- /**
477
- * Returns the value if it is defined, otherwise returns the fallback
478
- */
479
- declare function fallback<T>(value: T | undefined, fallback: T): T;
480
324
 
481
- /**
482
- * Prevents objects from being awaitable by intercepting the `then` method
483
- * when called by the native await mechanism. This is useful for preventing
484
- * accidental awaiting of objects that aren't meant to be promises.
485
- */
486
- declare function preventNativeAwait<T extends object>(target: T): T;
487
325
  /**
488
326
  * Create a proxy that overlays one object (`overlay`) on top of another (`target`).
489
327
  *
@@ -519,30 +357,9 @@ declare function asyncIteratorToStream<T>(iterator: AsyncIterator<T>): ReadableS
519
357
 
520
358
  declare function tryDecodeURIComponent(value: string): string;
521
359
 
522
- type SafeResult<TOutput, TError> = ([error: null, data: TOutput, isDefined: false, isSuccess: true] & {
523
- error: null;
524
- data: TOutput;
525
- isDefined: false;
526
- isSuccess: true;
527
- }) | ([error: Exclude<TError, ORPCError<any, any>>, data: undefined, isDefined: false, isSuccess: false] & {
528
- error: Exclude<TError, ORPCError<any, any>>;
529
- data: undefined;
530
- isDefined: false;
531
- isSuccess: false;
532
- }) | ([error: Extract<TError, ORPCError<any, any>>, data: undefined, isDefined: true, isSuccess: false] & {
533
- error: Extract<TError, ORPCError<any, any>>;
534
- data: undefined;
535
- isDefined: true;
536
- isSuccess: false;
537
- });
538
- /**
539
- * Works like try/catch, but can infer error types.
540
- *
541
- * @info support both tuple `[error, data, isDefined, isSuccess]` and object `{ error, data, isDefined, isSuccess }` styles.
542
- * @see {@link https://orpc.unnoq.com/docs/client/error-handling Client Error Handling Docs}
543
- */
544
- declare function safe<TOutput, TError = ThrowableError$1>(promise: ClientPromiseResult<TOutput, TError>): Promise<SafeResult<TOutput, TError>>;
545
360
  declare function toHttpPath(path: readonly string[]): HTTPPath;
361
+ declare function splitFirst(str: string, separator: string): [string, string];
362
+ declare function assertNever(value: never, message?: string): never;
546
363
 
547
- export { AbortError, AsyncIdQueue, AsyncIteratorClass, COMMON_ORPC_ERROR_DEFS, EventPublisher, HTTPMethods, NullProtoObj, ORPCError, ORPC_CLIENT_PACKAGE_NAME, ORPC_CLIENT_PACKAGE_VERSION, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorWithSpan, clone, createORPCErrorFromJson, defer, fallback, fallbackORPCErrorMessage, fallbackORPCErrorStatus, findDeepMatches, get, getConstructor, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isDefinedError, isORPCErrorJson, isORPCErrorStatus, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, overlayProxy, parseEmptyableJSON, preventNativeAwait, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, safe, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitInHalf, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toHttpPath, toORPCError, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };
548
- export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, AsyncIteratorWithSpanOptions, Client, ClientContext, ClientLink, ClientOptions, ClientPromiseResult, ClientRest, CommonORPCErrorCode, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, FriendlyClientOptions, HTTPEndpoint, HTTPMethod, HTTPPath, InferAsyncIterableYield, InferClientContext, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, IsEqual, MaybeOptionalOptions, NestedClient, ORPCErrorCode, ORPCErrorJSON, ORPCErrorOptions, OmitChainMethodDeep, OnFinishState, OtelConfig, Promisable, PromiseWithError, Registry, RunWithSpanOptions, SafeResult, Segment, SetOptional, SetSpanErrorOptions, StandardBody, StandardHeaders, StandardLazyRequest, StandardLazyResponse, StandardRequest, StandardResponse, ThrowableError, Value };
364
+ export { AbortError, AsyncIdQueue, AsyncIteratorClass, EventPublisher, HTTPMethods, NullProtoObj, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, assertNever, asyncIteratorToStream, asyncIteratorWithSpan, clone, defer, fallbackContractConfig, findDeepMatches, get, getConstructor, getGlobalOtelConfig, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, overlayProxy, parseEmptyableJSON, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitFirst, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toHttpPath, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };
365
+ export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, AsyncIteratorWithSpanOptions, Client, ClientContext, ClientLink, ClientOptions, ClientRest, ContractConfig, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, FriendlyClientOptions, HTTPEndpoint, HTTPMethod, HTTPPath, InferAsyncIterableYield, InferClientContext, IntersectPick, IsEqual, MaybeOptionalOptions, NestedClient, OnFinishState, OptionalIfEmpty, OtelConfig, OutputStructure, Promisable, RunWithSpanOptions, Segment, SetOptional, SetSpanErrorOptions, StandardBody, StandardLazyRequest, StandardLazyResponse, StandardRequest, StandardResponse, Value };
package/dist/index.mjs CHANGED
@@ -1,4 +1,3 @@
1
- import { resolveMaybeOptionalOptions as resolveMaybeOptionalOptions$1, getConstructor as getConstructor$1, isObject as isObject$1 } from '@temporary-name/shared';
2
1
  export { group, guard, mapEntries, mapValues, omit, retry, sleep } from 'radash';
3
2
 
4
3
  function resolveMaybeOptionalOptions(rest) {
@@ -8,190 +7,24 @@ function resolveMaybeOptionalOptions(rest) {
8
7
  function toArray(value) {
9
8
  return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];
10
9
  }
11
- function splitInHalf(arr) {
12
- const half = Math.ceil(arr.length / 2);
13
- return [arr.slice(0, half), arr.slice(half)];
14
- }
15
10
 
16
- function readAsBuffer(source) {
17
- if (typeof source.bytes === "function") {
18
- return source.bytes();
11
+ const DEFAULT_CONFIG = {
12
+ defaultMethod: "POST",
13
+ defaultSuccessStatus: 200,
14
+ defaultSuccessDescription: "OK",
15
+ defaultOutputStructure: "compact"
16
+ };
17
+ function fallbackContractConfig(key, value) {
18
+ if (value === void 0) {
19
+ return DEFAULT_CONFIG[key];
19
20
  }
20
- return source.arrayBuffer();
21
+ return value;
21
22
  }
22
23
 
23
24
  const ORPC_NAME = "orpc";
24
25
  const ORPC_SHARED_PACKAGE_NAME = "@temporary-name/shared";
25
- const ORPC_SHARED_PACKAGE_VERSION = "1.9.3-alpha.f9f5ce625d5edee78250b87b3a64f1d9760c2244";
26
+ const ORPC_SHARED_PACKAGE_VERSION = "1.9.3-alpha.fb7e3a67f82deaeffad5063e136b2f3c03c4b5b3";
26
27
 
27
- const ORPC_CLIENT_PACKAGE_NAME = "__ORPC_CLIENT_PACKAGE_NAME_PLACEHOLDER__";
28
- const ORPC_CLIENT_PACKAGE_VERSION = "__ORPC_CLIENT_PACKAGE_VERSION_PLACEHOLDER__";
29
- const COMMON_ORPC_ERROR_DEFS = {
30
- BAD_REQUEST: {
31
- status: 400,
32
- message: "Bad Request"
33
- },
34
- UNAUTHORIZED: {
35
- status: 401,
36
- message: "Unauthorized"
37
- },
38
- FORBIDDEN: {
39
- status: 403,
40
- message: "Forbidden"
41
- },
42
- NOT_FOUND: {
43
- status: 404,
44
- message: "Not Found"
45
- },
46
- METHOD_NOT_SUPPORTED: {
47
- status: 405,
48
- message: "Method Not Supported"
49
- },
50
- NOT_ACCEPTABLE: {
51
- status: 406,
52
- message: "Not Acceptable"
53
- },
54
- TIMEOUT: {
55
- status: 408,
56
- message: "Request Timeout"
57
- },
58
- CONFLICT: {
59
- status: 409,
60
- message: "Conflict"
61
- },
62
- PRECONDITION_FAILED: {
63
- status: 412,
64
- message: "Precondition Failed"
65
- },
66
- PAYLOAD_TOO_LARGE: {
67
- status: 413,
68
- message: "Payload Too Large"
69
- },
70
- UNSUPPORTED_MEDIA_TYPE: {
71
- status: 415,
72
- message: "Unsupported Media Type"
73
- },
74
- UNPROCESSABLE_CONTENT: {
75
- status: 422,
76
- message: "Unprocessable Content"
77
- },
78
- TOO_MANY_REQUESTS: {
79
- status: 429,
80
- message: "Too Many Requests"
81
- },
82
- CLIENT_CLOSED_REQUEST: {
83
- status: 499,
84
- message: "Client Closed Request"
85
- },
86
- INTERNAL_SERVER_ERROR: {
87
- status: 500,
88
- message: "Internal Server Error"
89
- },
90
- NOT_IMPLEMENTED: {
91
- status: 501,
92
- message: "Not Implemented"
93
- },
94
- BAD_GATEWAY: {
95
- status: 502,
96
- message: "Bad Gateway"
97
- },
98
- SERVICE_UNAVAILABLE: {
99
- status: 503,
100
- message: "Service Unavailable"
101
- },
102
- GATEWAY_TIMEOUT: {
103
- status: 504,
104
- message: "Gateway Timeout"
105
- }
106
- };
107
- function fallbackORPCErrorStatus(code, status) {
108
- return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
109
- }
110
- function fallbackORPCErrorMessage(code, message) {
111
- return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
112
- }
113
- const GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL = Symbol.for(
114
- `__${ORPC_CLIENT_PACKAGE_NAME}@${ORPC_CLIENT_PACKAGE_VERSION}/error/ORPC_ERROR_CONSTRUCTORS__`
115
- );
116
- void (globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL] ??= /* @__PURE__ */ new WeakSet());
117
- const globalORPCErrorConstructors = globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL];
118
- class ORPCError extends Error {
119
- defined;
120
- code;
121
- status;
122
- data;
123
- constructor(code, ...rest) {
124
- const options = resolveMaybeOptionalOptions$1(rest);
125
- if (options.status !== void 0 && !isORPCErrorStatus(options.status)) {
126
- throw new Error("[ORPCError] Invalid error status code.");
127
- }
128
- const message = fallbackORPCErrorMessage(code, options.message);
129
- super(message, options);
130
- this.code = code;
131
- this.status = fallbackORPCErrorStatus(code, options.status);
132
- this.defined = options.defined ?? false;
133
- this.data = options.data;
134
- }
135
- toJSON() {
136
- return {
137
- defined: this.defined,
138
- code: this.code,
139
- status: this.status,
140
- message: this.message,
141
- data: this.data
142
- };
143
- }
144
- /**
145
- * Workaround for Next.js where different contexts use separate
146
- * dependency graphs, causing multiple ORPCError constructors existing and breaking
147
- * `instanceof` checks across contexts.
148
- *
149
- * This is particularly problematic with "Optimized SSR", where orpc-client
150
- * executes in one context but is invoked from another. When an error is thrown
151
- * in the execution context, `instanceof ORPCError` checks fail in the
152
- * invocation context due to separate class constructors.
153
- *
154
- * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
155
- */
156
- static [Symbol.hasInstance](instance) {
157
- if (globalORPCErrorConstructors.has(this)) {
158
- const constructor = getConstructor$1(instance);
159
- if (constructor && globalORPCErrorConstructors.has(constructor)) {
160
- return true;
161
- }
162
- }
163
- return super[Symbol.hasInstance](instance);
164
- }
165
- }
166
- globalORPCErrorConstructors.add(ORPCError);
167
- function isDefinedError(error) {
168
- return error instanceof ORPCError && error.defined;
169
- }
170
- function toORPCError(error) {
171
- return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", {
172
- message: "Internal server error",
173
- cause: error
174
- });
175
- }
176
- function isORPCErrorStatus(status) {
177
- return status < 200 || status >= 400;
178
- }
179
- function isORPCErrorJson(json) {
180
- if (!isObject$1(json)) {
181
- return false;
182
- }
183
- const validKeys = ["defined", "code", "status", "message", "data"];
184
- if (Object.keys(json).some((k) => !validKeys.includes(k))) {
185
- return false;
186
- }
187
- return "defined" in json && typeof json.defined === "boolean" && "code" in json && typeof json.code === "string" && "status" in json && typeof json.status === "number" && isORPCErrorStatus(json.status) && "message" in json && typeof json.message === "string";
188
- }
189
- function createORPCErrorFromJson(json, options = {}) {
190
- return new ORPCError(json.code, {
191
- ...options,
192
- ...json
193
- });
194
- }
195
28
  class AbortError extends Error {
196
29
  constructor(...rest) {
197
30
  super(...rest);
@@ -628,15 +461,6 @@ class EventPublisher {
628
461
  }
629
462
  }
630
463
 
631
- class SequentialIdGenerator {
632
- index = BigInt(0);
633
- generate() {
634
- const id = this.index.toString(32);
635
- this.index++;
636
- return id;
637
- }
638
- }
639
-
640
464
  function onStart(callback) {
641
465
  return async (options, ...rest) => {
642
466
  await callback(options, ...rest);
@@ -675,19 +499,6 @@ function onFinish(callback) {
675
499
  }
676
500
  };
677
501
  }
678
- function intercept(interceptors, options, main) {
679
- const next = (options2, index) => {
680
- const interceptor = interceptors[index];
681
- if (!interceptor) {
682
- return main(options2);
683
- }
684
- return interceptor({
685
- ...options2,
686
- next: (newOptions = options2) => next(newOptions, index + 1)
687
- });
688
- };
689
- return next(options, 0);
690
- }
691
502
 
692
503
  function parseEmptyableJSON(text) {
693
504
  if (!text) {
@@ -771,46 +582,7 @@ function value(value2, ...args) {
771
582
  }
772
583
  return value2;
773
584
  }
774
- function fallback(value2, fallback2) {
775
- return value2 === void 0 ? fallback2 : value2;
776
- }
777
585
 
778
- function preventNativeAwait(target) {
779
- return new Proxy(target, {
780
- get(target2, prop, receiver) {
781
- const value2 = Reflect.get(target2, prop, receiver);
782
- if (prop !== "then" || typeof value2 !== "function") {
783
- return value2;
784
- }
785
- return new Proxy(value2, {
786
- apply(targetFn, thisArg, args) {
787
- if (args.length !== 2 || args.some((arg) => !isNativeFunction(arg))) {
788
- return Reflect.apply(targetFn, thisArg, args);
789
- }
790
- let shouldOmit = true;
791
- args[0].call(
792
- thisArg,
793
- preventNativeAwait(
794
- new Proxy(target2, {
795
- get: (target3, prop2, receiver2) => {
796
- if (shouldOmit && prop2 === "then") {
797
- shouldOmit = false;
798
- return void 0;
799
- }
800
- return Reflect.get(target3, prop2, receiver2);
801
- }
802
- })
803
- )
804
- );
805
- }
806
- });
807
- }
808
- });
809
- }
810
- const NATIVE_FUNCTION_REGEX = /^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;
811
- function isNativeFunction(fn) {
812
- return typeof fn === "function" && NATIVE_FUNCTION_REGEX.test(fn.toString());
813
- }
814
586
  function overlayProxy(target, partial) {
815
587
  const proxy = new Proxy(typeof target === "function" ? partial : target, {
816
588
  get(_, prop) {
@@ -862,38 +634,18 @@ function tryDecodeURIComponent(value) {
862
634
  }
863
635
  }
864
636
 
865
- async function safe(promise) {
866
- try {
867
- const output = await promise;
868
- return Object.assign([null, output, false, true], {
869
- error: null,
870
- data: output,
871
- isDefined: false,
872
- isSuccess: true
873
- });
874
- } catch (e) {
875
- const error = e;
876
- if (isDefinedError(error)) {
877
- return Object.assign([error, void 0, true, false], {
878
- error,
879
- data: void 0,
880
- isDefined: true,
881
- isSuccess: false
882
- });
883
- }
884
- return Object.assign(
885
- [error, void 0, false, false],
886
- {
887
- error,
888
- data: void 0,
889
- isDefined: false,
890
- isSuccess: false
891
- }
892
- );
893
- }
894
- }
895
637
  function toHttpPath(path) {
896
638
  return `/${path.map(encodeURIComponent).join("/")}`;
897
639
  }
640
+ function splitFirst(str, separator) {
641
+ const index = str.indexOf(separator);
642
+ if (index === -1) {
643
+ return [str, ""];
644
+ }
645
+ return [str.slice(0, index), str.slice(index + separator.length)];
646
+ }
647
+ function assertNever(value, message) {
648
+ throw new Error(message ?? `Unexpected value: ${value}`);
649
+ }
898
650
 
899
- export { AbortError, AsyncIdQueue, AsyncIteratorClass, COMMON_ORPC_ERROR_DEFS, EventPublisher, HTTPMethods, NullProtoObj, ORPCError, ORPC_CLIENT_PACKAGE_NAME, ORPC_CLIENT_PACKAGE_VERSION, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorWithSpan, clone, createORPCErrorFromJson, defer, fallback, fallbackORPCErrorMessage, fallbackORPCErrorStatus, findDeepMatches, get, getConstructor, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isDefinedError, isORPCErrorJson, isORPCErrorStatus, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, overlayProxy, parseEmptyableJSON, preventNativeAwait, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, safe, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitInHalf, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toHttpPath, toORPCError, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };
651
+ export { AbortError, AsyncIdQueue, AsyncIteratorClass, EventPublisher, HTTPMethods, NullProtoObj, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, assertNever, asyncIteratorToStream, asyncIteratorWithSpan, clone, defer, fallbackContractConfig, findDeepMatches, get, getConstructor, getGlobalOtelConfig, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, overlayProxy, parseEmptyableJSON, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitFirst, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toHttpPath, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@temporary-name/shared",
3
3
  "type": "module",
4
- "version": "1.9.3-alpha.f9f5ce625d5edee78250b87b3a64f1d9760c2244",
4
+ "version": "1.9.3-alpha.fb7e3a67f82deaeffad5063e136b2f3c03c4b5b3",
5
5
  "license": "MIT",
6
6
  "homepage": "https://www.stainless.com/",
7
7
  "repository": {
@@ -32,6 +32,7 @@
32
32
  }
33
33
  },
34
34
  "dependencies": {
35
+ "openapi-types": "^12.1.3",
35
36
  "radash": "^12.1.1"
36
37
  },
37
38
  "devDependencies": {
@@ -41,6 +42,7 @@
41
42
  "scripts": {
42
43
  "build": "unbuild",
43
44
  "build:watch": "pnpm run build --watch",
44
- "type:check": "tsc -b"
45
+ "clean": "tsc -b --clean",
46
+ "lint:tsc": "tsc -b"
45
47
  }
46
48
  }