@orpc/client 0.0.0-next.172fe95 → 0.0.0-next.173b319

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.
@@ -0,0 +1,334 @@
1
+ import { toArray, intercept, isObject, value, isAsyncIteratorObject, stringifyJSON } from '@orpc/shared';
2
+ import { O as ORPCError, m as mapEventIterator, t as toORPCError } from './client.BacCdg3F.mjs';
3
+ import { ErrorEvent } from '@orpc/standard-server';
4
+
5
+ class InvalidEventIteratorRetryResponse extends Error {
6
+ }
7
+ class StandardLink {
8
+ constructor(codec, sender, options = {}) {
9
+ this.codec = codec;
10
+ this.sender = sender;
11
+ for (const plugin of toArray(options.plugins)) {
12
+ plugin.init?.(options);
13
+ }
14
+ this.interceptors = toArray(options.interceptors);
15
+ this.clientInterceptors = toArray(options.clientInterceptors);
16
+ }
17
+ interceptors;
18
+ clientInterceptors;
19
+ call(path, input, options) {
20
+ return intercept(this.interceptors, { path, input, options }, async ({ path: path2, input: input2, options: options2 }) => {
21
+ const output = await this.#call(path2, input2, options2);
22
+ return output;
23
+ });
24
+ }
25
+ async #call(path, input, options) {
26
+ const request = await this.codec.encode(path, input, options);
27
+ const response = await intercept(
28
+ this.clientInterceptors,
29
+ { request },
30
+ ({ request: request2 }) => this.sender.call(request2, options, path, input)
31
+ );
32
+ const output = await this.codec.decode(response, options, path, input);
33
+ return output;
34
+ }
35
+ }
36
+
37
+ const STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES = {
38
+ BIGINT: 0,
39
+ DATE: 1,
40
+ NAN: 2,
41
+ UNDEFINED: 3,
42
+ URL: 4,
43
+ REGEXP: 5,
44
+ SET: 6,
45
+ MAP: 7
46
+ };
47
+ class StandardRPCJsonSerializer {
48
+ customSerializers;
49
+ constructor(options = {}) {
50
+ this.customSerializers = options.customJsonSerializers ?? [];
51
+ if (this.customSerializers.length !== new Set(this.customSerializers.map((custom) => custom.type)).size) {
52
+ throw new Error("Custom serializer type must be unique.");
53
+ }
54
+ }
55
+ serialize(data, segments = [], meta = [], maps = [], blobs = []) {
56
+ for (const custom of this.customSerializers) {
57
+ if (custom.condition(data)) {
58
+ const result = this.serialize(custom.serialize(data), segments, meta, maps, blobs);
59
+ meta.push([custom.type, ...segments]);
60
+ return result;
61
+ }
62
+ }
63
+ if (data instanceof Blob) {
64
+ maps.push(segments);
65
+ blobs.push(data);
66
+ return [data, meta, maps, blobs];
67
+ }
68
+ if (typeof data === "bigint") {
69
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT, ...segments]);
70
+ return [data.toString(), meta, maps, blobs];
71
+ }
72
+ if (data instanceof Date) {
73
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE, ...segments]);
74
+ if (Number.isNaN(data.getTime())) {
75
+ return [null, meta, maps, blobs];
76
+ }
77
+ return [data.toISOString(), meta, maps, blobs];
78
+ }
79
+ if (Number.isNaN(data)) {
80
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN, ...segments]);
81
+ return [null, meta, maps, blobs];
82
+ }
83
+ if (data instanceof URL) {
84
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL, ...segments]);
85
+ return [data.toString(), meta, maps, blobs];
86
+ }
87
+ if (data instanceof RegExp) {
88
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP, ...segments]);
89
+ return [data.toString(), meta, maps, blobs];
90
+ }
91
+ if (data instanceof Set) {
92
+ const result = this.serialize(Array.from(data), segments, meta, maps, blobs);
93
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET, ...segments]);
94
+ return result;
95
+ }
96
+ if (data instanceof Map) {
97
+ const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);
98
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP, ...segments]);
99
+ return result;
100
+ }
101
+ if (Array.isArray(data)) {
102
+ const json = data.map((v, i) => {
103
+ if (v === void 0) {
104
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED, ...segments, i]);
105
+ return v;
106
+ }
107
+ return this.serialize(v, [...segments, i], meta, maps, blobs)[0];
108
+ });
109
+ return [json, meta, maps, blobs];
110
+ }
111
+ if (isObject(data)) {
112
+ const json = {};
113
+ for (const k in data) {
114
+ if (k === "toJSON" && typeof data[k] === "function") {
115
+ continue;
116
+ }
117
+ json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];
118
+ }
119
+ return [json, meta, maps, blobs];
120
+ }
121
+ return [data, meta, maps, blobs];
122
+ }
123
+ deserialize(json, meta, maps, getBlob) {
124
+ const ref = { data: json };
125
+ if (maps && getBlob) {
126
+ maps.forEach((segments, i) => {
127
+ let currentRef = ref;
128
+ let preSegment = "data";
129
+ segments.forEach((segment) => {
130
+ currentRef = currentRef[preSegment];
131
+ preSegment = segment;
132
+ });
133
+ currentRef[preSegment] = getBlob(i);
134
+ });
135
+ }
136
+ for (const item of meta) {
137
+ const type = item[0];
138
+ let currentRef = ref;
139
+ let preSegment = "data";
140
+ for (let i = 1; i < item.length; i++) {
141
+ currentRef = currentRef[preSegment];
142
+ preSegment = item[i];
143
+ }
144
+ for (const custom of this.customSerializers) {
145
+ if (custom.type === type) {
146
+ currentRef[preSegment] = custom.deserialize(currentRef[preSegment]);
147
+ break;
148
+ }
149
+ }
150
+ switch (type) {
151
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT:
152
+ currentRef[preSegment] = BigInt(currentRef[preSegment]);
153
+ break;
154
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE:
155
+ currentRef[preSegment] = new Date(currentRef[preSegment] ?? "Invalid Date");
156
+ break;
157
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN:
158
+ currentRef[preSegment] = Number.NaN;
159
+ break;
160
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED:
161
+ currentRef[preSegment] = void 0;
162
+ break;
163
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL:
164
+ currentRef[preSegment] = new URL(currentRef[preSegment]);
165
+ break;
166
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP: {
167
+ const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
168
+ currentRef[preSegment] = new RegExp(pattern, flags);
169
+ break;
170
+ }
171
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET:
172
+ currentRef[preSegment] = new Set(currentRef[preSegment]);
173
+ break;
174
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP:
175
+ currentRef[preSegment] = new Map(currentRef[preSegment]);
176
+ break;
177
+ }
178
+ }
179
+ return ref.data;
180
+ }
181
+ }
182
+
183
+ class StandardRPCLinkCodec {
184
+ constructor(serializer, options) {
185
+ this.serializer = serializer;
186
+ this.baseUrl = options.url;
187
+ this.maxUrlLength = options.maxUrlLength ?? 2083;
188
+ this.fallbackMethod = options.fallbackMethod ?? "POST";
189
+ this.expectedMethod = options.method ?? this.fallbackMethod;
190
+ this.headers = options.headers ?? {};
191
+ }
192
+ baseUrl;
193
+ maxUrlLength;
194
+ fallbackMethod;
195
+ expectedMethod;
196
+ headers;
197
+ async encode(path, input, options) {
198
+ const expectedMethod = await value(this.expectedMethod, options, path, input);
199
+ const headers = { ...await value(this.headers, options, path, input) };
200
+ const baseUrl = await value(this.baseUrl, options, path, input);
201
+ const url = new URL(`${baseUrl.toString().replace(/\/$/, "")}/${path.map(encodeURIComponent).join("/")}`);
202
+ if (options.lastEventId !== void 0) {
203
+ if (Array.isArray(headers["last-event-id"])) {
204
+ headers["last-event-id"] = [...headers["last-event-id"], options.lastEventId];
205
+ } else if (headers["last-event-id"] !== void 0) {
206
+ headers["last-event-id"] = [headers["last-event-id"], options.lastEventId];
207
+ } else {
208
+ headers["last-event-id"] = options.lastEventId;
209
+ }
210
+ }
211
+ const serialized = this.serializer.serialize(input);
212
+ if (expectedMethod === "GET" && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
213
+ const maxUrlLength = await value(this.maxUrlLength, options, path, input);
214
+ const getUrl = new URL(url);
215
+ getUrl.searchParams.append("data", stringifyJSON(serialized));
216
+ if (getUrl.toString().length <= maxUrlLength) {
217
+ return {
218
+ body: void 0,
219
+ method: expectedMethod,
220
+ headers,
221
+ url: getUrl,
222
+ signal: options.signal
223
+ };
224
+ }
225
+ }
226
+ return {
227
+ url,
228
+ method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
229
+ headers,
230
+ body: serialized,
231
+ signal: options.signal
232
+ };
233
+ }
234
+ async decode(response) {
235
+ const isOk = response.status >= 200 && response.status < 300;
236
+ const deserialized = await (async () => {
237
+ let isBodyOk = false;
238
+ try {
239
+ const body = await response.body();
240
+ isBodyOk = true;
241
+ return this.serializer.deserialize(body);
242
+ } catch (error) {
243
+ if (!isBodyOk) {
244
+ throw new Error("Cannot parse response body, please check the response body and content-type.", {
245
+ cause: error
246
+ });
247
+ }
248
+ throw new Error("Invalid RPC response format.", {
249
+ cause: error
250
+ });
251
+ }
252
+ })();
253
+ if (!isOk) {
254
+ if (ORPCError.isValidJSON(deserialized)) {
255
+ throw ORPCError.fromJSON(deserialized);
256
+ }
257
+ throw new Error("Invalid RPC error response format.", {
258
+ cause: deserialized
259
+ });
260
+ }
261
+ return deserialized;
262
+ }
263
+ }
264
+
265
+ class StandardRPCSerializer {
266
+ constructor(jsonSerializer) {
267
+ this.jsonSerializer = jsonSerializer;
268
+ }
269
+ serialize(data) {
270
+ if (isAsyncIteratorObject(data)) {
271
+ return mapEventIterator(data, {
272
+ value: async (value) => this.#serialize(value, false),
273
+ error: async (e) => {
274
+ return new ErrorEvent({
275
+ data: this.#serialize(toORPCError(e).toJSON(), false),
276
+ cause: e
277
+ });
278
+ }
279
+ });
280
+ }
281
+ return this.#serialize(data, true);
282
+ }
283
+ #serialize(data, enableFormData) {
284
+ const [json, meta_, maps, blobs] = this.jsonSerializer.serialize(data);
285
+ const meta = meta_.length === 0 ? void 0 : meta_;
286
+ if (!enableFormData || blobs.length === 0) {
287
+ return {
288
+ json,
289
+ meta
290
+ };
291
+ }
292
+ const form = new FormData();
293
+ form.set("data", stringifyJSON({ json, meta, maps }));
294
+ blobs.forEach((blob, i) => {
295
+ form.set(i.toString(), blob);
296
+ });
297
+ return form;
298
+ }
299
+ deserialize(data) {
300
+ if (isAsyncIteratorObject(data)) {
301
+ return mapEventIterator(data, {
302
+ value: async (value) => this.#deserialize(value),
303
+ error: async (e) => {
304
+ if (!(e instanceof ErrorEvent)) {
305
+ return e;
306
+ }
307
+ const deserialized = this.#deserialize(e.data);
308
+ if (ORPCError.isValidJSON(deserialized)) {
309
+ return ORPCError.fromJSON(deserialized, { cause: e });
310
+ }
311
+ return new ErrorEvent({
312
+ data: deserialized,
313
+ cause: e
314
+ });
315
+ }
316
+ });
317
+ }
318
+ return this.#deserialize(data);
319
+ }
320
+ #deserialize(data) {
321
+ if (!(data instanceof FormData)) {
322
+ return this.jsonSerializer.deserialize(data.json, data.meta ?? []);
323
+ }
324
+ const serialized = JSON.parse(data.get("data"));
325
+ return this.jsonSerializer.deserialize(
326
+ serialized.json,
327
+ serialized.meta ?? [],
328
+ serialized.maps,
329
+ (i) => data.get(i.toString())
330
+ );
331
+ }
332
+ }
333
+
334
+ export { InvalidEventIteratorRetryResponse as I, StandardLink as S, STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES as a, StandardRPCJsonSerializer as b, StandardRPCLinkCodec as c, StandardRPCSerializer as d };
@@ -0,0 +1,39 @@
1
+ import { Interceptor } from '@orpc/shared';
2
+ import { StandardRequest, StandardLazyResponse } from '@orpc/standard-server';
3
+ import { a as ClientContext, C as ClientOptions, b as ClientLink } from './client.RZs5Myak.mjs';
4
+
5
+ interface StandardLinkCodec<T extends ClientContext> {
6
+ encode(path: readonly string[], input: unknown, options: ClientOptions<T>): Promise<StandardRequest>;
7
+ decode(response: StandardLazyResponse, options: ClientOptions<T>, path: readonly string[], input: unknown): Promise<unknown>;
8
+ }
9
+ interface StandardLinkClient<T extends ClientContext> {
10
+ call(request: StandardRequest, options: ClientOptions<T>, path: readonly string[], input: unknown): Promise<StandardLazyResponse>;
11
+ }
12
+
13
+ declare class InvalidEventIteratorRetryResponse extends Error {
14
+ }
15
+ interface StandardLinkPlugin<T extends ClientContext> {
16
+ init?(options: StandardLinkOptions<T>): void;
17
+ }
18
+ interface StandardLinkOptions<T extends ClientContext> {
19
+ interceptors?: Interceptor<{
20
+ path: readonly string[];
21
+ input: unknown;
22
+ options: ClientOptions<T>;
23
+ }, unknown, unknown>[];
24
+ clientInterceptors?: Interceptor<{
25
+ request: StandardRequest;
26
+ }, StandardLazyResponse, unknown>[];
27
+ plugins?: StandardLinkPlugin<T>[];
28
+ }
29
+ declare class StandardLink<T extends ClientContext> implements ClientLink<T> {
30
+ #private;
31
+ readonly codec: StandardLinkCodec<T>;
32
+ readonly sender: StandardLinkClient<T>;
33
+ private readonly interceptors;
34
+ private readonly clientInterceptors;
35
+ constructor(codec: StandardLinkCodec<T>, sender: StandardLinkClient<T>, options?: StandardLinkOptions<T>);
36
+ call(path: readonly string[], input: unknown, options: ClientOptions<T>): Promise<unknown>;
37
+ }
38
+
39
+ export { InvalidEventIteratorRetryResponse as I, type StandardLinkPlugin as S, type StandardLinkOptions as a, type StandardLinkClient as b, type StandardLinkCodec as c, StandardLink as d };
@@ -0,0 +1,30 @@
1
+ type ClientContext = Record<string, any>;
2
+ type FriendlyClientOptions<TClientContext extends ClientContext> = {
3
+ signal?: AbortSignal;
4
+ lastEventId?: string | undefined;
5
+ } & (Record<never, never> extends TClientContext ? {
6
+ context?: TClientContext;
7
+ } : {
8
+ context: TClientContext;
9
+ });
10
+ 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>];
11
+ type ClientPromiseResult<TOutput, TError extends Error> = Promise<TOutput> & {
12
+ __error?: {
13
+ type: TError;
14
+ };
15
+ };
16
+ interface Client<TClientContext extends ClientContext, TInput, TOutput, TError extends Error> {
17
+ (...rest: ClientRest<TClientContext, TInput>): ClientPromiseResult<TOutput, TError>;
18
+ }
19
+ type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | {
20
+ [k: string]: NestedClient<TClientContext>;
21
+ };
22
+ type InferClientContext<T extends NestedClient<any>> = T extends NestedClient<infer U> ? U : never;
23
+ type ClientOptions<TClientContext extends ClientContext> = FriendlyClientOptions<TClientContext> & {
24
+ context: TClientContext;
25
+ };
26
+ interface ClientLink<TClientContext extends ClientContext> {
27
+ call: (path: readonly string[], input: unknown, options: ClientOptions<TClientContext>) => Promise<unknown>;
28
+ }
29
+
30
+ export type { ClientOptions as C, FriendlyClientOptions as F, InferClientContext as I, NestedClient as N, ClientContext as a, ClientLink as b, ClientPromiseResult as c, ClientRest as d, Client as e };
@@ -0,0 +1,30 @@
1
+ type ClientContext = Record<string, any>;
2
+ type FriendlyClientOptions<TClientContext extends ClientContext> = {
3
+ signal?: AbortSignal;
4
+ lastEventId?: string | undefined;
5
+ } & (Record<never, never> extends TClientContext ? {
6
+ context?: TClientContext;
7
+ } : {
8
+ context: TClientContext;
9
+ });
10
+ 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>];
11
+ type ClientPromiseResult<TOutput, TError extends Error> = Promise<TOutput> & {
12
+ __error?: {
13
+ type: TError;
14
+ };
15
+ };
16
+ interface Client<TClientContext extends ClientContext, TInput, TOutput, TError extends Error> {
17
+ (...rest: ClientRest<TClientContext, TInput>): ClientPromiseResult<TOutput, TError>;
18
+ }
19
+ type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | {
20
+ [k: string]: NestedClient<TClientContext>;
21
+ };
22
+ type InferClientContext<T extends NestedClient<any>> = T extends NestedClient<infer U> ? U : never;
23
+ type ClientOptions<TClientContext extends ClientContext> = FriendlyClientOptions<TClientContext> & {
24
+ context: TClientContext;
25
+ };
26
+ interface ClientLink<TClientContext extends ClientContext> {
27
+ call: (path: readonly string[], input: unknown, options: ClientOptions<TClientContext>) => Promise<unknown>;
28
+ }
29
+
30
+ export type { ClientOptions as C, FriendlyClientOptions as F, InferClientContext as I, NestedClient as N, ClientContext as a, ClientLink as b, ClientPromiseResult as c, ClientRest as d, Client as e };
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.172fe95",
4
+ "version": "0.0.0-next.173b319",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -15,36 +15,39 @@
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
21
  },
22
- "./fetch": {
23
- "types": "./dist/src/adapters/fetch/index.d.ts",
24
- "import": "./dist/fetch.js",
25
- "default": "./dist/fetch.js"
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"
26
31
  },
27
- "./🔒/*": {
28
- "types": "./dist/src/*.d.ts"
32
+ "./fetch": {
33
+ "types": "./dist/adapters/fetch/index.d.mts",
34
+ "import": "./dist/adapters/fetch/index.mjs",
35
+ "default": "./dist/adapters/fetch/index.mjs"
29
36
  }
30
37
  },
31
38
  "files": [
32
- "!**/*.map",
33
- "!**/*.tsbuildinfo",
34
39
  "dist"
35
40
  ],
36
41
  "dependencies": {
37
- "@tinyhttp/content-disposition": "^2.2.2",
38
- "@orpc/contract": "0.0.0-next.172fe95",
39
- "@orpc/server": "0.0.0-next.172fe95",
40
- "@orpc/shared": "0.0.0-next.172fe95"
42
+ "@orpc/shared": "0.0.0-next.173b319",
43
+ "@orpc/standard-server": "0.0.0-next.173b319",
44
+ "@orpc/standard-server-fetch": "0.0.0-next.173b319"
41
45
  },
42
46
  "devDependencies": {
43
- "zod": "^3.24.1",
44
- "@orpc/openapi": "0.0.0-next.172fe95"
47
+ "zod": "^3.24.2"
45
48
  },
46
49
  "scripts": {
47
- "build": "tsup --clean --sourcemap --entry.index=src/index.ts --entry.fetch=src/adapters/fetch/index.ts --format=esm --onSuccess='tsc -b --noCheck'",
50
+ "build": "unbuild",
48
51
  "build:watch": "pnpm run build --watch",
49
52
  "type:check": "tsc -b"
50
53
  }
package/dist/fetch.js DELETED
@@ -1,111 +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 (input === void 0) {
82
- return {
83
- body: void 0,
84
- method,
85
- headers,
86
- url
87
- };
88
- }
89
- if (isPlainObject(serialized)) {
90
- if (!headers.has("content-type")) {
91
- headers.set("content-type", "application/json");
92
- }
93
- return {
94
- body: JSON.stringify(serialized),
95
- method,
96
- headers,
97
- url
98
- };
99
- }
100
- return {
101
- body: serialized,
102
- method,
103
- headers,
104
- url
105
- };
106
- }
107
- };
108
- export {
109
- RPCLink
110
- };
111
- //# 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