@orpc/shared 2.0.0-beta.5 → 2.0.0-beta.51

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 (51) hide show
  1. package/README.md +139 -102
  2. package/dist/args.d.ts +2 -0
  3. package/dist/args.js +5 -0
  4. package/dist/array.d.ts +5 -0
  5. package/dist/array.js +13 -0
  6. package/dist/bigint.d.ts +9 -0
  7. package/dist/bigint.js +15 -0
  8. package/dist/buffer.d.ts +18 -0
  9. package/dist/buffer.js +54 -0
  10. package/dist/compare.d.ts +1 -0
  11. package/dist/compare.js +26 -0
  12. package/dist/consts.d.ts +1 -0
  13. package/dist/consts.js +3 -0
  14. package/dist/error.d.ts +1 -0
  15. package/dist/error.js +5 -0
  16. package/dist/function.d.ts +12 -0
  17. package/dist/function.js +33 -0
  18. package/dist/http.d.ts +58 -0
  19. package/dist/http.js +147 -0
  20. package/dist/id.d.ts +8 -0
  21. package/dist/id.js +13 -0
  22. package/dist/index.d.ts +26 -306
  23. package/dist/index.js +23 -0
  24. package/dist/interceptor.d.ts +66 -0
  25. package/dist/interceptor.js +119 -0
  26. package/dist/iterator.d.ts +55 -0
  27. package/dist/iterator.js +141 -0
  28. package/dist/object.d.ts +62 -0
  29. package/dist/object.js +194 -0
  30. package/dist/plugin.d.ts +12 -0
  31. package/dist/plugin.js +45 -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 +25 -0
  36. package/dist/queue.d.ts +16 -0
  37. package/dist/queue.js +64 -0
  38. package/dist/regex.d.ts +9 -0
  39. package/dist/regex.js +11 -0
  40. package/dist/signal.d.ts +23 -0
  41. package/dist/signal.js +88 -0
  42. package/dist/stream.d.ts +47 -0
  43. package/dist/stream.js +129 -0
  44. package/dist/tracing.d.ts +73 -0
  45. package/dist/tracing.js +76 -0
  46. package/dist/types.d.ts +27 -0
  47. package/dist/value.d.ts +2 -0
  48. package/dist/value.js +6 -0
  49. package/package.json +22 -30
  50. package/dist/index.d.mts +0 -306
  51. package/dist/index.mjs +0 -892
package/dist/consts.js ADDED
@@ -0,0 +1,3 @@
1
+ // src/consts.ts
2
+ const ORPC_NAME = "orpc";
3
+ export { ORPC_NAME };
@@ -0,0 +1 @@
1
+ export declare function isAbortError(error: unknown): error is Error;
package/dist/error.js ADDED
@@ -0,0 +1,5 @@
1
+ // src/error.ts
2
+ function isAbortError(error) {
3
+ return error instanceof Error && error.name.includes("Abort");
4
+ }
5
+ export { isAbortError };
@@ -0,0 +1,12 @@
1
+ export type AnyFunction = (...args: any[]) => any;
2
+ /**
3
+ * Checks whether a value is an async generator function (`async function*`).
4
+ */
5
+ export declare function isAsyncGeneratorFunction(value: unknown): value is (...args: any[]) => AsyncGenerator;
6
+ export declare function once<T>(fn: () => T): () => T;
7
+ /**
8
+ * Executes the callback function after the current call stack has been cleared,
9
+ * waiting at least `delay` ms when `setTimeout` is available.
10
+ */
11
+ export declare function defer(callback: () => void, delay?: number): void;
12
+ export declare function tryOrUndefined<T>(fn: () => T): undefined | T;
@@ -0,0 +1,33 @@
1
+ // src/function.ts
2
+ const AsyncGeneratorFunction = /* @__PURE__ */ (() => Object.getPrototypeOf(async function* () {}).constructor)();
3
+ /**
4
+ * Checks whether a value is an async generator function (`async function*`).
5
+ */
6
+ function isAsyncGeneratorFunction(value) {
7
+ return value instanceof AsyncGeneratorFunction;
8
+ }
9
+ function once(fn) {
10
+ let cached;
11
+ return () => {
12
+ if (cached) return cached.result;
13
+ const result = fn();
14
+ cached = { result };
15
+ return result;
16
+ };
17
+ }
18
+ /**
19
+ * Executes the callback function after the current call stack has been cleared,
20
+ * waiting at least `delay` ms when `setTimeout` is available.
21
+ */
22
+ function defer(callback, delay = 0) {
23
+ if (typeof setTimeout === "function") setTimeout(callback, delay);
24
+ else Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(callback)));
25
+ }
26
+ function tryOrUndefined(fn) {
27
+ try {
28
+ return fn();
29
+ } catch {
30
+ return;
31
+ }
32
+ }
33
+ export { defer, isAsyncGeneratorFunction, once, tryOrUndefined };
package/dist/http.d.ts ADDED
@@ -0,0 +1,58 @@
1
+ export declare function pathToHttpPath(path: readonly string[]): `/${string}`;
2
+ export declare function normalizeHttpPath(path: string): `/${string}`;
3
+ export declare function mergeHttpPath(a: `/${string}`, b: `/${string}`): `/${string}`;
4
+ export declare function matchesHttpPathPrefix(url: `/${string}`, prefix: `/${string}`): boolean;
5
+ /**
6
+ * Removes `prefix` from `pathname`, or returns `undefined` when `pathname` is not under `prefix`.
7
+ * The rest of the path must start at a segment boundary, so `/apis` is not under `/api`.
8
+ */
9
+ export declare function stripHttpPathPrefix(pathname: `/${string}`, prefix: `/${string}`): `/${string}` | undefined;
10
+ export declare function matchesHttpPath(url: `/${string}`, path: `/${string}`): boolean;
11
+ /**
12
+ * Content codings that oRPC compression plugins can encode and decode.
13
+ */
14
+ declare const COMPRESSION_ENCODINGS: readonly ["gzip", "deflate", "deflate-raw"];
15
+ export type CompressionEncoding = (typeof COMPRESSION_ENCODINGS)[number];
16
+ export declare function isCompressionEncoding(encoding: string): encoding is CompressionEncoding;
17
+ /**
18
+ * Parse Content-Encoding into ordered codings (order applied), ignoring empty list elements.
19
+ *
20
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-content-encoding
21
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-lists-rule-abnf-extension
22
+ */
23
+ export declare function parseContentEncodings(header: string | undefined): string[];
24
+ /**
25
+ * Roughly estimates the UTF-8 byte length of a string without encoding it.
26
+ */
27
+ export declare function estimateUtf8ByteLength(value: string): number;
28
+ /**
29
+ * Estimates how many bytes of a FormData body are worth compressing. Non-compressible blobs count
30
+ * against the total. Returns `Infinity` when a compressible blob has an unknown size, and
31
+ * `-Infinity` when a non-compressible one does, since the estimate is then unreliable.
32
+ */
33
+ export declare function estimateCompressibleFormDataSize(formData: FormData, isCompressible: (contentType: string) => boolean): number;
34
+ /**
35
+ * Parse Accept-Encoding into each coding's q-value, where `0` means the coding is explicitly
36
+ * unacceptable. The `*` wildcard is kept under its own key; use {@link isAcceptableEncoding}
37
+ * to decide whether a coding is acceptable.
38
+ *
39
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-accept-encoding
40
+ */
41
+ export declare function parseAcceptEncodingQualities(header: string | undefined): Map<string, number>;
42
+ /**
43
+ * Whether the client accepts a coding, given qualities from {@link parseAcceptEncodingQualities}.
44
+ * An explicit q-value takes precedence over the `*` wildcard, so `gzip;q=0, *` never accepts gzip.
45
+ *
46
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-accept-encoding
47
+ */
48
+ export declare function isAcceptableEncoding(qualities: Map<string, number>, coding: string): boolean;
49
+ /**
50
+ * Add `accept-encoding` to a Vary header value. The encoding is chosen from the request, so a
51
+ * shared cache must key on it or it will hand a compressed body to a client that cannot decode it.
52
+ *
53
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-vary
54
+ */
55
+ export declare function varyByAcceptEncoding(vary: string | undefined): string;
56
+ export declare function isNoTransformCacheControl(cacheControl: string | undefined): boolean;
57
+ export declare function isCompressibleContentType(contentType: string | null | undefined): boolean;
58
+ export {};
package/dist/http.js ADDED
@@ -0,0 +1,147 @@
1
+ import { safeDecodeURIComponent, safeEncodeURIComponent } from "@standard-server/shared";
2
+ // src/http.ts
3
+ function pathToHttpPath(path) {
4
+ return `/${path.map(safeEncodeURIComponent).join("/")}`;
5
+ }
6
+ function normalizeHttpPath(path) {
7
+ const paths = path.split("/");
8
+ if (paths.at(0) === "") paths.shift();
9
+ return pathToHttpPath(paths.map(safeDecodeURIComponent));
10
+ }
11
+ function mergeHttpPath(a, b) {
12
+ return `${a.endsWith("/") ? a.slice(0, -1) : a}${b}`;
13
+ }
14
+ function matchesHttpPathPrefix(url, prefix) {
15
+ if (!url.startsWith(prefix)) return false;
16
+ const charAfterPrefix = url[prefix.length];
17
+ return charAfterPrefix === "/" || charAfterPrefix === "?" || charAfterPrefix === "#" || charAfterPrefix === void 0 || prefix[prefix.length - 1] === "/";
18
+ }
19
+ /**
20
+ * Removes `prefix` from `pathname`, or returns `undefined` when `pathname` is not under `prefix`.
21
+ * The rest of the path must start at a segment boundary, so `/apis` is not under `/api`.
22
+ */
23
+ function stripHttpPathPrefix(pathname, prefix) {
24
+ if (!pathname.startsWith(prefix)) return;
25
+ const charAfterPrefix = pathname[prefix.length];
26
+ if (charAfterPrefix === "/") return pathname.slice(prefix.length);
27
+ if (charAfterPrefix === void 0) return "/";
28
+ if (prefix[prefix.length - 1] === "/") return pathname.slice(prefix.length - 1);
29
+ }
30
+ function matchesHttpPath(url, path) {
31
+ const pathWithoutEndSlash = path.endsWith("/") ? path.slice(0, path.length - 1) : path;
32
+ if (!url.startsWith(pathWithoutEndSlash)) return false;
33
+ let charAfterPrefix = url[pathWithoutEndSlash.length];
34
+ if (charAfterPrefix === "/") charAfterPrefix = url[pathWithoutEndSlash.length + 1];
35
+ return charAfterPrefix === void 0 || charAfterPrefix === "?" || charAfterPrefix === "#";
36
+ }
37
+ /**
38
+ * Content codings that oRPC compression plugins can encode and decode.
39
+ */
40
+ const COMPRESSION_ENCODINGS = [
41
+ "gzip",
42
+ "deflate",
43
+ "deflate-raw"
44
+ ];
45
+ function isCompressionEncoding(encoding) {
46
+ return COMPRESSION_ENCODINGS.includes(encoding);
47
+ }
48
+ /**
49
+ * Parse Content-Encoding into ordered codings (order applied), ignoring empty list elements.
50
+ *
51
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-content-encoding
52
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-lists-rule-abnf-extension
53
+ */
54
+ function parseContentEncodings(header) {
55
+ const codings = [];
56
+ for (const part of header?.split(",") ?? []) {
57
+ const coding = part.trim().toLowerCase();
58
+ if (coding !== "") codings.push(coding);
59
+ }
60
+ return codings;
61
+ }
62
+ const AVG_UTF8_BYTES_PER_CHAR = 1.2;
63
+ /**
64
+ * Roughly estimates the UTF-8 byte length of a string without encoding it.
65
+ */
66
+ function estimateUtf8ByteLength(value) {
67
+ return value.length * AVG_UTF8_BYTES_PER_CHAR;
68
+ }
69
+ const FORM_DATA_PART_OVERHEAD = 64;
70
+ /**
71
+ * Estimates how many bytes of a FormData body are worth compressing. Non-compressible blobs count
72
+ * against the total. Returns `Infinity` when a compressible blob has an unknown size, and
73
+ * `-Infinity` when a non-compressible one does, since the estimate is then unreliable.
74
+ */
75
+ function estimateCompressibleFormDataSize(formData, isCompressible) {
76
+ let size = 0;
77
+ for (const [key, value] of formData) {
78
+ size += FORM_DATA_PART_OVERHEAD + key.length;
79
+ if (value instanceof Blob) {
80
+ if (!Number.isFinite(value.size)) {
81
+ if (!isCompressible(value.type)) return -Infinity;
82
+ size = Infinity;
83
+ } else size += isCompressible(value.type) ? value.size : -value.size;
84
+ } else size += estimateUtf8ByteLength(value);
85
+ }
86
+ return size;
87
+ }
88
+ const ACCEPT_ENCODING_QUALITY_REGEX = /^\s*q=([\d.]+)\s*$/i;
89
+ /**
90
+ * Parse Accept-Encoding into each coding's q-value, where `0` means the coding is explicitly
91
+ * unacceptable. The `*` wildcard is kept under its own key; use {@link isAcceptableEncoding}
92
+ * to decide whether a coding is acceptable.
93
+ *
94
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-accept-encoding
95
+ */
96
+ function parseAcceptEncodingQualities(header) {
97
+ const qualities = /* @__PURE__ */ new Map();
98
+ for (const part of header?.split(",") ?? []) {
99
+ const [rawCoding, ...params] = part.split(";");
100
+ const coding = rawCoding.trim().toLowerCase();
101
+ if (coding === "") continue;
102
+ const quality = params.map((param) => ACCEPT_ENCODING_QUALITY_REGEX.exec(param)?.[1]).find((value) => value !== void 0);
103
+ qualities.set(coding, quality === void 0 ? 1 : Number(quality));
104
+ }
105
+ return qualities;
106
+ }
107
+ /**
108
+ * Whether the client accepts a coding, given qualities from {@link parseAcceptEncodingQualities}.
109
+ * An explicit q-value takes precedence over the `*` wildcard, so `gzip;q=0, *` never accepts gzip.
110
+ *
111
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-accept-encoding
112
+ */
113
+ function isAcceptableEncoding(qualities, coding) {
114
+ return (qualities.get(coding) ?? qualities.get("*") ?? 0) > 0;
115
+ }
116
+ /**
117
+ * Add `accept-encoding` to a Vary header value. The encoding is chosen from the request, so a
118
+ * shared cache must key on it or it will hand a compressed body to a client that cannot decode it.
119
+ *
120
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-vary
121
+ */
122
+ function varyByAcceptEncoding(vary) {
123
+ if (vary === void 0) return "accept-encoding";
124
+ const fields = vary.split(",").map((field) => field.trim().toLowerCase());
125
+ return fields.includes("accept-encoding") || fields.includes("*") ? vary : `${vary}, accept-encoding`;
126
+ }
127
+ /**
128
+ * Whether Cache-Control includes the no-transform directive, which forbids transforming the body.
129
+ *
130
+ * @see https://www.rfc-editor.org/rfc/rfc9111.html#name-no-transform
131
+ */
132
+ const CACHE_CONTROL_NO_TRANSFORM_REGEX = /(?:^|,)\s*no-transform\s*(?:,|$)/i;
133
+ function isNoTransformCacheControl(cacheControl) {
134
+ if (cacheControl === void 0) return false;
135
+ return CACHE_CONTROL_NO_TRANSFORM_REGEX.test(cacheControl);
136
+ }
137
+ /**
138
+ * inspired from Hono Compression Plugin
139
+ */
140
+ const COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
141
+ const MAX_COMPRESSIBLE_CONTENT_TYPE_LENGTH = 1024;
142
+ function isCompressibleContentType(contentType) {
143
+ if (contentType === null || contentType === void 0) return false;
144
+ if (contentType.length > MAX_COMPRESSIBLE_CONTENT_TYPE_LENGTH) return false;
145
+ return COMPRESSIBLE_CONTENT_TYPE_REGEX.test(contentType);
146
+ }
147
+ export { estimateCompressibleFormDataSize, estimateUtf8ByteLength, isAcceptableEncoding, isCompressibleContentType, isCompressionEncoding, isNoTransformCacheControl, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, normalizeHttpPath, parseAcceptEncodingQualities, parseContentEncodings, pathToHttpPath, stripHttpPathPrefix, varyByAcceptEncoding };
package/dist/id.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Compares two sequential IDs.
3
+ * Returns:
4
+ * - negative if `a` < `b`
5
+ * - positive if `a` > `b`
6
+ * - 0 if equal
7
+ */
8
+ export declare function compareSequentialIds(a: string, b: string): number;
package/dist/id.js ADDED
@@ -0,0 +1,13 @@
1
+ // src/id.ts
2
+ /**
3
+ * Compares two sequential IDs.
4
+ * Returns:
5
+ * - negative if `a` < `b`
6
+ * - positive if `a` > `b`
7
+ * - 0 if equal
8
+ */
9
+ function compareSequentialIds(a, b) {
10
+ if (a.length !== b.length) return a.length - b.length;
11
+ return a < b ? -1 : a > b ? 1 : 0;
12
+ }
13
+ export { compareSequentialIds };
package/dist/index.d.ts CHANGED
@@ -1,306 +1,26 @@
1
- import { Promisable } from 'type-fest';
2
- export { IsEqual, PartialDeep, Promisable, Writable } from 'type-fest';
3
- import { Tracer, TraceAPI, ContextAPI, PropagationAPI, SpanOptions, Context, Span, AttributeValue, Exception } from '@opentelemetry/api';
4
- import { AsyncIteratorClass } from '@standardserver/shared';
5
- export { AbortError, AsyncCleanupFn, AsyncIteratorClass, AsyncIteratorClassNextFn, SequentialIdGenerator, getOrBind, isAsyncIteratorObject, isTypescriptObject, parseEmptyableJSON, sleep, stringifyJSON, toArray } from '@standardserver/shared';
6
-
7
- type MaybeOptionalOptions<TOptions> = object extends TOptions ? [options?: TOptions] : [options: TOptions];
8
- declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>): T;
9
-
10
- declare function splitInHalf<T>(arr: readonly T[]): [T[], T[]];
11
-
12
- /**
13
- * Load Request/Response/Blob/File/.. to a buffer (Uint8Array<ArrayBuffer>).
14
- *
15
- * Prefers the newer `.bytes` method when available as it more efficient but not widely supported yet.
16
- */
17
- declare function loadBytes(source: Pick<Blob, 'arrayBuffer' | 'bytes'>): Promise<Uint8Array<ArrayBuffer>>;
18
- /**
19
- * Normalize text or binary-like inputs to either:
20
- * - the original string value, or
21
- * - a Uint8Array view over the source bytes.
22
- */
23
- declare function toStringOrBytes(source: string | ArrayBuffer | Blob | Exclude<ConstructorParameters<typeof Blob>[0], undefined>[0][] | Pick<Uint8Array<ArrayBuffer>, 'buffer' | 'byteOffset' | 'byteLength'>): Promise<string | Uint8Array<ArrayBuffer>>;
24
-
25
- declare function isDeepEqual(a: unknown, b: unknown): boolean;
26
-
27
- declare const ORPC_NAME = "orpc";
28
-
29
- declare function isAbortError(error: unknown): error is Error;
30
-
31
- type AnyFunction = (...args: any[]) => any;
32
- declare function once<T>(fn: () => T): () => T;
33
- /**
34
- * Executes the callback function after the current call stack has been cleared.
35
- */
36
- declare function defer(callback: () => void): void;
37
- declare function tryOrUndefined<T>(fn: () => T): undefined | T;
38
-
39
- declare function pathToHttpPath(path: readonly string[]): `/${string}`;
40
- declare function normalizeHttpPath(path: string): `/${string}`;
41
- declare function mergeHttpPath(a: `/${string}`, b: `/${string}`): `/${string}`;
42
- declare function matchesHttpPathPrefix(url: `/${string}`, prefix: `/${string}`): boolean;
43
- declare function matchesHttpPath(url: `/${string}`, path: `/${string}`): boolean;
44
-
45
- /**
46
- * Compares two sequential IDs.
47
- * Returns:
48
- * - negative if `a` < `b`
49
- * - positive if `a` > `b`
50
- * - 0 if equal
51
- */
52
- declare function compareSequentialIds(a: string, b: string): number;
53
-
54
- type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
55
- /**
56
- * Remove protected/private properties/methods
57
- */
58
- type Public<T> = Pick<T, keyof T>;
59
- type PromiseWithError<T, TError> = Promise<T> & {
60
- __error?: {
61
- type: TError;
62
- };
63
- };
64
- /**
65
- * The place where you can config the orpc types.
66
- *
67
- * - `ThrowableError` the error type that represent throwable errors should be `Error` or `null | undefined | {}` if you want more strict.
68
- */
69
- interface Registry {
70
- }
71
- type ThrowableError = Registry extends {
72
- ThrowableError: infer T;
73
- } ? T : Error;
74
-
75
- type InterceptableOptions = Record<string, any>;
76
- type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
77
- next(options?: TOptions): TResult;
78
- };
79
- type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult;
80
- /**
81
- * Can used for interceptors or middlewares
82
- */
83
- declare function onStart<T, TOptions extends {
84
- next: () => any;
85
- }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
86
- /**
87
- * Can used for interceptors or middlewares
88
- */
89
- declare function onSuccess<T, TOptions extends {
90
- next: () => any;
91
- }, TRest extends any[]>(callback: NoInfer<(result: Awaited<ReturnType<TOptions['next']>>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
92
- /**
93
- * Can used for interceptors or middlewares
94
- */
95
- declare function onError<T, TOptions extends {
96
- next: () => any;
97
- }, TRest extends any[]>(callback: NoInfer<(error: 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']>>>;
98
- type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess: false] | [error: null, data: TResult, isSuccess: true];
99
- /**
100
- * Can used for interceptors or middlewares
101
- */
102
- declare function onFinish<T, TOptions extends {
103
- next: () => any;
104
- }, 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']>>>;
105
- declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: undefined | Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
106
-
107
- /**
108
- * Only import types from @opentelemetry/api to avoid runtime dependencies.
109
- */
110
-
111
- interface OpenTelemetryConfig {
112
- tracer: Tracer;
113
- trace: TraceAPI;
114
- context: ContextAPI;
115
- /**
116
- * propagation is optional, can reduce bundle size in some cases.
117
- */
118
- propagation?: PropagationAPI | undefined;
119
- }
120
- declare function setOpenTelemetryConfig(config: OpenTelemetryConfig | undefined): void;
121
- declare function getOpenTelemetryConfig(): OpenTelemetryConfig | undefined;
122
- interface StartSpanOptions extends SpanOptions {
123
- /**
124
- * The name of the span to create.
125
- */
126
- name: string;
127
- /**
128
- * Context to use for the created span.
129
- */
130
- context?: Context;
131
- }
132
- declare function startSpan(options: StartSpanOptions | string): Span | undefined;
133
- declare function recordSpanError(span: Span | undefined, error: unknown): void;
134
- declare function setSpanAttributeIfDefined(span: Span | undefined, key: string, value: AttributeValue | undefined): void;
135
- declare function toOtelException(error: unknown): Exclude<Exception, string>;
136
- declare function toSpanAttributeValue(data: unknown): string;
137
- interface RunWithSpanOptions extends StartSpanOptions {
138
- }
139
- declare function runWithSpan<T>(options: string | RunWithSpanOptions, fn: (span?: Span) => Promisable<T>): Promise<T>;
140
- declare function runInSpanContext<T>(span: Span | undefined, fn: () => Promisable<T>): Promise<T>;
141
-
142
- interface WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn> {
143
- /**
144
- * Any call to the original iterator will be executed inside this function.
145
- * Useful when you want execution to happen within a specific context,
146
- * such as AsyncLocalStorage.
147
- */
148
- runWith?: <T>(run: () => Promise<T>) => Promise<T>;
149
- mapResult?: (result: IteratorResult<TYield, TReturn>) => Promisable<IteratorResult<TMappedYield, TMappedReturn>>;
150
- mapError?: (error: unknown) => Promisable<unknown>;
151
- onError?: (error: unknown) => Promisable<void>;
152
- /**
153
- * Execute after the stream finishes or is cancelled.
154
- */
155
- onFinish?: () => Promisable<void>;
156
- }
157
- declare function wrapAsyncIterator<TYield, TReturn, TMappedYield = TYield, TMappedReturn = TReturn>(iterator: AsyncIterator<TYield, TReturn>, { runWith, mapResult, mapError, onError, onFinish }: WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>): NoInfer<AsyncIteratorClass<TMappedYield, TMappedReturn>>;
158
- declare function traceAsyncIterator<T, TReturn, TNext>(options: StartSpanOptions | string, iterator: AsyncIterator<T, TReturn, TNext>): AsyncIteratorClass<T, TReturn, TNext>;
159
- declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorClass<T, TReturn, TNext>)[];
160
-
161
- type Segment = string | number;
162
- declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
163
- maps: Segment[][];
164
- values: unknown[];
165
- };
166
- /**
167
- * Get constructor of the value
168
- *
169
- */
170
- declare function getConstructor(value: unknown): Function | null | undefined;
171
- /**
172
- * Checks whether a value is a plain object, including objects created with
173
- * `Object.create(null)`.
174
- */
175
- declare function isPlainObject(value: unknown): value is Record<PropertyKey, unknown>;
176
- declare function get(object: unknown, path: readonly PropertyKey[]): unknown;
177
- /**
178
- * Sets a value at the given path, creating plain objects for intermediate keys as needed.
179
- */
180
- declare function set(root: object, path: [PropertyKey, ...PropertyKey[]] | [...PropertyKey[], PropertyKey], value: unknown): void;
181
- declare function omit<T extends object, K extends keyof T>(obj: T, keys: readonly K[]): Omit<T, K>;
182
- declare function clone<T>(value: T): T;
183
- declare function isPropertyKey(value: unknown): value is PropertyKey;
184
- declare const NullProtoObj: ({
185
- new <T extends Record<PropertyKey, unknown>>(): T;
186
- });
187
- /**
188
- * Returns an object containing all methods of the given object, with each
189
- * method bound to the original object instance.
190
- *
191
- * Methods are collected from both the object itself and its prototype chain
192
- * (excluding `Object.prototype` and the `constructor` property).
193
- */
194
- declare function bindMethods<T extends object>(obj: T): Pick<T, {
195
- [K in keyof T]: T[K] extends AnyFunction ? K : never;
196
- }[keyof T]>;
197
-
198
- interface OrderablePlugin {
199
- /** Unique name of the plugin, used for ordering and identification. */
200
- name: string;
201
- /** Plugins this plugin should execute before. */
202
- before?: string[] | undefined;
203
- /** Plugins this plugin should execute after. */
204
- after?: string[] | undefined;
205
- }
206
- /**
207
- * Sorts plugins based on their `before` and `after` dependencies.
208
- */
209
- declare function sortPlugins<T extends OrderablePlugin>(plugins: T[]): T[];
210
-
211
- /**
212
- * Creates a promise together with its associated `resolve` and `reject`
213
- * functions.
214
- *
215
- * Equivalent to `Promise.withResolvers()`, but works in environments
216
- * where that API is not yet available.
217
- */
218
- declare function promiseWithResolvers<T>(): {
219
- promise: Promise<T>;
220
- resolve: (v: T) => void;
221
- reject: (reason: unknown) => void;
222
- };
223
-
224
- type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
225
- declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
226
-
227
- /**
228
- * Creates a proxy that overlays a `partial` object on top of a `target`.
229
- *
230
- * - Properties from `partial` take precedence.
231
- * - Properties not present in `partial` fall back to the resolved `target`.
232
- * - Methods are bound to the proxy to ensure a consistent `this` context.
233
- *
234
- * Useful for overriding specific properties of an object while delegating
235
- * all other access to the original target without needing to know its full structure.
236
- */
237
- declare function override<T extends object, U extends object>(target: Value<T>, partial: U): U & Omit<T, keyof U>;
238
-
239
- interface AsyncIdQueueCloseOptions {
240
- id?: string;
241
- reason?: unknown;
242
- }
243
- declare class AsyncIdQueue<T> {
244
- private readonly openIds;
245
- private readonly queues;
246
- private readonly waiters;
247
- get size(): number;
248
- open(id: string): void;
249
- isOpen(id: string): boolean;
250
- push(id: string, item: T): void;
251
- pull(id: string): Promise<T>;
252
- close({ id, reason }?: AsyncIdQueueCloseOptions): void;
253
- private assertOpen;
254
- }
255
-
256
- /**
257
- * Returns a signal that aborts only after all provided signals are aborted.
258
- */
259
- declare function allAbortSignal(signals: readonly (AbortSignal | undefined)[]): AbortSignal | undefined;
260
- declare function runWithSignal<T>(signal: AbortSignal | undefined, fn: () => Promise<T>): Promise<T>;
261
-
262
- declare function replicateReadableStream<T>(stream: ReadableStream<T>, count: number): ReadableStream<T>[];
263
- type ReadableStreamReadResult<T> = {
264
- done: false;
265
- value: T;
266
- } | {
267
- done: true;
268
- value: undefined | T;
269
- };
270
- interface WrapReadableStreamOptions<T, TMapped> {
271
- /**
272
- * Any call to the original stream reader will be executed inside this function.
273
- * Useful when you want execution to happen within a specific context,
274
- * such as AsyncLocalStorage.
275
- */
276
- runWith?: <T>(run: () => Promise<T>) => Promise<T>;
277
- mapResult?: (result: ReadableStreamReadResult<T>) => Promisable<ReadableStreamReadResult<TMapped>>;
278
- mapError?: (error: unknown) => Promisable<unknown>;
279
- onError?: (error: unknown) => Promisable<void>;
280
- /**
281
- * Guaranteed to execute exactly once after the stream finishes or is cancelled.
282
- */
283
- onFinish?: () => Promisable<void>;
284
- }
285
- declare function wrapReadableStream<T, TMapped = T>(stream: ReadableStream<T>, { runWith, mapResult, mapError, onError, onFinish }: WrapReadableStreamOptions<T, TMapped>): NoInfer<ReadableStream<TMapped>>;
286
- declare function traceReadableStream<T>(options: StartSpanOptions | string, stream: ReadableStream<T>): ReadableStream<T>;
287
- /**
288
- * Converts a `ReadableStream` into an `AsyncIteratorClass`.
289
- */
290
- declare function streamToAsyncIteratorClass<T>(stream: ReadableStream<T>, { signal }?: {
291
- signal?: undefined | AbortSignal;
292
- }): AsyncIteratorClass<T>;
293
- /**
294
- * Converts an `AsyncIterator` into a `ReadableStream`.
295
- */
296
- declare function asyncIteratorToStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
297
- /**
298
- * Converts an `AsyncIterator` into a `ReadableStream`, ensuring that
299
- * all emitted object values are *unproxied* before enqueuing.
300
- */
301
- declare function asyncIteratorToUnproxiedDataStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
302
-
303
- declare function tryDecodeURIComponent(value: string): string;
304
-
305
- export { AsyncIdQueue, NullProtoObj, ORPC_NAME, allAbortSignal, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, bindMethods, clone, compareSequentialIds, defer, findDeepMatches, get, getConstructor, getOpenTelemetryConfig, intercept, isAbortError, isDeepEqual, isPlainObject, isPropertyKey, loadBytes, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, normalizeHttpPath, omit, onError, onFinish, onStart, onSuccess, once, override, pathToHttpPath, promiseWithResolvers, recordSpanError, replicateAsyncIterator, replicateReadableStream, resolveMaybeOptionalOptions, runInSpanContext, runWithSignal, runWithSpan, set, setOpenTelemetryConfig, setSpanAttributeIfDefined, sortPlugins, splitInHalf, startSpan, streamToAsyncIteratorClass, toOtelException, toSpanAttributeValue, toStringOrBytes, traceAsyncIterator, traceReadableStream, tryDecodeURIComponent, tryOrUndefined, value, wrapAsyncIterator, wrapReadableStream };
306
- export type { AnyFunction, AsyncIdQueueCloseOptions, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OnFinishState, OpenTelemetryConfig, OrderablePlugin, PromiseWithError, Public, ReadableStreamReadResult, Registry, RunWithSpanOptions, Segment, StartSpanOptions, ThrowableError, Value, WrapAsyncIteratorOptions, WrapReadableStreamOptions };
1
+ import { MaybeOptionalOptions, resolveMaybeOptionalOptions } from "./args.js";
2
+ import { splitInHalf, takeLast } from "./array.js";
3
+ import { DEFAULT_MAX_BIGINT_DIGITS, parseBigIntString } from "./bigint.js";
4
+ import { encodeBase64, loadBytes, toStringOrBytes } from "./buffer.js";
5
+ import { isDeepEqual } from "./compare.js";
6
+ import { ORPC_NAME } from "./consts.js";
7
+ import { isAbortError } from "./error.js";
8
+ import { AnyFunction, defer, isAsyncGeneratorFunction, once, tryOrUndefined } from "./function.js";
9
+ import { CompressionEncoding, estimateCompressibleFormDataSize, estimateUtf8ByteLength, isAcceptableEncoding, isCompressibleContentType, isCompressionEncoding, isNoTransformCacheControl, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, normalizeHttpPath, parseAcceptEncodingQualities, parseContentEncodings, pathToHttpPath, stripHttpPathPrefix, varyByAcceptEncoding } from "./http.js";
10
+ import { compareSequentialIds } from "./id.js";
11
+ import { InferNextError, InterceptableOptions, Interceptor, InterceptorOptions, OnFinishState, intercept, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess } from "./interceptor.js";
12
+ import { ConsumeAsyncIteratorOptions, WrapAsyncIteratorOptions, consumeAsyncIterator, replicateAsyncIterator, traceAsyncIterator, wrapAsyncIterator } from "./iterator.js";
13
+ import { NullProtoObj, Segment, bindMethods, clone, copyOnWrite, findDeepMatches, get, getConstructor, getConstructors, getOwn, isPlainObject, isPlainObjectOrArray, isPropertyKey, mergeTwoLevels, omit, pick, set, setOwn } from "./object.js";
14
+ import { OrderablePlugin, sortPlugins } from "./plugin.js";
15
+ import { captureAsyncContext, promiseWithResolvers } from "./promise.js";
16
+ import { override } from "./proxy.js";
17
+ import { AsyncIdQueue, AsyncIdQueueCloseOptions } from "./queue.js";
18
+ import { INTEGER_REGEX, NON_NEGATIVE_INTEGER_REGEX } from "./regex.js";
19
+ import { DisposableAllAbortSignal, anyAbortSignal, disposableAllAbortSignal, listenAbort, runWithSignal } from "./signal.js";
20
+ import { ReadableStreamReadResult, WrapReadableStreamOptions, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, replicateReadableStream, streamToAsyncIteratorObject, traceReadableStream, wrapReadableStream } from "./stream.js";
21
+ import { StartSpanOptions, Tracer, TracingAttributeValue, TracingException, TracingExceptionLevel, TracingHeaders, TracingSpan, getTracer, recordSpanError, runInSpanContext, runWithSpan, setSpanAttributeIfDefined, setTracer, startSpan, toSpanAttributeValue, toTracingException } from "./tracing.js";
22
+ import { DistributiveOmit, IntersectPick, Promisable, PromiseWithError, Public, Registry, ThrowableError } from "./types.js";
23
+ import { Value, value } from "./value.js";
24
+ import { AbortError, AsyncCleanupFn, AsyncIteratorClass, AsyncIteratorClassNextFn, SequentialIdGenerator, getOrBind, isAsyncIteratorObject, isNonPrimitive, isNonPrimitive as isTypescriptObject, parseEmptyableJSON, safeDecodeURIComponent, safeEncodeURIComponent, sequential, sleep, stringifyJSON, throwIfAborted, toArray } from "@standard-server/shared";
25
+ import { Arrayable, IsEqual, PartialDeep, Writable } from "type-fest";
26
+ export { AbortError, AnyFunction, type Arrayable, type AsyncCleanupFn, AsyncIdQueue, AsyncIdQueueCloseOptions, AsyncIteratorClass, type AsyncIteratorClassNextFn, CompressionEncoding, ConsumeAsyncIteratorOptions, DEFAULT_MAX_BIGINT_DIGITS, DisposableAllAbortSignal, DistributiveOmit, INTEGER_REGEX, InferNextError, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, type IsEqual, MaybeOptionalOptions, NON_NEGATIVE_INTEGER_REGEX, NullProtoObj, ORPC_NAME, OnFinishState, OrderablePlugin, type PartialDeep, Promisable, PromiseWithError, Public, ReadableStreamReadResult, Registry, Segment, SequentialIdGenerator, StartSpanOptions, ThrowableError, Tracer, TracingAttributeValue, TracingException, TracingExceptionLevel, TracingHeaders, TracingSpan, Value, WrapAsyncIteratorOptions, WrapReadableStreamOptions, type Writable, anyAbortSignal, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, bindMethods, captureAsyncContext, clone, compareSequentialIds, consumeAsyncIterator, copyOnWrite, defer, disposableAllAbortSignal, encodeBase64, estimateCompressibleFormDataSize, estimateUtf8ByteLength, findDeepMatches, get, getConstructor, getConstructors, getOrBind, getOwn, getTracer, intercept, isAbortError, isAcceptableEncoding, isAsyncGeneratorFunction, isAsyncIteratorObject, isCompressibleContentType, isCompressionEncoding, isDeepEqual, isNoTransformCacheControl, isNonPrimitive, isPlainObject as isObject, isPlainObject, isPlainObjectOrArray, isPropertyKey, isTypescriptObject, listenAbort, loadBytes, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, mergeTwoLevels, normalizeHttpPath, omit, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, once, override, parseAcceptEncodingQualities, parseBigIntString, parseContentEncodings, parseEmptyableJSON, pathToHttpPath, pick, promiseWithResolvers, recordSpanError, replicateAsyncIterator, replicateReadableStream, resolveMaybeOptionalOptions, runInSpanContext, runWithSignal, runWithSpan, safeDecodeURIComponent, safeEncodeURIComponent, sequential, set, setOwn, setSpanAttributeIfDefined, setTracer, sleep, sortPlugins, splitInHalf, startSpan, streamToAsyncIteratorObject, stringifyJSON, stripHttpPathPrefix, takeLast, throwIfAborted, toArray, toSpanAttributeValue, toStringOrBytes, toTracingException, traceAsyncIterator, traceReadableStream, tryOrUndefined, value, varyByAcceptEncoding, wrapAsyncIterator, wrapReadableStream };