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

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 (94) hide show
  1. package/README.md +6 -7
  2. package/dist/adapters/fetch/index.d.ts +2 -48
  3. package/dist/adapters/fetch/index.js +2 -0
  4. package/dist/adapters/fetch/rpc-link.d.ts +14 -0
  5. package/dist/adapters/fetch/rpc-link.js +14 -0
  6. package/dist/adapters/fetch/transport.d.ts +34 -0
  7. package/dist/adapters/fetch/transport.js +65 -0
  8. package/dist/adapters/message-port/index.d.ts +3 -80
  9. package/dist/adapters/message-port/index.js +3 -0
  10. package/dist/adapters/message-port/message-port.d.ts +29 -0
  11. package/dist/adapters/message-port/message-port.js +56 -0
  12. package/dist/adapters/message-port/rpc-link.d.ts +15 -0
  13. package/dist/adapters/message-port/rpc-link.js +15 -0
  14. package/dist/adapters/message-port/transport.d.ts +38 -0
  15. package/dist/adapters/message-port/transport.js +52 -0
  16. package/dist/adapters/standard/codec.d.ts +14 -0
  17. package/dist/adapters/standard/codec.js +1 -0
  18. package/dist/adapters/standard/index.d.ts +5 -60
  19. package/dist/adapters/standard/index.js +4 -0
  20. package/dist/adapters/standard/link.d.ts +40 -0
  21. package/dist/adapters/standard/link.js +85 -0
  22. package/dist/adapters/standard/plugin.d.ts +32 -0
  23. package/dist/adapters/standard/plugin.js +16 -0
  24. package/dist/adapters/standard/{index.d.mts → rpc-link-codec.d.ts} +17 -14
  25. package/dist/adapters/standard/rpc-link-codec.js +104 -0
  26. package/dist/adapters/standard/transport.d.ts +14 -0
  27. package/dist/adapters/standard/transport.js +1 -0
  28. package/dist/adapters/websocket/index.d.ts +2 -136
  29. package/dist/adapters/websocket/index.js +2 -0
  30. package/dist/adapters/websocket/rpc-link.d.ts +14 -0
  31. package/dist/adapters/websocket/rpc-link.js +14 -0
  32. package/dist/adapters/websocket/{index.d.mts → transport.d.ts} +32 -53
  33. package/dist/adapters/websocket/transport.js +133 -0
  34. package/dist/async-iterator-object.d.ts +2 -0
  35. package/dist/async-iterator-object.js +29 -0
  36. package/dist/client-safe.d.ts +18 -0
  37. package/dist/client-safe.js +36 -0
  38. package/dist/client.d.ts +40 -0
  39. package/dist/client.js +39 -0
  40. package/dist/consts.d.ts +10 -0
  41. package/dist/consts.js +43 -0
  42. package/dist/dynamic-link.d.ts +13 -0
  43. package/dist/dynamic-link.js +17 -0
  44. package/dist/error-utils.d.ts +21 -0
  45. package/dist/error-utils.js +58 -0
  46. package/dist/error.d.ts +132 -0
  47. package/dist/error.js +178 -0
  48. package/dist/index.d.ts +38 -129
  49. package/dist/index.js +40 -0
  50. package/dist/plugins/batch.d.ts +185 -0
  51. package/dist/plugins/batch.js +401 -0
  52. package/dist/plugins/cookie-jar.d.ts +82 -0
  53. package/dist/plugins/cookie-jar.js +268 -0
  54. package/dist/plugins/dedupe.d.ts +64 -0
  55. package/dist/plugins/dedupe.js +226 -0
  56. package/dist/plugins/index.d.ts +20 -412
  57. package/dist/plugins/index.js +23 -0
  58. package/dist/plugins/request-compression.d.ts +44 -0
  59. package/dist/plugins/request-compression.js +178 -0
  60. package/dist/plugins/response-compression.d.ts +28 -0
  61. package/dist/plugins/response-compression.js +91 -0
  62. package/dist/plugins/retry-after.d.ts +50 -0
  63. package/dist/plugins/retry-after.js +88 -0
  64. package/dist/plugins/retry.d.ts +84 -0
  65. package/dist/plugins/retry.js +140 -0
  66. package/dist/plugins/timeout.d.ts +25 -0
  67. package/dist/plugins/timeout.js +37 -0
  68. package/dist/{shared/client.DqIWeNhQ.d.mts → rpc-json-serializer.d.ts} +9 -41
  69. package/dist/rpc-json-serializer.js +392 -0
  70. package/dist/rpc-serializer.d.ts +32 -0
  71. package/dist/rpc-serializer.js +130 -0
  72. package/dist/types.d.ts +97 -0
  73. package/dist/types.js +1 -0
  74. package/dist/utils.d.ts +47 -0
  75. package/dist/utils.js +51 -0
  76. package/package.json +43 -45
  77. package/dist/adapters/fetch/index.d.mts +0 -48
  78. package/dist/adapters/fetch/index.mjs +0 -77
  79. package/dist/adapters/message-port/index.d.mts +0 -80
  80. package/dist/adapters/message-port/index.mjs +0 -101
  81. package/dist/adapters/standard/index.mjs +0 -6
  82. package/dist/adapters/websocket/index.mjs +0 -131
  83. package/dist/index.d.mts +0 -144
  84. package/dist/index.mjs +0 -147
  85. package/dist/plugins/index.d.mts +0 -420
  86. package/dist/plugins/index.mjs +0 -971
  87. package/dist/shared/client.BoHJeq15.d.mts +0 -233
  88. package/dist/shared/client.BoHJeq15.d.ts +0 -233
  89. package/dist/shared/client.CKQeJJ2U.mjs +0 -172
  90. package/dist/shared/client.DqIWeNhQ.d.ts +0 -131
  91. package/dist/shared/client.JBJwBhR8.d.ts +0 -90
  92. package/dist/shared/client.LF04eOvL.mjs +0 -115
  93. package/dist/shared/client._wG5INmC.mjs +0 -505
  94. package/dist/shared/client.euYjjcFz.d.mts +0 -90
@@ -0,0 +1,178 @@
1
+ import { isAsyncIteratorObject, isCompressibleContentType, toArray } from '@orpc/shared';
2
+ import { flattenStandardHeader, generateContentDisposition } from '@standard-server/core';
3
+ import { toFetchBody } from '@standard-server/fetch';
4
+ // Rough UTF-8 estimate. Mostly ASCII text stays close to 1 byte/char;
5
+ // occasional multi-byte characters increase the average.
6
+ const AVG_BYTES_PER_CHAR = 1.2;
7
+ /**
8
+ * Compresses request bodies before sending them to the server,
9
+ * reducing bandwidth usage for large payloads.
10
+ *
11
+ * @see {@link https://orpc.dev/docs/plugins/request-compression | Request Compression Plugin}
12
+ */
13
+ export class RequestCompressionLinkPlugin {
14
+ name = '~request-compression';
15
+ /**
16
+ * Compression should be done after batching, to compress the final request
17
+ */
18
+ after = ['~batch'];
19
+ encoding;
20
+ threshold;
21
+ isCompressibleContentType;
22
+ constructor(options = {}) {
23
+ this.encoding = options.encoding ?? 'gzip';
24
+ this.threshold = options.threshold ?? 1024;
25
+ this.isCompressibleContentType = options.isCompressibleContentType ?? isCompressibleContentType;
26
+ }
27
+ init(options) {
28
+ const transportInterceptor = async ({ next, ...interceptorOptions }) => {
29
+ const request = interceptorOptions.request;
30
+ const contentEncoding = flattenStandardHeader(request.headers['content-encoding'])
31
+ ?.trim()
32
+ ?.toLowerCase();
33
+ if (contentEncoding !== undefined) {
34
+ // already compressed, do not compress again
35
+ return next();
36
+ }
37
+ if (request.body instanceof ReadableStream) {
38
+ const contentLength = Number(flattenStandardHeader(request.headers['content-length']));
39
+ if ((!Number.isFinite(contentLength) || contentLength >= this.threshold) &&
40
+ this.isCompressibleContentType(flattenStandardHeader(request.headers['content-type']), interceptorOptions)) {
41
+ const compressedStream = request.body.pipeThrough(new CompressionStream(this.encoding));
42
+ return next({
43
+ ...interceptorOptions,
44
+ request: {
45
+ ...interceptorOptions.request,
46
+ body: compressedStream,
47
+ headers: {
48
+ ...request.headers,
49
+ 'content-length': [],
50
+ 'content-encoding': this.encoding,
51
+ },
52
+ },
53
+ });
54
+ }
55
+ }
56
+ else if (request.body instanceof Blob) {
57
+ const contentType = request.headers['content-type'] ?? request.body.type;
58
+ if ((!Number.isFinite(request.body.size) || request.body.size >= this.threshold) &&
59
+ this.isCompressibleContentType(flattenStandardHeader(contentType), interceptorOptions)) {
60
+ const compressedStream = request.body
61
+ .stream()
62
+ .pipeThrough(new CompressionStream(this.encoding));
63
+ const contentDisposition = request.headers['content-disposition'] ??
64
+ generateContentDisposition(request.body instanceof File ? request.body.name : 'blob');
65
+ return next({
66
+ ...interceptorOptions,
67
+ request: {
68
+ ...interceptorOptions.request,
69
+ body: compressedStream,
70
+ headers: {
71
+ ...request.headers,
72
+ 'standard-server': request.headers['standard-server'] ?? 'file',
73
+ 'content-type': contentType,
74
+ 'content-length': [],
75
+ 'content-disposition': contentDisposition,
76
+ 'content-encoding': this.encoding,
77
+ },
78
+ },
79
+ });
80
+ }
81
+ }
82
+ else if (request.body instanceof FormData) {
83
+ const PART_OVERHEAD = 64; // approx bytes for boundary + Content-Disposition/Content-Type headers per part
84
+ let contentLength = 0;
85
+ for (const [key, value] of request.body) {
86
+ contentLength += PART_OVERHEAD + key.length;
87
+ if (value instanceof Blob) {
88
+ if (!Number.isFinite(value.size)) {
89
+ // Bun-s3 can use NaN for size
90
+ if (!this.isCompressibleContentType(value.type, interceptorOptions)) {
91
+ // Unknown non-compressible part size makes the estimate unreliable
92
+ contentLength = -Infinity;
93
+ break;
94
+ }
95
+ // Unknown size for compressible content - still apply compression
96
+ contentLength = Infinity;
97
+ }
98
+ else {
99
+ contentLength += this.isCompressibleContentType(value.type, interceptorOptions)
100
+ ? value.size
101
+ : -value.size;
102
+ }
103
+ }
104
+ else {
105
+ contentLength += value.length * AVG_BYTES_PER_CHAR;
106
+ }
107
+ }
108
+ if (contentLength >= this.threshold) {
109
+ const res = new Response(request.body);
110
+ const compressedStream = res.body.pipeThrough(new CompressionStream(this.encoding));
111
+ return next({
112
+ ...interceptorOptions,
113
+ request: {
114
+ ...interceptorOptions.request,
115
+ body: compressedStream,
116
+ headers: {
117
+ ...request.headers,
118
+ 'standard-server': [],
119
+ 'content-type': res.headers.get('content-type'),
120
+ 'content-length': [],
121
+ 'content-encoding': this.encoding,
122
+ },
123
+ },
124
+ });
125
+ }
126
+ }
127
+ else if (request.body instanceof URLSearchParams) {
128
+ const string = request.body.toString();
129
+ if (string.length * AVG_BYTES_PER_CHAR >= this.threshold) {
130
+ const compressedStream = new Blob([string])
131
+ .stream()
132
+ .pipeThrough(new CompressionStream(this.encoding));
133
+ const [, bodyHeaders] = toFetchBody(request.body, request.headers);
134
+ return next({
135
+ ...interceptorOptions,
136
+ request: {
137
+ ...interceptorOptions.request,
138
+ body: compressedStream,
139
+ headers: {
140
+ ...bodyHeaders,
141
+ // An empty hint rather than none, so the adapter does not hint the compressed stream as `octet-stream`
142
+ 'standard-server': bodyHeaders['standard-server'] ?? [],
143
+ 'content-length': [],
144
+ 'content-encoding': this.encoding,
145
+ },
146
+ },
147
+ });
148
+ }
149
+ }
150
+ else if (request.body !== undefined && !isAsyncIteratorObject(request.body)) {
151
+ const [string, bodyHeaders] = toFetchBody(request.body, request.headers);
152
+ if (string.length * AVG_BYTES_PER_CHAR >= this.threshold) {
153
+ const compressedStream = new Blob([string])
154
+ .stream()
155
+ .pipeThrough(new CompressionStream(this.encoding));
156
+ return next({
157
+ ...interceptorOptions,
158
+ request: {
159
+ ...interceptorOptions.request,
160
+ body: compressedStream,
161
+ headers: {
162
+ ...bodyHeaders,
163
+ 'standard-server': bodyHeaders['standard-server'] ?? [],
164
+ 'content-length': [],
165
+ 'content-encoding': this.encoding,
166
+ },
167
+ },
168
+ });
169
+ }
170
+ }
171
+ return next();
172
+ };
173
+ return {
174
+ ...options,
175
+ transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor],
176
+ };
177
+ }
178
+ }
@@ -0,0 +1,28 @@
1
+ import type { StandardLinkOptions, StandardLinkPlugin } from '../adapters/standard/index.ts';
2
+ import type { ClientContext } from '../types.ts';
3
+ export interface ResponseCompressionLinkPluginOptions<_T extends ClientContext> {
4
+ /**
5
+ * Compression schemes to advertise via Accept-Encoding, in preference order.
6
+ * Only schemes that can be decompressed by this plugin should be listed.
7
+ *
8
+ * @default ['gzip', 'deflate']
9
+ */
10
+ encodings?: readonly ('gzip' | 'deflate' | 'deflate-raw')[] | undefined;
11
+ }
12
+ /**
13
+ * Advertises Accept-Encoding on requests and decompresses response bodies
14
+ * based on the Content-Encoding header. Works at the standard link level,
15
+ * so it supports all adapters.
16
+ *
17
+ * @see {@link https://orpc.dev/docs/plugins/response-compression | Response Compression Plugin}
18
+ */
19
+ export declare class ResponseCompressionLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
20
+ name: string;
21
+ /**
22
+ * Decompression should wrap the final batch response instead of sub-responses.
23
+ */
24
+ after: string[];
25
+ private readonly encodings;
26
+ constructor(options?: ResponseCompressionLinkPluginOptions<T>);
27
+ init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
28
+ }
@@ -0,0 +1,91 @@
1
+ import { toArray } from '@orpc/shared';
2
+ import { flattenStandardHeader } from '@standard-server/core';
3
+ import { toFetchHeaders, toStandardBody } from '@standard-server/fetch';
4
+ /**
5
+ * Each coding adds a decompressor to the chain, so an unbounded list lets a tiny
6
+ * response cost unbounded CPU and memory. Same limit as undici and curl.
7
+ */
8
+ const MAX_CONTENT_ENCODINGS = 5;
9
+ /**
10
+ * Advertises Accept-Encoding on requests and decompresses response bodies
11
+ * based on the Content-Encoding header. Works at the standard link level,
12
+ * so it supports all adapters.
13
+ *
14
+ * @see {@link https://orpc.dev/docs/plugins/response-compression | Response Compression Plugin}
15
+ */
16
+ export class ResponseCompressionLinkPlugin {
17
+ name = '~response-compression';
18
+ /**
19
+ * Decompression should wrap the final batch response instead of sub-responses.
20
+ */
21
+ after = ['~batch'];
22
+ encodings;
23
+ constructor(options = {}) {
24
+ this.encodings = options.encodings ?? ['gzip', 'deflate'];
25
+ }
26
+ init(options) {
27
+ const acceptEncodingHeader = this.encodings.join(', ');
28
+ const transportInterceptor = async ({ next, ...interceptorOptions }) => {
29
+ const response = await next({
30
+ ...interceptorOptions,
31
+ request: {
32
+ ...interceptorOptions.request,
33
+ headers: {
34
+ ...interceptorOptions.request.headers,
35
+ 'accept-encoding': acceptEncodingHeader,
36
+ },
37
+ },
38
+ });
39
+ const encodings = parseContentEncodings(flattenStandardHeader(response.headers['content-encoding']));
40
+ if (encodings.length === 0 || !encodings.every(isSupportedEncoding)) {
41
+ return response;
42
+ }
43
+ const decompressedHeaders = {
44
+ ...response.headers,
45
+ 'content-length': undefined,
46
+ 'content-encoding': undefined,
47
+ };
48
+ return {
49
+ ...response,
50
+ headers: decompressedHeaders,
51
+ async resolveBody(hint) {
52
+ const stream = await response.resolveBody('octet-stream');
53
+ // adapter might not support hint (e.g. peer adapter)
54
+ if (!(stream instanceof ReadableStream)) {
55
+ return stream;
56
+ }
57
+ if (encodings.length > MAX_CONTENT_ENCODINGS) {
58
+ throw new TypeError('Too many content encodings.');
59
+ }
60
+ let decompressedStream = stream;
61
+ for (let i = encodings.length - 1; i >= 0; i--) {
62
+ decompressedStream = decompressedStream.pipeThrough(new DecompressionStream(encodings[i]));
63
+ }
64
+ const fetchResponse = new Response(decompressedStream, {
65
+ headers: toFetchHeaders(decompressedHeaders),
66
+ });
67
+ return toStandardBody(fetchResponse, { hint });
68
+ },
69
+ };
70
+ };
71
+ return {
72
+ ...options,
73
+ transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor],
74
+ };
75
+ }
76
+ }
77
+ const SUPPORTED_ENCODINGS = ['gzip', 'deflate', 'deflate-raw'];
78
+ function isSupportedEncoding(encoding) {
79
+ return SUPPORTED_ENCODINGS.includes(encoding);
80
+ }
81
+ /**
82
+ * Parse Content-Encoding into ordered codings (order applied).
83
+ *
84
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-content-encoding
85
+ */
86
+ function parseContentEncodings(header) {
87
+ if (header === undefined) {
88
+ return [];
89
+ }
90
+ return header.split(',').map((part) => part.trim().toLowerCase());
91
+ }
@@ -0,0 +1,50 @@
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';
5
+ 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;
33
+ }
34
+ /**
35
+ * The Retry After Link Plugin automatically retries requests based on server `retry-after` header.
36
+ * This is particularly useful for handling rate limiting and temporary server unavailability.
37
+ *
38
+ * @remarks
39
+ * **Note**: Requests with a stream or async iterator body are never retried, since the body cannot be resent.
40
+ *
41
+ * @see {@link https://orpc.dev/docs/plugins/retry-after | Retry After Plugin}
42
+ */
43
+ 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
+ }
@@ -0,0 +1,88 @@
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';
4
+ /**
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
+ }
74
+ 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;
88
+ }
@@ -0,0 +1,84 @@
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';
4
+ 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;
17
+ }
18
+ /**
19
+ * Client context options that control retry behavior per call
20
+ * when the `RetryLinkPlugin` is enabled.
21
+ *
22
+ * @see {@link https://orpc.dev/docs/plugins/retry | Retry Plugin}
23
+ */
24
+ 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;
53
+ }
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;
59
+ }
60
+ /**
61
+ * Default `shouldRetry` check of `RetryLinkPlugin`. Returns `false` only for errors
62
+ * from a 4xx response other than `408` and `429`.
63
+ *
64
+ * @see {@link https://orpc.dev/docs/plugins/retry#client-error-responses | Retry Plugin - Client Error Responses}
65
+ */
66
+ export declare function isRetryableError(error: unknown): boolean;
67
+ /**
68
+ * Automatically retries failed requests based on customizable retry strategies,
69
+ * improving the resilience of your application.
70
+ *
71
+ * @remarks
72
+ * **Note**: Retry behavior is configured through the client context on each call.
73
+ *
74
+ * @see {@link https://orpc.dev/docs/plugins/retry | Retry Plugin}
75
+ */
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
+ }
@@ -0,0 +1,140 @@
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';
4
+ /**
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);
20
+ }
21
+ /**
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
+ }