@orpc/client 0.39.0 → 0.41.0

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,288 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/error.ts
8
+ import { isObject } from "@orpc/shared";
9
+ var COMMON_ORPC_ERROR_DEFS = {
10
+ BAD_REQUEST: {
11
+ status: 400,
12
+ message: "Bad Request"
13
+ },
14
+ UNAUTHORIZED: {
15
+ status: 401,
16
+ message: "Unauthorized"
17
+ },
18
+ FORBIDDEN: {
19
+ status: 403,
20
+ message: "Forbidden"
21
+ },
22
+ NOT_FOUND: {
23
+ status: 404,
24
+ message: "Not Found"
25
+ },
26
+ METHOD_NOT_SUPPORTED: {
27
+ status: 405,
28
+ message: "Method Not Supported"
29
+ },
30
+ NOT_ACCEPTABLE: {
31
+ status: 406,
32
+ message: "Not Acceptable"
33
+ },
34
+ TIMEOUT: {
35
+ status: 408,
36
+ message: "Request Timeout"
37
+ },
38
+ CONFLICT: {
39
+ status: 409,
40
+ message: "Conflict"
41
+ },
42
+ PRECONDITION_FAILED: {
43
+ status: 412,
44
+ message: "Precondition Failed"
45
+ },
46
+ PAYLOAD_TOO_LARGE: {
47
+ status: 413,
48
+ message: "Payload Too Large"
49
+ },
50
+ UNSUPPORTED_MEDIA_TYPE: {
51
+ status: 415,
52
+ message: "Unsupported Media Type"
53
+ },
54
+ UNPROCESSABLE_CONTENT: {
55
+ status: 422,
56
+ message: "Unprocessable Content"
57
+ },
58
+ TOO_MANY_REQUESTS: {
59
+ status: 429,
60
+ message: "Too Many Requests"
61
+ },
62
+ CLIENT_CLOSED_REQUEST: {
63
+ status: 499,
64
+ message: "Client Closed Request"
65
+ },
66
+ INTERNAL_SERVER_ERROR: {
67
+ status: 500,
68
+ message: "Internal Server Error"
69
+ },
70
+ NOT_IMPLEMENTED: {
71
+ status: 501,
72
+ message: "Not Implemented"
73
+ },
74
+ BAD_GATEWAY: {
75
+ status: 502,
76
+ message: "Bad Gateway"
77
+ },
78
+ SERVICE_UNAVAILABLE: {
79
+ status: 503,
80
+ message: "Service Unavailable"
81
+ },
82
+ GATEWAY_TIMEOUT: {
83
+ status: 504,
84
+ message: "Gateway Timeout"
85
+ }
86
+ };
87
+ function fallbackORPCErrorStatus(code, status) {
88
+ return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
89
+ }
90
+ function fallbackORPCErrorMessage(code, message) {
91
+ return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
92
+ }
93
+ var ORPCError = class _ORPCError extends Error {
94
+ defined;
95
+ code;
96
+ status;
97
+ data;
98
+ constructor(code, ...[options]) {
99
+ if (options?.status && (options.status < 400 || options.status >= 600)) {
100
+ throw new Error("[ORPCError] The error status code must be in the 400-599 range.");
101
+ }
102
+ const message = fallbackORPCErrorMessage(code, options?.message);
103
+ super(message, options);
104
+ this.code = code;
105
+ this.status = fallbackORPCErrorStatus(code, options?.status);
106
+ this.defined = options?.defined ?? false;
107
+ this.data = options?.data;
108
+ }
109
+ toJSON() {
110
+ return {
111
+ defined: this.defined,
112
+ code: this.code,
113
+ status: this.status,
114
+ message: this.message,
115
+ data: this.data
116
+ };
117
+ }
118
+ static fromJSON(json, options) {
119
+ return new _ORPCError(json.code, {
120
+ ...options,
121
+ ...json
122
+ });
123
+ }
124
+ static isValidJSON(json) {
125
+ if (!isObject(json)) {
126
+ return false;
127
+ }
128
+ const validKeys = ["defined", "code", "status", "message", "data"];
129
+ if (Object.keys(json).some((k) => !validKeys.includes(k))) {
130
+ return false;
131
+ }
132
+ return "defined" in json && typeof json.defined === "boolean" && "code" in json && typeof json.code === "string" && "status" in json && typeof json.status === "number" && "message" in json && typeof json.message === "string";
133
+ }
134
+ };
135
+ function isDefinedError(error) {
136
+ return error instanceof ORPCError && error.defined;
137
+ }
138
+ function toORPCError(error) {
139
+ return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", {
140
+ message: "Internal server error",
141
+ cause: error
142
+ });
143
+ }
144
+
145
+ // src/event-iterator-state.ts
146
+ var iteratorStates = /* @__PURE__ */ new WeakMap();
147
+ function registerEventIteratorState(iterator, state) {
148
+ iteratorStates.set(iterator, state);
149
+ }
150
+ function updateEventIteratorStatus(state, status) {
151
+ if (state.status !== status) {
152
+ state.status = status;
153
+ state.listeners.forEach((cb) => cb(status));
154
+ }
155
+ }
156
+ function onEventIteratorStatusChange(iterator, callback, notifyImmediately = true) {
157
+ const state = iteratorStates.get(iterator);
158
+ if (!state) {
159
+ throw new Error("Iterator is not registered.");
160
+ }
161
+ if (notifyImmediately) {
162
+ callback(state.status);
163
+ }
164
+ state.listeners.push(callback);
165
+ return () => {
166
+ const index = state.listeners.indexOf(callback);
167
+ if (index !== -1) {
168
+ state.listeners.splice(index, 1);
169
+ }
170
+ };
171
+ }
172
+
173
+ // src/event-iterator.ts
174
+ import { getEventMeta, isEventMetaContainer, withEventMeta } from "@orpc/server-standard";
175
+ import { retry } from "@orpc/shared";
176
+ function mapEventIterator(iterator, maps) {
177
+ return async function* () {
178
+ try {
179
+ while (true) {
180
+ const { done, value } = await iterator.next();
181
+ let mappedValue = await maps.value(value, done);
182
+ if (mappedValue !== value) {
183
+ const meta = getEventMeta(value);
184
+ if (meta && isEventMetaContainer(mappedValue)) {
185
+ mappedValue = withEventMeta(mappedValue, meta);
186
+ }
187
+ }
188
+ if (done) {
189
+ return mappedValue;
190
+ }
191
+ yield mappedValue;
192
+ }
193
+ } catch (error) {
194
+ let mappedError = await maps.error(error);
195
+ if (mappedError !== error) {
196
+ const meta = getEventMeta(error);
197
+ if (meta && isEventMetaContainer(mappedError)) {
198
+ mappedError = withEventMeta(mappedError, meta);
199
+ }
200
+ }
201
+ throw mappedError;
202
+ } finally {
203
+ await iterator.return?.();
204
+ }
205
+ }();
206
+ }
207
+ var MAX_ALLOWED_RETRY_TIMES = 99;
208
+ function createAutoRetryEventIterator(initial, reconnect, initialLastEventId) {
209
+ const state = {
210
+ status: "connected",
211
+ listeners: []
212
+ };
213
+ const iterator = async function* () {
214
+ let current = initial;
215
+ let lastEventId = initialLastEventId;
216
+ let lastRetry;
217
+ let retryTimes = 0;
218
+ try {
219
+ while (true) {
220
+ try {
221
+ updateEventIteratorStatus(state, "connected");
222
+ const { done, value } = await current.next();
223
+ const meta = getEventMeta(value);
224
+ lastEventId = meta?.id ?? lastEventId;
225
+ lastRetry = meta?.retry ?? lastRetry;
226
+ retryTimes = 0;
227
+ if (done) {
228
+ return value;
229
+ }
230
+ yield value;
231
+ } catch (e) {
232
+ updateEventIteratorStatus(state, "reconnecting");
233
+ const meta = getEventMeta(e);
234
+ lastEventId = meta?.id ?? lastEventId;
235
+ lastRetry = meta?.retry ?? lastRetry;
236
+ let currentError = e;
237
+ current = await retry({ times: MAX_ALLOWED_RETRY_TIMES }, async (exit) => {
238
+ retryTimes += 1;
239
+ if (retryTimes > MAX_ALLOWED_RETRY_TIMES) {
240
+ throw exit(new Error(
241
+ `Exceeded maximum retry attempts (${MAX_ALLOWED_RETRY_TIMES}) for event source. Possible infinite retry loop detected. Please review the retry logic.`,
242
+ { cause: currentError }
243
+ ));
244
+ }
245
+ const reconnected = await (async () => {
246
+ try {
247
+ return await reconnect({
248
+ lastRetry,
249
+ lastEventId,
250
+ retryTimes,
251
+ error: currentError
252
+ });
253
+ } catch (e2) {
254
+ currentError = e2;
255
+ throw e2;
256
+ }
257
+ })();
258
+ if (!reconnected) {
259
+ throw exit(currentError);
260
+ }
261
+ return reconnected;
262
+ });
263
+ }
264
+ }
265
+ } finally {
266
+ updateEventIteratorStatus(state, "closed");
267
+ await current.return?.();
268
+ }
269
+ }();
270
+ registerEventIteratorState(iterator, state);
271
+ return iterator;
272
+ }
273
+
274
+ export {
275
+ __export,
276
+ COMMON_ORPC_ERROR_DEFS,
277
+ fallbackORPCErrorStatus,
278
+ fallbackORPCErrorMessage,
279
+ ORPCError,
280
+ isDefinedError,
281
+ toORPCError,
282
+ registerEventIteratorState,
283
+ updateEventIteratorStatus,
284
+ onEventIteratorStatusChange,
285
+ mapEventIterator,
286
+ createAutoRetryEventIterator
287
+ };
288
+ //# sourceMappingURL=chunk-2UPNYYFF.js.map
@@ -0,0 +1,178 @@
1
+ import {
2
+ ORPCError,
3
+ mapEventIterator,
4
+ toORPCError
5
+ } from "./chunk-2UPNYYFF.js";
6
+
7
+ // src/rpc/serializer.ts
8
+ import { ErrorEvent, isAsyncIteratorObject } from "@orpc/server-standard";
9
+ import { findDeepMatches, isObject, set } from "@orpc/shared";
10
+ var RPCSerializer = class {
11
+ serialize(data) {
12
+ if (isAsyncIteratorObject(data)) {
13
+ return mapEventIterator(data, {
14
+ value: async (value) => serializeRPCJson(value),
15
+ error: async (e) => {
16
+ if (e instanceof ErrorEvent) {
17
+ return new ErrorEvent({
18
+ data: serializeRPCJson(e.data),
19
+ cause: e
20
+ });
21
+ }
22
+ return new ErrorEvent({
23
+ data: serializeRPCJson(toORPCError(e).toJSON()),
24
+ cause: e
25
+ });
26
+ }
27
+ });
28
+ }
29
+ const serializedJSON = serializeRPCJson(data);
30
+ const { maps, values: blobs } = findDeepMatches((v) => v instanceof Blob, serializedJSON.json);
31
+ if (blobs.length === 0) {
32
+ return serializedJSON;
33
+ }
34
+ const form = new FormData();
35
+ form.set("data", JSON.stringify(serializedJSON));
36
+ form.set("maps", JSON.stringify(maps));
37
+ for (const i in blobs) {
38
+ form.set(i, blobs[i]);
39
+ }
40
+ return form;
41
+ }
42
+ deserialize(serialized) {
43
+ if (isAsyncIteratorObject(serialized)) {
44
+ return mapEventIterator(serialized, {
45
+ value: async (value) => deserializeRPCJson(value),
46
+ error: async (e) => {
47
+ if (!(e instanceof ErrorEvent)) {
48
+ return e;
49
+ }
50
+ const deserialized = deserializeRPCJson(e.data);
51
+ if (ORPCError.isValidJSON(deserialized)) {
52
+ return ORPCError.fromJSON(deserialized, { cause: e });
53
+ }
54
+ return new ErrorEvent({
55
+ data: deserialized,
56
+ cause: e
57
+ });
58
+ }
59
+ });
60
+ }
61
+ if (!(serialized instanceof FormData)) {
62
+ return deserializeRPCJson(serialized);
63
+ }
64
+ const data = JSON.parse(serialized.get("data"));
65
+ const maps = JSON.parse(serialized.get("maps"));
66
+ for (const i in maps) {
67
+ data.json = set(data.json, maps[i], serialized.get(i));
68
+ }
69
+ return deserializeRPCJson(data);
70
+ }
71
+ };
72
+ function serializeRPCJson(value, segments = [], meta = []) {
73
+ if (typeof value === "bigint") {
74
+ meta.push(["bigint", segments]);
75
+ return { json: value.toString(), meta };
76
+ }
77
+ if (value instanceof Date) {
78
+ meta.push(["date", segments]);
79
+ const data = Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
80
+ return { json: data, meta };
81
+ }
82
+ if (Number.isNaN(value)) {
83
+ meta.push(["nan", segments]);
84
+ return { json: "NaN", meta };
85
+ }
86
+ if (value instanceof RegExp) {
87
+ meta.push(["regexp", segments]);
88
+ return { json: value.toString(), meta };
89
+ }
90
+ if (value instanceof URL) {
91
+ meta.push(["url", segments]);
92
+ return { json: value.toString(), meta };
93
+ }
94
+ if (isObject(value)) {
95
+ const json = {};
96
+ for (const k in value) {
97
+ json[k] = serializeRPCJson(value[k], [...segments, k], meta).json;
98
+ }
99
+ return { json, meta };
100
+ }
101
+ if (Array.isArray(value)) {
102
+ const json = value.map((v, i) => {
103
+ if (v === void 0) {
104
+ meta.push(["undefined", [...segments, i]]);
105
+ return null;
106
+ }
107
+ return serializeRPCJson(v, [...segments, i], meta).json;
108
+ });
109
+ return { json, meta };
110
+ }
111
+ if (value instanceof Set) {
112
+ const result = serializeRPCJson(Array.from(value), segments, meta);
113
+ meta.push(["set", segments]);
114
+ return result;
115
+ }
116
+ if (value instanceof Map) {
117
+ const result = serializeRPCJson(Array.from(value.entries()), segments, meta);
118
+ meta.push(["map", segments]);
119
+ return result;
120
+ }
121
+ return { json: value, meta };
122
+ }
123
+ function deserializeRPCJson({
124
+ json,
125
+ meta
126
+ }) {
127
+ if (meta.length === 0) {
128
+ return json;
129
+ }
130
+ const ref = { data: json };
131
+ for (const [type, segments] of meta) {
132
+ let currentRef = ref;
133
+ let preSegment = "data";
134
+ for (let i = 0; i < segments.length; i++) {
135
+ currentRef = currentRef[preSegment];
136
+ preSegment = segments[i];
137
+ }
138
+ switch (type) {
139
+ case "nan":
140
+ currentRef[preSegment] = Number.NaN;
141
+ break;
142
+ case "bigint":
143
+ currentRef[preSegment] = BigInt(currentRef[preSegment]);
144
+ break;
145
+ case "date":
146
+ currentRef[preSegment] = new Date(currentRef[preSegment]);
147
+ break;
148
+ case "regexp": {
149
+ const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
150
+ currentRef[preSegment] = new RegExp(pattern, flags);
151
+ break;
152
+ }
153
+ case "url":
154
+ currentRef[preSegment] = new URL(currentRef[preSegment]);
155
+ break;
156
+ case "undefined":
157
+ currentRef[preSegment] = void 0;
158
+ break;
159
+ case "map":
160
+ currentRef[preSegment] = new Map(currentRef[preSegment]);
161
+ break;
162
+ case "set":
163
+ currentRef[preSegment] = new Set(currentRef[preSegment]);
164
+ break;
165
+ /* v8 ignore next 3 */
166
+ default: {
167
+ const _expected = type;
168
+ }
169
+ }
170
+ }
171
+ return ref.data;
172
+ }
173
+
174
+ export {
175
+ RPCSerializer,
176
+ serializeRPCJson
177
+ };
178
+ //# sourceMappingURL=chunk-TPEMQB7D.js.map
package/dist/fetch.js CHANGED
@@ -1,42 +1,74 @@
1
- // src/adapters/fetch/orpc-link.ts
2
- import { ORPCError } from "@orpc/contract";
3
- import { toStandardBody } from "@orpc/server-standard-fetch";
4
- import { RPCSerializer } from "@orpc/server/standard";
5
- import { isObject, trim } from "@orpc/shared";
6
- import { contentDisposition } from "@tinyhttp/content-disposition";
1
+ import {
2
+ RPCSerializer
3
+ } from "./chunk-TPEMQB7D.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
+ };
7
15
  var RPCLink = class {
8
16
  fetch;
9
17
  rpcSerializer;
10
- maxURLLength;
18
+ maxUrlLength;
11
19
  fallbackMethod;
12
- getMethod;
13
- getHeaders;
20
+ method;
21
+ headers;
14
22
  url;
23
+ eventSourceMaxNumberOfRetries;
24
+ eventSourceRetryDelay;
25
+ eventSourceRetry;
15
26
  constructor(options) {
16
27
  this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
17
28
  this.rpcSerializer = options.rpcSerializer ?? new RPCSerializer();
18
- this.maxURLLength = options.maxURLLength ?? 2083;
29
+ this.maxUrlLength = options.maxUrlLength ?? 2083;
19
30
  this.fallbackMethod = options.fallbackMethod ?? "POST";
20
31
  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
- };
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);
27
37
  }
28
38
  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"));
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);
33
65
  }
34
66
  const response = await this.fetch(encoded.url, {
35
67
  method: encoded.method,
36
68
  headers: encoded.headers,
37
- body: encoded.body,
69
+ body: fetchBody,
38
70
  signal: options.signal
39
- }, clientContext);
71
+ }, options, path, input);
40
72
  const body = await toStandardBody(response);
41
73
  const deserialized = (() => {
42
74
  try {
@@ -53,59 +85,44 @@ var RPCLink = class {
53
85
  });
54
86
  }
55
87
  })();
56
- if (response.ok) {
57
- return deserialized;
88
+ if (!response.ok) {
89
+ if (ORPCError.isValidJSON(deserialized)) {
90
+ throw ORPCError.fromJSON(deserialized);
91
+ }
92
+ throw new ORPCError("INTERNAL_SERVER_ERROR", {
93
+ message: "Invalid RPC error response",
94
+ cause: deserialized
95
+ });
58
96
  }
59
- throw ORPCError.fromJSON(deserialized);
97
+ return deserialized;
60
98
  }
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);
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));
65
102
  const url = new URL(`${trim(this.url, "/")}/${path.map(encodeURIComponent).join("/")}`);
66
- headers.append("x-orpc-handler", "rpc");
67
103
  const serialized = this.rpcSerializer.serialize(input);
68
- if (expectMethod === "GET" && isObject(serialized)) {
69
- const tryURL = new URL(url);
70
- tryURL.searchParams.append("data", JSON.stringify(serialized));
71
- if (tryURL.toString().length <= this.maxURLLength) {
104
+ if (expectedMethod === "GET" && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
105
+ const getUrl = new URL(url);
106
+ getUrl.searchParams.append("data", JSON.stringify(serialized));
107
+ if (getUrl.toString().length <= this.maxUrlLength) {
72
108
  return {
73
109
  body: void 0,
74
- method: expectMethod,
110
+ method: expectedMethod,
75
111
  headers,
76
- url: tryURL
112
+ url: getUrl
77
113
  };
78
114
  }
79
115
  }
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 (isObject(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
116
  return {
101
- body: serialized,
102
- method,
117
+ url,
118
+ method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
103
119
  headers,
104
- url
120
+ body: serialized
105
121
  };
106
122
  }
107
123
  };
108
124
  export {
125
+ InvalidEventSourceRetryResponse,
109
126
  RPCLink
110
127
  };
111
128
  //# sourceMappingURL=fetch.js.map