@orpc/client 2.0.0-beta.5 → 2.0.0-beta.50

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 +137 -102
  2. package/dist/adapters/fetch/index.d.ts +3 -65
  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 +17 -0
  6. package/dist/adapters/fetch/transport.d.ts +32 -0
  7. package/dist/adapters/fetch/transport.js +51 -0
  8. package/dist/adapters/message-port/index.d.ts +4 -75
  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 +38 -0
  12. package/dist/adapters/message-port/rpc-link.d.ts +15 -0
  13. package/dist/adapters/message-port/rpc-link.js +18 -0
  14. package/dist/adapters/message-port/transport.d.ts +35 -0
  15. package/dist/adapters/message-port/transport.js +38 -0
  16. package/dist/adapters/standard/codec.d.ts +14 -0
  17. package/dist/adapters/standard/index.d.ts +6 -61
  18. package/dist/adapters/standard/index.js +2 -0
  19. package/dist/adapters/standard/link.d.ts +40 -0
  20. package/dist/adapters/standard/link.js +101 -0
  21. package/dist/adapters/standard/plugin.d.ts +26 -0
  22. package/dist/adapters/standard/plugin.js +14 -0
  23. package/dist/adapters/standard/rpc-link-codec.d.ts +56 -0
  24. package/dist/adapters/standard/rpc-link-codec.js +100 -0
  25. package/dist/adapters/standard/transport.d.ts +14 -0
  26. package/dist/adapters/websocket/index.d.ts +3 -121
  27. package/dist/adapters/websocket/index.js +2 -0
  28. package/dist/adapters/websocket/rpc-link.d.ts +14 -0
  29. package/dist/adapters/websocket/rpc-link.js +17 -0
  30. package/dist/adapters/websocket/transport.d.ts +116 -0
  31. package/dist/adapters/websocket/transport.js +105 -0
  32. package/dist/async-iterator-object.d.ts +2 -0
  33. package/dist/async-iterator-object.js +28 -0
  34. package/dist/client-safe.d.ts +16 -0
  35. package/dist/client-safe.js +31 -0
  36. package/dist/client.d.ts +38 -0
  37. package/dist/client.js +37 -0
  38. package/dist/consts.d.ts +10 -0
  39. package/dist/consts.js +20 -0
  40. package/dist/dynamic-link.d.ts +13 -0
  41. package/dist/dynamic-link.js +17 -0
  42. package/dist/error-utils.d.ts +20 -0
  43. package/dist/error-utils.js +54 -0
  44. package/dist/error.d.ts +132 -0
  45. package/dist/error.js +166 -0
  46. package/dist/index.d.ts +14 -155
  47. package/dist/index.js +12 -0
  48. package/dist/plugins/batch.d.ts +152 -0
  49. package/dist/plugins/batch.js +330 -0
  50. package/dist/plugins/cookie-jar.d.ts +85 -0
  51. package/dist/plugins/cookie-jar.js +231 -0
  52. package/dist/plugins/dedupe.d.ts +60 -0
  53. package/dist/plugins/dedupe.js +183 -0
  54. package/dist/plugins/index.d.ts +9 -242
  55. package/dist/plugins/index.js +8 -0
  56. package/dist/plugins/request-compression.d.ts +47 -0
  57. package/dist/plugins/request-compression.js +132 -0
  58. package/dist/plugins/response-compression.d.ts +31 -0
  59. package/dist/plugins/response-compression.js +67 -0
  60. package/dist/plugins/retry-after.d.ts +43 -0
  61. package/dist/plugins/retry-after.js +63 -0
  62. package/dist/plugins/retry.d.ts +84 -0
  63. package/dist/plugins/retry.js +121 -0
  64. package/dist/plugins/timeout.d.ts +27 -0
  65. package/dist/plugins/timeout.js +42 -0
  66. package/dist/rpc-json-serializer.d.ts +99 -0
  67. package/dist/rpc-json-serializer.js +347 -0
  68. package/dist/rpc-serializer.d.ts +31 -0
  69. package/dist/rpc-serializer.js +102 -0
  70. package/dist/types.d.ts +85 -0
  71. package/dist/utils.d.ts +36 -0
  72. package/dist/utils.js +67 -0
  73. package/package.json +47 -35
  74. package/dist/adapters/fetch/index.d.mts +0 -65
  75. package/dist/adapters/fetch/index.mjs +0 -68
  76. package/dist/adapters/message-port/index.d.mts +0 -75
  77. package/dist/adapters/message-port/index.mjs +0 -91
  78. package/dist/adapters/standard/index.d.mts +0 -61
  79. package/dist/adapters/standard/index.mjs +0 -6
  80. package/dist/adapters/websocket/index.d.mts +0 -121
  81. package/dist/adapters/websocket/index.mjs +0 -110
  82. package/dist/index.d.mts +0 -155
  83. package/dist/index.mjs +0 -154
  84. package/dist/plugins/index.d.mts +0 -242
  85. package/dist/plugins/index.mjs +0 -574
  86. package/dist/shared/client.8ug8I-zu.d.mts +0 -167
  87. package/dist/shared/client.8ug8I-zu.d.ts +0 -167
  88. package/dist/shared/client.BdItY5DT.d.mts +0 -111
  89. package/dist/shared/client.BdItY5DT.d.ts +0 -111
  90. package/dist/shared/client.CPF3hX6O.d.ts +0 -96
  91. package/dist/shared/client.Cby_-GGh.d.mts +0 -96
  92. package/dist/shared/client.DMXKFDyV.mjs +0 -343
  93. package/dist/shared/client.DXhchJ84.mjs +0 -174
  94. package/dist/shared/client.Dnfj8jnT.mjs +0 -92
package/dist/consts.js ADDED
@@ -0,0 +1,20 @@
1
+ // src/consts.ts
2
+ /**
3
+ * Property names that should resolve to the underlying value instead of
4
+ * continuing recursive proxy traversal.
5
+ *
6
+ * These properties are commonly accessed automatically by JavaScript runtimes,
7
+ * language features, or third-party libraries. Returning another recursive
8
+ * proxy for them can cause unexpected behavior, compatibility issues, or
9
+ * infinite proxy chains.
10
+ */
11
+ const RECURSIVE_CLIENT_UNWRAP_KEYS = /* @__PURE__ */ new Set([
12
+ "then",
13
+ "bind",
14
+ "call",
15
+ "apply",
16
+ "valueOf",
17
+ "toString",
18
+ "toJSON"
19
+ ]);
20
+ export { RECURSIVE_CLIENT_UNWRAP_KEYS };
@@ -0,0 +1,13 @@
1
+ import { ClientContext, ClientLink, ClientOptions } from "./types.js";
2
+ import { Promisable } from "@orpc/shared";
3
+ /**
4
+ * DynamicLink provides a way to dynamically resolve and delegate calls to other ClientLinks
5
+ * based on the request path, input, and context.
6
+ *
7
+ * @see {@link https://orpc.dev/docs/client/dynamic-link | DynamicLink}
8
+ */
9
+ export declare class DynamicLink<TClientContext extends ClientContext> implements ClientLink<TClientContext> {
10
+ private readonly linkResolver;
11
+ constructor(linkResolver: (options: ClientOptions<TClientContext>, path: string[], input: unknown) => Promisable<ClientLink<TClientContext>>);
12
+ call(path: string[], input: unknown, options: ClientOptions<TClientContext>): Promise<unknown>;
13
+ }
@@ -0,0 +1,17 @@
1
+ // src/dynamic-link.ts
2
+ /**
3
+ * DynamicLink provides a way to dynamically resolve and delegate calls to other ClientLinks
4
+ * based on the request path, input, and context.
5
+ *
6
+ * @see {@link https://orpc.dev/docs/client/dynamic-link | DynamicLink}
7
+ */
8
+ var DynamicLink = class {
9
+ linkResolver;
10
+ constructor(linkResolver) {
11
+ this.linkResolver = linkResolver;
12
+ }
13
+ async call(path, input, options) {
14
+ return await (await this.linkResolver(options, path, input)).call(path, input, options);
15
+ }
16
+ };
17
+ export { DynamicLink };
@@ -0,0 +1,20 @@
1
+ import { AnyORPCError, ORPCError, ORPCErrorCode, ORPCErrorJSON } from "./error.js";
2
+ /**
3
+ * Checks if an error is an `ORPCError` that matches a definition in the procedure's `.errors` map,
4
+ * narrowing it so `code` and `data` are fully typed.
5
+ *
6
+ * @see {@link https://orpc.dev/docs/client/error-handling#using-safe-and-isdefinederror | Client Error Handling - Using safe and isDefinedError}
7
+ */
8
+ export declare function isDefinedError<T>(error: T): error is Extract<T, AnyORPCError>;
9
+ export declare function toORPCError<T>(error: T): Extract<T, AnyORPCError> | ORPCError<"INTERNAL_SERVER_ERROR", undefined>;
10
+ export declare function isORPCErrorJson(json: unknown): json is ORPCErrorJSON<ORPCErrorCode, unknown>;
11
+ export declare function createORPCErrorFromJson<TCode extends ORPCErrorCode, TData>(json: ORPCErrorJSON<TCode, TData>, options?: ErrorOptions): ORPCError<TCode, TData>;
12
+ /**
13
+ * Clones an `ORPCError` while preserving its prototype chain, so instances of
14
+ * `ORPCError` subclasses remain `instanceof` their class.
15
+ *
16
+ * Limitation: subclass constructors are not re-run, so private fields
17
+ * (`#field`) are not carried over and subclass members that read them
18
+ * will throw on the clone.
19
+ */
20
+ export declare function cloneORPCError<T extends AnyORPCError>(error: T): T;
@@ -0,0 +1,54 @@
1
+ import { ORPCError } from "./error.js";
2
+ import { isPlainObject } from "@orpc/shared";
3
+ // src/error-utils.ts
4
+ /**
5
+ * Checks if an error is an `ORPCError` that matches a definition in the procedure's `.errors` map,
6
+ * narrowing it so `code` and `data` are fully typed.
7
+ *
8
+ * @see {@link https://orpc.dev/docs/client/error-handling#using-safe-and-isdefinederror | Client Error Handling - Using safe and isDefinedError}
9
+ */
10
+ function isDefinedError(error) {
11
+ return error instanceof ORPCError && error.defined;
12
+ }
13
+ function toORPCError(error) {
14
+ return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", { cause: error });
15
+ }
16
+ function isORPCErrorJson(json) {
17
+ if (!isPlainObject(json)) return false;
18
+ const validKeys = [
19
+ "defined",
20
+ "code",
21
+ "message",
22
+ "data"
23
+ ];
24
+ if (Object.keys(json).some((k) => !validKeys.includes(k))) return false;
25
+ return "defined" in json && typeof json.defined === "boolean" && "code" in json && typeof json.code === "string" && "message" in json && typeof json.message === "string";
26
+ }
27
+ function createORPCErrorFromJson(json, options = {}) {
28
+ const error = new ORPCError(json.code, {
29
+ ...json,
30
+ ...options
31
+ });
32
+ error.defined = json.defined;
33
+ return error;
34
+ }
35
+ /**
36
+ * Clones an `ORPCError` while preserving its prototype chain, so instances of
37
+ * `ORPCError` subclasses remain `instanceof` their class.
38
+ *
39
+ * Limitation: subclass constructors are not re-run, so private fields
40
+ * (`#field`) are not carried over and subclass members that read them
41
+ * will throw on the clone.
42
+ */
43
+ function cloneORPCError(error) {
44
+ const cloned = new ORPCError(error.code, {
45
+ message: error.message,
46
+ data: error.data,
47
+ cause: error.cause
48
+ });
49
+ Object.setPrototypeOf(cloned, Object.getPrototypeOf(error));
50
+ Object.defineProperties(cloned, Object.getOwnPropertyDescriptors(error));
51
+ cloned.stack = error.stack;
52
+ return cloned;
53
+ }
54
+ export { cloneORPCError, createORPCErrorFromJson, isDefinedError, isORPCErrorJson, toORPCError };
@@ -0,0 +1,132 @@
1
+ import { MaybeOptionalOptions, Registry } from "@orpc/shared";
2
+ import { StandardResponse } from "@standard-server/core";
3
+ /**
4
+ * Default mapping between common oRPC error codes and HTTP status codes.
5
+ * Handlers use it to determine response status codes; spread it to build a custom `errorStatusMap`.
6
+ *
7
+ * @see {@link https://orpc.dev/docs/rpc/handler#custom-error-response | RPC Handler - Custom Error Response}
8
+ * @see {@link https://orpc.dev/docs/openapi/handler#custom-error-response | OpenAPI Handler - Custom Error Response}
9
+ */
10
+ export declare const COMMON_ERROR_STATUS_MAP: {
11
+ BAD_REQUEST: number;
12
+ UNAUTHORIZED: number;
13
+ PAYMENT_REQUIRED: number;
14
+ FORBIDDEN: number;
15
+ NOT_FOUND: number;
16
+ METHOD_NOT_SUPPORTED: number;
17
+ NOT_ACCEPTABLE: number;
18
+ TIMEOUT: number;
19
+ CONFLICT: number;
20
+ GONE: number;
21
+ LENGTH_REQUIRED: number;
22
+ PRECONDITION_FAILED: number;
23
+ PAYLOAD_TOO_LARGE: number;
24
+ UNSUPPORTED_MEDIA_TYPE: number;
25
+ UNPROCESSABLE_CONTENT: number;
26
+ PRECONDITION_REQUIRED: number;
27
+ TOO_MANY_REQUESTS: number;
28
+ CLIENT_CLOSED_REQUEST: number;
29
+ INTERNAL_SERVER_ERROR: number;
30
+ NOT_IMPLEMENTED: number;
31
+ BAD_GATEWAY: number;
32
+ SERVICE_UNAVAILABLE: number;
33
+ GATEWAY_TIMEOUT: number;
34
+ };
35
+ export type ORPCErrorCode = Registry extends {
36
+ ORPCErrorCode: infer T extends string;
37
+ } ? T : keyof typeof COMMON_ERROR_STATUS_MAP | (string & {});
38
+ export type ORPCErrorOptions<TData> = ErrorOptions & {
39
+ message?: string | undefined;
40
+ } & (undefined extends TData ? {
41
+ data?: TData;
42
+ } : {
43
+ data: TData;
44
+ });
45
+ /**
46
+ * Typed error carrying a `code`, a `message`, and optional `data`.
47
+ * Throw it from handlers or middleware to produce typed error responses on the client.
48
+ *
49
+ * @see {@link https://orpc.dev/docs/error-handling#orpcerror-class | Error Handling - ORPCError Class}
50
+ */
51
+ export declare class ORPCError<TCode extends ORPCErrorCode, TData> extends Error {
52
+ /**
53
+ * @remarks
54
+ * **Note**: The `__branch` property is used for type branding, helping TypeScript distinguish
55
+ * an `ORPCError` instance from plain objects with a similar structure.
56
+ */
57
+ override readonly name: "ORPCError" & {
58
+ __branch: "ORPCError";
59
+ };
60
+ /**
61
+ * Indicates whether the error matches a definition in the procedure's `.errors` map,
62
+ * which makes its type inferable on the client.
63
+ */
64
+ readonly defined: boolean;
65
+ code: TCode;
66
+ data: TData;
67
+ constructor(code: TCode, ...rest: MaybeOptionalOptions<ORPCErrorOptions<TData>>);
68
+ toJSON(): ORPCErrorJSON<TCode, TData>;
69
+ /**
70
+ * Workaround for Next.js where different contexts use separate
71
+ * dependency graphs, causing multiple ORPCError constructors existing and breaking
72
+ * `instanceof` checks across contexts.
73
+ *
74
+ * This is particularly problematic with "Optimized SSR", where orpc-client
75
+ * executes in one context but is invoked from another. When an error is thrown
76
+ * in the execution context, `instanceof ORPCError` checks fail in the
77
+ * invocation context due to separate class constructors.
78
+ *
79
+ * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
80
+ */
81
+ static override [Symbol.hasInstance](instance: unknown): boolean;
82
+ }
83
+ export interface ORPCErrorJSON<TCode extends string, TData> extends Pick<ORPCError<TCode, TData>, "code" | "message" | "data"> {
84
+ /**
85
+ * remove readonly
86
+ */
87
+ defined: boolean;
88
+ }
89
+ export type AnyORPCError = ORPCError<any, any>;
90
+ export type AnyORPCErrorJSON = ORPCErrorJSON<any, any>;
91
+ export interface ResponseErrorOptions extends ErrorOptions {
92
+ /**
93
+ * @default inferred from the response status
94
+ */
95
+ message?: string | undefined;
96
+ response: StandardResponse;
97
+ }
98
+ /**
99
+ * Error carrying the resolved response a link received. Links set it as the `cause`
100
+ * of an `ORPCError` decoded from an error response, so details that are not part
101
+ * of the error itself, such as its status or headers, stay available.
102
+ *
103
+ * @see {@link https://orpc.dev/docs/rpc/link#error-responses | RPC Link - Error Responses}
104
+ * @see {@link https://orpc.dev/docs/openapi/link#error-responses | OpenAPI Link - Error Responses}
105
+ */
106
+ export declare class ResponseError extends Error {
107
+ override readonly name: string;
108
+ response: StandardResponse;
109
+ constructor(options: ResponseErrorOptions);
110
+ }
111
+ export interface MalformedResponseErrorOptions extends ResponseErrorOptions {
112
+ /**
113
+ * @default inferred from the response body or status
114
+ */
115
+ message?: string | undefined;
116
+ }
117
+ /**
118
+ * Error thrown by links when a response does not follow the expected oRPC format,
119
+ * for example when a proxy or gateway answers instead of your handler. Extends
120
+ * `ResponseError`, so it carries the resolved response. Unless overridden via
121
+ * `options.message`, the message is inferred from the response body or status.
122
+ *
123
+ * Unlike `ORPCError`, it reaches a handler's callers as a generic `INTERNAL_SERVER_ERROR`
124
+ * when thrown from the handler, so an upstream's response is not sent to them.
125
+ *
126
+ * @see {@link https://orpc.dev/docs/rpc/link#malformed-responses | RPC Link - Malformed Responses}
127
+ * @see {@link https://orpc.dev/docs/openapi/link#malformed-responses | OpenAPI Link - Malformed Responses}
128
+ */
129
+ export declare class MalformedResponseError extends ResponseError {
130
+ override readonly name = "MalformedResponseError";
131
+ constructor(options: MalformedResponseErrorOptions);
132
+ }
package/dist/error.js ADDED
@@ -0,0 +1,166 @@
1
+ import { getConstructors, isPlainObject, resolveMaybeOptionalOptions } from "@orpc/shared";
2
+ // src/error.ts
3
+ /**
4
+ * Default mapping between common oRPC error codes and HTTP status codes.
5
+ * Handlers use it to determine response status codes; spread it to build a custom `errorStatusMap`.
6
+ *
7
+ * @see {@link https://orpc.dev/docs/rpc/handler#custom-error-response | RPC Handler - Custom Error Response}
8
+ * @see {@link https://orpc.dev/docs/openapi/handler#custom-error-response | OpenAPI Handler - Custom Error Response}
9
+ */
10
+ const COMMON_ERROR_STATUS_MAP = {
11
+ BAD_REQUEST: 400,
12
+ UNAUTHORIZED: 401,
13
+ PAYMENT_REQUIRED: 402,
14
+ FORBIDDEN: 403,
15
+ NOT_FOUND: 404,
16
+ METHOD_NOT_SUPPORTED: 405,
17
+ NOT_ACCEPTABLE: 406,
18
+ TIMEOUT: 408,
19
+ CONFLICT: 409,
20
+ GONE: 410,
21
+ LENGTH_REQUIRED: 411,
22
+ PRECONDITION_FAILED: 412,
23
+ PAYLOAD_TOO_LARGE: 413,
24
+ UNSUPPORTED_MEDIA_TYPE: 415,
25
+ UNPROCESSABLE_CONTENT: 422,
26
+ PRECONDITION_REQUIRED: 428,
27
+ TOO_MANY_REQUESTS: 429,
28
+ CLIENT_CLOSED_REQUEST: 499,
29
+ INTERNAL_SERVER_ERROR: 500,
30
+ NOT_IMPLEMENTED: 501,
31
+ BAD_GATEWAY: 502,
32
+ SERVICE_UNAVAILABLE: 503,
33
+ GATEWAY_TIMEOUT: 504
34
+ };
35
+ let ORPCErrorConstructors;
36
+ /**
37
+ * Typed error carrying a `code`, a `message`, and optional `data`.
38
+ * Throw it from handlers or middleware to produce typed error responses on the client.
39
+ *
40
+ * @see {@link https://orpc.dev/docs/error-handling#orpcerror-class | Error Handling - ORPCError Class}
41
+ */
42
+ var ORPCError = class ORPCError extends Error {
43
+ /**
44
+ * Placed inside a static block (rather than at module level) to ensure this
45
+ * registration is treated as part of the class definition by bundlers.
46
+ *
47
+ * With `"sideEffects": false` in package.json, bundlers like webpack/Rollup
48
+ * are allowed to tree-shake any module-level statements that appear to have
49
+ * no consumers. A free-floating `globalORPCErrorConstructors.add(ORPCError)`
50
+ * at module level could be dropped entirely if the bundler decides the module
51
+ * is only partially used.
52
+ *
53
+ * By placing this inside `static {}`, the registration becomes inseparable
54
+ * from the class body itself — a bundler cannot include `ORPCError` without
55
+ * executing this block.
56
+ *
57
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks
58
+ */
59
+ static {
60
+ /**
61
+ * Store all ORPCError constructors
62
+ * for workaround of instanceof check in case multiple dependency graphs exist
63
+ */
64
+ const ORPC_ERROR_CONSTRUCTORS_SYMBOL = Symbol.for("ORPC_ERROR_CONSTRUCTORS");
65
+ globalThis[ORPC_ERROR_CONSTRUCTORS_SYMBOL] ??= /* @__PURE__ */ new WeakSet();
66
+ ORPCErrorConstructors = globalThis[ORPC_ERROR_CONSTRUCTORS_SYMBOL];
67
+ ORPCErrorConstructors.add(ORPCError);
68
+ }
69
+ /**
70
+ * @remarks
71
+ * **Note**: The `__branch` property is used for type branding, helping TypeScript distinguish
72
+ * an `ORPCError` instance from plain objects with a similar structure.
73
+ */
74
+ name = "ORPCError";
75
+ /**
76
+ * Indicates whether the error matches a definition in the procedure's `.errors` map,
77
+ * which makes its type inferable on the client.
78
+ */
79
+ defined = false;
80
+ code;
81
+ data;
82
+ constructor(code, ...rest) {
83
+ const options = resolveMaybeOptionalOptions(rest);
84
+ const message = options.message ?? codeToMessage(code);
85
+ super(message, options);
86
+ this.code = code;
87
+ this.data = options.data;
88
+ }
89
+ toJSON() {
90
+ return {
91
+ defined: this.defined,
92
+ code: this.code,
93
+ message: this.message,
94
+ data: this.data
95
+ };
96
+ }
97
+ /**
98
+ * Workaround for Next.js where different contexts use separate
99
+ * dependency graphs, causing multiple ORPCError constructors existing and breaking
100
+ * `instanceof` checks across contexts.
101
+ *
102
+ * This is particularly problematic with "Optimized SSR", where orpc-client
103
+ * executes in one context but is invoked from another. When an error is thrown
104
+ * in the execution context, `instanceof ORPCError` checks fail in the
105
+ * invocation context due to separate class constructors.
106
+ *
107
+ * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
108
+ */
109
+ static [Symbol.hasInstance](instance) {
110
+ if (!ORPCErrorConstructors.has(this)) return super[Symbol.hasInstance](instance);
111
+ for (const constructor of getConstructors(instance)) if (ORPCErrorConstructors.has(constructor)) return true;
112
+ return false;
113
+ }
114
+ };
115
+ /**
116
+ * Error carrying the resolved response a link received. Links set it as the `cause`
117
+ * of an `ORPCError` decoded from an error response, so details that are not part
118
+ * of the error itself, such as its status or headers, stay available.
119
+ *
120
+ * @see {@link https://orpc.dev/docs/rpc/link#error-responses | RPC Link - Error Responses}
121
+ * @see {@link https://orpc.dev/docs/openapi/link#error-responses | OpenAPI Link - Error Responses}
122
+ */
123
+ var ResponseError = class extends Error {
124
+ name = "ResponseError";
125
+ response;
126
+ constructor(options) {
127
+ super(options.message ?? `Received a ${options.response.status} response.`, options);
128
+ this.response = options.response;
129
+ }
130
+ };
131
+ /**
132
+ * Error thrown by links when a response does not follow the expected oRPC format,
133
+ * for example when a proxy or gateway answers instead of your handler. Extends
134
+ * `ResponseError`, so it carries the resolved response. Unless overridden via
135
+ * `options.message`, the message is inferred from the response body or status.
136
+ *
137
+ * Unlike `ORPCError`, it reaches a handler's callers as a generic `INTERNAL_SERVER_ERROR`
138
+ * when thrown from the handler, so an upstream's response is not sent to them.
139
+ *
140
+ * @see {@link https://orpc.dev/docs/rpc/link#malformed-responses | RPC Link - Malformed Responses}
141
+ * @see {@link https://orpc.dev/docs/openapi/link#malformed-responses | OpenAPI Link - Malformed Responses}
142
+ */
143
+ var MalformedResponseError = class extends ResponseError {
144
+ name = "MalformedResponseError";
145
+ constructor(options) {
146
+ super({
147
+ ...options,
148
+ message: options.message ?? inferMalformedResponseMessage(options.response)
149
+ });
150
+ }
151
+ };
152
+ /**
153
+ * Longer body strings are not used as the error message,
154
+ * e.g. full HTML error pages from a proxy or gateway.
155
+ */
156
+ const INFERRED_MESSAGE_MAX_LENGTH = 256;
157
+ function inferMalformedResponseMessage(response) {
158
+ const candidate = isPlainObject(response.body) ? response.body.message : response.body;
159
+ if (typeof candidate === "string" && candidate.length > 0 && candidate.length <= INFERRED_MESSAGE_MAX_LENGTH) return candidate;
160
+ const commonCode = Object.entries(COMMON_ERROR_STATUS_MAP).find(([, status]) => status === response.status)?.[0];
161
+ return commonCode ? codeToMessage(commonCode) : "Malformed oRPC Response";
162
+ }
163
+ function codeToMessage(code) {
164
+ return code.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ");
165
+ }
166
+ export { COMMON_ERROR_STATUS_MAP, MalformedResponseError, ORPCError, ResponseError };
package/dist/index.d.ts CHANGED
@@ -1,155 +1,14 @@
1
- import { O as ORPCErrorCode, c as ORPCError, d as ORPCErrorJSON, A as AnyORPCError, C as ClientContext, a as ClientOptions, e as AnyNestedClient, I as InferClientContext, f as InferClientError, g as Client, b as ClientLink, h as ClientRest, F as FriendlyClientOptions } from './shared/client.8ug8I-zu.js';
2
- export { i as AnyORPCErrorJSON, j as COMMON_ERROR_STATUS_MAP, k as InferClientBodyInputs, l as InferClientBodyOutputs, m as InferClientErrors, n as InferClientInputs, o as InferClientOutputs, N as NestedClient, p as ORPCErrorOptions } from './shared/client.8ug8I-zu.js';
3
- import { Interceptor, PromiseWithError, ThrowableError, Promisable, WrapAsyncIteratorOptions, AsyncIteratorClass } from '@orpc/shared';
4
- export { AsyncCleanupFn, AsyncIteratorClass, AsyncIteratorClassNextFn, MaybeOptionalOptions, PromiseWithError, Registry, ThrowableError, asyncIteratorToStream as eventIteratorToStream, asyncIteratorToUnproxiedDataStream as eventIteratorToUnproxiedDataStream, onError, onFinish, onStart, onSuccess, streamToAsyncIteratorClass as streamToEventIterator } from '@orpc/shared';
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.BdItY5DT.js';
6
- export { ErrorEvent, EventMeta, getEventMeta, unwrapEvent, withEventMeta } from '@standardserver/core';
7
-
8
- declare function isInferableError<T>(error: T): error is Extract<T, AnyORPCError>;
9
- declare function toORPCError<T>(error: T): Extract<T, AnyORPCError> | ORPCError<'INTERNAL_SERVER_ERROR', undefined>;
10
- declare function isORPCErrorJson(json: unknown): json is ORPCErrorJSON<ORPCErrorCode, unknown>;
11
- declare function createORPCErrorFromJson<TCode extends ORPCErrorCode, TData>(json: ORPCErrorJSON<TCode, TData>, options?: ErrorOptions): ORPCError<TCode, TData>;
12
- declare function cloneORPCError<T extends ORPCErrorCode, TData>(error: ORPCError<T, TData>): ORPCError<T, TData>;
13
-
14
- interface ORPCClientInterceptorOptions<TClientContext extends ClientContext, TInput> extends ClientOptions<TClientContext> {
15
- path: string[];
16
- input: TInput;
17
- }
18
- type ORPCClientInterceptor<TClientContext extends ClientContext, TInput, TOutput, TError> = Interceptor<ORPCClientInterceptorOptions<TClientContext, TInput>, PromiseWithError<TOutput, TError>>;
19
- interface ORPCClientScopedOptions<TClientContext extends ClientContext, TInput, TOutput, TError> {
20
- /**
21
- * Interceptors that wrap the entire client call lifecycle.
22
- */
23
- interceptors?: ORPCClientInterceptor<TClientContext, TInput, TOutput, TError>[];
24
- }
25
- type ORPCClientScoped<T extends AnyNestedClient> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? ORPCClientScopedOptions<UClientContext, UInput, UOutput, UError> : {
26
- [K in keyof T]?: T[K] extends AnyNestedClient ? ORPCClientScoped<T[K]> : never;
27
- };
28
- interface ORPCClientOptions<T extends AnyNestedClient> {
29
- /**
30
- * Use as base path for all procedure, useful when you only want to call a subset of the procedure.
31
- */
32
- path?: string[];
33
- /**
34
- * Interceptors that wrap the entire client call lifecycle, applied to every procedure call.
35
- */
36
- interceptors?: ORPCClientInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[];
37
- /**
38
- * Per-procedure options following the shape of the router.
39
- * Allows fine-grained configuration (e.g. additional interceptors) for individual procedures
40
- * without affecting the rest of the router.
41
- */
42
- scoped?: ORPCClientScoped<T>;
43
- }
44
- declare function createORPCClient<T extends AnyNestedClient>(link: ClientLink<InferClientContext<T>>, { path, ...options }?: NoInfer<ORPCClientOptions<T>>): T;
45
-
46
- declare function resolveFriendlyClientOptions<T extends ClientContext>(options: FriendlyClientOptions<T>): ClientOptions<T>;
47
- declare function resolveClientRest<TClientContext extends ClientContext, TInput>(rest: ClientRest<TClientContext, TInput>): [input: TInput, options: ClientOptions<TClientContext>];
48
- type SafeResult<TOutput, TError> = [error: null, data: TOutput, inferableError: null, isSuccess: true] & {
49
- error: null;
50
- data: TOutput;
51
- inferableError: null;
52
- isSuccess: true;
53
- } | [error: Exclude<TError, AnyORPCError>, data: undefined, inferableError: null, isSuccess: false] & {
54
- error: Exclude<TError, AnyORPCError>;
55
- data: undefined;
56
- inferableError: null;
57
- isSuccess: false;
58
- } | [error: Extract<TError, AnyORPCError>, data: undefined, inferableError: Extract<TError, AnyORPCError>, isSuccess: false] & {
59
- error: Extract<TError, AnyORPCError>;
60
- data: undefined;
61
- inferableError: Extract<TError, AnyORPCError>;
62
- isSuccess: false;
63
- };
64
- /**
65
- * Works like try/catch, but help you infer the error type if it is inferable ORPCError.
66
- *
67
- * @example
68
- * ```ts
69
- * const [error, data, inferableError, isSuccess] = await safe(client(...))
70
- * // or const { error, data, inferableError, isSuccess } = await safe(client(...))
71
- *
72
- * if (inferableError) {
73
- * console.log(inferableError) // or error, both are well typed
74
- * }
75
- */
76
- declare function safe<TOutput, TError = ThrowableError>(promise: PromiseWithError<TOutput, TError>): Promise<SafeResult<TOutput, TError>>;
77
- interface ConsumeEventIteratorOptions<T, TReturn, TError> {
78
- /**
79
- * Called on each event
80
- */
81
- onEvent: (event: T) => void;
82
- /**
83
- * Called once error happens
84
- */
85
- onError?: (error: TError) => void;
86
- /**
87
- * Called once event iterator is done
88
- *
89
- * @info If iterator is canceled, `undefined` can be passed on success
90
- */
91
- onSuccess?: (value: TReturn | undefined) => void;
92
- /**
93
- * Called once after onError or onSuccess
94
- *
95
- * @info If iterator is canceled, `undefined` can be passed on success
96
- */
97
- onFinish?: (state: [error: TError, data: undefined, isSuccess: false] | [error: null, data: TReturn | undefined, isSuccess: true]) => void;
98
- }
99
- /**
100
- * Consumes an event iterator with lifecycle callbacks
101
- *
102
- * @warning If no `onError` or `onFinish` is provided, error will be thrown into unhandled rejection channel.
103
- * @return unsubscribe callback
104
- */
105
- declare function consumeEventIterator<T, TReturn, TError = ThrowableError>(iterator: AsyncIterator<T, TReturn> | PromiseWithError<AsyncIterator<T, TReturn>, TError>, options: ConsumeEventIteratorOptions<T, TReturn, TError>): () => Promise<void>;
106
-
107
- type SafeClient<T extends AnyNestedClient> = T extends Client<infer UContext, infer UInput, infer UOutput, infer UError> ? (...rest: ClientRest<UContext, UInput>) => Promise<SafeResult<UOutput, UError>> : {
108
- [K in keyof T]: T[K] extends AnyNestedClient ? SafeClient<T[K]> : never;
109
- };
110
- /**
111
- * Create a safe client that automatically wraps all procedure calls with the `safe` util.
112
- *
113
- * @example
114
- * ```ts
115
- * const safeClient = createSafeClient(client)
116
- * const { error, data, inferrableError, isSuccess } = await safeClient.doSomething({ id: '123' })
117
- * // or const [error, data, inferrableError, isSuccess] = await safeClient.doSomething({ id: '123' })
118
- * ```
119
- *
120
- * @see {@link https://orpc.dev/docs/client/error-handling#using-createsafeclient Safe Client Docs}
121
- */
122
- declare function createSafeClient<T extends AnyNestedClient>(client: T): SafeClient<T>;
123
-
124
- /**
125
- * Property names that should resolve to the underlying value instead of
126
- * continuing recursive proxy traversal.
127
- *
128
- * These properties are commonly accessed automatically by JavaScript runtimes,
129
- * language features, or third-party libraries. Returning another recursive
130
- * proxy for them can cause unexpected behavior, compatibility issues, or
131
- * infinite proxy chains.
132
- */
133
- declare const RECURSIVE_CLIENT_UNWRAP_KEYS: Set<string>;
134
-
135
- /**
136
- * DynamicLink provides a way to dynamically resolve and delegate calls to other ClientLinks
137
- * based on the request path, input, and context.
138
- *
139
- * @see {@link https://orpc.dev/docs/client/dynamic-link Dynamic Link Docs}
140
- */
141
- declare class DynamicLink<TClientContext extends ClientContext> implements ClientLink<TClientContext> {
142
- private readonly linkResolver;
143
- constructor(linkResolver: (options: ClientOptions<TClientContext>, path: string[], input: unknown) => Promisable<ClientLink<TClientContext>>);
144
- call(path: string[], input: unknown, options: ClientOptions<TClientContext>): Promise<unknown>;
145
- }
146
-
147
- declare function wrapEventIteratorPreservingMeta<TYield, TReturn, TMappedYield = TYield, TMappedReturn = TReturn>(iterator: AsyncIterator<TYield, TReturn>, { mapResult, mapError, ...rest }: WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>): AsyncIteratorClass<TMappedYield, TMappedReturn>;
148
-
149
- /**
150
- * @deprecated Use `isInferableError` instead.
151
- */
152
- declare const isDefinedError: typeof isInferableError;
153
-
154
- export { AnyNestedClient, AnyORPCError, Client, ClientContext, ClientLink, ClientOptions, ClientRest, DynamicLink, FriendlyClientOptions, InferClientContext, InferClientError, ORPCError, ORPCErrorCode, ORPCErrorJSON, RECURSIVE_CLIENT_UNWRAP_KEYS, cloneORPCError, consumeEventIterator, createORPCClient, createORPCErrorFromJson, createSafeClient, isDefinedError, isInferableError, isORPCErrorJson, resolveClientRest, resolveFriendlyClientOptions, safe, toORPCError, wrapEventIteratorPreservingMeta };
155
- export type { ConsumeEventIteratorOptions, ORPCClientInterceptor, ORPCClientInterceptorOptions, ORPCClientOptions, ORPCClientScoped, ORPCClientScopedOptions, SafeClient, SafeResult };
1
+ import { wrapAsyncIteratorPreservingEventMeta } from "./async-iterator-object.js";
2
+ import { ORPCClientInterceptor, ORPCClientInterceptorOptions, ORPCClientOptions, ORPCClientScoped, ORPCClientScopedOptions, createORPCClient } from "./client.js";
3
+ import { SafeClient, createSafeClient } from "./client-safe.js";
4
+ import { RECURSIVE_CLIENT_UNWRAP_KEYS } from "./consts.js";
5
+ import { DynamicLink } from "./dynamic-link.js";
6
+ import { AnyORPCError, AnyORPCErrorJSON, COMMON_ERROR_STATUS_MAP, MalformedResponseError, MalformedResponseErrorOptions, ORPCError, ORPCErrorCode, ORPCErrorJSON, ORPCErrorOptions, ResponseError, ResponseErrorOptions } from "./error.js";
7
+ import { cloneORPCError, createORPCErrorFromJson, isDefinedError, isORPCErrorJson, toORPCError } from "./error-utils.js";
8
+ import { RPCJsonSerialization, RPCJsonSerializationMeta, RPCJsonSerializer, RPCJsonSerializerHandler, RPCJsonSerializerOptions } from "./rpc-json-serializer.js";
9
+ import { RPCSerializer, RPCSerializerOptions, RPCSerializerSerializeOptions } from "./rpc-serializer.js";
10
+ import { AnyNestedClient, Client, ClientContext, ClientLink, ClientOptions, ClientRest, FriendlyClientOptions, InferClientBodyInputs, InferClientBodyOutputs, InferClientContext, InferClientError, InferClientErrors, InferClientInputs, InferClientOutputs, NestedClient } from "./types.js";
11
+ import { SafeResult, resolveClientRest, safe } from "./utils.js";
12
+ import { AsyncCleanupFn, AsyncIteratorClass, AsyncIteratorClassNextFn, MaybeOptionalOptions, PromiseWithError, PromiseWithError as ClientPromiseResult, Registry, ThrowableError, asyncIteratorToStream, asyncIteratorToStream as eventIteratorToStream, asyncIteratorToUnproxiedDataStream, asyncIteratorToUnproxiedDataStream as eventIteratorToUnproxiedDataStream, consumeAsyncIterator, consumeAsyncIterator as consumeEventIterator, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, streamToAsyncIteratorObject, streamToAsyncIteratorObject as streamToEventIterator } from "@orpc/shared";
13
+ import { EventMeta, EventStreamErrorEvent, EventStreamErrorEvent as ErrorEvent, StandardBody, StandardBodyHint, StandardHeaders, StandardLazyRequest, StandardLazyResponse, StandardMethod, StandardRequest, StandardResponse, StandardUrl, getEventMeta, unwrapEvent, withEventMeta } from "@standard-server/core";
14
+ export { AnyNestedClient, AnyORPCError, AnyORPCErrorJSON, type AsyncCleanupFn, AsyncIteratorClass, type AsyncIteratorClassNextFn, COMMON_ERROR_STATUS_MAP, Client, ClientContext, ClientLink, ClientOptions, type ClientPromiseResult, ClientRest, DynamicLink, ErrorEvent, type EventMeta, EventStreamErrorEvent, FriendlyClientOptions, InferClientBodyInputs, InferClientBodyOutputs, InferClientContext, InferClientError, type InferClientError as InferClientErrorUnion, InferClientErrors, InferClientInputs, InferClientOutputs, MalformedResponseError, MalformedResponseErrorOptions, type MaybeOptionalOptions, NestedClient, ORPCClientInterceptor, ORPCClientInterceptorOptions, ORPCClientOptions, ORPCClientScoped, ORPCClientScopedOptions, ORPCError, ORPCErrorCode, ORPCErrorJSON, ORPCErrorOptions, type PromiseWithError, RECURSIVE_CLIENT_UNWRAP_KEYS, RPCJsonSerialization, RPCJsonSerializationMeta, RPCJsonSerializer, RPCJsonSerializerHandler, RPCJsonSerializerOptions, RPCSerializer, RPCSerializerOptions, RPCSerializerSerializeOptions, type Registry, ResponseError, ResponseErrorOptions, SafeClient, type SafeResult, type StandardBody, type StandardBodyHint, type StandardHeaders, type StandardLazyRequest, type StandardLazyResponse, type StandardMethod, type StandardRequest, type StandardResponse, type StandardUrl, type ThrowableError, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, cloneORPCError, consumeAsyncIterator, consumeEventIterator, createORPCClient, createORPCErrorFromJson, createSafeClient, eventIteratorToStream, eventIteratorToUnproxiedDataStream, getEventMeta, isDefinedError, isORPCErrorJson, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, resolveClientRest, safe, streamToAsyncIteratorObject, streamToEventIterator, toORPCError, unwrapEvent, withEventMeta, wrapAsyncIteratorPreservingEventMeta };
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ export { wrapAsyncIteratorPreservingEventMeta } from "./async-iterator-object.js";
2
+ export { createORPCClient } from "./client.js";
3
+ export { createSafeClient } from "./client-safe.js";
4
+ export { RECURSIVE_CLIENT_UNWRAP_KEYS } from "./consts.js";
5
+ export { DynamicLink } from "./dynamic-link.js";
6
+ export { COMMON_ERROR_STATUS_MAP, MalformedResponseError, ORPCError, ResponseError } from "./error.js";
7
+ export { cloneORPCError, createORPCErrorFromJson, isDefinedError, isORPCErrorJson, toORPCError } from "./error-utils.js";
8
+ export { RPCJsonSerializer } from "./rpc-json-serializer.js";
9
+ export { RPCSerializer } from "./rpc-serializer.js";
10
+ export { resolveClientRest, safe } from "./utils.js";
11
+ export { AsyncIteratorClass, asyncIteratorToStream, asyncIteratorToStream as eventIteratorToStream, asyncIteratorToUnproxiedDataStream, asyncIteratorToUnproxiedDataStream as eventIteratorToUnproxiedDataStream, consumeAsyncIterator, consumeAsyncIterator as consumeEventIterator, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, streamToAsyncIteratorObject, streamToAsyncIteratorObject as streamToEventIterator } from "@orpc/shared";
12
+ export { EventStreamErrorEvent, EventStreamErrorEvent as ErrorEvent, getEventMeta, unwrapEvent, withEventMeta } from "@standard-server/core";