@orpc/client 0.0.0-next.f22c7ec → 0.0.0-next.f397ca2

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 +101 -0
  2. package/dist/adapters/fetch/index.d.mts +46 -0
  3. package/dist/adapters/fetch/index.d.ts +46 -0
  4. package/dist/adapters/fetch/index.mjs +46 -0
  5. package/dist/adapters/message-port/index.d.mts +80 -0
  6. package/dist/adapters/message-port/index.d.ts +80 -0
  7. package/dist/adapters/message-port/index.mjs +87 -0
  8. package/dist/adapters/standard/index.d.mts +11 -0
  9. package/dist/adapters/standard/index.d.ts +11 -0
  10. package/dist/adapters/standard/index.mjs +6 -0
  11. package/dist/adapters/websocket/index.d.mts +29 -0
  12. package/dist/adapters/websocket/index.d.ts +29 -0
  13. package/dist/adapters/websocket/index.mjs +47 -0
  14. package/dist/index.d.mts +230 -0
  15. package/dist/index.d.ts +230 -0
  16. package/dist/index.mjs +112 -0
  17. package/dist/plugins/index.d.mts +249 -0
  18. package/dist/plugins/index.d.ts +249 -0
  19. package/dist/plugins/index.mjs +485 -0
  20. package/dist/shared/client.B7wn9u6X.mjs +398 -0
  21. package/dist/shared/client.BH1AYT_p.d.mts +83 -0
  22. package/dist/shared/client.BH1AYT_p.d.ts +83 -0
  23. package/dist/shared/client.BLtwTQUg.mjs +40 -0
  24. package/dist/shared/client.BxV-mzeR.d.ts +91 -0
  25. package/dist/shared/client.CPgZaUox.d.mts +45 -0
  26. package/dist/shared/client.D8lMmWVC.d.mts +91 -0
  27. package/dist/shared/client.De8SW4Kw.d.ts +45 -0
  28. package/dist/shared/client.LHg4bnWP.mjs +171 -0
  29. package/package.json +32 -17
  30. package/dist/fetch.js +0 -89
  31. package/dist/index.js +0 -42
  32. package/dist/src/adapters/fetch/index.d.ts +0 -3
  33. package/dist/src/adapters/fetch/orpc-link.d.ts +0 -46
  34. package/dist/src/adapters/fetch/types.d.ts +0 -4
  35. package/dist/src/client.d.ts +0 -11
  36. package/dist/src/dynamic-link.d.ts +0 -13
  37. package/dist/src/index.d.ts +0 -6
  38. package/dist/src/types.d.ts +0 -5
@@ -0,0 +1,398 @@
1
+ import { toArray, runWithSpan, ORPC_NAME, isAsyncIteratorObject, asyncIteratorWithSpan, intercept, getGlobalOtelConfig, isObject, value, stringifyJSON } from '@orpc/shared';
2
+ import { mergeStandardHeaders, ErrorEvent } from '@orpc/standard-server';
3
+ import { C as COMMON_ORPC_ERROR_DEFS, d as isORPCErrorStatus, e as isORPCErrorJson, g as createORPCErrorFromJson, c as ORPCError, t as toORPCError } from './client.LHg4bnWP.mjs';
4
+ import { toStandardHeaders as toStandardHeaders$1 } from '@orpc/standard-server-fetch';
5
+ import { m as mapEventIterator } from './client.BLtwTQUg.mjs';
6
+
7
+ class CompositeStandardLinkPlugin {
8
+ plugins;
9
+ constructor(plugins = []) {
10
+ this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
11
+ }
12
+ init(options) {
13
+ for (const plugin of this.plugins) {
14
+ plugin.init?.(options);
15
+ }
16
+ }
17
+ }
18
+
19
+ class StandardLink {
20
+ constructor(codec, sender, options = {}) {
21
+ this.codec = codec;
22
+ this.sender = sender;
23
+ const plugin = new CompositeStandardLinkPlugin(options.plugins);
24
+ plugin.init(options);
25
+ this.interceptors = toArray(options.interceptors);
26
+ this.clientInterceptors = toArray(options.clientInterceptors);
27
+ }
28
+ interceptors;
29
+ clientInterceptors;
30
+ call(path, input, options) {
31
+ return runWithSpan(
32
+ { name: `${ORPC_NAME}.${path.join("/")}`, signal: options.signal },
33
+ (span) => {
34
+ span?.setAttribute("rpc.system", ORPC_NAME);
35
+ span?.setAttribute("rpc.method", path.join("."));
36
+ if (isAsyncIteratorObject(input)) {
37
+ input = asyncIteratorWithSpan(
38
+ { name: "consume_event_iterator_input", signal: options.signal },
39
+ input
40
+ );
41
+ }
42
+ return intercept(this.interceptors, { ...options, path, input }, async ({ path: path2, input: input2, ...options2 }) => {
43
+ const otelConfig = getGlobalOtelConfig();
44
+ let otelContext;
45
+ const currentSpan = otelConfig?.trace.getActiveSpan() ?? span;
46
+ if (currentSpan && otelConfig) {
47
+ otelContext = otelConfig?.trace.setSpan(otelConfig.context.active(), currentSpan);
48
+ }
49
+ const request = await runWithSpan(
50
+ { name: "encode_request", context: otelContext },
51
+ () => this.codec.encode(path2, input2, options2)
52
+ );
53
+ const response = await intercept(
54
+ this.clientInterceptors,
55
+ { ...options2, input: input2, path: path2, request },
56
+ ({ input: input3, path: path3, request: request2, ...options3 }) => {
57
+ return runWithSpan(
58
+ { name: "send_request", signal: options3.signal, context: otelContext },
59
+ () => this.sender.call(request2, options3, path3, input3)
60
+ );
61
+ }
62
+ );
63
+ const output = await runWithSpan(
64
+ { name: "decode_response", context: otelContext },
65
+ () => this.codec.decode(response, options2, path2, input2)
66
+ );
67
+ if (isAsyncIteratorObject(output)) {
68
+ return asyncIteratorWithSpan(
69
+ { name: "consume_event_iterator_output", signal: options2.signal },
70
+ output
71
+ );
72
+ }
73
+ return output;
74
+ });
75
+ }
76
+ );
77
+ }
78
+ }
79
+
80
+ const STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES = {
81
+ BIGINT: 0,
82
+ DATE: 1,
83
+ NAN: 2,
84
+ UNDEFINED: 3,
85
+ URL: 4,
86
+ REGEXP: 5,
87
+ SET: 6,
88
+ MAP: 7
89
+ };
90
+ class StandardRPCJsonSerializer {
91
+ customSerializers;
92
+ constructor(options = {}) {
93
+ this.customSerializers = options.customJsonSerializers ?? [];
94
+ if (this.customSerializers.length !== new Set(this.customSerializers.map((custom) => custom.type)).size) {
95
+ throw new Error("Custom serializer type must be unique.");
96
+ }
97
+ }
98
+ serialize(data, segments = [], meta = [], maps = [], blobs = []) {
99
+ for (const custom of this.customSerializers) {
100
+ if (custom.condition(data)) {
101
+ const result = this.serialize(custom.serialize(data), segments, meta, maps, blobs);
102
+ meta.push([custom.type, ...segments]);
103
+ return result;
104
+ }
105
+ }
106
+ if (data instanceof Blob) {
107
+ maps.push(segments);
108
+ blobs.push(data);
109
+ return [data, meta, maps, blobs];
110
+ }
111
+ if (typeof data === "bigint") {
112
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT, ...segments]);
113
+ return [data.toString(), meta, maps, blobs];
114
+ }
115
+ if (data instanceof Date) {
116
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE, ...segments]);
117
+ if (Number.isNaN(data.getTime())) {
118
+ return [null, meta, maps, blobs];
119
+ }
120
+ return [data.toISOString(), meta, maps, blobs];
121
+ }
122
+ if (Number.isNaN(data)) {
123
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN, ...segments]);
124
+ return [null, meta, maps, blobs];
125
+ }
126
+ if (data instanceof URL) {
127
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL, ...segments]);
128
+ return [data.toString(), meta, maps, blobs];
129
+ }
130
+ if (data instanceof RegExp) {
131
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP, ...segments]);
132
+ return [data.toString(), meta, maps, blobs];
133
+ }
134
+ if (data instanceof Set) {
135
+ const result = this.serialize(Array.from(data), segments, meta, maps, blobs);
136
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET, ...segments]);
137
+ return result;
138
+ }
139
+ if (data instanceof Map) {
140
+ const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);
141
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP, ...segments]);
142
+ return result;
143
+ }
144
+ if (Array.isArray(data)) {
145
+ const json = data.map((v, i) => {
146
+ if (v === void 0) {
147
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED, ...segments, i]);
148
+ return v;
149
+ }
150
+ return this.serialize(v, [...segments, i], meta, maps, blobs)[0];
151
+ });
152
+ return [json, meta, maps, blobs];
153
+ }
154
+ if (isObject(data)) {
155
+ const json = {};
156
+ for (const k in data) {
157
+ if (k === "toJSON" && typeof data[k] === "function") {
158
+ continue;
159
+ }
160
+ json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];
161
+ }
162
+ return [json, meta, maps, blobs];
163
+ }
164
+ return [data, meta, maps, blobs];
165
+ }
166
+ deserialize(json, meta, maps, getBlob) {
167
+ const ref = { data: json };
168
+ if (maps && getBlob) {
169
+ maps.forEach((segments, i) => {
170
+ let currentRef = ref;
171
+ let preSegment = "data";
172
+ segments.forEach((segment) => {
173
+ currentRef = currentRef[preSegment];
174
+ preSegment = segment;
175
+ });
176
+ currentRef[preSegment] = getBlob(i);
177
+ });
178
+ }
179
+ for (const item of meta) {
180
+ const type = item[0];
181
+ let currentRef = ref;
182
+ let preSegment = "data";
183
+ for (let i = 1; i < item.length; i++) {
184
+ currentRef = currentRef[preSegment];
185
+ preSegment = item[i];
186
+ }
187
+ for (const custom of this.customSerializers) {
188
+ if (custom.type === type) {
189
+ currentRef[preSegment] = custom.deserialize(currentRef[preSegment]);
190
+ break;
191
+ }
192
+ }
193
+ switch (type) {
194
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT:
195
+ currentRef[preSegment] = BigInt(currentRef[preSegment]);
196
+ break;
197
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE:
198
+ currentRef[preSegment] = new Date(currentRef[preSegment] ?? "Invalid Date");
199
+ break;
200
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN:
201
+ currentRef[preSegment] = Number.NaN;
202
+ break;
203
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED:
204
+ currentRef[preSegment] = void 0;
205
+ break;
206
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL:
207
+ currentRef[preSegment] = new URL(currentRef[preSegment]);
208
+ break;
209
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP: {
210
+ const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
211
+ currentRef[preSegment] = new RegExp(pattern, flags);
212
+ break;
213
+ }
214
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET:
215
+ currentRef[preSegment] = new Set(currentRef[preSegment]);
216
+ break;
217
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP:
218
+ currentRef[preSegment] = new Map(currentRef[preSegment]);
219
+ break;
220
+ }
221
+ }
222
+ return ref.data;
223
+ }
224
+ }
225
+
226
+ function toHttpPath(path) {
227
+ return `/${path.map(encodeURIComponent).join("/")}`;
228
+ }
229
+ function toStandardHeaders(headers) {
230
+ if (typeof headers.forEach === "function") {
231
+ return toStandardHeaders$1(headers);
232
+ }
233
+ return headers;
234
+ }
235
+ function getMalformedResponseErrorCode(status) {
236
+ return Object.entries(COMMON_ORPC_ERROR_DEFS).find(([, def]) => def.status === status)?.[0] ?? "MALFORMED_ORPC_ERROR_RESPONSE";
237
+ }
238
+
239
+ class StandardRPCLinkCodec {
240
+ constructor(serializer, options) {
241
+ this.serializer = serializer;
242
+ this.baseUrl = options.url;
243
+ this.maxUrlLength = options.maxUrlLength ?? 2083;
244
+ this.fallbackMethod = options.fallbackMethod ?? "POST";
245
+ this.expectedMethod = options.method ?? this.fallbackMethod;
246
+ this.headers = options.headers ?? {};
247
+ }
248
+ baseUrl;
249
+ maxUrlLength;
250
+ fallbackMethod;
251
+ expectedMethod;
252
+ headers;
253
+ async encode(path, input, options) {
254
+ let headers = toStandardHeaders(await value(this.headers, options, path, input));
255
+ if (options.lastEventId !== void 0) {
256
+ headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
257
+ }
258
+ const expectedMethod = await value(this.expectedMethod, options, path, input);
259
+ const baseUrl = await value(this.baseUrl, options, path, input);
260
+ const url = new URL(baseUrl);
261
+ url.pathname = `${url.pathname.replace(/\/$/, "")}${toHttpPath(path)}`;
262
+ const serialized = this.serializer.serialize(input);
263
+ if (expectedMethod === "GET" && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
264
+ const maxUrlLength = await value(this.maxUrlLength, options, path, input);
265
+ const getUrl = new URL(url);
266
+ getUrl.searchParams.append("data", stringifyJSON(serialized));
267
+ if (getUrl.toString().length <= maxUrlLength) {
268
+ return {
269
+ body: void 0,
270
+ method: expectedMethod,
271
+ headers,
272
+ url: getUrl,
273
+ signal: options.signal
274
+ };
275
+ }
276
+ }
277
+ return {
278
+ url,
279
+ method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
280
+ headers,
281
+ body: serialized,
282
+ signal: options.signal
283
+ };
284
+ }
285
+ async decode(response) {
286
+ const isOk = !isORPCErrorStatus(response.status);
287
+ const deserialized = await (async () => {
288
+ let isBodyOk = false;
289
+ try {
290
+ const body = await response.body();
291
+ isBodyOk = true;
292
+ return this.serializer.deserialize(body);
293
+ } catch (error) {
294
+ if (!isBodyOk) {
295
+ throw new Error("Cannot parse response body, please check the response body and content-type.", {
296
+ cause: error
297
+ });
298
+ }
299
+ throw new Error("Invalid RPC response format.", {
300
+ cause: error
301
+ });
302
+ }
303
+ })();
304
+ if (!isOk) {
305
+ if (isORPCErrorJson(deserialized)) {
306
+ throw createORPCErrorFromJson(deserialized);
307
+ }
308
+ throw new ORPCError(getMalformedResponseErrorCode(response.status), {
309
+ status: response.status,
310
+ data: { ...response, body: deserialized }
311
+ });
312
+ }
313
+ return deserialized;
314
+ }
315
+ }
316
+
317
+ class StandardRPCSerializer {
318
+ constructor(jsonSerializer) {
319
+ this.jsonSerializer = jsonSerializer;
320
+ }
321
+ serialize(data) {
322
+ if (isAsyncIteratorObject(data)) {
323
+ return mapEventIterator(data, {
324
+ value: async (value) => this.#serialize(value, false),
325
+ error: async (e) => {
326
+ return new ErrorEvent({
327
+ data: this.#serialize(toORPCError(e).toJSON(), false),
328
+ cause: e
329
+ });
330
+ }
331
+ });
332
+ }
333
+ return this.#serialize(data, true);
334
+ }
335
+ #serialize(data, enableFormData) {
336
+ const [json, meta_, maps, blobs] = this.jsonSerializer.serialize(data);
337
+ const meta = meta_.length === 0 ? void 0 : meta_;
338
+ if (!enableFormData || blobs.length === 0) {
339
+ return {
340
+ json,
341
+ meta
342
+ };
343
+ }
344
+ const form = new FormData();
345
+ form.set("data", stringifyJSON({ json, meta, maps }));
346
+ blobs.forEach((blob, i) => {
347
+ form.set(i.toString(), blob);
348
+ });
349
+ return form;
350
+ }
351
+ deserialize(data) {
352
+ if (isAsyncIteratorObject(data)) {
353
+ return mapEventIterator(data, {
354
+ value: async (value) => this.#deserialize(value),
355
+ error: async (e) => {
356
+ if (!(e instanceof ErrorEvent)) {
357
+ return e;
358
+ }
359
+ const deserialized = this.#deserialize(e.data);
360
+ if (isORPCErrorJson(deserialized)) {
361
+ return createORPCErrorFromJson(deserialized, { cause: e });
362
+ }
363
+ return new ErrorEvent({
364
+ data: deserialized,
365
+ cause: e
366
+ });
367
+ }
368
+ });
369
+ }
370
+ return this.#deserialize(data);
371
+ }
372
+ #deserialize(data) {
373
+ if (data === void 0) {
374
+ return void 0;
375
+ }
376
+ if (!(data instanceof FormData)) {
377
+ return this.jsonSerializer.deserialize(data.json, data.meta ?? []);
378
+ }
379
+ const serialized = JSON.parse(data.get("data"));
380
+ return this.jsonSerializer.deserialize(
381
+ serialized.json,
382
+ serialized.meta ?? [],
383
+ serialized.maps,
384
+ (i) => data.get(i.toString())
385
+ );
386
+ }
387
+ }
388
+
389
+ class StandardRPCLink extends StandardLink {
390
+ constructor(linkClient, options) {
391
+ const jsonSerializer = new StandardRPCJsonSerializer(options);
392
+ const serializer = new StandardRPCSerializer(jsonSerializer);
393
+ const linkCodec = new StandardRPCLinkCodec(serializer, options);
394
+ super(linkCodec, linkClient, options);
395
+ }
396
+ }
397
+
398
+ export { CompositeStandardLinkPlugin as C, StandardLink as S, STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES as a, StandardRPCJsonSerializer as b, StandardRPCLink as c, StandardRPCLinkCodec as d, StandardRPCSerializer as e, toStandardHeaders as f, getMalformedResponseErrorCode as g, toHttpPath as t };
@@ -0,0 +1,83 @@
1
+ import { PromiseWithError } from '@orpc/shared';
2
+
3
+ type HTTPPath = `/${string}`;
4
+ type HTTPMethod = 'HEAD' | 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
5
+ type ClientContext = Record<PropertyKey, any>;
6
+ interface ClientOptions<T extends ClientContext> {
7
+ signal?: AbortSignal;
8
+ lastEventId?: string | undefined;
9
+ context: T;
10
+ }
11
+ type FriendlyClientOptions<T extends ClientContext> = Omit<ClientOptions<T>, 'context'> & (Record<never, never> extends T ? {
12
+ context?: T;
13
+ } : {
14
+ context: T;
15
+ });
16
+ type ClientRest<TClientContext extends ClientContext, TInput> = Record<never, never> extends TClientContext ? undefined extends TInput ? [input?: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options: FriendlyClientOptions<TClientContext>];
17
+ type ClientPromiseResult<TOutput, TError> = PromiseWithError<TOutput, TError>;
18
+ interface Client<TClientContext extends ClientContext, TInput, TOutput, TError> {
19
+ (...rest: ClientRest<TClientContext, TInput>): ClientPromiseResult<TOutput, TError>;
20
+ }
21
+ type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | {
22
+ [k: string]: NestedClient<TClientContext>;
23
+ };
24
+ type InferClientContext<T extends NestedClient<any>> = T extends NestedClient<infer U> ? U : never;
25
+ interface ClientLink<TClientContext extends ClientContext> {
26
+ call: (path: readonly 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 NestedClient<any>> = T extends Client<any, infer U, any, any> ? U : {
34
+ [K in keyof T]: T[K] extends NestedClient<any> ? 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 NestedClient<any>> = 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 NestedClient<any> ? 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 NestedClient<any>> = T extends Client<any, any, infer U, any> ? U : {
53
+ [K in keyof T]: T[K] extends NestedClient<any> ? 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 NestedClient<any>> = 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 NestedClient<any> ? InferClientBodyOutputs<T[K]> : never;
65
+ };
66
+ /**
67
+ * Recursively infers the **error types** from a client when you use [type-safe errors](https://orpc.unnoq.com/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 NestedClient<any>> = T extends Client<any, any, any, infer U> ? U : {
72
+ [K in keyof T]: T[K] extends NestedClient<any> ? 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.unnoq.com/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 InferClientErrorUnion<T extends NestedClient<any>> = T extends Client<any, any, any, infer U> ? U : {
80
+ [K in keyof T]: T[K] extends NestedClient<any> ? InferClientErrorUnion<T[K]> : never;
81
+ }[keyof T];
82
+
83
+ export type { ClientLink as C, FriendlyClientOptions as F, HTTPPath as H, InferClientContext as I, NestedClient as N, ClientPromiseResult as a, ClientContext as b, ClientOptions as c, Client as d, ClientRest as e, HTTPMethod as f, InferClientInputs as g, InferClientBodyInputs as h, InferClientOutputs as i, InferClientBodyOutputs as j, InferClientErrors as k, InferClientErrorUnion as l };
@@ -0,0 +1,83 @@
1
+ import { PromiseWithError } from '@orpc/shared';
2
+
3
+ type HTTPPath = `/${string}`;
4
+ type HTTPMethod = 'HEAD' | 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
5
+ type ClientContext = Record<PropertyKey, any>;
6
+ interface ClientOptions<T extends ClientContext> {
7
+ signal?: AbortSignal;
8
+ lastEventId?: string | undefined;
9
+ context: T;
10
+ }
11
+ type FriendlyClientOptions<T extends ClientContext> = Omit<ClientOptions<T>, 'context'> & (Record<never, never> extends T ? {
12
+ context?: T;
13
+ } : {
14
+ context: T;
15
+ });
16
+ type ClientRest<TClientContext extends ClientContext, TInput> = Record<never, never> extends TClientContext ? undefined extends TInput ? [input?: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options: FriendlyClientOptions<TClientContext>];
17
+ type ClientPromiseResult<TOutput, TError> = PromiseWithError<TOutput, TError>;
18
+ interface Client<TClientContext extends ClientContext, TInput, TOutput, TError> {
19
+ (...rest: ClientRest<TClientContext, TInput>): ClientPromiseResult<TOutput, TError>;
20
+ }
21
+ type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | {
22
+ [k: string]: NestedClient<TClientContext>;
23
+ };
24
+ type InferClientContext<T extends NestedClient<any>> = T extends NestedClient<infer U> ? U : never;
25
+ interface ClientLink<TClientContext extends ClientContext> {
26
+ call: (path: readonly 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 NestedClient<any>> = T extends Client<any, infer U, any, any> ? U : {
34
+ [K in keyof T]: T[K] extends NestedClient<any> ? 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 NestedClient<any>> = 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 NestedClient<any> ? 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 NestedClient<any>> = T extends Client<any, any, infer U, any> ? U : {
53
+ [K in keyof T]: T[K] extends NestedClient<any> ? 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 NestedClient<any>> = 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 NestedClient<any> ? InferClientBodyOutputs<T[K]> : never;
65
+ };
66
+ /**
67
+ * Recursively infers the **error types** from a client when you use [type-safe errors](https://orpc.unnoq.com/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 NestedClient<any>> = T extends Client<any, any, any, infer U> ? U : {
72
+ [K in keyof T]: T[K] extends NestedClient<any> ? 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.unnoq.com/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 InferClientErrorUnion<T extends NestedClient<any>> = T extends Client<any, any, any, infer U> ? U : {
80
+ [K in keyof T]: T[K] extends NestedClient<any> ? InferClientErrorUnion<T[K]> : never;
81
+ }[keyof T];
82
+
83
+ export type { ClientLink as C, FriendlyClientOptions as F, HTTPPath as H, InferClientContext as I, NestedClient as N, ClientPromiseResult as a, ClientContext as b, ClientOptions as c, Client as d, ClientRest as e, HTTPMethod as f, InferClientInputs as g, InferClientBodyInputs as h, InferClientOutputs as i, InferClientBodyOutputs as j, InferClientErrors as k, InferClientErrorUnion as l };
@@ -0,0 +1,40 @@
1
+ import { AsyncIteratorClass, isTypescriptObject } from '@orpc/shared';
2
+ import { getEventMeta, withEventMeta } from '@orpc/standard-server';
3
+
4
+ function mapEventIterator(iterator, maps) {
5
+ const mapError = async (error) => {
6
+ let mappedError = await maps.error(error);
7
+ if (mappedError !== error) {
8
+ const meta = getEventMeta(error);
9
+ if (meta && isTypescriptObject(mappedError)) {
10
+ mappedError = withEventMeta(mappedError, meta);
11
+ }
12
+ }
13
+ return mappedError;
14
+ };
15
+ return new AsyncIteratorClass(async () => {
16
+ const { done, value } = await (async () => {
17
+ try {
18
+ return await iterator.next();
19
+ } catch (error) {
20
+ throw await mapError(error);
21
+ }
22
+ })();
23
+ let mappedValue = await maps.value(value, done);
24
+ if (mappedValue !== value) {
25
+ const meta = getEventMeta(value);
26
+ if (meta && isTypescriptObject(mappedValue)) {
27
+ mappedValue = withEventMeta(mappedValue, meta);
28
+ }
29
+ }
30
+ return { done, value: mappedValue };
31
+ }, async () => {
32
+ try {
33
+ await iterator.return?.();
34
+ } catch (error) {
35
+ throw await mapError(error);
36
+ }
37
+ });
38
+ }
39
+
40
+ export { mapEventIterator as m };