@orpc/client 2.0.0-beta.47 → 2.0.0-beta.48

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 (91) hide show
  1. package/README.md +2 -3
  2. package/dist/adapters/fetch/index.d.mts +2 -48
  3. package/dist/adapters/fetch/index.mjs +2 -77
  4. package/dist/adapters/fetch/rpc-link.d.mts +13 -0
  5. package/dist/adapters/fetch/rpc-link.mjs +10 -0
  6. package/dist/adapters/fetch/transport.d.mts +31 -0
  7. package/dist/adapters/fetch/transport.mjs +65 -0
  8. package/dist/adapters/message-port/index.d.mts +3 -80
  9. package/dist/adapters/message-port/index.mjs +3 -101
  10. package/dist/adapters/message-port/message-port.d.mts +29 -0
  11. package/dist/adapters/message-port/message-port.mjs +43 -0
  12. package/dist/adapters/message-port/rpc-link.d.mts +14 -0
  13. package/dist/adapters/message-port/rpc-link.mjs +10 -0
  14. package/dist/adapters/message-port/transport.d.mts +35 -0
  15. package/dist/adapters/message-port/transport.mjs +47 -0
  16. package/dist/adapters/standard/codec.d.mts +14 -0
  17. package/dist/adapters/standard/codec.mjs +1 -0
  18. package/dist/adapters/standard/index.d.mts +5 -60
  19. package/dist/adapters/standard/index.mjs +4 -6
  20. package/dist/adapters/standard/link.d.mts +40 -0
  21. package/dist/adapters/standard/link.mjs +79 -0
  22. package/dist/adapters/standard/plugin.d.mts +32 -0
  23. package/dist/adapters/standard/plugin.mjs +16 -0
  24. package/dist/adapters/standard/rpc-link-codec.d.mts +55 -0
  25. package/dist/adapters/standard/rpc-link-codec.mjs +104 -0
  26. package/dist/adapters/standard/transport.d.mts +14 -0
  27. package/dist/adapters/standard/transport.mjs +1 -0
  28. package/dist/adapters/websocket/index.d.mts +2 -136
  29. package/dist/adapters/websocket/index.mjs +2 -131
  30. package/dist/adapters/websocket/rpc-link.d.mts +13 -0
  31. package/dist/adapters/websocket/rpc-link.mjs +10 -0
  32. package/dist/adapters/websocket/transport.d.mts +119 -0
  33. package/dist/adapters/websocket/transport.mjs +123 -0
  34. package/dist/async-iterator-object.d.mts +7 -0
  35. package/dist/async-iterator-object.mjs +30 -0
  36. package/dist/client-safe.d.mts +16 -0
  37. package/dist/client-safe.mjs +23 -0
  38. package/dist/client.d.mts +51 -0
  39. package/dist/client.mjs +32 -0
  40. package/dist/consts.d.mts +10 -0
  41. package/dist/consts.mjs +10 -0
  42. package/dist/dynamic-link.d.mts +13 -0
  43. package/dist/dynamic-link.mjs +12 -0
  44. package/dist/error-utils.d.mts +24 -0
  45. package/dist/error-utils.mjs +44 -0
  46. package/dist/error.d.mts +138 -0
  47. package/dist/error.mjs +105 -0
  48. package/dist/index.d.mts +42 -137
  49. package/dist/index.mjs +18 -142
  50. package/dist/plugins/batch.d.mts +150 -0
  51. package/dist/plugins/batch.mjs +339 -0
  52. package/dist/plugins/cookie-jar.d.mts +82 -0
  53. package/dist/plugins/cookie-jar.mjs +229 -0
  54. package/dist/plugins/dedupe.d.mts +58 -0
  55. package/dist/plugins/dedupe.mjs +199 -0
  56. package/dist/plugins/index.d.mts +28 -420
  57. package/dist/plugins/index.mjs +17 -971
  58. package/dist/plugins/request-compression.d.mts +44 -0
  59. package/dist/plugins/request-compression.mjs +150 -0
  60. package/dist/plugins/response-compression.d.mts +28 -0
  61. package/dist/plugins/response-compression.mjs +78 -0
  62. package/dist/plugins/retry-after.d.mts +41 -0
  63. package/dist/plugins/retry-after.mjs +71 -0
  64. package/dist/plugins/retry.d.mts +82 -0
  65. package/dist/plugins/retry.mjs +127 -0
  66. package/dist/plugins/timeout.d.mts +25 -0
  67. package/dist/plugins/timeout.mjs +36 -0
  68. package/dist/rpc-json-serializer.d.mts +99 -0
  69. package/dist/rpc-json-serializer.mjs +365 -0
  70. package/dist/rpc-serializer.d.mts +32 -0
  71. package/dist/rpc-serializer.mjs +100 -0
  72. package/dist/types.d.mts +93 -0
  73. package/dist/types.mjs +1 -0
  74. package/dist/utils.d.mts +46 -0
  75. package/dist/utils.mjs +53 -0
  76. package/package.json +5 -5
  77. package/dist/adapters/fetch/index.d.ts +0 -48
  78. package/dist/adapters/message-port/index.d.ts +0 -80
  79. package/dist/adapters/standard/index.d.ts +0 -60
  80. package/dist/adapters/websocket/index.d.ts +0 -136
  81. package/dist/index.d.ts +0 -144
  82. package/dist/plugins/index.d.ts +0 -420
  83. package/dist/shared/client.BoHJeq15.d.mts +0 -233
  84. package/dist/shared/client.BoHJeq15.d.ts +0 -233
  85. package/dist/shared/client.CKQeJJ2U.mjs +0 -172
  86. package/dist/shared/client.DqIWeNhQ.d.mts +0 -131
  87. package/dist/shared/client.DqIWeNhQ.d.ts +0 -131
  88. package/dist/shared/client.JBJwBhR8.d.ts +0 -90
  89. package/dist/shared/client.LF04eOvL.mjs +0 -115
  90. package/dist/shared/client._wG5INmC.mjs +0 -505
  91. package/dist/shared/client.euYjjcFz.d.mts +0 -90
@@ -0,0 +1,99 @@
1
+ import type { Segment } from "@orpc/shared";
2
+ export type RPCJsonSerializationMeta = [type: string, ...path: Segment[]];
3
+ export type RPCJsonSerialization = {
4
+ json: unknown;
5
+ meta?: RPCJsonSerializationMeta[] | undefined;
6
+ maps?: undefined;
7
+ blobs?: undefined;
8
+ } | {
9
+ json: unknown;
10
+ meta?: RPCJsonSerializationMeta[] | undefined;
11
+ maps: Segment[][];
12
+ blobs: Blob[];
13
+ };
14
+ export interface RPCJsonSerializerHandler {
15
+ condition(value: unknown): boolean;
16
+ serialize(value: any): unknown;
17
+ /**
18
+ * `serialized` comes from the wire, so validate its type and throw on mismatch.
19
+ */
20
+ deserialize(serialized: unknown): unknown;
21
+ /**
22
+ * If false, the result of this serializer will not be further processed by other serializers,
23
+ * even if it matches their conditions and treat it as final serialized value.
24
+ * This can be useful for serializers that return primitive values, which should not be further processed.
25
+ * to improve performance and avoid potential issues with other serializers.
26
+ *
27
+ * @default false
28
+ */
29
+ isTerminal?: boolean | undefined;
30
+ }
31
+ export interface RPCJsonSerializerOptions {
32
+ /**
33
+ * Extend or override the built-in type handlers used during serialization and deserialization.
34
+ *
35
+ * Each key is a unique type identifier (e.g. `"date"`, `"bigint"`) and maps to a handler
36
+ * that defines how to detect, serialize, and deserialize values of that type.
37
+ *
38
+ * **Extending:** Add new keys to support custom types:
39
+ * ```ts
40
+ * handlers: {
41
+ * buffer: {
42
+ * condition: (v) => v instanceof Buffer,
43
+ * serialize: (v: Buffer) => v.toString('base64'),
44
+ * deserialize: (s: string) => Buffer.from(s, 'base64'),
45
+ * isTerminal: true,
46
+ * }
47
+ * }
48
+ * ```
49
+ *
50
+ * **Overriding:** Use an existing key to replace a built-in handler:
51
+ * ```ts
52
+ * handlers: {
53
+ * date: {
54
+ * condition: (v) => v instanceof Date,
55
+ * serialize: (v: Date) => v.getTime(),
56
+ * deserialize: (n: number) => new Date(n),
57
+ * isTerminal: true,
58
+ * }
59
+ * }
60
+ * ```
61
+ *
62
+ * **Disabling:** Set a key to `undefined` to remove a built-in handler:
63
+ * ```ts
64
+ * handlers: { url: undefined }
65
+ * ```
66
+ *
67
+ * During deserialization, values whose type has no handler are left in their serialized form,
68
+ * so a client and server with different handlers can still communicate.
69
+ *
70
+ * Built-in type keys: `undefined`, `bigint`, `date`, `nan`, `infinity`, `url`, `set`, `map`.
71
+ */
72
+ handlers?: Record<string, undefined | RPCJsonSerializerHandler> | undefined;
73
+ /**
74
+ * If true, properties with undefined values will be omitted during serialization.
75
+ *
76
+ * @default true
77
+ */
78
+ omitUndefinedProperties?: boolean | undefined;
79
+ }
80
+ /**
81
+ * Serializes and deserializes native types like Date, BigInt, Set, and Map
82
+ * into a JSON value plus separate metadata describing how to restore them.
83
+ *
84
+ * @see {@link https://orpc.dev/docs/rpc/serializer#rpc-json-serializer | RPC Serializer - RPC JSON Serializer}
85
+ */
86
+ export declare class RPCJsonSerializer {
87
+ private readonly handlers;
88
+ private readonly inlineBuiltInHandlers;
89
+ private readonly handlerEntries;
90
+ private readonly omitUndefinedProperties;
91
+ constructor(options?: RPCJsonSerializerOptions);
92
+ serializeJson(data: unknown): RPCJsonSerialization;
93
+ /**
94
+ * `segments` is a shared mutable stack (push/pop while walking),
95
+ * so it must be copied before being stored in `meta` or `maps`.
96
+ */
97
+ private serializeValue;
98
+ deserializeJson(serialized: RPCJsonSerialization): unknown;
99
+ }
@@ -0,0 +1,365 @@
1
+ import { copyOnWrite, DEFAULT_MAX_BIGINT_DIGITS, isPlainObject, NullProtoObj, parseBigIntString } from "@orpc/shared";
2
+ function invalidSerializedData(detail) {
3
+ return new TypeError(`Invalid RPC serialized data: ${detail}`);
4
+ }
5
+ function assertSerializedType(ok, type, expected) {
6
+ if (!ok) {
7
+ throw invalidSerializedData(`type "${type}" expects ${expected}.`);
8
+ }
9
+ }
10
+ function isWalkable(value) {
11
+ return Array.isArray(value) || isPlainObject(value);
12
+ }
13
+ function walkInto(parent, key, original, restored) {
14
+ const value = parent[key];
15
+ if (!isWalkable(value) || restored?.has(value)) {
16
+ throw invalidSerializedData(`segment "${key}" cannot be walked into.`);
17
+ }
18
+ return value === original ? copyOnWrite(parent, key, original) : value;
19
+ }
20
+ const DEFAULT_RPC_JSON_SERIALIZER_HANDLERS = {
21
+ undefined: {
22
+ condition(data) {
23
+ return data === undefined;
24
+ },
25
+ serialize() {
26
+ return null;
27
+ },
28
+ deserialize(serialized) {
29
+ assertSerializedType(serialized === null, "undefined", "null");
30
+ return undefined;
31
+ },
32
+ isTerminal: true
33
+ },
34
+ bigint: {
35
+ condition(data) {
36
+ return typeof data === "bigint";
37
+ },
38
+ serialize(data) {
39
+ return data.toString();
40
+ },
41
+ deserialize(serialized) {
42
+ assertSerializedType(typeof serialized === "string", "bigint", "a string");
43
+ const value = parseBigIntString(serialized, DEFAULT_MAX_BIGINT_DIGITS);
44
+ if (value === undefined) {
45
+ throw invalidSerializedData(`type "bigint" expects a decimal integer string of at most ${DEFAULT_MAX_BIGINT_DIGITS} digits.`);
46
+ }
47
+ return value;
48
+ },
49
+ isTerminal: true
50
+ },
51
+ date: {
52
+ condition(data) {
53
+ return data instanceof Date;
54
+ },
55
+ serialize(data) {
56
+ if (Number.isNaN(data.getTime())) {
57
+ return null;
58
+ }
59
+ return data.toISOString();
60
+ },
61
+ deserialize(serialized) {
62
+ assertSerializedType(typeof serialized === "string" || serialized === null, "date", "a string or null");
63
+ return new Date(serialized ?? Number.NaN);
64
+ },
65
+ isTerminal: true
66
+ },
67
+ nan: {
68
+ condition(data) {
69
+ return typeof data === "number" && Number.isNaN(data);
70
+ },
71
+ serialize() {
72
+ return null;
73
+ },
74
+ deserialize(serialized) {
75
+ assertSerializedType(serialized === null, "nan", "null");
76
+ return Number.NaN;
77
+ },
78
+ isTerminal: true
79
+ },
80
+ infinity: {
81
+ condition(data) {
82
+ return data === Number.POSITIVE_INFINITY || data === Number.NEGATIVE_INFINITY;
83
+ },
84
+ serialize(data) {
85
+ return data > 0 ? "Infinity" : "-Infinity";
86
+ },
87
+ deserialize(serialized) {
88
+ assertSerializedType(serialized === "Infinity" || serialized === "-Infinity", "infinity", "\"Infinity\" or \"-Infinity\"");
89
+ return serialized === "Infinity" ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
90
+ },
91
+ isTerminal: true
92
+ },
93
+ url: {
94
+ condition(data) {
95
+ return data instanceof URL;
96
+ },
97
+ serialize(data) {
98
+ return data.toString();
99
+ },
100
+ deserialize(serialized) {
101
+ assertSerializedType(typeof serialized === "string", "url", "a string");
102
+ return new URL(serialized);
103
+ },
104
+ isTerminal: true
105
+ },
106
+ set: {
107
+ condition(data) {
108
+ return data instanceof Set;
109
+ },
110
+ serialize(data) {
111
+ return Array.from(data);
112
+ },
113
+ deserialize(serialized) {
114
+ assertSerializedType(Array.isArray(serialized), "set", "an array");
115
+ return new Set(serialized);
116
+ }
117
+ },
118
+ map: {
119
+ condition(data) {
120
+ return data instanceof Map;
121
+ },
122
+ serialize(data) {
123
+ return Array.from(data.entries());
124
+ },
125
+ deserialize(serialized) {
126
+ assertSerializedType(Array.isArray(serialized), "map", "an array");
127
+ return new Map(serialized);
128
+ }
129
+ }
130
+ };
131
+
132
+ export class RPCJsonSerializer {
133
+ handlers;
134
+ inlineBuiltInHandlers;
135
+ handlerEntries;
136
+ omitUndefinedProperties;
137
+ constructor(options = {}) {
138
+ this.omitUndefinedProperties = options.omitUndefinedProperties !== false;
139
+ this.handlers = Object.assign(new NullProtoObj(), DEFAULT_RPC_JSON_SERIALIZER_HANDLERS);
140
+ const customHandlers = options.handlers;
141
+ if (customHandlers === undefined) {
142
+ this.inlineBuiltInHandlers = true;
143
+ return;
144
+ }
145
+ let inlineBuiltInHandlers = true;
146
+ let handlerEntries = [];
147
+ for (const key of Object.keys(customHandlers)) {
148
+ const handler = customHandlers[key];
149
+ this.handlers[key] = handler;
150
+ if (inlineBuiltInHandlers && key in DEFAULT_RPC_JSON_SERIALIZER_HANDLERS) {
151
+ inlineBuiltInHandlers = false;
152
+ }
153
+ if (inlineBuiltInHandlers && handler !== undefined) {
154
+ handlerEntries.push([key, handler]);
155
+ }
156
+ }
157
+ if (!inlineBuiltInHandlers) {
158
+ handlerEntries = [];
159
+ for (const key of Object.keys(this.handlers)) {
160
+ const handler = this.handlers[key];
161
+ if (handler !== undefined) {
162
+ handlerEntries.push([key, handler]);
163
+ }
164
+ }
165
+ }
166
+ this.inlineBuiltInHandlers = inlineBuiltInHandlers;
167
+ this.handlerEntries = handlerEntries;
168
+ }
169
+ serializeJson(data) {
170
+ let meta = [];
171
+ const maps = [];
172
+ const blobs = [];
173
+ const json = this.serializeValue(data, [], meta, maps, blobs);
174
+ meta = meta.length === 0 ? undefined : meta;
175
+ if (maps.length === 0) {
176
+ return {
177
+ json,
178
+ meta
179
+ };
180
+ }
181
+ return {
182
+ json,
183
+ meta,
184
+ maps,
185
+ blobs
186
+ };
187
+ }
188
+
189
+ serializeValue(data, segments, meta, maps, blobs) {
190
+
191
+ if (this.inlineBuiltInHandlers) {
192
+ switch (typeof data) {
193
+ case "string":
194
+ case "boolean": return data;
195
+ case "number":
196
+ if (Number.isFinite(data)) {
197
+ return data;
198
+ }
199
+ if (Number.isNaN(data)) {
200
+ meta.push(["nan", ...segments]);
201
+ return null;
202
+ }
203
+ meta.push(["infinity", ...segments]);
204
+ return data > 0 ? "Infinity" : "-Infinity";
205
+ case "undefined":
206
+ meta.push(["undefined", ...segments]);
207
+ return null;
208
+ case "bigint":
209
+ meta.push(["bigint", ...segments]);
210
+ return data.toString();
211
+ case "object": {
212
+ if (data === null) {
213
+ return data;
214
+ }
215
+ if (data instanceof Date) {
216
+ meta.push(["date", ...segments]);
217
+ return Number.isNaN(data.getTime()) ? null : data.toISOString();
218
+ }
219
+ if (data instanceof URL) {
220
+ meta.push(["url", ...segments]);
221
+ return data.toString();
222
+ }
223
+ if (data instanceof Set) {
224
+ const result = this.serializeValue(Array.from(data), segments, meta, maps, blobs);
225
+ meta.push(["set", ...segments]);
226
+ return result;
227
+ }
228
+ if (data instanceof Map) {
229
+ const result = this.serializeValue(Array.from(data.entries()), segments, meta, maps, blobs);
230
+ meta.push(["map", ...segments]);
231
+ return result;
232
+ }
233
+ }
234
+ }
235
+ }
236
+ const handlerEntries = this.handlerEntries;
237
+ if (handlerEntries) {
238
+ for (let i = 0; i < handlerEntries.length; i++) {
239
+ const entry = handlerEntries[i];
240
+ const handler = entry[1];
241
+ if (handler.condition(data)) {
242
+ const serialized = handler.serialize(data);
243
+ if (handler.isTerminal) {
244
+ meta.push([entry[0], ...segments]);
245
+ if (serialized instanceof Blob) {
246
+ maps.push(segments.slice());
247
+ blobs.push(serialized);
248
+ }
249
+ return serialized;
250
+ }
251
+ const result = this.serializeValue(serialized, segments, meta, maps, blobs);
252
+ meta.push([entry[0], ...segments]);
253
+ return result;
254
+ }
255
+ }
256
+ }
257
+ if (data instanceof Blob) {
258
+ maps.push(segments.slice());
259
+ blobs.push(data);
260
+ return data;
261
+ }
262
+ if (Array.isArray(data)) {
263
+ const json = [];
264
+ for (let i = 0; i < data.length; i++) {
265
+ segments.push(i);
266
+ json.push(this.serializeValue(data[i], segments, meta, maps, blobs));
267
+ segments.pop();
268
+ }
269
+ return json;
270
+ }
271
+ if (isPlainObject(data)) {
272
+ const json = new NullProtoObj();
273
+ for (const k of Object.keys(data)) {
274
+ const v = data[k];
275
+
276
+ if (k === "toJSON" && typeof v === "function") {
277
+ continue;
278
+ }
279
+ if (v === undefined && this.omitUndefinedProperties) {
280
+ continue;
281
+ }
282
+ segments.push(k);
283
+ json[k] = this.serializeValue(v, segments, meta, maps, blobs);
284
+ segments.pop();
285
+ }
286
+ return json;
287
+ }
288
+ return data;
289
+ }
290
+ deserializeJson(serialized) {
291
+ const ref = { json: serialized.json };
292
+ if (serialized.blobs?.length) {
293
+ for (let i = 0; i < serialized.maps.length; i++) {
294
+ const blob = serialized.blobs[i];
295
+ if (!(blob instanceof Blob)) {
296
+ throw invalidSerializedData(`blob ${i} is not a Blob.`);
297
+ }
298
+ const segments = serialized.maps[i];
299
+ let original = serialized;
300
+ let currentRef = ref;
301
+ let preSegment = "json";
302
+ for (let j = 0; j < segments.length; j++) {
303
+ original = original[preSegment];
304
+ currentRef = walkInto(currentRef, preSegment, original);
305
+ preSegment = segments[j];
306
+ if (!Object.hasOwn(currentRef, preSegment)) {
307
+ throw invalidSerializedData(`segment "${preSegment}" does not exist.`);
308
+ }
309
+ }
310
+ currentRef[preSegment] = blob;
311
+ }
312
+ }
313
+ const meta = serialized.meta;
314
+ if (meta) {
315
+ let restored;
316
+
317
+ const chain = meta.length === 1 ? undefined : [];
318
+ let chainDepth = 0;
319
+ for (const item of meta) {
320
+ const handler = this.handlers[item[0]];
321
+ if (handler === undefined) {
322
+ continue;
323
+ }
324
+ const depth = item.length - 1;
325
+ const shared = Math.min(depth, chainDepth);
326
+ let d = 0;
327
+ let original = serialized;
328
+ let currentRef = ref;
329
+ let preSegment = "json";
330
+ if (chain !== undefined && shared > 0) {
331
+ d = 1;
332
+ while (d < shared && chain[3 * d] === item[d]) {
333
+ d++;
334
+ }
335
+ currentRef = chain[3 * d - 2];
336
+ original = chain[3 * d - 1];
337
+ preSegment = item[d];
338
+ if (!Object.hasOwn(currentRef, preSegment)) {
339
+ throw invalidSerializedData(`segment "${preSegment}" does not exist.`);
340
+ }
341
+ }
342
+ while (d < depth) {
343
+ original = original[preSegment];
344
+ currentRef = walkInto(currentRef, preSegment, original, restored);
345
+ if (chain !== undefined) {
346
+ chain[3 * d] = preSegment;
347
+ chain[3 * d + 1] = currentRef;
348
+ chain[3 * d + 2] = original;
349
+ }
350
+ preSegment = item[++d];
351
+ if (!Object.hasOwn(currentRef, preSegment)) {
352
+ throw invalidSerializedData(`segment "${preSegment}" does not exist.`);
353
+ }
354
+ }
355
+ chainDepth = depth;
356
+ const value = handler.deserialize(currentRef[preSegment]);
357
+ currentRef[preSegment] = value;
358
+ if (isWalkable(value)) {
359
+ (restored ??= new Set()).add(value);
360
+ }
361
+ }
362
+ }
363
+ return ref.json;
364
+ }
365
+ }
@@ -0,0 +1,32 @@
1
+ import type { StandardBody } from "@standard-server/core";
2
+ import type { RPCJsonSerializerOptions } from "./rpc-json-serializer.mjs";
3
+ import { RPCJsonSerializer } from "./rpc-json-serializer.mjs";
4
+ export interface RPCSerializerSerializeOptions {
5
+ /**
6
+ * Use FormData for serialization when nested blobs are present.
7
+ * Does not apply to root-level Blob values.
8
+ *
9
+ * @default true
10
+ */
11
+ useFormDataForBlobFields?: boolean | undefined;
12
+ }
13
+ export interface RPCSerializerOptions extends RPCJsonSerializerOptions {
14
+ /**
15
+ * Default options for serialize method
16
+ */
17
+ serialize?: RPCSerializerSerializeOptions | undefined;
18
+ }
19
+ /**
20
+ * Serializes and deserializes data for the RPC protocol,
21
+ * preserving native types like Date, BigInt, Set, and Map that plain JSON cannot represent.
22
+ *
23
+ * @see {@link https://orpc.dev/docs/rpc/serializer | RPC Serializer}
24
+ */
25
+ export declare class RPCSerializer extends RPCJsonSerializer {
26
+ private readonly defaultSerializeOptions;
27
+ constructor(options?: RPCSerializerOptions);
28
+ serialize(data: unknown, options?: RPCSerializerSerializeOptions): StandardBody;
29
+ private serializePayload;
30
+ deserialize(data: StandardBody): unknown;
31
+ private deserializePayload;
32
+ }
@@ -0,0 +1,100 @@
1
+ import { isAsyncIteratorObject, stringifyJSON } from "@orpc/shared";
2
+ import { ErrorEvent } from "@standard-server/core";
3
+ import { wrapAsyncIteratorPreservingEventMeta } from "./async-iterator-object.mjs";
4
+ import { createORPCErrorFromJson, isORPCErrorJson, toORPCError } from "./error-utils.mjs";
5
+ import { RPCJsonSerializer } from "./rpc-json-serializer.mjs";
6
+
7
+ export class RPCSerializer extends RPCJsonSerializer {
8
+ defaultSerializeOptions;
9
+ constructor(options = {}) {
10
+ super(options);
11
+ this.defaultSerializeOptions = options.serialize;
12
+ }
13
+ serialize(data, options = {}) {
14
+
15
+ if (data === undefined || data instanceof ReadableStream || data instanceof Blob) {
16
+ return data;
17
+ }
18
+ if (isAsyncIteratorObject(data)) {
19
+ return wrapAsyncIteratorPreservingEventMeta(data, {
20
+ mapResult: (result) => {
21
+
22
+ if (result.value === undefined) {
23
+ return result;
24
+ }
25
+ return {
26
+ done: result.done,
27
+ value: this.serializePayload(result.value, false)
28
+ };
29
+ },
30
+ mapError: (e) => new ErrorEvent(this.serializePayload(toORPCError(e).toJSON(), false), { cause: e })
31
+ });
32
+ }
33
+ const useFormDataForBlobs = options.useFormDataForBlobFields ?? this.defaultSerializeOptions?.useFormDataForBlobFields ?? true;
34
+ return this.serializePayload(data, useFormDataForBlobs);
35
+ }
36
+ serializePayload(data, useFormDataForBlobs) {
37
+ const { json, meta, maps, blobs } = this.serializeJson(data);
38
+ if (!useFormDataForBlobs || !blobs?.length) {
39
+ return {
40
+ json,
41
+ meta
42
+ };
43
+ }
44
+ const form = new FormData();
45
+ form.set("data", stringifyJSON({
46
+ json,
47
+ meta,
48
+ maps
49
+ }));
50
+ blobs.forEach((blob, i) => {
51
+ form.set(i.toString(), blob);
52
+ });
53
+ return form;
54
+ }
55
+ deserialize(data) {
56
+ if (data === undefined || data instanceof ReadableStream || data instanceof Blob) {
57
+ return data;
58
+ }
59
+ if (isAsyncIteratorObject(data)) {
60
+ return wrapAsyncIteratorPreservingEventMeta(data, {
61
+ mapResult: (result) => {
62
+ if (result.value === undefined) {
63
+ return result;
64
+ }
65
+ return {
66
+ done: result.done,
67
+ value: this.deserializePayload(result.value)
68
+ };
69
+ },
70
+ mapError: (e) => {
71
+ if (!(e instanceof ErrorEvent)) {
72
+ return e;
73
+ }
74
+ const deserialized = this.deserializePayload(e.data);
75
+ if (isORPCErrorJson(deserialized)) {
76
+ return createORPCErrorFromJson(deserialized, { cause: e });
77
+ }
78
+ return new ErrorEvent(deserialized, { cause: e });
79
+ }
80
+ });
81
+ }
82
+ return this.deserializePayload(data);
83
+ }
84
+ deserializePayload(data) {
85
+ if (!(data instanceof FormData)) {
86
+ return this.deserializeJson(data);
87
+ }
88
+ const serialized = JSON.parse(data.get("data"));
89
+ const blobs = [];
90
+ for (const [key, value] of data) {
91
+ if (value instanceof Blob) {
92
+ blobs[Number(key)] = value;
93
+ }
94
+ }
95
+ return this.deserializeJson({
96
+ ...serialized,
97
+ blobs
98
+ });
99
+ }
100
+ }
@@ -0,0 +1,93 @@
1
+ import type { PromiseWithError } from "@orpc/shared";
2
+ export interface ClientContext {
3
+ [key: PropertyKey]: any;
4
+ }
5
+ export interface ClientOptions<T extends ClientContext> {
6
+ signal?: AbortSignal | undefined;
7
+ lastEventId?: string | undefined;
8
+ context: T;
9
+ }
10
+ export type FriendlyClientOptions<T extends ClientContext> = Omit<ClientOptions<T>, "context"> & (object extends T ? {
11
+ context?: T | undefined;
12
+ } : {
13
+ context: T;
14
+ });
15
+ export type ClientRest<
16
+ TClientContext extends ClientContext,
17
+ TInput
18
+ > = object extends TClientContext ? undefined extends TInput ? [input?: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options: FriendlyClientOptions<TClientContext>];
19
+ export interface Client<
20
+ TClientContext extends ClientContext,
21
+ TInput,
22
+ TOutput,
23
+ TError
24
+ > {
25
+ (...rest: ClientRest<TClientContext, TInput>): PromiseWithError<TOutput, TError>;
26
+ }
27
+ export type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | {
28
+ [k: string]: NestedClient<TClientContext>;
29
+ };
30
+ export type AnyNestedClient = NestedClient<any>;
31
+ /**
32
+ * Infers the **client context type** required by a client.
33
+ *
34
+ * @see {@link https://orpc.dev/docs/client/client-side#infer-client-context | Client-Side Clients - Infer Client Context}
35
+ */
36
+ export type InferClientContext<T extends AnyNestedClient> = T extends NestedClient<infer U> ? U : never;
37
+ export interface ClientLink<TClientContext extends ClientContext> {
38
+ call: (path: string[], input: unknown, options: ClientOptions<TClientContext>) => Promise<unknown>;
39
+ }
40
+ /**
41
+ * Recursively infers the **input types** from a client.
42
+ *
43
+ * Produces a nested map where each endpoint's input type is preserved.
44
+ *
45
+ * @see {@link https://orpc.dev/docs/client/client-side#infer-client-inputs | Client-Side Clients - Infer Client Inputs}
46
+ */
47
+ export type InferClientInputs<T extends AnyNestedClient> = T extends Client<any, infer U, any, any> ? U : { [K in keyof T]: T[K] extends AnyNestedClient ? InferClientInputs<T[K]> : never };
48
+ /**
49
+ * Recursively infers the **body input types** from a client.
50
+ *
51
+ * If an endpoint's input includes `{ body: ... }`, only the `body` portion is extracted.
52
+ * Produces a nested map of body input types.
53
+ *
54
+ * @see {@link https://orpc.dev/docs/client/client-side#infer-client-body-inputs | Client-Side Clients - Infer Client Body Inputs}
55
+ */
56
+ export type InferClientBodyInputs<T extends AnyNestedClient> = T extends Client<any, infer U, any, any> ? U extends {
57
+ body: infer UBody;
58
+ } ? UBody : U : { [K in keyof T]: T[K] extends AnyNestedClient ? InferClientBodyInputs<T[K]> : never };
59
+ /**
60
+ * Recursively infers the **output types** from a client.
61
+ *
62
+ * Produces a nested map where each endpoint's output type is preserved.
63
+ *
64
+ * @see {@link https://orpc.dev/docs/client/client-side#infer-client-outputs | Client-Side Clients - Infer Client Outputs}
65
+ */
66
+ export type InferClientOutputs<T extends AnyNestedClient> = T extends Client<any, any, infer U, any> ? U : { [K in keyof T]: T[K] extends AnyNestedClient ? InferClientOutputs<T[K]> : never };
67
+ /**
68
+ * Recursively infers the **body output types** from a client.
69
+ *
70
+ * If an endpoint's output includes `{ body: ... }`, only the `body` portion is extracted.
71
+ * Produces a nested map of body output types.
72
+ *
73
+ * @see {@link https://orpc.dev/docs/client/client-side#infer-client-body-outputs | Client-Side Clients - Infer Client Body Outputs}
74
+ */
75
+ export type InferClientBodyOutputs<T extends AnyNestedClient> = T extends Client<any, any, infer U, any> ? U extends {
76
+ body: infer UBody;
77
+ } ? UBody : U : { [K in keyof T]: T[K] extends AnyNestedClient ? InferClientBodyOutputs<T[K]> : never };
78
+ /**
79
+ * Recursively infers the **error types** from a client when you use [type-safe errors](https://orpc.dev/docs/error-handling#typesafe-errors).
80
+ *
81
+ * Produces a nested map where each endpoint's error type is preserved.
82
+ *
83
+ * @see {@link https://orpc.dev/docs/client/client-side#infer-client-errors | Client-Side Clients - Infer Client Errors}
84
+ */
85
+ export type InferClientErrors<T extends AnyNestedClient> = T extends Client<any, any, any, infer U> ? U : { [K in keyof T]: T[K] extends AnyNestedClient ? InferClientErrors<T[K]> : never };
86
+ /**
87
+ * Recursively infers a **union of all error types** from a client when you use [type-safe errors](https://orpc.dev/docs/error-handling#typesafe-errors).
88
+ *
89
+ * Useful when you want to handle all possible errors from any endpoint at once.
90
+ *
91
+ * @see {@link https://orpc.dev/docs/client/client-side#infer-client-error | Client-Side Clients - Infer Client Error}
92
+ */
93
+ export type InferClientError<T extends AnyNestedClient> = T extends Client<any, any, any, infer U> ? U : { [K in keyof T]: T[K] extends AnyNestedClient ? InferClientError<T[K]> : never }[keyof T];
package/dist/types.mjs ADDED
@@ -0,0 +1 @@
1
+ export {};