@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.
- package/README.md +6 -7
- package/dist/adapters/fetch/index.d.ts +2 -48
- 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 -80
- 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/codec.js +1 -0
- package/dist/adapters/standard/index.d.ts +5 -60
- 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/{index.d.mts → rpc-link-codec.d.ts} +17 -14
- package/dist/adapters/standard/rpc-link-codec.js +104 -0
- package/dist/adapters/standard/transport.d.ts +14 -0
- package/dist/adapters/standard/transport.js +1 -0
- package/dist/adapters/websocket/index.d.ts +2 -136
- 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/{index.d.mts → transport.d.ts} +32 -53
- 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 +38 -129
- 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 +20 -412
- 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/{shared/client.DqIWeNhQ.d.mts → rpc-json-serializer.d.ts} +9 -41
- 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/types.js +1 -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 -48
- package/dist/adapters/fetch/index.mjs +0 -77
- package/dist/adapters/message-port/index.d.mts +0 -80
- package/dist/adapters/message-port/index.mjs +0 -101
- package/dist/adapters/standard/index.mjs +0 -6
- package/dist/adapters/websocket/index.mjs +0 -131
- package/dist/index.d.mts +0 -144
- package/dist/index.mjs +0 -147
- package/dist/plugins/index.d.mts +0 -420
- package/dist/plugins/index.mjs +0 -971
- package/dist/shared/client.BoHJeq15.d.mts +0 -233
- package/dist/shared/client.BoHJeq15.d.ts +0 -233
- package/dist/shared/client.CKQeJJ2U.mjs +0 -172
- package/dist/shared/client.DqIWeNhQ.d.ts +0 -131
- package/dist/shared/client.JBJwBhR8.d.ts +0 -90
- package/dist/shared/client.LF04eOvL.mjs +0 -115
- package/dist/shared/client._wG5INmC.mjs +0 -505
- package/dist/shared/client.euYjjcFz.d.mts +0 -90
|
@@ -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>;
|
package/dist/consts.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
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 const RECURSIVE_CLIENT_UNWRAP_KEYS = /* @__PURE__ */ new Set([
|
|
11
|
+
/**
|
|
12
|
+
* Prevents the client from being treated as a thenable when users
|
|
13
|
+
* accidentally write `await client`.
|
|
14
|
+
*/
|
|
15
|
+
'then',
|
|
16
|
+
/**
|
|
17
|
+
* Commonly used by libraries to bind functions to a specific `this`
|
|
18
|
+
* context.
|
|
19
|
+
*/
|
|
20
|
+
'bind',
|
|
21
|
+
/**
|
|
22
|
+
* Commonly used by libraries to invoke functions with a specific `this`
|
|
23
|
+
* context.
|
|
24
|
+
*/
|
|
25
|
+
'call',
|
|
26
|
+
/**
|
|
27
|
+
* Commonly used by libraries to invoke functions with a specific `this`
|
|
28
|
+
* context and an arguments array.
|
|
29
|
+
*/
|
|
30
|
+
'apply',
|
|
31
|
+
/**
|
|
32
|
+
* Commonly accessed during primitive conversion, inspection, and logging.
|
|
33
|
+
*/
|
|
34
|
+
'valueOf',
|
|
35
|
+
/**
|
|
36
|
+
* Commonly accessed during string conversion, inspection, and logging.
|
|
37
|
+
*/
|
|
38
|
+
'toString',
|
|
39
|
+
/**
|
|
40
|
+
* Commonly accessed by serializers such as `JSON.stringify`.
|
|
41
|
+
*/
|
|
42
|
+
'toJSON',
|
|
43
|
+
]);
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Promisable } from '@orpc/shared';
|
|
2
|
+
import type { ClientContext, ClientLink, ClientOptions } from './types.ts';
|
|
3
|
+
/**
|
|
4
|
+
* DynamicLink provides a way to dynamically resolve and delegate calls to other ClientLinks
|
|
5
|
+
* based on the request path, input, and context.
|
|
6
|
+
*
|
|
7
|
+
* @see {@link https://orpc.dev/docs/client/dynamic-link | DynamicLink}
|
|
8
|
+
*/
|
|
9
|
+
export declare class DynamicLink<TClientContext extends ClientContext> implements ClientLink<TClientContext> {
|
|
10
|
+
private readonly linkResolver;
|
|
11
|
+
constructor(linkResolver: (options: ClientOptions<TClientContext>, path: string[], input: unknown) => Promisable<ClientLink<TClientContext>>);
|
|
12
|
+
call(path: string[], input: unknown, options: ClientOptions<TClientContext>): Promise<unknown>;
|
|
13
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DynamicLink provides a way to dynamically resolve and delegate calls to other ClientLinks
|
|
3
|
+
* based on the request path, input, and context.
|
|
4
|
+
*
|
|
5
|
+
* @see {@link https://orpc.dev/docs/client/dynamic-link | DynamicLink}
|
|
6
|
+
*/
|
|
7
|
+
export class DynamicLink {
|
|
8
|
+
linkResolver;
|
|
9
|
+
constructor(linkResolver) {
|
|
10
|
+
this.linkResolver = linkResolver;
|
|
11
|
+
}
|
|
12
|
+
async call(path, input, options) {
|
|
13
|
+
const resolvedLink = await this.linkResolver(options, path, input);
|
|
14
|
+
const output = await resolvedLink.call(path, input, options);
|
|
15
|
+
return output;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { AnyORPCError, ORPCErrorCode, ORPCErrorJSON } from './error.ts';
|
|
2
|
+
import { ORPCError } from './error.ts';
|
|
3
|
+
/**
|
|
4
|
+
* Checks if an error is an `ORPCError` that matches a definition in the procedure's `.errors` map,
|
|
5
|
+
* narrowing it so `code` and `data` are fully typed.
|
|
6
|
+
*
|
|
7
|
+
* @see {@link https://orpc.dev/docs/client/error-handling#using-safe-and-isdefinederror | Client Error Handling - Using safe and isDefinedError}
|
|
8
|
+
*/
|
|
9
|
+
export declare function isDefinedError<T>(error: T): error is Extract<T, AnyORPCError>;
|
|
10
|
+
export declare function toORPCError<T>(error: T): Extract<T, AnyORPCError> | ORPCError<'INTERNAL_SERVER_ERROR', undefined>;
|
|
11
|
+
export declare function isORPCErrorJson(json: unknown): json is ORPCErrorJSON<ORPCErrorCode, unknown>;
|
|
12
|
+
export declare function createORPCErrorFromJson<TCode extends ORPCErrorCode, TData>(json: ORPCErrorJSON<TCode, TData>, options?: ErrorOptions): ORPCError<TCode, TData>;
|
|
13
|
+
/**
|
|
14
|
+
* Clones an `ORPCError` while preserving its prototype chain, so instances of
|
|
15
|
+
* `ORPCError` subclasses remain `instanceof` their class.
|
|
16
|
+
*
|
|
17
|
+
* Limitation: subclass constructors are not re-run, so private fields
|
|
18
|
+
* (`#field`) are not carried over and subclass members that read them
|
|
19
|
+
* will throw on the clone.
|
|
20
|
+
*/
|
|
21
|
+
export declare function cloneORPCError<T extends AnyORPCError>(error: T): T;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { isPlainObject } from '@orpc/shared';
|
|
2
|
+
import { ORPCError } from './error.js';
|
|
3
|
+
/**
|
|
4
|
+
* Checks if an error is an `ORPCError` that matches a definition in the procedure's `.errors` map,
|
|
5
|
+
* narrowing it so `code` and `data` are fully typed.
|
|
6
|
+
*
|
|
7
|
+
* @see {@link https://orpc.dev/docs/client/error-handling#using-safe-and-isdefinederror | Client Error Handling - Using safe and isDefinedError}
|
|
8
|
+
*/
|
|
9
|
+
export function isDefinedError(error) {
|
|
10
|
+
return error instanceof ORPCError && error.defined;
|
|
11
|
+
}
|
|
12
|
+
export function toORPCError(error) {
|
|
13
|
+
return error instanceof ORPCError
|
|
14
|
+
? error
|
|
15
|
+
: new ORPCError('INTERNAL_SERVER_ERROR', { cause: error });
|
|
16
|
+
}
|
|
17
|
+
export function isORPCErrorJson(json) {
|
|
18
|
+
if (!isPlainObject(json)) {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
const validKeys = ['defined', 'code', 'message', 'data'];
|
|
22
|
+
if (Object.keys(json).some((k) => !validKeys.includes(k))) {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
return ('defined' in json &&
|
|
26
|
+
typeof json.defined === 'boolean' &&
|
|
27
|
+
'code' in json &&
|
|
28
|
+
typeof json.code === 'string' &&
|
|
29
|
+
'message' in json &&
|
|
30
|
+
typeof json.message === 'string');
|
|
31
|
+
}
|
|
32
|
+
export function createORPCErrorFromJson(json, options = {}) {
|
|
33
|
+
const error = new ORPCError(json.code, {
|
|
34
|
+
...json,
|
|
35
|
+
...options,
|
|
36
|
+
});
|
|
37
|
+
error.defined = json.defined;
|
|
38
|
+
return error;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Clones an `ORPCError` while preserving its prototype chain, so instances of
|
|
42
|
+
* `ORPCError` subclasses remain `instanceof` their class.
|
|
43
|
+
*
|
|
44
|
+
* Limitation: subclass constructors are not re-run, so private fields
|
|
45
|
+
* (`#field`) are not carried over and subclass members that read them
|
|
46
|
+
* will throw on the clone.
|
|
47
|
+
*/
|
|
48
|
+
export function cloneORPCError(error) {
|
|
49
|
+
const cloned = new ORPCError(error.code, {
|
|
50
|
+
message: error.message,
|
|
51
|
+
data: error.data,
|
|
52
|
+
cause: error.cause,
|
|
53
|
+
});
|
|
54
|
+
Object.setPrototypeOf(cloned, Object.getPrototypeOf(error));
|
|
55
|
+
Object.defineProperties(cloned, Object.getOwnPropertyDescriptors(error));
|
|
56
|
+
cloned.stack = error.stack;
|
|
57
|
+
return cloned;
|
|
58
|
+
}
|
package/dist/error.d.ts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import type { MaybeOptionalOptions, Registry } from '@orpc/shared';
|
|
2
|
+
import type { StandardResponse } from '@standard-server/core';
|
|
3
|
+
/**
|
|
4
|
+
* Default mapping between common oRPC error codes and HTTP status codes.
|
|
5
|
+
* Handlers use it to determine response status codes; spread it to build a custom `errorStatusMap`.
|
|
6
|
+
*
|
|
7
|
+
* @see {@link https://orpc.dev/docs/rpc/handler#custom-error-response | RPC Handler - Custom Error Response}
|
|
8
|
+
* @see {@link https://orpc.dev/docs/openapi/handler#custom-error-response | OpenAPI Handler - Custom Error Response}
|
|
9
|
+
*/
|
|
10
|
+
export declare const COMMON_ERROR_STATUS_MAP: {
|
|
11
|
+
BAD_REQUEST: number;
|
|
12
|
+
UNAUTHORIZED: number;
|
|
13
|
+
PAYMENT_REQUIRED: number;
|
|
14
|
+
FORBIDDEN: number;
|
|
15
|
+
NOT_FOUND: number;
|
|
16
|
+
METHOD_NOT_SUPPORTED: number;
|
|
17
|
+
NOT_ACCEPTABLE: number;
|
|
18
|
+
TIMEOUT: number;
|
|
19
|
+
CONFLICT: number;
|
|
20
|
+
GONE: number;
|
|
21
|
+
LENGTH_REQUIRED: number;
|
|
22
|
+
PRECONDITION_FAILED: number;
|
|
23
|
+
PAYLOAD_TOO_LARGE: number;
|
|
24
|
+
UNSUPPORTED_MEDIA_TYPE: number;
|
|
25
|
+
UNPROCESSABLE_CONTENT: number;
|
|
26
|
+
PRECONDITION_REQUIRED: number;
|
|
27
|
+
TOO_MANY_REQUESTS: number;
|
|
28
|
+
CLIENT_CLOSED_REQUEST: number;
|
|
29
|
+
INTERNAL_SERVER_ERROR: number;
|
|
30
|
+
NOT_IMPLEMENTED: number;
|
|
31
|
+
BAD_GATEWAY: number;
|
|
32
|
+
SERVICE_UNAVAILABLE: number;
|
|
33
|
+
GATEWAY_TIMEOUT: number;
|
|
34
|
+
};
|
|
35
|
+
export type ORPCErrorCode = Registry extends {
|
|
36
|
+
ORPCErrorCode: infer T extends string;
|
|
37
|
+
} ? T : keyof typeof COMMON_ERROR_STATUS_MAP | (string & {});
|
|
38
|
+
export type ORPCErrorOptions<TData> = ErrorOptions & {
|
|
39
|
+
message?: string | undefined;
|
|
40
|
+
} & (undefined extends TData ? {
|
|
41
|
+
data?: TData;
|
|
42
|
+
} : {
|
|
43
|
+
data: TData;
|
|
44
|
+
});
|
|
45
|
+
/**
|
|
46
|
+
* Typed error carrying a `code`, a `message`, and optional `data`.
|
|
47
|
+
* Throw it from handlers or middleware to produce typed error responses on the client.
|
|
48
|
+
*
|
|
49
|
+
* @see {@link https://orpc.dev/docs/error-handling#orpcerror-class | Error Handling - ORPCError Class}
|
|
50
|
+
*/
|
|
51
|
+
export declare class ORPCError<TCode extends ORPCErrorCode, TData> extends Error {
|
|
52
|
+
/**
|
|
53
|
+
* @remarks
|
|
54
|
+
* **Note**: The `__branch` property is used for type branding, helping TypeScript distinguish
|
|
55
|
+
* an `ORPCError` instance from plain objects with a similar structure.
|
|
56
|
+
*/
|
|
57
|
+
readonly name: 'ORPCError' & {
|
|
58
|
+
__branch: 'ORPCError';
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Indicates whether the error matches a definition in the procedure's `.errors` map,
|
|
62
|
+
* which makes its type inferable on the client.
|
|
63
|
+
*/
|
|
64
|
+
readonly defined: boolean;
|
|
65
|
+
code: TCode;
|
|
66
|
+
data: TData;
|
|
67
|
+
constructor(code: TCode, ...rest: MaybeOptionalOptions<ORPCErrorOptions<TData>>);
|
|
68
|
+
toJSON(): ORPCErrorJSON<TCode, TData>;
|
|
69
|
+
/**
|
|
70
|
+
* Workaround for Next.js where different contexts use separate
|
|
71
|
+
* dependency graphs, causing multiple ORPCError constructors existing and breaking
|
|
72
|
+
* `instanceof` checks across contexts.
|
|
73
|
+
*
|
|
74
|
+
* This is particularly problematic with "Optimized SSR", where orpc-client
|
|
75
|
+
* executes in one context but is invoked from another. When an error is thrown
|
|
76
|
+
* in the execution context, `instanceof ORPCError` checks fail in the
|
|
77
|
+
* invocation context due to separate class constructors.
|
|
78
|
+
*
|
|
79
|
+
* @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
|
|
80
|
+
*/
|
|
81
|
+
static [Symbol.hasInstance](instance: unknown): boolean;
|
|
82
|
+
}
|
|
83
|
+
export interface ORPCErrorJSON<TCode extends string, TData> extends Pick<ORPCError<TCode, TData>, 'code' | 'message' | 'data'> {
|
|
84
|
+
/**
|
|
85
|
+
* remove readonly
|
|
86
|
+
*/
|
|
87
|
+
defined: boolean;
|
|
88
|
+
}
|
|
89
|
+
export type AnyORPCError = ORPCError<any, any>;
|
|
90
|
+
export type AnyORPCErrorJSON = ORPCErrorJSON<any, any>;
|
|
91
|
+
export interface ResponseErrorOptions extends ErrorOptions {
|
|
92
|
+
/**
|
|
93
|
+
* @default inferred from the response status
|
|
94
|
+
*/
|
|
95
|
+
message?: string | undefined;
|
|
96
|
+
response: StandardResponse;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Error carrying the resolved response a link received. Links set it as the `cause`
|
|
100
|
+
* of an `ORPCError` decoded from an error response, so details that are not part
|
|
101
|
+
* of the error itself, such as its status or headers, stay available.
|
|
102
|
+
*
|
|
103
|
+
* @see {@link https://orpc.dev/docs/rpc/link#error-responses | RPC Link - Error Responses}
|
|
104
|
+
* @see {@link https://orpc.dev/docs/openapi/link#error-responses | OpenAPI Link - Error Responses}
|
|
105
|
+
*/
|
|
106
|
+
export declare class ResponseError extends Error {
|
|
107
|
+
readonly name: string;
|
|
108
|
+
response: StandardResponse;
|
|
109
|
+
constructor(options: ResponseErrorOptions);
|
|
110
|
+
}
|
|
111
|
+
export interface MalformedResponseErrorOptions extends ResponseErrorOptions {
|
|
112
|
+
/**
|
|
113
|
+
* @default inferred from the response body or status
|
|
114
|
+
*/
|
|
115
|
+
message?: string | undefined;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Error thrown by links when a response does not follow the expected oRPC format,
|
|
119
|
+
* for example when a proxy or gateway answers instead of your handler. Extends
|
|
120
|
+
* `ResponseError`, so it carries the resolved response. Unless overridden via
|
|
121
|
+
* `options.message`, the message is inferred from the response body or status.
|
|
122
|
+
*
|
|
123
|
+
* Unlike `ORPCError`, it reaches a handler's callers as a generic `INTERNAL_SERVER_ERROR`
|
|
124
|
+
* when thrown from the handler, so an upstream's response is not sent to them.
|
|
125
|
+
*
|
|
126
|
+
* @see {@link https://orpc.dev/docs/rpc/link#malformed-responses | RPC Link - Malformed Responses}
|
|
127
|
+
* @see {@link https://orpc.dev/docs/openapi/link#malformed-responses | OpenAPI Link - Malformed Responses}
|
|
128
|
+
*/
|
|
129
|
+
export declare class MalformedResponseError extends ResponseError {
|
|
130
|
+
readonly name = "MalformedResponseError";
|
|
131
|
+
constructor(options: MalformedResponseErrorOptions);
|
|
132
|
+
}
|