@orpc/client 0.0.0-next.b4fc1d9 → 0.0.0-next.b589620

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 (33) hide show
  1. package/README.md +26 -22
  2. package/dist/adapters/fetch/index.d.mts +16 -13
  3. package/dist/adapters/fetch/index.d.ts +16 -13
  4. package/dist/adapters/fetch/index.mjs +5 -13
  5. package/dist/adapters/message-port/index.d.mts +59 -0
  6. package/dist/adapters/message-port/index.d.ts +59 -0
  7. package/dist/adapters/message-port/index.mjs +71 -0
  8. package/dist/adapters/standard/index.d.mts +8 -103
  9. package/dist/adapters/standard/index.d.ts +8 -103
  10. package/dist/adapters/standard/index.mjs +2 -3
  11. package/dist/adapters/websocket/index.d.mts +29 -0
  12. package/dist/adapters/websocket/index.d.ts +29 -0
  13. package/dist/adapters/websocket/index.mjs +44 -0
  14. package/dist/index.d.mts +33 -14
  15. package/dist/index.d.ts +33 -14
  16. package/dist/index.mjs +35 -33
  17. package/dist/plugins/index.d.mts +163 -23
  18. package/dist/plugins/index.d.ts +163 -23
  19. package/dist/plugins/index.mjs +306 -44
  20. package/dist/shared/client.4TS_0JaO.d.mts +29 -0
  21. package/dist/shared/client.4TS_0JaO.d.ts +29 -0
  22. package/dist/shared/client.7UM0t5o-.d.ts +91 -0
  23. package/dist/shared/client.BMoG_EdN.d.mts +46 -0
  24. package/dist/shared/{client.BacCdg3F.mjs → client.BX0_8bnM.mjs} +35 -35
  25. package/dist/shared/client.BdD8cpjs.d.mts +91 -0
  26. package/dist/shared/client.C0KbSWlC.d.ts +46 -0
  27. package/dist/shared/{client.3Q53fveR.mjs → client.CQCGVpTM.mjs} +49 -28
  28. package/package.json +16 -5
  29. package/dist/shared/client.CupM8eRP.d.mts +0 -30
  30. package/dist/shared/client.CupM8eRP.d.ts +0 -30
  31. package/dist/shared/client.CvnV7_uV.mjs +0 -12
  32. package/dist/shared/client.DrOAzyMB.d.mts +0 -45
  33. package/dist/shared/client.aGal-uGY.d.ts +0 -45
@@ -1,12 +1,119 @@
1
- import { C as ClientPlugin, S as StandardLinkOptions } from '../shared/client.aGal-uGY.js';
2
- export { a as CompositeClientPlugin } from '../shared/client.aGal-uGY.js';
3
- import { Value } from '@orpc/shared';
4
- import { C as ClientOptionsOut, a as ClientContext } from '../shared/client.CupM8eRP.js';
5
- import '@orpc/standard-server';
1
+ import { Value, Promisable } from '@orpc/shared';
2
+ import { StandardHeaders, StandardRequest } 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.C0KbSWlC.js';
5
+ import { a as ClientContext } from '../shared/client.4TS_0JaO.js';
6
6
 
7
- interface ClientRetryPluginAttemptOptions {
7
+ interface BatchLinkPluginGroup<T extends ClientContext> {
8
+ condition(options: StandardLinkClientInterceptorOptions<T>): boolean;
9
+ context: T;
10
+ path?: readonly string[];
11
+ input?: unknown;
12
+ }
13
+ interface BatchLinkPluginOptions<T extends ClientContext> {
14
+ groups: readonly [BatchLinkPluginGroup<T>, ...BatchLinkPluginGroup<T>[]];
15
+ /**
16
+ * The maximum number of requests in the batch.
17
+ *
18
+ * @default 10
19
+ */
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>[]]]>;
27
+ /**
28
+ * Defines the URL to use for the batch request.
29
+ *
30
+ * @default the URL of the first request in the batch + '/__batch__'
31
+ */
32
+ url?: Value<Promisable<string | URL>, [readonly [StandardLinkClientInterceptorOptions<T>, ...StandardLinkClientInterceptorOptions<T>[]]]>;
33
+ /**
34
+ * The maximum length of the URL.
35
+ *
36
+ * @default 2083
37
+ */
38
+ maxUrlLength?: Value<Promisable<number>, [readonly [StandardLinkClientInterceptorOptions<T>, ...StandardLinkClientInterceptorOptions<T>[]]]>;
39
+ /**
40
+ * Defines the HTTP headers to use for the batch request.
41
+ *
42
+ * @default The same headers of all requests in the batch
43
+ */
44
+ headers?: Value<Promisable<StandardHeaders>, [readonly [StandardLinkClientInterceptorOptions<T>, ...StandardLinkClientInterceptorOptions<T>[]]]>;
45
+ /**
46
+ * Map the batch request items before sending them.
47
+ *
48
+ * @default Removes headers that are duplicated in the batch headers.
49
+ */
50
+ mapRequestItem?: (options: StandardLinkClientInterceptorOptions<T> & {
51
+ batchUrl: URL;
52
+ batchHeaders: StandardHeaders;
53
+ }) => StandardRequest;
54
+ /**
55
+ * Exclude a request from the batch.
56
+ *
57
+ * @default () => false
58
+ */
59
+ exclude?: (options: StandardLinkClientInterceptorOptions<T>) => boolean;
60
+ }
61
+ /**
62
+ * The Batch Requests Plugin allows you to combine multiple requests and responses into a single batch,
63
+ * reducing the overhead of sending each one separately.
64
+ *
65
+ * @see {@link https://orpc.unnoq.com/docs/plugins/batch-requests Batch Requests Plugin Docs}
66
+ */
67
+ declare class BatchLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
68
+ #private;
69
+ private readonly groups;
70
+ private readonly maxSize;
71
+ private readonly batchUrl;
72
+ private readonly maxUrlLength;
73
+ private readonly batchHeaders;
74
+ private readonly mapRequestItem;
75
+ private readonly exclude;
76
+ private readonly mode;
77
+ private pending;
78
+ order: number;
79
+ constructor(options: NoInfer<BatchLinkPluginOptions<T>>);
80
+ init(options: StandardLinkOptions<T>): void;
81
+ }
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
+
115
+ interface ClientRetryPluginAttemptOptions<T extends ClientContext> extends StandardLinkInterceptorOptions<T> {
8
116
  lastEventRetry: number | undefined;
9
- lastEventId: string | undefined;
10
117
  attemptIndex: number;
11
118
  error: unknown;
12
119
  }
@@ -17,40 +124,35 @@ interface ClientRetryPluginContext {
17
124
  *
18
125
  * @default 0
19
126
  */
20
- retry?: number;
127
+ retry?: Value<Promisable<number>, [StandardLinkInterceptorOptions<ClientRetryPluginContext>]>;
21
128
  /**
22
129
  * Delay (in ms) before retrying.
23
130
  *
24
131
  * @default (o) => o.lastEventRetry ?? 2000
25
132
  */
26
- retryDelay?: Value<number, [
27
- attemptOptions: ClientRetryPluginAttemptOptions,
28
- clientOptions: ClientOptionsOut<ClientRetryPluginContext>,
29
- path: readonly string[],
30
- input: unknown
31
- ]>;
133
+ retryDelay?: Value<Promisable<number>, [ClientRetryPluginAttemptOptions<ClientRetryPluginContext>]>;
32
134
  /**
33
135
  * Determine should retry or not.
34
136
  *
35
137
  * @default true
36
138
  */
37
- shouldRetry?: Value<boolean, [
38
- attemptOptions: ClientRetryPluginAttemptOptions,
39
- clientOptions: ClientOptionsOut<ClientRetryPluginContext>,
40
- path: readonly string[],
41
- input: unknown
42
- ]>;
139
+ shouldRetry?: Value<Promisable<boolean>, [ClientRetryPluginAttemptOptions<ClientRetryPluginContext>]>;
43
140
  /**
44
141
  * The hook called when retrying, and return the unsubscribe function.
45
142
  */
46
- onRetry?: (options: ClientRetryPluginAttemptOptions, clientOptions: ClientOptionsOut<ClientRetryPluginContext>, path: readonly string[], input: unknown) => void | (() => void);
143
+ onRetry?: (options: ClientRetryPluginAttemptOptions<ClientRetryPluginContext>) => void | ((isSuccess: boolean) => void);
47
144
  }
48
145
  declare class ClientRetryPluginInvalidEventIteratorRetryResponse extends Error {
49
146
  }
50
147
  interface ClientRetryPluginOptions {
51
148
  default?: ClientRetryPluginContext;
52
149
  }
53
- declare class ClientRetryPlugin<T extends ClientContext & ClientRetryPluginContext> implements ClientPlugin<T> {
150
+ /**
151
+ * The Client Retry Plugin enables retrying client calls when errors occur.
152
+ *
153
+ * @see {@link https://orpc.unnoq.com/docs/plugins/client-retry Client Retry Plugin Docs}
154
+ */
155
+ declare class ClientRetryPlugin<T extends ClientRetryPluginContext> implements StandardLinkPlugin<T> {
54
156
  private readonly defaultRetry;
55
157
  private readonly defaultRetryDelay;
56
158
  private readonly defaultShouldRetry;
@@ -59,4 +161,42 @@ declare class ClientRetryPlugin<T extends ClientContext & ClientRetryPluginConte
59
161
  init(options: StandardLinkOptions<T>): void;
60
162
  }
61
163
 
62
- export { ClientPlugin, ClientRetryPlugin, type ClientRetryPluginAttemptOptions, type ClientRetryPluginContext, ClientRetryPluginInvalidEventIteratorRetryResponse, type ClientRetryPluginOptions };
164
+ interface SimpleCsrfProtectionLinkPluginOptions<T extends ClientContext> {
165
+ /**
166
+ * The name of the header to check.
167
+ *
168
+ * @default 'x-csrf-token'
169
+ */
170
+ headerName?: Value<Promisable<string>, [options: StandardLinkClientInterceptorOptions<T>]>;
171
+ /**
172
+ * The value of the header to check.
173
+ *
174
+ * @default 'orpc'
175
+ *
176
+ */
177
+ headerValue?: Value<Promisable<string>, [options: StandardLinkClientInterceptorOptions<T>]>;
178
+ /**
179
+ * Exclude a procedure from the plugin.
180
+ *
181
+ * @default false
182
+ */
183
+ exclude?: Value<Promisable<boolean>, [options: StandardLinkClientInterceptorOptions<T>]>;
184
+ }
185
+ /**
186
+ * This plugin adds basic Cross-Site Request Forgery (CSRF) protection to your oRPC application.
187
+ * It helps ensure that requests to your procedures originate from JavaScript code,
188
+ * not from other sources like standard HTML forms or direct browser navigation.
189
+ *
190
+ * @see {@link https://orpc.unnoq.com/docs/plugins/simple-csrf-protection Simple CSRF Protection Plugin Docs}
191
+ */
192
+ declare class SimpleCsrfProtectionLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
193
+ private readonly headerName;
194
+ private readonly headerValue;
195
+ private readonly exclude;
196
+ constructor(options?: SimpleCsrfProtectionLinkPluginOptions<T>);
197
+ order: number;
198
+ init(options: StandardLinkOptions<T>): void;
199
+ }
200
+
201
+ export { BatchLinkPlugin, ClientRetryPlugin, ClientRetryPluginInvalidEventIteratorRetryResponse, DedupeRequestsPlugin, SimpleCsrfProtectionLinkPlugin };
202
+ export type { BatchLinkPluginGroup, BatchLinkPluginOptions, ClientRetryPluginAttemptOptions, ClientRetryPluginContext, ClientRetryPluginOptions, DedupeRequestsPluginGroup, DedupeRequestsPluginOptions, SimpleCsrfProtectionLinkPluginOptions };
@@ -1,6 +1,249 @@
1
- export { C as CompositeClientPlugin } from '../shared/client.CvnV7_uV.mjs';
2
- import { isAsyncIteratorObject, value } from '@orpc/shared';
3
- import { getEventMeta } from '@orpc/standard-server';
1
+ import { isAsyncIteratorObject, defer, value, splitInHalf, toArray, stringifyJSON } from '@orpc/shared';
2
+ import { toBatchRequest, parseBatchResponse, toBatchAbortSignal } from '@orpc/standard-server/batch';
3
+ import { replicateStandardLazyResponse, getEventMeta } from '@orpc/standard-server';
4
+
5
+ class BatchLinkPlugin {
6
+ groups;
7
+ maxSize;
8
+ batchUrl;
9
+ maxUrlLength;
10
+ batchHeaders;
11
+ mapRequestItem;
12
+ exclude;
13
+ mode;
14
+ pending;
15
+ order = 5e6;
16
+ constructor(options) {
17
+ this.groups = options.groups;
18
+ this.pending = /* @__PURE__ */ new Map();
19
+ this.maxSize = options.maxSize ?? 10;
20
+ this.maxUrlLength = options.maxUrlLength ?? 2083;
21
+ this.mode = options.mode ?? "streaming";
22
+ this.batchUrl = options.url ?? (([options2]) => `${options2.request.url.origin}${options2.request.url.pathname}/__batch__`);
23
+ this.batchHeaders = options.headers ?? (([options2, ...rest]) => {
24
+ const headers = {};
25
+ for (const [key, value2] of Object.entries(options2.request.headers)) {
26
+ if (rest.every((item) => item.request.headers[key] === value2)) {
27
+ headers[key] = value2;
28
+ }
29
+ }
30
+ return headers;
31
+ });
32
+ this.mapRequestItem = options.mapRequestItem ?? (({ request, batchHeaders }) => {
33
+ const headers = {};
34
+ for (const [key, value2] of Object.entries(request.headers)) {
35
+ if (batchHeaders[key] !== value2) {
36
+ headers[key] = value2;
37
+ }
38
+ }
39
+ return {
40
+ method: request.method,
41
+ url: request.url,
42
+ headers,
43
+ body: request.body,
44
+ signal: request.signal
45
+ };
46
+ });
47
+ this.exclude = options.exclude ?? (() => false);
48
+ }
49
+ init(options) {
50
+ options.clientInterceptors ??= [];
51
+ options.clientInterceptors.push((options2) => {
52
+ if (options2.request.headers["x-orpc-batch"] !== "1") {
53
+ return options2.next();
54
+ }
55
+ return options2.next({
56
+ ...options2,
57
+ request: {
58
+ ...options2.request,
59
+ headers: {
60
+ ...options2.request.headers,
61
+ "x-orpc-batch": void 0
62
+ }
63
+ }
64
+ });
65
+ });
66
+ options.clientInterceptors.push((options2) => {
67
+ if (this.exclude(options2) || options2.request.body instanceof Blob || options2.request.body instanceof FormData || isAsyncIteratorObject(options2.request.body)) {
68
+ return options2.next();
69
+ }
70
+ const group = this.groups.find((group2) => group2.condition(options2));
71
+ if (!group) {
72
+ return options2.next();
73
+ }
74
+ return new Promise((resolve, reject) => {
75
+ this.#enqueueRequest(group, options2, resolve, reject);
76
+ defer(() => this.#processPendingBatches());
77
+ });
78
+ });
79
+ }
80
+ #enqueueRequest(group, options, resolve, reject) {
81
+ const items = this.pending.get(group);
82
+ if (items) {
83
+ items.push([options, resolve, reject]);
84
+ } else {
85
+ this.pending.set(group, [[options, resolve, reject]]);
86
+ }
87
+ }
88
+ async #processPendingBatches() {
89
+ const pending = this.pending;
90
+ this.pending = /* @__PURE__ */ new Map();
91
+ for (const [group, items] of pending) {
92
+ const getItems = items.filter(([options]) => options.request.method === "GET");
93
+ const restItems = items.filter(([options]) => options.request.method !== "GET");
94
+ this.#executeBatch("GET", group, getItems);
95
+ this.#executeBatch("POST", group, restItems);
96
+ }
97
+ }
98
+ async #executeBatch(method, group, groupItems) {
99
+ if (!groupItems.length) {
100
+ return;
101
+ }
102
+ const batchItems = groupItems;
103
+ if (batchItems.length === 1) {
104
+ batchItems[0][0].next().then(batchItems[0][1]).catch(batchItems[0][2]);
105
+ return;
106
+ }
107
+ try {
108
+ const options = batchItems.map(([options2]) => options2);
109
+ const maxSize = await value(this.maxSize, options);
110
+ if (batchItems.length > maxSize) {
111
+ const [first, second] = splitInHalf(batchItems);
112
+ this.#executeBatch(method, group, first);
113
+ this.#executeBatch(method, group, second);
114
+ return;
115
+ }
116
+ const batchUrl = new URL(await value(this.batchUrl, options));
117
+ const batchHeaders = await value(this.batchHeaders, options);
118
+ const mappedItems = batchItems.map(([options2]) => this.mapRequestItem({ ...options2, batchUrl, batchHeaders }));
119
+ const batchRequest = toBatchRequest({
120
+ method,
121
+ url: batchUrl,
122
+ headers: batchHeaders,
123
+ requests: mappedItems
124
+ });
125
+ const maxUrlLength = await value(this.maxUrlLength, options);
126
+ if (batchRequest.url.toString().length > maxUrlLength) {
127
+ const [first, second] = splitInHalf(batchItems);
128
+ this.#executeBatch(method, group, first);
129
+ this.#executeBatch(method, group, second);
130
+ return;
131
+ }
132
+ const mode = value(this.mode, options);
133
+ const lazyResponse = await options[0].next({
134
+ request: { ...batchRequest, headers: { ...batchRequest.headers, "x-orpc-batch": mode } },
135
+ signal: batchRequest.signal,
136
+ context: group.context,
137
+ input: group.input,
138
+ path: toArray(group.path)
139
+ });
140
+ const parsed = parseBatchResponse({ ...lazyResponse, body: await lazyResponse.body() });
141
+ for await (const item of parsed) {
142
+ batchItems[item.index]?.[1]({ ...item, body: () => Promise.resolve(item.body) });
143
+ }
144
+ throw new Error("Something went wrong make batch response not contains enough responses. This can be a bug please report it.");
145
+ } catch (error) {
146
+ for (const [, , reject] of batchItems) {
147
+ reject(error);
148
+ }
149
+ }
150
+ }
151
+ }
152
+
153
+ class DedupeRequestsPlugin {
154
+ #groups;
155
+ #filter;
156
+ order = 4e6;
157
+ // make sure execute before batch plugin
158
+ #queue = /* @__PURE__ */ new Map();
159
+ constructor(options) {
160
+ this.#groups = options.groups;
161
+ this.#filter = options.filter ?? (({ request }) => request.method === "GET");
162
+ }
163
+ init(options) {
164
+ options.clientInterceptors ??= [];
165
+ options.clientInterceptors.push((options2) => {
166
+ if (options2.request.body instanceof Blob || options2.request.body instanceof FormData || options2.request.body instanceof URLSearchParams || isAsyncIteratorObject(options2.request.body) || !this.#filter(options2)) {
167
+ return options2.next();
168
+ }
169
+ const group = this.#groups.find((group2) => group2.condition(options2));
170
+ if (!group) {
171
+ return options2.next();
172
+ }
173
+ return new Promise((resolve, reject) => {
174
+ this.#enqueue(group, options2, resolve, reject);
175
+ defer(() => this.#dequeue());
176
+ });
177
+ });
178
+ }
179
+ #enqueue(group, options, resolve, reject) {
180
+ let queue = this.#queue.get(group);
181
+ if (!queue) {
182
+ this.#queue.set(group, queue = []);
183
+ }
184
+ const matched = queue.find((item) => {
185
+ const requestString1 = stringifyJSON({
186
+ body: item.options.request.body,
187
+ headers: item.options.request.headers,
188
+ method: item.options.request.method,
189
+ url: item.options.request.url
190
+ });
191
+ const requestString2 = stringifyJSON({
192
+ body: options.request.body,
193
+ headers: options.request.headers,
194
+ method: options.request.method,
195
+ url: options.request.url
196
+ });
197
+ return requestString1 === requestString2;
198
+ });
199
+ if (matched) {
200
+ matched.signals.push(options.request.signal);
201
+ matched.resolves.push(resolve);
202
+ matched.rejects.push(reject);
203
+ } else {
204
+ queue.push({
205
+ options,
206
+ signals: [options.request.signal],
207
+ resolves: [resolve],
208
+ rejects: [reject]
209
+ });
210
+ }
211
+ }
212
+ async #dequeue() {
213
+ const promises = [];
214
+ for (const [group, items] of this.#queue) {
215
+ for (const { options, signals, resolves, rejects } of items) {
216
+ promises.push(
217
+ this.#execute(group, options, signals, resolves, rejects)
218
+ );
219
+ }
220
+ }
221
+ this.#queue.clear();
222
+ await Promise.all(promises);
223
+ }
224
+ async #execute(group, options, signals, resolves, rejects) {
225
+ try {
226
+ const dedupedRequest = {
227
+ ...options.request,
228
+ signal: toBatchAbortSignal(signals)
229
+ };
230
+ const response = await options.next({
231
+ ...options,
232
+ request: dedupedRequest,
233
+ signal: dedupedRequest.signal,
234
+ context: group.context
235
+ });
236
+ const replicatedResponses = replicateStandardLazyResponse(response, resolves.length);
237
+ for (const resolve of resolves) {
238
+ resolve(replicatedResponses.shift());
239
+ }
240
+ } catch (error) {
241
+ for (const reject of rejects) {
242
+ reject(error);
243
+ }
244
+ }
245
+ }
246
+ }
4
247
 
5
248
  class ClientRetryPluginInvalidEventIteratorRetryResponse extends Error {
6
249
  }
@@ -18,71 +261,57 @@ class ClientRetryPlugin {
18
261
  init(options) {
19
262
  options.interceptors ??= [];
20
263
  options.interceptors.push(async (interceptorOptions) => {
21
- const maxAttempts = interceptorOptions.options.context.retry ?? this.defaultRetry;
22
- const retryDelay = interceptorOptions.options.context.retryDelay ?? this.defaultRetryDelay;
23
- const shouldRetry = interceptorOptions.options.context.shouldRetry ?? this.defaultShouldRetry;
24
- const onRetry = interceptorOptions.options.context.onRetry ?? this.defaultOnRetry;
264
+ const maxAttempts = await value(
265
+ interceptorOptions.context.retry ?? this.defaultRetry,
266
+ interceptorOptions
267
+ );
268
+ const retryDelay = interceptorOptions.context.retryDelay ?? this.defaultRetryDelay;
269
+ const shouldRetry = interceptorOptions.context.shouldRetry ?? this.defaultShouldRetry;
270
+ const onRetry = interceptorOptions.context.onRetry ?? this.defaultOnRetry;
25
271
  if (maxAttempts <= 0) {
26
272
  return interceptorOptions.next();
27
273
  }
28
- let lastEventId = interceptorOptions.options.lastEventId;
274
+ let lastEventId = interceptorOptions.lastEventId;
29
275
  let lastEventRetry;
30
- let unsubscribe;
276
+ let callback;
31
277
  let attemptIndex = 0;
32
- const next = async (initial) => {
33
- let current = initial;
278
+ const next = async (initialError) => {
279
+ let currentError = initialError;
34
280
  while (true) {
35
- const newClientOptions = { ...interceptorOptions.options, lastEventId };
36
- if (current) {
281
+ const updatedInterceptorOptions = { ...interceptorOptions, lastEventId };
282
+ if (currentError) {
37
283
  if (attemptIndex >= maxAttempts) {
38
- throw current.error;
284
+ throw currentError.error;
39
285
  }
40
286
  const attemptOptions = {
287
+ ...updatedInterceptorOptions,
41
288
  attemptIndex,
42
- error: current.error,
43
- lastEventId,
289
+ error: currentError.error,
44
290
  lastEventRetry
45
291
  };
46
292
  const shouldRetryBool = await value(
47
293
  shouldRetry,
48
- attemptOptions,
49
- newClientOptions,
50
- interceptorOptions.path,
51
- interceptorOptions.input
294
+ attemptOptions
52
295
  );
53
296
  if (!shouldRetryBool) {
54
- throw current.error;
297
+ throw currentError.error;
55
298
  }
56
- unsubscribe = onRetry?.(
57
- attemptOptions,
58
- newClientOptions,
59
- interceptorOptions.path,
60
- interceptorOptions.input
61
- );
62
- const retryDelayMs = await value(
63
- retryDelay,
64
- attemptOptions,
65
- newClientOptions,
66
- interceptorOptions.path,
67
- interceptorOptions.input
68
- );
299
+ callback = onRetry?.(attemptOptions);
300
+ const retryDelayMs = await value(retryDelay, attemptOptions);
69
301
  await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
70
302
  attemptIndex++;
71
303
  }
72
304
  try {
73
- const output2 = await interceptorOptions.next({
74
- ...interceptorOptions,
75
- options: newClientOptions
76
- });
77
- return output2;
305
+ currentError = void 0;
306
+ return await interceptorOptions.next(updatedInterceptorOptions);
78
307
  } catch (error) {
79
- if (newClientOptions.signal?.aborted === true) {
308
+ currentError = { error };
309
+ if (updatedInterceptorOptions.signal?.aborted === true) {
80
310
  throw error;
81
311
  }
82
- current = { error };
83
312
  } finally {
84
- unsubscribe?.();
85
- unsubscribe = void 0;
313
+ callback?.(!currentError);
314
+ callback = void 0;
86
315
  }
87
316
  }
88
317
  };
@@ -124,4 +353,37 @@ class ClientRetryPlugin {
124
353
  }
125
354
  }
126
355
 
127
- export { ClientRetryPlugin, ClientRetryPluginInvalidEventIteratorRetryResponse };
356
+ class SimpleCsrfProtectionLinkPlugin {
357
+ headerName;
358
+ headerValue;
359
+ exclude;
360
+ constructor(options = {}) {
361
+ this.headerName = options.headerName ?? "x-csrf-token";
362
+ this.headerValue = options.headerValue ?? "orpc";
363
+ this.exclude = options.exclude ?? false;
364
+ }
365
+ order = 8e6;
366
+ init(options) {
367
+ options.clientInterceptors ??= [];
368
+ options.clientInterceptors.push(async (options2) => {
369
+ const excluded = await value(this.exclude, options2);
370
+ if (excluded) {
371
+ return options2.next();
372
+ }
373
+ const headerName = await value(this.headerName, options2);
374
+ const headerValue = await value(this.headerValue, options2);
375
+ return options2.next({
376
+ ...options2,
377
+ request: {
378
+ ...options2.request,
379
+ headers: {
380
+ ...options2.request.headers,
381
+ [headerName]: headerValue
382
+ }
383
+ }
384
+ });
385
+ });
386
+ }
387
+ }
388
+
389
+ export { BatchLinkPlugin, ClientRetryPlugin, ClientRetryPluginInvalidEventIteratorRetryResponse, DedupeRequestsPlugin, SimpleCsrfProtectionLinkPlugin };
@@ -0,0 +1,29 @@
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
+ export type { ClientLink as C, FriendlyClientOptions as F, HTTPPath as H, InferClientContext as I, NestedClient as N, ClientContext as a, ClientOptions as b, ClientPromiseResult as c, HTTPMethod as d, ClientRest as e, Client as f };
@@ -0,0 +1,29 @@
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
+ export type { ClientLink as C, FriendlyClientOptions as F, HTTPPath as H, InferClientContext as I, NestedClient as N, ClientContext as a, ClientOptions as b, ClientPromiseResult as c, HTTPMethod as d, ClientRest as e, Client as f };