@orpc/client 0.0.0-next.44bdf93 → 0.0.0-next.47e44e3

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.
package/dist/fetch.js CHANGED
@@ -1,89 +1,128 @@
1
- // src/adapters/fetch/orpc-link.ts
2
- import { ORPCError } from "@orpc/contract";
3
- import { ORPCPayloadCodec } from "@orpc/server/fetch";
4
- import { ORPC_HANDLER_HEADER, ORPC_HANDLER_VALUE, trim } from "@orpc/shared";
1
+ import {
2
+ RPCSerializer
3
+ } from "./chunk-OX3K2AN4.js";
4
+ import {
5
+ ORPCError,
6
+ createAutoRetryEventIterator
7
+ } from "./chunk-2UPNYYFF.js";
8
+
9
+ // src/adapters/fetch/rpc-link.ts
10
+ import { isAsyncIteratorObject } from "@orpc/server-standard";
11
+ import { toFetchBody, toStandardBody } from "@orpc/server-standard-fetch";
12
+ import { trim, value } from "@orpc/shared";
13
+ var InvalidEventSourceRetryResponse = class extends Error {
14
+ };
5
15
  var RPCLink = class {
6
16
  fetch;
7
- payloadCodec;
8
- maxURLLength;
17
+ rpcSerializer;
18
+ maxUrlLength;
9
19
  fallbackMethod;
10
- getMethod;
11
- getHeaders;
20
+ method;
21
+ headers;
12
22
  url;
23
+ eventSourceMaxNumberOfRetries;
24
+ eventSourceRetryDelay;
25
+ eventSourceRetry;
13
26
  constructor(options) {
14
27
  this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
15
- this.payloadCodec = options.payloadCodec ?? new ORPCPayloadCodec();
16
- this.maxURLLength = options.maxURLLength ?? 2083;
28
+ this.rpcSerializer = options.rpcSerializer ?? new RPCSerializer();
29
+ this.maxUrlLength = options.maxUrlLength ?? 2083;
17
30
  this.fallbackMethod = options.fallbackMethod ?? "POST";
18
31
  this.url = options.url;
19
- this.getMethod = async (path, input, context) => {
20
- return await options.method?.(path, input, context) ?? this.fallbackMethod;
21
- };
22
- this.getHeaders = async (path, input, context) => {
23
- return new Headers(await options.headers?.(path, input, context));
24
- };
32
+ this.eventSourceMaxNumberOfRetries = options.eventSourceMaxNumberOfRetries ?? 5;
33
+ this.method = options.method ?? this.fallbackMethod;
34
+ this.headers = options.headers ?? {};
35
+ this.eventSourceRetry = options.eventSourceRetry ?? true;
36
+ this.eventSourceRetryDelay = options.eventSourceRetryDelay ?? (({ retryTimes, lastRetry }) => lastRetry ?? 1e3 * 2 ** retryTimes);
25
37
  }
26
38
  async call(path, input, options) {
27
- const clientContext = options.context;
28
- const encoded = await this.encode(path, input, options);
39
+ const output = await this.performCall(path, input, options);
40
+ if (!isAsyncIteratorObject(output)) {
41
+ return output;
42
+ }
43
+ return createAutoRetryEventIterator(output, async (reconnectOptions) => {
44
+ if (options.signal?.aborted || reconnectOptions.retryTimes > this.eventSourceMaxNumberOfRetries) {
45
+ return null;
46
+ }
47
+ if (!await value(this.eventSourceRetry, reconnectOptions, options, path, input)) {
48
+ return null;
49
+ }
50
+ const delay = await value(this.eventSourceRetryDelay, reconnectOptions, options, path, input);
51
+ await new Promise((resolve) => setTimeout(resolve, delay));
52
+ const updatedOptions = { ...options, lastEventId: reconnectOptions.lastEventId };
53
+ const maybeIterator = await this.performCall(path, input, updatedOptions);
54
+ if (!isAsyncIteratorObject(maybeIterator)) {
55
+ throw new InvalidEventSourceRetryResponse("Invalid EventSource retry response");
56
+ }
57
+ return maybeIterator;
58
+ }, void 0);
59
+ }
60
+ async performCall(path, input, options) {
61
+ const encoded = await this.encodeRequest(path, input, options);
62
+ const fetchBody = toFetchBody(encoded.body, encoded.headers);
63
+ if (options.lastEventId !== void 0) {
64
+ encoded.headers.set("last-event-id", options.lastEventId);
65
+ }
29
66
  const response = await this.fetch(encoded.url, {
30
67
  method: encoded.method,
31
68
  headers: encoded.headers,
32
- body: encoded.body,
69
+ body: fetchBody,
33
70
  signal: options.signal
34
- }, clientContext);
35
- const decoded = await this.payloadCodec.decode(response);
71
+ }, options, path, input);
72
+ const body = await toStandardBody(response);
73
+ const deserialized = (() => {
74
+ try {
75
+ return this.rpcSerializer.deserialize(body);
76
+ } catch (error) {
77
+ if (response.ok) {
78
+ throw new ORPCError("INTERNAL_SERVER_ERROR", {
79
+ message: "Invalid RPC response",
80
+ cause: error
81
+ });
82
+ }
83
+ throw new ORPCError(response.status.toString(), {
84
+ message: response.statusText
85
+ });
86
+ }
87
+ })();
36
88
  if (!response.ok) {
37
- if (ORPCError.isValidJSON(decoded)) {
38
- throw new ORPCError(decoded);
89
+ if (ORPCError.isValidJSON(deserialized)) {
90
+ throw ORPCError.fromJSON(deserialized);
39
91
  }
40
- throw new ORPCError({
41
- status: response.status,
42
- code: "INTERNAL_SERVER_ERROR",
43
- message: "Internal server error",
44
- cause: decoded
92
+ throw new ORPCError("INTERNAL_SERVER_ERROR", {
93
+ message: "Invalid RPC error response",
94
+ cause: deserialized
45
95
  });
46
96
  }
47
- return decoded;
97
+ return deserialized;
48
98
  }
49
- async encode(path, input, options) {
50
- const clientContext = options.context;
51
- const expectMethod = await this.getMethod(path, input, clientContext);
52
- const methods = /* @__PURE__ */ new Set([expectMethod, this.fallbackMethod]);
53
- const baseHeaders = await this.getHeaders(path, input, clientContext);
54
- const baseUrl = new URL(`${trim(this.url, "/")}/${path.map(encodeURIComponent).join("/")}`);
55
- baseHeaders.append(ORPC_HANDLER_HEADER, ORPC_HANDLER_VALUE);
56
- for (const method of methods) {
57
- const url = new URL(baseUrl);
58
- const headers = new Headers(baseHeaders);
59
- const encoded = this.payloadCodec.encode(input, method, this.fallbackMethod);
60
- if (encoded.query) {
61
- for (const [key, value] of encoded.query.entries()) {
62
- url.searchParams.append(key, value);
63
- }
99
+ async encodeRequest(path, input, options) {
100
+ const expectedMethod = await value(this.method, options, path, input);
101
+ const headers = new Headers(await value(this.headers, options, path, input));
102
+ const url = new URL(`${trim(this.url, "/")}/${path.map(encodeURIComponent).join("/")}`);
103
+ const serialized = this.rpcSerializer.serialize(input);
104
+ if (expectedMethod === "GET" && !(serialized instanceof FormData) && !(serialized instanceof Blob) && !isAsyncIteratorObject(serialized)) {
105
+ const getUrl = new URL(url);
106
+ getUrl.searchParams.append("data", JSON.stringify(serialized) ?? "");
107
+ if (getUrl.toString().length <= this.maxUrlLength) {
108
+ return {
109
+ body: void 0,
110
+ method: expectedMethod,
111
+ headers,
112
+ url: getUrl
113
+ };
64
114
  }
65
- if (url.toString().length > this.maxURLLength) {
66
- continue;
67
- }
68
- if (encoded.headers) {
69
- for (const [key, value] of encoded.headers.entries()) {
70
- headers.append(key, value);
71
- }
72
- }
73
- return {
74
- url,
75
- headers,
76
- method: encoded.method,
77
- body: encoded.body
78
- };
79
115
  }
80
- throw new ORPCError({
81
- code: "BAD_REQUEST",
82
- message: "Cannot encode the request, please check the url length or payload."
83
- });
116
+ return {
117
+ url,
118
+ method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
119
+ headers,
120
+ body: serialized
121
+ };
84
122
  }
85
123
  };
86
124
  export {
125
+ InvalidEventSourceRetryResponse,
87
126
  RPCLink
88
127
  };
89
128
  //# sourceMappingURL=fetch.js.map
package/dist/index.js CHANGED
@@ -1,8 +1,27 @@
1
+ import {
2
+ COMMON_ORPC_ERROR_DEFS,
3
+ ORPCError,
4
+ createAutoRetryEventIterator,
5
+ fallbackORPCErrorMessage,
6
+ fallbackORPCErrorStatus,
7
+ isDefinedError,
8
+ mapEventIterator,
9
+ onEventIteratorStatusChange,
10
+ registerEventIteratorState,
11
+ toORPCError,
12
+ updateEventIteratorStatus
13
+ } from "./chunk-2UPNYYFF.js";
14
+
1
15
  // src/client.ts
2
16
  function createORPCClient(link, options) {
3
17
  const path = options?.path ?? [];
4
18
  const procedureClient = async (...[input, options2]) => {
5
- return await link.call(path, input, options2 ?? {});
19
+ const optionsOut = {
20
+ ...options2,
21
+ context: options2?.context ?? {}
22
+ // options.context can be undefined when all field is optional
23
+ };
24
+ return await link.call(path, input, optionsOut);
6
25
  };
7
26
  const recursive = new Proxy(procedureClient, {
8
27
  get(target, key) {
@@ -24,19 +43,39 @@ var DynamicLink = class {
24
43
  this.linkResolver = linkResolver;
25
44
  }
26
45
  async call(path, input, options) {
27
- const resolvedLink = await this.linkResolver(path, input, options.context);
46
+ const resolvedLink = await this.linkResolver(options, path, input);
28
47
  const output = await resolvedLink.call(path, input, options);
29
48
  return output;
30
49
  }
31
50
  };
32
51
 
33
- // src/index.ts
34
- import { isDefinedError, ORPCError, safe } from "@orpc/contract";
52
+ // src/utils.ts
53
+ async function safe(promise) {
54
+ try {
55
+ const output = await promise;
56
+ return [output, void 0, false];
57
+ } catch (e) {
58
+ const error = e;
59
+ if (isDefinedError(error)) {
60
+ return [void 0, error, true];
61
+ }
62
+ return [void 0, error, false];
63
+ }
64
+ }
35
65
  export {
66
+ COMMON_ORPC_ERROR_DEFS,
36
67
  DynamicLink,
37
68
  ORPCError,
69
+ createAutoRetryEventIterator,
38
70
  createORPCClient,
71
+ fallbackORPCErrorMessage,
72
+ fallbackORPCErrorStatus,
39
73
  isDefinedError,
40
- safe
74
+ mapEventIterator,
75
+ onEventIteratorStatusChange,
76
+ registerEventIteratorState,
77
+ safe,
78
+ toORPCError,
79
+ updateEventIteratorStatus
41
80
  };
42
81
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,330 @@
1
+ import {
2
+ ORPCError,
3
+ __export,
4
+ mapEventIterator,
5
+ toORPCError
6
+ } from "./chunk-2UPNYYFF.js";
7
+
8
+ // src/openapi/bracket-notation.ts
9
+ var bracket_notation_exports = {};
10
+ __export(bracket_notation_exports, {
11
+ deserialize: () => deserialize,
12
+ escapeSegment: () => escapeSegment,
13
+ parsePath: () => parsePath,
14
+ serialize: () => serialize,
15
+ stringifyPath: () => stringifyPath
16
+ });
17
+ import { isObject } from "@orpc/shared";
18
+ function serialize(payload, parentKey = "") {
19
+ if (!Array.isArray(payload) && !isObject(payload))
20
+ return [["", payload]];
21
+ const result = [];
22
+ function helper(value, path) {
23
+ if (Array.isArray(value)) {
24
+ value.forEach((item, index) => {
25
+ helper(item, [...path, String(index)]);
26
+ });
27
+ } else if (isObject(value)) {
28
+ for (const [key, val] of Object.entries(value)) {
29
+ helper(val, [...path, key]);
30
+ }
31
+ } else {
32
+ result.push([stringifyPath(path), value]);
33
+ }
34
+ }
35
+ helper(payload, parentKey ? [parentKey] : []);
36
+ return result;
37
+ }
38
+ function deserialize(entities) {
39
+ if (entities.length === 0) {
40
+ return void 0;
41
+ }
42
+ const isRootArray = entities.every(([path]) => path === "");
43
+ const result = isRootArray ? [] : {};
44
+ const arrayPushPaths = /* @__PURE__ */ new Set();
45
+ for (const [path, _] of entities) {
46
+ const segments = parsePath(path);
47
+ const base = segments.slice(0, -1).join(".");
48
+ const last = segments[segments.length - 1];
49
+ if (last === "") {
50
+ arrayPushPaths.add(base);
51
+ } else {
52
+ arrayPushPaths.delete(base);
53
+ }
54
+ }
55
+ function setValue(obj, segments, value, fullPath) {
56
+ const [first, ...rest_] = segments;
57
+ if (Array.isArray(obj) && first === "") {
58
+ ;
59
+ obj.push(value);
60
+ return;
61
+ }
62
+ const objAsRecord = obj;
63
+ if (rest_.length === 0) {
64
+ objAsRecord[first] = value;
65
+ return;
66
+ }
67
+ const rest = rest_;
68
+ if (rest[0] === "") {
69
+ const pathToCheck = segments.slice(0, -1).join(".");
70
+ if (rest.length === 1 && arrayPushPaths.has(pathToCheck)) {
71
+ if (!(first in objAsRecord)) {
72
+ objAsRecord[first] = [];
73
+ }
74
+ if (Array.isArray(objAsRecord[first])) {
75
+ ;
76
+ objAsRecord[first].push(value);
77
+ return;
78
+ }
79
+ }
80
+ if (!(first in objAsRecord)) {
81
+ objAsRecord[first] = {};
82
+ }
83
+ const target = objAsRecord[first];
84
+ target[""] = value;
85
+ return;
86
+ }
87
+ if (!(first in objAsRecord)) {
88
+ objAsRecord[first] = {};
89
+ }
90
+ setValue(
91
+ objAsRecord[first],
92
+ rest,
93
+ value,
94
+ fullPath
95
+ );
96
+ }
97
+ for (const [path, value] of entities) {
98
+ const segments = parsePath(path);
99
+ setValue(result, segments, value, path);
100
+ }
101
+ return result;
102
+ }
103
+ function escapeSegment(segment) {
104
+ return segment.replace(/[\\[\]]/g, (match) => {
105
+ switch (match) {
106
+ case "\\":
107
+ return "\\\\";
108
+ case "[":
109
+ return "\\[";
110
+ case "]":
111
+ return "\\]";
112
+ default:
113
+ return match;
114
+ }
115
+ });
116
+ }
117
+ function stringifyPath(path) {
118
+ const [first, ...rest] = path;
119
+ const firstSegment = escapeSegment(first);
120
+ const base = first === "" ? "" : firstSegment;
121
+ return rest.reduce(
122
+ (result, segment) => `${result}[${escapeSegment(segment)}]`,
123
+ base
124
+ );
125
+ }
126
+ function parsePath(path) {
127
+ if (path === "")
128
+ return [""];
129
+ const result = [];
130
+ let currentSegment = "";
131
+ let inBracket = false;
132
+ let bracketContent = "";
133
+ let backslashCount = 0;
134
+ for (let i = 0; i < path.length; i++) {
135
+ const char = path[i];
136
+ if (char === "\\") {
137
+ backslashCount++;
138
+ continue;
139
+ }
140
+ if (backslashCount > 0) {
141
+ const literalBackslashes = "\\".repeat(Math.floor(backslashCount / 2));
142
+ if (char === "[" || char === "]") {
143
+ if (backslashCount % 2 === 1) {
144
+ if (inBracket) {
145
+ bracketContent += literalBackslashes + char;
146
+ } else {
147
+ currentSegment += literalBackslashes + char;
148
+ }
149
+ } else {
150
+ if (inBracket) {
151
+ bracketContent += literalBackslashes;
152
+ } else {
153
+ currentSegment += literalBackslashes;
154
+ }
155
+ if (char === "[" && !inBracket) {
156
+ if (currentSegment !== "" || result.length === 0) {
157
+ result.push(currentSegment);
158
+ }
159
+ inBracket = true;
160
+ bracketContent = "";
161
+ currentSegment = "";
162
+ } else if (char === "]" && inBracket) {
163
+ result.push(bracketContent);
164
+ inBracket = false;
165
+ bracketContent = "";
166
+ } else {
167
+ if (inBracket) {
168
+ bracketContent += char;
169
+ } else {
170
+ currentSegment += char;
171
+ }
172
+ }
173
+ }
174
+ } else {
175
+ const allBackslashes = "\\".repeat(backslashCount);
176
+ if (inBracket) {
177
+ bracketContent += allBackslashes + char;
178
+ } else {
179
+ currentSegment += allBackslashes + char;
180
+ }
181
+ }
182
+ backslashCount = 0;
183
+ continue;
184
+ }
185
+ if (char === "[" && !inBracket) {
186
+ if (currentSegment !== "" || result.length === 0) {
187
+ result.push(currentSegment);
188
+ }
189
+ inBracket = true;
190
+ bracketContent = "";
191
+ currentSegment = "";
192
+ continue;
193
+ }
194
+ if (char === "]" && inBracket) {
195
+ result.push(bracketContent);
196
+ inBracket = false;
197
+ bracketContent = "";
198
+ continue;
199
+ }
200
+ if (inBracket) {
201
+ bracketContent += char;
202
+ } else {
203
+ currentSegment += char;
204
+ }
205
+ }
206
+ if (backslashCount > 0) {
207
+ const remainingBackslashes = "\\".repeat(backslashCount);
208
+ if (inBracket) {
209
+ bracketContent += remainingBackslashes;
210
+ } else {
211
+ currentSegment += remainingBackslashes;
212
+ }
213
+ }
214
+ if (inBracket) {
215
+ if (currentSegment !== "" || result.length === 0) {
216
+ result.push(currentSegment);
217
+ }
218
+ result.push(`[${bracketContent}`);
219
+ } else if (currentSegment !== "" || result.length === 0) {
220
+ result.push(currentSegment);
221
+ }
222
+ return result;
223
+ }
224
+
225
+ // src/openapi/json-serializer.ts
226
+ import { isObject as isObject2 } from "@orpc/shared";
227
+ var OpenAPIJsonSerializer = class {
228
+ serialize(data, hasBlobRef = { value: false }) {
229
+ if (data instanceof Blob) {
230
+ hasBlobRef.value = true;
231
+ return [data, hasBlobRef.value];
232
+ }
233
+ if (data instanceof Set) {
234
+ return this.serialize(Array.from(data), hasBlobRef);
235
+ }
236
+ if (data instanceof Map) {
237
+ return this.serialize(Array.from(data.entries()), hasBlobRef);
238
+ }
239
+ if (Array.isArray(data)) {
240
+ const json = data.map((v) => v === void 0 ? null : this.serialize(v, hasBlobRef)[0]);
241
+ return [json, hasBlobRef.value];
242
+ }
243
+ if (isObject2(data)) {
244
+ const json = {};
245
+ for (const k in data) {
246
+ json[k] = this.serialize(data[k], hasBlobRef)[0];
247
+ }
248
+ return [json, hasBlobRef.value];
249
+ }
250
+ if (typeof data === "bigint" || data instanceof RegExp || data instanceof URL) {
251
+ return [data.toString(), hasBlobRef.value];
252
+ }
253
+ if (data instanceof Date) {
254
+ return [Number.isNaN(data.getTime()) ? null : data.toISOString(), hasBlobRef.value];
255
+ }
256
+ if (Number.isNaN(data)) {
257
+ return [null, hasBlobRef.value];
258
+ }
259
+ return [data, hasBlobRef.value];
260
+ }
261
+ };
262
+
263
+ // src/openapi/serializer.ts
264
+ import { ErrorEvent, isAsyncIteratorObject } from "@orpc/server-standard";
265
+ var OpenAPISerializer = class {
266
+ constructor(jsonSerializer = new OpenAPIJsonSerializer()) {
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
+ if (e instanceof ErrorEvent) {
275
+ return new ErrorEvent({
276
+ data: this.#serialize(e.data, false),
277
+ cause: e
278
+ });
279
+ }
280
+ return new ErrorEvent({
281
+ data: this.#serialize(toORPCError(e).toJSON(), false),
282
+ cause: e
283
+ });
284
+ }
285
+ });
286
+ }
287
+ return this.#serialize(data, true);
288
+ }
289
+ #serialize(data, enableFormData) {
290
+ if (data instanceof Blob || data === void 0) {
291
+ return data;
292
+ }
293
+ const [json, hasBlob] = this.jsonSerializer.serialize(data);
294
+ if (!enableFormData || !hasBlob) {
295
+ return json;
296
+ }
297
+ const form = new FormData();
298
+ for (const [path, value] of serialize(json)) {
299
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
300
+ form.append(path, value.toString());
301
+ } else if (value instanceof Blob) {
302
+ form.append(path, value);
303
+ }
304
+ }
305
+ return form;
306
+ }
307
+ deserialize(data) {
308
+ if (data instanceof URLSearchParams || data instanceof FormData) {
309
+ return deserialize(Array.from(data.entries()));
310
+ }
311
+ if (isAsyncIteratorObject(data)) {
312
+ return mapEventIterator(data, {
313
+ value: async (value) => value,
314
+ error: async (e) => {
315
+ if (e instanceof ErrorEvent && ORPCError.isValidJSON(e.data)) {
316
+ return ORPCError.fromJSON(e.data, { cause: e });
317
+ }
318
+ return e;
319
+ }
320
+ });
321
+ }
322
+ return data;
323
+ }
324
+ };
325
+ export {
326
+ bracket_notation_exports as BracketNotation,
327
+ OpenAPIJsonSerializer,
328
+ OpenAPISerializer
329
+ };
330
+ //# sourceMappingURL=openapi.js.map
package/dist/rpc.js ADDED
@@ -0,0 +1,10 @@
1
+ import {
2
+ RPCJsonSerializer,
3
+ RPCSerializer
4
+ } from "./chunk-OX3K2AN4.js";
5
+ import "./chunk-2UPNYYFF.js";
6
+ export {
7
+ RPCJsonSerializer,
8
+ RPCSerializer
9
+ };
10
+ //# sourceMappingURL=rpc.js.map
@@ -1,3 +1,3 @@
1
- export * from './orpc-link';
1
+ export * from './rpc-link';
2
2
  export * from './types';
3
3
  //# sourceMappingURL=index.d.ts.map