@orpc/client 0.0.0-next.564695e → 0.0.0-next.56695f3

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.BH1AYT_p.d.mts +83 -0
  21. package/dist/shared/client.BH1AYT_p.d.ts +83 -0
  22. package/dist/shared/client.BLtwTQUg.mjs +40 -0
  23. package/dist/shared/client.BxV-mzeR.d.ts +91 -0
  24. package/dist/shared/client.CPgZaUox.d.mts +45 -0
  25. package/dist/shared/client.D8lMmWVC.d.mts +91 -0
  26. package/dist/shared/client.De8SW4Kw.d.ts +45 -0
  27. package/dist/shared/client.Kb4Yizd7.mjs +171 -0
  28. package/dist/shared/client.tlByQHxE.mjs +398 -0
  29. package/package.json +32 -18
  30. package/dist/fetch.js +0 -103
  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.Kb4Yizd7.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 };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/client",
3
3
  "type": "module",
4
- "version": "0.0.0-next.564695e",
4
+ "version": "0.0.0-next.56695f3",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -15,36 +15,50 @@
15
15
  ],
16
16
  "exports": {
17
17
  ".": {
18
- "types": "./dist/src/index.d.ts",
19
- "import": "./dist/index.js",
20
- "default": "./dist/index.js"
18
+ "types": "./dist/index.d.mts",
19
+ "import": "./dist/index.mjs",
20
+ "default": "./dist/index.mjs"
21
+ },
22
+ "./plugins": {
23
+ "types": "./dist/plugins/index.d.mts",
24
+ "import": "./dist/plugins/index.mjs",
25
+ "default": "./dist/plugins/index.mjs"
26
+ },
27
+ "./standard": {
28
+ "types": "./dist/adapters/standard/index.d.mts",
29
+ "import": "./dist/adapters/standard/index.mjs",
30
+ "default": "./dist/adapters/standard/index.mjs"
21
31
  },
22
32
  "./fetch": {
23
- "types": "./dist/src/adapters/fetch/index.d.ts",
24
- "import": "./dist/fetch.js",
25
- "default": "./dist/fetch.js"
33
+ "types": "./dist/adapters/fetch/index.d.mts",
34
+ "import": "./dist/adapters/fetch/index.mjs",
35
+ "default": "./dist/adapters/fetch/index.mjs"
36
+ },
37
+ "./websocket": {
38
+ "types": "./dist/adapters/websocket/index.d.mts",
39
+ "import": "./dist/adapters/websocket/index.mjs",
40
+ "default": "./dist/adapters/websocket/index.mjs"
26
41
  },
27
- "./🔒/*": {
28
- "types": "./dist/src/*.d.ts"
42
+ "./message-port": {
43
+ "types": "./dist/adapters/message-port/index.d.mts",
44
+ "import": "./dist/adapters/message-port/index.mjs",
45
+ "default": "./dist/adapters/message-port/index.mjs"
29
46
  }
30
47
  },
31
48
  "files": [
32
- "!**/*.map",
33
- "!**/*.tsbuildinfo",
34
49
  "dist"
35
50
  ],
36
51
  "dependencies": {
37
- "@tinyhttp/content-disposition": "^2.2.2",
38
- "@orpc/contract": "0.0.0-next.564695e",
39
- "@orpc/server": "0.0.0-next.564695e",
40
- "@orpc/shared": "0.0.0-next.564695e"
52
+ "@orpc/shared": "0.0.0-next.56695f3",
53
+ "@orpc/standard-server": "0.0.0-next.56695f3",
54
+ "@orpc/standard-server-fetch": "0.0.0-next.56695f3",
55
+ "@orpc/standard-server-peer": "0.0.0-next.56695f3"
41
56
  },
42
57
  "devDependencies": {
43
- "zod": "^3.24.1",
44
- "@orpc/openapi": "0.0.0-next.564695e"
58
+ "zod": "^4.1.12"
45
59
  },
46
60
  "scripts": {
47
- "build": "tsup --clean --sourcemap --entry.index=src/index.ts --entry.fetch=src/adapters/fetch/index.ts --format=esm --onSuccess='tsc -b --noCheck'",
61
+ "build": "unbuild",
48
62
  "build:watch": "pnpm run build --watch",
49
63
  "type:check": "tsc -b"
50
64
  }
package/dist/fetch.js DELETED
@@ -1,103 +0,0 @@
1
- // src/adapters/fetch/orpc-link.ts
2
- import { ORPCError } from "@orpc/contract";
3
- import { fetchReToStandardBody } from "@orpc/server/fetch";
4
- import { RPCSerializer } from "@orpc/server/standard";
5
- import { isPlainObject, trim } from "@orpc/shared";
6
- import { contentDisposition } from "@tinyhttp/content-disposition";
7
- var RPCLink = class {
8
- fetch;
9
- rpcSerializer;
10
- maxURLLength;
11
- fallbackMethod;
12
- getMethod;
13
- getHeaders;
14
- url;
15
- constructor(options) {
16
- this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
17
- this.rpcSerializer = options.rpcSerializer ?? new RPCSerializer();
18
- this.maxURLLength = options.maxURLLength ?? 2083;
19
- this.fallbackMethod = options.fallbackMethod ?? "POST";
20
- this.url = options.url;
21
- this.getMethod = async (path, input, context) => {
22
- return await options.method?.(path, input, context) ?? this.fallbackMethod;
23
- };
24
- this.getHeaders = async (path, input, context) => {
25
- return new Headers(await options.headers?.(path, input, context));
26
- };
27
- }
28
- async call(path, input, options) {
29
- const clientContext = options.context;
30
- const encoded = await this.encode(path, input, options);
31
- if (encoded.body instanceof Blob && !encoded.headers.has("content-disposition")) {
32
- encoded.headers.set("content-disposition", contentDisposition(encoded.body instanceof File ? encoded.body.name : "blob"));
33
- }
34
- const response = await this.fetch(encoded.url, {
35
- method: encoded.method,
36
- headers: encoded.headers,
37
- body: encoded.body,
38
- signal: options.signal
39
- }, clientContext);
40
- const body = await fetchReToStandardBody(response);
41
- const deserialized = (() => {
42
- try {
43
- return this.rpcSerializer.deserialize(body);
44
- } catch (error) {
45
- if (response.ok) {
46
- throw new ORPCError("INTERNAL_SERVER_ERROR", {
47
- message: "Invalid RPC response",
48
- cause: error
49
- });
50
- }
51
- throw new ORPCError(response.status.toString(), {
52
- message: response.statusText
53
- });
54
- }
55
- })();
56
- if (response.ok) {
57
- return deserialized;
58
- }
59
- throw ORPCError.fromJSON(deserialized);
60
- }
61
- async encode(path, input, options) {
62
- const clientContext = options.context;
63
- const expectMethod = await this.getMethod(path, input, clientContext);
64
- const headers = await this.getHeaders(path, input, clientContext);
65
- const url = new URL(`${trim(this.url, "/")}/${path.map(encodeURIComponent).join("/")}`);
66
- headers.append("x-orpc-handler", "rpc");
67
- const serialized = this.rpcSerializer.serialize(input);
68
- if (expectMethod === "GET" && isPlainObject(serialized)) {
69
- const tryURL = new URL(url);
70
- tryURL.searchParams.append("data", JSON.stringify(serialized));
71
- if (tryURL.toString().length <= this.maxURLLength) {
72
- return {
73
- body: void 0,
74
- method: expectMethod,
75
- headers,
76
- url: tryURL
77
- };
78
- }
79
- }
80
- const method = expectMethod === "GET" ? this.fallbackMethod : expectMethod;
81
- if (isPlainObject(serialized)) {
82
- if (!headers.has("content-type")) {
83
- headers.set("content-type", "application/json");
84
- }
85
- return {
86
- body: JSON.stringify(serialized),
87
- method,
88
- headers,
89
- url
90
- };
91
- }
92
- return {
93
- body: serialized,
94
- method,
95
- headers,
96
- url
97
- };
98
- }
99
- };
100
- export {
101
- RPCLink
102
- };
103
- //# sourceMappingURL=fetch.js.map
package/dist/index.js DELETED
@@ -1,42 +0,0 @@
1
- // src/client.ts
2
- function createORPCClient(link, options) {
3
- const path = options?.path ?? [];
4
- const procedureClient = async (...[input, options2]) => {
5
- return await link.call(path, input, options2 ?? {});
6
- };
7
- const recursive = new Proxy(procedureClient, {
8
- get(target, key) {
9
- if (typeof key !== "string") {
10
- return Reflect.get(target, key);
11
- }
12
- return createORPCClient(link, {
13
- ...options,
14
- path: [...path, key]
15
- });
16
- }
17
- });
18
- return recursive;
19
- }
20
-
21
- // src/dynamic-link.ts
22
- var DynamicLink = class {
23
- constructor(linkResolver) {
24
- this.linkResolver = linkResolver;
25
- }
26
- async call(path, input, options) {
27
- const resolvedLink = await this.linkResolver(path, input, options.context);
28
- const output = await resolvedLink.call(path, input, options);
29
- return output;
30
- }
31
- };
32
-
33
- // src/index.ts
34
- import { isDefinedError, ORPCError, safe } from "@orpc/contract";
35
- export {
36
- DynamicLink,
37
- ORPCError,
38
- createORPCClient,
39
- isDefinedError,
40
- safe
41
- };
42
- //# sourceMappingURL=index.js.map
@@ -1,3 +0,0 @@
1
- export * from './orpc-link';
2
- export * from './types';
3
- //# sourceMappingURL=index.d.ts.map
@@ -1,46 +0,0 @@
1
- import type { ClientOptions, HTTPMethod } from '@orpc/contract';
2
- import type { Promisable } from '@orpc/shared';
3
- import type { ClientLink } from '../../types';
4
- import type { FetchWithContext } from './types';
5
- import { RPCSerializer } from '@orpc/server/standard';
6
- export interface RPCLinkOptions<TClientContext> {
7
- /**
8
- * Base url for all requests.
9
- */
10
- url: string;
11
- /**
12
- * The maximum length of the URL.
13
- *
14
- * @default 2083
15
- */
16
- maxURLLength?: number;
17
- /**
18
- * The method used to make the request.
19
- *
20
- * @default 'POST'
21
- */
22
- method?(path: readonly string[], input: unknown, context: TClientContext): Promisable<HTTPMethod | undefined>;
23
- /**
24
- * The method to use when the payload cannot safely pass to the server with method return from method function.
25
- * GET is not allowed, it's very dangerous.
26
- *
27
- * @default 'POST'
28
- */
29
- fallbackMethod?: Exclude<HTTPMethod, 'GET'>;
30
- headers?(path: readonly string[], input: unknown, context: TClientContext): Promisable<Headers | Record<string, string>>;
31
- fetch?: FetchWithContext<TClientContext>;
32
- rpcSerializer?: RPCSerializer;
33
- }
34
- export declare class RPCLink<TClientContext> implements ClientLink<TClientContext> {
35
- private readonly fetch;
36
- private readonly rpcSerializer;
37
- private readonly maxURLLength;
38
- private readonly fallbackMethod;
39
- private readonly getMethod;
40
- private readonly getHeaders;
41
- private readonly url;
42
- constructor(options: RPCLinkOptions<TClientContext>);
43
- call(path: readonly string[], input: unknown, options: ClientOptions<TClientContext>): Promise<unknown>;
44
- private encode;
45
- }
46
- //# sourceMappingURL=orpc-link.d.ts.map
@@ -1,4 +0,0 @@
1
- export interface FetchWithContext<TClientContext> {
2
- (input: RequestInfo | URL, init: RequestInit | undefined, context: TClientContext): Promise<Response>;
3
- }
4
- //# sourceMappingURL=types.d.ts.map
@@ -1,11 +0,0 @@
1
- import type { AnyContractRouter, ContractRouterClient } from '@orpc/contract';
2
- import type { AnyRouter, RouterClient } from '@orpc/server';
3
- import type { ClientLink } from './types';
4
- export interface createORPCClientOptions {
5
- /**
6
- * Use as base path for all procedure, useful when you only want to call a subset of the procedure.
7
- */
8
- path?: string[];
9
- }
10
- export declare function createORPCClient<TRouter extends AnyRouter | AnyContractRouter, TClientContext = unknown>(link: ClientLink<TClientContext>, options?: createORPCClientOptions): TRouter extends AnyRouter ? RouterClient<TRouter, TClientContext> : TRouter extends AnyContractRouter ? ContractRouterClient<TRouter, TClientContext> : never;
11
- //# sourceMappingURL=client.d.ts.map