@orpc/client 0.0.0-next.d452413 → 0.0.0-next.d53e45e

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.
@@ -1,320 +0,0 @@
1
- import { intercept, isAsyncIteratorObject, value, isObject, trim, stringifyJSON } from '@orpc/shared';
2
- import { c as createAutoRetryEventIterator, O as ORPCError, m as mapEventIterator, t as toORPCError } from './client.XAn8cDTM.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
- this.eventIteratorMaxRetries = options.eventIteratorMaxRetries ?? 5;
12
- this.eventIteratorRetryDelay = options.eventIteratorRetryDelay ?? ((o) => o.lastRetry ?? 1e3 * 2 ** o.retryTimes);
13
- this.eventIteratorShouldRetry = options.eventIteratorShouldRetry ?? true;
14
- this.interceptors = options.interceptors ?? [];
15
- this.clientInterceptors = options.clientInterceptors ?? [];
16
- }
17
- eventIteratorMaxRetries;
18
- eventIteratorRetryDelay;
19
- eventIteratorShouldRetry;
20
- interceptors;
21
- clientInterceptors;
22
- call(path, input, options) {
23
- return intercept(this.interceptors, { path, input, options }, async ({ path: path2, input: input2, options: options2 }) => {
24
- const output = await this.#call(path2, input2, options2);
25
- if (!isAsyncIteratorObject(output)) {
26
- return output;
27
- }
28
- return createAutoRetryEventIterator(output, async (reconnectOptions) => {
29
- const maxRetries = await value(this.eventIteratorMaxRetries, reconnectOptions, options2, path2, input2);
30
- if (options2.signal?.aborted || reconnectOptions.retryTimes > maxRetries) {
31
- return null;
32
- }
33
- const shouldRetry = await value(this.eventIteratorShouldRetry, reconnectOptions, options2, path2, input2);
34
- if (!shouldRetry) {
35
- return null;
36
- }
37
- const retryDelay = await value(this.eventIteratorRetryDelay, reconnectOptions, options2, path2, input2);
38
- await new Promise((resolve) => setTimeout(resolve, retryDelay));
39
- const updatedOptions = { ...options2, lastEventId: reconnectOptions.lastEventId };
40
- const maybeIterator = await this.#call(path2, input2, updatedOptions);
41
- if (!isAsyncIteratorObject(maybeIterator)) {
42
- throw new InvalidEventIteratorRetryResponse("Invalid Event Iterator retry response");
43
- }
44
- return maybeIterator;
45
- }, options2.lastEventId);
46
- });
47
- }
48
- async #call(path, input, options) {
49
- const request = await this.codec.encode(path, input, options);
50
- const response = await intercept(
51
- this.clientInterceptors,
52
- { request },
53
- ({ request: request2 }) => this.sender.call(request2, options, path, input)
54
- );
55
- const output = await this.codec.decode(response, options, path, input);
56
- return output;
57
- }
58
- }
59
-
60
- class RPCJsonSerializer {
61
- serialize(data, segments = [], meta = [], maps = [], blobs = []) {
62
- if (data instanceof Blob) {
63
- maps.push(segments);
64
- blobs.push(data);
65
- return [data, meta, maps, blobs];
66
- }
67
- if (typeof data === "bigint") {
68
- meta.push([0, segments]);
69
- return [data.toString(), meta, maps, blobs];
70
- }
71
- if (data instanceof Date) {
72
- meta.push([1, segments]);
73
- if (Number.isNaN(data.getTime())) {
74
- return [null, meta, maps, blobs];
75
- }
76
- return [data.toISOString(), meta, maps, blobs];
77
- }
78
- if (Number.isNaN(data)) {
79
- meta.push([2, segments]);
80
- return [null, meta, maps, blobs];
81
- }
82
- if (data instanceof URL) {
83
- meta.push([4, segments]);
84
- return [data.toString(), meta, maps, blobs];
85
- }
86
- if (data instanceof RegExp) {
87
- meta.push([5, segments]);
88
- return [data.toString(), meta, maps, blobs];
89
- }
90
- if (data instanceof Set) {
91
- const result = this.serialize(Array.from(data), segments, meta, maps, blobs);
92
- meta.push([6, segments]);
93
- return result;
94
- }
95
- if (data instanceof Map) {
96
- const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);
97
- meta.push([7, segments]);
98
- return result;
99
- }
100
- if (Array.isArray(data)) {
101
- const json = data.map((v, i) => {
102
- if (v === void 0) {
103
- meta.push([3, [...segments, i]]);
104
- return v;
105
- }
106
- return this.serialize(v, [...segments, i], meta, maps, blobs)[0];
107
- });
108
- return [json, meta, maps, blobs];
109
- }
110
- if (isObject(data)) {
111
- const json = {};
112
- for (const k in data) {
113
- json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];
114
- }
115
- return [json, meta, maps, blobs];
116
- }
117
- return [data, meta, maps, blobs];
118
- }
119
- deserialize(json, meta, maps, getBlob) {
120
- const ref = { data: json };
121
- if (maps && getBlob) {
122
- maps.forEach((segments, i) => {
123
- let currentRef = ref;
124
- let preSegment = "data";
125
- segments.forEach((segment) => {
126
- currentRef = currentRef[preSegment];
127
- preSegment = segment;
128
- });
129
- currentRef[preSegment] = getBlob(i);
130
- });
131
- }
132
- for (const [type, segments] of meta) {
133
- let currentRef = ref;
134
- let preSegment = "data";
135
- segments.forEach((segment) => {
136
- currentRef = currentRef[preSegment];
137
- preSegment = segment;
138
- });
139
- switch (type) {
140
- case 0:
141
- currentRef[preSegment] = BigInt(currentRef[preSegment]);
142
- break;
143
- case 1:
144
- currentRef[preSegment] = new Date(currentRef[preSegment] ?? "Invalid Date");
145
- break;
146
- case 2:
147
- currentRef[preSegment] = Number.NaN;
148
- break;
149
- case 3:
150
- currentRef[preSegment] = void 0;
151
- break;
152
- case 4:
153
- currentRef[preSegment] = new URL(currentRef[preSegment]);
154
- break;
155
- case 5: {
156
- const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
157
- currentRef[preSegment] = new RegExp(pattern, flags);
158
- break;
159
- }
160
- case 6:
161
- currentRef[preSegment] = new Set(currentRef[preSegment]);
162
- break;
163
- case 7:
164
- currentRef[preSegment] = new Map(currentRef[preSegment]);
165
- break;
166
- }
167
- }
168
- return ref.data;
169
- }
170
- }
171
-
172
- class StandardRPCLinkCodec {
173
- constructor(serializer, options) {
174
- this.serializer = serializer;
175
- this.baseUrl = options.url;
176
- this.maxUrlLength = options.maxUrlLength ?? 2083;
177
- this.fallbackMethod = options.fallbackMethod ?? "POST";
178
- this.expectedMethod = options.method ?? this.fallbackMethod;
179
- this.headers = options.headers ?? {};
180
- }
181
- baseUrl;
182
- maxUrlLength;
183
- fallbackMethod;
184
- expectedMethod;
185
- headers;
186
- async encode(path, input, options) {
187
- const expectedMethod = await value(this.expectedMethod, options, path, input);
188
- const headers = await value(this.headers, options, path, input);
189
- const baseUrl = await value(this.baseUrl, options, path, input);
190
- const url = new URL(`${trim(baseUrl.toString(), "/")}/${path.map(encodeURIComponent).join("/")}`);
191
- const serialized = this.serializer.serialize(input);
192
- if (expectedMethod === "GET" && !(serialized instanceof FormData) && !(serialized instanceof Blob) && !isAsyncIteratorObject(serialized)) {
193
- const maxUrlLength = await value(this.maxUrlLength, options, path, input);
194
- const getUrl = new URL(url);
195
- getUrl.searchParams.append("data", stringifyJSON(serialized) ?? "");
196
- if (getUrl.toString().length <= maxUrlLength) {
197
- return {
198
- body: void 0,
199
- method: expectedMethod,
200
- headers,
201
- url: getUrl,
202
- signal: options.signal
203
- };
204
- }
205
- }
206
- return {
207
- url,
208
- method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
209
- headers,
210
- body: serialized,
211
- signal: options.signal
212
- };
213
- }
214
- async decode(response) {
215
- const isOk = response.status >= 200 && response.status < 300;
216
- const deserialized = await (async () => {
217
- let isBodyOk = false;
218
- try {
219
- const body = await response.body();
220
- isBodyOk = true;
221
- return this.serializer.deserialize(body);
222
- } catch (error) {
223
- if (!isBodyOk) {
224
- throw new Error("Cannot parse response body, please check the response body and content-type.", {
225
- cause: error
226
- });
227
- }
228
- throw new Error("Invalid RPC response format.", {
229
- cause: error
230
- });
231
- }
232
- })();
233
- if (!isOk) {
234
- if (ORPCError.isValidJSON(deserialized)) {
235
- throw ORPCError.fromJSON(deserialized);
236
- }
237
- throw new Error("Invalid RPC error response format.", {
238
- cause: deserialized
239
- });
240
- }
241
- return deserialized;
242
- }
243
- }
244
-
245
- class RPCSerializer {
246
- constructor(jsonSerializer = new RPCJsonSerializer()) {
247
- this.jsonSerializer = jsonSerializer;
248
- }
249
- serialize(data) {
250
- if (isAsyncIteratorObject(data)) {
251
- return mapEventIterator(data, {
252
- value: async (value) => this.#serialize(value, false),
253
- error: async (e) => {
254
- return new ErrorEvent({
255
- data: this.#serialize(toORPCError(e).toJSON(), false),
256
- cause: e
257
- });
258
- }
259
- });
260
- }
261
- return this.#serialize(data, true);
262
- }
263
- #serialize(data, enableFormData) {
264
- if (data === void 0 || data instanceof Blob) {
265
- return data;
266
- }
267
- const [json, meta_, maps, blobs] = this.jsonSerializer.serialize(data);
268
- const meta = meta_.length === 0 ? void 0 : meta_;
269
- if (!enableFormData || blobs.length === 0) {
270
- return {
271
- json,
272
- meta
273
- };
274
- }
275
- const form = new FormData();
276
- form.set("data", stringifyJSON({ json, meta, maps }));
277
- blobs.forEach((blob, i) => {
278
- form.set(i.toString(), blob);
279
- });
280
- return form;
281
- }
282
- deserialize(data) {
283
- if (isAsyncIteratorObject(data)) {
284
- return mapEventIterator(data, {
285
- value: async (value) => this.#deserialize(value),
286
- error: async (e) => {
287
- if (!(e instanceof ErrorEvent)) {
288
- return e;
289
- }
290
- const deserialized = this.#deserialize(e.data);
291
- if (ORPCError.isValidJSON(deserialized)) {
292
- return ORPCError.fromJSON(deserialized, { cause: e });
293
- }
294
- return new ErrorEvent({
295
- data: deserialized,
296
- cause: e
297
- });
298
- }
299
- });
300
- }
301
- return this.#deserialize(data);
302
- }
303
- #deserialize(data) {
304
- if (data === void 0 || data instanceof Blob) {
305
- return data;
306
- }
307
- if (!(data instanceof FormData)) {
308
- return this.jsonSerializer.deserialize(data.json, data.meta ?? []);
309
- }
310
- const serialized = JSON.parse(data.get("data"));
311
- return this.jsonSerializer.deserialize(
312
- serialized.json,
313
- serialized.meta ?? [],
314
- serialized.maps,
315
- (i) => data.get(i.toString())
316
- );
317
- }
318
- }
319
-
320
- export { InvalidEventIteratorRetryResponse as I, RPCJsonSerializer as R, StandardLink as S, StandardRPCLinkCodec as a, RPCSerializer as b };
@@ -1,266 +0,0 @@
1
- import { isObject, isTypescriptObject, retry } from '@orpc/shared';
2
- import { getEventMeta, withEventMeta } from '@orpc/standard-server';
3
-
4
- const COMMON_ORPC_ERROR_DEFS = {
5
- BAD_REQUEST: {
6
- status: 400,
7
- message: "Bad Request"
8
- },
9
- UNAUTHORIZED: {
10
- status: 401,
11
- message: "Unauthorized"
12
- },
13
- FORBIDDEN: {
14
- status: 403,
15
- message: "Forbidden"
16
- },
17
- NOT_FOUND: {
18
- status: 404,
19
- message: "Not Found"
20
- },
21
- METHOD_NOT_SUPPORTED: {
22
- status: 405,
23
- message: "Method Not Supported"
24
- },
25
- NOT_ACCEPTABLE: {
26
- status: 406,
27
- message: "Not Acceptable"
28
- },
29
- TIMEOUT: {
30
- status: 408,
31
- message: "Request Timeout"
32
- },
33
- CONFLICT: {
34
- status: 409,
35
- message: "Conflict"
36
- },
37
- PRECONDITION_FAILED: {
38
- status: 412,
39
- message: "Precondition Failed"
40
- },
41
- PAYLOAD_TOO_LARGE: {
42
- status: 413,
43
- message: "Payload Too Large"
44
- },
45
- UNSUPPORTED_MEDIA_TYPE: {
46
- status: 415,
47
- message: "Unsupported Media Type"
48
- },
49
- UNPROCESSABLE_CONTENT: {
50
- status: 422,
51
- message: "Unprocessable Content"
52
- },
53
- TOO_MANY_REQUESTS: {
54
- status: 429,
55
- message: "Too Many Requests"
56
- },
57
- CLIENT_CLOSED_REQUEST: {
58
- status: 499,
59
- message: "Client Closed Request"
60
- },
61
- INTERNAL_SERVER_ERROR: {
62
- status: 500,
63
- message: "Internal Server Error"
64
- },
65
- NOT_IMPLEMENTED: {
66
- status: 501,
67
- message: "Not Implemented"
68
- },
69
- BAD_GATEWAY: {
70
- status: 502,
71
- message: "Bad Gateway"
72
- },
73
- SERVICE_UNAVAILABLE: {
74
- status: 503,
75
- message: "Service Unavailable"
76
- },
77
- GATEWAY_TIMEOUT: {
78
- status: 504,
79
- message: "Gateway Timeout"
80
- }
81
- };
82
- function fallbackORPCErrorStatus(code, status) {
83
- return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
84
- }
85
- function fallbackORPCErrorMessage(code, message) {
86
- return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
87
- }
88
- class ORPCError extends Error {
89
- defined;
90
- code;
91
- status;
92
- data;
93
- constructor(code, ...[options]) {
94
- if (options?.status && (options.status < 400 || options.status >= 600)) {
95
- throw new Error("[ORPCError] The error status code must be in the 400-599 range.");
96
- }
97
- const message = fallbackORPCErrorMessage(code, options?.message);
98
- super(message, options);
99
- this.code = code;
100
- this.status = fallbackORPCErrorStatus(code, options?.status);
101
- this.defined = options?.defined ?? false;
102
- this.data = options?.data;
103
- }
104
- toJSON() {
105
- return {
106
- defined: this.defined,
107
- code: this.code,
108
- status: this.status,
109
- message: this.message,
110
- data: this.data
111
- };
112
- }
113
- static fromJSON(json, options) {
114
- return new ORPCError(json.code, {
115
- ...options,
116
- ...json
117
- });
118
- }
119
- static isValidJSON(json) {
120
- if (!isObject(json)) {
121
- return false;
122
- }
123
- const validKeys = ["defined", "code", "status", "message", "data"];
124
- if (Object.keys(json).some((k) => !validKeys.includes(k))) {
125
- return false;
126
- }
127
- 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";
128
- }
129
- }
130
- function isDefinedError(error) {
131
- return error instanceof ORPCError && error.defined;
132
- }
133
- function toORPCError(error) {
134
- return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", {
135
- message: "Internal server error",
136
- cause: error
137
- });
138
- }
139
-
140
- const iteratorStates = /* @__PURE__ */ new WeakMap();
141
- function registerEventIteratorState(iterator, state) {
142
- iteratorStates.set(iterator, state);
143
- }
144
- function updateEventIteratorStatus(state, status) {
145
- if (state.status !== status) {
146
- state.status = status;
147
- state.listeners.forEach((cb) => cb(status));
148
- }
149
- }
150
- function onEventIteratorStatusChange(iterator, callback, options = {}) {
151
- const notifyImmediately = options.notifyImmediately ?? true;
152
- const state = iteratorStates.get(iterator);
153
- if (!state) {
154
- throw new Error("Iterator is not registered.");
155
- }
156
- if (notifyImmediately) {
157
- callback(state.status);
158
- }
159
- state.listeners.push(callback);
160
- return () => {
161
- const index = state.listeners.indexOf(callback);
162
- if (index !== -1) {
163
- state.listeners.splice(index, 1);
164
- }
165
- };
166
- }
167
-
168
- function mapEventIterator(iterator, maps) {
169
- return async function* () {
170
- try {
171
- while (true) {
172
- const { done, value } = await iterator.next();
173
- let mappedValue = await maps.value(value, done);
174
- if (mappedValue !== value) {
175
- const meta = getEventMeta(value);
176
- if (meta && isTypescriptObject(mappedValue)) {
177
- mappedValue = withEventMeta(mappedValue, meta);
178
- }
179
- }
180
- if (done) {
181
- return mappedValue;
182
- }
183
- yield mappedValue;
184
- }
185
- } catch (error) {
186
- let mappedError = await maps.error(error);
187
- if (mappedError !== error) {
188
- const meta = getEventMeta(error);
189
- if (meta && isTypescriptObject(mappedError)) {
190
- mappedError = withEventMeta(mappedError, meta);
191
- }
192
- }
193
- throw mappedError;
194
- } finally {
195
- await iterator.return?.();
196
- }
197
- }();
198
- }
199
- const MAX_ALLOWED_RETRY_TIMES = 99;
200
- function createAutoRetryEventIterator(initial, reconnect, initialLastEventId) {
201
- const state = {
202
- status: "connected",
203
- listeners: []
204
- };
205
- const iterator = async function* () {
206
- let current = initial;
207
- let lastEventId = initialLastEventId;
208
- let lastRetry;
209
- let retryTimes = 0;
210
- try {
211
- while (true) {
212
- try {
213
- updateEventIteratorStatus(state, "connected");
214
- const { done, value } = await current.next();
215
- const meta = getEventMeta(value);
216
- lastEventId = meta?.id ?? lastEventId;
217
- lastRetry = meta?.retry ?? lastRetry;
218
- retryTimes = 0;
219
- if (done) {
220
- return value;
221
- }
222
- yield value;
223
- } catch (e) {
224
- updateEventIteratorStatus(state, "reconnecting");
225
- const meta = getEventMeta(e);
226
- lastEventId = meta?.id ?? lastEventId;
227
- lastRetry = meta?.retry ?? lastRetry;
228
- let currentError = e;
229
- current = await retry({ times: MAX_ALLOWED_RETRY_TIMES }, async (exit) => {
230
- retryTimes += 1;
231
- if (retryTimes > MAX_ALLOWED_RETRY_TIMES) {
232
- throw exit(new Error(
233
- `Exceeded maximum retry attempts (${MAX_ALLOWED_RETRY_TIMES}) for event iterator. Possible infinite retry loop detected. Please review the retry logic.`,
234
- { cause: currentError }
235
- ));
236
- }
237
- const reconnected = await (async () => {
238
- try {
239
- return await reconnect({
240
- lastRetry,
241
- lastEventId,
242
- retryTimes,
243
- error: currentError
244
- });
245
- } catch (e2) {
246
- currentError = e2;
247
- throw e2;
248
- }
249
- })();
250
- if (!reconnected) {
251
- throw exit(currentError);
252
- }
253
- return reconnected;
254
- });
255
- }
256
- }
257
- } finally {
258
- updateEventIteratorStatus(state, "closed");
259
- await current.return?.();
260
- }
261
- }();
262
- registerEventIteratorState(iterator, state);
263
- return iterator;
264
- }
265
-
266
- export { COMMON_ORPC_ERROR_DEFS as C, ORPCError as O, fallbackORPCErrorMessage as a, createAutoRetryEventIterator as c, fallbackORPCErrorStatus as f, isDefinedError as i, mapEventIterator as m, onEventIteratorStatusChange as o, registerEventIteratorState as r, toORPCError as t, updateEventIteratorStatus as u };