@orpc/shared 0.0.0-next.e6490f2 → 0.0.0-next.e77ba7d
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 +7 -7
- package/dist/index.d.mts +167 -19
- package/dist/index.d.ts +167 -19
- package/dist/index.mjs +315 -60
- package/package.json +14 -5
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>
|
|
@@ -22,6 +17,9 @@
|
|
|
22
17
|
<a href="https://discord.gg/TXEbwRBvQn">
|
|
23
18
|
<img alt="Discord" src="https://img.shields.io/discord/1308966753044398161?color=7389D8&label&logo=discord&logoColor=ffffff" />
|
|
24
19
|
</a>
|
|
20
|
+
<a href="https://deepwiki.com/unnoq/orpc">
|
|
21
|
+
<img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki">
|
|
22
|
+
</a>
|
|
25
23
|
</div>
|
|
26
24
|
|
|
27
25
|
<h3 align="center">Typesafe APIs Made Simple 🪄</h3>
|
|
@@ -35,7 +33,8 @@
|
|
|
35
33
|
- **🔗 End-to-End Type Safety**: Ensure type-safe inputs, outputs, and errors from client to server.
|
|
36
34
|
- **📘 First-Class OpenAPI**: Built-in support that fully adheres to the OpenAPI standard.
|
|
37
35
|
- **📝 Contract-First Development**: Optionally define your API contract before implementation.
|
|
38
|
-
-
|
|
36
|
+
- **🔍 First-Class OpenTelemetry**: Seamlessly integrate with OpenTelemetry for observability.
|
|
37
|
+
- **⚙️ Framework Integrations**: Seamlessly integrate with TanStack Query (React, Vue, Solid, Svelte, Angular), SWR, Pinia Colada, and more.
|
|
39
38
|
- **🚀 Server Actions**: Fully compatible with React Server Actions on Next.js, TanStack Start, and other platforms.
|
|
40
39
|
- **🔠 Standard Schema Support**: Works out of the box with Zod, Valibot, ArkType, and other schema validators.
|
|
41
40
|
- **🗃️ Native Types**: Supports native types like Date, File, Blob, BigInt, URL, and more.
|
|
@@ -43,7 +42,6 @@
|
|
|
43
42
|
- **📡 SSE & Streaming**: Enjoy full type-safe support for SSE and streaming.
|
|
44
43
|
- **🌍 Multi-Runtime Support**: Fast and lightweight on Cloudflare, Deno, Bun, Node.js, and beyond.
|
|
45
44
|
- **🔌 Extendability**: Easily extend functionality with plugins, middleware, and interceptors.
|
|
46
|
-
- **🛡️ Reliability**: Well-tested, TypeScript-based, production-ready, and MIT licensed.
|
|
47
45
|
|
|
48
46
|
## Documentation
|
|
49
47
|
|
|
@@ -55,9 +53,11 @@ You can find the full documentation [here](https://orpc.unnoq.com).
|
|
|
55
53
|
- [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
|
|
56
54
|
- [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
|
|
57
55
|
- [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
|
|
56
|
+
- [@orpc/otel](https://www.npmjs.com/package/@orpc/otel): [OpenTelemetry](https://opentelemetry.io/) integration for observability.
|
|
58
57
|
- [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with [NestJS](https://nestjs.com/).
|
|
59
58
|
- [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
|
|
60
59
|
- [@orpc/tanstack-query](https://www.npmjs.com/package/@orpc/tanstack-query): [TanStack Query](https://tanstack.com/query/latest) integration.
|
|
60
|
+
- [@orpc/experimental-react-swr](https://www.npmjs.com/package/@orpc/experimental-react-swr): [SWR](https://swr.vercel.app/) integration.
|
|
61
61
|
- [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
|
|
62
62
|
- [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration.
|
|
63
63
|
- [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Promisable } from 'type-fest';
|
|
2
|
-
export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
|
|
3
|
-
|
|
2
|
+
export { IsEqual, IsNever, JsonValue, PartialDeep, Promisable } from 'type-fest';
|
|
3
|
+
import { Tracer, TraceAPI, ContextAPI, PropagationAPI, SpanOptions, Context, Span, AttributeValue, Exception } from '@opentelemetry/api';
|
|
4
|
+
export { group, guard, mapEntries, mapValues, omit, retry, sleep } from 'radash';
|
|
4
5
|
|
|
5
6
|
type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
|
|
6
7
|
declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>): T;
|
|
@@ -8,6 +9,13 @@ 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>;
|
|
13
21
|
declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
|
|
@@ -20,6 +28,18 @@ type OmitChainMethodDeep<T extends object, K extends keyof any> = {
|
|
|
20
28
|
[P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
|
|
21
29
|
};
|
|
22
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.e77ba7d";
|
|
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
|
+
|
|
23
43
|
interface EventPublisherOptions {
|
|
24
44
|
/**
|
|
25
45
|
* Maximum number of events to buffer for async iterator subscribers.
|
|
@@ -40,7 +60,7 @@ interface EventPublisherSubscribeIteratorOptions extends EventPublisherOptions {
|
|
|
40
60
|
/**
|
|
41
61
|
* Aborts the async iterator. Throws if aborted before or during pulling.
|
|
42
62
|
*/
|
|
43
|
-
signal?: AbortSignal;
|
|
63
|
+
signal?: AbortSignal | undefined;
|
|
44
64
|
}
|
|
45
65
|
declare class EventPublisher<T extends Record<PropertyKey, any>> {
|
|
46
66
|
#private;
|
|
@@ -80,9 +100,17 @@ declare class EventPublisher<T extends Record<PropertyKey, any>> {
|
|
|
80
100
|
}
|
|
81
101
|
|
|
82
102
|
declare class SequentialIdGenerator {
|
|
83
|
-
private
|
|
84
|
-
generate():
|
|
103
|
+
private index;
|
|
104
|
+
generate(): string;
|
|
85
105
|
}
|
|
106
|
+
/**
|
|
107
|
+
* Compares two sequential IDs.
|
|
108
|
+
* Returns:
|
|
109
|
+
* - negative if `a` < `b`
|
|
110
|
+
* - positive if `a` > `b`
|
|
111
|
+
* - 0 if equal
|
|
112
|
+
*/
|
|
113
|
+
declare function compareSequentialIds(a: string, b: string): number;
|
|
86
114
|
|
|
87
115
|
type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
|
|
88
116
|
type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
|
|
@@ -101,6 +129,7 @@ interface Registry {
|
|
|
101
129
|
type ThrowableError = Registry extends {
|
|
102
130
|
throwableError: infer T;
|
|
103
131
|
} ? T : Error;
|
|
132
|
+
type InferAsyncIterableYield<T> = T extends AsyncIterable<infer U> ? U : never;
|
|
104
133
|
|
|
105
134
|
type InterceptableOptions = Record<string, any>;
|
|
106
135
|
type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
|
|
@@ -134,6 +163,72 @@ declare function onFinish<T, TOptions extends {
|
|
|
134
163
|
}, 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
164
|
declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
|
|
136
165
|
|
|
166
|
+
/**
|
|
167
|
+
* Only import types from @opentelemetry/api to avoid runtime dependencies.
|
|
168
|
+
*/
|
|
169
|
+
|
|
170
|
+
interface OtelConfig {
|
|
171
|
+
tracer: Tracer;
|
|
172
|
+
trace: TraceAPI;
|
|
173
|
+
context: ContextAPI;
|
|
174
|
+
propagation: PropagationAPI;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Sets the global OpenTelemetry config.
|
|
178
|
+
* Call this once at app startup. Use `undefined` to disable tracing.
|
|
179
|
+
*/
|
|
180
|
+
declare function setGlobalOtelConfig(config: OtelConfig | undefined): void;
|
|
181
|
+
/**
|
|
182
|
+
* Gets the global OpenTelemetry config.
|
|
183
|
+
* Returns `undefined` if OpenTelemetry is not configured, initialized, or enabled.
|
|
184
|
+
*/
|
|
185
|
+
declare function getGlobalOtelConfig(): OtelConfig | undefined;
|
|
186
|
+
/**
|
|
187
|
+
* Starts a new OpenTelemetry span with the given name and options.
|
|
188
|
+
*
|
|
189
|
+
* @returns The new span, or `undefined` if no tracer is set.
|
|
190
|
+
*/
|
|
191
|
+
declare function startSpan(name: string, options?: SpanOptions, context?: Context): Span | undefined;
|
|
192
|
+
interface SetSpanErrorOptions {
|
|
193
|
+
/**
|
|
194
|
+
* Span error status is not set if error is due to cancellation by the signal.
|
|
195
|
+
*/
|
|
196
|
+
signal?: AbortSignal;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Records and sets the error status on the given span.
|
|
200
|
+
* If the span is `undefined`, it does nothing.
|
|
201
|
+
*/
|
|
202
|
+
declare function setSpanError(span: Span | undefined, error: unknown, options?: SetSpanErrorOptions): void;
|
|
203
|
+
declare function setSpanAttribute(span: Span | undefined, key: string, value: AttributeValue | undefined): void;
|
|
204
|
+
/**
|
|
205
|
+
* Converts an error to an OpenTelemetry Exception.
|
|
206
|
+
*/
|
|
207
|
+
declare function toOtelException(error: unknown): Exclude<Exception, string>;
|
|
208
|
+
/**
|
|
209
|
+
* Converts a value to a string suitable for OpenTelemetry span attributes.
|
|
210
|
+
*/
|
|
211
|
+
declare function toSpanAttributeValue(data: unknown): string;
|
|
212
|
+
interface RunWithSpanOptions extends SpanOptions, SetSpanErrorOptions {
|
|
213
|
+
/**
|
|
214
|
+
* The name of the span to create.
|
|
215
|
+
*/
|
|
216
|
+
name: string;
|
|
217
|
+
/**
|
|
218
|
+
* Context to use for the span.
|
|
219
|
+
*/
|
|
220
|
+
context?: Context;
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Runs a function within the context of a new OpenTelemetry span.
|
|
224
|
+
* The span is ended automatically, and errors are recorded to the span.
|
|
225
|
+
*/
|
|
226
|
+
declare function runWithSpan<T>({ name, context, ...options }: RunWithSpanOptions, fn: (span?: Span) => Promisable<T>): Promise<T>;
|
|
227
|
+
/**
|
|
228
|
+
* Runs a function within the context of an existing OpenTelemetry span.
|
|
229
|
+
*/
|
|
230
|
+
declare function runInSpanContext<T>(span: Span | undefined, fn: () => Promisable<T>): Promise<T>;
|
|
231
|
+
|
|
137
232
|
declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
|
|
138
233
|
interface AsyncIteratorClassNextFn<T, TReturn> {
|
|
139
234
|
(): Promise<IteratorResult<T, TReturn>>;
|
|
@@ -158,15 +253,29 @@ declare class AsyncIteratorClass<T, TReturn = unknown, TNext = unknown> implemen
|
|
|
158
253
|
[Symbol.asyncIterator](): this;
|
|
159
254
|
}
|
|
160
255
|
declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorClass<T, TReturn, TNext>)[];
|
|
256
|
+
interface AsyncIteratorWithSpanOptions extends SetSpanErrorOptions {
|
|
257
|
+
/**
|
|
258
|
+
* The name of the span to create.
|
|
259
|
+
*/
|
|
260
|
+
name: string;
|
|
261
|
+
}
|
|
262
|
+
declare function asyncIteratorWithSpan<T, TReturn, TNext>({ name, ...options }: AsyncIteratorWithSpanOptions, iterator: AsyncIterator<T, TReturn, TNext>): AsyncIteratorClass<T, TReturn, TNext>;
|
|
161
263
|
|
|
162
264
|
declare function parseEmptyableJSON(text: string | null | undefined): unknown;
|
|
163
|
-
declare function stringifyJSON<T>(value: T
|
|
265
|
+
declare function stringifyJSON<T>(value: T | {
|
|
266
|
+
toJSON(): T;
|
|
267
|
+
}): undefined extends T ? undefined | string : string;
|
|
164
268
|
|
|
165
269
|
type Segment = string | number;
|
|
166
270
|
declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
|
|
167
271
|
maps: Segment[][];
|
|
168
272
|
values: unknown[];
|
|
169
273
|
};
|
|
274
|
+
/**
|
|
275
|
+
* Get constructor of the value
|
|
276
|
+
*
|
|
277
|
+
*/
|
|
278
|
+
declare function getConstructor(value: unknown): Function | null | undefined;
|
|
170
279
|
/**
|
|
171
280
|
* Check if the value is an object even it created by `Object.create(null)` or more tricky way.
|
|
172
281
|
*/
|
|
@@ -176,31 +285,70 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
|
|
|
176
285
|
*/
|
|
177
286
|
declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
|
|
178
287
|
declare function clone<T>(value: T): T;
|
|
179
|
-
declare function get(object:
|
|
288
|
+
declare function get(object: unknown, path: readonly PropertyKey[]): unknown;
|
|
180
289
|
declare function isPropertyKey(value: unknown): value is PropertyKey;
|
|
181
290
|
declare const NullProtoObj: ({
|
|
182
291
|
new <T extends Record<PropertyKey, unknown>>(): T;
|
|
183
292
|
});
|
|
184
293
|
|
|
294
|
+
type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
|
|
295
|
+
declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
|
|
296
|
+
/**
|
|
297
|
+
* Returns the value if it is defined, otherwise returns the fallback
|
|
298
|
+
*/
|
|
299
|
+
declare function fallback<T>(value: T | undefined, fallback: T): T;
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Prevents objects from being awaitable by intercepting the `then` method
|
|
303
|
+
* when called by the native await mechanism. This is useful for preventing
|
|
304
|
+
* accidental awaiting of objects that aren't meant to be promises.
|
|
305
|
+
*/
|
|
306
|
+
declare function preventNativeAwait<T extends object>(target: T): T;
|
|
307
|
+
/**
|
|
308
|
+
* Create a proxy that overlays one object (`overlay`) on top of another (`target`).
|
|
309
|
+
*
|
|
310
|
+
* - Properties from `overlay` take precedence.
|
|
311
|
+
* - Properties not in `overlay` fall back to `target`.
|
|
312
|
+
* - Methods from either object are bound to `overlay` so `this` is consistent.
|
|
313
|
+
*
|
|
314
|
+
* Useful when you want to override or extend behavior without fully copying/merging objects.
|
|
315
|
+
*/
|
|
316
|
+
declare function overlayProxy<T extends object, U extends object>(target: Value<T>, partial: U): U & Omit<T, keyof U>;
|
|
317
|
+
|
|
185
318
|
interface AsyncIdQueueCloseOptions {
|
|
186
|
-
id?:
|
|
319
|
+
id?: string;
|
|
187
320
|
reason?: unknown;
|
|
188
321
|
}
|
|
189
322
|
declare class AsyncIdQueue<T> {
|
|
190
323
|
private readonly openIds;
|
|
191
|
-
private readonly
|
|
192
|
-
private readonly
|
|
324
|
+
private readonly queues;
|
|
325
|
+
private readonly waiters;
|
|
193
326
|
get length(): number;
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
327
|
+
get waiterIds(): string[];
|
|
328
|
+
hasBufferedItems(id: string): boolean;
|
|
329
|
+
open(id: string): void;
|
|
330
|
+
isOpen(id: string): boolean;
|
|
331
|
+
push(id: string, item: T): void;
|
|
332
|
+
pull(id: string): Promise<T>;
|
|
198
333
|
close({ id, reason }?: AsyncIdQueueCloseOptions): void;
|
|
199
|
-
assertOpen(id:
|
|
334
|
+
assertOpen(id: string): void;
|
|
200
335
|
}
|
|
201
336
|
|
|
202
|
-
|
|
203
|
-
|
|
337
|
+
/**
|
|
338
|
+
* Converts a `ReadableStream` into an `AsyncIteratorClass`.
|
|
339
|
+
*/
|
|
340
|
+
declare function streamToAsyncIteratorClass<T>(stream: ReadableStream<T>): AsyncIteratorClass<T>;
|
|
341
|
+
/**
|
|
342
|
+
* Converts an `AsyncIterator` into a `ReadableStream`.
|
|
343
|
+
*/
|
|
344
|
+
declare function asyncIteratorToStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
|
|
345
|
+
/**
|
|
346
|
+
* Converts an `AsyncIterator` into a `ReadableStream`, ensuring that
|
|
347
|
+
* all emitted object values are *unproxied* before enqueuing.
|
|
348
|
+
*/
|
|
349
|
+
declare function asyncIteratorToUnproxiedDataStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
|
|
350
|
+
|
|
351
|
+
declare function tryDecodeURIComponent(value: string): string;
|
|
204
352
|
|
|
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 };
|
|
353
|
+
export { AbortError, AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, asyncIteratorWithSpan, clone, compareSequentialIds, defer, fallback, findDeepMatches, get, getConstructor, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, overlayProxy, parseEmptyableJSON, preventNativeAwait, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitInHalf, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };
|
|
354
|
+
export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, AsyncIteratorWithSpanOptions, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, InferAsyncIterableYield, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, OtelConfig, PromiseWithError, Registry, RunWithSpanOptions, Segment, SetOptional, SetSpanErrorOptions, ThrowableError, Value };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Promisable } from 'type-fest';
|
|
2
|
-
export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
|
|
3
|
-
|
|
2
|
+
export { IsEqual, IsNever, JsonValue, PartialDeep, Promisable } from 'type-fest';
|
|
3
|
+
import { Tracer, TraceAPI, ContextAPI, PropagationAPI, SpanOptions, Context, Span, AttributeValue, Exception } from '@opentelemetry/api';
|
|
4
|
+
export { group, guard, mapEntries, mapValues, omit, retry, sleep } from 'radash';
|
|
4
5
|
|
|
5
6
|
type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
|
|
6
7
|
declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>): T;
|
|
@@ -8,6 +9,13 @@ 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>;
|
|
13
21
|
declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
|
|
@@ -20,6 +28,18 @@ type OmitChainMethodDeep<T extends object, K extends keyof any> = {
|
|
|
20
28
|
[P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
|
|
21
29
|
};
|
|
22
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.e77ba7d";
|
|
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
|
+
|
|
23
43
|
interface EventPublisherOptions {
|
|
24
44
|
/**
|
|
25
45
|
* Maximum number of events to buffer for async iterator subscribers.
|
|
@@ -40,7 +60,7 @@ interface EventPublisherSubscribeIteratorOptions extends EventPublisherOptions {
|
|
|
40
60
|
/**
|
|
41
61
|
* Aborts the async iterator. Throws if aborted before or during pulling.
|
|
42
62
|
*/
|
|
43
|
-
signal?: AbortSignal;
|
|
63
|
+
signal?: AbortSignal | undefined;
|
|
44
64
|
}
|
|
45
65
|
declare class EventPublisher<T extends Record<PropertyKey, any>> {
|
|
46
66
|
#private;
|
|
@@ -80,9 +100,17 @@ declare class EventPublisher<T extends Record<PropertyKey, any>> {
|
|
|
80
100
|
}
|
|
81
101
|
|
|
82
102
|
declare class SequentialIdGenerator {
|
|
83
|
-
private
|
|
84
|
-
generate():
|
|
103
|
+
private index;
|
|
104
|
+
generate(): string;
|
|
85
105
|
}
|
|
106
|
+
/**
|
|
107
|
+
* Compares two sequential IDs.
|
|
108
|
+
* Returns:
|
|
109
|
+
* - negative if `a` < `b`
|
|
110
|
+
* - positive if `a` > `b`
|
|
111
|
+
* - 0 if equal
|
|
112
|
+
*/
|
|
113
|
+
declare function compareSequentialIds(a: string, b: string): number;
|
|
86
114
|
|
|
87
115
|
type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
|
|
88
116
|
type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
|
|
@@ -101,6 +129,7 @@ interface Registry {
|
|
|
101
129
|
type ThrowableError = Registry extends {
|
|
102
130
|
throwableError: infer T;
|
|
103
131
|
} ? T : Error;
|
|
132
|
+
type InferAsyncIterableYield<T> = T extends AsyncIterable<infer U> ? U : never;
|
|
104
133
|
|
|
105
134
|
type InterceptableOptions = Record<string, any>;
|
|
106
135
|
type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
|
|
@@ -134,6 +163,72 @@ declare function onFinish<T, TOptions extends {
|
|
|
134
163
|
}, 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
164
|
declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
|
|
136
165
|
|
|
166
|
+
/**
|
|
167
|
+
* Only import types from @opentelemetry/api to avoid runtime dependencies.
|
|
168
|
+
*/
|
|
169
|
+
|
|
170
|
+
interface OtelConfig {
|
|
171
|
+
tracer: Tracer;
|
|
172
|
+
trace: TraceAPI;
|
|
173
|
+
context: ContextAPI;
|
|
174
|
+
propagation: PropagationAPI;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Sets the global OpenTelemetry config.
|
|
178
|
+
* Call this once at app startup. Use `undefined` to disable tracing.
|
|
179
|
+
*/
|
|
180
|
+
declare function setGlobalOtelConfig(config: OtelConfig | undefined): void;
|
|
181
|
+
/**
|
|
182
|
+
* Gets the global OpenTelemetry config.
|
|
183
|
+
* Returns `undefined` if OpenTelemetry is not configured, initialized, or enabled.
|
|
184
|
+
*/
|
|
185
|
+
declare function getGlobalOtelConfig(): OtelConfig | undefined;
|
|
186
|
+
/**
|
|
187
|
+
* Starts a new OpenTelemetry span with the given name and options.
|
|
188
|
+
*
|
|
189
|
+
* @returns The new span, or `undefined` if no tracer is set.
|
|
190
|
+
*/
|
|
191
|
+
declare function startSpan(name: string, options?: SpanOptions, context?: Context): Span | undefined;
|
|
192
|
+
interface SetSpanErrorOptions {
|
|
193
|
+
/**
|
|
194
|
+
* Span error status is not set if error is due to cancellation by the signal.
|
|
195
|
+
*/
|
|
196
|
+
signal?: AbortSignal;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Records and sets the error status on the given span.
|
|
200
|
+
* If the span is `undefined`, it does nothing.
|
|
201
|
+
*/
|
|
202
|
+
declare function setSpanError(span: Span | undefined, error: unknown, options?: SetSpanErrorOptions): void;
|
|
203
|
+
declare function setSpanAttribute(span: Span | undefined, key: string, value: AttributeValue | undefined): void;
|
|
204
|
+
/**
|
|
205
|
+
* Converts an error to an OpenTelemetry Exception.
|
|
206
|
+
*/
|
|
207
|
+
declare function toOtelException(error: unknown): Exclude<Exception, string>;
|
|
208
|
+
/**
|
|
209
|
+
* Converts a value to a string suitable for OpenTelemetry span attributes.
|
|
210
|
+
*/
|
|
211
|
+
declare function toSpanAttributeValue(data: unknown): string;
|
|
212
|
+
interface RunWithSpanOptions extends SpanOptions, SetSpanErrorOptions {
|
|
213
|
+
/**
|
|
214
|
+
* The name of the span to create.
|
|
215
|
+
*/
|
|
216
|
+
name: string;
|
|
217
|
+
/**
|
|
218
|
+
* Context to use for the span.
|
|
219
|
+
*/
|
|
220
|
+
context?: Context;
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Runs a function within the context of a new OpenTelemetry span.
|
|
224
|
+
* The span is ended automatically, and errors are recorded to the span.
|
|
225
|
+
*/
|
|
226
|
+
declare function runWithSpan<T>({ name, context, ...options }: RunWithSpanOptions, fn: (span?: Span) => Promisable<T>): Promise<T>;
|
|
227
|
+
/**
|
|
228
|
+
* Runs a function within the context of an existing OpenTelemetry span.
|
|
229
|
+
*/
|
|
230
|
+
declare function runInSpanContext<T>(span: Span | undefined, fn: () => Promisable<T>): Promise<T>;
|
|
231
|
+
|
|
137
232
|
declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
|
|
138
233
|
interface AsyncIteratorClassNextFn<T, TReturn> {
|
|
139
234
|
(): Promise<IteratorResult<T, TReturn>>;
|
|
@@ -158,15 +253,29 @@ declare class AsyncIteratorClass<T, TReturn = unknown, TNext = unknown> implemen
|
|
|
158
253
|
[Symbol.asyncIterator](): this;
|
|
159
254
|
}
|
|
160
255
|
declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorClass<T, TReturn, TNext>)[];
|
|
256
|
+
interface AsyncIteratorWithSpanOptions extends SetSpanErrorOptions {
|
|
257
|
+
/**
|
|
258
|
+
* The name of the span to create.
|
|
259
|
+
*/
|
|
260
|
+
name: string;
|
|
261
|
+
}
|
|
262
|
+
declare function asyncIteratorWithSpan<T, TReturn, TNext>({ name, ...options }: AsyncIteratorWithSpanOptions, iterator: AsyncIterator<T, TReturn, TNext>): AsyncIteratorClass<T, TReturn, TNext>;
|
|
161
263
|
|
|
162
264
|
declare function parseEmptyableJSON(text: string | null | undefined): unknown;
|
|
163
|
-
declare function stringifyJSON<T>(value: T
|
|
265
|
+
declare function stringifyJSON<T>(value: T | {
|
|
266
|
+
toJSON(): T;
|
|
267
|
+
}): undefined extends T ? undefined | string : string;
|
|
164
268
|
|
|
165
269
|
type Segment = string | number;
|
|
166
270
|
declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
|
|
167
271
|
maps: Segment[][];
|
|
168
272
|
values: unknown[];
|
|
169
273
|
};
|
|
274
|
+
/**
|
|
275
|
+
* Get constructor of the value
|
|
276
|
+
*
|
|
277
|
+
*/
|
|
278
|
+
declare function getConstructor(value: unknown): Function | null | undefined;
|
|
170
279
|
/**
|
|
171
280
|
* Check if the value is an object even it created by `Object.create(null)` or more tricky way.
|
|
172
281
|
*/
|
|
@@ -176,31 +285,70 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
|
|
|
176
285
|
*/
|
|
177
286
|
declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
|
|
178
287
|
declare function clone<T>(value: T): T;
|
|
179
|
-
declare function get(object:
|
|
288
|
+
declare function get(object: unknown, path: readonly PropertyKey[]): unknown;
|
|
180
289
|
declare function isPropertyKey(value: unknown): value is PropertyKey;
|
|
181
290
|
declare const NullProtoObj: ({
|
|
182
291
|
new <T extends Record<PropertyKey, unknown>>(): T;
|
|
183
292
|
});
|
|
184
293
|
|
|
294
|
+
type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
|
|
295
|
+
declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
|
|
296
|
+
/**
|
|
297
|
+
* Returns the value if it is defined, otherwise returns the fallback
|
|
298
|
+
*/
|
|
299
|
+
declare function fallback<T>(value: T | undefined, fallback: T): T;
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Prevents objects from being awaitable by intercepting the `then` method
|
|
303
|
+
* when called by the native await mechanism. This is useful for preventing
|
|
304
|
+
* accidental awaiting of objects that aren't meant to be promises.
|
|
305
|
+
*/
|
|
306
|
+
declare function preventNativeAwait<T extends object>(target: T): T;
|
|
307
|
+
/**
|
|
308
|
+
* Create a proxy that overlays one object (`overlay`) on top of another (`target`).
|
|
309
|
+
*
|
|
310
|
+
* - Properties from `overlay` take precedence.
|
|
311
|
+
* - Properties not in `overlay` fall back to `target`.
|
|
312
|
+
* - Methods from either object are bound to `overlay` so `this` is consistent.
|
|
313
|
+
*
|
|
314
|
+
* Useful when you want to override or extend behavior without fully copying/merging objects.
|
|
315
|
+
*/
|
|
316
|
+
declare function overlayProxy<T extends object, U extends object>(target: Value<T>, partial: U): U & Omit<T, keyof U>;
|
|
317
|
+
|
|
185
318
|
interface AsyncIdQueueCloseOptions {
|
|
186
|
-
id?:
|
|
319
|
+
id?: string;
|
|
187
320
|
reason?: unknown;
|
|
188
321
|
}
|
|
189
322
|
declare class AsyncIdQueue<T> {
|
|
190
323
|
private readonly openIds;
|
|
191
|
-
private readonly
|
|
192
|
-
private readonly
|
|
324
|
+
private readonly queues;
|
|
325
|
+
private readonly waiters;
|
|
193
326
|
get length(): number;
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
327
|
+
get waiterIds(): string[];
|
|
328
|
+
hasBufferedItems(id: string): boolean;
|
|
329
|
+
open(id: string): void;
|
|
330
|
+
isOpen(id: string): boolean;
|
|
331
|
+
push(id: string, item: T): void;
|
|
332
|
+
pull(id: string): Promise<T>;
|
|
198
333
|
close({ id, reason }?: AsyncIdQueueCloseOptions): void;
|
|
199
|
-
assertOpen(id:
|
|
334
|
+
assertOpen(id: string): void;
|
|
200
335
|
}
|
|
201
336
|
|
|
202
|
-
|
|
203
|
-
|
|
337
|
+
/**
|
|
338
|
+
* Converts a `ReadableStream` into an `AsyncIteratorClass`.
|
|
339
|
+
*/
|
|
340
|
+
declare function streamToAsyncIteratorClass<T>(stream: ReadableStream<T>): AsyncIteratorClass<T>;
|
|
341
|
+
/**
|
|
342
|
+
* Converts an `AsyncIterator` into a `ReadableStream`.
|
|
343
|
+
*/
|
|
344
|
+
declare function asyncIteratorToStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
|
|
345
|
+
/**
|
|
346
|
+
* Converts an `AsyncIterator` into a `ReadableStream`, ensuring that
|
|
347
|
+
* all emitted object values are *unproxied* before enqueuing.
|
|
348
|
+
*/
|
|
349
|
+
declare function asyncIteratorToUnproxiedDataStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
|
|
350
|
+
|
|
351
|
+
declare function tryDecodeURIComponent(value: string): string;
|
|
204
352
|
|
|
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 };
|
|
353
|
+
export { AbortError, AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, asyncIteratorWithSpan, clone, compareSequentialIds, defer, fallback, findDeepMatches, get, getConstructor, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, overlayProxy, parseEmptyableJSON, preventNativeAwait, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitInHalf, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };
|
|
354
|
+
export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, AsyncIteratorWithSpanOptions, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, InferAsyncIterableYield, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, OtelConfig, PromiseWithError, Registry, RunWithSpanOptions, Segment, SetOptional, SetSpanErrorOptions, ThrowableError, Value };
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { group, guard, mapEntries, mapValues, omit } from 'radash';
|
|
1
|
+
export { group, guard, mapEntries, mapValues, omit, retry, sleep } from 'radash';
|
|
2
2
|
|
|
3
3
|
function resolveMaybeOptionalOptions(rest) {
|
|
4
4
|
return rest[0] ?? {};
|
|
@@ -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.e77ba7d";
|
|
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 () => {
|
|
@@ -40,13 +58,112 @@ function defer(callback) {
|
|
|
40
58
|
}
|
|
41
59
|
}
|
|
42
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
|
+
|
|
43
154
|
class AsyncIdQueue {
|
|
44
155
|
openIds = /* @__PURE__ */ new Set();
|
|
45
|
-
|
|
46
|
-
|
|
156
|
+
queues = /* @__PURE__ */ new Map();
|
|
157
|
+
waiters = /* @__PURE__ */ new Map();
|
|
47
158
|
get length() {
|
|
48
159
|
return this.openIds.size;
|
|
49
160
|
}
|
|
161
|
+
get waiterIds() {
|
|
162
|
+
return Array.from(this.waiters.keys());
|
|
163
|
+
}
|
|
164
|
+
hasBufferedItems(id) {
|
|
165
|
+
return Boolean(this.queues.get(id)?.length);
|
|
166
|
+
}
|
|
50
167
|
open(id) {
|
|
51
168
|
this.openIds.add(id);
|
|
52
169
|
}
|
|
@@ -55,59 +172,57 @@ class AsyncIdQueue {
|
|
|
55
172
|
}
|
|
56
173
|
push(id, item) {
|
|
57
174
|
this.assertOpen(id);
|
|
58
|
-
const pending = this.
|
|
175
|
+
const pending = this.waiters.get(id);
|
|
59
176
|
if (pending?.length) {
|
|
60
177
|
pending.shift()[0](item);
|
|
61
178
|
if (pending.length === 0) {
|
|
62
|
-
this.
|
|
179
|
+
this.waiters.delete(id);
|
|
63
180
|
}
|
|
64
181
|
} else {
|
|
65
|
-
const items = this.
|
|
182
|
+
const items = this.queues.get(id);
|
|
66
183
|
if (items) {
|
|
67
184
|
items.push(item);
|
|
68
185
|
} else {
|
|
69
|
-
this.
|
|
186
|
+
this.queues.set(id, [item]);
|
|
70
187
|
}
|
|
71
188
|
}
|
|
72
189
|
}
|
|
73
190
|
async pull(id) {
|
|
74
191
|
this.assertOpen(id);
|
|
75
|
-
const items = this.
|
|
192
|
+
const items = this.queues.get(id);
|
|
76
193
|
if (items?.length) {
|
|
77
194
|
const item = items.shift();
|
|
78
195
|
if (items.length === 0) {
|
|
79
|
-
this.
|
|
196
|
+
this.queues.delete(id);
|
|
80
197
|
}
|
|
81
198
|
return item;
|
|
82
199
|
}
|
|
83
200
|
return new Promise((resolve, reject) => {
|
|
84
|
-
const waitingPulls = this.
|
|
201
|
+
const waitingPulls = this.waiters.get(id);
|
|
85
202
|
const pending = [resolve, reject];
|
|
86
203
|
if (waitingPulls) {
|
|
87
204
|
waitingPulls.push(pending);
|
|
88
205
|
} else {
|
|
89
|
-
this.
|
|
206
|
+
this.waiters.set(id, [pending]);
|
|
90
207
|
}
|
|
91
208
|
});
|
|
92
209
|
}
|
|
93
210
|
close({ id, reason } = {}) {
|
|
94
211
|
if (id === void 0) {
|
|
95
|
-
this.
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
});
|
|
212
|
+
this.waiters.forEach((pendingPulls, id2) => {
|
|
213
|
+
const error2 = reason ?? new AbortError(`[AsyncIdQueue] Queue[${id2}] was closed or aborted while waiting for pulling.`);
|
|
214
|
+
pendingPulls.forEach(([, reject]) => reject(error2));
|
|
99
215
|
});
|
|
100
|
-
this.
|
|
216
|
+
this.waiters.clear();
|
|
101
217
|
this.openIds.clear();
|
|
102
|
-
this.
|
|
218
|
+
this.queues.clear();
|
|
103
219
|
return;
|
|
104
220
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
this.pendingPulls.delete(id);
|
|
221
|
+
const error = reason ?? new AbortError(`[AsyncIdQueue] Queue[${id}] was closed or aborted while waiting for pulling.`);
|
|
222
|
+
this.waiters.get(id)?.forEach(([, reject]) => reject(error));
|
|
223
|
+
this.waiters.delete(id);
|
|
109
224
|
this.openIds.delete(id);
|
|
110
|
-
this.
|
|
225
|
+
this.queues.delete(id);
|
|
111
226
|
}
|
|
112
227
|
assertOpen(id) {
|
|
113
228
|
if (!this.isOpen(id)) {
|
|
@@ -120,7 +235,7 @@ function isAsyncIteratorObject(maybe) {
|
|
|
120
235
|
if (!maybe || typeof maybe !== "object") {
|
|
121
236
|
return false;
|
|
122
237
|
}
|
|
123
|
-
return Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
|
|
238
|
+
return "next" in maybe && typeof maybe.next === "function" && Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
|
|
124
239
|
}
|
|
125
240
|
const fallbackAsyncDisposeSymbol = Symbol.for("asyncDispose");
|
|
126
241
|
const asyncDisposeSymbol = Symbol.asyncDispose ?? fallbackAsyncDisposeSymbol;
|
|
@@ -187,51 +302,81 @@ class AsyncIteratorClass {
|
|
|
187
302
|
}
|
|
188
303
|
function replicateAsyncIterator(source, count) {
|
|
189
304
|
const queue = new AsyncIdQueue();
|
|
190
|
-
const
|
|
191
|
-
let
|
|
305
|
+
const ids = Array.from({ length: count }, (_, i) => i.toString());
|
|
306
|
+
let isSourceFinished = false;
|
|
192
307
|
const start = once(async () => {
|
|
193
308
|
try {
|
|
194
309
|
while (true) {
|
|
195
310
|
const item = await source.next();
|
|
196
|
-
|
|
311
|
+
ids.forEach((id) => {
|
|
197
312
|
if (queue.isOpen(id)) {
|
|
198
|
-
queue.push(id, item);
|
|
313
|
+
queue.push(id, { next: item });
|
|
199
314
|
}
|
|
200
|
-
}
|
|
315
|
+
});
|
|
201
316
|
if (item.done) {
|
|
202
317
|
break;
|
|
203
318
|
}
|
|
204
319
|
}
|
|
205
|
-
} catch (
|
|
206
|
-
|
|
320
|
+
} catch (error) {
|
|
321
|
+
ids.forEach((id) => {
|
|
322
|
+
if (queue.isOpen(id)) {
|
|
323
|
+
queue.push(id, { error });
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
} finally {
|
|
327
|
+
isSourceFinished = true;
|
|
207
328
|
}
|
|
208
329
|
});
|
|
209
|
-
|
|
330
|
+
const replicated = ids.map((id) => {
|
|
210
331
|
queue.open(id);
|
|
211
|
-
|
|
212
|
-
() => {
|
|
332
|
+
return new AsyncIteratorClass(
|
|
333
|
+
async () => {
|
|
213
334
|
start();
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
}
|
|
220
|
-
});
|
|
221
|
-
});
|
|
335
|
+
const item = await queue.pull(id);
|
|
336
|
+
if (item.next) {
|
|
337
|
+
return item.next;
|
|
338
|
+
}
|
|
339
|
+
throw item.error;
|
|
222
340
|
},
|
|
223
341
|
async (reason) => {
|
|
224
342
|
queue.close({ id });
|
|
225
|
-
if (reason !== "next") {
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
}
|
|
343
|
+
if (reason !== "next" && !queue.length && !isSourceFinished) {
|
|
344
|
+
isSourceFinished = true;
|
|
345
|
+
await source?.return?.();
|
|
229
346
|
}
|
|
230
347
|
}
|
|
231
|
-
)
|
|
232
|
-
}
|
|
348
|
+
);
|
|
349
|
+
});
|
|
233
350
|
return replicated;
|
|
234
351
|
}
|
|
352
|
+
function asyncIteratorWithSpan({ name, ...options }, iterator) {
|
|
353
|
+
let span;
|
|
354
|
+
return new AsyncIteratorClass(
|
|
355
|
+
async () => {
|
|
356
|
+
span ??= startSpan(name);
|
|
357
|
+
try {
|
|
358
|
+
const result = await runInSpanContext(span, () => iterator.next());
|
|
359
|
+
span?.addEvent(result.done ? "completed" : "yielded");
|
|
360
|
+
return result;
|
|
361
|
+
} catch (err) {
|
|
362
|
+
setSpanError(span, err, options);
|
|
363
|
+
throw err;
|
|
364
|
+
}
|
|
365
|
+
},
|
|
366
|
+
async (reason) => {
|
|
367
|
+
try {
|
|
368
|
+
if (reason !== "next") {
|
|
369
|
+
await runInSpanContext(span, () => iterator.return?.());
|
|
370
|
+
}
|
|
371
|
+
} catch (err) {
|
|
372
|
+
setSpanError(span, err, options);
|
|
373
|
+
throw err;
|
|
374
|
+
} finally {
|
|
375
|
+
span?.end();
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
);
|
|
379
|
+
}
|
|
235
380
|
|
|
236
381
|
class EventPublisher {
|
|
237
382
|
#listenersMap = /* @__PURE__ */ new Map();
|
|
@@ -258,18 +403,19 @@ class EventPublisher {
|
|
|
258
403
|
if (typeof listenerOrOptions === "function") {
|
|
259
404
|
let listeners = this.#listenersMap.get(event);
|
|
260
405
|
if (!listeners) {
|
|
261
|
-
this.#listenersMap.set(event, listeners =
|
|
406
|
+
this.#listenersMap.set(event, listeners = []);
|
|
262
407
|
}
|
|
263
|
-
listeners.
|
|
264
|
-
return () => {
|
|
265
|
-
listeners.
|
|
266
|
-
if (listeners.
|
|
408
|
+
listeners.push(listenerOrOptions);
|
|
409
|
+
return once(() => {
|
|
410
|
+
listeners.splice(listeners.indexOf(listenerOrOptions), 1);
|
|
411
|
+
if (listeners.length === 0) {
|
|
267
412
|
this.#listenersMap.delete(event);
|
|
268
413
|
}
|
|
269
|
-
};
|
|
414
|
+
});
|
|
270
415
|
}
|
|
271
416
|
const signal = listenerOrOptions?.signal;
|
|
272
417
|
const maxBufferedEvents = listenerOrOptions?.maxBufferedEvents ?? this.#maxBufferedEvents;
|
|
418
|
+
signal?.throwIfAborted();
|
|
273
419
|
const bufferedEvents = [];
|
|
274
420
|
const pullResolvers = [];
|
|
275
421
|
const unsubscribe = this.subscribe(event, (payload) => {
|
|
@@ -311,14 +457,18 @@ class EventPublisher {
|
|
|
311
457
|
}
|
|
312
458
|
|
|
313
459
|
class SequentialIdGenerator {
|
|
314
|
-
|
|
460
|
+
index = BigInt(1);
|
|
315
461
|
generate() {
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
462
|
+
const id = this.index.toString(36);
|
|
463
|
+
this.index++;
|
|
464
|
+
return id;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
function compareSequentialIds(a, b) {
|
|
468
|
+
if (a.length !== b.length) {
|
|
469
|
+
return a.length - b.length;
|
|
321
470
|
}
|
|
471
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
322
472
|
}
|
|
323
473
|
|
|
324
474
|
function onStart(callback) {
|
|
@@ -398,6 +548,12 @@ function findDeepMatches(check, payload, segments = [], maps = [], values = [])
|
|
|
398
548
|
}
|
|
399
549
|
return { maps, values };
|
|
400
550
|
}
|
|
551
|
+
function getConstructor(value) {
|
|
552
|
+
if (!isTypescriptObject(value)) {
|
|
553
|
+
return null;
|
|
554
|
+
}
|
|
555
|
+
return Object.getPrototypeOf(value)?.constructor;
|
|
556
|
+
}
|
|
401
557
|
function isObject(value) {
|
|
402
558
|
if (!value || typeof value !== "object") {
|
|
403
559
|
return false;
|
|
@@ -449,5 +605,104 @@ function value(value2, ...args) {
|
|
|
449
605
|
}
|
|
450
606
|
return value2;
|
|
451
607
|
}
|
|
608
|
+
function fallback(value2, fallback2) {
|
|
609
|
+
return value2 === void 0 ? fallback2 : value2;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
function preventNativeAwait(target) {
|
|
613
|
+
return new Proxy(target, {
|
|
614
|
+
get(target2, prop, receiver) {
|
|
615
|
+
const value2 = Reflect.get(target2, prop, receiver);
|
|
616
|
+
if (prop !== "then" || typeof value2 !== "function") {
|
|
617
|
+
return value2;
|
|
618
|
+
}
|
|
619
|
+
return new Proxy(value2, {
|
|
620
|
+
apply(targetFn, thisArg, args) {
|
|
621
|
+
if (args.length !== 2 || args.some((arg) => !isNativeFunction(arg))) {
|
|
622
|
+
return Reflect.apply(targetFn, thisArg, args);
|
|
623
|
+
}
|
|
624
|
+
let shouldOmit = true;
|
|
625
|
+
args[0].call(thisArg, preventNativeAwait(new Proxy(target2, {
|
|
626
|
+
get: (target3, prop2, receiver2) => {
|
|
627
|
+
if (shouldOmit && prop2 === "then") {
|
|
628
|
+
shouldOmit = false;
|
|
629
|
+
return void 0;
|
|
630
|
+
}
|
|
631
|
+
return Reflect.get(target3, prop2, receiver2);
|
|
632
|
+
}
|
|
633
|
+
})));
|
|
634
|
+
}
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
const NATIVE_FUNCTION_REGEX = /^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;
|
|
640
|
+
function isNativeFunction(fn) {
|
|
641
|
+
return typeof fn === "function" && NATIVE_FUNCTION_REGEX.test(fn.toString());
|
|
642
|
+
}
|
|
643
|
+
function overlayProxy(target, partial) {
|
|
644
|
+
const proxy = new Proxy(typeof target === "function" ? partial : target, {
|
|
645
|
+
get(_, prop) {
|
|
646
|
+
const targetValue = prop in partial ? partial : value(target);
|
|
647
|
+
const v = Reflect.get(targetValue, prop);
|
|
648
|
+
return typeof v === "function" ? v.bind(targetValue) : v;
|
|
649
|
+
},
|
|
650
|
+
has(_, prop) {
|
|
651
|
+
return Reflect.has(partial, prop) || Reflect.has(value(target), prop);
|
|
652
|
+
}
|
|
653
|
+
});
|
|
654
|
+
return proxy;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function streamToAsyncIteratorClass(stream) {
|
|
658
|
+
const reader = stream.getReader();
|
|
659
|
+
return new AsyncIteratorClass(
|
|
660
|
+
async () => {
|
|
661
|
+
return reader.read();
|
|
662
|
+
},
|
|
663
|
+
async () => {
|
|
664
|
+
await reader.cancel();
|
|
665
|
+
}
|
|
666
|
+
);
|
|
667
|
+
}
|
|
668
|
+
function asyncIteratorToStream(iterator) {
|
|
669
|
+
return new ReadableStream({
|
|
670
|
+
async pull(controller) {
|
|
671
|
+
const { done, value } = await iterator.next();
|
|
672
|
+
if (done) {
|
|
673
|
+
controller.close();
|
|
674
|
+
} else {
|
|
675
|
+
controller.enqueue(value);
|
|
676
|
+
}
|
|
677
|
+
},
|
|
678
|
+
async cancel() {
|
|
679
|
+
await iterator.return?.();
|
|
680
|
+
}
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
function asyncIteratorToUnproxiedDataStream(iterator) {
|
|
684
|
+
return new ReadableStream({
|
|
685
|
+
async pull(controller) {
|
|
686
|
+
const { done, value } = await iterator.next();
|
|
687
|
+
if (done) {
|
|
688
|
+
controller.close();
|
|
689
|
+
} else {
|
|
690
|
+
const unproxied = isObject(value) ? { ...value } : Array.isArray(value) ? value.map((i) => i) : value;
|
|
691
|
+
controller.enqueue(unproxied);
|
|
692
|
+
}
|
|
693
|
+
},
|
|
694
|
+
async cancel() {
|
|
695
|
+
await iterator.return?.();
|
|
696
|
+
}
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
function tryDecodeURIComponent(value) {
|
|
701
|
+
try {
|
|
702
|
+
return decodeURIComponent(value);
|
|
703
|
+
} catch {
|
|
704
|
+
return value;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
452
707
|
|
|
453
|
-
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 };
|
|
708
|
+
export { AbortError, AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, asyncIteratorWithSpan, clone, compareSequentialIds, defer, fallback, findDeepMatches, get, getConstructor, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, overlayProxy, parseEmptyableJSON, preventNativeAwait, 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.
|
|
4
|
+
"version": "0.0.0-next.e77ba7d",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://orpc.unnoq.com",
|
|
7
7
|
"repository": {
|
|
@@ -23,14 +23,23 @@
|
|
|
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.
|
|
28
|
-
"type-fest": "^
|
|
35
|
+
"radash": "^12.1.1",
|
|
36
|
+
"type-fest": "^5.2.0"
|
|
29
37
|
},
|
|
30
38
|
"devDependencies": {
|
|
31
|
-
"
|
|
39
|
+
"@opentelemetry/api": "^1.9.0",
|
|
40
|
+
"arktype": "2.1.27",
|
|
32
41
|
"valibot": "^1.1.0",
|
|
33
|
-
"zod": "^
|
|
42
|
+
"zod": "^4.1.12"
|
|
34
43
|
},
|
|
35
44
|
"scripts": {
|
|
36
45
|
"build": "unbuild",
|