@orpc/shared 0.0.0-next.eae6003 → 0.0.0-next.ec7d801

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
@@ -54,14 +54,12 @@ You can find the full documentation [here](https://orpc.unnoq.com).
54
54
  - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
55
55
  - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
56
56
  - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
57
- - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with NestJS.
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/).
58
59
  - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
59
- - [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
60
- - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
61
- - [@orpc/solid-query](https://www.npmjs.com/package/@orpc/solid-query): Integration with [Solid Query](https://tanstack.com/query/latest/docs/framework/solid/overview).
62
- - [@orpc/svelte-query](https://www.npmjs.com/package/@orpc/svelte-query): Integration with [Svelte Query](https://tanstack.com/query/latest/docs/framework/svelte/overview).
60
+ - [@orpc/tanstack-query](https://www.npmjs.com/package/@orpc/tanstack-query): [TanStack Query](https://tanstack.com/query/latest) integration.
63
61
  - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
64
- - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
62
+ - [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration.
65
63
  - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
66
64
  - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
67
65
  - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
package/dist/index.d.mts CHANGED
@@ -11,11 +11,74 @@ declare function splitInHalf<T>(arr: readonly T[]): [T[], T[]];
11
11
  type AnyFunction = (...args: any[]) => any;
12
12
  declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
13
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;
14
18
 
15
19
  type OmitChainMethodDeep<T extends object, K extends keyof any> = {
16
20
  [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
17
21
  };
18
22
 
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
+ }
81
+
19
82
  declare class SequentialIdGenerator {
20
83
  private nextId;
21
84
  generate(): number;
@@ -40,10 +103,10 @@ type ThrowableError = Registry extends {
40
103
  } ? T : Error;
41
104
 
42
105
  type InterceptableOptions = Record<string, any>;
43
- type InterceptorOptions<TOptions extends InterceptableOptions, TResult, TError> = Omit<TOptions, 'next'> & {
44
- next(options?: TOptions): PromiseWithError<TResult, TError>;
106
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
107
+ next(options?: TOptions): TResult;
45
108
  };
46
- type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult, TError>) => Promisable<TResult>;
109
+ type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult;
47
110
  /**
48
111
  * Can used for interceptors or middlewares
49
112
  */
@@ -69,13 +132,32 @@ type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess
69
132
  declare function onFinish<T, TOptions extends {
70
133
  next(): any;
71
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']>>>;
72
- declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
135
+ declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
73
136
 
74
137
  declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
75
- interface CreateAsyncIteratorObjectCleanupFn {
138
+ interface AsyncIteratorClassNextFn<T, TReturn> {
139
+ (): Promise<IteratorResult<T, TReturn>>;
140
+ }
141
+ interface AsyncIteratorClassCleanupFn {
76
142
  (reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
77
143
  }
78
- declare function createAsyncIteratorObject<T, TReturn, TNext>(next: () => Promise<IteratorResult<T, TReturn>>, cleanup: CreateAsyncIteratorObjectCleanupFn): AsyncIteratorObject<T, TReturn, TNext> & AsyncGenerator<T, TReturn, TNext>;
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>)[];
79
161
 
80
162
  declare function parseEmptyableJSON(text: string | null | undefined): unknown;
81
163
  declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
@@ -95,10 +177,14 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
95
177
  declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
96
178
  declare function clone<T>(value: T): T;
97
179
  declare function get(object: object, path: readonly string[]): unknown;
180
+ declare function isPropertyKey(value: unknown): value is PropertyKey;
181
+ declare const NullProtoObj: ({
182
+ new <T extends Record<PropertyKey, unknown>>(): T;
183
+ });
98
184
 
99
185
  interface AsyncIdQueueCloseOptions {
100
186
  id?: number;
101
- reason?: Error;
187
+ reason?: unknown;
102
188
  }
103
189
  declare class AsyncIdQueue<T> {
104
190
  private readonly openIds;
@@ -113,8 +199,8 @@ declare class AsyncIdQueue<T> {
113
199
  assertOpen(id: number): void;
114
200
  }
115
201
 
116
- type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
117
- declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>;
202
+ type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
203
+ declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
118
204
 
119
- export { AsyncIdQueue, SequentialIdGenerator, clone, createAsyncIteratorObject, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
120
- export type { AnyFunction, AsyncIdQueueCloseOptions, CreateAsyncIteratorObjectCleanupFn, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
205
+ 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 };
206
+ 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
@@ -11,11 +11,74 @@ declare function splitInHalf<T>(arr: readonly T[]): [T[], T[]];
11
11
  type AnyFunction = (...args: any[]) => any;
12
12
  declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
13
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;
14
18
 
15
19
  type OmitChainMethodDeep<T extends object, K extends keyof any> = {
16
20
  [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
17
21
  };
18
22
 
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
+ }
81
+
19
82
  declare class SequentialIdGenerator {
20
83
  private nextId;
21
84
  generate(): number;
@@ -40,10 +103,10 @@ type ThrowableError = Registry extends {
40
103
  } ? T : Error;
41
104
 
42
105
  type InterceptableOptions = Record<string, any>;
43
- type InterceptorOptions<TOptions extends InterceptableOptions, TResult, TError> = Omit<TOptions, 'next'> & {
44
- next(options?: TOptions): PromiseWithError<TResult, TError>;
106
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
107
+ next(options?: TOptions): TResult;
45
108
  };
46
- type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult, TError>) => Promisable<TResult>;
109
+ type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult;
47
110
  /**
48
111
  * Can used for interceptors or middlewares
49
112
  */
@@ -69,13 +132,32 @@ type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess
69
132
  declare function onFinish<T, TOptions extends {
70
133
  next(): any;
71
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']>>>;
72
- declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
135
+ declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
73
136
 
74
137
  declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
75
- interface CreateAsyncIteratorObjectCleanupFn {
138
+ interface AsyncIteratorClassNextFn<T, TReturn> {
139
+ (): Promise<IteratorResult<T, TReturn>>;
140
+ }
141
+ interface AsyncIteratorClassCleanupFn {
76
142
  (reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
77
143
  }
78
- declare function createAsyncIteratorObject<T, TReturn, TNext>(next: () => Promise<IteratorResult<T, TReturn>>, cleanup: CreateAsyncIteratorObjectCleanupFn): AsyncIteratorObject<T, TReturn, TNext> & AsyncGenerator<T, TReturn, TNext>;
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>)[];
79
161
 
80
162
  declare function parseEmptyableJSON(text: string | null | undefined): unknown;
81
163
  declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
@@ -95,10 +177,14 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
95
177
  declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
96
178
  declare function clone<T>(value: T): T;
97
179
  declare function get(object: object, path: readonly string[]): unknown;
180
+ declare function isPropertyKey(value: unknown): value is PropertyKey;
181
+ declare const NullProtoObj: ({
182
+ new <T extends Record<PropertyKey, unknown>>(): T;
183
+ });
98
184
 
99
185
  interface AsyncIdQueueCloseOptions {
100
186
  id?: number;
101
- reason?: Error;
187
+ reason?: unknown;
102
188
  }
103
189
  declare class AsyncIdQueue<T> {
104
190
  private readonly openIds;
@@ -113,8 +199,8 @@ declare class AsyncIdQueue<T> {
113
199
  assertOpen(id: number): void;
114
200
  }
115
201
 
116
- type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
117
- declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>;
202
+ type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
203
+ declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
118
204
 
119
- export { AsyncIdQueue, SequentialIdGenerator, clone, createAsyncIteratorObject, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
120
- export type { AnyFunction, AsyncIdQueueCloseOptions, CreateAsyncIteratorObjectCleanupFn, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
205
+ 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 };
206
+ 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
@@ -32,6 +32,284 @@ function sequential(fn) {
32
32
  });
33
33
  };
34
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
+ 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)) {
198
+ queue.push(id, 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);
211
+ replicated.push(new AsyncIteratorClass(
212
+ () => {
213
+ start();
214
+ return new Promise((resolve, reject) => {
215
+ queue.pull(id).then(resolve).catch(reject);
216
+ defer(() => {
217
+ if (error) {
218
+ reject(error.value);
219
+ }
220
+ });
221
+ });
222
+ },
223
+ async (reason) => {
224
+ queue.close({ id });
225
+ if (reason !== "next") {
226
+ if (replicated.every((_, id2) => !queue.isOpen(id2))) {
227
+ await source?.return?.();
228
+ }
229
+ }
230
+ }
231
+ ));
232
+ }
233
+ return replicated;
234
+ }
235
+
236
+ class EventPublisher {
237
+ #listenersMap = /* @__PURE__ */ new Map();
238
+ #maxBufferedEvents;
239
+ constructor(options = {}) {
240
+ this.#maxBufferedEvents = options.maxBufferedEvents ?? 100;
241
+ }
242
+ get size() {
243
+ return this.#listenersMap.size;
244
+ }
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;
252
+ }
253
+ for (const listener of listeners) {
254
+ listener(payload);
255
+ }
256
+ }
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
+ }
312
+ }
35
313
 
36
314
  class SequentialIdGenerator {
37
315
  nextId = 0;
@@ -82,13 +360,13 @@ function onFinish(callback) {
82
360
  }
83
361
  };
84
362
  }
85
- async function intercept(interceptors, options, main) {
86
- const next = async (options2, index) => {
363
+ function intercept(interceptors, options, main) {
364
+ const next = (options2, index) => {
87
365
  const interceptor = interceptors[index];
88
366
  if (!interceptor) {
89
- return await main(options2);
367
+ return main(options2);
90
368
  }
91
- return await interceptor({
369
+ return interceptor({
92
370
  ...options2,
93
371
  next: (newOptions = options2) => next(newOptions, index + 1)
94
372
  });
@@ -96,69 +374,6 @@ async function intercept(interceptors, options, main) {
96
374
  return next(options, 0);
97
375
  }
98
376
 
99
- function isAsyncIteratorObject(maybe) {
100
- if (!maybe || typeof maybe !== "object") {
101
- return false;
102
- }
103
- return Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
104
- }
105
- function createAsyncIteratorObject(next, cleanup) {
106
- let isExecuteComplete = false;
107
- let isDone = false;
108
- const iterator = {
109
- next: sequential(async () => {
110
- if (isDone) {
111
- return { done: true, value: void 0 };
112
- }
113
- try {
114
- const result = await next();
115
- if (result.done) {
116
- isDone = true;
117
- }
118
- return result;
119
- } catch (err) {
120
- isDone = true;
121
- throw err;
122
- } finally {
123
- if (isDone && !isExecuteComplete) {
124
- isExecuteComplete = true;
125
- await cleanup("next");
126
- }
127
- }
128
- }),
129
- async return(value) {
130
- isDone = true;
131
- if (!isExecuteComplete) {
132
- isExecuteComplete = true;
133
- await cleanup("return");
134
- }
135
- return { done: true, value };
136
- },
137
- async throw(err) {
138
- isDone = true;
139
- if (!isExecuteComplete) {
140
- isExecuteComplete = true;
141
- await cleanup("throw");
142
- }
143
- throw err;
144
- },
145
- /**
146
- * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
147
- */
148
- async [Symbol.asyncDispose ?? Symbol.for("asyncDispose")]() {
149
- isDone = true;
150
- if (!isExecuteComplete) {
151
- isExecuteComplete = true;
152
- await cleanup("dispose");
153
- }
154
- },
155
- [Symbol.asyncIterator]() {
156
- return iterator;
157
- }
158
- };
159
- return iterator;
160
- }
161
-
162
377
  function parseEmptyableJSON(text) {
163
378
  if (!text) {
164
379
  return void 0;
@@ -217,82 +432,17 @@ function get(object, path) {
217
432
  }
218
433
  return current;
219
434
  }
220
-
221
- class AsyncIdQueue {
222
- openIds = /* @__PURE__ */ new Set();
223
- items = /* @__PURE__ */ new Map();
224
- pendingPulls = /* @__PURE__ */ new Map();
225
- get length() {
226
- return this.openIds.size;
227
- }
228
- open(id) {
229
- this.openIds.add(id);
230
- }
231
- isOpen(id) {
232
- return this.openIds.has(id);
233
- }
234
- push(id, item) {
235
- this.assertOpen(id);
236
- const pending = this.pendingPulls.get(id);
237
- if (pending?.length) {
238
- pending.shift()[0](item);
239
- if (pending.length === 0) {
240
- this.pendingPulls.delete(id);
241
- }
242
- } else {
243
- const items = this.items.get(id);
244
- if (items) {
245
- items.push(item);
246
- } else {
247
- this.items.set(id, [item]);
248
- }
249
- }
250
- }
251
- async pull(id) {
252
- this.assertOpen(id);
253
- const items = this.items.get(id);
254
- if (items?.length) {
255
- const item = items.shift();
256
- if (items.length === 0) {
257
- this.items.delete(id);
258
- }
259
- return item;
260
- }
261
- return new Promise((resolve, reject) => {
262
- const waitingPulls = this.pendingPulls.get(id);
263
- const pending = [resolve, reject];
264
- if (waitingPulls) {
265
- waitingPulls.push(pending);
266
- } else {
267
- this.pendingPulls.set(id, [pending]);
268
- }
269
- });
270
- }
271
- close({ id, reason } = {}) {
272
- if (id === void 0) {
273
- this.pendingPulls.forEach((pendingPulls, id2) => {
274
- pendingPulls.forEach(([, reject]) => {
275
- reject(reason ?? new Error(`[AsyncIdQueue] Queue[${id2}] was closed or aborted while waiting for pulling.`));
276
- });
277
- });
278
- this.pendingPulls.clear();
279
- this.openIds.clear();
280
- this.items.clear();
281
- return;
282
- }
283
- this.pendingPulls.get(id)?.forEach(([, reject]) => {
284
- reject(reason ?? new Error(`[AsyncIdQueue] Queue[${id}] was closed or aborted while waiting for pulling.`));
285
- });
286
- this.pendingPulls.delete(id);
287
- this.openIds.delete(id);
288
- this.items.delete(id);
289
- }
290
- assertOpen(id) {
291
- if (!this.isOpen(id)) {
292
- throw new Error(`[AsyncIdQueue] Cannot access queue[${id}] because it is not open or aborted.`);
293
- }
294
- }
435
+ function isPropertyKey(value) {
436
+ const type = typeof value;
437
+ return type === "string" || type === "number" || type === "symbol";
295
438
  }
439
+ const NullProtoObj = /* @__PURE__ */ (() => {
440
+ const e = function() {
441
+ };
442
+ e.prototype = /* @__PURE__ */ Object.create(null);
443
+ Object.freeze(e.prototype);
444
+ return e;
445
+ })();
296
446
 
297
447
  function value(value2, ...args) {
298
448
  if (typeof value2 === "function") {
@@ -301,4 +451,4 @@ function value(value2, ...args) {
301
451
  return value2;
302
452
  }
303
453
 
304
- export { AsyncIdQueue, SequentialIdGenerator, clone, createAsyncIteratorObject, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
454
+ 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.eae6003",
4
+ "version": "0.0.0-next.ec7d801",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -27,6 +27,11 @@
27
27
  "radash": "^12.1.0",
28
28
  "type-fest": "^4.39.1"
29
29
  },
30
+ "devDependencies": {
31
+ "arktype": "2.1.20",
32
+ "valibot": "^1.1.0",
33
+ "zod": "^3.25.57"
34
+ },
30
35
  "scripts": {
31
36
  "build": "unbuild",
32
37
  "build:watch": "pnpm run build --watch",