@orpc/shared 0.0.0-next.e563486 → 0.0.0-next.e7896e2
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 +26 -22
- package/dist/index.d.mts +134 -30
- package/dist/index.d.ts +134 -30
- package/dist/index.mjs +332 -24
- package/package.json +7 -2
package/README.md
CHANGED
|
@@ -26,28 +26,24 @@
|
|
|
26
26
|
|
|
27
27
|
<h3 align="center">Typesafe APIs Made Simple 🪄</h3>
|
|
28
28
|
|
|
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
|
|
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
|
|
30
30
|
|
|
31
31
|
---
|
|
32
32
|
|
|
33
33
|
## Highlights
|
|
34
34
|
|
|
35
|
-
-
|
|
36
|
-
-
|
|
37
|
-
-
|
|
38
|
-
-
|
|
39
|
-
-
|
|
40
|
-
-
|
|
41
|
-
-
|
|
42
|
-
-
|
|
43
|
-
-
|
|
44
|
-
-
|
|
45
|
-
-
|
|
46
|
-
-
|
|
47
|
-
- **Reusability 🔄**: Write once and reuse your code across multiple purposes effortlessly.
|
|
48
|
-
- **Extendability 🔌**: Easily enhance oRPC with plugins, middleware, and interceptors.
|
|
49
|
-
- **Reliability 🛡️**: Well-tested, fully TypeScript, production-ready, and MIT licensed for peace of mind.
|
|
50
|
-
- **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.
|
|
51
47
|
|
|
52
48
|
## Documentation
|
|
53
49
|
|
|
@@ -58,12 +54,12 @@ You can find the full documentation [here](https://orpc.unnoq.com).
|
|
|
58
54
|
- [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
|
|
59
55
|
- [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
|
|
60
56
|
- [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
|
|
61
|
-
- [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
|
|
62
|
-
- [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
|
|
63
|
-
- [@orpc/solid-query](https://www.npmjs.com/package/@orpc/solid-query): Integration with [Solid Query](https://tanstack.com/query/latest/docs/framework/solid/overview).
|
|
64
|
-
- [@orpc/svelte-query](https://www.npmjs.com/package/@orpc/svelte-query): Integration with [Svelte Query](https://tanstack.com/query/latest/docs/framework/svelte/overview).
|
|
65
|
-
- [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
|
|
66
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.
|
|
67
63
|
- [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
|
|
68
64
|
- [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
|
|
69
65
|
- [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
|
|
@@ -72,6 +68,14 @@ You can find the full documentation [here](https://orpc.unnoq.com).
|
|
|
72
68
|
|
|
73
69
|
Provides shared utilities for oRPC packages.
|
|
74
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
|
+
|
|
75
79
|
## License
|
|
76
80
|
|
|
77
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,61 +1,145 @@
|
|
|
1
1
|
import { Promisable } from 'type-fest';
|
|
2
2
|
export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
|
|
3
|
-
export { group, guard, mapEntries, mapValues, omit
|
|
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
|
-
|
|
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
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
}
|
|
18
|
-
|
|
82
|
+
declare class SequentialIdGenerator {
|
|
83
|
+
private nextId;
|
|
84
|
+
generate(): number;
|
|
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<
|
|
125
|
+
declare function onError<T, TOptions extends {
|
|
39
126
|
next(): any;
|
|
40
|
-
}, TRest extends any[]>(callback: NoInfer<(error:
|
|
41
|
-
|
|
42
|
-
type: TError;
|
|
43
|
-
};
|
|
44
|
-
};
|
|
45
|
-
type OnFinishState<TResult, TError> = [TResult, null, '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<
|
|
132
|
+
declare function onFinish<T, TOptions extends {
|
|
50
133
|
next(): any;
|
|
51
|
-
}, TRest extends any[]>(callback: NoInfer<(state: OnFinishState<Awaited<ReturnType<TOptions['next']>>,
|
|
52
|
-
|
|
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 CreateAsyncIteratorObjectCleanupFn {
|
|
139
|
+
(reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
|
|
140
|
+
}
|
|
141
|
+
declare function createAsyncIteratorObject<T, TReturn, TNext>(next: () => Promise<IteratorResult<T, TReturn>>, cleanup: CreateAsyncIteratorObjectCleanupFn): AsyncIteratorObject<T, TReturn, TNext> & AsyncGenerator<T, TReturn, TNext>;
|
|
142
|
+
declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorObject<T, TReturn, TNext> & AsyncGenerator<T, TReturn, TNext>)[];
|
|
59
143
|
|
|
60
144
|
declare function parseEmptyableJSON(text: string | null | undefined): unknown;
|
|
61
145
|
declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
|
|
@@ -74,11 +158,31 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
|
|
|
74
158
|
*/
|
|
75
159
|
declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
|
|
76
160
|
declare function clone<T>(value: T): T;
|
|
161
|
+
declare function get(object: object, path: readonly string[]): unknown;
|
|
162
|
+
declare function isPropertyKey(value: unknown): value is PropertyKey;
|
|
163
|
+
declare const NullProtoObj: ({
|
|
164
|
+
new <T extends Record<PropertyKey, unknown>>(): T;
|
|
165
|
+
});
|
|
77
166
|
|
|
78
|
-
|
|
79
|
-
|
|
167
|
+
interface AsyncIdQueueCloseOptions {
|
|
168
|
+
id?: number;
|
|
169
|
+
reason?: unknown;
|
|
170
|
+
}
|
|
171
|
+
declare class AsyncIdQueue<T> {
|
|
172
|
+
private readonly openIds;
|
|
173
|
+
private readonly items;
|
|
174
|
+
private readonly pendingPulls;
|
|
175
|
+
get length(): number;
|
|
176
|
+
open(id: number): void;
|
|
177
|
+
isOpen(id: number): boolean;
|
|
178
|
+
push(id: number, item: T): void;
|
|
179
|
+
pull(id: number): Promise<T>;
|
|
180
|
+
close({ id, reason }?: AsyncIdQueueCloseOptions): void;
|
|
181
|
+
assertOpen(id: number): void;
|
|
182
|
+
}
|
|
80
183
|
|
|
81
|
-
type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) =>
|
|
82
|
-
declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>):
|
|
184
|
+
type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
|
|
185
|
+
declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
|
|
83
186
|
|
|
84
|
-
export {
|
|
187
|
+
export { AsyncIdQueue, EventPublisher, NullProtoObj, SequentialIdGenerator, clone, createAsyncIteratorObject, defer, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, replicateAsyncIterator, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
|
|
188
|
+
export type { AnyFunction, AsyncIdQueueCloseOptions, CreateAsyncIteratorObjectCleanupFn, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,61 +1,145 @@
|
|
|
1
1
|
import { Promisable } from 'type-fest';
|
|
2
2
|
export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
|
|
3
|
-
export { group, guard, mapEntries, mapValues, omit
|
|
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
|
-
|
|
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
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
}
|
|
18
|
-
|
|
82
|
+
declare class SequentialIdGenerator {
|
|
83
|
+
private nextId;
|
|
84
|
+
generate(): number;
|
|
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<
|
|
125
|
+
declare function onError<T, TOptions extends {
|
|
39
126
|
next(): any;
|
|
40
|
-
}, TRest extends any[]>(callback: NoInfer<(error:
|
|
41
|
-
|
|
42
|
-
type: TError;
|
|
43
|
-
};
|
|
44
|
-
};
|
|
45
|
-
type OnFinishState<TResult, TError> = [TResult, null, '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<
|
|
132
|
+
declare function onFinish<T, TOptions extends {
|
|
50
133
|
next(): any;
|
|
51
|
-
}, TRest extends any[]>(callback: NoInfer<(state: OnFinishState<Awaited<ReturnType<TOptions['next']>>,
|
|
52
|
-
|
|
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 CreateAsyncIteratorObjectCleanupFn {
|
|
139
|
+
(reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
|
|
140
|
+
}
|
|
141
|
+
declare function createAsyncIteratorObject<T, TReturn, TNext>(next: () => Promise<IteratorResult<T, TReturn>>, cleanup: CreateAsyncIteratorObjectCleanupFn): AsyncIteratorObject<T, TReturn, TNext> & AsyncGenerator<T, TReturn, TNext>;
|
|
142
|
+
declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorObject<T, TReturn, TNext> & AsyncGenerator<T, TReturn, TNext>)[];
|
|
59
143
|
|
|
60
144
|
declare function parseEmptyableJSON(text: string | null | undefined): unknown;
|
|
61
145
|
declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
|
|
@@ -74,11 +158,31 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
|
|
|
74
158
|
*/
|
|
75
159
|
declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
|
|
76
160
|
declare function clone<T>(value: T): T;
|
|
161
|
+
declare function get(object: object, path: readonly string[]): unknown;
|
|
162
|
+
declare function isPropertyKey(value: unknown): value is PropertyKey;
|
|
163
|
+
declare const NullProtoObj: ({
|
|
164
|
+
new <T extends Record<PropertyKey, unknown>>(): T;
|
|
165
|
+
});
|
|
77
166
|
|
|
78
|
-
|
|
79
|
-
|
|
167
|
+
interface AsyncIdQueueCloseOptions {
|
|
168
|
+
id?: number;
|
|
169
|
+
reason?: unknown;
|
|
170
|
+
}
|
|
171
|
+
declare class AsyncIdQueue<T> {
|
|
172
|
+
private readonly openIds;
|
|
173
|
+
private readonly items;
|
|
174
|
+
private readonly pendingPulls;
|
|
175
|
+
get length(): number;
|
|
176
|
+
open(id: number): void;
|
|
177
|
+
isOpen(id: number): boolean;
|
|
178
|
+
push(id: number, item: T): void;
|
|
179
|
+
pull(id: number): Promise<T>;
|
|
180
|
+
close({ id, reason }?: AsyncIdQueueCloseOptions): void;
|
|
181
|
+
assertOpen(id: number): void;
|
|
182
|
+
}
|
|
80
183
|
|
|
81
|
-
type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) =>
|
|
82
|
-
declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>):
|
|
184
|
+
type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
|
|
185
|
+
declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
|
|
83
186
|
|
|
84
|
-
export {
|
|
187
|
+
export { AsyncIdQueue, EventPublisher, NullProtoObj, SequentialIdGenerator, clone, createAsyncIteratorObject, defer, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, replicateAsyncIterator, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
|
|
188
|
+
export type { AnyFunction, AsyncIdQueueCloseOptions, CreateAsyncIteratorObjectCleanupFn, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
|
package/dist/index.mjs
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
|
-
export { group, guard, mapEntries, mapValues, omit
|
|
1
|
+
export { group, guard, mapEntries, mapValues, omit } from 'radash';
|
|
2
2
|
|
|
3
|
-
function
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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)];
|
|
8
13
|
}
|
|
9
14
|
|
|
10
15
|
function once(fn) {
|
|
@@ -18,6 +23,296 @@ function once(fn) {
|
|
|
18
23
|
return result;
|
|
19
24
|
};
|
|
20
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)));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
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
|
+
}
|
|
91
|
+
});
|
|
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.`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function isAsyncIteratorObject(maybe) {
|
|
120
|
+
if (!maybe || typeof maybe !== "object") {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
return Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
|
|
124
|
+
}
|
|
125
|
+
function createAsyncIteratorObject(next, cleanup) {
|
|
126
|
+
let isExecuteComplete = false;
|
|
127
|
+
let isDone = false;
|
|
128
|
+
const iterator = {
|
|
129
|
+
next: sequential(async () => {
|
|
130
|
+
if (isDone) {
|
|
131
|
+
return { done: true, value: void 0 };
|
|
132
|
+
}
|
|
133
|
+
try {
|
|
134
|
+
const result = await next();
|
|
135
|
+
if (result.done) {
|
|
136
|
+
isDone = true;
|
|
137
|
+
}
|
|
138
|
+
return result;
|
|
139
|
+
} catch (err) {
|
|
140
|
+
isDone = true;
|
|
141
|
+
throw err;
|
|
142
|
+
} finally {
|
|
143
|
+
if (isDone && !isExecuteComplete) {
|
|
144
|
+
isExecuteComplete = true;
|
|
145
|
+
await cleanup("next");
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}),
|
|
149
|
+
async return(value) {
|
|
150
|
+
isDone = true;
|
|
151
|
+
if (!isExecuteComplete) {
|
|
152
|
+
isExecuteComplete = true;
|
|
153
|
+
await cleanup("return");
|
|
154
|
+
}
|
|
155
|
+
return { done: true, value };
|
|
156
|
+
},
|
|
157
|
+
async throw(err) {
|
|
158
|
+
isDone = true;
|
|
159
|
+
if (!isExecuteComplete) {
|
|
160
|
+
isExecuteComplete = true;
|
|
161
|
+
await cleanup("throw");
|
|
162
|
+
}
|
|
163
|
+
throw err;
|
|
164
|
+
},
|
|
165
|
+
/**
|
|
166
|
+
* asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
|
|
167
|
+
*/
|
|
168
|
+
async [Symbol.asyncDispose ?? Symbol.for("asyncDispose")]() {
|
|
169
|
+
isDone = true;
|
|
170
|
+
if (!isExecuteComplete) {
|
|
171
|
+
isExecuteComplete = true;
|
|
172
|
+
await cleanup("dispose");
|
|
173
|
+
}
|
|
174
|
+
},
|
|
175
|
+
[Symbol.asyncIterator]() {
|
|
176
|
+
return iterator;
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
return iterator;
|
|
180
|
+
}
|
|
181
|
+
function replicateAsyncIterator(source, count) {
|
|
182
|
+
const queue = new AsyncIdQueue();
|
|
183
|
+
const replicated = [];
|
|
184
|
+
let error;
|
|
185
|
+
const start = once(async () => {
|
|
186
|
+
try {
|
|
187
|
+
while (true) {
|
|
188
|
+
const item = await source.next();
|
|
189
|
+
for (let id = 0; id < count; id++) {
|
|
190
|
+
if (queue.isOpen(id)) {
|
|
191
|
+
queue.push(id, item);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (item.done) {
|
|
195
|
+
break;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
} catch (e) {
|
|
199
|
+
error = { value: e };
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
for (let id = 0; id < count; id++) {
|
|
203
|
+
queue.open(id);
|
|
204
|
+
replicated.push(createAsyncIteratorObject(
|
|
205
|
+
() => {
|
|
206
|
+
start();
|
|
207
|
+
return new Promise((resolve, reject) => {
|
|
208
|
+
queue.pull(id).then(resolve).catch(reject);
|
|
209
|
+
defer(() => {
|
|
210
|
+
if (error) {
|
|
211
|
+
reject(error.value);
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
},
|
|
216
|
+
async (reason) => {
|
|
217
|
+
queue.close({ id });
|
|
218
|
+
if (reason !== "next") {
|
|
219
|
+
if (replicated.every((_, id2) => !queue.isOpen(id2))) {
|
|
220
|
+
await source?.return?.();
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
));
|
|
225
|
+
}
|
|
226
|
+
return replicated;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
class EventPublisher {
|
|
230
|
+
#listenersMap = /* @__PURE__ */ new Map();
|
|
231
|
+
#maxBufferedEvents;
|
|
232
|
+
constructor(options = {}) {
|
|
233
|
+
this.#maxBufferedEvents = options.maxBufferedEvents ?? 100;
|
|
234
|
+
}
|
|
235
|
+
get size() {
|
|
236
|
+
return this.#listenersMap.size;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Emits an event and delivers the payload to all subscribed listeners.
|
|
240
|
+
*/
|
|
241
|
+
publish(event, payload) {
|
|
242
|
+
const listeners = this.#listenersMap.get(event);
|
|
243
|
+
if (!listeners) {
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
for (const listener of listeners) {
|
|
247
|
+
listener(payload);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
subscribe(event, listenerOrOptions) {
|
|
251
|
+
if (typeof listenerOrOptions === "function") {
|
|
252
|
+
let listeners = this.#listenersMap.get(event);
|
|
253
|
+
if (!listeners) {
|
|
254
|
+
this.#listenersMap.set(event, listeners = /* @__PURE__ */ new Set());
|
|
255
|
+
}
|
|
256
|
+
listeners.add(listenerOrOptions);
|
|
257
|
+
return () => {
|
|
258
|
+
listeners.delete(listenerOrOptions);
|
|
259
|
+
if (listeners.size === 0) {
|
|
260
|
+
this.#listenersMap.delete(event);
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
const signal = listenerOrOptions?.signal;
|
|
265
|
+
const maxBufferedEvents = listenerOrOptions?.maxBufferedEvents ?? this.#maxBufferedEvents;
|
|
266
|
+
const bufferedEvents = [];
|
|
267
|
+
const pullResolvers = [];
|
|
268
|
+
const unsubscribe = this.subscribe(event, (payload) => {
|
|
269
|
+
const resolver = pullResolvers.shift();
|
|
270
|
+
if (resolver) {
|
|
271
|
+
resolver[0]({ done: false, value: payload });
|
|
272
|
+
} else {
|
|
273
|
+
bufferedEvents.push(payload);
|
|
274
|
+
if (bufferedEvents.length > maxBufferedEvents) {
|
|
275
|
+
bufferedEvents.shift();
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
const abortListener = (event2) => {
|
|
280
|
+
unsubscribe();
|
|
281
|
+
pullResolvers.forEach((resolver) => resolver[1](event2.target.reason));
|
|
282
|
+
pullResolvers.length = 0;
|
|
283
|
+
bufferedEvents.length = 0;
|
|
284
|
+
};
|
|
285
|
+
signal?.addEventListener("abort", abortListener, { once: true });
|
|
286
|
+
return createAsyncIteratorObject(async () => {
|
|
287
|
+
if (signal?.aborted) {
|
|
288
|
+
throw signal.reason;
|
|
289
|
+
}
|
|
290
|
+
if (bufferedEvents.length > 0) {
|
|
291
|
+
return { done: false, value: bufferedEvents.shift() };
|
|
292
|
+
}
|
|
293
|
+
return new Promise((resolve, reject) => {
|
|
294
|
+
pullResolvers.push([resolve, reject]);
|
|
295
|
+
});
|
|
296
|
+
}, async () => {
|
|
297
|
+
unsubscribe();
|
|
298
|
+
signal?.removeEventListener("abort", abortListener);
|
|
299
|
+
pullResolvers.forEach((resolver) => resolver[0]({ done: true, value: void 0 }));
|
|
300
|
+
pullResolvers.length = 0;
|
|
301
|
+
bufferedEvents.length = 0;
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
class SequentialIdGenerator {
|
|
307
|
+
nextId = 0;
|
|
308
|
+
generate() {
|
|
309
|
+
if (this.nextId === Number.MAX_SAFE_INTEGER) {
|
|
310
|
+
this.nextId = 0;
|
|
311
|
+
return Number.MAX_SAFE_INTEGER;
|
|
312
|
+
}
|
|
313
|
+
return this.nextId++;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
21
316
|
|
|
22
317
|
function onStart(callback) {
|
|
23
318
|
return async (options, ...rest) => {
|
|
@@ -47,36 +342,28 @@ function onFinish(callback) {
|
|
|
47
342
|
return async (options, ...rest) => {
|
|
48
343
|
try {
|
|
49
344
|
const result = await options.next();
|
|
50
|
-
state = [
|
|
345
|
+
state = [null, result, true];
|
|
51
346
|
return result;
|
|
52
347
|
} catch (error) {
|
|
53
|
-
state = [void 0,
|
|
348
|
+
state = [error, void 0, false];
|
|
54
349
|
throw error;
|
|
55
350
|
} finally {
|
|
56
351
|
await callback(state, options, ...rest);
|
|
57
352
|
}
|
|
58
353
|
};
|
|
59
354
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
const interceptor = interceptors[index++];
|
|
355
|
+
function intercept(interceptors, options, main) {
|
|
356
|
+
const next = (options2, index) => {
|
|
357
|
+
const interceptor = interceptors[index];
|
|
64
358
|
if (!interceptor) {
|
|
65
|
-
return
|
|
359
|
+
return main(options2);
|
|
66
360
|
}
|
|
67
|
-
return
|
|
361
|
+
return interceptor({
|
|
68
362
|
...options2,
|
|
69
|
-
next: (newOptions = options2) => next(newOptions)
|
|
363
|
+
next: (newOptions = options2) => next(newOptions, index + 1)
|
|
70
364
|
});
|
|
71
365
|
};
|
|
72
|
-
return
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
function isAsyncIteratorObject(maybe) {
|
|
76
|
-
if (!maybe || typeof maybe !== "object") {
|
|
77
|
-
return false;
|
|
78
|
-
}
|
|
79
|
-
return Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
|
|
366
|
+
return next(options, 0);
|
|
80
367
|
}
|
|
81
368
|
|
|
82
369
|
function parseEmptyableJSON(text) {
|
|
@@ -127,6 +414,27 @@ function clone(value) {
|
|
|
127
414
|
}
|
|
128
415
|
return value;
|
|
129
416
|
}
|
|
417
|
+
function get(object, path) {
|
|
418
|
+
let current = object;
|
|
419
|
+
for (const key of path) {
|
|
420
|
+
if (!isTypescriptObject(current)) {
|
|
421
|
+
return void 0;
|
|
422
|
+
}
|
|
423
|
+
current = current[key];
|
|
424
|
+
}
|
|
425
|
+
return current;
|
|
426
|
+
}
|
|
427
|
+
function isPropertyKey(value) {
|
|
428
|
+
const type = typeof value;
|
|
429
|
+
return type === "string" || type === "number" || type === "symbol";
|
|
430
|
+
}
|
|
431
|
+
const NullProtoObj = /* @__PURE__ */ (() => {
|
|
432
|
+
const e = function() {
|
|
433
|
+
};
|
|
434
|
+
e.prototype = /* @__PURE__ */ Object.create(null);
|
|
435
|
+
Object.freeze(e.prototype);
|
|
436
|
+
return e;
|
|
437
|
+
})();
|
|
130
438
|
|
|
131
439
|
function value(value2, ...args) {
|
|
132
440
|
if (typeof value2 === "function") {
|
|
@@ -135,4 +443,4 @@ function value(value2, ...args) {
|
|
|
135
443
|
return value2;
|
|
136
444
|
}
|
|
137
445
|
|
|
138
|
-
export { clone, findDeepMatches, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, stringifyJSON,
|
|
446
|
+
export { AsyncIdQueue, EventPublisher, NullProtoObj, SequentialIdGenerator, clone, createAsyncIteratorObject, 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.
|
|
4
|
+
"version": "0.0.0-next.e7896e2",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://orpc.unnoq.com",
|
|
7
7
|
"repository": {
|
|
@@ -25,7 +25,12 @@
|
|
|
25
25
|
],
|
|
26
26
|
"dependencies": {
|
|
27
27
|
"radash": "^12.1.0",
|
|
28
|
-
"type-fest": "^4.
|
|
28
|
+
"type-fest": "^4.39.1"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"arktype": "2.1.20",
|
|
32
|
+
"valibot": "^1.1.0",
|
|
33
|
+
"zod": "^3.25.49"
|
|
29
34
|
},
|
|
30
35
|
"scripts": {
|
|
31
36
|
"build": "unbuild",
|