@orpc/client 2.0.0-beta.49 → 2.0.0-beta.50

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 (75) hide show
  1. package/dist/adapters/fetch/index.d.ts +3 -2
  2. package/dist/adapters/fetch/index.js +2 -2
  3. package/dist/adapters/fetch/rpc-link.d.ts +8 -8
  4. package/dist/adapters/fetch/rpc-link.js +16 -13
  5. package/dist/adapters/fetch/transport.d.ts +29 -31
  6. package/dist/adapters/fetch/transport.js +49 -63
  7. package/dist/adapters/message-port/index.d.ts +4 -3
  8. package/dist/adapters/message-port/index.js +3 -3
  9. package/dist/adapters/message-port/message-port.d.ts +13 -13
  10. package/dist/adapters/message-port/message-port.js +35 -53
  11. package/dist/adapters/message-port/rpc-link.d.ts +8 -8
  12. package/dist/adapters/message-port/rpc-link.js +17 -14
  13. package/dist/adapters/message-port/transport.d.ts +31 -34
  14. package/dist/adapters/message-port/transport.js +38 -52
  15. package/dist/adapters/standard/codec.d.ts +10 -10
  16. package/dist/adapters/standard/index.d.ts +6 -5
  17. package/dist/adapters/standard/index.js +2 -4
  18. package/dist/adapters/standard/link.d.ts +31 -31
  19. package/dist/adapters/standard/link.js +101 -85
  20. package/dist/adapters/standard/plugin.d.ts +25 -31
  21. package/dist/adapters/standard/plugin.js +14 -16
  22. package/dist/adapters/standard/rpc-link-codec.d.ts +53 -60
  23. package/dist/adapters/standard/rpc-link-codec.js +98 -102
  24. package/dist/adapters/standard/transport.d.ts +7 -7
  25. package/dist/adapters/websocket/index.d.ts +3 -2
  26. package/dist/adapters/websocket/index.js +2 -2
  27. package/dist/adapters/websocket/rpc-link.d.ts +8 -8
  28. package/dist/adapters/websocket/rpc-link.js +16 -13
  29. package/dist/adapters/websocket/transport.d.ts +101 -100
  30. package/dist/adapters/websocket/transport.js +102 -130
  31. package/dist/async-iterator-object.d.ts +2 -2
  32. package/dist/async-iterator-object.js +27 -28
  33. package/dist/client-safe.d.ts +4 -6
  34. package/dist/client-safe.js +29 -34
  35. package/dist/client.d.ts +24 -26
  36. package/dist/client.js +35 -37
  37. package/dist/consts.d.ts +1 -1
  38. package/dist/consts.js +18 -41
  39. package/dist/dynamic-link.d.ts +6 -6
  40. package/dist/dynamic-link.js +16 -16
  41. package/dist/error-utils.d.ts +3 -4
  42. package/dist/error-utils.js +47 -51
  43. package/dist/error.d.ts +79 -79
  44. package/dist/error.js +154 -166
  45. package/dist/index.d.ts +14 -53
  46. package/dist/index.js +12 -40
  47. package/dist/plugins/batch.d.ts +122 -155
  48. package/dist/plugins/batch.js +320 -391
  49. package/dist/plugins/cookie-jar.d.ts +64 -61
  50. package/dist/plugins/cookie-jar.js +208 -245
  51. package/dist/plugins/dedupe.d.ts +49 -53
  52. package/dist/plugins/dedupe.js +168 -211
  53. package/dist/plugins/index.d.ts +9 -28
  54. package/dist/plugins/index.js +8 -23
  55. package/dist/plugins/request-compression.d.ts +38 -35
  56. package/dist/plugins/request-compression.js +131 -177
  57. package/dist/plugins/response-compression.d.ts +21 -18
  58. package/dist/plugins/response-compression.js +64 -88
  59. package/dist/plugins/retry-after.d.ts +31 -38
  60. package/dist/plugins/retry-after.js +60 -85
  61. package/dist/plugins/retry.d.ts +55 -55
  62. package/dist/plugins/retry.js +118 -137
  63. package/dist/plugins/timeout.d.ts +19 -17
  64. package/dist/plugins/timeout.js +41 -36
  65. package/dist/rpc-json-serializer.d.ts +84 -84
  66. package/dist/rpc-json-serializer.js +338 -383
  67. package/dist/rpc-serializer.d.ts +20 -21
  68. package/dist/rpc-serializer.js +97 -125
  69. package/dist/types.d.ts +19 -31
  70. package/dist/utils.d.ts +18 -29
  71. package/dist/utils.js +63 -47
  72. package/package.json +5 -5
  73. package/dist/adapters/standard/codec.js +0 -1
  74. package/dist/adapters/standard/transport.js +0 -1
  75. package/dist/types.js +0 -1
@@ -1,35 +1,28 @@
1
- import type { Value } from '@orpc/shared';
2
- import type { StandardLazyResponse } from '@standard-server/core';
3
- import type { StandardLinkOptions, StandardLinkPlugin, StandardLinkTransportInterceptorOptions } from '../adapters/standard/index.ts';
4
- import type { ClientContext } from '../types.ts';
1
+ import "../adapters/standard/index.js";
2
+ import { StandardLinkPlugin } from "../adapters/standard/plugin.js";
3
+ import { StandardLinkOptions, StandardLinkTransportInterceptorOptions } from "../adapters/standard/link.js";
4
+ import { ClientContext } from "../types.js";
5
+ import { Value } from "@orpc/shared";
6
+ import { StandardLazyResponse } from "@standard-server/core";
5
7
  export interface RetryAfterLinkPluginOptions<T extends ClientContext> {
6
- /**
7
- * Override condition to determine whether to retry or not.
8
- *
9
- * @default ((response) => response.status === 429 || response.status === 503)
10
- */
11
- condition?: Value<boolean, [
12
- response: StandardLazyResponse,
13
- options: StandardLinkTransportInterceptorOptions<T>
14
- ]> | undefined;
15
- /**
16
- * Maximum attempts before giving up retries.
17
- *
18
- * @default 3
19
- */
20
- maxAttempts?: Value<number, [
21
- response: StandardLazyResponse,
22
- options: StandardLinkTransportInterceptorOptions<T>
23
- ]> | undefined;
24
- /**
25
- * Maximum timeout in milliseconds to wait before giving up retries.
26
- *
27
- * @default 5 * 60 * 1000 (5 minutes)
28
- */
29
- timeout?: Value<number, [
30
- response: StandardLazyResponse,
31
- options: StandardLinkTransportInterceptorOptions<T>
32
- ]> | undefined;
8
+ /**
9
+ * Override condition to determine whether to retry or not.
10
+ *
11
+ * @default ((response) => response.status === 429 || response.status === 503)
12
+ */
13
+ condition?: Value<boolean, [response: StandardLazyResponse, options: StandardLinkTransportInterceptorOptions<T>]> | undefined;
14
+ /**
15
+ * Maximum attempts before giving up retries.
16
+ *
17
+ * @default 3
18
+ */
19
+ maxAttempts?: Value<number, [response: StandardLazyResponse, options: StandardLinkTransportInterceptorOptions<T>]> | undefined;
20
+ /**
21
+ * Maximum timeout in milliseconds to wait before giving up retries.
22
+ *
23
+ * @default 5 * 60 * 1000 (5 minutes)
24
+ */
25
+ timeout?: Value<number, [response: StandardLazyResponse, options: StandardLinkTransportInterceptorOptions<T>]> | undefined;
33
26
  }
34
27
  /**
35
28
  * The Retry After Link Plugin automatically retries requests based on server `retry-after` header.
@@ -41,10 +34,10 @@ export interface RetryAfterLinkPluginOptions<T extends ClientContext> {
41
34
  * @see {@link https://orpc.dev/docs/plugins/retry-after | Retry After Plugin}
42
35
  */
43
36
  export declare class RetryAfterLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
44
- private readonly condition;
45
- private readonly maxAttempts;
46
- private readonly timeout;
47
- name: string;
48
- constructor(options?: RetryAfterLinkPluginOptions<T>);
49
- init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
50
- }
37
+ private readonly condition;
38
+ private readonly maxAttempts;
39
+ private readonly timeout;
40
+ name: string;
41
+ constructor(options?: RetryAfterLinkPluginOptions<T>);
42
+ init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
43
+ }
@@ -1,88 +1,63 @@
1
- import { isAsyncIteratorObject, sleep, toArray, value } from '@orpc/shared';
2
- import { flattenStandardHeader } from '@standard-server/core';
3
- import { COMMON_ERROR_STATUS_MAP } from '../error.js';
1
+ import { COMMON_ERROR_STATUS_MAP } from "../error.js";
2
+ import { isAsyncIteratorObject, sleep, toArray, value } from "@orpc/shared";
3
+ import { flattenStandardHeader } from "@standard-server/core";
4
+ // src/plugins/retry-after.ts
4
5
  /**
5
- * The Retry After Link Plugin automatically retries requests based on server `retry-after` header.
6
- * This is particularly useful for handling rate limiting and temporary server unavailability.
7
- *
8
- * @remarks
9
- * **Note**: Requests with a stream or async iterator body are never retried, since the body cannot be resent.
10
- *
11
- * @see {@link https://orpc.dev/docs/plugins/retry-after | Retry After Plugin}
12
- */
13
- export class RetryAfterLinkPlugin {
14
- condition;
15
- maxAttempts;
16
- timeout;
17
- name = '~retry-after';
18
- constructor(options = {}) {
19
- this.condition =
20
- options.condition ??
21
- ((response) => response.status === COMMON_ERROR_STATUS_MAP.TOO_MANY_REQUESTS ||
22
- response.status === COMMON_ERROR_STATUS_MAP.SERVICE_UNAVAILABLE);
23
- this.maxAttempts = options.maxAttempts ?? 3;
24
- this.timeout = options.timeout ?? 5 * 60 * 1000; // 5 minutes
25
- }
26
- init(options) {
27
- const interceptor = async (interceptorOptions) => {
28
- const { body } = interceptorOptions.request;
29
- /**
30
- * A stream or iterator body is consumed by the first attempt and cannot be resent,
31
- * so return its response as-is instead of retrying with an empty or locked body.
32
- */
33
- if (body instanceof ReadableStream || isAsyncIteratorObject(body)) {
34
- return interceptorOptions.next();
35
- }
36
- const startTime = Date.now();
37
- let attemptCount = 0;
38
- while (true) {
39
- attemptCount++;
40
- const response = await interceptorOptions.next();
41
- if (!value(this.condition, response, interceptorOptions)) {
42
- return response;
43
- }
44
- const retryAfterHeader = flattenStandardHeader(response.headers['retry-after']);
45
- const retryAfterMs = parseRetryAfterHeader(retryAfterHeader);
46
- if (retryAfterMs === undefined) {
47
- return response;
48
- }
49
- if (attemptCount >= value(this.maxAttempts, response, interceptorOptions)) {
50
- return response;
51
- }
52
- const timeoutMs = value(this.timeout, response, interceptorOptions);
53
- const elapsedTime = Date.now() - startTime;
54
- if (elapsedTime + retryAfterMs > timeoutMs) {
55
- return response;
56
- }
57
- try {
58
- await sleep(retryAfterMs, { signal: interceptorOptions.signal });
59
- }
60
- catch {
61
- // can throw if the signal is aborted while sleeping
62
- }
63
- if (interceptorOptions.signal?.aborted) {
64
- return response;
65
- }
66
- }
67
- };
68
- return {
69
- ...options,
70
- transportInterceptors: [interceptor, ...toArray(options.transportInterceptors)],
71
- };
72
- }
73
- }
6
+ * The Retry After Link Plugin automatically retries requests based on server `retry-after` header.
7
+ * This is particularly useful for handling rate limiting and temporary server unavailability.
8
+ *
9
+ * @remarks
10
+ * **Note**: Requests with a stream or async iterator body are never retried, since the body cannot be resent.
11
+ *
12
+ * @see {@link https://orpc.dev/docs/plugins/retry-after | Retry After Plugin}
13
+ */
14
+ var RetryAfterLinkPlugin = class {
15
+ condition;
16
+ maxAttempts;
17
+ timeout;
18
+ name = "~retry-after";
19
+ constructor(options = {}) {
20
+ this.condition = options.condition ?? ((response) => response.status === COMMON_ERROR_STATUS_MAP.TOO_MANY_REQUESTS || response.status === COMMON_ERROR_STATUS_MAP.SERVICE_UNAVAILABLE);
21
+ this.maxAttempts = options.maxAttempts ?? 3;
22
+ this.timeout = options.timeout ?? 3e5;
23
+ }
24
+ init(options) {
25
+ const interceptor = async (interceptorOptions) => {
26
+ const { body } = interceptorOptions.request;
27
+ /**
28
+ * A stream or iterator body is consumed by the first attempt and cannot be resent,
29
+ * so return its response as-is instead of retrying with an empty or locked body.
30
+ */
31
+ if (body instanceof ReadableStream || isAsyncIteratorObject(body)) return interceptorOptions.next();
32
+ const startTime = Date.now();
33
+ let attemptCount = 0;
34
+ while (true) {
35
+ attemptCount++;
36
+ const response = await interceptorOptions.next();
37
+ if (!value(this.condition, response, interceptorOptions)) return response;
38
+ const retryAfterMs = parseRetryAfterHeader(flattenStandardHeader(response.headers["retry-after"]));
39
+ if (retryAfterMs === void 0) return response;
40
+ if (attemptCount >= value(this.maxAttempts, response, interceptorOptions)) return response;
41
+ const timeoutMs = value(this.timeout, response, interceptorOptions);
42
+ if (Date.now() - startTime + retryAfterMs > timeoutMs) return response;
43
+ try {
44
+ await sleep(retryAfterMs, { signal: interceptorOptions.signal });
45
+ } catch {}
46
+ if (interceptorOptions.signal?.aborted) return response;
47
+ }
48
+ };
49
+ return {
50
+ ...options,
51
+ transportInterceptors: [interceptor, ...toArray(options.transportInterceptors)]
52
+ };
53
+ }
54
+ };
74
55
  function parseRetryAfterHeader(value) {
75
- value = value?.trim();
76
- if (!value) {
77
- return undefined;
78
- }
79
- const seconds = Number(value);
80
- if (Number.isFinite(seconds)) {
81
- return Math.max(0, seconds * 1000);
82
- }
83
- const retryDate = Date.parse(value);
84
- if (!Number.isNaN(retryDate)) {
85
- return Math.max(0, retryDate - Date.now());
86
- }
87
- return undefined;
56
+ value = value?.trim();
57
+ if (!value) return;
58
+ const seconds = Number(value);
59
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
60
+ const retryDate = Date.parse(value);
61
+ if (!Number.isNaN(retryDate)) return Math.max(0, retryDate - Date.now());
88
62
  }
63
+ export { RetryAfterLinkPlugin };
@@ -1,19 +1,21 @@
1
- import type { Promisable, Value } from '@orpc/shared';
2
- import type { StandardLinkInterceptorOptions, StandardLinkOptions, StandardLinkPlugin } from '../adapters/standard/index.ts';
3
- import type { ClientContext } from '../types.ts';
1
+ import "../adapters/standard/index.js";
2
+ import { StandardLinkPlugin } from "../adapters/standard/plugin.js";
3
+ import { StandardLinkInterceptorOptions, StandardLinkOptions } from "../adapters/standard/link.js";
4
+ import { ClientContext } from "../types.js";
5
+ import { Promisable, Value } from "@orpc/shared";
4
6
  export interface RetryLinkPluginAttemptOptions<T extends RetryLinkPluginContext> extends StandardLinkInterceptorOptions<T> {
5
- /**
6
- * Latest retry delay advertised by the server via event metadata.
7
- */
8
- lastEventRetry: number | undefined;
9
- /**
10
- * Current retry attempt number, starting at 1.
11
- */
12
- attempt: number;
13
- /**
14
- * Error that triggered this retry attempt.
15
- */
16
- error: unknown;
7
+ /**
8
+ * Latest retry delay advertised by the server via event metadata.
9
+ */
10
+ lastEventRetry: number | undefined;
11
+ /**
12
+ * Current retry attempt number, starting at 1.
13
+ */
14
+ attempt: number;
15
+ /**
16
+ * Error that triggered this retry attempt.
17
+ */
18
+ error: unknown;
17
19
  }
18
20
  /**
19
21
  * Client context options that control retry behavior per call
@@ -22,40 +24,38 @@ export interface RetryLinkPluginAttemptOptions<T extends RetryLinkPluginContext>
22
24
  * @see {@link https://orpc.dev/docs/plugins/retry | Retry Plugin}
23
25
  */
24
26
  export interface RetryLinkPluginContext {
25
- /**
26
- * Maximum retry attempts before throwing.
27
- * Use `Number.POSITIVE_INFINITY` for infinite retries (e.g. for AsyncIteratorObject).
28
- *
29
- * @default 0
30
- */
31
- retry?: Value<Promisable<number>, [
32
- Omit<StandardLinkInterceptorOptions<RetryLinkPluginContext>, 'next'>
33
- ]> | undefined;
34
- /**
35
- * Delay (in ms) before retrying.
36
- *
37
- * @remarks
38
- * **Note**: Why 2000ms? The EventSource spec suggests a default retry delay of 2 seconds if it doesn't specify
39
- *
40
- * @default (o) => o.lastEventRetry ?? 2000
41
- */
42
- retryDelay?: Value<Promisable<number>, [RetryLinkPluginAttemptOptions<RetryLinkPluginContext>]> | undefined;
43
- /**
44
- * Determine whether to retry.
45
- *
46
- * @default (o) => isRetryableError(o.error)
47
- */
48
- shouldRetry?: Value<Promisable<boolean>, [RetryLinkPluginAttemptOptions<RetryLinkPluginContext>]> | undefined;
49
- /**
50
- * Hook called before each retry. Can return a cleanup callback.
51
- */
52
- onRetry?: ((options: RetryLinkPluginAttemptOptions<RetryLinkPluginContext>) => void | ((isSuccess: boolean) => void)) | undefined;
27
+ /**
28
+ * Maximum retry attempts before throwing.
29
+ * Use `Number.POSITIVE_INFINITY` for infinite retries (e.g. for AsyncIteratorObject).
30
+ *
31
+ * @default 0
32
+ */
33
+ retry?: Value<Promisable<number>, [Omit<StandardLinkInterceptorOptions<RetryLinkPluginContext>, "next">]> | undefined;
34
+ /**
35
+ * Delay (in ms) before retrying.
36
+ *
37
+ * @remarks
38
+ * **Note**: Why 2000ms? The EventSource spec suggests a default retry delay of 2 seconds if it doesn't specify
39
+ *
40
+ * @default (o) => o.lastEventRetry ?? 2000
41
+ */
42
+ retryDelay?: Value<Promisable<number>, [RetryLinkPluginAttemptOptions<RetryLinkPluginContext>]> | undefined;
43
+ /**
44
+ * Determine whether to retry.
45
+ *
46
+ * @default (o) => isRetryableError(o.error)
47
+ */
48
+ shouldRetry?: Value<Promisable<boolean>, [RetryLinkPluginAttemptOptions<RetryLinkPluginContext>]> | undefined;
49
+ /**
50
+ * Hook called before each retry. Can return a cleanup callback.
51
+ */
52
+ onRetry?: ((options: RetryLinkPluginAttemptOptions<RetryLinkPluginContext>) => void | ((isSuccess: boolean) => void)) | undefined;
53
53
  }
54
54
  export interface RetryLinkPluginOptions<_T extends RetryLinkPluginContext> {
55
- /**
56
- * Default retry options. Can be overridden by individual calls via the context.
57
- */
58
- default?: RetryLinkPluginContext | undefined;
55
+ /**
56
+ * Default retry options. Can be overridden by individual calls via the context.
57
+ */
58
+ default?: RetryLinkPluginContext | undefined;
59
59
  }
60
60
  /**
61
61
  * Default `shouldRetry` check of `RetryLinkPlugin`. Returns `false` only for errors
@@ -74,11 +74,11 @@ export declare function isRetryableError(error: unknown): boolean;
74
74
  * @see {@link https://orpc.dev/docs/plugins/retry | Retry Plugin}
75
75
  */
76
76
  export declare class RetryLinkPlugin<T extends RetryLinkPluginContext & ClientContext> implements StandardLinkPlugin<T> {
77
- private readonly defaultRetry;
78
- private readonly defaultRetryDelay;
79
- private readonly defaultShouldRetry;
80
- private readonly defaultOnRetry;
81
- name: string;
82
- constructor(options?: RetryLinkPluginOptions<T>);
83
- init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
84
- }
77
+ private readonly defaultRetry;
78
+ private readonly defaultRetryDelay;
79
+ private readonly defaultShouldRetry;
80
+ private readonly defaultOnRetry;
81
+ name: string;
82
+ constructor(options?: RetryLinkPluginOptions<T>);
83
+ init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
84
+ }
@@ -1,140 +1,121 @@
1
- import { AsyncIteratorClass, isAsyncIteratorObject, override, sleep, toArray, value, } from '@orpc/shared';
2
- import { getEventMeta } from '@standard-server/core';
3
- import { COMMON_ERROR_STATUS_MAP, ORPCError, ResponseError } from '../error.js';
1
+ import { COMMON_ERROR_STATUS_MAP, ORPCError, ResponseError } from "../error.js";
2
+ import { AsyncIteratorClass, isAsyncIteratorObject, override, sleep, toArray, value } from "@orpc/shared";
3
+ import { getEventMeta } from "@standard-server/core";
4
+ // src/plugins/retry.ts
4
5
  /**
5
- * Default `shouldRetry` check of `RetryLinkPlugin`. Returns `false` only for errors
6
- * from a 4xx response other than `408` and `429`.
7
- *
8
- * @see {@link https://orpc.dev/docs/plugins/retry#client-error-responses | Retry Plugin - Client Error Responses}
9
- */
10
- export function isRetryableError(error) {
11
- const responseError = error instanceof ORPCError ? error.cause : error;
12
- if (!(responseError instanceof ResponseError)) {
13
- return true;
14
- }
15
- const { status } = responseError.response;
16
- return (status < 400 ||
17
- status >= 500 ||
18
- status === COMMON_ERROR_STATUS_MAP.TIMEOUT ||
19
- status === COMMON_ERROR_STATUS_MAP.TOO_MANY_REQUESTS);
6
+ * Default `shouldRetry` check of `RetryLinkPlugin`. Returns `false` only for errors
7
+ * from a 4xx response other than `408` and `429`.
8
+ *
9
+ * @see {@link https://orpc.dev/docs/plugins/retry#client-error-responses | Retry Plugin - Client Error Responses}
10
+ */
11
+ function isRetryableError(error) {
12
+ const responseError = error instanceof ORPCError ? error.cause : error;
13
+ if (!(responseError instanceof ResponseError)) return true;
14
+ const { status } = responseError.response;
15
+ return status < 400 || status >= 500 || status === COMMON_ERROR_STATUS_MAP.TIMEOUT || status === COMMON_ERROR_STATUS_MAP.TOO_MANY_REQUESTS;
20
16
  }
21
17
  /**
22
- * Automatically retries failed requests based on customizable retry strategies,
23
- * improving the resilience of your application.
24
- *
25
- * @remarks
26
- * **Note**: Retry behavior is configured through the client context on each call.
27
- *
28
- * @see {@link https://orpc.dev/docs/plugins/retry | Retry Plugin}
29
- */
30
- export class RetryLinkPlugin {
31
- defaultRetry;
32
- defaultRetryDelay;
33
- defaultShouldRetry;
34
- defaultOnRetry;
35
- name = '~retry';
36
- constructor(options = {}) {
37
- this.defaultRetry = options.default?.retry ?? 0;
38
- this.defaultRetryDelay = options.default?.retryDelay ?? ((o) => o.lastEventRetry ?? 2000);
39
- this.defaultShouldRetry = options.default?.shouldRetry ?? ((o) => isRetryableError(o.error));
40
- this.defaultOnRetry = options.default?.onRetry;
41
- }
42
- init(options) {
43
- const interceptor = async (interceptorOptions) => {
44
- const { next, ...callOptions } = interceptorOptions;
45
- const maxAttempts = await value(callOptions.context.retry ?? this.defaultRetry, callOptions);
46
- const retryDelay = callOptions.context.retryDelay ?? this.defaultRetryDelay;
47
- const shouldRetry = callOptions.context.shouldRetry ?? this.defaultShouldRetry;
48
- const onRetry = callOptions.context.onRetry ?? this.defaultOnRetry;
49
- if (maxAttempts <= 0) {
50
- return next(callOptions);
51
- }
52
- let lastEventId = callOptions.lastEventId;
53
- let lastEventRetry;
54
- let callback;
55
- let attempt = 1;
56
- let isIteratorAborted = false;
57
- const callNext = async (initialError) => {
58
- let currentError = initialError;
59
- while (true) {
60
- const updatedCallOptions = { ...callOptions, lastEventId };
61
- let retryDelayMs = 0;
62
- if (currentError) {
63
- if (isIteratorAborted || attempt > maxAttempts) {
64
- throw currentError.error;
65
- }
66
- const attemptOptions = {
67
- ...updatedCallOptions,
68
- attempt,
69
- error: currentError.error,
70
- lastEventRetry,
71
- };
72
- const shouldRetryBool = await value(shouldRetry, attemptOptions);
73
- if (!shouldRetryBool) {
74
- throw currentError.error;
75
- }
76
- retryDelayMs = await value(retryDelay, attemptOptions);
77
- callback = onRetry?.(attemptOptions);
78
- }
79
- try {
80
- if (currentError) {
81
- await sleep(retryDelayMs, { signal: updatedCallOptions.signal });
82
- if (isIteratorAborted) {
83
- throw currentError.error;
84
- }
85
- attempt++;
86
- }
87
- currentError = undefined;
88
- return await next(updatedCallOptions);
89
- }
90
- catch (error) {
91
- currentError = { error };
92
- if (updatedCallOptions.signal?.aborted) {
93
- throw error;
94
- }
95
- }
96
- finally {
97
- callback?.(!currentError);
98
- callback = undefined;
99
- }
100
- }
101
- };
102
- const output = await callNext();
103
- if (!isAsyncIteratorObject(output)) {
104
- return output;
105
- }
106
- let current = output;
107
- return override(() => current, new AsyncIteratorClass(async () => {
108
- while (true) {
109
- try {
110
- const item = await current.next();
111
- const meta = getEventMeta(item.value);
112
- lastEventId = meta?.id ?? lastEventId;
113
- lastEventRetry = meta?.retry ?? lastEventRetry;
114
- return item;
115
- }
116
- catch (error) {
117
- const meta = getEventMeta(error);
118
- lastEventId = meta?.id ?? lastEventId;
119
- lastEventRetry = meta?.retry ?? lastEventRetry;
120
- const asyncIteratorObject = await callNext({ error });
121
- if (!isAsyncIteratorObject(asyncIteratorObject)) {
122
- throw new TypeError('RetryLinkPlugin: Expected an AsyncIteratorObject, got a different type.', { cause: error });
123
- }
124
- current = asyncIteratorObject;
125
- if (isIteratorAborted) {
126
- await current.return?.();
127
- throw error;
128
- }
129
- }
130
- }
131
- }, async ({ kind }) => {
132
- isIteratorAborted = true;
133
- if (kind === 'cancelled') {
134
- await current.return?.();
135
- }
136
- }));
137
- };
138
- return { ...options, interceptors: [interceptor, ...toArray(options.interceptors)] };
139
- }
140
- }
18
+ * Automatically retries failed requests based on customizable retry strategies,
19
+ * improving the resilience of your application.
20
+ *
21
+ * @remarks
22
+ * **Note**: Retry behavior is configured through the client context on each call.
23
+ *
24
+ * @see {@link https://orpc.dev/docs/plugins/retry | Retry Plugin}
25
+ */
26
+ var RetryLinkPlugin = class {
27
+ defaultRetry;
28
+ defaultRetryDelay;
29
+ defaultShouldRetry;
30
+ defaultOnRetry;
31
+ name = "~retry";
32
+ constructor(options = {}) {
33
+ this.defaultRetry = options.default?.retry ?? 0;
34
+ this.defaultRetryDelay = options.default?.retryDelay ?? ((o) => o.lastEventRetry ?? 2e3);
35
+ this.defaultShouldRetry = options.default?.shouldRetry ?? ((o) => isRetryableError(o.error));
36
+ this.defaultOnRetry = options.default?.onRetry;
37
+ }
38
+ init(options) {
39
+ const interceptor = async (interceptorOptions) => {
40
+ const { next, ...callOptions } = interceptorOptions;
41
+ const maxAttempts = await value(callOptions.context.retry ?? this.defaultRetry, callOptions);
42
+ const retryDelay = callOptions.context.retryDelay ?? this.defaultRetryDelay;
43
+ const shouldRetry = callOptions.context.shouldRetry ?? this.defaultShouldRetry;
44
+ const onRetry = callOptions.context.onRetry ?? this.defaultOnRetry;
45
+ if (maxAttempts <= 0) return next(callOptions);
46
+ let lastEventId = callOptions.lastEventId;
47
+ let lastEventRetry;
48
+ let callback;
49
+ let attempt = 1;
50
+ let isIteratorAborted = false;
51
+ const callNext = async (initialError) => {
52
+ let currentError = initialError;
53
+ while (true) {
54
+ const updatedCallOptions = {
55
+ ...callOptions,
56
+ lastEventId
57
+ };
58
+ let retryDelayMs = 0;
59
+ if (currentError) {
60
+ if (isIteratorAborted || attempt > maxAttempts) throw currentError.error;
61
+ const attemptOptions = {
62
+ ...updatedCallOptions,
63
+ attempt,
64
+ error: currentError.error,
65
+ lastEventRetry
66
+ };
67
+ if (!await value(shouldRetry, attemptOptions)) throw currentError.error;
68
+ retryDelayMs = await value(retryDelay, attemptOptions);
69
+ callback = onRetry?.(attemptOptions);
70
+ }
71
+ try {
72
+ if (currentError) {
73
+ await sleep(retryDelayMs, { signal: updatedCallOptions.signal });
74
+ if (isIteratorAborted) throw currentError.error;
75
+ attempt++;
76
+ }
77
+ currentError = void 0;
78
+ return await next(updatedCallOptions);
79
+ } catch (error) {
80
+ currentError = { error };
81
+ if (updatedCallOptions.signal?.aborted) throw error;
82
+ } finally {
83
+ callback?.(!currentError);
84
+ callback = void 0;
85
+ }
86
+ }
87
+ };
88
+ const output = await callNext();
89
+ if (!isAsyncIteratorObject(output)) return output;
90
+ let current = output;
91
+ return override(() => current, new AsyncIteratorClass(async () => {
92
+ while (true) try {
93
+ const item = await current.next();
94
+ const meta = getEventMeta(item.value);
95
+ lastEventId = meta?.id ?? lastEventId;
96
+ lastEventRetry = meta?.retry ?? lastEventRetry;
97
+ return item;
98
+ } catch (error) {
99
+ const meta = getEventMeta(error);
100
+ lastEventId = meta?.id ?? lastEventId;
101
+ lastEventRetry = meta?.retry ?? lastEventRetry;
102
+ const asyncIteratorObject = await callNext({ error });
103
+ if (!isAsyncIteratorObject(asyncIteratorObject)) throw new TypeError("RetryLinkPlugin: Expected an AsyncIteratorObject, got a different type.", { cause: error });
104
+ current = asyncIteratorObject;
105
+ if (isIteratorAborted) {
106
+ await current.return?.();
107
+ throw error;
108
+ }
109
+ }
110
+ }, async ({ kind }) => {
111
+ isIteratorAborted = true;
112
+ if (kind === "cancelled") await current.return?.();
113
+ }));
114
+ };
115
+ return {
116
+ ...options,
117
+ interceptors: [interceptor, ...toArray(options.interceptors)]
118
+ };
119
+ }
120
+ };
121
+ export { RetryLinkPlugin, isRetryableError };