@orpc/shared 0.0.0-next.fa8d145 → 0.0.0-next.fc1ae52

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/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,17 +9,99 @@ 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>;
22
+ /**
23
+ * Executes the callback function after the current call stack has been cleared.
24
+ */
25
+ declare function defer(callback: () => void): void;
14
26
 
15
27
  type OmitChainMethodDeep<T extends object, K extends keyof any> = {
16
28
  [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
17
29
  };
18
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.fc1ae52";
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 | undefined;
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
+
19
102
  declare class SequentialIdGenerator {
20
- private nextId;
21
- generate(): number;
103
+ private index;
104
+ generate(): string;
22
105
  }
23
106
 
24
107
  type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
@@ -38,12 +121,13 @@ interface Registry {
38
121
  type ThrowableError = Registry extends {
39
122
  throwableError: infer T;
40
123
  } ? T : Error;
124
+ type InferAsyncIterableYield<T> = T extends AsyncIterable<infer U> ? U : never;
41
125
 
42
126
  type InterceptableOptions = Record<string, any>;
43
- type InterceptorOptions<TOptions extends InterceptableOptions, TResult, TError> = Omit<TOptions, 'next'> & {
44
- next(options?: TOptions): PromiseWithError<TResult, TError>;
127
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
128
+ next(options?: TOptions): TResult;
45
129
  };
46
- type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult, TError>) => Promisable<TResult>;
130
+ type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult;
47
131
  /**
48
132
  * Can used for interceptors or middlewares
49
133
  */
@@ -69,22 +153,121 @@ type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess
69
153
  declare function onFinish<T, TOptions extends {
70
154
  next(): any;
71
155
  }, TRest extends any[]>(callback: NoInfer<(state: OnFinishState<Awaited<ReturnType<TOptions['next']>>, ReturnType<TOptions['next']> extends PromiseWithError<any, infer E> ? E : ThrowableError>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
72
- declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
156
+ declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
157
+
158
+ /**
159
+ * Only import types from @opentelemetry/api to avoid runtime dependencies.
160
+ */
161
+
162
+ interface OtelConfig {
163
+ tracer: Tracer;
164
+ trace: TraceAPI;
165
+ context: ContextAPI;
166
+ propagation: PropagationAPI;
167
+ }
168
+ /**
169
+ * Sets the global OpenTelemetry config.
170
+ * Call this once at app startup. Use `undefined` to disable tracing.
171
+ */
172
+ declare function setGlobalOtelConfig(config: OtelConfig | undefined): void;
173
+ /**
174
+ * Gets the global OpenTelemetry config.
175
+ * Returns `undefined` if OpenTelemetry is not configured, initialized, or enabled.
176
+ */
177
+ declare function getGlobalOtelConfig(): OtelConfig | undefined;
178
+ /**
179
+ * Starts a new OpenTelemetry span with the given name and options.
180
+ *
181
+ * @returns The new span, or `undefined` if no tracer is set.
182
+ */
183
+ declare function startSpan(name: string, options?: SpanOptions, context?: Context): Span | undefined;
184
+ interface SetSpanErrorOptions {
185
+ /**
186
+ * Span error status is not set if error is due to cancellation by the signal.
187
+ */
188
+ signal?: AbortSignal;
189
+ }
190
+ /**
191
+ * Records and sets the error status on the given span.
192
+ * If the span is `undefined`, it does nothing.
193
+ */
194
+ declare function setSpanError(span: Span | undefined, error: unknown, options?: SetSpanErrorOptions): void;
195
+ declare function setSpanAttribute(span: Span | undefined, key: string, value: AttributeValue | undefined): void;
196
+ /**
197
+ * Converts an error to an OpenTelemetry Exception.
198
+ */
199
+ declare function toOtelException(error: unknown): Exclude<Exception, string>;
200
+ /**
201
+ * Converts a value to a string suitable for OpenTelemetry span attributes.
202
+ */
203
+ declare function toSpanAttributeValue(data: unknown): string;
204
+ interface RunWithSpanOptions extends SpanOptions, SetSpanErrorOptions {
205
+ /**
206
+ * The name of the span to create.
207
+ */
208
+ name: string;
209
+ /**
210
+ * Context to use for the span.
211
+ */
212
+ context?: Context;
213
+ }
214
+ /**
215
+ * Runs a function within the context of a new OpenTelemetry span.
216
+ * The span is ended automatically, and errors are recorded to the span.
217
+ */
218
+ declare function runWithSpan<T>({ name, context, ...options }: RunWithSpanOptions, fn: (span?: Span) => Promisable<T>): Promise<T>;
219
+ /**
220
+ * Runs a function within the context of an existing OpenTelemetry span.
221
+ */
222
+ declare function runInSpanContext<T>(span: Span | undefined, fn: () => Promisable<T>): Promise<T>;
73
223
 
74
224
  declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
75
- interface CreateAsyncIteratorObjectCleanupFn {
225
+ interface AsyncIteratorClassNextFn<T, TReturn> {
226
+ (): Promise<IteratorResult<T, TReturn>>;
227
+ }
228
+ interface AsyncIteratorClassCleanupFn {
76
229
  (reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
77
230
  }
78
- declare function createAsyncIteratorObject<T, TReturn, TNext>(next: () => Promise<IteratorResult<T, TReturn>>, cleanup: CreateAsyncIteratorObjectCleanupFn): AsyncIteratorObject<T, TReturn, TNext> & AsyncGenerator<T, TReturn, TNext>;
231
+ declare const fallbackAsyncDisposeSymbol: unique symbol;
232
+ declare const asyncDisposeSymbol: typeof Symbol extends {
233
+ asyncDispose: infer T;
234
+ } ? T : typeof fallbackAsyncDisposeSymbol;
235
+ declare class AsyncIteratorClass<T, TReturn = unknown, TNext = unknown> implements AsyncIteratorObject<T, TReturn, TNext>, AsyncGenerator<T, TReturn, TNext> {
236
+ #private;
237
+ constructor(next: AsyncIteratorClassNextFn<T, TReturn>, cleanup: AsyncIteratorClassCleanupFn);
238
+ next(): Promise<IteratorResult<T, TReturn>>;
239
+ return(value?: any): Promise<IteratorResult<T, TReturn>>;
240
+ throw(err: any): Promise<IteratorResult<T, TReturn>>;
241
+ /**
242
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
243
+ */
244
+ [asyncDisposeSymbol](): Promise<void>;
245
+ [Symbol.asyncIterator](): this;
246
+ }
247
+ declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorClass<T, TReturn, TNext>)[];
248
+ interface AsyncIteratorWithSpanOptions extends SetSpanErrorOptions {
249
+ /**
250
+ * The name of the span to create.
251
+ */
252
+ name: string;
253
+ }
254
+ declare function asyncIteratorWithSpan<T, TReturn, TNext>({ name, ...options }: AsyncIteratorWithSpanOptions, iterator: AsyncIterator<T, TReturn, TNext>): AsyncIteratorClass<T, TReturn, TNext>;
79
255
 
80
256
  declare function parseEmptyableJSON(text: string | null | undefined): unknown;
81
- declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
257
+ declare function stringifyJSON<T>(value: T | {
258
+ toJSON(): T;
259
+ }): undefined extends T ? undefined | string : string;
82
260
 
83
261
  type Segment = string | number;
84
262
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
85
263
  maps: Segment[][];
86
264
  values: unknown[];
87
265
  };
266
+ /**
267
+ * Get constructor of the value
268
+ *
269
+ */
270
+ declare function getConstructor(value: unknown): Function | null | undefined;
88
271
  /**
89
272
  * Check if the value is an object even it created by `Object.create(null)` or more tricky way.
90
273
  */
@@ -94,27 +277,45 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
94
277
  */
95
278
  declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
96
279
  declare function clone<T>(value: T): T;
97
- declare function get(object: object, path: readonly string[]): unknown;
280
+ declare function get(object: unknown, path: readonly string[]): unknown;
281
+ declare function isPropertyKey(value: unknown): value is PropertyKey;
282
+ declare const NullProtoObj: ({
283
+ new <T extends Record<PropertyKey, unknown>>(): T;
284
+ });
285
+
286
+ /**
287
+ * Prevents objects from being awaitable by intercepting the `then` method
288
+ * when called by the native await mechanism. This is useful for preventing
289
+ * accidental awaiting of objects that aren't meant to be promises.
290
+ */
291
+ declare function preventNativeAwait<T extends object>(target: T): T;
98
292
 
99
293
  interface AsyncIdQueueCloseOptions {
100
- id?: number;
101
- reason?: Error;
294
+ id?: string;
295
+ reason?: unknown;
102
296
  }
103
297
  declare class AsyncIdQueue<T> {
104
298
  private readonly openIds;
105
- private readonly items;
106
- private readonly pendingPulls;
299
+ private readonly queues;
300
+ private readonly waiters;
107
301
  get length(): number;
108
- open(id: number): void;
109
- isOpen(id: number): boolean;
110
- push(id: number, item: T): void;
111
- pull(id: number): Promise<T>;
302
+ get waiterIds(): string[];
303
+ hasBufferedItems(id: string): boolean;
304
+ open(id: string): void;
305
+ isOpen(id: string): boolean;
306
+ push(id: string, item: T): void;
307
+ pull(id: string): Promise<T>;
112
308
  close({ id, reason }?: AsyncIdQueueCloseOptions): void;
113
- assertOpen(id: number): void;
309
+ assertOpen(id: string): void;
114
310
  }
115
311
 
116
- type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
117
- declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>;
312
+ declare function streamToAsyncIteratorClass<T>(stream: ReadableStream<T>): AsyncIteratorClass<T>;
313
+ declare function asyncIteratorToStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
314
+
315
+ declare function tryDecodeURIComponent(value: string): string;
316
+
317
+ type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
318
+ declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
118
319
 
119
- export { AsyncIdQueue, SequentialIdGenerator, clone, createAsyncIteratorObject, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
120
- export type { AnyFunction, AsyncIdQueueCloseOptions, CreateAsyncIteratorObjectCleanupFn, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
320
+ export { AbortError, AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorWithSpan, clone, defer, findDeepMatches, get, getConstructor, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, preventNativeAwait, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitInHalf, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };
321
+ 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 };