@orpc/client 0.0.0-next.d888fab → 0.0.0-next.d8deda3

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 (31) hide show
  1. package/README.md +11 -8
  2. package/dist/adapters/fetch/index.d.mts +23 -10
  3. package/dist/adapters/fetch/index.d.ts +23 -10
  4. package/dist/adapters/fetch/index.mjs +25 -8
  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 +6 -5
  9. package/dist/adapters/standard/index.d.ts +6 -5
  10. package/dist/adapters/standard/index.mjs +4 -2
  11. package/dist/adapters/websocket/index.d.mts +12 -12
  12. package/dist/adapters/websocket/index.d.ts +12 -12
  13. package/dist/adapters/websocket/index.mjs +27 -11
  14. package/dist/index.d.mts +86 -25
  15. package/dist/index.d.ts +86 -25
  16. package/dist/index.mjs +55 -8
  17. package/dist/plugins/index.d.mts +105 -18
  18. package/dist/plugins/index.d.ts +105 -18
  19. package/dist/plugins/index.mjs +221 -27
  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.B2432-Lu.d.ts → client.BxV-mzeR.d.ts} +7 -7
  24. package/dist/shared/{client.7ZYxJok_.d.ts → client.CPgZaUox.d.mts} +4 -5
  25. package/dist/shared/{client.ClwIM_ku.d.mts → client.D8lMmWVC.d.mts} +7 -7
  26. package/dist/shared/{client.CRWEpqLB.mjs → client.DaTrs7SW.mjs} +37 -41
  27. package/dist/shared/{client.ds1abV85.d.mts → client.De8SW4Kw.d.ts} +4 -5
  28. package/dist/shared/{client.DpICn1BD.mjs → client.vtdIueWp.mjs} +63 -20
  29. package/package.json +11 -6
  30. package/dist/shared/client.4TS_0JaO.d.mts +0 -29
  31. package/dist/shared/client.4TS_0JaO.d.ts +0 -29
@@ -1,7 +1,8 @@
1
- import { Value } from '@orpc/shared';
2
- import { StandardHeaders, StandardRequest } from '@orpc/standard-server';
3
- import { S as StandardLinkClientInterceptorOptions, a as StandardLinkPlugin, b as StandardLinkOptions, c as StandardLinkInterceptorOptions } from '../shared/client.7ZYxJok_.js';
4
- import { a as ClientContext } from '../shared/client.4TS_0JaO.js';
1
+ import { Value, Promisable } from '@orpc/shared';
2
+ import { StandardHeaders, StandardRequest, StandardLazyResponse } from '@orpc/standard-server';
3
+ import { BatchResponseMode } from '@orpc/standard-server/batch';
4
+ import { S as StandardLinkClientInterceptorOptions, a as StandardLinkPlugin, b as StandardLinkOptions, c as StandardLinkInterceptorOptions } from '../shared/client.De8SW4Kw.js';
5
+ import { b as ClientContext } from '../shared/client.BH1AYT_p.js';
5
6
 
6
7
  interface BatchLinkPluginGroup<T extends ClientContext> {
7
8
  condition(options: StandardLinkClientInterceptorOptions<T>): boolean;
@@ -16,25 +17,31 @@ interface BatchLinkPluginOptions<T extends ClientContext> {
16
17
  *
17
18
  * @default 10
18
19
  */
19
- maxSize?: Value<number, [readonly [StandardLinkClientInterceptorOptions<T>, ...StandardLinkClientInterceptorOptions<T>[]]]>;
20
+ maxSize?: Value<Promisable<number>, [readonly [StandardLinkClientInterceptorOptions<T>, ...StandardLinkClientInterceptorOptions<T>[]]]>;
21
+ /**
22
+ * The batch response mode.
23
+ *
24
+ * @default 'streaming'
25
+ */
26
+ mode?: Value<BatchResponseMode, [readonly [StandardLinkClientInterceptorOptions<T>, ...StandardLinkClientInterceptorOptions<T>[]]]>;
20
27
  /**
21
28
  * Defines the URL to use for the batch request.
22
29
  *
23
30
  * @default the URL of the first request in the batch + '/__batch__'
24
31
  */
25
- url?: Value<string | URL, [readonly [StandardLinkClientInterceptorOptions<T>, ...StandardLinkClientInterceptorOptions<T>[]]]>;
32
+ url?: Value<Promisable<string | URL>, [readonly [StandardLinkClientInterceptorOptions<T>, ...StandardLinkClientInterceptorOptions<T>[]]]>;
26
33
  /**
27
34
  * The maximum length of the URL.
28
35
  *
29
36
  * @default 2083
30
37
  */
31
- maxUrlLength?: Value<number, [readonly [StandardLinkClientInterceptorOptions<T>, ...StandardLinkClientInterceptorOptions<T>[]]]>;
38
+ maxUrlLength?: Value<Promisable<number>, [readonly [StandardLinkClientInterceptorOptions<T>, ...StandardLinkClientInterceptorOptions<T>[]]]>;
32
39
  /**
33
40
  * Defines the HTTP headers to use for the batch request.
34
41
  *
35
42
  * @default The same headers of all requests in the batch
36
43
  */
37
- headers?: Value<StandardHeaders, [readonly [StandardLinkClientInterceptorOptions<T>, ...StandardLinkClientInterceptorOptions<T>[]]]>;
44
+ headers?: Value<Promisable<StandardHeaders>, [readonly [StandardLinkClientInterceptorOptions<T>, ...StandardLinkClientInterceptorOptions<T>[]]]>;
38
45
  /**
39
46
  * Map the batch request items before sending them.
40
47
  *
@@ -52,10 +59,10 @@ interface BatchLinkPluginOptions<T extends ClientContext> {
52
59
  exclude?: (options: StandardLinkClientInterceptorOptions<T>) => boolean;
53
60
  }
54
61
  /**
55
- * The Batch Request/Response Plugin allows you to combine multiple requests and responses into a single batch,
62
+ * The Batch Requests Plugin allows you to combine multiple requests and responses into a single batch,
56
63
  * reducing the overhead of sending each one separately.
57
64
  *
58
- * @see {@link https://orpc.unnoq.com/docs/plugins/batch-request-response Batch Request/Response Plugin Docs}
65
+ * @see {@link https://orpc.unnoq.com/docs/plugins/batch-requests Batch Requests Plugin Docs}
59
66
  */
60
67
  declare class BatchLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
61
68
  #private;
@@ -66,12 +73,45 @@ declare class BatchLinkPlugin<T extends ClientContext> implements StandardLinkPl
66
73
  private readonly batchHeaders;
67
74
  private readonly mapRequestItem;
68
75
  private readonly exclude;
76
+ private readonly mode;
69
77
  private pending;
70
78
  order: number;
71
79
  constructor(options: NoInfer<BatchLinkPluginOptions<T>>);
72
80
  init(options: StandardLinkOptions<T>): void;
73
81
  }
74
82
 
83
+ interface DedupeRequestsPluginGroup<T extends ClientContext> {
84
+ condition(options: StandardLinkClientInterceptorOptions<T>): boolean;
85
+ /**
86
+ * The context used for the rest of the request lifecycle.
87
+ */
88
+ context: T;
89
+ }
90
+ interface DedupeRequestsPluginOptions<T extends ClientContext> {
91
+ /**
92
+ * To enable deduplication, a request must match at least one defined group.
93
+ * Requests that fall into the same group are considered for deduplication together.
94
+ */
95
+ groups: readonly [DedupeRequestsPluginGroup<T>, ...DedupeRequestsPluginGroup<T>[]];
96
+ /**
97
+ * Filters requests to dedupe
98
+ *
99
+ * @default (({ request }) => request.method === 'GET')
100
+ */
101
+ filter?: (options: StandardLinkClientInterceptorOptions<T>) => boolean;
102
+ }
103
+ /**
104
+ * Prevents duplicate requests by deduplicating similar ones to reduce server load.
105
+ *
106
+ * @see {@link https://orpc.unnoq.com/docs/plugins/dedupe-requests Dedupe Requests Plugin}
107
+ */
108
+ declare class DedupeRequestsPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
109
+ #private;
110
+ order: number;
111
+ constructor(options: NoInfer<DedupeRequestsPluginOptions<T>>);
112
+ init(options: StandardLinkOptions<T>): void;
113
+ }
114
+
75
115
  interface ClientRetryPluginAttemptOptions<T extends ClientContext> extends StandardLinkInterceptorOptions<T> {
76
116
  lastEventRetry: number | undefined;
77
117
  attemptIndex: number;
@@ -84,19 +124,19 @@ interface ClientRetryPluginContext {
84
124
  *
85
125
  * @default 0
86
126
  */
87
- retry?: Value<number, [StandardLinkInterceptorOptions<ClientRetryPluginContext>]>;
127
+ retry?: Value<Promisable<number>, [StandardLinkInterceptorOptions<ClientRetryPluginContext>]>;
88
128
  /**
89
129
  * Delay (in ms) before retrying.
90
130
  *
91
131
  * @default (o) => o.lastEventRetry ?? 2000
92
132
  */
93
- retryDelay?: Value<number, [ClientRetryPluginAttemptOptions<ClientRetryPluginContext>]>;
133
+ retryDelay?: Value<Promisable<number>, [ClientRetryPluginAttemptOptions<ClientRetryPluginContext>]>;
94
134
  /**
95
135
  * Determine should retry or not.
96
136
  *
97
137
  * @default true
98
138
  */
99
- shouldRetry?: Value<boolean, [ClientRetryPluginAttemptOptions<ClientRetryPluginContext>]>;
139
+ shouldRetry?: Value<Promisable<boolean>, [ClientRetryPluginAttemptOptions<ClientRetryPluginContext>]>;
100
140
  /**
101
141
  * The hook called when retrying, and return the unsubscribe function.
102
142
  */
@@ -117,30 +157,77 @@ declare class ClientRetryPlugin<T extends ClientRetryPluginContext> implements S
117
157
  private readonly defaultRetryDelay;
118
158
  private readonly defaultShouldRetry;
119
159
  private readonly defaultOnRetry;
160
+ order: number;
120
161
  constructor(options?: ClientRetryPluginOptions);
121
162
  init(options: StandardLinkOptions<T>): void;
122
163
  }
123
164
 
165
+ interface RetryAfterPluginOptions<T extends ClientContext> {
166
+ /**
167
+ * Override condition to determine whether to retry or not.
168
+ *
169
+ * @default ((response) => response.status === 429 || response.status === 503)
170
+ */
171
+ condition?: Value<boolean, [
172
+ response: StandardLazyResponse,
173
+ options: StandardLinkClientInterceptorOptions<T>
174
+ ]>;
175
+ /**
176
+ * Maximum attempts before giving up retries.
177
+ *
178
+ * @default 3
179
+ */
180
+ maxAttempts?: Value<number, [
181
+ response: StandardLazyResponse,
182
+ options: StandardLinkClientInterceptorOptions<T>
183
+ ]>;
184
+ /**
185
+ * Maximum timeout in milliseconds to wait before giving up retries.
186
+ *
187
+ * @default 5 * 60 * 1000 (5 minutes)
188
+ */
189
+ timeout?: Value<number, [
190
+ response: StandardLazyResponse,
191
+ options: StandardLinkClientInterceptorOptions<T>
192
+ ]>;
193
+ }
194
+ /**
195
+ * The Retry After Plugin automatically retries requests based on server `Retry-After` headers.
196
+ * This is particularly useful for handling rate limiting and temporary server unavailability.
197
+ *
198
+ * @see {@link https://orpc.unnoq.com/docs/plugins/retry-after Retry After Plugin Docs}
199
+ */
200
+ declare class RetryAfterPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
201
+ private readonly condition;
202
+ private readonly maxAttempts;
203
+ private readonly timeout;
204
+ order: number;
205
+ constructor(options?: RetryAfterPluginOptions<T>);
206
+ init(options: StandardLinkOptions<T>): void;
207
+ private parseRetryAfterHeader;
208
+ private delayExecution;
209
+ }
210
+
124
211
  interface SimpleCsrfProtectionLinkPluginOptions<T extends ClientContext> {
125
212
  /**
126
213
  * The name of the header to check.
127
214
  *
128
215
  * @default 'x-csrf-token'
129
216
  */
130
- headerName?: Value<string, [options: StandardLinkClientInterceptorOptions<T>]>;
217
+ headerName?: Value<Promisable<string>, [options: StandardLinkClientInterceptorOptions<T>]>;
131
218
  /**
132
219
  * The value of the header to check.
133
220
  *
134
221
  * @default 'orpc'
135
222
  *
136
223
  */
137
- headerValue?: Value<string, [options: StandardLinkClientInterceptorOptions<T>]>;
224
+ headerValue?: Value<Promisable<string>, [options: StandardLinkClientInterceptorOptions<T>]>;
138
225
  /**
139
226
  * Exclude a procedure from the plugin.
140
227
  *
141
228
  * @default false
142
229
  */
143
- exclude?: Value<boolean, [options: StandardLinkClientInterceptorOptions<T>]>;
230
+ exclude?: Value<Promisable<boolean>, [options: StandardLinkClientInterceptorOptions<T>]>;
144
231
  }
145
232
  /**
146
233
  * This plugin adds basic Cross-Site Request Forgery (CSRF) protection to your oRPC application.
@@ -158,5 +245,5 @@ declare class SimpleCsrfProtectionLinkPlugin<T extends ClientContext> implements
158
245
  init(options: StandardLinkOptions<T>): void;
159
246
  }
160
247
 
161
- export { BatchLinkPlugin, ClientRetryPlugin, ClientRetryPluginInvalidEventIteratorRetryResponse, SimpleCsrfProtectionLinkPlugin };
162
- export type { BatchLinkPluginGroup, BatchLinkPluginOptions, ClientRetryPluginAttemptOptions, ClientRetryPluginContext, ClientRetryPluginOptions, SimpleCsrfProtectionLinkPluginOptions };
248
+ export { BatchLinkPlugin, ClientRetryPlugin, ClientRetryPluginInvalidEventIteratorRetryResponse, DedupeRequestsPlugin, RetryAfterPlugin, SimpleCsrfProtectionLinkPlugin };
249
+ export type { BatchLinkPluginGroup, BatchLinkPluginOptions, ClientRetryPluginAttemptOptions, ClientRetryPluginContext, ClientRetryPluginOptions, DedupeRequestsPluginGroup, DedupeRequestsPluginOptions, RetryAfterPluginOptions, SimpleCsrfProtectionLinkPluginOptions };
@@ -1,6 +1,7 @@
1
- import { isAsyncIteratorObject, value, splitInHalf, toArray } from '@orpc/shared';
2
- import { toBatchRequest, parseBatchResponse } from '@orpc/standard-server/batch';
3
- import { getEventMeta } from '@orpc/standard-server';
1
+ import { isAsyncIteratorObject, defer, value, splitInHalf, toArray, stringifyJSON, overlayProxy, AsyncIteratorClass } from '@orpc/shared';
2
+ import { toBatchRequest, parseBatchResponse, toBatchAbortSignal } from '@orpc/standard-server/batch';
3
+ import { replicateStandardLazyResponse, getEventMeta, flattenHeader } from '@orpc/standard-server';
4
+ import { C as COMMON_ORPC_ERROR_DEFS } from '../shared/client.DaTrs7SW.mjs';
4
5
 
5
6
  class BatchLinkPlugin {
6
7
  groups;
@@ -10,6 +11,7 @@ class BatchLinkPlugin {
10
11
  batchHeaders;
11
12
  mapRequestItem;
12
13
  exclude;
14
+ mode;
13
15
  pending;
14
16
  order = 5e6;
15
17
  constructor(options) {
@@ -17,6 +19,7 @@ class BatchLinkPlugin {
17
19
  this.pending = /* @__PURE__ */ new Map();
18
20
  this.maxSize = options.maxSize ?? 10;
19
21
  this.maxUrlLength = options.maxUrlLength ?? 2083;
22
+ this.mode = options.mode ?? "streaming";
20
23
  this.batchUrl = options.url ?? (([options2]) => `${options2.request.url.origin}${options2.request.url.pathname}/__batch__`);
21
24
  this.batchHeaders = options.headers ?? (([options2, ...rest]) => {
22
25
  const headers = {};
@@ -62,7 +65,7 @@ class BatchLinkPlugin {
62
65
  });
63
66
  });
64
67
  options.clientInterceptors.push((options2) => {
65
- if (this.exclude(options2) || options2.request.body instanceof Blob || options2.request.body instanceof FormData || isAsyncIteratorObject(options2.request.body)) {
68
+ if (this.exclude(options2) || options2.request.body instanceof Blob || options2.request.body instanceof FormData || isAsyncIteratorObject(options2.request.body) || options2.request.signal?.aborted) {
66
69
  return options2.next();
67
70
  }
68
71
  const group = this.groups.find((group2) => group2.condition(options2));
@@ -71,7 +74,7 @@ class BatchLinkPlugin {
71
74
  }
72
75
  return new Promise((resolve, reject) => {
73
76
  this.#enqueueRequest(group, options2, resolve, reject);
74
- setTimeout(() => this.#processPendingBatches());
77
+ defer(() => this.#processPendingBatches());
75
78
  });
76
79
  });
77
80
  }
@@ -127,16 +130,28 @@ class BatchLinkPlugin {
127
130
  this.#executeBatch(method, group, second);
128
131
  return;
129
132
  }
130
- const lazyResponse = await options[0].next({
131
- request: { ...batchRequest, headers: { ...batchRequest.headers, "x-orpc-batch": "1" } },
132
- signal: batchRequest.signal,
133
- context: group.context,
134
- input: group.input,
135
- path: toArray(group.path)
136
- });
137
- const parsed = parseBatchResponse({ ...lazyResponse, body: await lazyResponse.body() });
138
- for await (const item of parsed) {
139
- batchItems[item.index]?.[1]({ ...item, body: () => Promise.resolve(item.body) });
133
+ const mode = value(this.mode, options);
134
+ try {
135
+ const lazyResponse = await options[0].next({
136
+ request: { ...batchRequest, headers: { ...batchRequest.headers, "x-orpc-batch": mode } },
137
+ signal: batchRequest.signal,
138
+ context: group.context,
139
+ input: group.input,
140
+ path: toArray(group.path)
141
+ });
142
+ const parsed = parseBatchResponse({ ...lazyResponse, body: await lazyResponse.body() });
143
+ for await (const item of parsed) {
144
+ batchItems[item.index]?.[1]({ ...item, body: () => Promise.resolve(item.body) });
145
+ }
146
+ } catch (err) {
147
+ if (batchRequest.signal?.aborted && batchRequest.signal.reason === err) {
148
+ for (const [{ signal }, , reject] of batchItems) {
149
+ if (signal?.aborted) {
150
+ reject(signal.reason);
151
+ }
152
+ }
153
+ }
154
+ throw err;
140
155
  }
141
156
  throw new Error("Something went wrong make batch response not contains enough responses. This can be a bug please report it.");
142
157
  } catch (error) {
@@ -147,6 +162,101 @@ class BatchLinkPlugin {
147
162
  }
148
163
  }
149
164
 
165
+ class DedupeRequestsPlugin {
166
+ #groups;
167
+ #filter;
168
+ order = 4e6;
169
+ // make sure execute before batch plugin
170
+ #queue = /* @__PURE__ */ new Map();
171
+ constructor(options) {
172
+ this.#groups = options.groups;
173
+ this.#filter = options.filter ?? (({ request }) => request.method === "GET");
174
+ }
175
+ init(options) {
176
+ options.clientInterceptors ??= [];
177
+ options.clientInterceptors.push((options2) => {
178
+ if (options2.request.body instanceof Blob || options2.request.body instanceof FormData || options2.request.body instanceof URLSearchParams || isAsyncIteratorObject(options2.request.body) || !this.#filter(options2)) {
179
+ return options2.next();
180
+ }
181
+ const group = this.#groups.find((group2) => group2.condition(options2));
182
+ if (!group) {
183
+ return options2.next();
184
+ }
185
+ return new Promise((resolve, reject) => {
186
+ this.#enqueue(group, options2, resolve, reject);
187
+ defer(() => this.#dequeue());
188
+ });
189
+ });
190
+ }
191
+ #enqueue(group, options, resolve, reject) {
192
+ let queue = this.#queue.get(group);
193
+ if (!queue) {
194
+ this.#queue.set(group, queue = []);
195
+ }
196
+ const matched = queue.find((item) => {
197
+ const requestString1 = stringifyJSON({
198
+ body: item.options.request.body,
199
+ headers: item.options.request.headers,
200
+ method: item.options.request.method,
201
+ url: item.options.request.url
202
+ });
203
+ const requestString2 = stringifyJSON({
204
+ body: options.request.body,
205
+ headers: options.request.headers,
206
+ method: options.request.method,
207
+ url: options.request.url
208
+ });
209
+ return requestString1 === requestString2;
210
+ });
211
+ if (matched) {
212
+ matched.signals.push(options.request.signal);
213
+ matched.resolves.push(resolve);
214
+ matched.rejects.push(reject);
215
+ } else {
216
+ queue.push({
217
+ options,
218
+ signals: [options.request.signal],
219
+ resolves: [resolve],
220
+ rejects: [reject]
221
+ });
222
+ }
223
+ }
224
+ async #dequeue() {
225
+ const promises = [];
226
+ for (const [group, items] of this.#queue) {
227
+ for (const { options, signals, resolves, rejects } of items) {
228
+ promises.push(
229
+ this.#execute(group, options, signals, resolves, rejects)
230
+ );
231
+ }
232
+ }
233
+ this.#queue.clear();
234
+ await Promise.all(promises);
235
+ }
236
+ async #execute(group, options, signals, resolves, rejects) {
237
+ try {
238
+ const dedupedRequest = {
239
+ ...options.request,
240
+ signal: toBatchAbortSignal(signals)
241
+ };
242
+ const response = await options.next({
243
+ ...options,
244
+ request: dedupedRequest,
245
+ signal: dedupedRequest.signal,
246
+ context: group.context
247
+ });
248
+ const replicatedResponses = replicateStandardLazyResponse(response, resolves.length);
249
+ for (const resolve of resolves) {
250
+ resolve(replicatedResponses.shift());
251
+ }
252
+ } catch (error) {
253
+ for (const reject of rejects) {
254
+ reject(error);
255
+ }
256
+ }
257
+ }
258
+ }
259
+
150
260
  class ClientRetryPluginInvalidEventIteratorRetryResponse extends Error {
151
261
  }
152
262
  class ClientRetryPlugin {
@@ -154,6 +264,7 @@ class ClientRetryPlugin {
154
264
  defaultRetryDelay;
155
265
  defaultShouldRetry;
156
266
  defaultOnRetry;
267
+ order = 18e5;
157
268
  constructor(options = {}) {
158
269
  this.defaultRetry = options.default?.retry ?? 0;
159
270
  this.defaultRetryDelay = options.default?.retryDelay ?? ((o) => o.lastEventRetry ?? 2e3);
@@ -208,7 +319,7 @@ class ClientRetryPlugin {
208
319
  return await interceptorOptions.next(updatedInterceptorOptions);
209
320
  } catch (error) {
210
321
  currentError = { error };
211
- if (updatedInterceptorOptions.signal?.aborted === true) {
322
+ if (updatedInterceptorOptions.signal?.aborted) {
212
323
  throw error;
213
324
  }
214
325
  } finally {
@@ -221,19 +332,17 @@ class ClientRetryPlugin {
221
332
  if (!isAsyncIteratorObject(output)) {
222
333
  return output;
223
334
  }
224
- return async function* () {
225
- let current = output;
226
- try {
335
+ let current = output;
336
+ let isIteratorAborted = false;
337
+ return overlayProxy(() => current, new AsyncIteratorClass(
338
+ async () => {
227
339
  while (true) {
228
340
  try {
229
341
  const item = await current.next();
230
342
  const meta = getEventMeta(item.value);
231
343
  lastEventId = meta?.id ?? lastEventId;
232
344
  lastEventRetry = meta?.retry ?? lastEventRetry;
233
- if (item.done) {
234
- return item.value;
235
- }
236
- yield item.value;
345
+ return item;
237
346
  } catch (error) {
238
347
  const meta = getEventMeta(error);
239
348
  lastEventId = meta?.id ?? lastEventId;
@@ -245,12 +354,97 @@ class ClientRetryPlugin {
245
354
  );
246
355
  }
247
356
  current = maybeEventIterator;
357
+ if (isIteratorAborted) {
358
+ await current.return?.();
359
+ throw error;
360
+ }
248
361
  }
249
362
  }
250
- } finally {
251
- await current.return?.();
363
+ },
364
+ async (reason) => {
365
+ isIteratorAborted = true;
366
+ if (reason !== "next") {
367
+ await current.return?.();
368
+ }
252
369
  }
253
- }();
370
+ ));
371
+ });
372
+ }
373
+ }
374
+
375
+ class RetryAfterPlugin {
376
+ condition;
377
+ maxAttempts;
378
+ timeout;
379
+ order = 19e5;
380
+ constructor(options = {}) {
381
+ this.condition = options.condition ?? ((response) => response.status === COMMON_ORPC_ERROR_DEFS.TOO_MANY_REQUESTS.status || response.status === COMMON_ORPC_ERROR_DEFS.SERVICE_UNAVAILABLE.status);
382
+ this.maxAttempts = options.maxAttempts ?? 3;
383
+ this.timeout = options.timeout ?? 5 * 60 * 1e3;
384
+ }
385
+ init(options) {
386
+ options.clientInterceptors ??= [];
387
+ options.clientInterceptors.push(async (interceptorOptions) => {
388
+ const startTime = Date.now();
389
+ let attemptCount = 0;
390
+ while (true) {
391
+ attemptCount++;
392
+ const response = await interceptorOptions.next();
393
+ if (!value(this.condition, response, interceptorOptions)) {
394
+ return response;
395
+ }
396
+ const retryAfterHeader = flattenHeader(response.headers["retry-after"]);
397
+ const retryAfterMs = this.parseRetryAfterHeader(retryAfterHeader);
398
+ if (retryAfterMs === void 0) {
399
+ return response;
400
+ }
401
+ if (attemptCount >= value(this.maxAttempts, response, interceptorOptions)) {
402
+ return response;
403
+ }
404
+ const timeoutMs = value(this.timeout, response, interceptorOptions);
405
+ const elapsedTime = Date.now() - startTime;
406
+ if (elapsedTime + retryAfterMs > timeoutMs) {
407
+ return response;
408
+ }
409
+ await this.delayExecution(retryAfterMs, interceptorOptions.signal);
410
+ if (interceptorOptions.signal?.aborted) {
411
+ return response;
412
+ }
413
+ }
414
+ });
415
+ }
416
+ parseRetryAfterHeader(value2) {
417
+ value2 = value2?.trim();
418
+ if (!value2) {
419
+ return void 0;
420
+ }
421
+ const seconds = Number(value2);
422
+ if (Number.isFinite(seconds)) {
423
+ return Math.max(0, seconds * 1e3);
424
+ }
425
+ const retryDate = Date.parse(value2);
426
+ if (!Number.isNaN(retryDate)) {
427
+ return Math.max(0, retryDate - Date.now());
428
+ }
429
+ return void 0;
430
+ }
431
+ delayExecution(ms, signal) {
432
+ return new Promise((resolve) => {
433
+ if (signal?.aborted) {
434
+ resolve();
435
+ return;
436
+ }
437
+ let timeout;
438
+ const onAbort = () => {
439
+ clearTimeout(timeout);
440
+ timeout = void 0;
441
+ resolve();
442
+ };
443
+ signal?.addEventListener("abort", onAbort, { once: true });
444
+ timeout = setTimeout(() => {
445
+ signal?.removeEventListener("abort", onAbort);
446
+ resolve();
447
+ }, ms);
254
448
  });
255
449
  }
256
450
  }
@@ -288,4 +482,4 @@ class SimpleCsrfProtectionLinkPlugin {
288
482
  }
289
483
  }
290
484
 
291
- export { BatchLinkPlugin, ClientRetryPlugin, ClientRetryPluginInvalidEventIteratorRetryResponse, SimpleCsrfProtectionLinkPlugin };
485
+ export { BatchLinkPlugin, ClientRetryPlugin, ClientRetryPluginInvalidEventIteratorRetryResponse, DedupeRequestsPlugin, RetryAfterPlugin, SimpleCsrfProtectionLinkPlugin };
@@ -0,0 +1,83 @@
1
+ import { PromiseWithError } from '@orpc/shared';
2
+
3
+ type HTTPPath = `/${string}`;
4
+ type HTTPMethod = 'HEAD' | 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
5
+ type ClientContext = Record<PropertyKey, any>;
6
+ interface ClientOptions<T extends ClientContext> {
7
+ signal?: AbortSignal;
8
+ lastEventId?: string | undefined;
9
+ context: T;
10
+ }
11
+ type FriendlyClientOptions<T extends ClientContext> = Omit<ClientOptions<T>, 'context'> & (Record<never, never> extends T ? {
12
+ context?: T;
13
+ } : {
14
+ context: T;
15
+ });
16
+ 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>];
17
+ type ClientPromiseResult<TOutput, TError> = PromiseWithError<TOutput, TError>;
18
+ interface Client<TClientContext extends ClientContext, TInput, TOutput, TError> {
19
+ (...rest: ClientRest<TClientContext, TInput>): ClientPromiseResult<TOutput, TError>;
20
+ }
21
+ type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | {
22
+ [k: string]: NestedClient<TClientContext>;
23
+ };
24
+ type InferClientContext<T extends NestedClient<any>> = T extends NestedClient<infer U> ? U : never;
25
+ interface ClientLink<TClientContext extends ClientContext> {
26
+ call: (path: readonly string[], input: unknown, options: ClientOptions<TClientContext>) => Promise<unknown>;
27
+ }
28
+ /**
29
+ * Recursively infers the **input types** from a client.
30
+ *
31
+ * Produces a nested map where each endpoint's input type is preserved.
32
+ */
33
+ type InferClientInputs<T extends NestedClient<any>> = T extends Client<any, infer U, any, any> ? U : {
34
+ [K in keyof T]: T[K] extends NestedClient<any> ? InferClientInputs<T[K]> : never;
35
+ };
36
+ /**
37
+ * Recursively infers the **body input types** from a client.
38
+ *
39
+ * If an endpoint's input includes `{ body: ... }`, only the `body` portion is extracted.
40
+ * Produces a nested map of body input types.
41
+ */
42
+ type InferClientBodyInputs<T extends NestedClient<any>> = T extends Client<any, infer U, any, any> ? U extends {
43
+ body: infer UBody;
44
+ } ? UBody : U : {
45
+ [K in keyof T]: T[K] extends NestedClient<any> ? InferClientBodyInputs<T[K]> : never;
46
+ };
47
+ /**
48
+ * Recursively infers the **output types** from a client.
49
+ *
50
+ * Produces a nested map where each endpoint's output type is preserved.
51
+ */
52
+ type InferClientOutputs<T extends NestedClient<any>> = T extends Client<any, any, infer U, any> ? U : {
53
+ [K in keyof T]: T[K] extends NestedClient<any> ? InferClientOutputs<T[K]> : never;
54
+ };
55
+ /**
56
+ * Recursively infers the **body output types** from a client.
57
+ *
58
+ * If an endpoint's output includes `{ body: ... }`, only the `body` portion is extracted.
59
+ * Produces a nested map of body output types.
60
+ */
61
+ type InferClientBodyOutputs<T extends NestedClient<any>> = T extends Client<any, any, infer U, any> ? U extends {
62
+ body: infer UBody;
63
+ } ? UBody : U : {
64
+ [K in keyof T]: T[K] extends NestedClient<any> ? InferClientBodyOutputs<T[K]> : never;
65
+ };
66
+ /**
67
+ * Recursively infers the **error types** from a client when you use [type-safe errors](https://orpc.unnoq.com/docs/error-handling#type‐safe-error-handling).
68
+ *
69
+ * Produces a nested map where each endpoint's error type is preserved.
70
+ */
71
+ type InferClientErrors<T extends NestedClient<any>> = T extends Client<any, any, any, infer U> ? U : {
72
+ [K in keyof T]: T[K] extends NestedClient<any> ? InferClientErrors<T[K]> : never;
73
+ };
74
+ /**
75
+ * Recursively infers a **union of all error types** from a client when you use [type-safe errors](https://orpc.unnoq.com/docs/error-handling#type‐safe-error-handling).
76
+ *
77
+ * Useful when you want to handle all possible errors from any endpoint at once.
78
+ */
79
+ type InferClientErrorUnion<T extends NestedClient<any>> = T extends Client<any, any, any, infer U> ? U : {
80
+ [K in keyof T]: T[K] extends NestedClient<any> ? InferClientErrorUnion<T[K]> : never;
81
+ }[keyof T];
82
+
83
+ export type { ClientLink as C, FriendlyClientOptions as F, HTTPPath as H, InferClientContext as I, NestedClient as N, ClientPromiseResult as a, ClientContext as b, ClientOptions as c, Client as d, ClientRest as e, HTTPMethod as f, InferClientInputs as g, InferClientBodyInputs as h, InferClientOutputs as i, InferClientBodyOutputs as j, InferClientErrors as k, InferClientErrorUnion as l };