@orpc/client 1.14.6 → 2.0.0-beta.10

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 (38) hide show
  1. package/README.md +78 -107
  2. package/dist/adapters/fetch/index.d.mts +54 -35
  3. package/dist/adapters/fetch/index.d.ts +54 -35
  4. package/dist/adapters/fetch/index.mjs +49 -27
  5. package/dist/adapters/message-port/index.d.mts +25 -30
  6. package/dist/adapters/message-port/index.d.ts +25 -30
  7. package/dist/adapters/message-port/index.mjs +33 -29
  8. package/dist/adapters/standard/index.d.mts +59 -9
  9. package/dist/adapters/standard/index.d.ts +59 -9
  10. package/dist/adapters/standard/index.mjs +5 -5
  11. package/dist/adapters/websocket/index.d.mts +113 -21
  12. package/dist/adapters/websocket/index.d.ts +113 -21
  13. package/dist/adapters/websocket/index.mjs +95 -37
  14. package/dist/index.d.mts +84 -159
  15. package/dist/index.d.ts +84 -159
  16. package/dist/index.mjs +76 -34
  17. package/dist/plugins/index.d.mts +125 -132
  18. package/dist/plugins/index.d.ts +125 -132
  19. package/dist/plugins/index.mjs +373 -284
  20. package/dist/shared/client.8ug8I-zu.d.mts +167 -0
  21. package/dist/shared/client.8ug8I-zu.d.ts +167 -0
  22. package/dist/shared/client.BN52ep3E.mjs +174 -0
  23. package/dist/shared/client.BdItY5DT.d.mts +111 -0
  24. package/dist/shared/client.BdItY5DT.d.ts +111 -0
  25. package/dist/shared/client.CPF3hX6O.d.ts +96 -0
  26. package/dist/shared/client.Cby_-GGh.d.mts +96 -0
  27. package/dist/shared/client.D3TIIok6.mjs +343 -0
  28. package/dist/shared/client.Dnfj8jnT.mjs +92 -0
  29. package/package.json +7 -7
  30. package/dist/shared/client.2jUAqzYU.d.ts +0 -45
  31. package/dist/shared/client.B3pNRBih.d.ts +0 -91
  32. package/dist/shared/client.BFAVy68H.d.mts +0 -91
  33. package/dist/shared/client.BLtwTQUg.mjs +0 -40
  34. package/dist/shared/client.CpCa3si8.d.mts +0 -45
  35. package/dist/shared/client.D9eWXdBV.mjs +0 -174
  36. package/dist/shared/client.DLhbktiD.mjs +0 -404
  37. package/dist/shared/client.i2uoJbEp.d.mts +0 -83
  38. package/dist/shared/client.i2uoJbEp.d.ts +0 -83
@@ -0,0 +1,167 @@
1
+ import { PromiseWithError, Registry, MaybeOptionalOptions } from '@orpc/shared';
2
+
3
+ interface ClientContext {
4
+ [key: PropertyKey]: any;
5
+ }
6
+ interface ClientOptions<T extends ClientContext> {
7
+ signal?: AbortSignal | undefined;
8
+ lastEventId?: string | undefined;
9
+ context: T;
10
+ }
11
+ type FriendlyClientOptions<T extends ClientContext> = Omit<ClientOptions<T>, 'context'> & (object extends T ? {
12
+ context?: T;
13
+ } : {
14
+ context: T;
15
+ });
16
+ type ClientRest<TClientContext extends ClientContext, TInput> = object extends TClientContext ? undefined extends TInput ? [input?: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options: FriendlyClientOptions<TClientContext>];
17
+ interface Client<TClientContext extends ClientContext, TInput, TOutput, TError> {
18
+ (...rest: ClientRest<TClientContext, TInput>): PromiseWithError<TOutput, TError>;
19
+ }
20
+ type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | {
21
+ [k: string]: NestedClient<TClientContext>;
22
+ };
23
+ type AnyNestedClient = NestedClient<any>;
24
+ type InferClientContext<T extends AnyNestedClient> = T extends NestedClient<infer U> ? U : never;
25
+ interface ClientLink<TClientContext extends ClientContext> {
26
+ call: (path: string[], input: unknown, options: ClientOptions<TClientContext>) => Promise<unknown>;
27
+ }
28
+ /**
29
+ * Recursively infers the **input types** from a client.
30
+ *
31
+ * Produces a nested map where each endpoint's input type is preserved.
32
+ */
33
+ type InferClientInputs<T extends AnyNestedClient> = T extends Client<any, infer U, any, any> ? U : {
34
+ [K in keyof T]: T[K] extends AnyNestedClient ? InferClientInputs<T[K]> : never;
35
+ };
36
+ /**
37
+ * Recursively infers the **body input types** from a client.
38
+ *
39
+ * If an endpoint's input includes `{ body: ... }`, only the `body` portion is extracted.
40
+ * Produces a nested map of body input types.
41
+ */
42
+ type InferClientBodyInputs<T extends AnyNestedClient> = T extends Client<any, infer U, any, any> ? U extends {
43
+ body: infer UBody;
44
+ } ? UBody : U : {
45
+ [K in keyof T]: T[K] extends AnyNestedClient ? InferClientBodyInputs<T[K]> : never;
46
+ };
47
+ /**
48
+ * Recursively infers the **output types** from a client.
49
+ *
50
+ * Produces a nested map where each endpoint's output type is preserved.
51
+ */
52
+ type InferClientOutputs<T extends AnyNestedClient> = T extends Client<any, any, infer U, any> ? U : {
53
+ [K in keyof T]: T[K] extends AnyNestedClient ? InferClientOutputs<T[K]> : never;
54
+ };
55
+ /**
56
+ * Recursively infers the **body output types** from a client.
57
+ *
58
+ * If an endpoint's output includes `{ body: ... }`, only the `body` portion is extracted.
59
+ * Produces a nested map of body output types.
60
+ */
61
+ type InferClientBodyOutputs<T extends AnyNestedClient> = T extends Client<any, any, infer U, any> ? U extends {
62
+ body: infer UBody;
63
+ } ? UBody : U : {
64
+ [K in keyof T]: T[K] extends AnyNestedClient ? InferClientBodyOutputs<T[K]> : never;
65
+ };
66
+ /**
67
+ * Recursively infers the **error types** from a client when you use [type-safe errors](https://orpc.dev/docs/error-handling#type‐safe-error-handling).
68
+ *
69
+ * Produces a nested map where each endpoint's error type is preserved.
70
+ */
71
+ type InferClientErrors<T extends AnyNestedClient> = T extends Client<any, any, any, infer U> ? U : {
72
+ [K in keyof T]: T[K] extends AnyNestedClient ? InferClientErrors<T[K]> : never;
73
+ };
74
+ /**
75
+ * Recursively infers a **union of all error types** from a client when you use [type-safe errors](https://orpc.dev/docs/error-handling#type‐safe-error-handling).
76
+ *
77
+ * Useful when you want to handle all possible errors from any endpoint at once.
78
+ */
79
+ type InferClientError<T extends AnyNestedClient> = T extends Client<any, any, any, infer U> ? U : {
80
+ [K in keyof T]: T[K] extends AnyNestedClient ? InferClientError<T[K]> : never;
81
+ }[keyof T];
82
+
83
+ declare const COMMON_ERROR_STATUS_MAP: {
84
+ BAD_REQUEST: number;
85
+ UNAUTHORIZED: number;
86
+ PAYMENT_REQUIRED: number;
87
+ FORBIDDEN: number;
88
+ NOT_FOUND: number;
89
+ METHOD_NOT_SUPPORTED: number;
90
+ NOT_ACCEPTABLE: number;
91
+ TIMEOUT: number;
92
+ CONFLICT: number;
93
+ GONE: number;
94
+ PRECONDITION_FAILED: number;
95
+ PAYLOAD_TOO_LARGE: number;
96
+ UNSUPPORTED_MEDIA_TYPE: number;
97
+ UNPROCESSABLE_CONTENT: number;
98
+ PRECONDITION_REQUIRED: number;
99
+ TOO_MANY_REQUESTS: number;
100
+ CLIENT_CLOSED_REQUEST: number;
101
+ INTERNAL_SERVER_ERROR: number;
102
+ NOT_IMPLEMENTED: number;
103
+ BAD_GATEWAY: number;
104
+ SERVICE_UNAVAILABLE: number;
105
+ GATEWAY_TIMEOUT: number;
106
+ };
107
+ type ORPCErrorCode = Registry extends {
108
+ ORPCErrorCode: infer T extends string;
109
+ } ? T : (keyof typeof COMMON_ERROR_STATUS_MAP) | (string & {});
110
+ type ORPCErrorOptions<TData> = ErrorOptions & {
111
+ message?: string;
112
+ } & (undefined extends TData ? {
113
+ data?: TData;
114
+ } : {
115
+ data: TData;
116
+ });
117
+ declare class ORPCError<TCode extends ORPCErrorCode, TData> extends Error {
118
+ /**
119
+ * @info
120
+ * The `__branch` property is used for type branding, helping TypeScript distinguish
121
+ * an `ORPCError` instance from plain objects with a similar structure.
122
+ */
123
+ readonly name: "ORPCError" & {
124
+ __branch: "ORPCError";
125
+ };
126
+ /**
127
+ * Indicates whether the error matches a definition in the procedure's `.errors` map.
128
+ */
129
+ readonly defined: boolean;
130
+ /**
131
+ * Indicates whether the error's type is inferable at the TypeScript level.
132
+ * This is typically true when the error is explicitly defined or returned within a handler.
133
+ */
134
+ readonly inferable: boolean;
135
+ code: TCode;
136
+ data: TData;
137
+ constructor(code: TCode, ...rest: MaybeOptionalOptions<ORPCErrorOptions<TData>>);
138
+ toJSON(): ORPCErrorJSON<TCode, TData>;
139
+ /**
140
+ * Workaround for Next.js where different contexts use separate
141
+ * dependency graphs, causing multiple ORPCError constructors existing and breaking
142
+ * `instanceof` checks across contexts.
143
+ *
144
+ * This is particularly problematic with "Optimized SSR", where orpc-client
145
+ * executes in one context but is invoked from another. When an error is thrown
146
+ * in the execution context, `instanceof ORPCError` checks fail in the
147
+ * invocation context due to separate class constructors.
148
+ *
149
+ * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
150
+ */
151
+ static [Symbol.hasInstance](instance: unknown): boolean;
152
+ }
153
+ interface ORPCErrorJSON<TCode extends string, TData> extends Pick<ORPCError<TCode, TData>, 'code' | 'message' | 'data'> {
154
+ /**
155
+ * remove readonly
156
+ */
157
+ defined: boolean;
158
+ /**
159
+ * remove readonly
160
+ */
161
+ inferable: boolean;
162
+ }
163
+ type AnyORPCError = ORPCError<any, any>;
164
+ type AnyORPCErrorJSON = ORPCErrorJSON<any, any>;
165
+
166
+ export { ORPCError as c, COMMON_ERROR_STATUS_MAP as j };
167
+ export type { AnyORPCError as A, ClientContext as C, FriendlyClientOptions as F, InferClientContext as I, NestedClient as N, ORPCErrorCode as O, ClientOptions as a, ClientLink as b, ORPCErrorJSON as d, AnyNestedClient as e, InferClientError as f, Client as g, ClientRest as h, AnyORPCErrorJSON as i, InferClientBodyInputs as k, InferClientBodyOutputs as l, InferClientErrors as m, InferClientInputs as n, InferClientOutputs as o, ORPCErrorOptions as p };
@@ -0,0 +1,167 @@
1
+ import { PromiseWithError, Registry, MaybeOptionalOptions } from '@orpc/shared';
2
+
3
+ interface ClientContext {
4
+ [key: PropertyKey]: any;
5
+ }
6
+ interface ClientOptions<T extends ClientContext> {
7
+ signal?: AbortSignal | undefined;
8
+ lastEventId?: string | undefined;
9
+ context: T;
10
+ }
11
+ type FriendlyClientOptions<T extends ClientContext> = Omit<ClientOptions<T>, 'context'> & (object extends T ? {
12
+ context?: T;
13
+ } : {
14
+ context: T;
15
+ });
16
+ type ClientRest<TClientContext extends ClientContext, TInput> = object extends TClientContext ? undefined extends TInput ? [input?: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options: FriendlyClientOptions<TClientContext>];
17
+ interface Client<TClientContext extends ClientContext, TInput, TOutput, TError> {
18
+ (...rest: ClientRest<TClientContext, TInput>): PromiseWithError<TOutput, TError>;
19
+ }
20
+ type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | {
21
+ [k: string]: NestedClient<TClientContext>;
22
+ };
23
+ type AnyNestedClient = NestedClient<any>;
24
+ type InferClientContext<T extends AnyNestedClient> = T extends NestedClient<infer U> ? U : never;
25
+ interface ClientLink<TClientContext extends ClientContext> {
26
+ call: (path: string[], input: unknown, options: ClientOptions<TClientContext>) => Promise<unknown>;
27
+ }
28
+ /**
29
+ * Recursively infers the **input types** from a client.
30
+ *
31
+ * Produces a nested map where each endpoint's input type is preserved.
32
+ */
33
+ type InferClientInputs<T extends AnyNestedClient> = T extends Client<any, infer U, any, any> ? U : {
34
+ [K in keyof T]: T[K] extends AnyNestedClient ? InferClientInputs<T[K]> : never;
35
+ };
36
+ /**
37
+ * Recursively infers the **body input types** from a client.
38
+ *
39
+ * If an endpoint's input includes `{ body: ... }`, only the `body` portion is extracted.
40
+ * Produces a nested map of body input types.
41
+ */
42
+ type InferClientBodyInputs<T extends AnyNestedClient> = T extends Client<any, infer U, any, any> ? U extends {
43
+ body: infer UBody;
44
+ } ? UBody : U : {
45
+ [K in keyof T]: T[K] extends AnyNestedClient ? InferClientBodyInputs<T[K]> : never;
46
+ };
47
+ /**
48
+ * Recursively infers the **output types** from a client.
49
+ *
50
+ * Produces a nested map where each endpoint's output type is preserved.
51
+ */
52
+ type InferClientOutputs<T extends AnyNestedClient> = T extends Client<any, any, infer U, any> ? U : {
53
+ [K in keyof T]: T[K] extends AnyNestedClient ? InferClientOutputs<T[K]> : never;
54
+ };
55
+ /**
56
+ * Recursively infers the **body output types** from a client.
57
+ *
58
+ * If an endpoint's output includes `{ body: ... }`, only the `body` portion is extracted.
59
+ * Produces a nested map of body output types.
60
+ */
61
+ type InferClientBodyOutputs<T extends AnyNestedClient> = T extends Client<any, any, infer U, any> ? U extends {
62
+ body: infer UBody;
63
+ } ? UBody : U : {
64
+ [K in keyof T]: T[K] extends AnyNestedClient ? InferClientBodyOutputs<T[K]> : never;
65
+ };
66
+ /**
67
+ * Recursively infers the **error types** from a client when you use [type-safe errors](https://orpc.dev/docs/error-handling#type‐safe-error-handling).
68
+ *
69
+ * Produces a nested map where each endpoint's error type is preserved.
70
+ */
71
+ type InferClientErrors<T extends AnyNestedClient> = T extends Client<any, any, any, infer U> ? U : {
72
+ [K in keyof T]: T[K] extends AnyNestedClient ? InferClientErrors<T[K]> : never;
73
+ };
74
+ /**
75
+ * Recursively infers a **union of all error types** from a client when you use [type-safe errors](https://orpc.dev/docs/error-handling#type‐safe-error-handling).
76
+ *
77
+ * Useful when you want to handle all possible errors from any endpoint at once.
78
+ */
79
+ type InferClientError<T extends AnyNestedClient> = T extends Client<any, any, any, infer U> ? U : {
80
+ [K in keyof T]: T[K] extends AnyNestedClient ? InferClientError<T[K]> : never;
81
+ }[keyof T];
82
+
83
+ declare const COMMON_ERROR_STATUS_MAP: {
84
+ BAD_REQUEST: number;
85
+ UNAUTHORIZED: number;
86
+ PAYMENT_REQUIRED: number;
87
+ FORBIDDEN: number;
88
+ NOT_FOUND: number;
89
+ METHOD_NOT_SUPPORTED: number;
90
+ NOT_ACCEPTABLE: number;
91
+ TIMEOUT: number;
92
+ CONFLICT: number;
93
+ GONE: number;
94
+ PRECONDITION_FAILED: number;
95
+ PAYLOAD_TOO_LARGE: number;
96
+ UNSUPPORTED_MEDIA_TYPE: number;
97
+ UNPROCESSABLE_CONTENT: number;
98
+ PRECONDITION_REQUIRED: number;
99
+ TOO_MANY_REQUESTS: number;
100
+ CLIENT_CLOSED_REQUEST: number;
101
+ INTERNAL_SERVER_ERROR: number;
102
+ NOT_IMPLEMENTED: number;
103
+ BAD_GATEWAY: number;
104
+ SERVICE_UNAVAILABLE: number;
105
+ GATEWAY_TIMEOUT: number;
106
+ };
107
+ type ORPCErrorCode = Registry extends {
108
+ ORPCErrorCode: infer T extends string;
109
+ } ? T : (keyof typeof COMMON_ERROR_STATUS_MAP) | (string & {});
110
+ type ORPCErrorOptions<TData> = ErrorOptions & {
111
+ message?: string;
112
+ } & (undefined extends TData ? {
113
+ data?: TData;
114
+ } : {
115
+ data: TData;
116
+ });
117
+ declare class ORPCError<TCode extends ORPCErrorCode, TData> extends Error {
118
+ /**
119
+ * @info
120
+ * The `__branch` property is used for type branding, helping TypeScript distinguish
121
+ * an `ORPCError` instance from plain objects with a similar structure.
122
+ */
123
+ readonly name: "ORPCError" & {
124
+ __branch: "ORPCError";
125
+ };
126
+ /**
127
+ * Indicates whether the error matches a definition in the procedure's `.errors` map.
128
+ */
129
+ readonly defined: boolean;
130
+ /**
131
+ * Indicates whether the error's type is inferable at the TypeScript level.
132
+ * This is typically true when the error is explicitly defined or returned within a handler.
133
+ */
134
+ readonly inferable: boolean;
135
+ code: TCode;
136
+ data: TData;
137
+ constructor(code: TCode, ...rest: MaybeOptionalOptions<ORPCErrorOptions<TData>>);
138
+ toJSON(): ORPCErrorJSON<TCode, TData>;
139
+ /**
140
+ * Workaround for Next.js where different contexts use separate
141
+ * dependency graphs, causing multiple ORPCError constructors existing and breaking
142
+ * `instanceof` checks across contexts.
143
+ *
144
+ * This is particularly problematic with "Optimized SSR", where orpc-client
145
+ * executes in one context but is invoked from another. When an error is thrown
146
+ * in the execution context, `instanceof ORPCError` checks fail in the
147
+ * invocation context due to separate class constructors.
148
+ *
149
+ * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
150
+ */
151
+ static [Symbol.hasInstance](instance: unknown): boolean;
152
+ }
153
+ interface ORPCErrorJSON<TCode extends string, TData> extends Pick<ORPCError<TCode, TData>, 'code' | 'message' | 'data'> {
154
+ /**
155
+ * remove readonly
156
+ */
157
+ defined: boolean;
158
+ /**
159
+ * remove readonly
160
+ */
161
+ inferable: boolean;
162
+ }
163
+ type AnyORPCError = ORPCError<any, any>;
164
+ type AnyORPCErrorJSON = ORPCErrorJSON<any, any>;
165
+
166
+ export { ORPCError as c, COMMON_ERROR_STATUS_MAP as j };
167
+ export type { AnyORPCError as A, ClientContext as C, FriendlyClientOptions as F, InferClientContext as I, NestedClient as N, ORPCErrorCode as O, ClientOptions as a, ClientLink as b, ORPCErrorJSON as d, AnyNestedClient as e, InferClientError as f, Client as g, ClientRest as h, AnyORPCErrorJSON as i, InferClientBodyInputs as k, InferClientBodyOutputs as l, InferClientErrors as m, InferClientInputs as n, InferClientOutputs as o, ORPCErrorOptions as p };
@@ -0,0 +1,174 @@
1
+ import { sortPlugins, runWithSpan, ORPC_NAME, isAsyncIteratorObject, override, traceAsyncIterator, intercept, getOpenTelemetryConfig, value, pathToHttpPath, stringifyJSON } from '@orpc/shared';
2
+ import { mergeStandardHeaders, parseStandardUrl } from '@standardserver/core';
3
+ import { toStandardHeaders } from '@standardserver/fetch';
4
+ import { O as ORPCError } from './client.Dnfj8jnT.mjs';
5
+ import { R as RPCSerializer, i as isORPCErrorJson, c as createORPCErrorFromJson } from './client.D3TIIok6.mjs';
6
+
7
+ class CompositeStandardLinkPlugin {
8
+ name = "~composite";
9
+ plugins;
10
+ constructor(plugins = []) {
11
+ this.plugins = sortPlugins(plugins);
12
+ }
13
+ init(options) {
14
+ for (const plugin of this.plugins) {
15
+ if (plugin.init) {
16
+ options = plugin.init(options);
17
+ }
18
+ }
19
+ return options;
20
+ }
21
+ }
22
+
23
+ class StandardLink {
24
+ constructor(codec, transport, options = {}) {
25
+ this.codec = codec;
26
+ this.transport = transport;
27
+ options = new CompositeStandardLinkPlugin(options.plugins).init(options);
28
+ this.interceptors = options.interceptors;
29
+ this.transportInterceptors = options.transportInterceptors;
30
+ }
31
+ interceptors;
32
+ transportInterceptors;
33
+ /**
34
+ * @throws ORPCError, transport-level errors (network failures, timeouts, etc.)
35
+ */
36
+ call(path, input, options) {
37
+ return runWithSpan(`${ORPC_NAME}.${path.join("/")}`, (span) => {
38
+ span?.setAttribute("rpc.system", ORPC_NAME);
39
+ span?.setAttribute("rpc.method", path.join("."));
40
+ if (isAsyncIteratorObject(input)) {
41
+ input = override(input, traceAsyncIterator("consume_event_iterator_input", input));
42
+ }
43
+ return intercept(this.interceptors, { ...options, path, input }, async ({ path: path2, input: input2, ...options2 }) => {
44
+ const otel = getOpenTelemetryConfig();
45
+ let activeContext;
46
+ const activeSpan = otel?.trace.getActiveSpan() ?? span;
47
+ if (activeSpan && otel) {
48
+ activeContext = otel.trace.setSpan(otel.context.active(), activeSpan);
49
+ }
50
+ let request = await runWithSpan(
51
+ { name: "encode_input", context: activeContext },
52
+ () => this.codec.encodeInput(input2, path2, options2)
53
+ );
54
+ if (activeContext && otel?.propagation) {
55
+ const headers = { ...request.headers };
56
+ otel.propagation.inject(activeContext, headers);
57
+ request = { ...request, headers };
58
+ }
59
+ const response = await intercept(
60
+ this.transportInterceptors,
61
+ { ...options2, path: path2, request },
62
+ ({ path: path3, request: request2, ...options3 }) => {
63
+ let activeTransportContext;
64
+ const activeTransportSpan = otel?.trace.getActiveSpan() ?? activeSpan;
65
+ if (activeTransportSpan && otel) {
66
+ activeTransportContext = otel.trace.setSpan(otel.context.active(), activeTransportSpan);
67
+ }
68
+ return runWithSpan(
69
+ { name: "send_request", context: activeTransportContext },
70
+ () => this.transport.send(request2, path3, options3)
71
+ );
72
+ }
73
+ );
74
+ const decodedResult = await runWithSpan(
75
+ { name: "decode_response", context: activeContext },
76
+ () => this.codec.decodeResponse(response, path2, options2)
77
+ );
78
+ if (decodedResult.kind === "error") {
79
+ throw decodedResult.error;
80
+ }
81
+ const output = decodedResult.output;
82
+ if (isAsyncIteratorObject(output)) {
83
+ return override(output, traceAsyncIterator("consume_event_iterator_output", output));
84
+ }
85
+ return output;
86
+ });
87
+ });
88
+ }
89
+ }
90
+
91
+ const END_SLASH_REGEX = /\/$/;
92
+ class RPCLinkCodec {
93
+ baseUrl;
94
+ maxUrlLength;
95
+ fallbackMethod;
96
+ expectedMethod;
97
+ headers;
98
+ serializer;
99
+ constructor(options) {
100
+ this.baseUrl = options.url ?? "/";
101
+ this.maxUrlLength = options.maxUrlLength ?? 2083;
102
+ this.fallbackMethod = options.fallbackMethod ?? "POST";
103
+ this.expectedMethod = options.method ?? this.fallbackMethod;
104
+ this.headers = options.headers ?? {};
105
+ this.serializer = options.serializer ?? new RPCSerializer();
106
+ }
107
+ async encodeInput(input, path, options) {
108
+ let headers = toResolvedStandardHeaders(await value(this.headers, options, path, input));
109
+ if (options.lastEventId !== void 0) {
110
+ headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
111
+ }
112
+ const expectedMethod = await value(this.expectedMethod, options, path, input);
113
+ const baseUrl = await value(this.baseUrl, options, path, input);
114
+ const [pathname, search, hash] = parseStandardUrl(baseUrl);
115
+ const newPathname = `${pathname.replace(END_SLASH_REGEX, "")}${pathToHttpPath(path)}`;
116
+ const serialized = this.serializer.serialize(input);
117
+ if (expectedMethod === "GET" && !(serialized instanceof Blob) && !(serialized instanceof ReadableStream) && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
118
+ const maxUrlLength = await value(this.maxUrlLength, options, path, input);
119
+ const mergedSearch = new URLSearchParams(search);
120
+ mergedSearch.append("data", stringifyJSON(serialized) ?? "");
121
+ const url2 = `${newPathname}?${mergedSearch}${hash ?? ""}`;
122
+ if (url2.length <= maxUrlLength) {
123
+ return {
124
+ body: void 0,
125
+ method: expectedMethod,
126
+ headers,
127
+ url: url2,
128
+ signal: options.signal
129
+ };
130
+ }
131
+ }
132
+ const url = `${newPathname}${search ?? ""}${hash ?? ""}`;
133
+ return {
134
+ url,
135
+ method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
136
+ headers,
137
+ body: serialized,
138
+ signal: options.signal
139
+ };
140
+ }
141
+ async decodeResponse(response) {
142
+ const isOk = response.status >= 200 && response.status < 400;
143
+ const body = await response.resolveBody();
144
+ const deserialized = await (async () => {
145
+ try {
146
+ return this.serializer.deserialize(body);
147
+ } catch (cause) {
148
+ throw new Error("Invalid RPC response format.", {
149
+ cause
150
+ });
151
+ }
152
+ })();
153
+ if (!isOk) {
154
+ if (isORPCErrorJson(deserialized)) {
155
+ return { kind: "error", error: createORPCErrorFromJson(deserialized) };
156
+ }
157
+ return {
158
+ kind: "error",
159
+ error: new ORPCError("MALFORMED_ORPC_ERROR_RESPONSE", {
160
+ data: { headers: response.headers, status: response.status, body: deserialized }
161
+ })
162
+ };
163
+ }
164
+ return { kind: "output", output: deserialized };
165
+ }
166
+ }
167
+ function toResolvedStandardHeaders(headers) {
168
+ if (typeof headers.forEach === "function") {
169
+ return toStandardHeaders(headers);
170
+ }
171
+ return headers;
172
+ }
173
+
174
+ export { CompositeStandardLinkPlugin as C, RPCLinkCodec as R, StandardLink as S };
@@ -0,0 +1,111 @@
1
+ import { StandardBody } from '@standardserver/core';
2
+ import { Segment } from '@orpc/shared';
3
+
4
+ type RPCJsonSerializationMeta = [type: string, ...path: Segment[]];
5
+ type RPCJsonSerialization = {
6
+ json: unknown;
7
+ meta?: RPCJsonSerializationMeta[] | undefined;
8
+ maps?: undefined;
9
+ blobs?: undefined;
10
+ } | {
11
+ json: unknown;
12
+ meta?: RPCJsonSerializationMeta[] | undefined;
13
+ maps: Segment[][];
14
+ blobs: Blob[];
15
+ };
16
+ interface RPCJsonSerializerHandler {
17
+ condition(value: unknown): boolean;
18
+ serialize(value: any): unknown;
19
+ deserialize(serialized: any): unknown;
20
+ /**
21
+ * If false, the result of this serializer will not be further processed by other serializers,
22
+ * even if it matches their conditions and treat it as final serialized value.
23
+ * This can be useful for serializers that return primitive values, which should not be further processed.
24
+ * to improve performance and avoid potential issues with other serializers.
25
+ *
26
+ * @default false
27
+ */
28
+ isTerminal?: boolean;
29
+ }
30
+ interface RPCJsonSerializerOptions {
31
+ /**
32
+ * Extend or override the built-in type handlers used during serialization and deserialization.
33
+ *
34
+ * Each key is a unique type identifier (e.g. `"date"`, `"bigint"`) and maps to a handler
35
+ * that defines how to detect, serialize, and deserialize values of that type.
36
+ *
37
+ * **Extending:** Add new keys to support custom types:
38
+ * ```ts
39
+ * handlers: {
40
+ * buffer: {
41
+ * condition: (v) => v instanceof Buffer,
42
+ * serialize: (v: Buffer) => v.toString('base64'),
43
+ * deserialize: (s: string) => Buffer.from(s, 'base64'),
44
+ * isTerminal: true,
45
+ * }
46
+ * }
47
+ * ```
48
+ *
49
+ * **Overriding:** Use an existing key to replace a built-in handler:
50
+ * ```ts
51
+ * handlers: {
52
+ * date: {
53
+ * condition: (v) => v instanceof Date,
54
+ * serialize: (v: Date) => v.getTime(),
55
+ * deserialize: (n: number) => new Date(n),
56
+ * isTerminal: true,
57
+ * }
58
+ * }
59
+ * ```
60
+ *
61
+ * **Disabling:** Set a key to `undefined` to remove a built-in handler:
62
+ * ```ts
63
+ * handlers: { regexp: undefined }
64
+ * ```
65
+ *
66
+ * Built-in type keys: `undefined`, `bigint`, `date`, `nan`, `url`, `regexp`, `set`, `map`.
67
+ */
68
+ handlers?: Record<string, undefined | RPCJsonSerializerHandler> | undefined;
69
+ /**
70
+ * If true, properties with undefined values will be omitted during serialization.
71
+ *
72
+ * @default true
73
+ */
74
+ omitUndefinedProperties?: boolean | undefined;
75
+ }
76
+ declare class RPCJsonSerializer {
77
+ private readonly handlers;
78
+ private readonly omitUndefinedProperties;
79
+ constructor(options?: RPCJsonSerializerOptions);
80
+ serialize(data: unknown): RPCJsonSerialization;
81
+ private serializeValue;
82
+ deserialize(serialized: RPCJsonSerialization): unknown;
83
+ }
84
+
85
+ interface RPCSerializerSerializeOptions {
86
+ /**
87
+ * Use FormData for serialization when nested blobs are present.
88
+ * Does not apply to root-level Blob values.
89
+ *
90
+ * @default true
91
+ */
92
+ useFormDataForBlobFields?: boolean;
93
+ }
94
+ interface RPCSerializerOptions extends RPCJsonSerializerOptions {
95
+ /**
96
+ * Default options for serialize method
97
+ */
98
+ serialize?: RPCSerializerSerializeOptions | undefined;
99
+ }
100
+ declare class RPCSerializer {
101
+ private readonly jsonSerializer;
102
+ private readonly defaultSerializeOptions;
103
+ constructor(options?: RPCSerializerOptions);
104
+ serialize(data: unknown, options?: RPCSerializerSerializeOptions): StandardBody;
105
+ private serializeValue;
106
+ deserialize(data: StandardBody): unknown;
107
+ private deserializeValue;
108
+ }
109
+
110
+ export { RPCJsonSerializer as b, RPCSerializer as e };
111
+ export type { RPCJsonSerialization as R, RPCJsonSerializationMeta as a, RPCJsonSerializerHandler as c, RPCJsonSerializerOptions as d, RPCSerializerOptions as f, RPCSerializerSerializeOptions as g };