@orpc/shared 0.0.0-next.df024bb → 0.0.0-next.e000d9a

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/README.md CHANGED
@@ -1,3 +1,8 @@
1
+ > [!WARNING]
2
+ >
3
+ > `@orpc/shared` is an internal dependency of oRPC packages. It does not follow semver and may change at any time without notice.
4
+ > Please do not use it in your project.
5
+
1
6
  <div align="center">
2
7
  <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 alt="oRPC logo" />
3
8
  </div>
@@ -21,28 +26,24 @@
21
26
 
22
27
  <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
23
28
 
24
- **oRPC is a powerful combination of RPC and OpenAPI**, makes it easy to build APIs that are end-to-end type-safe and adhere to OpenAPI standards, ensuring a smooth and enjoyable developer experience.
29
+ **oRPC is a powerful combination of RPC and OpenAPI**, makes it easy to build APIs that are end-to-end type-safe and adhere to OpenAPI standards
25
30
 
26
31
  ---
27
32
 
28
33
  ## Highlights
29
34
 
30
- - **End-to-End Type Safety 🔒**: Ensure complete type safety from inputs to outputs and errors, bridging server and client seamlessly.
31
- - **First-Class OpenAPI 📄**: Adheres to the OpenAPI standard out of the box, ensuring seamless integration and comprehensive API documentation.
32
- - **Contract-First Development 📜**: (Optional) Define your API contract upfront and implement it with confidence.
33
- - **Exceptional Developer Experience ✨**: Enjoy a streamlined workflow with robust typing and clear, in-code documentation.
34
- - **Multi-Runtime Support 🌍**: Run your code seamlessly on Cloudflare, Deno, Bun, Node.js, and more.
35
- - **Framework Integrations 🧩**: Supports Tanstack Query (React, Vue), Pinia Colada, and more.
36
- - **Server Actions ⚡️**: Fully compatible with React Server Actions on Next.js, TanStack Start, and more.
37
- - **Standard Schema Support 🗂️**: Effortlessly work with Zod, Valibot, ArkType, and others right out of the box.
38
- - **Fast & Lightweight 💨**: Built on native APIs across all runtimes – optimized for speed and efficiency.
39
- - **Native Types 📦**: Enjoy built-in support for Date, File, Blob, BigInt, URL and more with no extra setup.
40
- - **Lazy Router ⏱️**: Improve cold start times with our lazy routing feature.
41
- - **SSE & Streaming 📡**: Provides SSE and streaming features – perfect for real-time notifications and AI-powered streaming responses.
42
- - **Reusability 🔄**: Write once and reuse your code across multiple purposes effortlessly.
43
- - **Extendability 🔌**: Easily enhance oRPC with plugins, middleware, and interceptors.
44
- - **Reliability 🛡️**: Well-tested, fully TypeScript, production-ready, and MIT licensed for peace of mind.
45
- - **Simplicity 💡**: Enjoy straightforward, clean code with no hidden magic.
35
+ - **🔗 End-to-End Type Safety**: Ensure type-safe inputs, outputs, and errors from client to server.
36
+ - **📘 First-Class OpenAPI**: Built-in support that fully adheres to the OpenAPI standard.
37
+ - **📝 Contract-First Development**: Optionally define your API contract before implementation.
38
+ - **⚙️ Framework Integrations**: Seamlessly integrate with TanStack Query (React, Vue, Solid, Svelte), Pinia Colada, and more.
39
+ - **🚀 Server Actions**: Fully compatible with React Server Actions on Next.js, TanStack Start, and other platforms.
40
+ - **🔠 Standard Schema Support**: Works out of the box with Zod, Valibot, ArkType, and other schema validators.
41
+ - **🗃️ Native Types**: Supports native types like Date, File, Blob, BigInt, URL, and more.
42
+ - **⏱️ Lazy Router**: Enhance cold start times with our lazy routing feature.
43
+ - **📡 SSE & Streaming**: Enjoy full type-safe support for SSE and streaming.
44
+ - **🌍 Multi-Runtime Support**: Fast and lightweight on Cloudflare, Deno, Bun, Node.js, and beyond.
45
+ - **🔌 Extendability**: Easily extend functionality with plugins, middleware, and interceptors.
46
+ - **🛡️ Reliability**: Well-tested, TypeScript-based, production-ready, and MIT licensed.
46
47
 
47
48
  ## Documentation
48
49
 
@@ -53,16 +54,30 @@ You can find the full documentation [here](https://orpc.unnoq.com).
53
54
  - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
54
55
  - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
55
56
  - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
57
+ - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with NestJS.
58
+ - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
56
59
  - [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
57
60
  - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
61
+ - [@orpc/solid-query](https://www.npmjs.com/package/@orpc/solid-query): Integration with [Solid Query](https://tanstack.com/query/latest/docs/framework/solid/overview).
62
+ - [@orpc/svelte-query](https://www.npmjs.com/package/@orpc/svelte-query): Integration with [Svelte Query](https://tanstack.com/query/latest/docs/framework/svelte/overview).
58
63
  - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
59
64
  - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
60
65
  - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
66
+ - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
67
+ - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
61
68
 
62
69
  ## `@orpc/shared`
63
70
 
64
71
  Provides shared utilities for oRPC packages.
65
72
 
73
+ ## Sponsors
74
+
75
+ <p align="center">
76
+ <a href="https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg">
77
+ <img src='https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg'/>
78
+ </a>
79
+ </p>
80
+
66
81
  ## License
67
82
 
68
83
  Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
package/dist/index.d.mts CHANGED
@@ -1,68 +1,86 @@
1
1
  import { Promisable } from 'type-fest';
2
2
  export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
3
- export { group, guard, mapEntries, mapValues, omit, retry, trim } from 'radash';
3
+ export { group, guard, mapEntries, mapValues, omit } from 'radash';
4
+
5
+ type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
6
+ declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>): T;
7
+
8
+ 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[]];
4
10
 
5
11
  type AnyFunction = (...args: any[]) => any;
6
12
  declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
13
+ declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
7
14
 
8
15
  type OmitChainMethodDeep<T extends object, K extends keyof any> = {
9
16
  [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
10
17
  };
11
18
 
12
- declare function toError(error: unknown): Error;
19
+ declare class SequentialIdGenerator {
20
+ private nextId;
21
+ generate(): number;
22
+ }
13
23
 
14
- type InterceptableOptions = Record<string, any>;
15
- type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
16
- next(options?: TOptions): Promise<TResult>;
17
- };
18
- type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult>) => Promise<TResult> & {
24
+ type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
25
+ type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
26
+ type PromiseWithError<T, TError> = Promise<T> & {
19
27
  __error?: {
20
28
  type: TError;
21
29
  };
22
30
  };
31
+ /**
32
+ * The place where you can config the orpc types.
33
+ *
34
+ * - `throwableError` the error type that represent throwable errors should be `Error` or `null | undefined | {}` if you want more strict.
35
+ */
36
+ interface Registry {
37
+ }
38
+ type ThrowableError = Registry extends {
39
+ throwableError: infer T;
40
+ } ? T : Error;
41
+
42
+ type InterceptableOptions = Record<string, any>;
43
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult, TError> = Omit<TOptions, 'next'> & {
44
+ next(options?: TOptions): PromiseWithError<TResult, TError>;
45
+ };
46
+ type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult, TError>) => Promisable<TResult>;
23
47
  /**
24
48
  * Can used for interceptors or middlewares
25
49
  */
26
- declare function onStart<TOptions extends {
50
+ declare function onStart<T, TOptions extends {
27
51
  next(): any;
28
- }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
52
+ }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
29
53
  /**
30
54
  * Can used for interceptors or middlewares
31
55
  */
32
- declare function onSuccess<TOptions extends {
56
+ declare function onSuccess<T, TOptions extends {
33
57
  next(): any;
34
- }, TRest extends any[]>(callback: NoInfer<(result: Awaited<ReturnType<TOptions['next']>>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
58
+ }, 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']>>>;
35
59
  /**
36
60
  * Can used for interceptors or middlewares
37
61
  */
38
- declare function onError<TError, TOptions extends {
62
+ declare function onError<T, TOptions extends {
39
63
  next(): any;
40
- }, TRest extends any[]>(callback: NoInfer<(error: TError, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>> & {
41
- __error?: {
42
- type: TError;
43
- };
44
- };
45
- type OnFinishState<TResult, TError> = [TResult, undefined, 'success'] | [undefined, TError, 'error'];
64
+ }, 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']>>>;
65
+ type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess: false] | [error: null, data: TResult, isSuccess: true];
46
66
  /**
47
67
  * Can used for interceptors or middlewares
48
68
  */
49
- declare function onFinish<TError, TOptions extends {
69
+ declare function onFinish<T, TOptions extends {
50
70
  next(): any;
51
- }, TRest extends any[]>(callback: NoInfer<(state: OnFinishState<Awaited<ReturnType<TOptions['next']>>, TError>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>> & {
52
- __error?: {
53
- type: TError;
54
- };
55
- };
71
+ }, 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']>>>;
56
72
  declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
57
73
 
58
74
  declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
75
+ interface CreateAsyncIteratorObjectCleanupFn {
76
+ (reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
77
+ }
78
+ declare function createAsyncIteratorObject<T, TReturn, TNext>(next: () => Promise<IteratorResult<T, TReturn>>, cleanup: CreateAsyncIteratorObjectCleanupFn): AsyncIteratorObject<T, TReturn, TNext> & AsyncGenerator<T, TReturn, TNext>;
59
79
 
60
80
  declare function parseEmptyableJSON(text: string | null | undefined): unknown;
61
81
  declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
62
82
 
63
83
  type Segment = string | number;
64
- declare function set(root: unknown, segments: Readonly<Segment[]>, value: unknown): unknown;
65
- declare function get(root: Readonly<Record<string, unknown> | unknown[]>, segments: Readonly<Segment[]>): unknown;
66
84
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
67
85
  maps: Segment[][];
68
86
  values: unknown[];
@@ -75,11 +93,29 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
75
93
  * Check if the value satisfy a `object` type in typescript
76
94
  */
77
95
  declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
96
+ declare function clone<T>(value: T): T;
97
+ declare function get(object: object, path: readonly string[]): unknown;
98
+ declare function isPropertyKey(value: unknown): value is PropertyKey;
78
99
 
79
- type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
80
- type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
100
+ interface AsyncIdQueueCloseOptions {
101
+ id?: number;
102
+ reason?: Error;
103
+ }
104
+ declare class AsyncIdQueue<T> {
105
+ private readonly openIds;
106
+ private readonly items;
107
+ private readonly pendingPulls;
108
+ get length(): number;
109
+ open(id: number): void;
110
+ isOpen(id: number): boolean;
111
+ push(id: number, item: T): void;
112
+ pull(id: number): Promise<T>;
113
+ close({ id, reason }?: AsyncIdQueueCloseOptions): void;
114
+ assertOpen(id: number): void;
115
+ }
81
116
 
82
117
  type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
83
118
  declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>;
84
119
 
85
- export { type AnyFunction, type InterceptableOptions, type Interceptor, type InterceptorOptions, type MaybeOptionalOptions, type OmitChainMethodDeep, type OnFinishState, type Segment, type SetOptional, type Value, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, set, stringifyJSON, toError, value };
120
+ export { AsyncIdQueue, SequentialIdGenerator, clone, createAsyncIteratorObject, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
121
+ export type { AnyFunction, AsyncIdQueueCloseOptions, CreateAsyncIteratorObjectCleanupFn, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
package/dist/index.d.ts CHANGED
@@ -1,68 +1,86 @@
1
1
  import { Promisable } from 'type-fest';
2
2
  export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
3
- export { group, guard, mapEntries, mapValues, omit, retry, trim } from 'radash';
3
+ export { group, guard, mapEntries, mapValues, omit } from 'radash';
4
+
5
+ type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
6
+ declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>): T;
7
+
8
+ 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[]];
4
10
 
5
11
  type AnyFunction = (...args: any[]) => any;
6
12
  declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
13
+ declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
7
14
 
8
15
  type OmitChainMethodDeep<T extends object, K extends keyof any> = {
9
16
  [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
10
17
  };
11
18
 
12
- declare function toError(error: unknown): Error;
19
+ declare class SequentialIdGenerator {
20
+ private nextId;
21
+ generate(): number;
22
+ }
13
23
 
14
- type InterceptableOptions = Record<string, any>;
15
- type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
16
- next(options?: TOptions): Promise<TResult>;
17
- };
18
- type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult>) => Promise<TResult> & {
24
+ type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
25
+ type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
26
+ type PromiseWithError<T, TError> = Promise<T> & {
19
27
  __error?: {
20
28
  type: TError;
21
29
  };
22
30
  };
31
+ /**
32
+ * The place where you can config the orpc types.
33
+ *
34
+ * - `throwableError` the error type that represent throwable errors should be `Error` or `null | undefined | {}` if you want more strict.
35
+ */
36
+ interface Registry {
37
+ }
38
+ type ThrowableError = Registry extends {
39
+ throwableError: infer T;
40
+ } ? T : Error;
41
+
42
+ type InterceptableOptions = Record<string, any>;
43
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult, TError> = Omit<TOptions, 'next'> & {
44
+ next(options?: TOptions): PromiseWithError<TResult, TError>;
45
+ };
46
+ type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult, TError>) => Promisable<TResult>;
23
47
  /**
24
48
  * Can used for interceptors or middlewares
25
49
  */
26
- declare function onStart<TOptions extends {
50
+ declare function onStart<T, TOptions extends {
27
51
  next(): any;
28
- }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
52
+ }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
29
53
  /**
30
54
  * Can used for interceptors or middlewares
31
55
  */
32
- declare function onSuccess<TOptions extends {
56
+ declare function onSuccess<T, TOptions extends {
33
57
  next(): any;
34
- }, TRest extends any[]>(callback: NoInfer<(result: Awaited<ReturnType<TOptions['next']>>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
58
+ }, 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']>>>;
35
59
  /**
36
60
  * Can used for interceptors or middlewares
37
61
  */
38
- declare function onError<TError, TOptions extends {
62
+ declare function onError<T, TOptions extends {
39
63
  next(): any;
40
- }, TRest extends any[]>(callback: NoInfer<(error: TError, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>> & {
41
- __error?: {
42
- type: TError;
43
- };
44
- };
45
- type OnFinishState<TResult, TError> = [TResult, undefined, 'success'] | [undefined, TError, 'error'];
64
+ }, 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']>>>;
65
+ type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess: false] | [error: null, data: TResult, isSuccess: true];
46
66
  /**
47
67
  * Can used for interceptors or middlewares
48
68
  */
49
- declare function onFinish<TError, TOptions extends {
69
+ declare function onFinish<T, TOptions extends {
50
70
  next(): any;
51
- }, TRest extends any[]>(callback: NoInfer<(state: OnFinishState<Awaited<ReturnType<TOptions['next']>>, TError>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>> & {
52
- __error?: {
53
- type: TError;
54
- };
55
- };
71
+ }, 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']>>>;
56
72
  declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
57
73
 
58
74
  declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
75
+ interface CreateAsyncIteratorObjectCleanupFn {
76
+ (reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
77
+ }
78
+ declare function createAsyncIteratorObject<T, TReturn, TNext>(next: () => Promise<IteratorResult<T, TReturn>>, cleanup: CreateAsyncIteratorObjectCleanupFn): AsyncIteratorObject<T, TReturn, TNext> & AsyncGenerator<T, TReturn, TNext>;
59
79
 
60
80
  declare function parseEmptyableJSON(text: string | null | undefined): unknown;
61
81
  declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
62
82
 
63
83
  type Segment = string | number;
64
- declare function set(root: unknown, segments: Readonly<Segment[]>, value: unknown): unknown;
65
- declare function get(root: Readonly<Record<string, unknown> | unknown[]>, segments: Readonly<Segment[]>): unknown;
66
84
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
67
85
  maps: Segment[][];
68
86
  values: unknown[];
@@ -75,11 +93,29 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
75
93
  * Check if the value satisfy a `object` type in typescript
76
94
  */
77
95
  declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
96
+ declare function clone<T>(value: T): T;
97
+ declare function get(object: object, path: readonly string[]): unknown;
98
+ declare function isPropertyKey(value: unknown): value is PropertyKey;
78
99
 
79
- type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
80
- type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
100
+ interface AsyncIdQueueCloseOptions {
101
+ id?: number;
102
+ reason?: Error;
103
+ }
104
+ declare class AsyncIdQueue<T> {
105
+ private readonly openIds;
106
+ private readonly items;
107
+ private readonly pendingPulls;
108
+ get length(): number;
109
+ open(id: number): void;
110
+ isOpen(id: number): boolean;
111
+ push(id: number, item: T): void;
112
+ pull(id: number): Promise<T>;
113
+ close({ id, reason }?: AsyncIdQueueCloseOptions): void;
114
+ assertOpen(id: number): void;
115
+ }
81
116
 
82
117
  type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
83
118
  declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>;
84
119
 
85
- export { type AnyFunction, type InterceptableOptions, type Interceptor, type InterceptorOptions, type MaybeOptionalOptions, type OmitChainMethodDeep, type OnFinishState, type Segment, type SetOptional, type Value, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, set, stringifyJSON, toError, value };
120
+ export { AsyncIdQueue, SequentialIdGenerator, clone, createAsyncIteratorObject, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
121
+ export type { AnyFunction, AsyncIdQueueCloseOptions, CreateAsyncIteratorObjectCleanupFn, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
package/dist/index.mjs CHANGED
@@ -1,74 +1,15 @@
1
- export { group, guard, mapEntries, mapValues, omit, retry, trim } from 'radash';
1
+ export { group, guard, mapEntries, mapValues, omit } from 'radash';
2
2
 
3
- function set(root, segments, value) {
4
- const ref = { root };
5
- let currentRef = ref;
6
- let preSegment = "root";
7
- for (const segment of segments) {
8
- currentRef = currentRef[preSegment];
9
- preSegment = segment;
10
- }
11
- currentRef[preSegment] = value;
12
- return ref.root;
13
- }
14
- function get(root, segments) {
15
- const ref = { root };
16
- let currentRef = ref;
17
- let preSegment = "root";
18
- for (const segment of segments) {
19
- if (typeof currentRef !== "object" && typeof currentRef !== "function" || currentRef === null) {
20
- return void 0;
21
- }
22
- currentRef = currentRef[preSegment];
23
- preSegment = segment;
24
- }
25
- if (typeof currentRef !== "object" && typeof currentRef !== "function" || currentRef === null) {
26
- return void 0;
27
- }
28
- return currentRef[preSegment];
29
- }
30
- function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
31
- if (check(payload)) {
32
- maps.push(segments);
33
- values.push(payload);
34
- } else if (Array.isArray(payload)) {
35
- payload.forEach((v, i) => {
36
- findDeepMatches(check, v, [...segments, i], maps, values);
37
- });
38
- } else if (isObject(payload)) {
39
- for (const key in payload) {
40
- findDeepMatches(check, payload[key], [...segments, key], maps, values);
41
- }
42
- }
43
- return { maps, values };
44
- }
45
- function isObject(value) {
46
- if (!value || typeof value !== "object") {
47
- return false;
48
- }
49
- const proto = Object.getPrototypeOf(value);
50
- return proto === Object.prototype || !proto || !proto.constructor;
51
- }
52
- function isTypescriptObject(value) {
53
- return !!value && (typeof value === "object" || typeof value === "function");
3
+ function resolveMaybeOptionalOptions(rest) {
4
+ return rest[0] ?? {};
54
5
  }
55
6
 
56
- function toError(error) {
57
- if (error instanceof Error) {
58
- return error;
59
- }
60
- if (typeof error === "string") {
61
- return new Error(error, { cause: error });
62
- }
63
- if (isObject(error)) {
64
- if ("message" in error && typeof error.message === "string") {
65
- return new Error(error.message, { cause: error });
66
- }
67
- if ("name" in error && typeof error.name === "string") {
68
- return new Error(error.name, { cause: error });
69
- }
70
- }
71
- return new Error("Unknown error", { cause: error });
7
+ function toArray(value) {
8
+ return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];
9
+ }
10
+ function splitInHalf(arr) {
11
+ const half = Math.ceil(arr.length / 2);
12
+ return [arr.slice(0, half), arr.slice(half)];
72
13
  }
73
14
 
74
15
  function once(fn) {
@@ -82,6 +23,26 @@ function once(fn) {
82
23
  return result;
83
24
  };
84
25
  }
26
+ function sequential(fn) {
27
+ let lastOperationPromise = Promise.resolve();
28
+ return (...args) => {
29
+ return lastOperationPromise = lastOperationPromise.catch(() => {
30
+ }).then(() => {
31
+ return fn(...args);
32
+ });
33
+ };
34
+ }
35
+
36
+ class SequentialIdGenerator {
37
+ nextId = 0;
38
+ generate() {
39
+ if (this.nextId === Number.MAX_SAFE_INTEGER) {
40
+ this.nextId = 0;
41
+ return Number.MAX_SAFE_INTEGER;
42
+ }
43
+ return this.nextId++;
44
+ }
45
+ }
85
46
 
86
47
  function onStart(callback) {
87
48
  return async (options, ...rest) => {
@@ -111,10 +72,10 @@ function onFinish(callback) {
111
72
  return async (options, ...rest) => {
112
73
  try {
113
74
  const result = await options.next();
114
- state = [result, void 0, "success"];
75
+ state = [null, result, true];
115
76
  return result;
116
77
  } catch (error) {
117
- state = [void 0, error, "error"];
78
+ state = [error, void 0, false];
118
79
  throw error;
119
80
  } finally {
120
81
  await callback(state, options, ...rest);
@@ -122,18 +83,17 @@ function onFinish(callback) {
122
83
  };
123
84
  }
124
85
  async function intercept(interceptors, options, main) {
125
- let index = 0;
126
- const next = async (options2) => {
127
- const interceptor = interceptors[index++];
86
+ const next = async (options2, index) => {
87
+ const interceptor = interceptors[index];
128
88
  if (!interceptor) {
129
89
  return await main(options2);
130
90
  }
131
91
  return await interceptor({
132
92
  ...options2,
133
- next: (newOptions = options2) => next(newOptions)
93
+ next: (newOptions = options2) => next(newOptions, index + 1)
134
94
  });
135
95
  };
136
- return await next(options);
96
+ return next(options, 0);
137
97
  }
138
98
 
139
99
  function isAsyncIteratorObject(maybe) {
@@ -142,6 +102,62 @@ function isAsyncIteratorObject(maybe) {
142
102
  }
143
103
  return Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
144
104
  }
105
+ function createAsyncIteratorObject(next, cleanup) {
106
+ let isExecuteComplete = false;
107
+ let isDone = false;
108
+ const iterator = {
109
+ next: sequential(async () => {
110
+ if (isDone) {
111
+ return { done: true, value: void 0 };
112
+ }
113
+ try {
114
+ const result = await next();
115
+ if (result.done) {
116
+ isDone = true;
117
+ }
118
+ return result;
119
+ } catch (err) {
120
+ isDone = true;
121
+ throw err;
122
+ } finally {
123
+ if (isDone && !isExecuteComplete) {
124
+ isExecuteComplete = true;
125
+ await cleanup("next");
126
+ }
127
+ }
128
+ }),
129
+ async return(value) {
130
+ isDone = true;
131
+ if (!isExecuteComplete) {
132
+ isExecuteComplete = true;
133
+ await cleanup("return");
134
+ }
135
+ return { done: true, value };
136
+ },
137
+ async throw(err) {
138
+ isDone = true;
139
+ if (!isExecuteComplete) {
140
+ isExecuteComplete = true;
141
+ await cleanup("throw");
142
+ }
143
+ throw err;
144
+ },
145
+ /**
146
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
147
+ */
148
+ async [Symbol.asyncDispose ?? Symbol.for("asyncDispose")]() {
149
+ isDone = true;
150
+ if (!isExecuteComplete) {
151
+ isExecuteComplete = true;
152
+ await cleanup("dispose");
153
+ }
154
+ },
155
+ [Symbol.asyncIterator]() {
156
+ return iterator;
157
+ }
158
+ };
159
+ return iterator;
160
+ }
145
161
 
146
162
  function parseEmptyableJSON(text) {
147
163
  if (!text) {
@@ -153,6 +169,135 @@ function stringifyJSON(value) {
153
169
  return JSON.stringify(value);
154
170
  }
155
171
 
172
+ function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
173
+ if (check(payload)) {
174
+ maps.push(segments);
175
+ values.push(payload);
176
+ } else if (Array.isArray(payload)) {
177
+ payload.forEach((v, i) => {
178
+ findDeepMatches(check, v, [...segments, i], maps, values);
179
+ });
180
+ } else if (isObject(payload)) {
181
+ for (const key in payload) {
182
+ findDeepMatches(check, payload[key], [...segments, key], maps, values);
183
+ }
184
+ }
185
+ return { maps, values };
186
+ }
187
+ function isObject(value) {
188
+ if (!value || typeof value !== "object") {
189
+ return false;
190
+ }
191
+ const proto = Object.getPrototypeOf(value);
192
+ return proto === Object.prototype || !proto || !proto.constructor;
193
+ }
194
+ function isTypescriptObject(value) {
195
+ return !!value && (typeof value === "object" || typeof value === "function");
196
+ }
197
+ function clone(value) {
198
+ if (Array.isArray(value)) {
199
+ return value.map(clone);
200
+ }
201
+ if (isObject(value)) {
202
+ const result = {};
203
+ for (const key in value) {
204
+ result[key] = clone(value[key]);
205
+ }
206
+ return result;
207
+ }
208
+ return value;
209
+ }
210
+ function get(object, path) {
211
+ let current = object;
212
+ for (const key of path) {
213
+ if (!isTypescriptObject(current)) {
214
+ return void 0;
215
+ }
216
+ current = current[key];
217
+ }
218
+ return current;
219
+ }
220
+ function isPropertyKey(value) {
221
+ const type = typeof value;
222
+ return type === "string" || type === "number" || type === "symbol";
223
+ }
224
+
225
+ class AsyncIdQueue {
226
+ openIds = /* @__PURE__ */ new Set();
227
+ items = /* @__PURE__ */ new Map();
228
+ pendingPulls = /* @__PURE__ */ new Map();
229
+ get length() {
230
+ return this.openIds.size;
231
+ }
232
+ open(id) {
233
+ this.openIds.add(id);
234
+ }
235
+ isOpen(id) {
236
+ return this.openIds.has(id);
237
+ }
238
+ push(id, item) {
239
+ this.assertOpen(id);
240
+ const pending = this.pendingPulls.get(id);
241
+ if (pending?.length) {
242
+ pending.shift()[0](item);
243
+ if (pending.length === 0) {
244
+ this.pendingPulls.delete(id);
245
+ }
246
+ } else {
247
+ const items = this.items.get(id);
248
+ if (items) {
249
+ items.push(item);
250
+ } else {
251
+ this.items.set(id, [item]);
252
+ }
253
+ }
254
+ }
255
+ async pull(id) {
256
+ this.assertOpen(id);
257
+ const items = this.items.get(id);
258
+ if (items?.length) {
259
+ const item = items.shift();
260
+ if (items.length === 0) {
261
+ this.items.delete(id);
262
+ }
263
+ return item;
264
+ }
265
+ return new Promise((resolve, reject) => {
266
+ const waitingPulls = this.pendingPulls.get(id);
267
+ const pending = [resolve, reject];
268
+ if (waitingPulls) {
269
+ waitingPulls.push(pending);
270
+ } else {
271
+ this.pendingPulls.set(id, [pending]);
272
+ }
273
+ });
274
+ }
275
+ close({ id, reason } = {}) {
276
+ if (id === void 0) {
277
+ this.pendingPulls.forEach((pendingPulls, id2) => {
278
+ pendingPulls.forEach(([, reject]) => {
279
+ reject(reason ?? new Error(`[AsyncIdQueue] Queue[${id2}] was closed or aborted while waiting for pulling.`));
280
+ });
281
+ });
282
+ this.pendingPulls.clear();
283
+ this.openIds.clear();
284
+ this.items.clear();
285
+ return;
286
+ }
287
+ this.pendingPulls.get(id)?.forEach(([, reject]) => {
288
+ reject(reason ?? new Error(`[AsyncIdQueue] Queue[${id}] was closed or aborted while waiting for pulling.`));
289
+ });
290
+ this.pendingPulls.delete(id);
291
+ this.openIds.delete(id);
292
+ this.items.delete(id);
293
+ }
294
+ assertOpen(id) {
295
+ if (!this.isOpen(id)) {
296
+ throw new Error(`[AsyncIdQueue] Cannot access queue[${id}] because it is not open or aborted.`);
297
+ }
298
+ }
299
+ }
300
+
156
301
  function value(value2, ...args) {
157
302
  if (typeof value2 === "function") {
158
303
  return value2(...args);
@@ -160,4 +305,4 @@ function value(value2, ...args) {
160
305
  return value2;
161
306
  }
162
307
 
163
- export { findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, set, stringifyJSON, toError, value };
308
+ export { AsyncIdQueue, SequentialIdGenerator, clone, createAsyncIteratorObject, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/shared",
3
3
  "type": "module",
4
- "version": "0.0.0-next.df024bb",
4
+ "version": "0.0.0-next.e000d9a",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -25,7 +25,7 @@
25
25
  ],
26
26
  "dependencies": {
27
27
  "radash": "^12.1.0",
28
- "type-fest": "^4.26.1"
28
+ "type-fest": "^4.39.1"
29
29
  },
30
30
  "scripts": {
31
31
  "build": "unbuild",