UNPKG

@trpc/client

Version:

The tRPC client library

308 lines • 11.1 kB
import { t as TRPCConnectionState } from "./subscriptions-DcqRZc4h.cjs"; import { a as OperationResultEnvelope, d as TRPCClientError, n as Operation, u as TRPCLink } from "./types-BrCJd1zp.cjs"; import { n as TransformerOptions } from "./unstable-internals-CNoyg7Yf.cjs"; import { AnyRouter, CombinedDataTransformer, Encoder, inferClientTypes } from "@trpc/server/unstable-core-do-not-import"; import { BehaviorSubject } from "@trpc/server/observable"; import { AnyTRPCRouter } from "@trpc/server"; import { TRPCRequestInfo } from "@trpc/server/http"; //#region src/links/wsLink/wsClient/encoder.d.ts /** * The default WebSocket encoder. Sends messages as JSON text frames. */ declare const jsonEncoder: Encoder; //#endregion //#region src/links/internals/urlWithConnectionParams.d.ts /** * A value that can be wrapped in callback */ type CallbackOrValue<T> = T | (() => T | Promise<T>); interface UrlOptionsWithConnectionParams { /** * The URL to connect to (can be a function that returns a URL) */ url: CallbackOrValue<string>; /** * Connection params that are available in `createContext()` * - For `wsLink`/`wsClient`, these are sent as the first message * - For `httpSubscriptionLink`, these are serialized as part of the URL under the `connectionParams` query * @see https://trpc.io/docs/server/websockets#connectionParams */ connectionParams?: CallbackOrValue<TRPCRequestInfo['connectionParams']>; } //#endregion //#region src/links/wsLink/wsClient/options.d.ts /** * Options for `createWSClient`. * * @see https://trpc.io/docs/client/links/wsLink#wslink--createwsclient-options */ interface WebSocketClientOptions extends UrlOptionsWithConnectionParams { /** * The `WebSocket` class to use, for runtimes that don't have one. */ WebSocket?: typeof WebSocket; /** * The number of milliseconds before a reconnect is attempted. * @default {@link exponentialBackoff} */ retryDelayMs?: (attemptIndex: number) => number; /** * Triggered when a WebSocket connection is established */ onOpen?: () => void; /** * Triggered when a WebSocket connection encounters an error */ onError?: (evt?: Event) => void; /** * Triggered when a WebSocket connection is closed */ onClose?: (cause?: { code?: number; }) => void; /** * Lazy mode will close the WebSocket automatically after a period of inactivity (no messages sent or received and no pending requests) */ lazy?: { /** * Enable lazy mode * @default false */ enabled: boolean; /** * Close the WebSocket after this many milliseconds * @default 0 */ closeMs: number; }; /** * Send ping messages to the server and kill the connection if no pong message is returned */ keepAlive?: { /** * @default false */ enabled: boolean; /** * Send a ping message every this many milliseconds * @default 5_000 */ intervalMs?: number; /** * Close the WebSocket after this many milliseconds if the server does not respond * @default 1_000 */ pongTimeoutMs?: number; }; /** * Encodes and decodes messages on the wire, for example as a binary format. * @default jsonEncoder */ experimental_encoder?: Encoder; } //#endregion //#region src/links/wsLink/wsClient/wsClient.d.ts /** * A WebSocket client for managing TRPC operations, supporting lazy initialization, * reconnection, keep-alive, and request management. */ declare class WsClient { /** * Observable tracking the current connection state, including errors. */ readonly connectionState: BehaviorSubject<TRPCConnectionState<TRPCClientError<AnyTRPCRouter>>>; private allowReconnect; private requestManager; /** * The last id sent on the wire. Each request gets its own instead of its * `op.id`: a retry reuses the failed attempt's `op.id`, and the server's * late frames for that attempt must not reach the retry. A subscription * sent again after its socket was lost gets a new one for the same reason. */ private lastRequestId; private readonly connectionOptions; /** * The connection new requests are sent on. A reconnect replaces it only * once the new connection is fully open, `connectionParams` included, so * until then requests keep going to the old one. */ private activeConnection; private readonly reconnectRetryDelay; private inactivityTimeout; private readonly callbacks; private readonly lazyMode; private readonly encoder; constructor(opts: WebSocketClientOptions); private createConnection; /** * Opens the WebSocket connection. Handles reconnection attempts and updates * the connection state accordingly. */ private open; /** * Closes the WebSocket connection and stops managing requests. * Ensures all outgoing and pending requests are properly finalized. */ close(): Promise<void>; /** * Method to request the server. * Handles data transformation, batching of requests, and subscription lifecycle. * * @param op - The operation details including type, path, input and signal. Each subscription to the returned observable is sent with a new id, not `op.id`. * @param transformer - Data transformer for serializing requests and deserializing responses * @param lastEventId - Optional ID of the last received event for subscriptions * * @returns An observable that emits operation results and handles cleanup */ request({ op: { type, path, input, signal }, transformer, lastEventId }: { op: Pick<Operation, 'id' | 'type' | 'path' | 'input' | 'signal'>; transformer: CombinedDataTransformer; lastEventId?: string; }): import("@trpc/server/observable").Observable<OperationResultEnvelope<unknown, TRPCClientError<AnyTRPCRouter>>, TRPCClientError<AnyTRPCRouter>>; /** * The current WebSocket and its state, or `null` when there is no socket. */ get connection(): { readonly id: number; readonly state: 'open'; readonly ws: WebSocket; } | { readonly id: number; readonly state: 'closed'; readonly ws: WebSocket; } | { readonly id: number; readonly state: 'connecting'; readonly ws: WebSocket; } | null; /** * Manages the reconnection process for the WebSocket using retry logic. * Ensures that only one reconnection attempt is active at a time by tracking the current * reconnection state in the `reconnecting` promise. */ private reconnecting; /** * The connection a reconnect is opening to replace the active one. */ private nextConnection; /** * The connection the active one replaced, while it's open. If the active * one is lost first, this one serves every request again until the next. */ private retiredConnection; /** * Why the latest attempt to replace a socket that's still open failed. * It's shown once that socket closes, since until then it serves every * request. */ private replacementError; /** * The retry attempt that opened the current connection. */ private connectionAttemptIndex; /** * Set when the server rejects the current connection with an `id: null` * error, e.g. because `createContext` threw. The server closes the socket * right after, so the reconnect that follows carries on with the backoff * instead of starting over at attempt 0. Cleared again when the socket * receives a result, which proves the connection was accepted. * @see https://github.com/trpc/trpc/issues/4774 */ private connectionRejected; /** Subscriptions whose subscriber has seen `started`. */ private readonly started; /** * Opens a new connection, retrying until one opens. While the current * socket is open, it keeps serving every request, new ones included, until * the new one is fully open, `connectionParams` included. * * @param closedError - Why the current socket was lost, or `null` when it's * still open and serving requests, e.g. on a server-requested reconnect. */ private reconnect; /** * Moves the pending subscriptions to the active socket, which has just * opened: each is resubscribed with the id of the last event it delivered. * A subscription whose old socket is still open keeps delivering from it * until the new socket confirms it with `started`; see `confirmMove()`. * Closes the previous socket once nothing is left on it. */ private handOff; /** * Completes a subscription's move once its new socket has confirmed it: * stops it on the old socket, whose later messages for it are dropped * apart from events without ids, and closes that socket once everything it * sent before the stop has arrived and nothing else is left on it. */ private confirmMove; private releaseMovedFrom; private hasRequestsOn; /** * Closes `ws` once it's been replaced and nothing is left on it. */ private closeIfDrained; /** * Stops a subscription on the socket it was sent on, if that's still open. * * @returns Whether the stop was sent. */ private stopSubscription; /** * Fails the pending queries and mutations sent on `ws`, and returns its * pending subscriptions, which are kept to be sent again. */ private failPendingRequests; private setupWebSocketListeners; private handleResponseMessage; private handleIncomingRequest; /** * Sends a message or batch of messages directly to the server. */ private send; /** * Groups requests for batch sending. * * @returns A function to abort the batched request. */ private batchSend; /** * Sends `message` with the other outgoing requests once the connection is * open, batching those queued in the same tick. */ private flushOutgoing; } //#endregion //#region src/links/wsLink/createWsClient.d.ts /** * Opens and manages a WebSocket connection to a tRPC server. Pass it to * `wsLink`. * * @see https://trpc.io/docs/client/links/wsLink#wslink--createwsclient-options */ declare function createWSClient(opts: WebSocketClientOptions): WsClient; /** * The client returned by {@link createWSClient}. */ type TRPCWebSocketClient = ReturnType<typeof createWSClient>; //#endregion //#region src/links/wsLink/wsLink.d.ts /** * Options for {@link wsLink}. * * @see https://trpc.io/docs/client/links/wsLink#wslink--createwsclient-options */ type WebSocketLinkOptions<TRouter extends AnyRouter> = { /** * The client made with `createWSClient`. */ client: TRPCWebSocketClient; } & TransformerOptions<inferClientTypes<TRouter>>; /** * A terminating link that sends calls over a WebSocket. * * @see https://trpc.io/docs/client/links/wsLink */ declare function wsLink<TRouter extends AnyRouter>(opts: WebSocketLinkOptions<TRouter>): TRPCLink<TRouter>; //#endregion export { WebSocketClientOptions as a, jsonEncoder as c, createWSClient as i, wsLink as n, UrlOptionsWithConnectionParams as o, TRPCWebSocketClient as r, Encoder as s, WebSocketLinkOptions as t }; //# sourceMappingURL=wsLink-Cpw-BznR.d.cts.map