@orpc/shared 0.0.0-next.f81b4a2 → 0.0.0-next.f9e0a4c

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,8 +1,3 @@
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
-
6
1
  <div align="center">
7
2
  <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 alt="oRPC logo" />
8
3
  </div>
@@ -26,28 +21,24 @@
26
21
 
27
22
  <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
28
23
 
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, ensuring a smooth and enjoyable developer experience.
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
30
25
 
31
26
  ---
32
27
 
33
28
  ## Highlights
34
29
 
35
- - **End-to-End Type Safety 🔒**: Ensure complete type safety from inputs to outputs and errors, bridging server and client seamlessly.
36
- - **First-Class OpenAPI 📄**: Adheres to the OpenAPI standard out of the box, ensuring seamless integration and comprehensive API documentation.
37
- - **Contract-First Development 📜**: (Optional) Define your API contract upfront and implement it with confidence.
38
- - **Exceptional Developer Experience ✨**: Enjoy a streamlined workflow with robust typing and clear, in-code documentation.
39
- - **Multi-Runtime Support 🌍**: Run your code seamlessly on Cloudflare, Deno, Bun, Node.js, and more.
40
- - **Framework Integrations 🧩**: Supports Tanstack Query (React, Vue, Solid, Svelte), Pinia Colada, and more.
41
- - **Server Actions ⚡️**: Fully compatible with React Server Actions on Next.js, TanStack Start, and more.
42
- - **Standard Schema Support 🗂️**: Effortlessly work with Zod, Valibot, ArkType, and others right out of the box.
43
- - **Fast & Lightweight 💨**: Built on native APIs across all runtimes – optimized for speed and efficiency.
44
- - **Native Types 📦**: Enjoy built-in support for Date, File, Blob, BigInt, URL and more with no extra setup.
45
- - **Lazy Router ⏱️**: Improve cold start times with our lazy routing feature.
46
- - **SSE & Streaming 📡**: Provides SSE and streaming features – perfect for real-time notifications and AI-powered streaming responses.
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.
30
+ - **🔗 End-to-End Type Safety**: Ensure type-safe inputs, outputs, and errors from client to server.
31
+ - **📘 First-Class OpenAPI**: Built-in support that fully adheres to the OpenAPI standard.
32
+ - **📝 Contract-First Development**: Optionally define your API contract before implementation.
33
+ - **🔍 First-Class OpenTelemetry**: Seamlessly integrate with OpenTelemetry for observability.
34
+ - **⚙️ Framework Integrations**: Seamlessly integrate with TanStack Query (React, Vue, Solid, Svelte, Angular), Pinia Colada, and more.
35
+ - **🚀 Server Actions**: Fully compatible with React Server Actions on Next.js, TanStack Start, and other platforms.
36
+ - **🔠 Standard Schema Support**: Works out of the box with Zod, Valibot, ArkType, and other schema validators.
37
+ - **🗃️ Native Types**: Supports native types like Date, File, Blob, BigInt, URL, and more.
38
+ - **⏱️ Lazy Router**: Enhance cold start times with our lazy routing feature.
39
+ - **📡 SSE & Streaming**: Enjoy full type-safe support for SSE and streaming.
40
+ - **🌍 Multi-Runtime Support**: Fast and lightweight on Cloudflare, Deno, Bun, Node.js, and beyond.
41
+ - **🔌 Extendability**: Easily extend functionality with plugins, middleware, and interceptors.
51
42
 
52
43
  ## Documentation
53
44
 
@@ -58,13 +49,13 @@ You can find the full documentation [here](https://orpc.unnoq.com).
58
49
  - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
59
50
  - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
60
51
  - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
52
+ - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
53
+ - [@orpc/otel](https://www.npmjs.com/package/@orpc/otel): [OpenTelemetry](https://opentelemetry.io/) integration for observability.
54
+ - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with [NestJS](https://nestjs.com/).
61
55
  - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
62
- - [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
63
- - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
64
- - [@orpc/solid-query](https://www.npmjs.com/package/@orpc/solid-query): Integration with [Solid Query](https://tanstack.com/query/latest/docs/framework/solid/overview).
65
- - [@orpc/svelte-query](https://www.npmjs.com/package/@orpc/svelte-query): Integration with [Svelte Query](https://tanstack.com/query/latest/docs/framework/svelte/overview).
56
+ - [@orpc/tanstack-query](https://www.npmjs.com/package/@orpc/tanstack-query): [TanStack Query](https://tanstack.com/query/latest) integration.
66
57
  - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
67
- - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
58
+ - [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration.
68
59
  - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
69
60
  - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
70
61
  - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
package/dist/index.d.mts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Promisable } from 'type-fest';
2
- export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
2
+ export { IsEqual, IsNever, JsonValue, PartialDeep, Promisable } from 'type-fest';
3
+ import { Tracer, TraceAPI, ContextAPI, PropagationAPI, SpanOptions, Context, Span, AttributeValue, Exception } from '@opentelemetry/api';
3
4
  export { group, guard, mapEntries, mapValues, omit } from 'radash';
4
5
 
5
6
  type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
@@ -8,13 +9,101 @@ declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>):
8
9
  declare function toArray<T>(value: T): T extends readonly any[] ? T : Exclude<T, undefined | null>[];
9
10
  declare function splitInHalf<T>(arr: readonly T[]): [T[], T[]];
10
11
 
12
+ /**
13
+ * Converts Request/Response/Blob/File/.. to a buffer (ArrayBuffer or Uint8Array).
14
+ *
15
+ * Prefers the newer `.bytes` method when available as it more efficient but not widely supported yet.
16
+ */
17
+ declare function readAsBuffer(source: Pick<Blob, 'arrayBuffer' | 'bytes'>): Promise<ArrayBuffer | Uint8Array>;
18
+
11
19
  type AnyFunction = (...args: any[]) => any;
12
20
  declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
21
+ declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
22
+ /**
23
+ * Executes the callback function after the current call stack has been cleared.
24
+ */
25
+ declare function defer(callback: () => void): void;
13
26
 
14
27
  type OmitChainMethodDeep<T extends object, K extends keyof any> = {
15
28
  [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
16
29
  };
17
30
 
31
+ declare const ORPC_NAME = "orpc";
32
+ declare const ORPC_SHARED_PACKAGE_NAME = "@orpc/shared";
33
+ declare const ORPC_SHARED_PACKAGE_VERSION = "0.0.0-next.f9e0a4c";
34
+
35
+ /**
36
+ * Error thrown when an operation is aborted.
37
+ * Uses the standardized 'AbortError' name for consistency with JavaScript APIs.
38
+ */
39
+ declare class AbortError extends Error {
40
+ constructor(...rest: ConstructorParameters<typeof Error>);
41
+ }
42
+
43
+ interface EventPublisherOptions {
44
+ /**
45
+ * Maximum number of events to buffer for async iterator subscribers.
46
+ *
47
+ * If the buffer exceeds this limit, the oldest event is dropped.
48
+ * This prevents unbounded memory growth if consumers process events slowly.
49
+ *
50
+ * Set to:
51
+ * - `0`: Disable buffering. Events must be consumed before the next one arrives.
52
+ * - `1`: Only keep the latest event. Useful for real-time updates where only the most recent value matters.
53
+ * - `Infinity`: Keep all events. Ensures no data loss, but may lead to high memory usage.
54
+ *
55
+ * @default 100
56
+ */
57
+ maxBufferedEvents?: number;
58
+ }
59
+ interface EventPublisherSubscribeIteratorOptions extends EventPublisherOptions {
60
+ /**
61
+ * Aborts the async iterator. Throws if aborted before or during pulling.
62
+ */
63
+ signal?: AbortSignal;
64
+ }
65
+ declare class EventPublisher<T extends Record<PropertyKey, any>> {
66
+ #private;
67
+ constructor(options?: EventPublisherOptions);
68
+ get size(): number;
69
+ /**
70
+ * Emits an event and delivers the payload to all subscribed listeners.
71
+ */
72
+ publish<K extends keyof T>(event: K, payload: T[K]): void;
73
+ /**
74
+ * Subscribes to a specific event using a callback function.
75
+ * Returns an unsubscribe function to remove the listener.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * const unsubscribe = publisher.subscribe('event', (payload) => {
80
+ * console.log(payload)
81
+ * })
82
+ *
83
+ * // Later
84
+ * unsubscribe()
85
+ * ```
86
+ */
87
+ subscribe<K extends keyof T>(event: K, listener: (payload: T[K]) => void): () => void;
88
+ /**
89
+ * Subscribes to a specific event using an async iterator.
90
+ * Useful for `for await...of` loops with optional buffering and abort support.
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * for await (const payload of publisher.subscribe('event', { signal })) {
95
+ * console.log(payload)
96
+ * }
97
+ * ```
98
+ */
99
+ subscribe<K extends keyof T>(event: K, options?: EventPublisherSubscribeIteratorOptions): AsyncGenerator<T[K]> & AsyncIteratorObject<T[K]>;
100
+ }
101
+
102
+ declare class SequentialIdGenerator {
103
+ private index;
104
+ generate(): string;
105
+ }
106
+
18
107
  type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
19
108
  type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
20
109
  type PromiseWithError<T, TError> = Promise<T> & {
@@ -34,10 +123,10 @@ type ThrowableError = Registry extends {
34
123
  } ? T : Error;
35
124
 
36
125
  type InterceptableOptions = Record<string, any>;
37
- type InterceptorOptions<TOptions extends InterceptableOptions, TResult, TError> = Omit<TOptions, 'next'> & {
38
- next(options?: TOptions): PromiseWithError<TResult, TError>;
126
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
127
+ next(options?: TOptions): TResult;
39
128
  };
40
- type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult, TError>) => Promisable<TResult>;
129
+ type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult;
41
130
  /**
42
131
  * Can used for interceptors or middlewares
43
132
  */
@@ -63,12 +152,110 @@ type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess
63
152
  declare function onFinish<T, TOptions extends {
64
153
  next(): any;
65
154
  }, 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']>>>;
66
- declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
155
+ declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
156
+
157
+ /**
158
+ * Only import types from @opentelemetry/api to avoid runtime dependencies.
159
+ */
160
+
161
+ interface OtelConfig {
162
+ tracer: Tracer;
163
+ trace: TraceAPI;
164
+ context: ContextAPI;
165
+ propagation: PropagationAPI;
166
+ }
167
+ /**
168
+ * Sets the global OpenTelemetry config.
169
+ * Call this once at app startup. Use `undefined` to disable tracing.
170
+ */
171
+ declare function setGlobalOtelConfig(config: OtelConfig | undefined): void;
172
+ /**
173
+ * Gets the global OpenTelemetry config.
174
+ * Returns `undefined` if OpenTelemetry is not configured, initialized, or enabled.
175
+ */
176
+ declare function getGlobalOtelConfig(): OtelConfig | undefined;
177
+ /**
178
+ * Starts a new OpenTelemetry span with the given name and options.
179
+ *
180
+ * @returns The new span, or `undefined` if no tracer is set.
181
+ */
182
+ declare function startSpan(name: string, options?: SpanOptions, context?: Context): Span | undefined;
183
+ interface SetSpanErrorOptions {
184
+ /**
185
+ * Span error status is not set if error is due to cancellation by the signal.
186
+ */
187
+ signal?: AbortSignal;
188
+ }
189
+ /**
190
+ * Records and sets the error status on the given span.
191
+ * If the span is `undefined`, it does nothing.
192
+ */
193
+ declare function setSpanError(span: Span | undefined, error: unknown, options?: SetSpanErrorOptions): void;
194
+ declare function setSpanAttribute(span: Span | undefined, key: string, value: AttributeValue | undefined): void;
195
+ /**
196
+ * Converts an error to an OpenTelemetry Exception.
197
+ */
198
+ declare function toOtelException(error: unknown): Exclude<Exception, string>;
199
+ /**
200
+ * Converts a value to a string suitable for OpenTelemetry span attributes.
201
+ */
202
+ declare function toSpanAttributeValue(data: unknown): string;
203
+ interface RunWithSpanOptions extends SpanOptions, SetSpanErrorOptions {
204
+ /**
205
+ * The name of the span to create.
206
+ */
207
+ name: string;
208
+ /**
209
+ * Context to use for the span.
210
+ */
211
+ context?: Context;
212
+ }
213
+ /**
214
+ * Runs a function within the context of a new OpenTelemetry span.
215
+ * The span is ended automatically, and errors are recorded to the span.
216
+ */
217
+ declare function runWithSpan<T>({ name, context, ...options }: RunWithSpanOptions, fn: (span?: Span) => Promisable<T>): Promise<T>;
218
+ /**
219
+ * Runs a function within the context of an existing OpenTelemetry span.
220
+ */
221
+ declare function runInSpanContext<T>(span: Span | undefined, fn: () => Promisable<T>): Promise<T>;
67
222
 
68
223
  declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
224
+ interface AsyncIteratorClassNextFn<T, TReturn> {
225
+ (): Promise<IteratorResult<T, TReturn>>;
226
+ }
227
+ interface AsyncIteratorClassCleanupFn {
228
+ (reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
229
+ }
230
+ declare const fallbackAsyncDisposeSymbol: unique symbol;
231
+ declare const asyncDisposeSymbol: typeof Symbol extends {
232
+ asyncDispose: infer T;
233
+ } ? T : typeof fallbackAsyncDisposeSymbol;
234
+ declare class AsyncIteratorClass<T, TReturn = unknown, TNext = unknown> implements AsyncIteratorObject<T, TReturn, TNext>, AsyncGenerator<T, TReturn, TNext> {
235
+ #private;
236
+ constructor(next: AsyncIteratorClassNextFn<T, TReturn>, cleanup: AsyncIteratorClassCleanupFn);
237
+ next(): Promise<IteratorResult<T, TReturn>>;
238
+ return(value?: any): Promise<IteratorResult<T, TReturn>>;
239
+ throw(err: any): Promise<IteratorResult<T, TReturn>>;
240
+ /**
241
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
242
+ */
243
+ [asyncDisposeSymbol](): Promise<void>;
244
+ [Symbol.asyncIterator](): this;
245
+ }
246
+ declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorClass<T, TReturn, TNext>)[];
247
+ interface AsyncIteratorWithSpanOptions extends SetSpanErrorOptions {
248
+ /**
249
+ * The name of the span to create.
250
+ */
251
+ name: string;
252
+ }
253
+ declare function asyncIteratorWithSpan<T, TReturn, TNext>({ name, ...options }: AsyncIteratorWithSpanOptions, iterator: AsyncIterator<T, TReturn, TNext>): AsyncIteratorClass<T, TReturn, TNext>;
69
254
 
70
255
  declare function parseEmptyableJSON(text: string | null | undefined): unknown;
71
- declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
256
+ declare function stringifyJSON<T>(value: T | {
257
+ toJSON(): T;
258
+ }): undefined extends T ? undefined | string : string;
72
259
 
73
260
  type Segment = string | number;
74
261
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
@@ -84,10 +271,36 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
84
271
  */
85
272
  declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
86
273
  declare function clone<T>(value: T): T;
87
- declare function get(object: object, path: readonly string[]): unknown;
274
+ declare function get(object: unknown, path: readonly string[]): unknown;
275
+ declare function isPropertyKey(value: unknown): value is PropertyKey;
276
+ declare const NullProtoObj: ({
277
+ new <T extends Record<PropertyKey, unknown>>(): T;
278
+ });
279
+
280
+ interface AsyncIdQueueCloseOptions {
281
+ id?: string;
282
+ reason?: unknown;
283
+ }
284
+ declare class AsyncIdQueue<T> {
285
+ private readonly openIds;
286
+ private readonly items;
287
+ private readonly pendingPulls;
288
+ get length(): number;
289
+ open(id: string): void;
290
+ isOpen(id: string): boolean;
291
+ push(id: string, item: T): void;
292
+ pull(id: string): Promise<T>;
293
+ close({ id, reason }?: AsyncIdQueueCloseOptions): void;
294
+ assertOpen(id: string): void;
295
+ }
296
+
297
+ declare function streamToAsyncIteratorClass<T>(stream: ReadableStream<T>): AsyncIteratorClass<T>;
298
+ declare function asyncIteratorToStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
299
+
300
+ declare function tryDecodeURIComponent(value: string): string;
88
301
 
89
- type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
90
- declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>;
302
+ type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
303
+ declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
91
304
 
92
- export { clone, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, splitInHalf, stringifyJSON, toArray, value };
93
- export type { AnyFunction, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
305
+ export { AbortError, AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorWithSpan, clone, defer, findDeepMatches, get, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitInHalf, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };
306
+ export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, AsyncIteratorWithSpanOptions, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, OtelConfig, PromiseWithError, Registry, RunWithSpanOptions, Segment, SetOptional, SetSpanErrorOptions, ThrowableError, Value };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Promisable } from 'type-fest';
2
- export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
2
+ export { IsEqual, IsNever, JsonValue, PartialDeep, Promisable } from 'type-fest';
3
+ import { Tracer, TraceAPI, ContextAPI, PropagationAPI, SpanOptions, Context, Span, AttributeValue, Exception } from '@opentelemetry/api';
3
4
  export { group, guard, mapEntries, mapValues, omit } from 'radash';
4
5
 
5
6
  type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
@@ -8,13 +9,101 @@ declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>):
8
9
  declare function toArray<T>(value: T): T extends readonly any[] ? T : Exclude<T, undefined | null>[];
9
10
  declare function splitInHalf<T>(arr: readonly T[]): [T[], T[]];
10
11
 
12
+ /**
13
+ * Converts Request/Response/Blob/File/.. to a buffer (ArrayBuffer or Uint8Array).
14
+ *
15
+ * Prefers the newer `.bytes` method when available as it more efficient but not widely supported yet.
16
+ */
17
+ declare function readAsBuffer(source: Pick<Blob, 'arrayBuffer' | 'bytes'>): Promise<ArrayBuffer | Uint8Array>;
18
+
11
19
  type AnyFunction = (...args: any[]) => any;
12
20
  declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
21
+ declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
22
+ /**
23
+ * Executes the callback function after the current call stack has been cleared.
24
+ */
25
+ declare function defer(callback: () => void): void;
13
26
 
14
27
  type OmitChainMethodDeep<T extends object, K extends keyof any> = {
15
28
  [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
16
29
  };
17
30
 
31
+ declare const ORPC_NAME = "orpc";
32
+ declare const ORPC_SHARED_PACKAGE_NAME = "@orpc/shared";
33
+ declare const ORPC_SHARED_PACKAGE_VERSION = "0.0.0-next.f9e0a4c";
34
+
35
+ /**
36
+ * Error thrown when an operation is aborted.
37
+ * Uses the standardized 'AbortError' name for consistency with JavaScript APIs.
38
+ */
39
+ declare class AbortError extends Error {
40
+ constructor(...rest: ConstructorParameters<typeof Error>);
41
+ }
42
+
43
+ interface EventPublisherOptions {
44
+ /**
45
+ * Maximum number of events to buffer for async iterator subscribers.
46
+ *
47
+ * If the buffer exceeds this limit, the oldest event is dropped.
48
+ * This prevents unbounded memory growth if consumers process events slowly.
49
+ *
50
+ * Set to:
51
+ * - `0`: Disable buffering. Events must be consumed before the next one arrives.
52
+ * - `1`: Only keep the latest event. Useful for real-time updates where only the most recent value matters.
53
+ * - `Infinity`: Keep all events. Ensures no data loss, but may lead to high memory usage.
54
+ *
55
+ * @default 100
56
+ */
57
+ maxBufferedEvents?: number;
58
+ }
59
+ interface EventPublisherSubscribeIteratorOptions extends EventPublisherOptions {
60
+ /**
61
+ * Aborts the async iterator. Throws if aborted before or during pulling.
62
+ */
63
+ signal?: AbortSignal;
64
+ }
65
+ declare class EventPublisher<T extends Record<PropertyKey, any>> {
66
+ #private;
67
+ constructor(options?: EventPublisherOptions);
68
+ get size(): number;
69
+ /**
70
+ * Emits an event and delivers the payload to all subscribed listeners.
71
+ */
72
+ publish<K extends keyof T>(event: K, payload: T[K]): void;
73
+ /**
74
+ * Subscribes to a specific event using a callback function.
75
+ * Returns an unsubscribe function to remove the listener.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * const unsubscribe = publisher.subscribe('event', (payload) => {
80
+ * console.log(payload)
81
+ * })
82
+ *
83
+ * // Later
84
+ * unsubscribe()
85
+ * ```
86
+ */
87
+ subscribe<K extends keyof T>(event: K, listener: (payload: T[K]) => void): () => void;
88
+ /**
89
+ * Subscribes to a specific event using an async iterator.
90
+ * Useful for `for await...of` loops with optional buffering and abort support.
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * for await (const payload of publisher.subscribe('event', { signal })) {
95
+ * console.log(payload)
96
+ * }
97
+ * ```
98
+ */
99
+ subscribe<K extends keyof T>(event: K, options?: EventPublisherSubscribeIteratorOptions): AsyncGenerator<T[K]> & AsyncIteratorObject<T[K]>;
100
+ }
101
+
102
+ declare class SequentialIdGenerator {
103
+ private index;
104
+ generate(): string;
105
+ }
106
+
18
107
  type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
19
108
  type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
20
109
  type PromiseWithError<T, TError> = Promise<T> & {
@@ -34,10 +123,10 @@ type ThrowableError = Registry extends {
34
123
  } ? T : Error;
35
124
 
36
125
  type InterceptableOptions = Record<string, any>;
37
- type InterceptorOptions<TOptions extends InterceptableOptions, TResult, TError> = Omit<TOptions, 'next'> & {
38
- next(options?: TOptions): PromiseWithError<TResult, TError>;
126
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
127
+ next(options?: TOptions): TResult;
39
128
  };
40
- type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult, TError>) => Promisable<TResult>;
129
+ type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult;
41
130
  /**
42
131
  * Can used for interceptors or middlewares
43
132
  */
@@ -63,12 +152,110 @@ type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess
63
152
  declare function onFinish<T, TOptions extends {
64
153
  next(): any;
65
154
  }, 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']>>>;
66
- declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
155
+ declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
156
+
157
+ /**
158
+ * Only import types from @opentelemetry/api to avoid runtime dependencies.
159
+ */
160
+
161
+ interface OtelConfig {
162
+ tracer: Tracer;
163
+ trace: TraceAPI;
164
+ context: ContextAPI;
165
+ propagation: PropagationAPI;
166
+ }
167
+ /**
168
+ * Sets the global OpenTelemetry config.
169
+ * Call this once at app startup. Use `undefined` to disable tracing.
170
+ */
171
+ declare function setGlobalOtelConfig(config: OtelConfig | undefined): void;
172
+ /**
173
+ * Gets the global OpenTelemetry config.
174
+ * Returns `undefined` if OpenTelemetry is not configured, initialized, or enabled.
175
+ */
176
+ declare function getGlobalOtelConfig(): OtelConfig | undefined;
177
+ /**
178
+ * Starts a new OpenTelemetry span with the given name and options.
179
+ *
180
+ * @returns The new span, or `undefined` if no tracer is set.
181
+ */
182
+ declare function startSpan(name: string, options?: SpanOptions, context?: Context): Span | undefined;
183
+ interface SetSpanErrorOptions {
184
+ /**
185
+ * Span error status is not set if error is due to cancellation by the signal.
186
+ */
187
+ signal?: AbortSignal;
188
+ }
189
+ /**
190
+ * Records and sets the error status on the given span.
191
+ * If the span is `undefined`, it does nothing.
192
+ */
193
+ declare function setSpanError(span: Span | undefined, error: unknown, options?: SetSpanErrorOptions): void;
194
+ declare function setSpanAttribute(span: Span | undefined, key: string, value: AttributeValue | undefined): void;
195
+ /**
196
+ * Converts an error to an OpenTelemetry Exception.
197
+ */
198
+ declare function toOtelException(error: unknown): Exclude<Exception, string>;
199
+ /**
200
+ * Converts a value to a string suitable for OpenTelemetry span attributes.
201
+ */
202
+ declare function toSpanAttributeValue(data: unknown): string;
203
+ interface RunWithSpanOptions extends SpanOptions, SetSpanErrorOptions {
204
+ /**
205
+ * The name of the span to create.
206
+ */
207
+ name: string;
208
+ /**
209
+ * Context to use for the span.
210
+ */
211
+ context?: Context;
212
+ }
213
+ /**
214
+ * Runs a function within the context of a new OpenTelemetry span.
215
+ * The span is ended automatically, and errors are recorded to the span.
216
+ */
217
+ declare function runWithSpan<T>({ name, context, ...options }: RunWithSpanOptions, fn: (span?: Span) => Promisable<T>): Promise<T>;
218
+ /**
219
+ * Runs a function within the context of an existing OpenTelemetry span.
220
+ */
221
+ declare function runInSpanContext<T>(span: Span | undefined, fn: () => Promisable<T>): Promise<T>;
67
222
 
68
223
  declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
224
+ interface AsyncIteratorClassNextFn<T, TReturn> {
225
+ (): Promise<IteratorResult<T, TReturn>>;
226
+ }
227
+ interface AsyncIteratorClassCleanupFn {
228
+ (reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
229
+ }
230
+ declare const fallbackAsyncDisposeSymbol: unique symbol;
231
+ declare const asyncDisposeSymbol: typeof Symbol extends {
232
+ asyncDispose: infer T;
233
+ } ? T : typeof fallbackAsyncDisposeSymbol;
234
+ declare class AsyncIteratorClass<T, TReturn = unknown, TNext = unknown> implements AsyncIteratorObject<T, TReturn, TNext>, AsyncGenerator<T, TReturn, TNext> {
235
+ #private;
236
+ constructor(next: AsyncIteratorClassNextFn<T, TReturn>, cleanup: AsyncIteratorClassCleanupFn);
237
+ next(): Promise<IteratorResult<T, TReturn>>;
238
+ return(value?: any): Promise<IteratorResult<T, TReturn>>;
239
+ throw(err: any): Promise<IteratorResult<T, TReturn>>;
240
+ /**
241
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
242
+ */
243
+ [asyncDisposeSymbol](): Promise<void>;
244
+ [Symbol.asyncIterator](): this;
245
+ }
246
+ declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorClass<T, TReturn, TNext>)[];
247
+ interface AsyncIteratorWithSpanOptions extends SetSpanErrorOptions {
248
+ /**
249
+ * The name of the span to create.
250
+ */
251
+ name: string;
252
+ }
253
+ declare function asyncIteratorWithSpan<T, TReturn, TNext>({ name, ...options }: AsyncIteratorWithSpanOptions, iterator: AsyncIterator<T, TReturn, TNext>): AsyncIteratorClass<T, TReturn, TNext>;
69
254
 
70
255
  declare function parseEmptyableJSON(text: string | null | undefined): unknown;
71
- declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
256
+ declare function stringifyJSON<T>(value: T | {
257
+ toJSON(): T;
258
+ }): undefined extends T ? undefined | string : string;
72
259
 
73
260
  type Segment = string | number;
74
261
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
@@ -84,10 +271,36 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
84
271
  */
85
272
  declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
86
273
  declare function clone<T>(value: T): T;
87
- declare function get(object: object, path: readonly string[]): unknown;
274
+ declare function get(object: unknown, path: readonly string[]): unknown;
275
+ declare function isPropertyKey(value: unknown): value is PropertyKey;
276
+ declare const NullProtoObj: ({
277
+ new <T extends Record<PropertyKey, unknown>>(): T;
278
+ });
279
+
280
+ interface AsyncIdQueueCloseOptions {
281
+ id?: string;
282
+ reason?: unknown;
283
+ }
284
+ declare class AsyncIdQueue<T> {
285
+ private readonly openIds;
286
+ private readonly items;
287
+ private readonly pendingPulls;
288
+ get length(): number;
289
+ open(id: string): void;
290
+ isOpen(id: string): boolean;
291
+ push(id: string, item: T): void;
292
+ pull(id: string): Promise<T>;
293
+ close({ id, reason }?: AsyncIdQueueCloseOptions): void;
294
+ assertOpen(id: string): void;
295
+ }
296
+
297
+ declare function streamToAsyncIteratorClass<T>(stream: ReadableStream<T>): AsyncIteratorClass<T>;
298
+ declare function asyncIteratorToStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
299
+
300
+ declare function tryDecodeURIComponent(value: string): string;
88
301
 
89
- type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
90
- declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>;
302
+ type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
303
+ declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
91
304
 
92
- export { clone, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, splitInHalf, stringifyJSON, toArray, value };
93
- export type { AnyFunction, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
305
+ export { AbortError, AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorWithSpan, clone, defer, findDeepMatches, get, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitInHalf, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };
306
+ export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, AsyncIteratorWithSpanOptions, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, OtelConfig, PromiseWithError, Registry, RunWithSpanOptions, Segment, SetOptional, SetSpanErrorOptions, ThrowableError, Value };
package/dist/index.mjs CHANGED
@@ -12,6 +12,24 @@ function splitInHalf(arr) {
12
12
  return [arr.slice(0, half), arr.slice(half)];
13
13
  }
14
14
 
15
+ function readAsBuffer(source) {
16
+ if (typeof source.bytes === "function") {
17
+ return source.bytes();
18
+ }
19
+ return source.arrayBuffer();
20
+ }
21
+
22
+ const ORPC_NAME = "orpc";
23
+ const ORPC_SHARED_PACKAGE_NAME = "@orpc/shared";
24
+ const ORPC_SHARED_PACKAGE_VERSION = "0.0.0-next.f9e0a4c";
25
+
26
+ class AbortError extends Error {
27
+ constructor(...rest) {
28
+ super(...rest);
29
+ this.name = "AbortError";
30
+ }
31
+ }
32
+
15
33
  function once(fn) {
16
34
  let cached;
17
35
  return () => {
@@ -23,6 +41,423 @@ function once(fn) {
23
41
  return result;
24
42
  };
25
43
  }
44
+ function sequential(fn) {
45
+ let lastOperationPromise = Promise.resolve();
46
+ return (...args) => {
47
+ return lastOperationPromise = lastOperationPromise.catch(() => {
48
+ }).then(() => {
49
+ return fn(...args);
50
+ });
51
+ };
52
+ }
53
+ function defer(callback) {
54
+ if (typeof setTimeout === "function") {
55
+ setTimeout(callback, 0);
56
+ } else {
57
+ Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(callback)));
58
+ }
59
+ }
60
+
61
+ const SPAN_ERROR_STATUS = 2;
62
+ const GLOBAL_OTEL_CONFIG_KEY = `__${ORPC_SHARED_PACKAGE_NAME}@${ORPC_SHARED_PACKAGE_VERSION}/otel/config__`;
63
+ function setGlobalOtelConfig(config) {
64
+ globalThis[GLOBAL_OTEL_CONFIG_KEY] = config;
65
+ }
66
+ function getGlobalOtelConfig() {
67
+ return globalThis[GLOBAL_OTEL_CONFIG_KEY];
68
+ }
69
+ function startSpan(name, options = {}, context) {
70
+ const tracer = getGlobalOtelConfig()?.tracer;
71
+ return tracer?.startSpan(name, options, context);
72
+ }
73
+ function setSpanError(span, error, options = {}) {
74
+ if (!span) {
75
+ return;
76
+ }
77
+ const exception = toOtelException(error);
78
+ span.recordException(exception);
79
+ if (!options.signal?.aborted || options.signal.reason !== error) {
80
+ span.setStatus({
81
+ code: SPAN_ERROR_STATUS,
82
+ message: exception.message
83
+ });
84
+ }
85
+ }
86
+ function setSpanAttribute(span, key, value) {
87
+ if (!span || value === void 0) {
88
+ return;
89
+ }
90
+ span.setAttribute(key, value);
91
+ }
92
+ function toOtelException(error) {
93
+ if (error instanceof Error) {
94
+ const exception = {
95
+ message: error.message,
96
+ name: error.name,
97
+ stack: error.stack
98
+ };
99
+ if ("code" in error && (typeof error.code === "string" || typeof error.code === "number")) {
100
+ exception.code = error.code;
101
+ }
102
+ return exception;
103
+ }
104
+ return { message: String(error) };
105
+ }
106
+ function toSpanAttributeValue(data) {
107
+ if (data === void 0) {
108
+ return "undefined";
109
+ }
110
+ try {
111
+ return JSON.stringify(data, (_, value) => {
112
+ if (typeof value === "bigint") {
113
+ return value.toString();
114
+ }
115
+ if (value instanceof Map || value instanceof Set) {
116
+ return Array.from(value);
117
+ }
118
+ return value;
119
+ });
120
+ } catch {
121
+ return String(data);
122
+ }
123
+ }
124
+ async function runWithSpan({ name, context, ...options }, fn) {
125
+ const tracer = getGlobalOtelConfig()?.tracer;
126
+ if (!tracer) {
127
+ return fn();
128
+ }
129
+ const callback = async (span) => {
130
+ try {
131
+ return await fn(span);
132
+ } catch (e) {
133
+ setSpanError(span, e, options);
134
+ throw e;
135
+ } finally {
136
+ span.end();
137
+ }
138
+ };
139
+ if (context) {
140
+ return tracer.startActiveSpan(name, options, context, callback);
141
+ } else {
142
+ return tracer.startActiveSpan(name, options, callback);
143
+ }
144
+ }
145
+ async function runInSpanContext(span, fn) {
146
+ const otelConfig = getGlobalOtelConfig();
147
+ if (!span || !otelConfig) {
148
+ return fn();
149
+ }
150
+ const ctx = otelConfig.trace.setSpan(otelConfig.context.active(), span);
151
+ return otelConfig.context.with(ctx, fn);
152
+ }
153
+
154
+ class AsyncIdQueue {
155
+ openIds = /* @__PURE__ */ new Set();
156
+ items = /* @__PURE__ */ new Map();
157
+ pendingPulls = /* @__PURE__ */ new Map();
158
+ get length() {
159
+ return this.openIds.size;
160
+ }
161
+ open(id) {
162
+ this.openIds.add(id);
163
+ }
164
+ isOpen(id) {
165
+ return this.openIds.has(id);
166
+ }
167
+ push(id, item) {
168
+ this.assertOpen(id);
169
+ const pending = this.pendingPulls.get(id);
170
+ if (pending?.length) {
171
+ pending.shift()[0](item);
172
+ if (pending.length === 0) {
173
+ this.pendingPulls.delete(id);
174
+ }
175
+ } else {
176
+ const items = this.items.get(id);
177
+ if (items) {
178
+ items.push(item);
179
+ } else {
180
+ this.items.set(id, [item]);
181
+ }
182
+ }
183
+ }
184
+ async pull(id) {
185
+ this.assertOpen(id);
186
+ const items = this.items.get(id);
187
+ if (items?.length) {
188
+ const item = items.shift();
189
+ if (items.length === 0) {
190
+ this.items.delete(id);
191
+ }
192
+ return item;
193
+ }
194
+ return new Promise((resolve, reject) => {
195
+ const waitingPulls = this.pendingPulls.get(id);
196
+ const pending = [resolve, reject];
197
+ if (waitingPulls) {
198
+ waitingPulls.push(pending);
199
+ } else {
200
+ this.pendingPulls.set(id, [pending]);
201
+ }
202
+ });
203
+ }
204
+ close({ id, reason } = {}) {
205
+ if (id === void 0) {
206
+ this.pendingPulls.forEach((pendingPulls, id2) => {
207
+ pendingPulls.forEach(([, reject]) => {
208
+ reject(reason ?? new Error(`[AsyncIdQueue] Queue[${id2}] was closed or aborted while waiting for pulling.`));
209
+ });
210
+ });
211
+ this.pendingPulls.clear();
212
+ this.openIds.clear();
213
+ this.items.clear();
214
+ return;
215
+ }
216
+ this.pendingPulls.get(id)?.forEach(([, reject]) => {
217
+ reject(reason ?? new Error(`[AsyncIdQueue] Queue[${id}] was closed or aborted while waiting for pulling.`));
218
+ });
219
+ this.pendingPulls.delete(id);
220
+ this.openIds.delete(id);
221
+ this.items.delete(id);
222
+ }
223
+ assertOpen(id) {
224
+ if (!this.isOpen(id)) {
225
+ throw new Error(`[AsyncIdQueue] Cannot access queue[${id}] because it is not open or aborted.`);
226
+ }
227
+ }
228
+ }
229
+
230
+ function isAsyncIteratorObject(maybe) {
231
+ if (!maybe || typeof maybe !== "object") {
232
+ return false;
233
+ }
234
+ return "next" in maybe && typeof maybe.next === "function" && Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
235
+ }
236
+ const fallbackAsyncDisposeSymbol = Symbol.for("asyncDispose");
237
+ const asyncDisposeSymbol = Symbol.asyncDispose ?? fallbackAsyncDisposeSymbol;
238
+ class AsyncIteratorClass {
239
+ #isDone = false;
240
+ #isExecuteComplete = false;
241
+ #cleanup;
242
+ #next;
243
+ constructor(next, cleanup) {
244
+ this.#cleanup = cleanup;
245
+ this.#next = sequential(async () => {
246
+ if (this.#isDone) {
247
+ return { done: true, value: void 0 };
248
+ }
249
+ try {
250
+ const result = await next();
251
+ if (result.done) {
252
+ this.#isDone = true;
253
+ }
254
+ return result;
255
+ } catch (err) {
256
+ this.#isDone = true;
257
+ throw err;
258
+ } finally {
259
+ if (this.#isDone && !this.#isExecuteComplete) {
260
+ this.#isExecuteComplete = true;
261
+ await this.#cleanup("next");
262
+ }
263
+ }
264
+ });
265
+ }
266
+ next() {
267
+ return this.#next();
268
+ }
269
+ async return(value) {
270
+ this.#isDone = true;
271
+ if (!this.#isExecuteComplete) {
272
+ this.#isExecuteComplete = true;
273
+ await this.#cleanup("return");
274
+ }
275
+ return { done: true, value };
276
+ }
277
+ async throw(err) {
278
+ this.#isDone = true;
279
+ if (!this.#isExecuteComplete) {
280
+ this.#isExecuteComplete = true;
281
+ await this.#cleanup("throw");
282
+ }
283
+ throw err;
284
+ }
285
+ /**
286
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
287
+ */
288
+ async [asyncDisposeSymbol]() {
289
+ this.#isDone = true;
290
+ if (!this.#isExecuteComplete) {
291
+ this.#isExecuteComplete = true;
292
+ await this.#cleanup("dispose");
293
+ }
294
+ }
295
+ [Symbol.asyncIterator]() {
296
+ return this;
297
+ }
298
+ }
299
+ function replicateAsyncIterator(source, count) {
300
+ const queue = new AsyncIdQueue();
301
+ const replicated = [];
302
+ let error;
303
+ const start = once(async () => {
304
+ try {
305
+ while (true) {
306
+ const item = await source.next();
307
+ for (let id = 0; id < count; id++) {
308
+ if (queue.isOpen(id.toString())) {
309
+ queue.push(id.toString(), item);
310
+ }
311
+ }
312
+ if (item.done) {
313
+ break;
314
+ }
315
+ }
316
+ } catch (e) {
317
+ error = { value: e };
318
+ }
319
+ });
320
+ for (let id = 0; id < count; id++) {
321
+ queue.open(id.toString());
322
+ replicated.push(new AsyncIteratorClass(
323
+ () => {
324
+ start();
325
+ return new Promise((resolve, reject) => {
326
+ queue.pull(id.toString()).then(resolve).catch(reject);
327
+ defer(() => {
328
+ if (error) {
329
+ reject(error.value);
330
+ }
331
+ });
332
+ });
333
+ },
334
+ async (reason) => {
335
+ queue.close({ id: id.toString() });
336
+ if (reason !== "next") {
337
+ if (replicated.every((_, id2) => !queue.isOpen(id2.toString()))) {
338
+ await source?.return?.();
339
+ }
340
+ }
341
+ }
342
+ ));
343
+ }
344
+ return replicated;
345
+ }
346
+ function asyncIteratorWithSpan({ name, ...options }, iterator) {
347
+ let span;
348
+ return new AsyncIteratorClass(
349
+ async () => {
350
+ span ??= startSpan(name);
351
+ try {
352
+ const result = await runInSpanContext(span, () => iterator.next());
353
+ span?.addEvent(result.done ? "completed" : "yielded");
354
+ return result;
355
+ } catch (err) {
356
+ setSpanError(span, err, options);
357
+ throw err;
358
+ }
359
+ },
360
+ async (reason) => {
361
+ try {
362
+ if (reason !== "next") {
363
+ await runInSpanContext(span, () => iterator.return?.());
364
+ }
365
+ } catch (err) {
366
+ setSpanError(span, err, options);
367
+ throw err;
368
+ } finally {
369
+ span?.end();
370
+ }
371
+ }
372
+ );
373
+ }
374
+
375
+ class EventPublisher {
376
+ #listenersMap = /* @__PURE__ */ new Map();
377
+ #maxBufferedEvents;
378
+ constructor(options = {}) {
379
+ this.#maxBufferedEvents = options.maxBufferedEvents ?? 100;
380
+ }
381
+ get size() {
382
+ return this.#listenersMap.size;
383
+ }
384
+ /**
385
+ * Emits an event and delivers the payload to all subscribed listeners.
386
+ */
387
+ publish(event, payload) {
388
+ const listeners = this.#listenersMap.get(event);
389
+ if (!listeners) {
390
+ return;
391
+ }
392
+ for (const listener of listeners) {
393
+ listener(payload);
394
+ }
395
+ }
396
+ subscribe(event, listenerOrOptions) {
397
+ if (typeof listenerOrOptions === "function") {
398
+ let listeners = this.#listenersMap.get(event);
399
+ if (!listeners) {
400
+ this.#listenersMap.set(event, listeners = /* @__PURE__ */ new Set());
401
+ }
402
+ listeners.add(listenerOrOptions);
403
+ return () => {
404
+ listeners.delete(listenerOrOptions);
405
+ if (listeners.size === 0) {
406
+ this.#listenersMap.delete(event);
407
+ }
408
+ };
409
+ }
410
+ const signal = listenerOrOptions?.signal;
411
+ const maxBufferedEvents = listenerOrOptions?.maxBufferedEvents ?? this.#maxBufferedEvents;
412
+ signal?.throwIfAborted();
413
+ const bufferedEvents = [];
414
+ const pullResolvers = [];
415
+ const unsubscribe = this.subscribe(event, (payload) => {
416
+ const resolver = pullResolvers.shift();
417
+ if (resolver) {
418
+ resolver[0]({ done: false, value: payload });
419
+ } else {
420
+ bufferedEvents.push(payload);
421
+ if (bufferedEvents.length > maxBufferedEvents) {
422
+ bufferedEvents.shift();
423
+ }
424
+ }
425
+ });
426
+ const abortListener = (event2) => {
427
+ unsubscribe();
428
+ pullResolvers.forEach((resolver) => resolver[1](event2.target.reason));
429
+ pullResolvers.length = 0;
430
+ bufferedEvents.length = 0;
431
+ };
432
+ signal?.addEventListener("abort", abortListener, { once: true });
433
+ return new AsyncIteratorClass(async () => {
434
+ if (signal?.aborted) {
435
+ throw signal.reason;
436
+ }
437
+ if (bufferedEvents.length > 0) {
438
+ return { done: false, value: bufferedEvents.shift() };
439
+ }
440
+ return new Promise((resolve, reject) => {
441
+ pullResolvers.push([resolve, reject]);
442
+ });
443
+ }, async () => {
444
+ unsubscribe();
445
+ signal?.removeEventListener("abort", abortListener);
446
+ pullResolvers.forEach((resolver) => resolver[0]({ done: true, value: void 0 }));
447
+ pullResolvers.length = 0;
448
+ bufferedEvents.length = 0;
449
+ });
450
+ }
451
+ }
452
+
453
+ class SequentialIdGenerator {
454
+ index = BigInt(0);
455
+ generate() {
456
+ const id = this.index.toString(32);
457
+ this.index++;
458
+ return id;
459
+ }
460
+ }
26
461
 
27
462
  function onStart(callback) {
28
463
  return async (options, ...rest) => {
@@ -62,13 +497,13 @@ function onFinish(callback) {
62
497
  }
63
498
  };
64
499
  }
65
- async function intercept(interceptors, options, main) {
66
- const next = async (options2, index) => {
500
+ function intercept(interceptors, options, main) {
501
+ const next = (options2, index) => {
67
502
  const interceptor = interceptors[index];
68
503
  if (!interceptor) {
69
- return await main(options2);
504
+ return main(options2);
70
505
  }
71
- return await interceptor({
506
+ return interceptor({
72
507
  ...options2,
73
508
  next: (newOptions = options2) => next(newOptions, index + 1)
74
509
  });
@@ -76,13 +511,6 @@ async function intercept(interceptors, options, main) {
76
511
  return next(options, 0);
77
512
  }
78
513
 
79
- function isAsyncIteratorObject(maybe) {
80
- if (!maybe || typeof maybe !== "object") {
81
- return false;
82
- }
83
- return Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
84
- }
85
-
86
514
  function parseEmptyableJSON(text) {
87
515
  if (!text) {
88
516
  return void 0;
@@ -141,6 +569,52 @@ function get(object, path) {
141
569
  }
142
570
  return current;
143
571
  }
572
+ function isPropertyKey(value) {
573
+ const type = typeof value;
574
+ return type === "string" || type === "number" || type === "symbol";
575
+ }
576
+ const NullProtoObj = /* @__PURE__ */ (() => {
577
+ const e = function() {
578
+ };
579
+ e.prototype = /* @__PURE__ */ Object.create(null);
580
+ Object.freeze(e.prototype);
581
+ return e;
582
+ })();
583
+
584
+ function streamToAsyncIteratorClass(stream) {
585
+ const reader = stream.getReader();
586
+ return new AsyncIteratorClass(
587
+ async () => {
588
+ return reader.read();
589
+ },
590
+ async () => {
591
+ await reader.cancel();
592
+ }
593
+ );
594
+ }
595
+ function asyncIteratorToStream(iterator) {
596
+ return new ReadableStream({
597
+ async pull(controller) {
598
+ const { done, value } = await iterator.next();
599
+ if (done) {
600
+ controller.close();
601
+ } else {
602
+ controller.enqueue(value);
603
+ }
604
+ },
605
+ async cancel() {
606
+ await iterator.return?.();
607
+ }
608
+ });
609
+ }
610
+
611
+ function tryDecodeURIComponent(value) {
612
+ try {
613
+ return decodeURIComponent(value);
614
+ } catch {
615
+ return value;
616
+ }
617
+ }
144
618
 
145
619
  function value(value2, ...args) {
146
620
  if (typeof value2 === "function") {
@@ -149,4 +623,4 @@ function value(value2, ...args) {
149
623
  return value2;
150
624
  }
151
625
 
152
- export { clone, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, splitInHalf, stringifyJSON, toArray, value };
626
+ export { AbortError, AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorWithSpan, clone, defer, findDeepMatches, get, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitInHalf, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, 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.f81b4a2",
4
+ "version": "0.0.0-next.f9e0a4c",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -23,10 +23,24 @@
23
23
  "files": [
24
24
  "dist"
25
25
  ],
26
+ "peerDependencies": {
27
+ "@opentelemetry/api": ">=1.9.0"
28
+ },
29
+ "peerDependenciesMeta": {
30
+ "@opentelemetry/api": {
31
+ "optional": true
32
+ }
33
+ },
26
34
  "dependencies": {
27
- "radash": "^12.1.0",
35
+ "radash": "^12.1.1",
28
36
  "type-fest": "^4.39.1"
29
37
  },
38
+ "devDependencies": {
39
+ "@opentelemetry/api": "^1.9.0",
40
+ "arktype": "2.1.20",
41
+ "valibot": "^1.1.0",
42
+ "zod": "^4.0.17"
43
+ },
30
44
  "scripts": {
31
45
  "build": "unbuild",
32
46
  "build:watch": "pnpm run build --watch",