@orpc/shared 0.0.0-next.e7ee5a9 → 0.0.0-next.e82d760

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, Angular), 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,28 @@ 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.
56
- - [@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
- - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
58
- - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
59
57
  - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
58
+ - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with [NestJS](https://nestjs.com/).
59
+ - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
60
+ - [@orpc/tanstack-query](https://www.npmjs.com/package/@orpc/tanstack-query): [TanStack Query](https://tanstack.com/query/latest) integration.
61
+ - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
62
+ - [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration.
60
63
  - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
64
+ - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
65
+ - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
61
66
 
62
67
  ## `@orpc/shared`
63
68
 
64
69
  Provides shared utilities for oRPC packages.
65
70
 
71
+ ## Sponsors
72
+
73
+ <p align="center">
74
+ <a href="https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg">
75
+ <img src='https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg'/>
76
+ </a>
77
+ </p>
78
+
66
79
  ## License
67
80
 
68
81
  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,170 @@
1
1
  import { Promisable } from 'type-fest';
2
- export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
3
- export { group, guard, mapEntries, mapValues, omit, retry, trim } from 'radash';
2
+ export { IsEqual, IsNever, JsonValue, PartialDeep, Promisable } from 'type-fest';
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>;
14
+ /**
15
+ * Executes the callback function after the current call stack has been cleared.
16
+ */
17
+ declare function defer(callback: () => void): void;
7
18
 
8
19
  type OmitChainMethodDeep<T extends object, K extends keyof any> = {
9
20
  [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
10
21
  };
11
22
 
12
- declare function toError(error: unknown): Error;
23
+ interface EventPublisherOptions {
24
+ /**
25
+ * Maximum number of events to buffer for async iterator subscribers.
26
+ *
27
+ * If the buffer exceeds this limit, the oldest event is dropped.
28
+ * This prevents unbounded memory growth if consumers process events slowly.
29
+ *
30
+ * Set to:
31
+ * - `0`: Disable buffering. Events must be consumed before the next one arrives.
32
+ * - `1`: Only keep the latest event. Useful for real-time updates where only the most recent value matters.
33
+ * - `Infinity`: Keep all events. Ensures no data loss, but may lead to high memory usage.
34
+ *
35
+ * @default 100
36
+ */
37
+ maxBufferedEvents?: number;
38
+ }
39
+ interface EventPublisherSubscribeIteratorOptions extends EventPublisherOptions {
40
+ /**
41
+ * Aborts the async iterator. Throws if aborted before or during pulling.
42
+ */
43
+ signal?: AbortSignal;
44
+ }
45
+ declare class EventPublisher<T extends Record<PropertyKey, any>> {
46
+ #private;
47
+ constructor(options?: EventPublisherOptions);
48
+ get size(): number;
49
+ /**
50
+ * Emits an event and delivers the payload to all subscribed listeners.
51
+ */
52
+ publish<K extends keyof T>(event: K, payload: T[K]): void;
53
+ /**
54
+ * Subscribes to a specific event using a callback function.
55
+ * Returns an unsubscribe function to remove the listener.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * const unsubscribe = publisher.subscribe('event', (payload) => {
60
+ * console.log(payload)
61
+ * })
62
+ *
63
+ * // Later
64
+ * unsubscribe()
65
+ * ```
66
+ */
67
+ subscribe<K extends keyof T>(event: K, listener: (payload: T[K]) => void): () => void;
68
+ /**
69
+ * Subscribes to a specific event using an async iterator.
70
+ * Useful for `for await...of` loops with optional buffering and abort support.
71
+ *
72
+ * @example
73
+ * ```ts
74
+ * for await (const payload of publisher.subscribe('event', { signal })) {
75
+ * console.log(payload)
76
+ * }
77
+ * ```
78
+ */
79
+ subscribe<K extends keyof T>(event: K, options?: EventPublisherSubscribeIteratorOptions): AsyncGenerator<T[K]> & AsyncIteratorObject<T[K]>;
80
+ }
13
81
 
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> & {
82
+ declare class SequentialIdGenerator {
83
+ private index;
84
+ generate(): string;
85
+ }
86
+
87
+ type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
88
+ type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
89
+ type PromiseWithError<T, TError> = Promise<T> & {
19
90
  __error?: {
20
91
  type: TError;
21
92
  };
22
93
  };
94
+ /**
95
+ * The place where you can config the orpc types.
96
+ *
97
+ * - `throwableError` the error type that represent throwable errors should be `Error` or `null | undefined | {}` if you want more strict.
98
+ */
99
+ interface Registry {
100
+ }
101
+ type ThrowableError = Registry extends {
102
+ throwableError: infer T;
103
+ } ? T : Error;
104
+
105
+ type InterceptableOptions = Record<string, any>;
106
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
107
+ next(options?: TOptions): TResult;
108
+ };
109
+ type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult;
23
110
  /**
24
111
  * Can used for interceptors or middlewares
25
112
  */
26
- declare function onStart<TOptions extends {
113
+ declare function onStart<T, TOptions extends {
27
114
  next(): any;
28
- }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
115
+ }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
29
116
  /**
30
117
  * Can used for interceptors or middlewares
31
118
  */
32
- declare function onSuccess<TOptions extends {
119
+ declare function onSuccess<T, TOptions extends {
33
120
  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']>>>;
121
+ }, 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
122
  /**
36
123
  * Can used for interceptors or middlewares
37
124
  */
38
- declare function onError<TError, TOptions extends {
125
+ declare function onError<T, TOptions extends {
39
126
  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'];
127
+ }, 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']>>>;
128
+ type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess: false] | [error: null, data: TResult, isSuccess: true];
46
129
  /**
47
130
  * Can used for interceptors or middlewares
48
131
  */
49
- declare function onFinish<TError, TOptions extends {
132
+ declare function onFinish<T, TOptions extends {
50
133
  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
- };
56
- declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
134
+ }, 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']>>>;
135
+ declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
57
136
 
58
137
  declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
138
+ interface AsyncIteratorClassNextFn<T, TReturn> {
139
+ (): Promise<IteratorResult<T, TReturn>>;
140
+ }
141
+ interface AsyncIteratorClassCleanupFn {
142
+ (reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
143
+ }
144
+ declare const fallbackAsyncDisposeSymbol: unique symbol;
145
+ declare const asyncDisposeSymbol: typeof Symbol extends {
146
+ asyncDispose: infer T;
147
+ } ? T : typeof fallbackAsyncDisposeSymbol;
148
+ declare class AsyncIteratorClass<T, TReturn = unknown, TNext = unknown> implements AsyncIteratorObject<T, TReturn, TNext>, AsyncGenerator<T, TReturn, TNext> {
149
+ #private;
150
+ constructor(next: AsyncIteratorClassNextFn<T, TReturn>, cleanup: AsyncIteratorClassCleanupFn);
151
+ next(): Promise<IteratorResult<T, TReturn>>;
152
+ return(value?: any): Promise<IteratorResult<T, TReturn>>;
153
+ throw(err: any): Promise<IteratorResult<T, TReturn>>;
154
+ /**
155
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
156
+ */
157
+ [asyncDisposeSymbol](): Promise<void>;
158
+ [Symbol.asyncIterator](): this;
159
+ }
160
+ declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorClass<T, TReturn, TNext>)[];
59
161
 
60
162
  declare function parseEmptyableJSON(text: string | null | undefined): unknown;
61
- declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
163
+ declare function stringifyJSON<T>(value: T | {
164
+ toJSON(): T;
165
+ }): undefined extends T ? undefined | string : string;
62
166
 
63
167
  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
168
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
67
169
  maps: Segment[][];
68
170
  values: unknown[];
@@ -75,11 +177,32 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
75
177
  * Check if the value satisfy a `object` type in typescript
76
178
  */
77
179
  declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
180
+ declare function clone<T>(value: T): T;
181
+ declare function get(object: object, path: readonly string[]): unknown;
182
+ declare function isPropertyKey(value: unknown): value is PropertyKey;
183
+ declare const NullProtoObj: ({
184
+ new <T extends Record<PropertyKey, unknown>>(): T;
185
+ });
78
186
 
79
- type MaybeOptionalOptions<TOptions> = [options: TOptions] | (Record<never, never> extends TOptions ? [] : never);
80
- type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
187
+ interface AsyncIdQueueCloseOptions {
188
+ id?: string;
189
+ reason?: unknown;
190
+ }
191
+ declare class AsyncIdQueue<T> {
192
+ private readonly openIds;
193
+ private readonly items;
194
+ private readonly pendingPulls;
195
+ get length(): number;
196
+ open(id: string): void;
197
+ isOpen(id: string): boolean;
198
+ push(id: string, item: T): void;
199
+ pull(id: string): Promise<T>;
200
+ close({ id, reason }?: AsyncIdQueueCloseOptions): void;
201
+ assertOpen(id: string): void;
202
+ }
81
203
 
82
- type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
83
- declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>;
204
+ type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
205
+ declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
84
206
 
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 };
207
+ export { AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, SequentialIdGenerator, clone, defer, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, replicateAsyncIterator, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
208
+ export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
package/dist/index.d.ts CHANGED
@@ -1,68 +1,170 @@
1
1
  import { Promisable } from 'type-fest';
2
- export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
3
- export { group, guard, mapEntries, mapValues, omit, retry, trim } from 'radash';
2
+ export { IsEqual, IsNever, JsonValue, PartialDeep, Promisable } from 'type-fest';
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>;
14
+ /**
15
+ * Executes the callback function after the current call stack has been cleared.
16
+ */
17
+ declare function defer(callback: () => void): void;
7
18
 
8
19
  type OmitChainMethodDeep<T extends object, K extends keyof any> = {
9
20
  [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
10
21
  };
11
22
 
12
- declare function toError(error: unknown): Error;
23
+ interface EventPublisherOptions {
24
+ /**
25
+ * Maximum number of events to buffer for async iterator subscribers.
26
+ *
27
+ * If the buffer exceeds this limit, the oldest event is dropped.
28
+ * This prevents unbounded memory growth if consumers process events slowly.
29
+ *
30
+ * Set to:
31
+ * - `0`: Disable buffering. Events must be consumed before the next one arrives.
32
+ * - `1`: Only keep the latest event. Useful for real-time updates where only the most recent value matters.
33
+ * - `Infinity`: Keep all events. Ensures no data loss, but may lead to high memory usage.
34
+ *
35
+ * @default 100
36
+ */
37
+ maxBufferedEvents?: number;
38
+ }
39
+ interface EventPublisherSubscribeIteratorOptions extends EventPublisherOptions {
40
+ /**
41
+ * Aborts the async iterator. Throws if aborted before or during pulling.
42
+ */
43
+ signal?: AbortSignal;
44
+ }
45
+ declare class EventPublisher<T extends Record<PropertyKey, any>> {
46
+ #private;
47
+ constructor(options?: EventPublisherOptions);
48
+ get size(): number;
49
+ /**
50
+ * Emits an event and delivers the payload to all subscribed listeners.
51
+ */
52
+ publish<K extends keyof T>(event: K, payload: T[K]): void;
53
+ /**
54
+ * Subscribes to a specific event using a callback function.
55
+ * Returns an unsubscribe function to remove the listener.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * const unsubscribe = publisher.subscribe('event', (payload) => {
60
+ * console.log(payload)
61
+ * })
62
+ *
63
+ * // Later
64
+ * unsubscribe()
65
+ * ```
66
+ */
67
+ subscribe<K extends keyof T>(event: K, listener: (payload: T[K]) => void): () => void;
68
+ /**
69
+ * Subscribes to a specific event using an async iterator.
70
+ * Useful for `for await...of` loops with optional buffering and abort support.
71
+ *
72
+ * @example
73
+ * ```ts
74
+ * for await (const payload of publisher.subscribe('event', { signal })) {
75
+ * console.log(payload)
76
+ * }
77
+ * ```
78
+ */
79
+ subscribe<K extends keyof T>(event: K, options?: EventPublisherSubscribeIteratorOptions): AsyncGenerator<T[K]> & AsyncIteratorObject<T[K]>;
80
+ }
13
81
 
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> & {
82
+ declare class SequentialIdGenerator {
83
+ private index;
84
+ generate(): string;
85
+ }
86
+
87
+ type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
88
+ type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
89
+ type PromiseWithError<T, TError> = Promise<T> & {
19
90
  __error?: {
20
91
  type: TError;
21
92
  };
22
93
  };
94
+ /**
95
+ * The place where you can config the orpc types.
96
+ *
97
+ * - `throwableError` the error type that represent throwable errors should be `Error` or `null | undefined | {}` if you want more strict.
98
+ */
99
+ interface Registry {
100
+ }
101
+ type ThrowableError = Registry extends {
102
+ throwableError: infer T;
103
+ } ? T : Error;
104
+
105
+ type InterceptableOptions = Record<string, any>;
106
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
107
+ next(options?: TOptions): TResult;
108
+ };
109
+ type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult;
23
110
  /**
24
111
  * Can used for interceptors or middlewares
25
112
  */
26
- declare function onStart<TOptions extends {
113
+ declare function onStart<T, TOptions extends {
27
114
  next(): any;
28
- }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
115
+ }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
29
116
  /**
30
117
  * Can used for interceptors or middlewares
31
118
  */
32
- declare function onSuccess<TOptions extends {
119
+ declare function onSuccess<T, TOptions extends {
33
120
  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']>>>;
121
+ }, 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
122
  /**
36
123
  * Can used for interceptors or middlewares
37
124
  */
38
- declare function onError<TError, TOptions extends {
125
+ declare function onError<T, TOptions extends {
39
126
  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'];
127
+ }, 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']>>>;
128
+ type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess: false] | [error: null, data: TResult, isSuccess: true];
46
129
  /**
47
130
  * Can used for interceptors or middlewares
48
131
  */
49
- declare function onFinish<TError, TOptions extends {
132
+ declare function onFinish<T, TOptions extends {
50
133
  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
- };
56
- declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
134
+ }, 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']>>>;
135
+ declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
57
136
 
58
137
  declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
138
+ interface AsyncIteratorClassNextFn<T, TReturn> {
139
+ (): Promise<IteratorResult<T, TReturn>>;
140
+ }
141
+ interface AsyncIteratorClassCleanupFn {
142
+ (reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
143
+ }
144
+ declare const fallbackAsyncDisposeSymbol: unique symbol;
145
+ declare const asyncDisposeSymbol: typeof Symbol extends {
146
+ asyncDispose: infer T;
147
+ } ? T : typeof fallbackAsyncDisposeSymbol;
148
+ declare class AsyncIteratorClass<T, TReturn = unknown, TNext = unknown> implements AsyncIteratorObject<T, TReturn, TNext>, AsyncGenerator<T, TReturn, TNext> {
149
+ #private;
150
+ constructor(next: AsyncIteratorClassNextFn<T, TReturn>, cleanup: AsyncIteratorClassCleanupFn);
151
+ next(): Promise<IteratorResult<T, TReturn>>;
152
+ return(value?: any): Promise<IteratorResult<T, TReturn>>;
153
+ throw(err: any): Promise<IteratorResult<T, TReturn>>;
154
+ /**
155
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
156
+ */
157
+ [asyncDisposeSymbol](): Promise<void>;
158
+ [Symbol.asyncIterator](): this;
159
+ }
160
+ declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorClass<T, TReturn, TNext>)[];
59
161
 
60
162
  declare function parseEmptyableJSON(text: string | null | undefined): unknown;
61
- declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
163
+ declare function stringifyJSON<T>(value: T | {
164
+ toJSON(): T;
165
+ }): undefined extends T ? undefined | string : string;
62
166
 
63
167
  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
168
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
67
169
  maps: Segment[][];
68
170
  values: unknown[];
@@ -75,11 +177,32 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
75
177
  * Check if the value satisfy a `object` type in typescript
76
178
  */
77
179
  declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
180
+ declare function clone<T>(value: T): T;
181
+ declare function get(object: object, path: readonly string[]): unknown;
182
+ declare function isPropertyKey(value: unknown): value is PropertyKey;
183
+ declare const NullProtoObj: ({
184
+ new <T extends Record<PropertyKey, unknown>>(): T;
185
+ });
78
186
 
79
- type MaybeOptionalOptions<TOptions> = [options: TOptions] | (Record<never, never> extends TOptions ? [] : never);
80
- type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
187
+ interface AsyncIdQueueCloseOptions {
188
+ id?: string;
189
+ reason?: unknown;
190
+ }
191
+ declare class AsyncIdQueue<T> {
192
+ private readonly openIds;
193
+ private readonly items;
194
+ private readonly pendingPulls;
195
+ get length(): number;
196
+ open(id: string): void;
197
+ isOpen(id: string): boolean;
198
+ push(id: string, item: T): void;
199
+ pull(id: string): Promise<T>;
200
+ close({ id, reason }?: AsyncIdQueueCloseOptions): void;
201
+ assertOpen(id: string): void;
202
+ }
81
203
 
82
- type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
83
- declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>;
204
+ type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
205
+ declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
84
206
 
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 };
207
+ export { AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, SequentialIdGenerator, clone, defer, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, replicateAsyncIterator, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
208
+ export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
package/dist/index.mjs CHANGED
@@ -1,86 +1,323 @@
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;
3
+ function resolveMaybeOptionalOptions(rest) {
4
+ return rest[0] ?? {};
5
+ }
6
+
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)];
13
+ }
14
+
15
+ function once(fn) {
16
+ let cached;
17
+ return () => {
18
+ if (cached) {
19
+ return cached.result;
21
20
  }
22
- currentRef = currentRef[preSegment];
23
- preSegment = segment;
24
- }
25
- if (typeof currentRef !== "object" && typeof currentRef !== "function" || currentRef === null) {
26
- return void 0;
21
+ const result = fn();
22
+ cached = { result };
23
+ return result;
24
+ };
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
+ function defer(callback) {
36
+ if (typeof setTimeout === "function") {
37
+ setTimeout(callback, 0);
38
+ } else {
39
+ Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(callback)));
27
40
  }
28
- return currentRef[preSegment];
29
41
  }
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);
42
+
43
+ class AsyncIdQueue {
44
+ openIds = /* @__PURE__ */ new Set();
45
+ items = /* @__PURE__ */ new Map();
46
+ pendingPulls = /* @__PURE__ */ new Map();
47
+ get length() {
48
+ return this.openIds.size;
49
+ }
50
+ open(id) {
51
+ this.openIds.add(id);
52
+ }
53
+ isOpen(id) {
54
+ return this.openIds.has(id);
55
+ }
56
+ push(id, item) {
57
+ this.assertOpen(id);
58
+ const pending = this.pendingPulls.get(id);
59
+ if (pending?.length) {
60
+ pending.shift()[0](item);
61
+ if (pending.length === 0) {
62
+ this.pendingPulls.delete(id);
63
+ }
64
+ } else {
65
+ const items = this.items.get(id);
66
+ if (items) {
67
+ items.push(item);
68
+ } else {
69
+ this.items.set(id, [item]);
70
+ }
71
+ }
72
+ }
73
+ async pull(id) {
74
+ this.assertOpen(id);
75
+ const items = this.items.get(id);
76
+ if (items?.length) {
77
+ const item = items.shift();
78
+ if (items.length === 0) {
79
+ this.items.delete(id);
80
+ }
81
+ return item;
82
+ }
83
+ return new Promise((resolve, reject) => {
84
+ const waitingPulls = this.pendingPulls.get(id);
85
+ const pending = [resolve, reject];
86
+ if (waitingPulls) {
87
+ waitingPulls.push(pending);
88
+ } else {
89
+ this.pendingPulls.set(id, [pending]);
90
+ }
37
91
  });
38
- } else if (isObject(payload)) {
39
- for (const key in payload) {
40
- findDeepMatches(check, payload[key], [...segments, key], maps, values);
92
+ }
93
+ close({ id, reason } = {}) {
94
+ if (id === void 0) {
95
+ this.pendingPulls.forEach((pendingPulls, id2) => {
96
+ pendingPulls.forEach(([, reject]) => {
97
+ reject(reason ?? new Error(`[AsyncIdQueue] Queue[${id2}] was closed or aborted while waiting for pulling.`));
98
+ });
99
+ });
100
+ this.pendingPulls.clear();
101
+ this.openIds.clear();
102
+ this.items.clear();
103
+ return;
104
+ }
105
+ this.pendingPulls.get(id)?.forEach(([, reject]) => {
106
+ reject(reason ?? new Error(`[AsyncIdQueue] Queue[${id}] was closed or aborted while waiting for pulling.`));
107
+ });
108
+ this.pendingPulls.delete(id);
109
+ this.openIds.delete(id);
110
+ this.items.delete(id);
111
+ }
112
+ assertOpen(id) {
113
+ if (!this.isOpen(id)) {
114
+ throw new Error(`[AsyncIdQueue] Cannot access queue[${id}] because it is not open or aborted.`);
41
115
  }
42
116
  }
43
- return { maps, values };
44
117
  }
45
- function isObject(value) {
46
- if (!value || typeof value !== "object") {
118
+
119
+ function isAsyncIteratorObject(maybe) {
120
+ if (!maybe || typeof maybe !== "object") {
47
121
  return false;
48
122
  }
49
- const proto = Object.getPrototypeOf(value);
50
- return proto === Object.prototype || !proto || !proto.constructor;
123
+ return Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
51
124
  }
52
- function isTypescriptObject(value) {
53
- return !!value && (typeof value === "object" || typeof value === "function");
125
+ const fallbackAsyncDisposeSymbol = Symbol.for("asyncDispose");
126
+ const asyncDisposeSymbol = Symbol.asyncDispose ?? fallbackAsyncDisposeSymbol;
127
+ class AsyncIteratorClass {
128
+ #isDone = false;
129
+ #isExecuteComplete = false;
130
+ #cleanup;
131
+ #next;
132
+ constructor(next, cleanup) {
133
+ this.#cleanup = cleanup;
134
+ this.#next = sequential(async () => {
135
+ if (this.#isDone) {
136
+ return { done: true, value: void 0 };
137
+ }
138
+ try {
139
+ const result = await next();
140
+ if (result.done) {
141
+ this.#isDone = true;
142
+ }
143
+ return result;
144
+ } catch (err) {
145
+ this.#isDone = true;
146
+ throw err;
147
+ } finally {
148
+ if (this.#isDone && !this.#isExecuteComplete) {
149
+ this.#isExecuteComplete = true;
150
+ await this.#cleanup("next");
151
+ }
152
+ }
153
+ });
154
+ }
155
+ next() {
156
+ return this.#next();
157
+ }
158
+ async return(value) {
159
+ this.#isDone = true;
160
+ if (!this.#isExecuteComplete) {
161
+ this.#isExecuteComplete = true;
162
+ await this.#cleanup("return");
163
+ }
164
+ return { done: true, value };
165
+ }
166
+ async throw(err) {
167
+ this.#isDone = true;
168
+ if (!this.#isExecuteComplete) {
169
+ this.#isExecuteComplete = true;
170
+ await this.#cleanup("throw");
171
+ }
172
+ throw err;
173
+ }
174
+ /**
175
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
176
+ */
177
+ async [asyncDisposeSymbol]() {
178
+ this.#isDone = true;
179
+ if (!this.#isExecuteComplete) {
180
+ this.#isExecuteComplete = true;
181
+ await this.#cleanup("dispose");
182
+ }
183
+ }
184
+ [Symbol.asyncIterator]() {
185
+ return this;
186
+ }
187
+ }
188
+ function replicateAsyncIterator(source, count) {
189
+ const queue = new AsyncIdQueue();
190
+ const replicated = [];
191
+ let error;
192
+ const start = once(async () => {
193
+ try {
194
+ while (true) {
195
+ const item = await source.next();
196
+ for (let id = 0; id < count; id++) {
197
+ if (queue.isOpen(id.toString())) {
198
+ queue.push(id.toString(), item);
199
+ }
200
+ }
201
+ if (item.done) {
202
+ break;
203
+ }
204
+ }
205
+ } catch (e) {
206
+ error = { value: e };
207
+ }
208
+ });
209
+ for (let id = 0; id < count; id++) {
210
+ queue.open(id.toString());
211
+ replicated.push(new AsyncIteratorClass(
212
+ () => {
213
+ start();
214
+ return new Promise((resolve, reject) => {
215
+ queue.pull(id.toString()).then(resolve).catch(reject);
216
+ defer(() => {
217
+ if (error) {
218
+ reject(error.value);
219
+ }
220
+ });
221
+ });
222
+ },
223
+ async (reason) => {
224
+ queue.close({ id: id.toString() });
225
+ if (reason !== "next") {
226
+ if (replicated.every((_, id2) => !queue.isOpen(id2.toString()))) {
227
+ await source?.return?.();
228
+ }
229
+ }
230
+ }
231
+ ));
232
+ }
233
+ return replicated;
54
234
  }
55
235
 
56
- function toError(error) {
57
- if (error instanceof Error) {
58
- return error;
236
+ class EventPublisher {
237
+ #listenersMap = /* @__PURE__ */ new Map();
238
+ #maxBufferedEvents;
239
+ constructor(options = {}) {
240
+ this.#maxBufferedEvents = options.maxBufferedEvents ?? 100;
59
241
  }
60
- if (typeof error === "string") {
61
- return new Error(error, { cause: error });
242
+ get size() {
243
+ return this.#listenersMap.size;
62
244
  }
63
- if (isObject(error)) {
64
- if ("message" in error && typeof error.message === "string") {
65
- return new Error(error.message, { cause: error });
245
+ /**
246
+ * Emits an event and delivers the payload to all subscribed listeners.
247
+ */
248
+ publish(event, payload) {
249
+ const listeners = this.#listenersMap.get(event);
250
+ if (!listeners) {
251
+ return;
66
252
  }
67
- if ("name" in error && typeof error.name === "string") {
68
- return new Error(error.name, { cause: error });
253
+ for (const listener of listeners) {
254
+ listener(payload);
69
255
  }
70
256
  }
71
- return new Error("Unknown error", { cause: error });
257
+ subscribe(event, listenerOrOptions) {
258
+ if (typeof listenerOrOptions === "function") {
259
+ let listeners = this.#listenersMap.get(event);
260
+ if (!listeners) {
261
+ this.#listenersMap.set(event, listeners = /* @__PURE__ */ new Set());
262
+ }
263
+ listeners.add(listenerOrOptions);
264
+ return () => {
265
+ listeners.delete(listenerOrOptions);
266
+ if (listeners.size === 0) {
267
+ this.#listenersMap.delete(event);
268
+ }
269
+ };
270
+ }
271
+ const signal = listenerOrOptions?.signal;
272
+ const maxBufferedEvents = listenerOrOptions?.maxBufferedEvents ?? this.#maxBufferedEvents;
273
+ signal?.throwIfAborted();
274
+ const bufferedEvents = [];
275
+ const pullResolvers = [];
276
+ const unsubscribe = this.subscribe(event, (payload) => {
277
+ const resolver = pullResolvers.shift();
278
+ if (resolver) {
279
+ resolver[0]({ done: false, value: payload });
280
+ } else {
281
+ bufferedEvents.push(payload);
282
+ if (bufferedEvents.length > maxBufferedEvents) {
283
+ bufferedEvents.shift();
284
+ }
285
+ }
286
+ });
287
+ const abortListener = (event2) => {
288
+ unsubscribe();
289
+ pullResolvers.forEach((resolver) => resolver[1](event2.target.reason));
290
+ pullResolvers.length = 0;
291
+ bufferedEvents.length = 0;
292
+ };
293
+ signal?.addEventListener("abort", abortListener, { once: true });
294
+ return new AsyncIteratorClass(async () => {
295
+ if (signal?.aborted) {
296
+ throw signal.reason;
297
+ }
298
+ if (bufferedEvents.length > 0) {
299
+ return { done: false, value: bufferedEvents.shift() };
300
+ }
301
+ return new Promise((resolve, reject) => {
302
+ pullResolvers.push([resolve, reject]);
303
+ });
304
+ }, async () => {
305
+ unsubscribe();
306
+ signal?.removeEventListener("abort", abortListener);
307
+ pullResolvers.forEach((resolver) => resolver[0]({ done: true, value: void 0 }));
308
+ pullResolvers.length = 0;
309
+ bufferedEvents.length = 0;
310
+ });
311
+ }
72
312
  }
73
313
 
74
- function once(fn) {
75
- let cached;
76
- return () => {
77
- if (cached) {
78
- return cached.result;
79
- }
80
- const result = fn();
81
- cached = { result };
82
- return result;
83
- };
314
+ class SequentialIdGenerator {
315
+ index = BigInt(0);
316
+ generate() {
317
+ const id = this.index.toString(32);
318
+ this.index++;
319
+ return id;
320
+ }
84
321
  }
85
322
 
86
323
  function onStart(callback) {
@@ -111,36 +348,28 @@ function onFinish(callback) {
111
348
  return async (options, ...rest) => {
112
349
  try {
113
350
  const result = await options.next();
114
- state = [result, void 0, "success"];
351
+ state = [null, result, true];
115
352
  return result;
116
353
  } catch (error) {
117
- state = [void 0, error, "error"];
354
+ state = [error, void 0, false];
118
355
  throw error;
119
356
  } finally {
120
357
  await callback(state, options, ...rest);
121
358
  }
122
359
  };
123
360
  }
124
- async function intercept(interceptors, options, main) {
125
- let index = 0;
126
- const next = async (options2) => {
127
- const interceptor = interceptors[index++];
361
+ function intercept(interceptors, options, main) {
362
+ const next = (options2, index) => {
363
+ const interceptor = interceptors[index];
128
364
  if (!interceptor) {
129
- return await main(options2);
365
+ return main(options2);
130
366
  }
131
- return await interceptor({
367
+ return interceptor({
132
368
  ...options2,
133
- next: (newOptions = options2) => next(newOptions)
369
+ next: (newOptions = options2) => next(newOptions, index + 1)
134
370
  });
135
371
  };
136
- return await next(options);
137
- }
138
-
139
- function isAsyncIteratorObject(maybe) {
140
- if (!maybe || typeof maybe !== "object") {
141
- return false;
142
- }
143
- return Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
372
+ return next(options, 0);
144
373
  }
145
374
 
146
375
  function parseEmptyableJSON(text) {
@@ -153,6 +382,66 @@ function stringifyJSON(value) {
153
382
  return JSON.stringify(value);
154
383
  }
155
384
 
385
+ function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
386
+ if (check(payload)) {
387
+ maps.push(segments);
388
+ values.push(payload);
389
+ } else if (Array.isArray(payload)) {
390
+ payload.forEach((v, i) => {
391
+ findDeepMatches(check, v, [...segments, i], maps, values);
392
+ });
393
+ } else if (isObject(payload)) {
394
+ for (const key in payload) {
395
+ findDeepMatches(check, payload[key], [...segments, key], maps, values);
396
+ }
397
+ }
398
+ return { maps, values };
399
+ }
400
+ function isObject(value) {
401
+ if (!value || typeof value !== "object") {
402
+ return false;
403
+ }
404
+ const proto = Object.getPrototypeOf(value);
405
+ return proto === Object.prototype || !proto || !proto.constructor;
406
+ }
407
+ function isTypescriptObject(value) {
408
+ return !!value && (typeof value === "object" || typeof value === "function");
409
+ }
410
+ function clone(value) {
411
+ if (Array.isArray(value)) {
412
+ return value.map(clone);
413
+ }
414
+ if (isObject(value)) {
415
+ const result = {};
416
+ for (const key in value) {
417
+ result[key] = clone(value[key]);
418
+ }
419
+ return result;
420
+ }
421
+ return value;
422
+ }
423
+ function get(object, path) {
424
+ let current = object;
425
+ for (const key of path) {
426
+ if (!isTypescriptObject(current)) {
427
+ return void 0;
428
+ }
429
+ current = current[key];
430
+ }
431
+ return current;
432
+ }
433
+ function isPropertyKey(value) {
434
+ const type = typeof value;
435
+ return type === "string" || type === "number" || type === "symbol";
436
+ }
437
+ const NullProtoObj = /* @__PURE__ */ (() => {
438
+ const e = function() {
439
+ };
440
+ e.prototype = /* @__PURE__ */ Object.create(null);
441
+ Object.freeze(e.prototype);
442
+ return e;
443
+ })();
444
+
156
445
  function value(value2, ...args) {
157
446
  if (typeof value2 === "function") {
158
447
  return value2(...args);
@@ -160,4 +449,4 @@ function value(value2, ...args) {
160
449
  return value2;
161
450
  }
162
451
 
163
- export { findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, set, stringifyJSON, toError, value };
452
+ export { AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, SequentialIdGenerator, clone, defer, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, replicateAsyncIterator, 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.e7ee5a9",
4
+ "version": "0.0.0-next.e82d760",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -24,8 +24,13 @@
24
24
  "dist"
25
25
  ],
26
26
  "dependencies": {
27
- "radash": "^12.1.0",
28
- "type-fest": "^4.26.1"
27
+ "radash": "^12.1.1",
28
+ "type-fest": "^4.39.1"
29
+ },
30
+ "devDependencies": {
31
+ "arktype": "2.1.20",
32
+ "valibot": "^1.1.0",
33
+ "zod": "^3.25.67"
29
34
  },
30
35
  "scripts": {
31
36
  "build": "unbuild",