@orpc/client 1.14.6 → 2.0.0-beta.10

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 (38) hide show
  1. package/README.md +78 -107
  2. package/dist/adapters/fetch/index.d.mts +54 -35
  3. package/dist/adapters/fetch/index.d.ts +54 -35
  4. package/dist/adapters/fetch/index.mjs +49 -27
  5. package/dist/adapters/message-port/index.d.mts +25 -30
  6. package/dist/adapters/message-port/index.d.ts +25 -30
  7. package/dist/adapters/message-port/index.mjs +33 -29
  8. package/dist/adapters/standard/index.d.mts +59 -9
  9. package/dist/adapters/standard/index.d.ts +59 -9
  10. package/dist/adapters/standard/index.mjs +5 -5
  11. package/dist/adapters/websocket/index.d.mts +113 -21
  12. package/dist/adapters/websocket/index.d.ts +113 -21
  13. package/dist/adapters/websocket/index.mjs +95 -37
  14. package/dist/index.d.mts +84 -159
  15. package/dist/index.d.ts +84 -159
  16. package/dist/index.mjs +76 -34
  17. package/dist/plugins/index.d.mts +125 -132
  18. package/dist/plugins/index.d.ts +125 -132
  19. package/dist/plugins/index.mjs +373 -284
  20. package/dist/shared/client.8ug8I-zu.d.mts +167 -0
  21. package/dist/shared/client.8ug8I-zu.d.ts +167 -0
  22. package/dist/shared/client.BN52ep3E.mjs +174 -0
  23. package/dist/shared/client.BdItY5DT.d.mts +111 -0
  24. package/dist/shared/client.BdItY5DT.d.ts +111 -0
  25. package/dist/shared/client.CPF3hX6O.d.ts +96 -0
  26. package/dist/shared/client.Cby_-GGh.d.mts +96 -0
  27. package/dist/shared/client.D3TIIok6.mjs +343 -0
  28. package/dist/shared/client.Dnfj8jnT.mjs +92 -0
  29. package/package.json +7 -7
  30. package/dist/shared/client.2jUAqzYU.d.ts +0 -45
  31. package/dist/shared/client.B3pNRBih.d.ts +0 -91
  32. package/dist/shared/client.BFAVy68H.d.mts +0 -91
  33. package/dist/shared/client.BLtwTQUg.mjs +0 -40
  34. package/dist/shared/client.CpCa3si8.d.mts +0 -45
  35. package/dist/shared/client.D9eWXdBV.mjs +0 -174
  36. package/dist/shared/client.DLhbktiD.mjs +0 -404
  37. package/dist/shared/client.i2uoJbEp.d.mts +0 -83
  38. package/dist/shared/client.i2uoJbEp.d.ts +0 -83
@@ -1,29 +1,121 @@
1
- import { StandardRequest, StandardLazyResponse } from '@orpc/standard-server';
2
- import { b as ClientContext, c as ClientOptions } from '../../shared/client.i2uoJbEp.mjs';
3
- import { f as StandardLinkClient } from '../../shared/client.CpCa3si8.mjs';
4
- import { f as StandardRPCLinkOptions, g as StandardRPCLink } from '../../shared/client.BFAVy68H.mjs';
5
- import '@orpc/shared';
1
+ import { C as ClientContext, a as ClientOptions } from '../../shared/client.8ug8I-zu.mjs';
2
+ import { Promisable } from '@orpc/shared';
3
+ import { StandardRequest, StandardLazyResponse } from '@standardserver/core';
4
+ import { EncodePeerMessageOptions, DecodePeerMessageOptions } from '@standardserver/peer';
5
+ import { S as StandardLinkTransport, a as StandardLink, b as StandardLinkOptions } from '../../shared/client.Cby_-GGh.mjs';
6
+ import { RPCLinkCodecOptions } from '../standard/index.mjs';
7
+ import '../../shared/client.BdItY5DT.mjs';
6
8
 
7
- interface LinkWebsocketClientOptions {
8
- websocket: Pick<WebSocket, 'addEventListener' | 'removeEventListener' | 'send' | 'readyState'>;
9
+ type WebSocketLike = Pick<WebSocket, 'addEventListener' | 'removeEventListener' | 'send' | 'readyState'>;
10
+ interface WebSocketLinkTransportAttemptInfo {
11
+ /**
12
+ * Total number of connection attempts for this transport's lifetime.
13
+ * Starts at 1 on the first attempt, increments on every subsequent
14
+ * attempt, and never resets.
15
+ */
16
+ totalAttempt: number;
17
+ /**
18
+ * Attempt number within the current (re)connect cycle.
19
+ * Starts at 1, increments on each consecutive failure, and resets to 1
20
+ * once a connection succeeds. Use this for backoff calculations.
21
+ */
22
+ attempt: number;
9
23
  }
10
- declare class LinkWebsocketClient<T extends ClientContext> implements StandardLinkClient<T> {
11
- private readonly peer;
12
- constructor(options: LinkWebsocketClientOptions);
13
- call(request: StandardRequest, _options: ClientOptions<T>, _path: readonly string[], _input: unknown): Promise<StandardLazyResponse>;
24
+ interface WebSocketLinkTransportReconnectOptions {
25
+ /**
26
+ * Whether to automatically reconnect when the connection is lost.
27
+ *
28
+ * @default false
29
+ */
30
+ enabled: boolean;
31
+ /**
32
+ * Delay before a (re)connect attempt, in milliseconds.
33
+ *
34
+ * @default info => info.attempt === 1 ? 0 : 2_000
35
+ */
36
+ delay?: undefined | ((info: WebSocketLinkTransportAttemptInfo) => number);
37
+ /**
38
+ * Maximum number of consecutive failed attempts before giving up.
39
+ * When exceeded, `getConnectedPeer` throws instead of retrying.
40
+ * Should greater than 1
41
+ *
42
+ * @default Infinity
43
+ */
44
+ maxAttempt?: undefined | number;
45
+ /**
46
+ * Whether to proactively reconnect right after the socket closes,
47
+ * rather than waiting for the next call to trigger reconnection.
48
+ * Reduces latency for the next request.
49
+ *
50
+ * @default { enabled: false }
51
+ */
52
+ onClose?: undefined | {
53
+ /**
54
+ * Whether to proactively reconnect right after the socket closes,
55
+ * rather than waiting for the next call to trigger reconnection.
56
+ * Reduces latency for the next request.
57
+ *
58
+ * @default false
59
+ */
60
+ enabled: boolean;
61
+ /**
62
+ * Delay before reconnecting after the socket closes, in milliseconds.
63
+ *
64
+ * @default 0
65
+ */
66
+ delay?: number;
67
+ };
68
+ }
69
+ interface WebSocketLinkTransportOptions<_T extends ClientContext> {
70
+ /**
71
+ * Returns a WebSocket instance for peer communication.
72
+ * Can be async for lazy resolution.
73
+ */
74
+ connect: (info: WebSocketLinkTransportAttemptInfo) => Promisable<WebSocketLike>;
75
+ /**
76
+ * Whether to connect immediately on initialization, instead of waiting
77
+ * for the first call. Reduces latency for the first request.
78
+ *
79
+ * @default false
80
+ */
81
+ connectOnInit?: undefined | boolean;
82
+ /**
83
+ * Reconnection behavior when the connection is lost.
84
+ *
85
+ * @default { enabled: false }
86
+ */
87
+ reconnect?: undefined | WebSocketLinkTransportReconnectOptions;
88
+ /**
89
+ * Options for encoding peer messages. such as `prefix` for distinguishing messages on the same channel..
90
+ */
91
+ encodePeerMessage?: EncodePeerMessageOptions | undefined;
92
+ /**
93
+ * Options for decoding peer messages. such as `prefix` for distinguishing messages on the same channel..
94
+ */
95
+ decodePeerMessage?: DecodePeerMessageOptions | undefined;
96
+ }
97
+ declare class WebSocketLinkTransport<T extends ClientContext> implements StandardLinkTransport<T> {
98
+ private readonly connect;
99
+ private readonly reconnectEnabled;
100
+ private readonly reconnectDelay;
101
+ private readonly reconnectMaxAttempt;
102
+ private readonly reconnectOnCloseEnabled;
103
+ private readonly reconnectOnCloseDelay;
104
+ private readonly encodePeerMessageOptions;
105
+ private readonly decodePeerMessageOptions;
106
+ constructor(options: WebSocketLinkTransportOptions<T>);
107
+ send(standardRequest: StandardRequest, _path: string[], _options: ClientOptions<T>): Promise<StandardLazyResponse>;
108
+ private totalAttempt;
109
+ private attempt;
110
+ private current;
111
+ private getConnectedPeer;
14
112
  }
15
113
 
16
- interface RPCLinkOptions<T extends ClientContext> extends Omit<StandardRPCLinkOptions<T>, 'url' | 'method' | 'fallbackMethod' | 'maxUrlLength'>, LinkWebsocketClientOptions {
114
+ interface RPCLinkOptions<T extends ClientContext> extends StandardLinkOptions<T>, WebSocketLinkTransportOptions<T>, RPCLinkCodecOptions<T> {
17
115
  }
18
- /**
19
- * The RPC Link communicates with the server using the RPC protocol over WebSocket.
20
- *
21
- * @see {@link https://orpc.dev/docs/client/rpc-link RPC Link Docs}
22
- * @see {@link https://orpc.dev/docs/adapters/websocket WebSocket Adapter Docs}
23
- */
24
- declare class RPCLink<T extends ClientContext> extends StandardRPCLink<T> {
116
+ declare class RPCLink<T extends ClientContext> extends StandardLink<T> {
25
117
  constructor(options: RPCLinkOptions<T>);
26
118
  }
27
119
 
28
- export { LinkWebsocketClient, RPCLink };
29
- export type { LinkWebsocketClientOptions, RPCLinkOptions };
120
+ export { RPCLink, WebSocketLinkTransport };
121
+ export type { RPCLinkOptions, WebSocketLike, WebSocketLinkTransportAttemptInfo, WebSocketLinkTransportOptions, WebSocketLinkTransportReconnectOptions };
@@ -1,29 +1,121 @@
1
- import { StandardRequest, StandardLazyResponse } from '@orpc/standard-server';
2
- import { b as ClientContext, c as ClientOptions } from '../../shared/client.i2uoJbEp.js';
3
- import { f as StandardLinkClient } from '../../shared/client.2jUAqzYU.js';
4
- import { f as StandardRPCLinkOptions, g as StandardRPCLink } from '../../shared/client.B3pNRBih.js';
5
- import '@orpc/shared';
1
+ import { C as ClientContext, a as ClientOptions } from '../../shared/client.8ug8I-zu.js';
2
+ import { Promisable } from '@orpc/shared';
3
+ import { StandardRequest, StandardLazyResponse } from '@standardserver/core';
4
+ import { EncodePeerMessageOptions, DecodePeerMessageOptions } from '@standardserver/peer';
5
+ import { S as StandardLinkTransport, a as StandardLink, b as StandardLinkOptions } from '../../shared/client.CPF3hX6O.js';
6
+ import { RPCLinkCodecOptions } from '../standard/index.js';
7
+ import '../../shared/client.BdItY5DT.js';
6
8
 
7
- interface LinkWebsocketClientOptions {
8
- websocket: Pick<WebSocket, 'addEventListener' | 'removeEventListener' | 'send' | 'readyState'>;
9
+ type WebSocketLike = Pick<WebSocket, 'addEventListener' | 'removeEventListener' | 'send' | 'readyState'>;
10
+ interface WebSocketLinkTransportAttemptInfo {
11
+ /**
12
+ * Total number of connection attempts for this transport's lifetime.
13
+ * Starts at 1 on the first attempt, increments on every subsequent
14
+ * attempt, and never resets.
15
+ */
16
+ totalAttempt: number;
17
+ /**
18
+ * Attempt number within the current (re)connect cycle.
19
+ * Starts at 1, increments on each consecutive failure, and resets to 1
20
+ * once a connection succeeds. Use this for backoff calculations.
21
+ */
22
+ attempt: number;
9
23
  }
10
- declare class LinkWebsocketClient<T extends ClientContext> implements StandardLinkClient<T> {
11
- private readonly peer;
12
- constructor(options: LinkWebsocketClientOptions);
13
- call(request: StandardRequest, _options: ClientOptions<T>, _path: readonly string[], _input: unknown): Promise<StandardLazyResponse>;
24
+ interface WebSocketLinkTransportReconnectOptions {
25
+ /**
26
+ * Whether to automatically reconnect when the connection is lost.
27
+ *
28
+ * @default false
29
+ */
30
+ enabled: boolean;
31
+ /**
32
+ * Delay before a (re)connect attempt, in milliseconds.
33
+ *
34
+ * @default info => info.attempt === 1 ? 0 : 2_000
35
+ */
36
+ delay?: undefined | ((info: WebSocketLinkTransportAttemptInfo) => number);
37
+ /**
38
+ * Maximum number of consecutive failed attempts before giving up.
39
+ * When exceeded, `getConnectedPeer` throws instead of retrying.
40
+ * Should greater than 1
41
+ *
42
+ * @default Infinity
43
+ */
44
+ maxAttempt?: undefined | number;
45
+ /**
46
+ * Whether to proactively reconnect right after the socket closes,
47
+ * rather than waiting for the next call to trigger reconnection.
48
+ * Reduces latency for the next request.
49
+ *
50
+ * @default { enabled: false }
51
+ */
52
+ onClose?: undefined | {
53
+ /**
54
+ * Whether to proactively reconnect right after the socket closes,
55
+ * rather than waiting for the next call to trigger reconnection.
56
+ * Reduces latency for the next request.
57
+ *
58
+ * @default false
59
+ */
60
+ enabled: boolean;
61
+ /**
62
+ * Delay before reconnecting after the socket closes, in milliseconds.
63
+ *
64
+ * @default 0
65
+ */
66
+ delay?: number;
67
+ };
68
+ }
69
+ interface WebSocketLinkTransportOptions<_T extends ClientContext> {
70
+ /**
71
+ * Returns a WebSocket instance for peer communication.
72
+ * Can be async for lazy resolution.
73
+ */
74
+ connect: (info: WebSocketLinkTransportAttemptInfo) => Promisable<WebSocketLike>;
75
+ /**
76
+ * Whether to connect immediately on initialization, instead of waiting
77
+ * for the first call. Reduces latency for the first request.
78
+ *
79
+ * @default false
80
+ */
81
+ connectOnInit?: undefined | boolean;
82
+ /**
83
+ * Reconnection behavior when the connection is lost.
84
+ *
85
+ * @default { enabled: false }
86
+ */
87
+ reconnect?: undefined | WebSocketLinkTransportReconnectOptions;
88
+ /**
89
+ * Options for encoding peer messages. such as `prefix` for distinguishing messages on the same channel..
90
+ */
91
+ encodePeerMessage?: EncodePeerMessageOptions | undefined;
92
+ /**
93
+ * Options for decoding peer messages. such as `prefix` for distinguishing messages on the same channel..
94
+ */
95
+ decodePeerMessage?: DecodePeerMessageOptions | undefined;
96
+ }
97
+ declare class WebSocketLinkTransport<T extends ClientContext> implements StandardLinkTransport<T> {
98
+ private readonly connect;
99
+ private readonly reconnectEnabled;
100
+ private readonly reconnectDelay;
101
+ private readonly reconnectMaxAttempt;
102
+ private readonly reconnectOnCloseEnabled;
103
+ private readonly reconnectOnCloseDelay;
104
+ private readonly encodePeerMessageOptions;
105
+ private readonly decodePeerMessageOptions;
106
+ constructor(options: WebSocketLinkTransportOptions<T>);
107
+ send(standardRequest: StandardRequest, _path: string[], _options: ClientOptions<T>): Promise<StandardLazyResponse>;
108
+ private totalAttempt;
109
+ private attempt;
110
+ private current;
111
+ private getConnectedPeer;
14
112
  }
15
113
 
16
- interface RPCLinkOptions<T extends ClientContext> extends Omit<StandardRPCLinkOptions<T>, 'url' | 'method' | 'fallbackMethod' | 'maxUrlLength'>, LinkWebsocketClientOptions {
114
+ interface RPCLinkOptions<T extends ClientContext> extends StandardLinkOptions<T>, WebSocketLinkTransportOptions<T>, RPCLinkCodecOptions<T> {
17
115
  }
18
- /**
19
- * The RPC Link communicates with the server using the RPC protocol over WebSocket.
20
- *
21
- * @see {@link https://orpc.dev/docs/client/rpc-link RPC Link Docs}
22
- * @see {@link https://orpc.dev/docs/adapters/websocket WebSocket Adapter Docs}
23
- */
24
- declare class RPCLink<T extends ClientContext> extends StandardRPCLink<T> {
116
+ declare class RPCLink<T extends ClientContext> extends StandardLink<T> {
25
117
  constructor(options: RPCLinkOptions<T>);
26
118
  }
27
119
 
28
- export { LinkWebsocketClient, RPCLink };
29
- export type { LinkWebsocketClientOptions, RPCLinkOptions };
120
+ export { RPCLink, WebSocketLinkTransport };
121
+ export type { RPCLinkOptions, WebSocketLike, WebSocketLinkTransportAttemptInfo, WebSocketLinkTransportOptions, WebSocketLinkTransportReconnectOptions };
@@ -1,52 +1,110 @@
1
- import { readAsBuffer } from '@orpc/shared';
2
- import { ClientPeer } from '@orpc/standard-server-peer';
3
- import { c as StandardRPCLink } from '../../shared/client.DLhbktiD.mjs';
4
- import '@orpc/standard-server';
5
- import '../../shared/client.D9eWXdBV.mjs';
6
- import '@orpc/standard-server-fetch';
7
- import '../../shared/client.BLtwTQUg.mjs';
1
+ import { runWithSignal, AbortError, sleep, promiseWithResolvers, toStringOrBytes } from '@orpc/shared';
2
+ import { ClientPeer, encodePeerMessage, decodePeerMessage, isServerPeerSendMessage } from '@standardserver/peer';
3
+ import { S as StandardLink, R as RPCLinkCodec } from '../../shared/client.BN52ep3E.mjs';
4
+ import '@standardserver/core';
5
+ import '@standardserver/fetch';
6
+ import '../../shared/client.Dnfj8jnT.mjs';
7
+ import '../../shared/client.D3TIIok6.mjs';
8
8
 
9
9
  const WEBSOCKET_CONNECTING = 0;
10
10
  const WEBSOCKET_OPEN = 1;
11
- class LinkWebsocketClient {
12
- peer;
11
+ class WebSocketLinkTransport {
12
+ connect;
13
+ reconnectEnabled;
14
+ reconnectDelay;
15
+ reconnectMaxAttempt;
16
+ reconnectOnCloseEnabled;
17
+ reconnectOnCloseDelay;
18
+ encodePeerMessageOptions;
19
+ decodePeerMessageOptions;
13
20
  constructor(options) {
14
- this.peer = new ClientPeer(async (message) => {
15
- if (options.websocket.readyState === WEBSOCKET_CONNECTING) {
16
- await new Promise((resolve) => {
17
- const settle = () => {
18
- options.websocket.removeEventListener("open", settle);
19
- options.websocket.removeEventListener("close", settle);
20
- resolve();
21
- };
22
- options.websocket.addEventListener("open", settle, { once: true });
23
- options.websocket.addEventListener("close", settle, { once: true });
21
+ this.connect = options.connect;
22
+ this.reconnectEnabled = options.reconnect?.enabled ?? false;
23
+ this.reconnectDelay = options.reconnect?.delay ?? ((info) => info.attempt === 1 ? 0 : 2e3);
24
+ this.reconnectMaxAttempt = options.reconnect?.maxAttempt ?? Infinity;
25
+ this.reconnectOnCloseEnabled = this.reconnectEnabled && (options.reconnect?.onClose?.enabled ?? false);
26
+ this.reconnectOnCloseDelay = options.reconnect?.onClose?.delay ?? 0;
27
+ this.encodePeerMessageOptions = options.encodePeerMessage;
28
+ this.decodePeerMessageOptions = options.decodePeerMessage;
29
+ if (options.connectOnInit) {
30
+ this.getConnectedPeer().catch(() => {
31
+ });
32
+ }
33
+ }
34
+ async send(standardRequest, _path, _options) {
35
+ const peer = await runWithSignal(
36
+ standardRequest.signal,
37
+ () => this.getConnectedPeer()
38
+ );
39
+ return peer.request(standardRequest);
40
+ }
41
+ totalAttempt = 0;
42
+ attempt = 0;
43
+ current;
44
+ async getConnectedPeer() {
45
+ const current = this.current;
46
+ const resolved = await current;
47
+ if (resolved && (!this.reconnectEnabled || resolved.websocket.readyState === WEBSOCKET_OPEN)) {
48
+ this.attempt = 0;
49
+ return resolved.peer;
50
+ }
51
+ if (current !== this.current) {
52
+ return this.getConnectedPeer();
53
+ }
54
+ if (this.attempt >= this.reconnectMaxAttempt) {
55
+ throw new AbortError(`WebSocket reconnect failed after ${this.attempt} attempt(s)`);
56
+ }
57
+ this.current = (async () => {
58
+ this.totalAttempt += 1;
59
+ this.attempt += 1;
60
+ const info = { totalAttempt: this.totalAttempt, attempt: this.attempt };
61
+ await sleep(this.reconnectDelay(info));
62
+ const websocket = await this.connect(info);
63
+ const peer = new ClientPeer(async (message) => {
64
+ const encoded = await encodePeerMessage(message, this.encodePeerMessageOptions);
65
+ return websocket.send(encoded);
66
+ });
67
+ let connectingResolvers;
68
+ if (websocket.readyState === WEBSOCKET_CONNECTING) {
69
+ connectingResolvers = promiseWithResolvers();
70
+ websocket.addEventListener("open", () => {
71
+ connectingResolvers?.resolve();
24
72
  });
25
73
  }
26
- if (options.websocket.readyState !== WEBSOCKET_OPEN) {
27
- throw new Error("Cannot send message, WebSocket is not open.");
74
+ websocket.addEventListener("message", async (event) => {
75
+ const message = await toStringOrBytes(event.data);
76
+ const result = decodePeerMessage(message, this.decodePeerMessageOptions);
77
+ if (result.matched && isServerPeerSendMessage(result.message)) {
78
+ await peer.message(result.message);
79
+ }
80
+ });
81
+ websocket.addEventListener("close", async (event) => {
82
+ connectingResolvers?.resolve();
83
+ if (this.reconnectOnCloseEnabled) {
84
+ sleep(this.reconnectOnCloseDelay).then(() => this.getConnectedPeer()).catch(() => {
85
+ });
86
+ }
87
+ const reason = new AbortError(`WebSocket closed (code ${event.code}: ${event.reason})`);
88
+ await peer.close(reason);
89
+ });
90
+ await connectingResolvers?.promise;
91
+ connectingResolvers = void 0;
92
+ return { websocket, peer };
93
+ })().catch((error) => {
94
+ if (!this.reconnectEnabled) {
95
+ throw error;
28
96
  }
29
- return options.websocket.send(message);
30
- });
31
- options.websocket.addEventListener("message", async (event) => {
32
- const message = event.data instanceof Blob ? await readAsBuffer(event.data) : event.data;
33
- this.peer.message(message);
34
97
  });
35
- options.websocket.addEventListener("close", () => {
36
- this.peer.close();
37
- });
38
- }
39
- async call(request, _options, _path, _input) {
40
- const response = await this.peer.request(request);
41
- return { ...response, body: () => Promise.resolve(response.body) };
98
+ return this.getConnectedPeer();
42
99
  }
43
100
  }
44
101
 
45
- class RPCLink extends StandardRPCLink {
102
+ class RPCLink extends StandardLink {
46
103
  constructor(options) {
47
- const linkClient = new LinkWebsocketClient(options);
48
- super(linkClient, { ...options, url: "http://orpc" });
104
+ const codec = new RPCLinkCodec(options);
105
+ const transport = new WebSocketLinkTransport(options);
106
+ super(codec, transport, options);
49
107
  }
50
108
  }
51
109
 
52
- export { LinkWebsocketClient, RPCLink };
110
+ export { RPCLink, WebSocketLinkTransport };