@orpc/client 2.0.0-beta.48 → 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.
- package/README.md +4 -4
- package/dist/adapters/fetch/index.d.ts +2 -0
- package/dist/adapters/fetch/index.js +2 -0
- package/dist/adapters/fetch/rpc-link.d.ts +14 -0
- package/dist/adapters/fetch/rpc-link.js +14 -0
- package/dist/adapters/fetch/transport.d.ts +34 -0
- package/dist/adapters/fetch/transport.js +65 -0
- package/dist/adapters/message-port/index.d.ts +3 -0
- package/dist/adapters/message-port/index.js +3 -0
- package/dist/adapters/message-port/message-port.d.ts +29 -0
- package/dist/adapters/message-port/message-port.js +56 -0
- package/dist/adapters/message-port/rpc-link.d.ts +15 -0
- package/dist/adapters/message-port/rpc-link.js +15 -0
- package/dist/adapters/message-port/transport.d.ts +38 -0
- package/dist/adapters/message-port/transport.js +52 -0
- package/dist/adapters/standard/codec.d.ts +14 -0
- package/dist/adapters/standard/index.d.ts +5 -0
- package/dist/adapters/standard/index.js +4 -0
- package/dist/adapters/standard/link.d.ts +40 -0
- package/dist/adapters/standard/link.js +85 -0
- package/dist/adapters/standard/plugin.d.ts +32 -0
- package/dist/adapters/standard/plugin.js +16 -0
- package/dist/adapters/standard/rpc-link-codec.d.ts +63 -0
- package/dist/adapters/standard/rpc-link-codec.js +104 -0
- package/dist/adapters/standard/transport.d.ts +14 -0
- package/dist/adapters/websocket/index.d.ts +2 -0
- package/dist/adapters/websocket/index.js +2 -0
- package/dist/adapters/websocket/rpc-link.d.ts +14 -0
- package/dist/adapters/websocket/rpc-link.js +14 -0
- package/dist/adapters/websocket/transport.d.ts +115 -0
- package/dist/adapters/websocket/transport.js +133 -0
- package/dist/async-iterator-object.d.ts +2 -0
- package/dist/async-iterator-object.js +29 -0
- package/dist/client-safe.d.ts +18 -0
- package/dist/client-safe.js +36 -0
- package/dist/client.d.ts +40 -0
- package/dist/client.js +39 -0
- package/dist/consts.d.ts +10 -0
- package/dist/consts.js +43 -0
- package/dist/dynamic-link.d.ts +13 -0
- package/dist/dynamic-link.js +17 -0
- package/dist/error-utils.d.ts +21 -0
- package/dist/error-utils.js +58 -0
- package/dist/error.d.ts +132 -0
- package/dist/error.js +178 -0
- package/dist/index.d.ts +53 -0
- package/dist/index.js +40 -0
- package/dist/plugins/batch.d.ts +185 -0
- package/dist/plugins/batch.js +401 -0
- package/dist/plugins/cookie-jar.d.ts +82 -0
- package/dist/plugins/cookie-jar.js +268 -0
- package/dist/plugins/dedupe.d.ts +64 -0
- package/dist/plugins/dedupe.js +226 -0
- package/dist/plugins/index.d.ts +28 -0
- package/dist/plugins/index.js +23 -0
- package/dist/plugins/request-compression.d.ts +44 -0
- package/dist/plugins/request-compression.js +178 -0
- package/dist/plugins/response-compression.d.ts +28 -0
- package/dist/plugins/response-compression.js +91 -0
- package/dist/plugins/retry-after.d.ts +50 -0
- package/dist/plugins/retry-after.js +88 -0
- package/dist/plugins/retry.d.ts +84 -0
- package/dist/plugins/retry.js +140 -0
- package/dist/plugins/timeout.d.ts +25 -0
- package/dist/plugins/timeout.js +37 -0
- package/dist/rpc-json-serializer.d.ts +99 -0
- package/dist/rpc-json-serializer.js +392 -0
- package/dist/rpc-serializer.d.ts +32 -0
- package/dist/rpc-serializer.js +130 -0
- package/dist/types.d.ts +97 -0
- package/dist/utils.d.ts +47 -0
- package/dist/utils.js +51 -0
- package/package.json +43 -45
- package/dist/adapters/fetch/index.d.mts +0 -2
- package/dist/adapters/fetch/index.mjs +0 -2
- package/dist/adapters/fetch/rpc-link.d.mts +0 -13
- package/dist/adapters/fetch/rpc-link.mjs +0 -10
- package/dist/adapters/fetch/transport.d.mts +0 -31
- package/dist/adapters/fetch/transport.mjs +0 -65
- package/dist/adapters/message-port/index.d.mts +0 -3
- package/dist/adapters/message-port/index.mjs +0 -3
- package/dist/adapters/message-port/message-port.d.mts +0 -29
- package/dist/adapters/message-port/message-port.mjs +0 -43
- package/dist/adapters/message-port/rpc-link.d.mts +0 -14
- package/dist/adapters/message-port/rpc-link.mjs +0 -10
- package/dist/adapters/message-port/transport.d.mts +0 -35
- package/dist/adapters/message-port/transport.mjs +0 -47
- package/dist/adapters/standard/codec.d.mts +0 -14
- package/dist/adapters/standard/index.d.mts +0 -5
- package/dist/adapters/standard/index.mjs +0 -4
- package/dist/adapters/standard/link.d.mts +0 -40
- package/dist/adapters/standard/link.mjs +0 -79
- package/dist/adapters/standard/plugin.d.mts +0 -32
- package/dist/adapters/standard/plugin.mjs +0 -16
- package/dist/adapters/standard/rpc-link-codec.d.mts +0 -55
- package/dist/adapters/standard/rpc-link-codec.mjs +0 -104
- package/dist/adapters/standard/transport.d.mts +0 -14
- package/dist/adapters/websocket/index.d.mts +0 -2
- package/dist/adapters/websocket/index.mjs +0 -2
- package/dist/adapters/websocket/rpc-link.d.mts +0 -13
- package/dist/adapters/websocket/rpc-link.mjs +0 -10
- package/dist/adapters/websocket/transport.d.mts +0 -119
- package/dist/adapters/websocket/transport.mjs +0 -123
- package/dist/async-iterator-object.d.mts +0 -7
- package/dist/async-iterator-object.mjs +0 -30
- package/dist/client-safe.d.mts +0 -16
- package/dist/client-safe.mjs +0 -23
- package/dist/client.d.mts +0 -51
- package/dist/client.mjs +0 -32
- package/dist/consts.d.mts +0 -10
- package/dist/consts.mjs +0 -10
- package/dist/dynamic-link.d.mts +0 -13
- package/dist/dynamic-link.mjs +0 -12
- package/dist/error-utils.d.mts +0 -24
- package/dist/error-utils.mjs +0 -44
- package/dist/error.d.mts +0 -138
- package/dist/error.mjs +0 -105
- package/dist/index.d.mts +0 -49
- package/dist/index.mjs +0 -23
- package/dist/plugins/batch.d.mts +0 -150
- package/dist/plugins/batch.mjs +0 -339
- package/dist/plugins/cookie-jar.d.mts +0 -82
- package/dist/plugins/cookie-jar.mjs +0 -229
- package/dist/plugins/dedupe.d.mts +0 -58
- package/dist/plugins/dedupe.mjs +0 -199
- package/dist/plugins/index.d.mts +0 -28
- package/dist/plugins/index.mjs +0 -17
- package/dist/plugins/request-compression.d.mts +0 -44
- package/dist/plugins/request-compression.mjs +0 -150
- package/dist/plugins/response-compression.d.mts +0 -28
- package/dist/plugins/response-compression.mjs +0 -78
- package/dist/plugins/retry-after.d.mts +0 -41
- package/dist/plugins/retry-after.mjs +0 -71
- package/dist/plugins/retry.d.mts +0 -82
- package/dist/plugins/retry.mjs +0 -127
- package/dist/plugins/timeout.d.mts +0 -25
- package/dist/plugins/timeout.mjs +0 -36
- package/dist/rpc-json-serializer.d.mts +0 -99
- package/dist/rpc-json-serializer.mjs +0 -365
- package/dist/rpc-serializer.d.mts +0 -32
- package/dist/rpc-serializer.mjs +0 -100
- package/dist/types.d.mts +0 -93
- package/dist/utils.d.mts +0 -46
- package/dist/utils.mjs +0 -53
- /package/dist/adapters/standard/{codec.mjs → codec.js} +0 -0
- /package/dist/adapters/standard/{transport.mjs → transport.js} +0 -0
- /package/dist/{types.mjs → types.js} +0 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { Promisable, Public, Value } from '@orpc/shared';
|
|
2
|
+
import type { StandardHeaders, StandardLazyResponse, StandardRequest, StandardUrl } from '@standard-server/core';
|
|
3
|
+
import { RPCSerializer } from '../../rpc-serializer.ts';
|
|
4
|
+
import type { ClientContext, ClientOptions } from '../../types.ts';
|
|
5
|
+
import type { StandardLinkCodec, StandardLinkCodecDecodedResponse } from '../standard/index.ts';
|
|
6
|
+
export interface RPCLinkCodecOptions<T extends ClientContext> {
|
|
7
|
+
/**
|
|
8
|
+
* Base url for all requests (without origin). Should match with handler's prefix.
|
|
9
|
+
*
|
|
10
|
+
* @example '/rpc?base=1'
|
|
11
|
+
*
|
|
12
|
+
* @default '/'
|
|
13
|
+
*/
|
|
14
|
+
url?: Value<Promisable<StandardUrl>, [options: ClientOptions<T>, path: string[], input: unknown]> | undefined;
|
|
15
|
+
/**
|
|
16
|
+
* The maximum length of the URL.
|
|
17
|
+
*
|
|
18
|
+
* If the URL exceeds this length, the codec should use the `fallbackMethod` to send the request with the payload in the body instead of the URL.
|
|
19
|
+
*
|
|
20
|
+
* @default 2083
|
|
21
|
+
*/
|
|
22
|
+
maxUrlLength?: Value<Promisable<number>, [options: ClientOptions<T>, path: string[], input: unknown]> | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* The method used to make the request.
|
|
25
|
+
*
|
|
26
|
+
* @default 'POST'
|
|
27
|
+
*/
|
|
28
|
+
method?: Value<Promisable<'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'QUERY'>, [
|
|
29
|
+
options: ClientOptions<T>,
|
|
30
|
+
path: string[],
|
|
31
|
+
input: unknown
|
|
32
|
+
]> | undefined;
|
|
33
|
+
/**
|
|
34
|
+
* The method to use when the payload cannot safely pass to the server with method return from method function.
|
|
35
|
+
* GET is not allowed, it's very dangerous.
|
|
36
|
+
*
|
|
37
|
+
* @default 'POST'
|
|
38
|
+
*/
|
|
39
|
+
fallbackMethod?: 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'QUERY' | undefined;
|
|
40
|
+
/**
|
|
41
|
+
* Inject headers to the request.
|
|
42
|
+
*/
|
|
43
|
+
headers?: Value<Promisable<StandardHeaders | Headers>, [
|
|
44
|
+
options: ClientOptions<T>,
|
|
45
|
+
path: string[],
|
|
46
|
+
input: unknown
|
|
47
|
+
]> | undefined;
|
|
48
|
+
/**
|
|
49
|
+
* Override the default RPC serializer.
|
|
50
|
+
*/
|
|
51
|
+
serializer?: Public<RPCSerializer> | undefined;
|
|
52
|
+
}
|
|
53
|
+
export declare class RPCLinkCodec<T extends ClientContext> implements StandardLinkCodec<T> {
|
|
54
|
+
private readonly baseUrl;
|
|
55
|
+
private readonly maxUrlLength;
|
|
56
|
+
private readonly fallbackMethod;
|
|
57
|
+
private readonly expectedMethod;
|
|
58
|
+
private readonly headers;
|
|
59
|
+
private readonly serializer;
|
|
60
|
+
constructor(options: RPCLinkCodecOptions<T>);
|
|
61
|
+
encodeInput(input: unknown, path: string[], options: ClientOptions<T>): Promise<StandardRequest>;
|
|
62
|
+
decodeResponse(response: StandardLazyResponse): Promise<StandardLinkCodecDecodedResponse>;
|
|
63
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { isAsyncIteratorObject, pathToHttpPath, stringifyJSON, value } from '@orpc/shared';
|
|
2
|
+
import { mergeStandardHeaders, parseStandardUrl } from '@standard-server/core';
|
|
3
|
+
import { toStandardHeaders } from '@standard-server/fetch';
|
|
4
|
+
import { createORPCErrorFromJson, isORPCErrorJson } from '../../error-utils.js';
|
|
5
|
+
import { MalformedResponseError, ResponseError } from '../../error.js';
|
|
6
|
+
import { RPCSerializer } from '../../rpc-serializer.js';
|
|
7
|
+
const END_SLASH_REGEX = /\/$/;
|
|
8
|
+
export class RPCLinkCodec {
|
|
9
|
+
baseUrl;
|
|
10
|
+
maxUrlLength;
|
|
11
|
+
fallbackMethod;
|
|
12
|
+
expectedMethod;
|
|
13
|
+
headers;
|
|
14
|
+
serializer;
|
|
15
|
+
constructor(options) {
|
|
16
|
+
this.baseUrl = options.url ?? '/';
|
|
17
|
+
this.maxUrlLength = options.maxUrlLength ?? 2083;
|
|
18
|
+
this.fallbackMethod = options.fallbackMethod ?? 'POST';
|
|
19
|
+
this.expectedMethod = options.method ?? this.fallbackMethod;
|
|
20
|
+
this.headers = options.headers ?? {};
|
|
21
|
+
this.serializer = options.serializer ?? new RPCSerializer();
|
|
22
|
+
}
|
|
23
|
+
async encodeInput(input, path, options) {
|
|
24
|
+
let headers = toResolvedStandardHeaders(await value(this.headers, options, path, input));
|
|
25
|
+
if (options.lastEventId !== undefined) {
|
|
26
|
+
headers = mergeStandardHeaders(headers, { 'last-event-id': options.lastEventId });
|
|
27
|
+
}
|
|
28
|
+
const expectedMethod = await value(this.expectedMethod, options, path, input);
|
|
29
|
+
const baseUrl = await value(this.baseUrl, options, path, input);
|
|
30
|
+
const [pathname, search, hash] = parseStandardUrl(baseUrl);
|
|
31
|
+
const newPathname = `${pathname.replace(END_SLASH_REGEX, '')}${pathToHttpPath(path)}`;
|
|
32
|
+
const serialized = this.serializer.serialize(input);
|
|
33
|
+
if (expectedMethod === 'GET' &&
|
|
34
|
+
!(serialized instanceof Blob) &&
|
|
35
|
+
!(serialized instanceof ReadableStream) &&
|
|
36
|
+
!(serialized instanceof FormData) &&
|
|
37
|
+
!isAsyncIteratorObject(serialized)) {
|
|
38
|
+
const maxUrlLength = await value(this.maxUrlLength, options, path, input);
|
|
39
|
+
const mergedSearch = new URLSearchParams(search);
|
|
40
|
+
mergedSearch.append('data', stringifyJSON(serialized) ?? '');
|
|
41
|
+
const url = `${newPathname}?${mergedSearch}${hash ?? ''}`;
|
|
42
|
+
if (url.length <= maxUrlLength) {
|
|
43
|
+
return {
|
|
44
|
+
body: undefined,
|
|
45
|
+
method: expectedMethod,
|
|
46
|
+
headers,
|
|
47
|
+
url,
|
|
48
|
+
signal: options.signal,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const url = `${newPathname}${search ?? ''}${hash ?? ''}`;
|
|
53
|
+
return {
|
|
54
|
+
url,
|
|
55
|
+
method: expectedMethod === 'GET' ? this.fallbackMethod : expectedMethod,
|
|
56
|
+
headers,
|
|
57
|
+
body: serialized,
|
|
58
|
+
signal: options.signal,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
async decodeResponse(response) {
|
|
62
|
+
const isOk = response.status < 400;
|
|
63
|
+
const body = await response.resolveBody();
|
|
64
|
+
const deserialized = await (async () => {
|
|
65
|
+
try {
|
|
66
|
+
return this.serializer.deserialize(body);
|
|
67
|
+
}
|
|
68
|
+
catch (cause) {
|
|
69
|
+
throw new MalformedResponseError({
|
|
70
|
+
message: isOk ? 'Invalid RPC response format.' : undefined,
|
|
71
|
+
response: { status: response.status, headers: response.headers, body },
|
|
72
|
+
cause,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
})();
|
|
76
|
+
if (!isOk) {
|
|
77
|
+
if (isORPCErrorJson(deserialized)) {
|
|
78
|
+
return {
|
|
79
|
+
kind: 'error',
|
|
80
|
+
error: createORPCErrorFromJson(deserialized, {
|
|
81
|
+
cause: new ResponseError({
|
|
82
|
+
response: { status: response.status, headers: response.headers, body },
|
|
83
|
+
}),
|
|
84
|
+
}),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
throw new MalformedResponseError({
|
|
88
|
+
response: { headers: response.headers, status: response.status, body },
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
return { kind: 'output', output: deserialized };
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
function toResolvedStandardHeaders(headers) {
|
|
95
|
+
/**
|
|
96
|
+
* Headers class might not be available in some environments,
|
|
97
|
+
* so we check for the existence of `forEach` and `get`
|
|
98
|
+
* methods to determine if it's a Headers instance.
|
|
99
|
+
*/
|
|
100
|
+
if (typeof headers.forEach === 'function') {
|
|
101
|
+
return toStandardHeaders(headers);
|
|
102
|
+
}
|
|
103
|
+
return headers;
|
|
104
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { StandardLazyResponse, StandardRequest } from '@standard-server/core';
|
|
2
|
+
import type { ClientContext, ClientOptions } from '../../types.ts';
|
|
3
|
+
/**
|
|
4
|
+
* Handles the transport layer for sending requests and receiving responses.
|
|
5
|
+
*
|
|
6
|
+
* Implementations are responsible for the actual network communication,
|
|
7
|
+
* such as HTTP fetch, WebSocket, or other transport mechanisms.
|
|
8
|
+
*/
|
|
9
|
+
export interface StandardLinkTransport<T extends ClientContext> {
|
|
10
|
+
/**
|
|
11
|
+
* @throws Transport-level errors (network failures, timeouts, etc.)
|
|
12
|
+
*/
|
|
13
|
+
send(request: StandardRequest, path: string[], options: ClientOptions<T>): Promise<StandardLazyResponse>;
|
|
14
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ClientContext } from '../../types.ts';
|
|
2
|
+
import type { RPCLinkCodecOptions, StandardLinkOptions } from '../standard/index.ts';
|
|
3
|
+
import { StandardLink } from '../standard/index.ts';
|
|
4
|
+
import type { WebSocketLinkTransportOptions } from './transport.ts';
|
|
5
|
+
export interface RPCLinkOptions<T extends ClientContext> extends StandardLinkOptions<T>, WebSocketLinkTransportOptions<T>, RPCLinkCodecOptions<T> {
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Client link that communicates with an RPC Handler over a WebSocket connection.
|
|
9
|
+
*
|
|
10
|
+
* @see {@link https://orpc.dev/docs/adapters/websocket | WebSocket Adapters}
|
|
11
|
+
*/
|
|
12
|
+
export declare class RPCLink<T extends ClientContext> extends StandardLink<T> {
|
|
13
|
+
constructor(options: RPCLinkOptions<T>);
|
|
14
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { RPCLinkCodec, StandardLink } from '../standard/index.js';
|
|
2
|
+
import { WebSocketLinkTransport } from './transport.js';
|
|
3
|
+
/**
|
|
4
|
+
* Client link that communicates with an RPC Handler over a WebSocket connection.
|
|
5
|
+
*
|
|
6
|
+
* @see {@link https://orpc.dev/docs/adapters/websocket | WebSocket Adapters}
|
|
7
|
+
*/
|
|
8
|
+
export class RPCLink extends StandardLink {
|
|
9
|
+
constructor(options) {
|
|
10
|
+
const codec = new RPCLinkCodec(options);
|
|
11
|
+
const transport = new WebSocketLinkTransport(options);
|
|
12
|
+
super(codec, transport, options);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { Promisable } from '@orpc/shared';
|
|
2
|
+
import type { StandardLazyResponse, StandardRequest } from '@standard-server/core';
|
|
3
|
+
import type { DecodePeerMessageOptions, EncodePeerMessageOptions } from '@standard-server/peer';
|
|
4
|
+
import type { ClientContext, ClientOptions } from '../../types.ts';
|
|
5
|
+
import type { StandardLinkTransport } from '../standard/index.ts';
|
|
6
|
+
export type WebSocketLike = Pick<WebSocket, 'addEventListener' | 'removeEventListener' | 'send' | 'readyState'>;
|
|
7
|
+
export interface WebSocketLinkTransportAttemptInfo {
|
|
8
|
+
/**
|
|
9
|
+
* Total number of connection attempts for this transport's lifetime.
|
|
10
|
+
* Starts at 1 on the first attempt, increments on every subsequent
|
|
11
|
+
* attempt, and never resets.
|
|
12
|
+
*/
|
|
13
|
+
totalAttempt: number;
|
|
14
|
+
/**
|
|
15
|
+
* Attempt number within the current (re)connect cycle.
|
|
16
|
+
* Starts at 1, increments on each consecutive failure, and resets to 1
|
|
17
|
+
* once a connection succeeds or the cycle gives up. Use this for backoff calculations.
|
|
18
|
+
*/
|
|
19
|
+
attempt: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Reconnection behavior when the connection is lost. Passing it enables reconnection.
|
|
23
|
+
*/
|
|
24
|
+
export interface WebSocketLinkTransportReconnectOptions {
|
|
25
|
+
/**
|
|
26
|
+
* Delay before a (re)connect attempt, in milliseconds.
|
|
27
|
+
*
|
|
28
|
+
* @default info => info.attempt === 1 ? 0 : 2_000
|
|
29
|
+
*/
|
|
30
|
+
delay?: ((info: WebSocketLinkTransportAttemptInfo) => number) | undefined;
|
|
31
|
+
/**
|
|
32
|
+
* Maximum number of consecutive failed attempts before giving up.
|
|
33
|
+
* When reached, calls waiting for the connection fail, and the next
|
|
34
|
+
* call starts a new reconnect cycle.
|
|
35
|
+
* Should greater than 1
|
|
36
|
+
*
|
|
37
|
+
* @default Infinity
|
|
38
|
+
*/
|
|
39
|
+
maxAttempt?: number | undefined;
|
|
40
|
+
/**
|
|
41
|
+
* Maximum number of connection attempts over the transport's lifetime,
|
|
42
|
+
* successful ones included (see `totalAttempt`).
|
|
43
|
+
* When reached, calls that need a new connection fail instead of connecting.
|
|
44
|
+
*
|
|
45
|
+
* @default Infinity
|
|
46
|
+
*/
|
|
47
|
+
maxTotalAttempt?: number | undefined;
|
|
48
|
+
/**
|
|
49
|
+
* Whether to proactively reconnect right after the socket closes,
|
|
50
|
+
* rather than waiting for the next call to trigger reconnection.
|
|
51
|
+
* Reduces latency for the next request.
|
|
52
|
+
*
|
|
53
|
+
* `true` enables it, {@link WebSocketLinkTransportReconnectOnCloseOptions} enables and customizes it.
|
|
54
|
+
*
|
|
55
|
+
* @default false
|
|
56
|
+
*/
|
|
57
|
+
onClose?: boolean | WebSocketLinkTransportReconnectOnCloseOptions | undefined;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Proactive reconnection right after the socket closes. Passing it enables it.
|
|
61
|
+
*/
|
|
62
|
+
export interface WebSocketLinkTransportReconnectOnCloseOptions {
|
|
63
|
+
/**
|
|
64
|
+
* Delay before reconnecting after the socket closes, in milliseconds.
|
|
65
|
+
*
|
|
66
|
+
* @default 0
|
|
67
|
+
*/
|
|
68
|
+
delay?: number | undefined;
|
|
69
|
+
}
|
|
70
|
+
export interface WebSocketLinkTransportOptions<_T extends ClientContext> {
|
|
71
|
+
/**
|
|
72
|
+
* Returns a WebSocket instance for peer communication.
|
|
73
|
+
* Can be async for lazy resolution.
|
|
74
|
+
*/
|
|
75
|
+
connect: (info: WebSocketLinkTransportAttemptInfo) => Promisable<WebSocketLike>;
|
|
76
|
+
/**
|
|
77
|
+
* Whether to connect immediately on initialization, instead of waiting
|
|
78
|
+
* for the first call. Reduces latency for the first request.
|
|
79
|
+
*
|
|
80
|
+
* @default false
|
|
81
|
+
*/
|
|
82
|
+
connectOnInit?: boolean | undefined;
|
|
83
|
+
/**
|
|
84
|
+
* Reconnection when the connection is lost. `true` enables it,
|
|
85
|
+
* {@link WebSocketLinkTransportReconnectOptions} enables and customizes it.
|
|
86
|
+
*
|
|
87
|
+
* @default false
|
|
88
|
+
*/
|
|
89
|
+
reconnect?: boolean | WebSocketLinkTransportReconnectOptions | undefined;
|
|
90
|
+
/**
|
|
91
|
+
* Options for encoding peer messages. such as `prefix` for distinguishing messages on the same channel..
|
|
92
|
+
*/
|
|
93
|
+
encodePeerMessage?: EncodePeerMessageOptions | undefined;
|
|
94
|
+
/**
|
|
95
|
+
* Options for decoding peer messages. such as `prefix` for distinguishing messages on the same channel..
|
|
96
|
+
*/
|
|
97
|
+
decodePeerMessage?: DecodePeerMessageOptions | undefined;
|
|
98
|
+
}
|
|
99
|
+
export declare class WebSocketLinkTransport<T extends ClientContext> implements StandardLinkTransport<T> {
|
|
100
|
+
private readonly connect;
|
|
101
|
+
private readonly reconnectEnabled;
|
|
102
|
+
private readonly reconnectDelay;
|
|
103
|
+
private readonly reconnectMaxAttempt;
|
|
104
|
+
private readonly reconnectMaxTotalAttempt;
|
|
105
|
+
private readonly reconnectOnCloseEnabled;
|
|
106
|
+
private readonly reconnectOnCloseDelay;
|
|
107
|
+
private readonly encodePeerMessageOptions;
|
|
108
|
+
private readonly decodePeerMessageOptions;
|
|
109
|
+
constructor(options: WebSocketLinkTransportOptions<T>);
|
|
110
|
+
send(standardRequest: StandardRequest, _path: string[], _options: ClientOptions<T>): Promise<StandardLazyResponse>;
|
|
111
|
+
private totalAttempt;
|
|
112
|
+
private attempt;
|
|
113
|
+
private current;
|
|
114
|
+
private getConnectedPeer;
|
|
115
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { AbortError, loadBytes, promiseWithResolvers, runWithSignal, sequential, sleep, toStringOrBytes, } from '@orpc/shared';
|
|
2
|
+
import { ClientPeer, decodePeerMessage, encodePeerMessage, isServerPeerSendMessage, } from '@standard-server/peer';
|
|
3
|
+
/**
|
|
4
|
+
* Some env maybe not available WebSocket global, like node 20
|
|
5
|
+
*/
|
|
6
|
+
const WEBSOCKET_CONNECTING = 0;
|
|
7
|
+
const WEBSOCKET_OPEN = 1;
|
|
8
|
+
export class WebSocketLinkTransport {
|
|
9
|
+
connect;
|
|
10
|
+
reconnectEnabled;
|
|
11
|
+
reconnectDelay;
|
|
12
|
+
reconnectMaxAttempt;
|
|
13
|
+
reconnectMaxTotalAttempt;
|
|
14
|
+
reconnectOnCloseEnabled;
|
|
15
|
+
reconnectOnCloseDelay;
|
|
16
|
+
encodePeerMessageOptions;
|
|
17
|
+
decodePeerMessageOptions;
|
|
18
|
+
constructor(options) {
|
|
19
|
+
this.connect = options.connect;
|
|
20
|
+
const reconnect = typeof options.reconnect === 'object' ? options.reconnect : {};
|
|
21
|
+
const onClose = typeof reconnect.onClose === 'object' ? reconnect.onClose : {};
|
|
22
|
+
this.reconnectEnabled = options.reconnect !== undefined && options.reconnect !== false;
|
|
23
|
+
this.reconnectDelay = reconnect.delay ?? ((info) => (info.attempt === 1 ? 0 : 2_000));
|
|
24
|
+
this.reconnectMaxAttempt = reconnect.maxAttempt ?? Infinity;
|
|
25
|
+
this.reconnectMaxTotalAttempt = reconnect.maxTotalAttempt ?? Infinity;
|
|
26
|
+
this.reconnectOnCloseEnabled =
|
|
27
|
+
this.reconnectEnabled && reconnect.onClose !== undefined && reconnect.onClose !== false;
|
|
28
|
+
this.reconnectOnCloseDelay = onClose.delay ?? 0;
|
|
29
|
+
this.encodePeerMessageOptions = options.encodePeerMessage;
|
|
30
|
+
this.decodePeerMessageOptions = options.decodePeerMessage;
|
|
31
|
+
if (options.connectOnInit) {
|
|
32
|
+
this.getConnectedPeer().catch(() => { });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
async send(standardRequest, _path, _options) {
|
|
36
|
+
const peer = await runWithSignal(standardRequest.signal, () => this.getConnectedPeer());
|
|
37
|
+
return peer.request(standardRequest);
|
|
38
|
+
}
|
|
39
|
+
totalAttempt = 0;
|
|
40
|
+
attempt = 0;
|
|
41
|
+
current;
|
|
42
|
+
async getConnectedPeer() {
|
|
43
|
+
const current = this.current;
|
|
44
|
+
const resolved = await current;
|
|
45
|
+
if (resolved && (!this.reconnectEnabled || resolved.websocket.readyState === WEBSOCKET_OPEN)) {
|
|
46
|
+
return resolved.peer;
|
|
47
|
+
}
|
|
48
|
+
if (current !== this.current) {
|
|
49
|
+
return this.getConnectedPeer();
|
|
50
|
+
}
|
|
51
|
+
if (this.totalAttempt >= this.reconnectMaxTotalAttempt) {
|
|
52
|
+
throw new AbortError(`WebSocket reconnect stopped after ${this.totalAttempt} total attempt(s)`);
|
|
53
|
+
}
|
|
54
|
+
this.current = (async () => {
|
|
55
|
+
this.totalAttempt += 1;
|
|
56
|
+
this.attempt += 1;
|
|
57
|
+
const info = {
|
|
58
|
+
totalAttempt: this.totalAttempt,
|
|
59
|
+
attempt: this.attempt,
|
|
60
|
+
};
|
|
61
|
+
await sleep(this.reconnectDelay(info));
|
|
62
|
+
const websocket = await this.connect(info);
|
|
63
|
+
if (websocket.readyState !== WEBSOCKET_CONNECTING &&
|
|
64
|
+
websocket.readyState !== WEBSOCKET_OPEN) {
|
|
65
|
+
throw new AbortError('WebSocket is already closing or closed');
|
|
66
|
+
}
|
|
67
|
+
let closeReason;
|
|
68
|
+
const peer = new ClientPeer(async (message) => {
|
|
69
|
+
// `send` silently discards data once the socket is closed, so requests would never settle
|
|
70
|
+
if (closeReason) {
|
|
71
|
+
throw closeReason;
|
|
72
|
+
}
|
|
73
|
+
const encoded = await encodePeerMessage(message, this.encodePeerMessageOptions);
|
|
74
|
+
return websocket.send(encoded);
|
|
75
|
+
});
|
|
76
|
+
let connectingResolvers;
|
|
77
|
+
if (websocket.readyState === WEBSOCKET_CONNECTING) {
|
|
78
|
+
connectingResolvers = promiseWithResolvers();
|
|
79
|
+
websocket.addEventListener('open', () => {
|
|
80
|
+
connectingResolvers?.resolve();
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Message order is important: loading -> decode -> .message.
|
|
85
|
+
* This flow must stay synchronous, or we need to use `sequential` helper
|
|
86
|
+
*/
|
|
87
|
+
websocket.addEventListener('message', sequential(async (event) => {
|
|
88
|
+
// For better compatibility avoid control or depend on websocket.binaryType
|
|
89
|
+
const message = event.data instanceof Blob ? await loadBytes(event.data) : toStringOrBytes(event.data);
|
|
90
|
+
const result = decodePeerMessage(message, this.decodePeerMessageOptions);
|
|
91
|
+
if (result.matched && isServerPeerSendMessage(result.message)) {
|
|
92
|
+
// Not awaited: `peer.message` runs handling message may be slow,
|
|
93
|
+
// and awaiting it would block decoding of subsequent messages.
|
|
94
|
+
void peer.message(result.message);
|
|
95
|
+
}
|
|
96
|
+
}));
|
|
97
|
+
websocket.addEventListener('close', async (event) => {
|
|
98
|
+
closeReason = new AbortError(`WebSocket closed (code ${event.code}: ${event.reason})`);
|
|
99
|
+
connectingResolvers?.resolve();
|
|
100
|
+
await peer.close(closeReason);
|
|
101
|
+
});
|
|
102
|
+
// EventEmitter-based implementations like `ws` throw an unhandled `error` event,
|
|
103
|
+
// so a refused connection or malformed frame would crash the process. `close` always follows and handles cleanup.
|
|
104
|
+
websocket.addEventListener('error', () => { });
|
|
105
|
+
await connectingResolvers?.promise;
|
|
106
|
+
if (closeReason) {
|
|
107
|
+
throw closeReason;
|
|
108
|
+
}
|
|
109
|
+
if (this.reconnectOnCloseEnabled) {
|
|
110
|
+
websocket.addEventListener('close', () => {
|
|
111
|
+
sleep(this.reconnectOnCloseDelay)
|
|
112
|
+
.then(() => this.getConnectedPeer())
|
|
113
|
+
.catch(() => { });
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
this.attempt = 0;
|
|
117
|
+
return { websocket, peer };
|
|
118
|
+
})().catch((error) => {
|
|
119
|
+
if (!this.reconnectEnabled) {
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
122
|
+
if (this.attempt >= this.reconnectMaxAttempt) {
|
|
123
|
+
const attempt = this.attempt;
|
|
124
|
+
this.attempt = 0;
|
|
125
|
+
this.current = undefined;
|
|
126
|
+
throw new AbortError(`WebSocket reconnect failed after ${attempt} attempt(s)`, {
|
|
127
|
+
cause: error,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
return this.getConnectedPeer();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import type { AsyncIteratorClass, WrapAsyncIteratorOptions } from '@orpc/shared';
|
|
2
|
+
export declare function wrapAsyncIteratorPreservingEventMeta<TYield, TReturn, TMappedYield = TYield, TMappedReturn = TReturn>(iterator: AsyncIterator<TYield, TReturn>, { mapResult, mapError, ...rest }: WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>): AsyncIteratorClass<TMappedYield, TMappedReturn>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { isNonPrimitive, wrapAsyncIterator } from '@orpc/shared';
|
|
2
|
+
import { getEventMeta, withEventMeta } from '@standard-server/core';
|
|
3
|
+
export function wrapAsyncIteratorPreservingEventMeta(iterator, { mapResult, mapError, ...rest }) {
|
|
4
|
+
return wrapAsyncIterator(iterator, {
|
|
5
|
+
...rest,
|
|
6
|
+
mapResult: mapResult &&
|
|
7
|
+
(async (result) => {
|
|
8
|
+
const mapped = await mapResult(result);
|
|
9
|
+
if (mapped.value !== result.value) {
|
|
10
|
+
const meta = getEventMeta(result.value);
|
|
11
|
+
if (meta && isNonPrimitive(mapped.value)) {
|
|
12
|
+
return { done: mapped.done, value: withEventMeta(mapped.value, meta) };
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
return mapped;
|
|
16
|
+
}),
|
|
17
|
+
mapError: mapError &&
|
|
18
|
+
(async (error) => {
|
|
19
|
+
const mapped = await mapError(error);
|
|
20
|
+
if (mapped !== error) {
|
|
21
|
+
const meta = getEventMeta(error);
|
|
22
|
+
if (meta && isNonPrimitive(mapped)) {
|
|
23
|
+
return withEventMeta(mapped, meta);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return mapped;
|
|
27
|
+
}),
|
|
28
|
+
});
|
|
29
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { AnyNestedClient, Client, ClientRest } from './types.ts';
|
|
2
|
+
import type { SafeResult } from './utils.ts';
|
|
3
|
+
export type SafeClient<T extends AnyNestedClient> = T extends Client<infer UContext, infer UInput, infer UOutput, infer UError> ? (...rest: ClientRest<UContext, UInput>) => Promise<SafeResult<UOutput, UError>> : {
|
|
4
|
+
[K in keyof T]: T[K] extends AnyNestedClient ? SafeClient<T[K]> : never;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Create a safe client that automatically wraps all procedure calls with the `safe` util.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* const safeClient = createSafeClient(client)
|
|
12
|
+
* const { error, data, definedError, isSuccess } = await safeClient.doSomething({ id: '123' })
|
|
13
|
+
* // or const [error, data, definedError, isSuccess] = await safeClient.doSomething({ id: '123' })
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* @see {@link https://orpc.dev/docs/client/error-handling#safe-client | Client Error Handling - Safe Client}
|
|
17
|
+
*/
|
|
18
|
+
export declare function createSafeClient<T extends AnyNestedClient>(client: T): SafeClient<T>;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { isNonPrimitive } from '@orpc/shared';
|
|
2
|
+
import { RECURSIVE_CLIENT_UNWRAP_KEYS } from './consts.js';
|
|
3
|
+
import { safe } from './utils.js';
|
|
4
|
+
/**
|
|
5
|
+
* Create a safe client that automatically wraps all procedure calls with the `safe` util.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* const safeClient = createSafeClient(client)
|
|
10
|
+
* const { error, data, definedError, isSuccess } = await safeClient.doSomething({ id: '123' })
|
|
11
|
+
* // or const [error, data, definedError, isSuccess] = await safeClient.doSomething({ id: '123' })
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* @see {@link https://orpc.dev/docs/client/error-handling#safe-client | Client Error Handling - Safe Client}
|
|
15
|
+
*/
|
|
16
|
+
export function createSafeClient(client) {
|
|
17
|
+
const cache = new Map();
|
|
18
|
+
const proxy = new Proxy((...args) => safe(client(...args)), {
|
|
19
|
+
get(target, prop) {
|
|
20
|
+
if (typeof prop !== 'string' || RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop)) {
|
|
21
|
+
return Reflect.get(target, prop);
|
|
22
|
+
}
|
|
23
|
+
let safeClient = cache.get(prop);
|
|
24
|
+
if (safeClient === undefined) {
|
|
25
|
+
const value = client[prop];
|
|
26
|
+
if (!isNonPrimitive(value)) {
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
safeClient = createSafeClient(value);
|
|
30
|
+
cache.set(prop, safeClient);
|
|
31
|
+
}
|
|
32
|
+
return safeClient;
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
return proxy;
|
|
36
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Interceptor, PromiseWithError } from '@orpc/shared';
|
|
2
|
+
import type { AnyNestedClient, Client, ClientContext, ClientLink, ClientOptions, InferClientContext, InferClientError } from './types.ts';
|
|
3
|
+
export interface ORPCClientInterceptorOptions<TClientContext extends ClientContext, TInput> extends ClientOptions<TClientContext> {
|
|
4
|
+
path: string[];
|
|
5
|
+
input: TInput;
|
|
6
|
+
}
|
|
7
|
+
export type ORPCClientInterceptor<TClientContext extends ClientContext, TInput, TOutput, TError> = Interceptor<ORPCClientInterceptorOptions<TClientContext, TInput>, PromiseWithError<TOutput, TError>>;
|
|
8
|
+
export interface ORPCClientScopedOptions<TClientContext extends ClientContext, TInput, TOutput, TError> {
|
|
9
|
+
/**
|
|
10
|
+
* Interceptors that wrap the entire client call lifecycle.
|
|
11
|
+
*/
|
|
12
|
+
interceptors?: ORPCClientInterceptor<TClientContext, TInput, TOutput, TError>[] | undefined;
|
|
13
|
+
}
|
|
14
|
+
export type ORPCClientScoped<T extends AnyNestedClient> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? ORPCClientScopedOptions<UClientContext, UInput, UOutput, UError> : {
|
|
15
|
+
[K in keyof T]?: (T[K] extends AnyNestedClient ? ORPCClientScoped<T[K]> : never) | undefined;
|
|
16
|
+
};
|
|
17
|
+
export interface ORPCClientOptions<T extends AnyNestedClient> {
|
|
18
|
+
/**
|
|
19
|
+
* Use as base path for all procedure, useful when you only want to call a subset of the procedure.
|
|
20
|
+
*/
|
|
21
|
+
path?: string[] | undefined;
|
|
22
|
+
/**
|
|
23
|
+
* Interceptors that wrap the entire client call lifecycle, applied to every procedure call.
|
|
24
|
+
*/
|
|
25
|
+
interceptors?: ORPCClientInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
|
|
26
|
+
/**
|
|
27
|
+
* Per-procedure options following the shape of the router.
|
|
28
|
+
* Allows fine-grained configuration (e.g. additional interceptors) for individual procedures
|
|
29
|
+
* without affecting the rest of the router.
|
|
30
|
+
*/
|
|
31
|
+
scoped?: ORPCClientScoped<T> | undefined;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Creates a fully typed oRPC client from a link.
|
|
35
|
+
* The returned client mirrors the shape of your router or contract,
|
|
36
|
+
* so calling a procedure is as simple as calling a function.
|
|
37
|
+
*
|
|
38
|
+
* @see {@link https://orpc.dev/docs/client/client-side | Client-Side Clients}
|
|
39
|
+
*/
|
|
40
|
+
export declare function createORPCClient<T extends AnyNestedClient>(link: ClientLink<InferClientContext<T>>, { path, ...options }?: NoInfer<ORPCClientOptions<T>>): T;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { intercept, toArray } from '@orpc/shared';
|
|
2
|
+
import { RECURSIVE_CLIENT_UNWRAP_KEYS } from './consts.js';
|
|
3
|
+
import { resolveClientRest } from './utils.js';
|
|
4
|
+
/**
|
|
5
|
+
* Creates a fully typed oRPC client from a link.
|
|
6
|
+
* The returned client mirrors the shape of your router or contract,
|
|
7
|
+
* so calling a procedure is as simple as calling a function.
|
|
8
|
+
*
|
|
9
|
+
* @see {@link https://orpc.dev/docs/client/client-side | Client-Side Clients}
|
|
10
|
+
*/
|
|
11
|
+
export function createORPCClient(link, { path = [], ...options } = {}) {
|
|
12
|
+
const procedureClient = (...rest) => {
|
|
13
|
+
const [input, callOptions] = resolveClientRest(rest);
|
|
14
|
+
const interceptors = [
|
|
15
|
+
...toArray(options.interceptors),
|
|
16
|
+
...toArray(options.scoped?.interceptors),
|
|
17
|
+
];
|
|
18
|
+
return intercept(interceptors, { ...callOptions, input, path }, ({ path, input, ...callOptions }) => link.call(path, input, callOptions));
|
|
19
|
+
};
|
|
20
|
+
const cache = new Map();
|
|
21
|
+
const recursive = new Proxy(procedureClient, {
|
|
22
|
+
get(target, key) {
|
|
23
|
+
if (typeof key !== 'string' || RECURSIVE_CLIENT_UNWRAP_KEYS.has(key)) {
|
|
24
|
+
return Reflect.get(target, key);
|
|
25
|
+
}
|
|
26
|
+
let client = cache.get(key);
|
|
27
|
+
if (client === undefined) {
|
|
28
|
+
client = createORPCClient(link, {
|
|
29
|
+
...options,
|
|
30
|
+
path: [...path, key],
|
|
31
|
+
scoped: options.scoped?.[key],
|
|
32
|
+
});
|
|
33
|
+
cache.set(key, client);
|
|
34
|
+
}
|
|
35
|
+
return client;
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
return recursive;
|
|
39
|
+
}
|
package/dist/consts.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Property names that should resolve to the underlying value instead of
|
|
3
|
+
* continuing recursive proxy traversal.
|
|
4
|
+
*
|
|
5
|
+
* These properties are commonly accessed automatically by JavaScript runtimes,
|
|
6
|
+
* language features, or third-party libraries. Returning another recursive
|
|
7
|
+
* proxy for them can cause unexpected behavior, compatibility issues, or
|
|
8
|
+
* infinite proxy chains.
|
|
9
|
+
*/
|
|
10
|
+
export declare const RECURSIVE_CLIENT_UNWRAP_KEYS: Set<PropertyKey>;
|