@orpc/client 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 (94) hide show
  1. package/README.md +6 -7
  2. package/dist/adapters/fetch/index.d.ts +2 -48
  3. package/dist/adapters/fetch/index.js +2 -0
  4. package/dist/adapters/fetch/rpc-link.d.ts +14 -0
  5. package/dist/adapters/fetch/rpc-link.js +14 -0
  6. package/dist/adapters/fetch/transport.d.ts +34 -0
  7. package/dist/adapters/fetch/transport.js +65 -0
  8. package/dist/adapters/message-port/index.d.ts +3 -80
  9. package/dist/adapters/message-port/index.js +3 -0
  10. package/dist/adapters/message-port/message-port.d.ts +29 -0
  11. package/dist/adapters/message-port/message-port.js +56 -0
  12. package/dist/adapters/message-port/rpc-link.d.ts +15 -0
  13. package/dist/adapters/message-port/rpc-link.js +15 -0
  14. package/dist/adapters/message-port/transport.d.ts +38 -0
  15. package/dist/adapters/message-port/transport.js +52 -0
  16. package/dist/adapters/standard/codec.d.ts +14 -0
  17. package/dist/adapters/standard/codec.js +1 -0
  18. package/dist/adapters/standard/index.d.ts +5 -60
  19. package/dist/adapters/standard/index.js +4 -0
  20. package/dist/adapters/standard/link.d.ts +40 -0
  21. package/dist/adapters/standard/link.js +85 -0
  22. package/dist/adapters/standard/plugin.d.ts +32 -0
  23. package/dist/adapters/standard/plugin.js +16 -0
  24. package/dist/adapters/standard/{index.d.mts → rpc-link-codec.d.ts} +17 -14
  25. package/dist/adapters/standard/rpc-link-codec.js +104 -0
  26. package/dist/adapters/standard/transport.d.ts +14 -0
  27. package/dist/adapters/standard/transport.js +1 -0
  28. package/dist/adapters/websocket/index.d.ts +2 -136
  29. package/dist/adapters/websocket/index.js +2 -0
  30. package/dist/adapters/websocket/rpc-link.d.ts +14 -0
  31. package/dist/adapters/websocket/rpc-link.js +14 -0
  32. package/dist/adapters/websocket/{index.d.mts → transport.d.ts} +32 -53
  33. package/dist/adapters/websocket/transport.js +133 -0
  34. package/dist/async-iterator-object.d.ts +2 -0
  35. package/dist/async-iterator-object.js +29 -0
  36. package/dist/client-safe.d.ts +18 -0
  37. package/dist/client-safe.js +36 -0
  38. package/dist/client.d.ts +40 -0
  39. package/dist/client.js +39 -0
  40. package/dist/consts.d.ts +10 -0
  41. package/dist/consts.js +43 -0
  42. package/dist/dynamic-link.d.ts +13 -0
  43. package/dist/dynamic-link.js +17 -0
  44. package/dist/error-utils.d.ts +21 -0
  45. package/dist/error-utils.js +58 -0
  46. package/dist/error.d.ts +132 -0
  47. package/dist/error.js +178 -0
  48. package/dist/index.d.ts +38 -129
  49. package/dist/index.js +40 -0
  50. package/dist/plugins/batch.d.ts +185 -0
  51. package/dist/plugins/batch.js +401 -0
  52. package/dist/plugins/cookie-jar.d.ts +82 -0
  53. package/dist/plugins/cookie-jar.js +268 -0
  54. package/dist/plugins/dedupe.d.ts +64 -0
  55. package/dist/plugins/dedupe.js +226 -0
  56. package/dist/plugins/index.d.ts +20 -412
  57. package/dist/plugins/index.js +23 -0
  58. package/dist/plugins/request-compression.d.ts +44 -0
  59. package/dist/plugins/request-compression.js +178 -0
  60. package/dist/plugins/response-compression.d.ts +28 -0
  61. package/dist/plugins/response-compression.js +91 -0
  62. package/dist/plugins/retry-after.d.ts +50 -0
  63. package/dist/plugins/retry-after.js +88 -0
  64. package/dist/plugins/retry.d.ts +84 -0
  65. package/dist/plugins/retry.js +140 -0
  66. package/dist/plugins/timeout.d.ts +25 -0
  67. package/dist/plugins/timeout.js +37 -0
  68. package/dist/{shared/client.DqIWeNhQ.d.mts → rpc-json-serializer.d.ts} +9 -41
  69. package/dist/rpc-json-serializer.js +392 -0
  70. package/dist/rpc-serializer.d.ts +32 -0
  71. package/dist/rpc-serializer.js +130 -0
  72. package/dist/types.d.ts +97 -0
  73. package/dist/types.js +1 -0
  74. package/dist/utils.d.ts +47 -0
  75. package/dist/utils.js +51 -0
  76. package/package.json +43 -45
  77. package/dist/adapters/fetch/index.d.mts +0 -48
  78. package/dist/adapters/fetch/index.mjs +0 -77
  79. package/dist/adapters/message-port/index.d.mts +0 -80
  80. package/dist/adapters/message-port/index.mjs +0 -101
  81. package/dist/adapters/standard/index.mjs +0 -6
  82. package/dist/adapters/websocket/index.mjs +0 -131
  83. package/dist/index.d.mts +0 -144
  84. package/dist/index.mjs +0 -147
  85. package/dist/plugins/index.d.mts +0 -420
  86. package/dist/plugins/index.mjs +0 -971
  87. package/dist/shared/client.BoHJeq15.d.mts +0 -233
  88. package/dist/shared/client.BoHJeq15.d.ts +0 -233
  89. package/dist/shared/client.CKQeJJ2U.mjs +0 -172
  90. package/dist/shared/client.DqIWeNhQ.d.ts +0 -131
  91. package/dist/shared/client.JBJwBhR8.d.ts +0 -90
  92. package/dist/shared/client.LF04eOvL.mjs +0 -115
  93. package/dist/shared/client._wG5INmC.mjs +0 -505
  94. package/dist/shared/client.euYjjcFz.d.mts +0 -90
package/dist/error.js ADDED
@@ -0,0 +1,178 @@
1
+ import { getConstructors, isPlainObject, resolveMaybeOptionalOptions } from '@orpc/shared';
2
+ /**
3
+ * Default mapping between common oRPC error codes and HTTP status codes.
4
+ * Handlers use it to determine response status codes; spread it to build a custom `errorStatusMap`.
5
+ *
6
+ * @see {@link https://orpc.dev/docs/rpc/handler#custom-error-response | RPC Handler - Custom Error Response}
7
+ * @see {@link https://orpc.dev/docs/openapi/handler#custom-error-response | OpenAPI Handler - Custom Error Response}
8
+ */
9
+ export const COMMON_ERROR_STATUS_MAP = {
10
+ BAD_REQUEST: 400,
11
+ UNAUTHORIZED: 401,
12
+ PAYMENT_REQUIRED: 402,
13
+ FORBIDDEN: 403,
14
+ NOT_FOUND: 404,
15
+ METHOD_NOT_SUPPORTED: 405,
16
+ NOT_ACCEPTABLE: 406,
17
+ TIMEOUT: 408,
18
+ CONFLICT: 409,
19
+ GONE: 410,
20
+ LENGTH_REQUIRED: 411,
21
+ PRECONDITION_FAILED: 412,
22
+ PAYLOAD_TOO_LARGE: 413,
23
+ UNSUPPORTED_MEDIA_TYPE: 415,
24
+ UNPROCESSABLE_CONTENT: 422,
25
+ PRECONDITION_REQUIRED: 428,
26
+ TOO_MANY_REQUESTS: 429,
27
+ CLIENT_CLOSED_REQUEST: 499,
28
+ INTERNAL_SERVER_ERROR: 500,
29
+ NOT_IMPLEMENTED: 501,
30
+ BAD_GATEWAY: 502,
31
+ SERVICE_UNAVAILABLE: 503,
32
+ GATEWAY_TIMEOUT: 504,
33
+ };
34
+ let ORPCErrorConstructors;
35
+ /**
36
+ * Typed error carrying a `code`, a `message`, and optional `data`.
37
+ * Throw it from handlers or middleware to produce typed error responses on the client.
38
+ *
39
+ * @see {@link https://orpc.dev/docs/error-handling#orpcerror-class | Error Handling - ORPCError Class}
40
+ */
41
+ export class ORPCError extends Error {
42
+ /**
43
+ * Placed inside a static block (rather than at module level) to ensure this
44
+ * registration is treated as part of the class definition by bundlers.
45
+ *
46
+ * With `"sideEffects": false` in package.json, bundlers like webpack/Rollup
47
+ * are allowed to tree-shake any module-level statements that appear to have
48
+ * no consumers. A free-floating `globalORPCErrorConstructors.add(ORPCError)`
49
+ * at module level could be dropped entirely if the bundler decides the module
50
+ * is only partially used.
51
+ *
52
+ * By placing this inside `static {}`, the registration becomes inseparable
53
+ * from the class body itself — a bundler cannot include `ORPCError` without
54
+ * executing this block.
55
+ *
56
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks
57
+ */
58
+ static {
59
+ /**
60
+ * Store all ORPCError constructors
61
+ * for workaround of instanceof check in case multiple dependency graphs exist
62
+ */
63
+ const ORPC_ERROR_CONSTRUCTORS_SYMBOL = Symbol.for('ORPC_ERROR_CONSTRUCTORS');
64
+ void (globalThis[ORPC_ERROR_CONSTRUCTORS_SYMBOL] ??= new WeakSet());
65
+ ORPCErrorConstructors = globalThis[ORPC_ERROR_CONSTRUCTORS_SYMBOL];
66
+ ORPCErrorConstructors.add(ORPCError);
67
+ }
68
+ /**
69
+ * @remarks
70
+ * **Note**: The `__branch` property is used for type branding, helping TypeScript distinguish
71
+ * an `ORPCError` instance from plain objects with a similar structure.
72
+ */
73
+ name = 'ORPCError';
74
+ /**
75
+ * Indicates whether the error matches a definition in the procedure's `.errors` map,
76
+ * which makes its type inferable on the client.
77
+ */
78
+ defined = false;
79
+ code;
80
+ data;
81
+ constructor(code, ...rest) {
82
+ const options = resolveMaybeOptionalOptions(rest);
83
+ const message = options.message ?? codeToMessage(code);
84
+ super(message, options);
85
+ this.code = code;
86
+ this.data = options.data; // data only optional when TData is undefinable so can safely cast here
87
+ }
88
+ toJSON() {
89
+ return {
90
+ defined: this.defined,
91
+ code: this.code,
92
+ message: this.message,
93
+ data: this.data,
94
+ };
95
+ }
96
+ /**
97
+ * Workaround for Next.js where different contexts use separate
98
+ * dependency graphs, causing multiple ORPCError constructors existing and breaking
99
+ * `instanceof` checks across contexts.
100
+ *
101
+ * This is particularly problematic with "Optimized SSR", where orpc-client
102
+ * executes in one context but is invoked from another. When an error is thrown
103
+ * in the execution context, `instanceof ORPCError` checks fail in the
104
+ * invocation context due to separate class constructors.
105
+ *
106
+ * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
107
+ */
108
+ static [Symbol.hasInstance](instance) {
109
+ if (!ORPCErrorConstructors.has(this)) {
110
+ // not applicable to extended classes
111
+ return super[Symbol.hasInstance](instance);
112
+ }
113
+ for (const constructor of getConstructors(instance)) {
114
+ if (ORPCErrorConstructors.has(constructor)) {
115
+ return true;
116
+ }
117
+ }
118
+ return false;
119
+ }
120
+ }
121
+ /**
122
+ * Error carrying the resolved response a link received. Links set it as the `cause`
123
+ * of an `ORPCError` decoded from an error response, so details that are not part
124
+ * of the error itself, such as its status or headers, stay available.
125
+ *
126
+ * @see {@link https://orpc.dev/docs/rpc/link#error-responses | RPC Link - Error Responses}
127
+ * @see {@link https://orpc.dev/docs/openapi/link#error-responses | OpenAPI Link - Error Responses}
128
+ */
129
+ export class ResponseError extends Error {
130
+ name = 'ResponseError';
131
+ response;
132
+ constructor(options) {
133
+ super(options.message ?? `Received a ${options.response.status} response.`, options);
134
+ this.response = options.response;
135
+ }
136
+ }
137
+ /**
138
+ * Error thrown by links when a response does not follow the expected oRPC format,
139
+ * for example when a proxy or gateway answers instead of your handler. Extends
140
+ * `ResponseError`, so it carries the resolved response. Unless overridden via
141
+ * `options.message`, the message is inferred from the response body or status.
142
+ *
143
+ * Unlike `ORPCError`, it reaches a handler's callers as a generic `INTERNAL_SERVER_ERROR`
144
+ * when thrown from the handler, so an upstream's response is not sent to them.
145
+ *
146
+ * @see {@link https://orpc.dev/docs/rpc/link#malformed-responses | RPC Link - Malformed Responses}
147
+ * @see {@link https://orpc.dev/docs/openapi/link#malformed-responses | OpenAPI Link - Malformed Responses}
148
+ */
149
+ export class MalformedResponseError extends ResponseError {
150
+ name = 'MalformedResponseError';
151
+ constructor(options) {
152
+ super({
153
+ ...options,
154
+ message: options.message ?? inferMalformedResponseMessage(options.response),
155
+ });
156
+ }
157
+ }
158
+ /**
159
+ * Longer body strings are not used as the error message,
160
+ * e.g. full HTML error pages from a proxy or gateway.
161
+ */
162
+ const INFERRED_MESSAGE_MAX_LENGTH = 256;
163
+ function inferMalformedResponseMessage(response) {
164
+ const candidate = isPlainObject(response.body) ? response.body.message : response.body;
165
+ if (typeof candidate === 'string' &&
166
+ candidate.length > 0 &&
167
+ candidate.length <= INFERRED_MESSAGE_MAX_LENGTH) {
168
+ return candidate;
169
+ }
170
+ const commonCode = Object.entries(COMMON_ERROR_STATUS_MAP).find(([, status]) => status === response.status)?.[0];
171
+ return commonCode ? codeToMessage(commonCode) : 'Malformed oRPC Response';
172
+ }
173
+ function codeToMessage(code) {
174
+ return code
175
+ .split('_')
176
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
177
+ .join(' ');
178
+ }
package/dist/index.d.ts CHANGED
@@ -1,144 +1,53 @@
1
- import { WrapAsyncIteratorOptions, AsyncIteratorClass, Interceptor, PromiseWithError, ThrowableError, Promisable } from '@orpc/shared';
2
- export { AsyncCleanupFn, AsyncIteratorClass, AsyncIteratorClassNextFn, PromiseWithError as ClientPromiseResult, MaybeOptionalOptions, PromiseWithError, Registry, ThrowableError, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, consumeAsyncIterator, consumeAsyncIterator as consumeEventIterator, asyncIteratorToStream as eventIteratorToStream, asyncIteratorToUnproxiedDataStream as eventIteratorToUnproxiedDataStream, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, streamToAsyncIteratorObject, streamToAsyncIteratorObject as streamToEventIterator } from '@orpc/shared';
3
- import { C as ClientContext, a as ClientOptions, c as AnyNestedClient, I as InferClientContext, d as InferClientError, e as Client, b as ClientLink, A as AnyORPCError, f as ClientRest, O as ORPCErrorCode, g as ORPCErrorJSON, h as ORPCError } from './shared/client.BoHJeq15.js';
4
- export { i as AnyORPCErrorJSON, j as COMMON_ERROR_STATUS_MAP, F as FriendlyClientOptions, k as InferClientBodyInputs, l as InferClientBodyOutputs, m as InferClientErrors, n as InferClientInputs, o as InferClientOutputs, M as MalformedResponseError, p as MalformedResponseErrorOptions, N as NestedClient, q as ORPCErrorOptions, R as ResponseError, r as ResponseErrorOptions } from './shared/client.BoHJeq15.js';
5
- export { R as RPCJsonSerialization, a as RPCJsonSerializationMeta, b as RPCJsonSerializer, c as RPCJsonSerializerHandler, d as RPCJsonSerializerOptions, e as RPCSerializer, f as RPCSerializerOptions, g as RPCSerializerSerializeOptions } from './shared/client.DqIWeNhQ.js';
6
- export { ErrorEvent, EventMeta, StandardBody, StandardBodyHint, StandardHeaders, StandardLazyRequest, StandardLazyResponse, StandardMethod, StandardRequest, StandardResponse, StandardUrl, getEventMeta, unwrapEvent, withEventMeta } from '@standard-server/core';
7
-
8
- declare function wrapAsyncIteratorPreservingEventMeta<TYield, TReturn, TMappedYield = TYield, TMappedReturn = TReturn>(iterator: AsyncIterator<TYield, TReturn>, { mapResult, mapError, ...rest }: WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>): AsyncIteratorClass<TMappedYield, TMappedReturn>;
9
-
10
- interface ORPCClientInterceptorOptions<TClientContext extends ClientContext, TInput> extends ClientOptions<TClientContext> {
11
- path: string[];
12
- input: TInput;
13
- }
14
- type ORPCClientInterceptor<TClientContext extends ClientContext, TInput, TOutput, TError> = Interceptor<ORPCClientInterceptorOptions<TClientContext, TInput>, PromiseWithError<TOutput, TError>>;
15
- interface ORPCClientScopedOptions<TClientContext extends ClientContext, TInput, TOutput, TError> {
16
- /**
17
- * Interceptors that wrap the entire client call lifecycle.
18
- */
19
- interceptors?: ORPCClientInterceptor<TClientContext, TInput, TOutput, TError>[] | undefined;
20
- }
21
- type ORPCClientScoped<T extends AnyNestedClient> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? ORPCClientScopedOptions<UClientContext, UInput, UOutput, UError> : {
22
- [K in keyof T]?: (T[K] extends AnyNestedClient ? ORPCClientScoped<T[K]> : never) | undefined;
23
- };
24
- interface ORPCClientOptions<T extends AnyNestedClient> {
25
- /**
26
- * Use as base path for all procedure, useful when you only want to call a subset of the procedure.
27
- */
28
- path?: string[] | undefined;
29
- /**
30
- * Interceptors that wrap the entire client call lifecycle, applied to every procedure call.
31
- */
32
- interceptors?: ORPCClientInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
33
- /**
34
- * Per-procedure options following the shape of the router.
35
- * Allows fine-grained configuration (e.g. additional interceptors) for individual procedures
36
- * without affecting the rest of the router.
37
- */
38
- scoped?: ORPCClientScoped<T> | undefined;
39
- }
1
+ export * from './async-iterator-object.ts';
2
+ export * from './client.ts';
3
+ export * from './client-safe.ts';
4
+ export * from './consts.ts';
5
+ export * from './dynamic-link.ts';
6
+ export * from './error.ts';
7
+ export * from './error-utils.ts';
8
+ export * from './rpc-json-serializer.ts';
9
+ export * from './rpc-serializer.ts';
10
+ export * from './types.ts';
11
+ export type {
40
12
  /**
41
- * Creates a fully typed oRPC client from a link.
42
- * The returned client mirrors the shape of your router or contract,
43
- * so calling a procedure is as simple as calling a function.
44
- *
45
- * @see {@link https://orpc.dev/docs/client/client-side | Client-Side Clients}
13
+ * @deprecated Use `InferClientError` instead.
46
14
  */
47
- declare function createORPCClient<T extends AnyNestedClient>(link: ClientLink<InferClientContext<T>>, { path, ...options }?: NoInfer<ORPCClientOptions<T>>): T;
48
-
49
- declare function resolveClientRest<TClientContext extends ClientContext, TInput>(rest: ClientRest<TClientContext, TInput>): [input: TInput, options: ClientOptions<TClientContext>];
50
- type SafeResult<TOutput, TError> = [error: null, data: TOutput, definedError: null, isSuccess: true] & {
51
- error: null;
52
- data: TOutput;
53
- definedError: null;
54
- isSuccess: true;
55
- } | [error: Exclude<TError, AnyORPCError>, data: undefined, definedError: null, isSuccess: false] & {
56
- error: Exclude<TError, AnyORPCError>;
57
- data: undefined;
58
- definedError: null;
59
- isSuccess: false;
60
- } | [error: Extract<TError, AnyORPCError>, data: undefined, definedError: Extract<TError, AnyORPCError>, isSuccess: false] & {
61
- error: Extract<TError, AnyORPCError>;
62
- data: undefined;
63
- definedError: Extract<TError, AnyORPCError>;
64
- isSuccess: false;
65
- };
15
+ InferClientError as InferClientErrorUnion, } from './types.ts';
16
+ export { resolveClientRest, safe } from './utils.ts';
17
+ export type { SafeResult } from './utils.ts';
18
+ export type { AsyncCleanupFn, AsyncIteratorClassNextFn, MaybeOptionalOptions, PromiseWithError, Registry, ThrowableError, } from '@orpc/shared';
19
+ export { AsyncIteratorClass, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, consumeAsyncIterator,
66
20
  /**
67
- * Works like try/catch, but help you infer the error type if it is a defined ORPCError.
68
- *
69
- * @example
70
- * ```ts
71
- * const [error, data, definedError, isSuccess] = await safe(client(...))
72
- * // or const { error, data, definedError, isSuccess } = await safe(client(...))
73
- *
74
- * if (definedError) {
75
- * console.log(definedError) // or error, both are well typed
76
- * }
77
- * ```
78
- *
79
- * @see {@link https://orpc.dev/docs/client/error-handling#using-safe-and-isdefinederror | Client Error Handling - Using safe and isDefinedError}
21
+ * @deprecated Use `consumeAsyncIterator` instead.
80
22
  */
81
- declare function safe<TOutput, TError = ThrowableError>(promise: PromiseWithError<TOutput, TError>): Promise<SafeResult<TOutput, TError>>;
82
-
83
- type SafeClient<T extends AnyNestedClient> = T extends Client<infer UContext, infer UInput, infer UOutput, infer UError> ? (...rest: ClientRest<UContext, UInput>) => Promise<SafeResult<UOutput, UError>> : {
84
- [K in keyof T]: T[K] extends AnyNestedClient ? SafeClient<T[K]> : never;
85
- };
23
+ consumeAsyncIterator as consumeEventIterator,
86
24
  /**
87
- * Create a safe client that automatically wraps all procedure calls with the `safe` util.
88
- *
89
- * @example
90
- * ```ts
91
- * const safeClient = createSafeClient(client)
92
- * const { error, data, definedError, isSuccess } = await safeClient.doSomething({ id: '123' })
93
- * // or const [error, data, definedError, isSuccess] = await safeClient.doSomething({ id: '123' })
94
- * ```
95
- *
96
- * @see {@link https://orpc.dev/docs/client/error-handling#safe-client | Client Error Handling - Safe Client}
25
+ * @deprecated Use `asyncIteratorToStream` instead.
97
26
  */
98
- declare function createSafeClient<T extends AnyNestedClient>(client: T): SafeClient<T>;
99
-
27
+ asyncIteratorToStream as eventIteratorToStream,
100
28
  /**
101
- * Property names that should resolve to the underlying value instead of
102
- * continuing recursive proxy traversal.
103
- *
104
- * These properties are commonly accessed automatically by JavaScript runtimes,
105
- * language features, or third-party libraries. Returning another recursive
106
- * proxy for them can cause unexpected behavior, compatibility issues, or
107
- * infinite proxy chains.
29
+ * @deprecated Use `asyncIteratorToUnproxiedDataStream` instead.
108
30
  */
109
- declare const RECURSIVE_CLIENT_UNWRAP_KEYS: Set<PropertyKey>;
110
-
31
+ asyncIteratorToUnproxiedDataStream as eventIteratorToUnproxiedDataStream, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, streamToAsyncIteratorObject,
111
32
  /**
112
- * DynamicLink provides a way to dynamically resolve and delegate calls to other ClientLinks
113
- * based on the request path, input, and context.
114
- *
115
- * @see {@link https://orpc.dev/docs/client/dynamic-link | DynamicLink}
33
+ * @deprecated Use `streamToAsyncIteratorObject` instead.
116
34
  */
117
- declare class DynamicLink<TClientContext extends ClientContext> implements ClientLink<TClientContext> {
118
- private readonly linkResolver;
119
- constructor(linkResolver: (options: ClientOptions<TClientContext>, path: string[], input: unknown) => Promisable<ClientLink<TClientContext>>);
120
- call(path: string[], input: unknown, options: ClientOptions<TClientContext>): Promise<unknown>;
121
- }
122
-
35
+ streamToAsyncIteratorObject as streamToEventIterator, } from '@orpc/shared';
36
+ export type {
123
37
  /**
124
- * Checks if an error is an `ORPCError` that matches a definition in the procedure's `.errors` map,
125
- * narrowing it so `code` and `data` are fully typed.
126
- *
127
- * @see {@link https://orpc.dev/docs/client/error-handling#using-safe-and-isdefinederror | Client Error Handling - Using safe and isDefinedError}
38
+ * @deprecated Use `PromiseWithError` instead.
39
+ */
40
+ PromiseWithError as ClientPromiseResult, } from '@orpc/shared';
41
+ export type { EventMeta, StandardBody, StandardBodyHint, StandardHeaders, StandardLazyRequest, StandardLazyResponse, StandardMethod, StandardRequest, StandardResponse, StandardUrl, } from '@standard-server/core';
42
+ export {
43
+ /**
44
+ * @deprecated Use `EventStreamErrorEvent` instead.
128
45
  */
129
- declare function isDefinedError<T>(error: T): error is Extract<T, AnyORPCError>;
130
- declare function toORPCError<T>(error: T): Extract<T, AnyORPCError> | ORPCError<'INTERNAL_SERVER_ERROR', undefined>;
131
- declare function isORPCErrorJson(json: unknown): json is ORPCErrorJSON<ORPCErrorCode, unknown>;
132
- declare function createORPCErrorFromJson<TCode extends ORPCErrorCode, TData>(json: ORPCErrorJSON<TCode, TData>, options?: ErrorOptions): ORPCError<TCode, TData>;
46
+ EventStreamErrorEvent as ErrorEvent, EventStreamErrorEvent,
133
47
  /**
134
- * Clones an `ORPCError` while preserving its prototype chain, so instances of
135
- * `ORPCError` subclasses remain `instanceof` their class.
48
+ * Retrieves event metadata (such as the event id and retry interval)
49
+ * attached to a single iterator event value.
136
50
  *
137
- * Limitation: subclass constructors are not re-run, so private fields
138
- * (`#field`) are not carried over and subclass members that read them
139
- * will throw on the clone.
51
+ * @see {@link https://orpc.dev/docs/client/async-iterator-object#event-metadata | AsyncIteratorObject in Client - Event Metadata}
140
52
  */
141
- declare function cloneORPCError<T extends AnyORPCError>(error: T): T;
142
-
143
- export { AnyNestedClient, AnyORPCError, Client, ClientContext, ClientLink, ClientOptions, ClientRest, DynamicLink, InferClientContext, InferClientError, InferClientError as InferClientErrorUnion, ORPCError, ORPCErrorCode, ORPCErrorJSON, RECURSIVE_CLIENT_UNWRAP_KEYS, cloneORPCError, createORPCClient, createORPCErrorFromJson, createSafeClient, isDefinedError, isORPCErrorJson, resolveClientRest, safe, toORPCError, wrapAsyncIteratorPreservingEventMeta };
144
- export type { ORPCClientInterceptor, ORPCClientInterceptorOptions, ORPCClientOptions, ORPCClientScoped, ORPCClientScopedOptions, SafeClient, SafeResult };
53
+ getEventMeta, unwrapEvent, withEventMeta, } from '@standard-server/core';
package/dist/index.js ADDED
@@ -0,0 +1,40 @@
1
+ export * from './async-iterator-object.js';
2
+ export * from './client.js';
3
+ export * from './client-safe.js';
4
+ export * from './consts.js';
5
+ export * from './dynamic-link.js';
6
+ export * from './error.js';
7
+ export * from './error-utils.js';
8
+ export * from './rpc-json-serializer.js';
9
+ export * from './rpc-serializer.js';
10
+ export * from './types.js';
11
+ export { resolveClientRest, safe } from './utils.js';
12
+ export { AsyncIteratorClass, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, consumeAsyncIterator,
13
+ /**
14
+ * @deprecated Use `consumeAsyncIterator` instead.
15
+ */
16
+ consumeAsyncIterator as consumeEventIterator,
17
+ /**
18
+ * @deprecated Use `asyncIteratorToStream` instead.
19
+ */
20
+ asyncIteratorToStream as eventIteratorToStream,
21
+ /**
22
+ * @deprecated Use `asyncIteratorToUnproxiedDataStream` instead.
23
+ */
24
+ asyncIteratorToUnproxiedDataStream as eventIteratorToUnproxiedDataStream, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, streamToAsyncIteratorObject,
25
+ /**
26
+ * @deprecated Use `streamToAsyncIteratorObject` instead.
27
+ */
28
+ streamToAsyncIteratorObject as streamToEventIterator, } from '@orpc/shared';
29
+ export {
30
+ /**
31
+ * @deprecated Use `EventStreamErrorEvent` instead.
32
+ */
33
+ EventStreamErrorEvent as ErrorEvent, EventStreamErrorEvent,
34
+ /**
35
+ * Retrieves event metadata (such as the event id and retry interval)
36
+ * attached to a single iterator event value.
37
+ *
38
+ * @see {@link https://orpc.dev/docs/client/async-iterator-object#event-metadata | AsyncIteratorObject in Client - Event Metadata}
39
+ */
40
+ getEventMeta, unwrapEvent, withEventMeta, } from '@standard-server/core';
@@ -0,0 +1,185 @@
1
+ import type { Promisable, Value } from '@orpc/shared';
2
+ import type { StandardHeaders, StandardLazyResponse, StandardRequest, StandardUrl } from '@standard-server/core';
3
+ import type { StandardLinkOptions, StandardLinkPlugin, StandardLinkTransportInterceptorOptions } from '../adapters/standard/index.ts';
4
+ import type { ClientContext } from '../types.ts';
5
+ /**
6
+ * Header that marks a request as a batch, set by the Batch Link Plugin and detected by the Batch Handler Plugin.
7
+ * Nothing between the client and server, such as a CORS policy or proxy, should block or strip it.
8
+ *
9
+ * @see {@link https://orpc.dev/docs/plugins/batch#setup | Batch Plugin - Setup}
10
+ */
11
+ export declare const BATCH_HEADER = "orpc-batch";
12
+ /**
13
+ * Default `maxSize` of both the Batch Link Plugin and the Batch Handler Plugin.
14
+ *
15
+ * @see {@link https://orpc.dev/docs/plugins/batch#max-size | Batch Plugin - Max Size}
16
+ */
17
+ export declare const DEFAULT_BATCH_MAX_SIZE = 10;
18
+ /**
19
+ * @see {@link https://orpc.dev/docs/plugins/batch#response-modes | Batch Plugin - Response Modes}
20
+ */
21
+ export type BatchLinkPluginMode = 'buffered' | 'streaming';
22
+ export interface BatchLinkPluginGroup<T extends ClientContext> {
23
+ /**
24
+ * Determines whether a request should be included in this batch group.
25
+ * Requests will be evaluated against each group's condition in order,
26
+ * and included in the first group whose condition returns true.
27
+ * If no group's condition returns true, the request will not be batched.
28
+ */
29
+ condition: Value<boolean, [options: StandardLinkTransportInterceptorOptions<T>]>;
30
+ /**
31
+ * The client context applied to requests in this batch group for the remainder of the link chain.
32
+ */
33
+ context: Value<T, [
34
+ items: [
35
+ StandardLinkTransportInterceptorOptions<T>,
36
+ ...StandardLinkTransportInterceptorOptions<T>[]
37
+ ]
38
+ ]>;
39
+ /**
40
+ * The path segments applied to requests in this batch group for the remainder of the link chain.
41
+ *
42
+ * @default []
43
+ */
44
+ path?: Value<string[], [
45
+ items: [
46
+ StandardLinkTransportInterceptorOptions<T>,
47
+ ...StandardLinkTransportInterceptorOptions<T>[]
48
+ ]
49
+ ]> | undefined;
50
+ }
51
+ export interface BatchLinkPluginOptions<T extends ClientContext> {
52
+ groups: [BatchLinkPluginGroup<T>, ...BatchLinkPluginGroup<T>[]];
53
+ /**
54
+ * Filters requests to batch.
55
+ *
56
+ * @default () => true
57
+ */
58
+ filter?: Value<boolean, [options: StandardLinkTransportInterceptorOptions<T>]> | undefined;
59
+ /**
60
+ * Only requests with the same scope are batched together.
61
+ * On the server, return a value unique to the incoming request so different users never share a batch.
62
+ *
63
+ * @default () => undefined
64
+ */
65
+ scope?: ((options: StandardLinkTransportInterceptorOptions<T>) => unknown) | undefined;
66
+ /**
67
+ * The maximum number of requests in the batch. Larger batches are split.
68
+ * Keep it at or below the server Batch Handler Plugin's `maxSize`, which rejects larger batches with a `413`.
69
+ *
70
+ * @default DEFAULT_BATCH_MAX_SIZE (10)
71
+ * @see {@link https://orpc.dev/docs/plugins/batch#max-size | Batch Plugin - Max Size}
72
+ */
73
+ maxSize?: Value<Promisable<number>, [
74
+ subOptionsList: [
75
+ StandardLinkTransportInterceptorOptions<T>,
76
+ ...StandardLinkTransportInterceptorOptions<T>[]
77
+ ]
78
+ ]> | undefined;
79
+ /**
80
+ * How long (in ms) to wait for more requests before sending the batch,
81
+ * counted from the first queued request.
82
+ * With `0`, only requests made in the same event loop tick are batched.
83
+ *
84
+ * @default 0
85
+ */
86
+ wait?: number | undefined;
87
+ /**
88
+ * How the server sends the batch response.
89
+ *
90
+ * - `buffered`: waits for every subrequest, so the response carries their cookies and shared headers.
91
+ * - `streaming`: starts once the first subrequest responds and sends each other response as soon as it is
92
+ * ready, but carries only that first one's cookies.
93
+ *
94
+ * @default 'buffered'
95
+ * @see {@link https://orpc.dev/docs/plugins/batch#response-modes | Batch Plugin - Response Modes}
96
+ */
97
+ mode?: Value<Promisable<BatchLinkPluginMode>, [
98
+ subOptionsList: [
99
+ StandardLinkTransportInterceptorOptions<T>,
100
+ ...StandardLinkTransportInterceptorOptions<T>[]
101
+ ]
102
+ ]> | undefined;
103
+ /**
104
+ * URL for the batch request.
105
+ *
106
+ * @default URL of the first subrequest in the batch + '/__batch__'
107
+ */
108
+ url?: Value<Promisable<StandardUrl>, [
109
+ subOptionsList: [
110
+ StandardLinkTransportInterceptorOptions<T>,
111
+ ...StandardLinkTransportInterceptorOptions<T>[]
112
+ ]
113
+ ]> | undefined;
114
+ /**
115
+ * The maximum length of the URL that runtime supports,
116
+ * if exceeded, the batch will be split into smaller batches and sent sequentially.
117
+ *
118
+ * This only applies to GET batch requests where the batch data is sent via URL query parameter.
119
+ *
120
+ * @default 2083
121
+ */
122
+ maxUrlLength?: Value<Promisable<number>, [
123
+ subOptionsList: [
124
+ StandardLinkTransportInterceptorOptions<T>,
125
+ ...StandardLinkTransportInterceptorOptions<T>[]
126
+ ]
127
+ ]> | undefined;
128
+ /**
129
+ * Headers used for the batch request.
130
+ *
131
+ * @default Common headers among all subrequests in the batch.
132
+ */
133
+ headers?: Value<Promisable<StandardHeaders>, [
134
+ subOptionsList: [
135
+ StandardLinkTransportInterceptorOptions<T>,
136
+ ...StandardLinkTransportInterceptorOptions<T>[]
137
+ ]
138
+ ]> | undefined;
139
+ /**
140
+ * Map each subrequest in the batch before it is sent.
141
+ *
142
+ * @default Removes headers that are duplicated with the batch headers
143
+ */
144
+ mapSubrequest?: ((subOptions: StandardLinkTransportInterceptorOptions<T>, partialBatchRequest: Pick<StandardRequest, 'url' | 'headers'>) => StandardRequest) | undefined;
145
+ /**
146
+ * Maps each subresponse before returning the final response.
147
+ *
148
+ * @default Low-priority merges headers from the batch response into each subresponse.
149
+ */
150
+ mapSubresponse?: ((subResponse: StandardLazyResponse, batchResponse: StandardLazyResponse, subOptions: StandardLinkTransportInterceptorOptions<T>) => StandardLazyResponse) | undefined;
151
+ }
152
+ /**
153
+ * Combines multiple client requests into a single batch request
154
+ * and splits the batch response back into individual responses.
155
+ *
156
+ * @remarks
157
+ * **Note**: HTTP/2 and later already multiplex requests over a single connection, so this plugin is often less useful than it once was.
158
+ *
159
+ * @see {@link https://orpc.dev/docs/plugins/batch | Batch Plugin}
160
+ */
161
+ export declare class BatchLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
162
+ name: string;
163
+ private readonly groups;
164
+ private readonly filter;
165
+ private readonly scope;
166
+ private readonly maxSize;
167
+ private readonly wait;
168
+ private readonly mode;
169
+ private readonly batchUrl;
170
+ private readonly maxUrlLength;
171
+ private readonly batchHeaders;
172
+ private readonly mapSubrequest;
173
+ private readonly mapSubresponse;
174
+ private readonly queue;
175
+ constructor(options: NoInfer<BatchLinkPluginOptions<T>>);
176
+ init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
177
+ private processPendingBatches;
178
+ /**
179
+ * Runs the batch in the async context of its first request instead of the timer's,
180
+ * so the transport and batch options see that caller's request state.
181
+ * `executeBatch` always runs in the context of its first request.
182
+ */
183
+ private executeBatchInOwnContext;
184
+ private executeBatch;
185
+ }