@orpc/shared 2.0.0-beta.47 → 2.0.0-beta.49

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.
Files changed (50) hide show
  1. package/README.md +6 -7
  2. package/dist/args.d.ts +2 -0
  3. package/dist/args.js +3 -0
  4. package/dist/array.d.ts +2 -0
  5. package/dist/array.js +7 -0
  6. package/dist/bigint.d.ts +9 -0
  7. package/dist/bigint.js +19 -0
  8. package/dist/buffer.d.ts +18 -0
  9. package/dist/buffer.js +77 -0
  10. package/dist/compare.d.ts +1 -0
  11. package/dist/compare.js +45 -0
  12. package/dist/consts.d.ts +1 -0
  13. package/dist/consts.js +1 -0
  14. package/dist/error.d.ts +1 -0
  15. package/dist/error.js +3 -0
  16. package/dist/function.d.ts +12 -0
  17. package/dist/function.js +38 -0
  18. package/dist/http.d.ts +29 -0
  19. package/dist/http.js +113 -0
  20. package/dist/id.d.ts +8 -0
  21. package/dist/id.js +13 -0
  22. package/dist/index.d.ts +34 -492
  23. package/dist/index.js +32 -0
  24. package/dist/interceptor.d.ts +60 -0
  25. package/dist/interceptor.js +139 -0
  26. package/dist/iterator.d.ts +56 -0
  27. package/dist/iterator.js +157 -0
  28. package/dist/object.d.ts +60 -0
  29. package/dist/object.js +245 -0
  30. package/dist/plugin.d.ts +12 -0
  31. package/dist/plugin.js +61 -0
  32. package/dist/promise.d.ts +17 -0
  33. package/dist/promise.js +32 -0
  34. package/dist/proxy.d.ts +12 -0
  35. package/dist/proxy.js +24 -0
  36. package/dist/queue.d.ts +16 -0
  37. package/dist/queue.js +79 -0
  38. package/dist/signal.d.ts +18 -0
  39. package/dist/signal.js +85 -0
  40. package/dist/stream.d.ts +48 -0
  41. package/dist/stream.js +155 -0
  42. package/dist/tracing.d.ts +73 -0
  43. package/dist/tracing.js +94 -0
  44. package/dist/types.d.ts +26 -0
  45. package/dist/types.js +1 -0
  46. package/dist/value.d.ts +2 -0
  47. package/dist/value.js +6 -0
  48. package/package.json +17 -20
  49. package/dist/index.d.mts +0 -492
  50. package/dist/index.mjs +0 -1117
package/dist/plugin.js ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Sorts plugins based on their `before` and `after` dependencies.
3
+ */
4
+ export function sortPlugins(plugins) {
5
+ const pluginCount = plugins.length;
6
+ const pluginIdToIndices = new Map();
7
+ for (let i = 0; i < pluginCount; i++) {
8
+ const plugin = plugins[i];
9
+ const indices = pluginIdToIndices.get(plugin.name);
10
+ if (indices === undefined) {
11
+ pluginIdToIndices.set(plugin.name, [i]);
12
+ }
13
+ else {
14
+ indices.push(i);
15
+ }
16
+ }
17
+ const dependencies = Array.from({ length: pluginCount }, () => []);
18
+ for (let i = 0; i < pluginCount; i++) {
19
+ const plugin = plugins[i];
20
+ if (plugin.before !== undefined) {
21
+ for (const beforeId of plugin.before) {
22
+ const beforeIndices = pluginIdToIndices.get(beforeId);
23
+ if (beforeIndices !== undefined) {
24
+ for (const beforeIndex of beforeIndices) {
25
+ dependencies[beforeIndex].push(i);
26
+ }
27
+ }
28
+ }
29
+ }
30
+ if (plugin.after !== undefined) {
31
+ for (const afterId of plugin.after) {
32
+ const afterIndices = pluginIdToIndices.get(afterId);
33
+ if (afterIndices !== undefined) {
34
+ for (const afterIndex of afterIndices) {
35
+ dependencies[i].push(afterIndex);
36
+ }
37
+ }
38
+ }
39
+ }
40
+ }
41
+ const sorted = [];
42
+ const placed = new Set();
43
+ while (sorted.length < pluginCount) {
44
+ const next = plugins.findIndex((_, i) => !placed.has(i) && dependencies[i].every((dependency) => placed.has(dependency)));
45
+ if (next === -1) {
46
+ throw new Error(`Circular dependency detected involving plugin "${findCyclicPlugin(plugins, dependencies, placed).name}"`);
47
+ }
48
+ placed.add(next);
49
+ sorted.push(plugins[next]);
50
+ }
51
+ return sorted;
52
+ }
53
+ function findCyclicPlugin(plugins, dependencies, placed) {
54
+ const seen = new Set();
55
+ let current = plugins.findIndex((_, i) => !placed.has(i));
56
+ while (!seen.has(current)) {
57
+ seen.add(current);
58
+ current = dependencies[current].find((dependency) => !placed.has(dependency));
59
+ }
60
+ return plugins[current];
61
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Creates a promise together with its associated `resolve` and `reject`
3
+ * functions.
4
+ *
5
+ * Equivalent to `Promise.withResolvers()`, but works in environments
6
+ * where that API is not yet available.
7
+ */
8
+ export declare function promiseWithResolvers<T>(): {
9
+ promise: Promise<T>;
10
+ resolve: (v: T) => void;
11
+ reject: (reason: unknown) => void;
12
+ };
13
+ /**
14
+ * Captures the current async context (such as AsyncLocalStorage) through a promise reaction, so no runtime API is needed.
15
+ * The returned function runs a callback inside it once; later calls reject.
16
+ */
17
+ export declare function captureAsyncContext(): <T>(callback: () => Promise<T>) => Promise<T>;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Creates a promise together with its associated `resolve` and `reject`
3
+ * functions.
4
+ *
5
+ * Equivalent to `Promise.withResolvers()`, but works in environments
6
+ * where that API is not yet available.
7
+ */
8
+ export function promiseWithResolvers() {
9
+ const result = {};
10
+ result.promise = new Promise((resolve, reject) => {
11
+ result.resolve = resolve;
12
+ result.reject = reject;
13
+ });
14
+ return result;
15
+ }
16
+ /**
17
+ * Captures the current async context (such as AsyncLocalStorage) through a promise reaction, so no runtime API is needed.
18
+ * The returned function runs a callback inside it once; later calls reject.
19
+ */
20
+ export function captureAsyncContext() {
21
+ const { promise, resolve } = promiseWithResolvers();
22
+ const result = promise.then((callback) => callback());
23
+ let called = false;
24
+ return (callback) => {
25
+ if (called) {
26
+ return Promise.reject(new Error('A captured async context can be run only once.'));
27
+ }
28
+ called = true;
29
+ resolve(callback);
30
+ return result;
31
+ };
32
+ }
@@ -0,0 +1,12 @@
1
+ import type { Value } from './value.ts';
2
+ /**
3
+ * Creates a proxy that overlays a `partial` object on top of a `target`.
4
+ *
5
+ * - Properties from `partial` take precedence.
6
+ * - Properties not present in `partial` fall back to the resolved `target`.
7
+ * - Methods are bound to the proxy to ensure a consistent `this` context.
8
+ *
9
+ * Useful for overriding specific properties of an object while delegating
10
+ * all other access to the original target without needing to know its full structure.
11
+ */
12
+ export declare function override<T extends object, U extends object>(target: Value<T>, partial: U): U & Omit<T, keyof U>;
package/dist/proxy.js ADDED
@@ -0,0 +1,24 @@
1
+ import { getOrBind } from '@standard-server/shared';
2
+ import { value } from './value.js';
3
+ /**
4
+ * Creates a proxy that overlays a `partial` object on top of a `target`.
5
+ *
6
+ * - Properties from `partial` take precedence.
7
+ * - Properties not present in `partial` fall back to the resolved `target`.
8
+ * - Methods are bound to the proxy to ensure a consistent `this` context.
9
+ *
10
+ * Useful for overriding specific properties of an object while delegating
11
+ * all other access to the original target without needing to know its full structure.
12
+ */
13
+ export function override(target, partial) {
14
+ const proxy = new Proxy(typeof target === 'function' ? partial : target, {
15
+ get(_, prop) {
16
+ const targetValue = prop in partial ? partial : value(target);
17
+ return getOrBind(targetValue, prop);
18
+ },
19
+ has(_, prop) {
20
+ return Reflect.has(partial, prop) || Reflect.has(value(target), prop);
21
+ },
22
+ });
23
+ return proxy;
24
+ }
@@ -0,0 +1,16 @@
1
+ export interface AsyncIdQueueCloseOptions {
2
+ id?: string | undefined;
3
+ reason?: unknown;
4
+ }
5
+ export declare class AsyncIdQueue<T> {
6
+ private readonly openIds;
7
+ private readonly queues;
8
+ private readonly waiters;
9
+ get size(): number;
10
+ open(id: string): void;
11
+ isOpen(id: string): boolean;
12
+ push(id: string, item: T): void;
13
+ pull(id: string): Promise<T>;
14
+ close({ id, reason }?: AsyncIdQueueCloseOptions): void;
15
+ private assertOpen;
16
+ }
package/dist/queue.js ADDED
@@ -0,0 +1,79 @@
1
+ import { AbortError } from '@standard-server/shared';
2
+ export class AsyncIdQueue {
3
+ openIds = new Set();
4
+ queues = new Map();
5
+ waiters = new Map();
6
+ get size() {
7
+ return this.openIds.size;
8
+ }
9
+ open(id) {
10
+ this.openIds.add(id);
11
+ }
12
+ isOpen(id) {
13
+ return this.openIds.has(id);
14
+ }
15
+ push(id, item) {
16
+ this.assertOpen(id);
17
+ const pending = this.waiters.get(id);
18
+ if (pending?.length) {
19
+ pending.shift()[0](item);
20
+ if (pending.length === 0) {
21
+ this.waiters.delete(id);
22
+ }
23
+ }
24
+ else {
25
+ const items = this.queues.get(id);
26
+ if (items) {
27
+ items.push(item);
28
+ }
29
+ else {
30
+ this.queues.set(id, [item]);
31
+ }
32
+ }
33
+ }
34
+ async pull(id) {
35
+ this.assertOpen(id);
36
+ const items = this.queues.get(id);
37
+ if (items?.length) {
38
+ const item = items.shift();
39
+ if (items.length === 0) {
40
+ this.queues.delete(id);
41
+ }
42
+ return item;
43
+ }
44
+ return new Promise((resolve, reject) => {
45
+ const waitingPulls = this.waiters.get(id);
46
+ const pending = [resolve, reject];
47
+ if (waitingPulls) {
48
+ waitingPulls.push(pending);
49
+ }
50
+ else {
51
+ this.waiters.set(id, [pending]);
52
+ }
53
+ });
54
+ }
55
+ close({ id, reason } = {}) {
56
+ if (id === undefined) {
57
+ this.waiters.forEach((pendingPulls, id) => {
58
+ const error = reason ??
59
+ new AbortError(`[AsyncIdQueue] Queue[${id}] was closed or aborted while waiting for pulling.`);
60
+ pendingPulls.forEach(([, reject]) => reject(error));
61
+ });
62
+ this.waiters.clear();
63
+ this.openIds.clear();
64
+ this.queues.clear();
65
+ return;
66
+ }
67
+ const error = reason ??
68
+ new AbortError(`[AsyncIdQueue] Queue[${id}] was closed or aborted while waiting for pulling.`);
69
+ this.waiters.get(id)?.forEach(([, reject]) => reject(error));
70
+ this.waiters.delete(id);
71
+ this.openIds.delete(id);
72
+ this.queues.delete(id);
73
+ }
74
+ assertOpen(id) {
75
+ if (!this.isOpen(id)) {
76
+ throw new Error(`[AsyncIdQueue] Cannot access queue[${id}] because it is not open or aborted.`);
77
+ }
78
+ }
79
+ }
@@ -0,0 +1,18 @@
1
+ export interface DisposableAllAbortSignal {
2
+ signal: AbortSignal | undefined;
3
+ dispose: () => void;
4
+ }
5
+ /**
6
+ * Returns a signal that aborts only after all provided signals are aborted,
7
+ * and a `dispose` function that removes the listeners added to the input signals.
8
+ */
9
+ export declare function disposableAllAbortSignal(signals: readonly (AbortSignal | undefined)[]): DisposableAllAbortSignal;
10
+ /**
11
+ * Returns a signal that aborts as soon as any of the provided signals aborts,
12
+ * with the same abort reason.
13
+ *
14
+ * Prefers the native `AbortSignal.any` when available, and falls back to a manual
15
+ * implementation otherwise, including in runtimes without the `AbortSignal` global.
16
+ */
17
+ export declare function anyAbortSignal(signals: readonly (AbortSignal | undefined)[]): AbortSignal | undefined;
18
+ export declare function runWithSignal<T>(signal: AbortSignal | undefined, fn: () => Promise<T>): Promise<T>;
package/dist/signal.js ADDED
@@ -0,0 +1,85 @@
1
+ import { throwIfAborted } from '@standard-server/shared';
2
+ import { promiseWithResolvers } from './promise.js';
3
+ /**
4
+ * Returns a signal that aborts only after all provided signals are aborted,
5
+ * and a `dispose` function that removes the listeners added to the input signals.
6
+ */
7
+ export function disposableAllAbortSignal(signals) {
8
+ const realSignals = signals.filter((signal) => signal !== undefined);
9
+ if (realSignals.length === 0 || realSignals.length !== signals.length) {
10
+ return { signal: undefined, dispose: () => { } };
11
+ }
12
+ const controller = new AbortController();
13
+ const listenersController = new AbortController();
14
+ const dispose = () => listenersController.abort();
15
+ const abortIfAllAborted = () => {
16
+ if (realSignals.every((signal) => signal.aborted)) {
17
+ controller.abort();
18
+ dispose();
19
+ }
20
+ };
21
+ abortIfAllAborted();
22
+ for (const signal of realSignals) {
23
+ signal.addEventListener('abort', abortIfAllAborted, {
24
+ once: true,
25
+ signal: listenersController.signal,
26
+ });
27
+ }
28
+ return { signal: controller.signal, dispose };
29
+ }
30
+ /**
31
+ * Returns a signal that aborts as soon as any of the provided signals aborts,
32
+ * with the same abort reason.
33
+ *
34
+ * Prefers the native `AbortSignal.any` when available, and falls back to a manual
35
+ * implementation otherwise, including in runtimes without the `AbortSignal` global.
36
+ */
37
+ export function anyAbortSignal(signals) {
38
+ const realSignals = signals.filter((signal) => signal !== undefined);
39
+ if (realSignals.length === 0) {
40
+ return undefined;
41
+ }
42
+ if (realSignals.length === 1) {
43
+ return realSignals[0];
44
+ }
45
+ // oxlint-disable-next-line no-restricted-globals, no-restricted-properties
46
+ if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.any === 'function') {
47
+ // oxlint-disable-next-line no-restricted-properties, no-restricted-globals
48
+ return AbortSignal.any(realSignals);
49
+ }
50
+ const controller = new AbortController();
51
+ for (const signal of realSignals) {
52
+ if (signal.aborted) {
53
+ controller.abort(signal.reason);
54
+ break;
55
+ }
56
+ signal.addEventListener('abort', () => {
57
+ controller.abort(signal.reason);
58
+ }, {
59
+ once: true,
60
+ signal: controller.signal,
61
+ });
62
+ }
63
+ return controller.signal;
64
+ }
65
+ export async function runWithSignal(signal, fn) {
66
+ if (!signal) {
67
+ return fn();
68
+ }
69
+ throwIfAborted(signal);
70
+ const { promise, reject, resolve } = promiseWithResolvers();
71
+ let abortListener;
72
+ signal.addEventListener('abort', (abortListener = () => {
73
+ reject(signal.reason);
74
+ abortListener = undefined;
75
+ }));
76
+ try {
77
+ fn().then(resolve, reject);
78
+ return await promise;
79
+ }
80
+ finally {
81
+ if (abortListener) {
82
+ signal.removeEventListener('abort', abortListener);
83
+ }
84
+ }
85
+ }
@@ -0,0 +1,48 @@
1
+ import { AsyncIteratorClass } from '@standard-server/shared';
2
+ import type { Promisable } from 'type-fest';
3
+ import type { StartSpanOptions } from './tracing.ts';
4
+ import type { ThrowableError } from './types.ts';
5
+ export declare function replicateReadableStream<T>(stream: ReadableStream<T>, count: number): ReadableStream<T>[];
6
+ export type ReadableStreamReadResult<T> = {
7
+ done: false;
8
+ value: T;
9
+ } | {
10
+ done: true;
11
+ value?: T | undefined;
12
+ };
13
+ export interface WrapReadableStreamOptions<T, TMapped> {
14
+ /**
15
+ * Any call to the original stream reader will be executed inside this function.
16
+ * Useful when you want execution to happen within a specific context,
17
+ * such as AsyncLocalStorage.
18
+ */
19
+ runWith?: (<T>(run: () => Promise<T>) => Promisable<T>) | undefined;
20
+ mapResult?: ((result: ReadableStreamReadResult<T>) => Promisable<ReadableStreamReadResult<TMapped>>) | undefined;
21
+ mapError?: ((error: ThrowableError) => Promisable<ThrowableError>) | undefined;
22
+ onError?: ((error: ThrowableError) => Promisable<void>) | undefined;
23
+ /**
24
+ * Guaranteed to execute exactly once after the stream finishes or is cancelled.
25
+ */
26
+ onFinish?: (() => Promisable<void>) | undefined;
27
+ }
28
+ export declare function wrapReadableStream<T, TMapped = T>(stream: ReadableStream<T>, { runWith, mapResult, mapError, onError, onFinish }: WrapReadableStreamOptions<T, TMapped>): NoInfer<ReadableStream<TMapped>>;
29
+ export declare function traceReadableStream<T>(options: StartSpanOptions | string, stream: ReadableStream<T>): ReadableStream<T>;
30
+ /**
31
+ * Converts a {@link ReadableStream} into an {@link AsyncIteratorClass}.
32
+ *
33
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk | AI SDK Integration}
34
+ */
35
+ export declare function streamToAsyncIteratorObject<T>(stream: ReadableStream<T>, { signal }?: {
36
+ signal?: AbortSignal | undefined;
37
+ }): AsyncIteratorClass<T>;
38
+ /**
39
+ * Converts an `AsyncIterator` into a `ReadableStream`.
40
+ */
41
+ export declare function asyncIteratorToStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
42
+ /**
43
+ * Converts an `AsyncIterator` into a `ReadableStream`, ensuring that
44
+ * all emitted object values are *unproxied* before enqueuing.
45
+ *
46
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk | AI SDK Integration}
47
+ */
48
+ export declare function asyncIteratorToUnproxiedDataStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
package/dist/stream.js ADDED
@@ -0,0 +1,155 @@
1
+ import { AsyncIteratorClass } from '@standard-server/shared';
2
+ import { once } from './function.js';
3
+ import { isPlainObject } from './object.js';
4
+ import { promiseWithResolvers } from './promise.js';
5
+ import { recordSpanError, runInSpanContext, startSpan } from './tracing.js';
6
+ export function replicateReadableStream(stream, count) {
7
+ if (count <= 0) {
8
+ return [];
9
+ }
10
+ const replicated = [];
11
+ let pending = stream;
12
+ for (let index = 0; index < count - 1; index++) {
13
+ const [replica, remainder] = pending.tee();
14
+ replicated.push(replica);
15
+ pending = remainder;
16
+ }
17
+ replicated.push(pending);
18
+ return replicated;
19
+ }
20
+ export function wrapReadableStream(stream, { runWith, mapResult, mapError, onError, onFinish }) {
21
+ runWith ??= (run) => run();
22
+ const reader = once(() => stream.getReader());
23
+ const finish = once(async () => onFinish?.());
24
+ // TODO:
25
+ return new ReadableStream({
26
+ async pull(controller) {
27
+ let result;
28
+ try {
29
+ const readResult = await runWith(() => reader().read());
30
+ result = mapResult
31
+ ? await mapResult(readResult)
32
+ : readResult;
33
+ }
34
+ catch (error) {
35
+ try {
36
+ await onError?.(error);
37
+ controller.error(mapError ? await mapError(error) : error);
38
+ }
39
+ finally {
40
+ await finish();
41
+ }
42
+ return;
43
+ }
44
+ if (result.done) {
45
+ controller.close();
46
+ await finish();
47
+ }
48
+ else {
49
+ controller.enqueue(result.value);
50
+ }
51
+ },
52
+ async cancel(reason) {
53
+ try {
54
+ try {
55
+ await runWith(() => reader().cancel(reason));
56
+ }
57
+ catch (error) {
58
+ await onError?.(error);
59
+ throw error;
60
+ }
61
+ }
62
+ finally {
63
+ await finish();
64
+ }
65
+ },
66
+ }, { highWaterMark: 0 });
67
+ }
68
+ export function traceReadableStream(options, stream) {
69
+ const getSpan = once(() => startSpan(options));
70
+ return wrapReadableStream(stream, {
71
+ runWith: (run) => runInSpanContext(getSpan(), run),
72
+ mapResult(result) {
73
+ getSpan()?.addEvent(result.done ? 'closed' : 'enqueued');
74
+ return result;
75
+ },
76
+ onError(error) {
77
+ recordSpanError(getSpan(), error);
78
+ },
79
+ onFinish() {
80
+ getSpan()?.end();
81
+ },
82
+ });
83
+ }
84
+ /**
85
+ * Converts a {@link ReadableStream} into an {@link AsyncIteratorClass}.
86
+ *
87
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk | AI SDK Integration}
88
+ */
89
+ export function streamToAsyncIteratorObject(stream, { signal } = {}) {
90
+ const reader = stream.getReader();
91
+ let cancelledBySignal = false;
92
+ return new AsyncIteratorClass(async () => {
93
+ if (signal?.aborted) {
94
+ cancelledBySignal = true;
95
+ throw signal.reason;
96
+ }
97
+ if (!signal) {
98
+ return reader.read();
99
+ }
100
+ const { promise, reject } = promiseWithResolvers();
101
+ const onAbort = () => reject(signal.reason);
102
+ signal.addEventListener('abort', onAbort, { once: true });
103
+ try {
104
+ return await Promise.race([
105
+ reader.read(),
106
+ promise.catch(async (reason) => {
107
+ cancelledBySignal = true;
108
+ throw reason;
109
+ }),
110
+ ]);
111
+ }
112
+ finally {
113
+ signal.removeEventListener('abort', onAbort);
114
+ }
115
+ }, async ({ kind, error }) => {
116
+ if (kind === 'cancelled' || (kind === 'error' && cancelledBySignal)) {
117
+ await reader.cancel(error);
118
+ }
119
+ });
120
+ }
121
+ /**
122
+ * Converts an `AsyncIterator` into a `ReadableStream`.
123
+ */
124
+ export function asyncIteratorToStream(iterator) {
125
+ return createIteratorStream(iterator, (value) => value);
126
+ }
127
+ /**
128
+ * Converts an `AsyncIterator` into a `ReadableStream`, ensuring that
129
+ * all emitted object values are *unproxied* before enqueuing.
130
+ *
131
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk | AI SDK Integration}
132
+ */
133
+ export function asyncIteratorToUnproxiedDataStream(iterator) {
134
+ return createIteratorStream(iterator, (value) => isPlainObject(value)
135
+ ? { ...value }
136
+ : Array.isArray(value)
137
+ ? value.map((i) => i) // use .map instead of ... to deal with sparse arrays
138
+ : value);
139
+ }
140
+ function createIteratorStream(iterator, map) {
141
+ return new ReadableStream({
142
+ async pull(controller) {
143
+ const { done, value } = await iterator.next();
144
+ if (done) {
145
+ controller.close();
146
+ }
147
+ else {
148
+ controller.enqueue(map(value));
149
+ }
150
+ },
151
+ async cancel() {
152
+ await iterator.return?.();
153
+ },
154
+ }, { highWaterMark: 0 });
155
+ }
@@ -0,0 +1,73 @@
1
+ import type { Promisable } from 'type-fest';
2
+ export type TracingAttributeValue = string | number | boolean | string[] | number[] | boolean[];
3
+ export interface TracingException {
4
+ name?: string;
5
+ message: string;
6
+ stack?: string;
7
+ code?: string | number;
8
+ }
9
+ export type TracingHeaders = Record<string, string | string[] | undefined>;
10
+ export type TracingExceptionLevel = 'error' | 'info';
11
+ export interface TracingSpan {
12
+ setAttribute(key: string, value: TracingAttributeValue): void;
13
+ /**
14
+ * Renames the span. Backends that cannot rename spans ignore it.
15
+ */
16
+ updateName(name: string): void;
17
+ /**
18
+ * Adds an event to the span. Backends without span events ignore it.
19
+ */
20
+ addEvent(name: string): void;
21
+ /**
22
+ * Records an exception on the span. The `error` level also marks the span as failed.
23
+ */
24
+ recordException(level: TracingExceptionLevel, exception: TracingException): void;
25
+ end(): void;
26
+ }
27
+ /**
28
+ * The tracing backend oRPC records spans with, see `@orpc/opentelemetry` and `@orpc/cloudflare`.
29
+ *
30
+ * A `parent` defaults to the active span of the backend when omitted.
31
+ */
32
+ export interface Tracer {
33
+ /**
34
+ * Starts a span without making it active. The caller must end it.
35
+ */
36
+ startSpan(name: string, parent?: TracingSpan): TracingSpan;
37
+ /**
38
+ * Starts a span, makes it active while `fn` runs, and passes it to `fn`. The caller must end it.
39
+ */
40
+ startActiveSpan<T>(name: string, parent: TracingSpan | undefined, fn: (span: TracingSpan) => Promise<T>): Promise<T>;
41
+ getActiveSpan(): TracingSpan | undefined;
42
+ /**
43
+ * Runs `fn` with `span` as the active span. Backends that cannot activate a span run `fn` directly.
44
+ */
45
+ withActiveSpan<T>(span: TracingSpan, fn: () => Promisable<T>): Promisable<T>;
46
+ /**
47
+ * Writes the trace context of `span` into `headers`. Absent when the backend does not propagate context.
48
+ */
49
+ inject?(span: TracingSpan, headers: TracingHeaders): void;
50
+ /**
51
+ * Reads the remote parent from `headers`. Absent when the backend does not propagate context.
52
+ */
53
+ extract?(headers: TracingHeaders): TracingSpan | undefined;
54
+ }
55
+ export declare function setTracer(tracer: Tracer | undefined): void;
56
+ export declare function getTracer(): Tracer | undefined;
57
+ export interface StartSpanOptions {
58
+ /**
59
+ * The name of the span to create.
60
+ */
61
+ name: string;
62
+ /**
63
+ * The span to use as parent. Defaults to the active span of the backend.
64
+ */
65
+ parent?: TracingSpan | undefined;
66
+ }
67
+ export declare function startSpan(options: StartSpanOptions | string): TracingSpan | undefined;
68
+ export declare function recordSpanError(span: TracingSpan | undefined, error: unknown): void;
69
+ export declare function setSpanAttributeIfDefined(span: TracingSpan | undefined, key: string, value: TracingAttributeValue | undefined): void;
70
+ export declare function toTracingException(error: unknown): TracingException;
71
+ export declare function toSpanAttributeValue(data: unknown): string;
72
+ export declare function runWithSpan<T>(options: string | StartSpanOptions, fn: (span?: TracingSpan) => Promisable<T>): Promise<T>;
73
+ export declare function runInSpanContext<T>(span: TracingSpan | undefined, fn: () => Promisable<T>): Promisable<T>;