@trpc/client 11.31.2 → 11.31.4
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/dist/index.cjs +3 -2
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +4 -3
- package/dist/index.mjs.map +1 -1
- package/dist/links/wsLink/wsLink.cjs +1 -1
- package/dist/links/wsLink/wsLink.mjs +1 -1
- package/dist/wsLink-CEooxn80.d.cts.map +1 -1
- package/dist/wsLink-CnVTvoqf.d.mts.map +1 -1
- package/dist/{wsLink-D054Z7rw.mjs → wsLink-DSmHMirJ.mjs} +4 -3
- package/dist/{wsLink-D054Z7rw.mjs.map → wsLink-DSmHMirJ.mjs.map} +1 -1
- package/dist/{wsLink-DBHs9wiK.cjs → wsLink-vHwF4z7F.cjs} +3 -2
- package/package.json +3 -3
- package/skills/client-setup/SKILL.md +1 -1
- package/skills/links/SKILL.md +1 -1
- package/skills/superjson/SKILL.md +1 -1
- package/src/links/localLink.ts +10 -2
- package/src/links/wsLink/wsClient/wsClient.ts +5 -1
package/dist/index.cjs
CHANGED
|
@@ -7,7 +7,7 @@ const require_httpLink = require("./httpLink-C7hAx__E.cjs");
|
|
|
7
7
|
const require_httpBatchLink = require("./httpBatchLink-D5PwsSuY.cjs");
|
|
8
8
|
const require_unstable_internals = require("./unstable-internals.cjs");
|
|
9
9
|
const require_links_loggerLink = require("./links/loggerLink.cjs");
|
|
10
|
-
const require_wsLink = require("./wsLink-
|
|
10
|
+
const require_wsLink = require("./wsLink-vHwF4z7F.cjs");
|
|
11
11
|
let _trpc_server_observable = require("@trpc/server/observable");
|
|
12
12
|
let _trpc_server_unstable_core_do_not_import = require("@trpc/server/unstable-core-do-not-import");
|
|
13
13
|
let _trpc_server = require("@trpc/server");
|
|
@@ -833,7 +833,8 @@ function localLink(opts) {
|
|
|
833
833
|
await (0, _trpc_server_unstable_core_do_not_import.run)(async () => {
|
|
834
834
|
while (true) try {
|
|
835
835
|
var _usingCtx4 = _usingCtx();
|
|
836
|
-
const
|
|
836
|
+
const procedureResult = await runProcedure(inputWithTrackedEventId(op.input, lastEventId));
|
|
837
|
+
const result = (0, _trpc_server_observable.isObservable)(procedureResult) ? (0, _trpc_server_observable.observableToAsyncIterable)(procedureResult, signal) : procedureResult;
|
|
837
838
|
if (!(0, _trpc_server_unstable_core_do_not_import.isAsyncIterable)(result)) throw new Error("Expected an async iterable");
|
|
838
839
|
const iterator = _usingCtx4.a((0, _trpc_server_unstable_core_do_not_import.iteratorResource)(result));
|
|
839
840
|
observer.next({ result: { type: "started" } });
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":["AnyRouter"],"sources":["../src/internals/TRPCUntypedClient.ts","../src/createTRPCUntypedClient.ts","../src/safe.ts","../src/createTRPCClient.ts","../src/getFetch.ts","../src/links/httpBatchStreamLink.ts","../src/links/httpSubscriptionLink.ts","../src/links/retryLink.ts","../src/links/localLink.ts"],"mappings":";;;;;;;;;;;;;UA6BiB;;;;;EAKf,UAAU;;;;;EAKV,SAAS;;;UAIM,yBAAyB,QAAQ;;EAEhD,YAAY;IAAQ,SAAS;;;EAE7B,SAAS,OAAO,wBAAwB;;EAExC,UAAU,KAAK;;;;;EAKf;;EAEA;;EAEA,0BAA0B,OAAO,oBAAoB;;KAGlD,oBAAoB;;;;;;KAOb,iCAAiC,SAAS,WAEnD,QAAQ,6BAER,cAAc,QAAQ;;;;;KAOb,0BAA0B,QAAQ,UAAU,QACtD,yBAAyB,QAAQ,cAG9B,QAAQ,cAAc,KAAK,yBAAyB,QAAQ,SAAS,SACtE;;;;;KAeQ,wBAAwB,gBAAgB;;;;;;EAMlD,OAAO,SAAS;EAChB,cAAc;;;;;;qBAOH,kBAAkB,oBAAoB;mBAChC;WACD,SAAS;UACjB;EAER,YAAY,MAAM,wBAAwB;UASlC;UAkBM;;EAmBP,MAAM,cAAc,iBAAi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names":["AnyRouter"],"sources":["../src/internals/TRPCUntypedClient.ts","../src/createTRPCUntypedClient.ts","../src/safe.ts","../src/createTRPCClient.ts","../src/getFetch.ts","../src/links/httpBatchStreamLink.ts","../src/links/httpSubscriptionLink.ts","../src/links/retryLink.ts","../src/links/localLink.ts"],"mappings":";;;;;;;;;;;;;UA6BiB;;;;;EAKf,UAAU;;;;;EAKV,SAAS;;;UAIM,yBAAyB,QAAQ;;EAEhD,YAAY;IAAQ,SAAS;;;EAE7B,SAAS,OAAO,wBAAwB;;EAExC,UAAU,KAAK;;;;;EAKf;;EAEA;;EAEA,0BAA0B,OAAO,oBAAoB;;KAGlD,oBAAoB;;;;;;KAOb,iCAAiC,SAAS,WAEnD,QAAQ,6BAER,cAAc,QAAQ;;;;;KAOb,0BAA0B,QAAQ,UAAU,QACtD,yBAAyB,QAAQ,cAG9B,QAAQ,cAAc,KAAK,yBAAyB,QAAQ,SAAS,SACtE;;;;;KAeQ,wBAAwB,gBAAgB;;;;;;EAMlD,OAAO,SAAS;EAChB,cAAc;;;;;;qBAOH,kBAAkB,oBAAoB;mBAChC;WACD,SAAS;UACjB;EAER,YAAY,MAAM,wBAAwB;UASlC;UAkBM;;EAmBP,MAAM,cAAc,iBAAiB,OAAO,qBAAkB;;EAU9D,SAAS,cAAc,iBAAiB,OAAO,qBAAkB;;;;;;;EAejE,aACL,cACA,gBACA,MAAM,mCAAmC,gBAAgB,cACvD,qBACD;EACI,aACL,cAAc,qBACZ,QAAQ,kCAAkC,gBAAgB,eAC1D,oBAEF,cACA,gBACA,OAAO,iCAAiC,SACvC;;;;;;wBCnMW,wBAAwB,gBAAgB,WACtD,MAAM,wBAAwB,WAC7B,kBAAkB;;;;cCLA;;;;;KAMT,kBAAkB,OAAO,eAAe,QAAQ;YAChD,gBAAgB;;;;;KAMhB,eAAe,eAAe;EACxC,YAAY;EACZ;;;;;;KAOU,WAAW,OAAO,yBAChB,MAAM,OAAO,8BACb,iBAAiB,OAAO,eAAe;;;;;;;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CpNL,SACd,kBAAkB,aAAa,mBAC9B;;;;;;;YCkBS,2BAA2B,cAAc,kBACnD,qBAAqB;;;;;;;EAOnB;;;;;;;;wBAeY,oBAAoB,gBAAgBA,aAClD,MAAM,2BAA2B,wCAChC,SAAS;;;;qBA0NC,qCAA4B;;;;KCrOpC,4BACH,cAAc,gBACd,qBAAqB,gBAAgB,wBAAwB;;;;;EAM7D,cAAc;;;;;EAKd,qBACI,gBAAgB,WAAW,kBACzB;IACA,IAAI;QAEF,gBAAgB,WAAW,gBAC3B,QAAQ,gBAAgB,WAAW;IACzC,KAAK,oBAAoB,2BAC3B,mBAAmB,SACnB;;;;;;wBAOc,qBACd,oBAAoB,uBACpB,qBAAqB,gBAAgB,gBAErC,MAAM,4BACJ,iBAAiB,cACjB,gBAED,SAAS;;;;qBA4KC,sCAA6B;UCpPhC,iBAAiB,oBAAoB;;;;EAI7C,QAAQ,MAAM,eAAe;;;;EAI7B,gBAAgB;;UAGR,eAAe,oBAAoB;;;;EAI3C,IAAI;;;;EAIJ,OAAO,gBAAgB;;;;EAIvB;;;;;;;;wBASc,UAAU,oBAAoB,uBAC5C,MAAM,iBAAiB,eACtB,SAAS;;;;YCHA;;;;;EAKV;;;;;IAKE,QAAQ;;;;;;;;YASA,iBAAiB,gBAAgB;;;;;EAK3C,QAAQ;;;;;;EAMR,gBACE,MAAM,kCACH,QAAQ,mBAAmB;;;;;EAKhC,WAAW,MAAM,oBAAoB,mBAAmB;IACtD,mBAAmB,iBAAiB;;;;;;;wBAQxB,UAAU,gBAAgB,WACxC,MAAM,iBAAiB,WACtB,SAAS;;;;;qBAqQC,2BAAkB;;;;;qBAMlB,+BAAsB"}
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":["AnyRouter"],"sources":["../src/links/internals/contentTypes.ts","../src/internals/TRPCUntypedClient.ts","../src/createTRPCUntypedClient.ts","../src/safe.ts","../src/createTRPCClient.ts","../src/getF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B,kBAAkB;;;;;wBCpNL,SACd,kBAAkB,aAAa,mBAC9B;;;;;;;YCkBS,2BAA2B,cAAc,kBACnD,qBAAqB;;;;;;;EAOnB;;;;;;;;wBAeY,oBAAoB,gBAAgBA,aAClD,MAAM,2BAA2B,wCAChC,SAAS;;;;qBA0NC,qCAA4B;;;;KCrOpC,4BACH,cAAc,gBACd,qBAAqB,gBAAgB,wBAAwB;;;;;EAM7D,cAAc;;;;;EAKd,qBACI,gBAAgB,WAAW,kBACzB;IACA,IAAI;QAEF,gBAAgB,WAAW,gBAC3B,QAAQ,gBAAgB,WAAW;IACzC,KAAK,oBAAoB,2BAC3B,mBAAmB,SACnB;;;;;;wBAOc,qBACd,oBAAoB,uBACpB,qBAAqB,gBAAgB,gBAErC,MAAM,4BACJ,iBAAiB,cACjB,gBAED,SAAS;;;;qBA4KC,sCAA6B;UCpPhC,iBAAiB,oBAAoB;;;;EAI7C,QAAQ,MAAM,eAAe;;;;EAI7B,gBAAgB;;UAGR,eAAe,oBAAoB;;;;EAI3C,IAAI;;;;EAIJ,OAAO,gBAAgB;;;;EAIvB;;;;;;;;wBASc,UAAU,oBAAoB,uBAC5C,MAAM,iBAAiB,eACtB,SAAS;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":["AnyRouter"],"sources":["../src/links/internals/contentTypes.ts","../src/internals/TRPCUntypedClient.ts","../src/createTRPCUntypedClient.ts","../src/safe.ts","../src/createTRPCClient.ts","../src/getFetch.ts","../src/links/httpBatchStreamLink.ts","../src/links/httpSubscriptionLink.ts","../src/links/retryLink.ts","../src/links/localLink.ts"],"mappings":";;;;;;;;;;;;;wBACgB,YACd,iBACC,SAAS,WAAW,eAAe;;wBAStB,WAAW,iBAAc,SAAA;;;;;;wBASzB,sBAAsB,iBAAc,SAAA,OAAA,WAAA,WAAA;;UCQnC;;;;;EAKf,UAAU;;;;;EAKV,SAAS;;;UAIM,yBAAyB,QAAQ;;EAEhD,YAAY;IAAQ,SAAS;;;EAE7B,SA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BAAgB,WAAW,gBAC3B,QAAQ,gBAAgB,WAAW;IACzC,KAAK,oBAAoB,2BAC3B,mBAAmB,SACnB;;;;;;wBAOc,qBACd,oBAAoB,uBACpB,qBAAqB,gBAAgB,gBAErC,MAAM,4BACJ,iBAAiB,cACjB,gBAED,SAAS;;;;qBA4KC,sCAA6B;UCpPhC,iBAAiB,oBAAoB;;;;EAI7C,QAAQ,MAAM,eAAe;;;;EAI7B,gBAAgB;;UAGR,eAAe,oBAAoB;;;;EAI3C,IAAI;;;;EAIJ,OAAO,gBAAgB;;;;EAIvB;;;;;;;;wBASc,UAAU,oBAAoB,uBAC5C,MAAM,iBAAiB,eACtB,SAAS;;;;YCHA;;;;;EAKV;;;;;IAKE,QAAQ;;;;;;;;YASA,iBAAiB,gBAAgB;;;;;EAK3C,QAAQ;;;;;;EAMR,gBACE,MAAM,kCACH,QAAQ,mBAAmB;;;;;EAKhC,WAAW,MAAM,oBAAoB,mBAAmB;IACtD,mBAAmB,iBAAiB;;;;;;;wBAQxB,UAAU,gBAAgB,WACxC,MAAM,iBAAiB,WACtB,SAAS;;;;;qBAqQC,2BAAkB;;;;;qBAMlB,+BAAsB"}
|
package/dist/index.mjs
CHANGED
|
@@ -6,8 +6,8 @@ import { i as isOctetType, n as isFormData, r as isNonJsonSerializable, t as htt
|
|
|
6
6
|
import { n as dataLoader, t as httpBatchLink } from "./httpBatchLink-BkVNtNND.mjs";
|
|
7
7
|
import { getTransformer } from "./unstable-internals.mjs";
|
|
8
8
|
import { loggerLink } from "./links/loggerLink.mjs";
|
|
9
|
-
import { i as jsonEncoder, n as createWSClient, r as resultOf, t as wsLink } from "./wsLink-
|
|
10
|
-
import { behaviorSubject, observable, observableToAsyncIterable, observableToPromise, share } from "@trpc/server/observable";
|
|
9
|
+
import { i as jsonEncoder, n as createWSClient, r as resultOf, t as wsLink } from "./wsLink-DSmHMirJ.mjs";
|
|
10
|
+
import { behaviorSubject, isObservable, observable, observableToAsyncIterable, observableToPromise, share } from "@trpc/server/observable";
|
|
11
11
|
import { callProcedure, createFlatProxy, createRecursiveProxy, isAbortError, isAsyncIterable, isObject, iteratorResource, jsonlStreamConsumer, makeResource, resolvePathSeparator, retryableRpcCodes, run, sseStreamConsumer } from "@trpc/server/unstable-core-do-not-import";
|
|
12
12
|
import { getTRPCErrorFromUnknown, getTRPCErrorShape, isTrackedEnvelope } from "@trpc/server";
|
|
13
13
|
import { TRPC_ERROR_CODES_BY_KEY } from "@trpc/server/rpc";
|
|
@@ -832,7 +832,8 @@ function localLink(opts) {
|
|
|
832
832
|
await run(async () => {
|
|
833
833
|
while (true) try {
|
|
834
834
|
var _usingCtx4 = _usingCtx();
|
|
835
|
-
const
|
|
835
|
+
const procedureResult = await runProcedure(inputWithTrackedEventId(op.input, lastEventId));
|
|
836
|
+
const result = isObservable(procedureResult) ? observableToAsyncIterable(procedureResult, signal) : procedureResult;
|
|
836
837
|
if (!isAsyncIterable(result)) throw new Error("Expected an async iterable");
|
|
837
838
|
const iterator = _usingCtx4.a(iteratorResource(result));
|
|
838
839
|
observer.next({ result: { type: "started" } });
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/internals/TRPCUntypedClient.ts","../src/createTRPCUntypedClient.ts","../src/createTRPCClient.ts","../src/links/httpBatchStreamLink.ts","../src/internals/inputWithTrackedEventId.ts","../src/links/httpSubscriptionLink.ts","../src/links/retryLink.ts","../src/links/localLink.ts","../src/safe.ts"],"sourcesContent":["import type {\n inferObservableValue,\n Unsubscribable,\n} from '@trpc/server/observable';\nimport {\n observable,\n observableToAsyncIterable,\n observableToPromise,\n share,\n} from '@trpc/server/observable';\nimport type {\n AnyRouter,\n inferAsyncIterableYield,\n InferrableClientTypes,\n Maybe,\n TypeError,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { createChain } from '../links/internals/createChain';\nimport type { TRPCConnectionState } from '../links/internals/subscriptions';\nimport type {\n OperationContext,\n OperationLink,\n TRPCClientRuntime,\n TRPCLink,\n} from '../links/types';\nimport { TRPCClientError } from '../TRPCClientError';\n\ntype TRPCType = 'mutation' | 'query' | 'subscription';\n/** The options of a call made with the untyped client. */\nexport interface TRPCRequestOptions {\n /**\n * Context for the links, such as a flag a `splitLink` reads.\n * @see https://trpc.io/docs/client/links#managing-context\n */\n context?: OperationContext;\n /**\n * Aborts the call. With `httpBatchLink`, the request is only aborted once\n * every call in its batch is, so an aborted call can still get a result.\n */\n signal?: AbortSignal;\n}\n\n/** The callbacks a subscription takes on the client. */\nexport interface TRPCSubscriptionObserver<TValue, TError> {\n /** Called when the link sends a `started` result. */\n onStarted: (opts: { context: OperationContext | undefined }) => void;\n /** Called with each event. */\n onData: (value: inferAsyncIterableYield<TValue>) => void;\n /** Called when the subscription ends with an error. */\n onError: (err: TError) => void;\n /**\n * Called when the link sends a `stopped` result. Not every link sends\n * one; `localLink` doesn't.\n */\n onStopped: () => void;\n /** Called when the subscription's observable completes, for any reason. */\n onComplete: () => void;\n /** Called when the connection connects, drops or reconnects. */\n onConnectionStateChange: (state: TRPCConnectionState<TError>) => void;\n}\n\ntype ObserverKey = keyof TRPCSubscriptionObserver<unknown, unknown>;\n\n/**\n * Subscription options without callbacks: `TOpts` must not have any of the\n * callback keys, not even set to `undefined`.\n * @internal\n */\nexport type TRPCSubscriptionWithoutCallbacks<TOpts> = TOpts & {\n // `keyof` a union only has its shared keys, so this one catches each member\n [TKey in ObserverKey]?: never;\n} & {\n [TKey in keyof TOpts & ObserverKey]: never;\n};\n\n/**\n * Subscription callbacks, at least one of which is defined.\n * @internal\n */\nexport type TRPCSubscriptionCallbacks<TValue, TError> = Partial<\n TRPCSubscriptionObserver<TValue, TError>\n> &\n {\n [TKey in ObserverKey]: Pick<TRPCSubscriptionObserver<TValue, TError>, TKey>;\n }[ObserverKey];\n\nconst observerKeys: ObserverKey[] = [\n 'onStarted',\n 'onData',\n 'onError',\n 'onStopped',\n 'onComplete',\n 'onConnectionStateChange',\n];\n\n/**\n * The options of `createTRPCClient`.\n * @internal\n */\nexport type CreateTRPCClientOptions<TRouter extends InferrableClientTypes> = {\n /**\n * The links each call goes through, in order. The last one must send\n * the call, such as `httpBatchLink`.\n * @see https://trpc.io/docs/client/links\n */\n links: TRPCLink<TRouter>[];\n transformer?: TypeError<'The transformer property has moved to httpLink/httpBatchLink/wsLink'>;\n};\n\n/**\n * A client that calls procedures by path string, without types.\n * `createTRPCClient` wraps one.\n */\nexport class TRPCUntypedClient<TInferrable extends InferrableClientTypes> {\n private readonly links: OperationLink<TInferrable>[];\n public readonly runtime: TRPCClientRuntime;\n private requestId: number;\n\n constructor(opts: CreateTRPCClientOptions<TInferrable>) {\n this.requestId = 0;\n\n this.runtime = {};\n\n // Initialize the links\n this.links = opts.links.map((link) => link(this.runtime));\n }\n\n private $request<TInput = unknown, TOutput = unknown>(opts: {\n type: TRPCType;\n input: TInput;\n path: string;\n context?: OperationContext;\n signal: Maybe<AbortSignal>;\n }) {\n const chain$ = createChain<AnyRouter, TInput, TOutput>({\n links: this.links as OperationLink<any, any, any>[],\n op: {\n ...opts,\n context: opts.context ?? {},\n id: ++this.requestId,\n },\n });\n return chain$.pipe(share());\n }\n\n private async requestAsPromise<TInput = unknown, TOutput = unknown>(opts: {\n type: TRPCType;\n input: TInput;\n path: string;\n context?: OperationContext;\n signal: Maybe<AbortSignal>;\n }): Promise<TOutput> {\n try {\n const req$ = this.$request<TInput, TOutput>(opts);\n type TValue = inferObservableValue<typeof req$>;\n\n const envelope = await observableToPromise<TValue>(req$);\n const data = (envelope.result as any).data;\n return data;\n } catch (err) {\n throw TRPCClientError.from(err as Error);\n }\n }\n /** Calls a query. */\n public query(path: string, input?: unknown, opts?: TRPCRequestOptions) {\n return this.requestAsPromise<unknown, unknown>({\n type: 'query',\n path,\n input,\n context: opts?.context,\n signal: opts?.signal,\n });\n }\n /** Calls a mutation. */\n public mutation(path: string, input?: unknown, opts?: TRPCRequestOptions) {\n return this.requestAsPromise<unknown, unknown>({\n type: 'mutation',\n path,\n input,\n context: opts?.context,\n signal: opts?.signal,\n });\n }\n /**\n * Starts a subscription. With callbacks, returns what stops it. Without,\n * returns an async iterator to read it with `for await`, which `signal`,\n * `break` or `return()` stops. It can be iterated once.\n * @see https://trpc.io/docs/client/vanilla/setup#5-use-subscriptions\n */\n public subscription(\n path: string,\n input: unknown,\n opts: TRPCSubscriptionCallbacks<unknown, TRPCClientError<AnyRouter>> &\n TRPCRequestOptions,\n ): Unsubscribable;\n public subscription<\n TOpts extends TRPCRequestOptions &\n Partial<TRPCSubscriptionObserver<unknown, TRPCClientError<AnyRouter>>> =\n TRPCRequestOptions,\n >(\n path: string,\n input: unknown,\n opts?: TRPCSubscriptionWithoutCallbacks<TOpts>,\n ): AsyncIterableIterator<unknown>;\n public subscription(\n path: string,\n input: unknown,\n opts: Partial<\n TRPCSubscriptionObserver<unknown, TRPCClientError<AnyRouter>>\n > &\n TRPCRequestOptions = {},\n ): Unsubscribable | AsyncIterableIterator<unknown> {\n const hasCallbacks = observerKeys.some(\n (key) => typeof opts[key] === 'function',\n );\n const observable$ = this.$request({\n type: 'subscription',\n path,\n input,\n context: opts.context,\n signal: opts.signal,\n });\n if (!hasCallbacks) {\n const data$ = observable<unknown, TRPCClientError<AnyRouter>>(\n (observer) =>\n observable$.subscribe({\n next(envelope) {\n if (\n envelope.result.type === 'data' ||\n envelope.result.type === undefined\n ) {\n observer.next(envelope.result.data);\n }\n },\n error: (err) => observer.error(err),\n complete: () => observer.complete(),\n }),\n );\n const iterator = observableToAsyncIterable(\n data$,\n opts.signal ?? new AbortController().signal,\n );\n // a second loop over the same iterator would split the data with the\n // first, or end straight away once the first has left\n let iterated = false;\n iterator[Symbol.asyncIterator] = () => {\n if (iterated) {\n throw new Error(\n 'A subscription can only be iterated once. Call subscribe() again for another loop.',\n );\n }\n iterated = true;\n return iterator;\n };\n return iterator;\n }\n return observable$.subscribe({\n next(envelope) {\n switch (envelope.result.type) {\n case 'state': {\n opts.onConnectionStateChange?.(envelope.result);\n break;\n }\n case 'started': {\n opts.onStarted?.({\n context: envelope.context,\n });\n break;\n }\n case 'stopped': {\n opts.onStopped?.();\n break;\n }\n case 'data':\n case undefined: {\n opts.onData?.(envelope.result.data);\n break;\n }\n }\n },\n error(err) {\n opts.onError?.(err);\n },\n complete() {\n opts.onComplete?.();\n },\n });\n }\n}\n","import type { AnyRouter } from '@trpc/server/unstable-core-do-not-import';\nimport type { CreateTRPCClientOptions } from './internals/TRPCUntypedClient';\nimport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\n\n/**\n * Creates a client that calls procedures by path string, without types.\n * Meant for libraries built on tRPC; apps should use `createTRPCClient`.\n */\nexport function createTRPCUntypedClient<TRouter extends AnyRouter>(\n opts: CreateTRPCClientOptions<TRouter>,\n): TRPCUntypedClient<TRouter> {\n return new TRPCUntypedClient(opts);\n}\n\nexport type {\n CreateTRPCClientOptions,\n TRPCRequestOptions,\n} from './internals/TRPCUntypedClient';\nexport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\n","/* oxlint-disable typescript/no-non-null-assertion */\nimport type { Unsubscribable } from '@trpc/server/observable';\nimport type {\n AnyProcedure,\n AnyRouter,\n inferAsyncIterableYield,\n inferClientTypes,\n inferProcedureErrorShape,\n inferProcedureInput,\n InferrableClientTypes,\n inferTransformedProcedureOutput,\n ProcedureType,\n RouterRecord,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n createFlatProxy,\n createRecursiveProxy,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type { CreateTRPCClientOptions } from './createTRPCUntypedClient';\nimport type {\n TRPCSubscriptionCallbacks,\n TRPCSubscriptionObserver,\n TRPCSubscriptionWithoutCallbacks,\n} from './internals/TRPCUntypedClient';\nimport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\nimport type { TRPCProcedureOptions } from './internals/types';\nimport type { TRPCTaggedPromise } from './safe';\nimport type { TRPCClientError } from './TRPCClientError';\n\n/**\n * The type of a client for a router.\n * @deprecated Use {@link TRPCClient} instead. This will be removed in v12.\n * @public\n **/\nexport type inferRouterClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;\n\n/**\n * The type of a client for a router.\n * @deprecated Use {@link TRPCClient} instead. This will be removed in v12.\n * @public\n **/\nexport type CreateTRPCClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;\n\nconst untypedClientSymbol = Symbol.for('trpc_untypedClient');\n\n/**\n * A typed client for a router, as `createTRPCClient` returns it. Each\n * procedure has `.query()`, `.mutate()` or `.subscribe()`.\n * @see https://trpc.io/docs/client/vanilla/infer-types\n * @public\n **/\nexport type TRPCClient<TRouter extends AnyRouter> = DecoratedProcedureRecord<\n {\n transformer: TRouter['_def']['_config']['$types']['transformer'];\n errorShape: TRouter['_def']['_config']['$types']['errorShape'];\n },\n TRouter['_def']['record']\n> & {\n [untypedClientSymbol]: TRPCUntypedClient<TRouter>;\n};\n\n/**\n * A procedure's types, as the client sees them.\n * @internal\n */\nexport type TRPCResolverDef = {\n input: any;\n output: any;\n transformer: boolean;\n errorShape: any;\n};\n\ntype coerceAsyncGeneratorToIterable<T> =\n T extends AsyncGenerator<infer $T, infer $Return, infer $Next>\n ? AsyncIterable<$T, $Return, $Next>\n : T;\n\n/**\n * The `.query()` or `.mutate()` of a procedure on the client.\n * @internal\n */\nexport type Resolver<TDef extends TRPCResolverDef> = (\n input: TDef['input'],\n opts?: TRPCProcedureOptions,\n) => TRPCTaggedPromise<\n coerceAsyncGeneratorToIterable<TDef['output']>,\n TDef['errorShape']\n>;\n\n/**\n * The `.subscribe()` of a subscription procedure on the client.\n * @internal\n */\nexport type SubscriptionResolver<TDef extends TRPCResolverDef> = {\n (\n input: TDef['input'],\n opts: TRPCSubscriptionCallbacks<TDef['output'], TRPCClientError<TDef>> &\n TRPCProcedureOptions,\n ): Unsubscribable;\n <\n TOpts extends TRPCProcedureOptions &\n Partial<TRPCSubscriptionObserver<TDef['output'], TRPCClientError<TDef>>> =\n TRPCProcedureOptions,\n >(\n input: TDef['input'],\n opts?: TRPCSubscriptionWithoutCallbacks<TOpts>,\n ): AsyncIterableIterator<inferAsyncIterableYield<TDef['output']>>;\n};\n\ntype DecorateProcedure<\n TType extends ProcedureType,\n TDef extends TRPCResolverDef,\n> = TType extends 'query'\n ? {\n query: Resolver<TDef>;\n }\n : TType extends 'mutation'\n ? {\n mutate: Resolver<TDef>;\n }\n : TType extends 'subscription'\n ? {\n subscribe: SubscriptionResolver<TDef>;\n }\n : never;\n\n/**\n * @internal\n */\ntype DecoratedProcedureRecord<\n TRoot extends InferrableClientTypes,\n TRecord extends RouterRecord,\n> = {\n [TKey in keyof TRecord]: TRecord[TKey] extends infer $Value\n ? $Value extends AnyProcedure\n ? DecorateProcedure<\n $Value['_def']['type'],\n {\n input: inferProcedureInput<$Value>;\n output: inferTransformedProcedureOutput<\n inferClientTypes<TRoot>,\n $Value\n >;\n errorShape: inferProcedureErrorShape<TRoot, $Value>;\n transformer: inferClientTypes<TRoot>['transformer'];\n }\n >\n : $Value extends RouterRecord\n ? DecoratedProcedureRecord<TRoot, $Value>\n : never\n : never;\n};\n\nconst clientCallTypeMap: Record<\n keyof DecorateProcedure<any, any>,\n ProcedureType\n> = {\n query: 'query',\n mutate: 'mutation',\n subscribe: 'subscription',\n};\n\n/**\n * The procedure type of a client method: `query`, `mutate` or `subscribe`.\n * @internal\n */\nexport const clientCallTypeToProcedureType = (\n clientCallType: string,\n): ProcedureType => {\n return clientCallTypeMap[clientCallType as keyof typeof clientCallTypeMap];\n};\n\n/**\n * Wraps an untyped client in the typed proxy `createTRPCClient` returns.\n * @internal\n */\nexport function createTRPCClientProxy<TRouter extends AnyRouter>(\n client: TRPCUntypedClient<TRouter>,\n): TRPCClient<TRouter> {\n const proxy = createRecursiveProxy<TRPCClient<TRouter>>(({ path, args }) => {\n const pathCopy = [...path];\n const procedureType = clientCallTypeToProcedureType(pathCopy.pop()!);\n\n const fullPath = pathCopy.join('.');\n\n return (client[procedureType] as any)(fullPath, ...(args as any));\n });\n return createFlatProxy<TRPCClient<TRouter>>((key) => {\n if (key === untypedClientSymbol) {\n return client;\n }\n return proxy[key];\n });\n}\n\n/**\n * Creates a typed client for a router. Pass the router's type, and the\n * links that send its calls.\n * @example\n * ```ts\n * const client = createTRPCClient<AppRouter>({\n * links: [httpBatchLink({ url: 'http://localhost:3000/trpc' })],\n * });\n * const post = await client.post.byId.query({ id: '1' });\n * ```\n * @see https://trpc.io/docs/client/vanilla/setup#3-initialize-the-trpc-client\n */\nexport function createTRPCClient<TRouter extends AnyRouter>(\n opts: CreateTRPCClientOptions<TRouter>,\n): TRPCClient<TRouter> {\n const client = new TRPCUntypedClient(opts);\n const proxy = createTRPCClientProxy<TRouter>(client);\n return proxy;\n}\n\n/**\n * The untyped client behind a typed client, which calls procedures by\n * path string.\n * @internal\n */\nexport function getUntypedClient<TRouter extends AnyRouter>(\n client: TRPCClient<TRouter>,\n): TRPCUntypedClient<TRouter> {\n return client[untypedClientSymbol];\n}\n","import type { AnyRouter, ProcedureType } from '@trpc/server';\nimport { observable } from '@trpc/server/observable';\nimport type { TRPCErrorShape, TRPCResponse } from '@trpc/server/rpc';\nimport type { AnyClientTypes } from '@trpc/server/unstable-core-do-not-import';\nimport { jsonlStreamConsumer } from '@trpc/server/unstable-core-do-not-import';\nimport type { BatchLoader } from '../internals/dataLoader';\nimport { dataLoader } from '../internals/dataLoader';\nimport {\n allAbortSignals,\n raceAbortSignals,\n raceAbortSignalsWithCleanup,\n} from '../internals/signals';\nimport type { NonEmptyArray } from '../internals/types';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type { HTTPBatchLinkOptions } from './HTTPBatchLinkOptions';\nimport type { HTTPResult } from './internals/httpUtils';\nimport {\n fetchHTTPResponse,\n getBody,\n getUrl,\n resolveHTTPLinkOptions,\n} from './internals/httpUtils';\nimport type { Operation, TRPCLink } from './types';\n\n/**\n * Options for {@link httpBatchStreamLink}. Takes the same options as\n * `httpBatchLink`, plus `streamHeader`.\n *\n * @see https://trpc.io/docs/client/links/httpBatchStreamLink#options\n */\nexport type HTTPBatchStreamLinkOptions<TRoot extends AnyClientTypes> =\n HTTPBatchLinkOptions<TRoot> & {\n /**\n * Which header to use to signal the server that the client wants a streaming response.\n * - `'trpc-accept'` (default): sends `trpc-accept: application/jsonl` header\n * - `'accept'`: sends `Accept: application/jsonl` header, which can avoid CORS preflight for cross-origin streaming queries. Be aware that `application/jsonl` is not an official MIME type and so this is not completely spec-compliant - you should test that your infrastructure supports this value.\n * @default 'trpc-accept'\n */\n streamHeader?: 'trpc-accept' | 'accept';\n };\n\ntype BatchStreamOperation = Operation & {\n releaseSignal: () => void;\n /** Aborts the op's signal once its response has nothing left to stream */\n settle: () => void;\n};\n\n/**\n * A terminating link that batches calls like `httpBatchLink`, but streams each\n * response back as soon as it is ready.\n *\n * @see https://trpc.io/docs/client/links/httpBatchStreamLink\n */\nexport function httpBatchStreamLink<TRouter extends AnyRouter>(\n opts: HTTPBatchStreamLinkOptions<TRouter['_def']['_config']['$types']>,\n): TRPCLink<TRouter> {\n const resolvedOpts = resolveHTTPLinkOptions(opts);\n const maxURLLength = opts.maxURLLength ?? Infinity;\n const maxItems = opts.maxItems ?? Infinity;\n\n return () => {\n const batchLoader = (\n type: ProcedureType,\n ): BatchLoader<BatchStreamOperation, HTTPResult> => {\n return {\n validate(batchOps) {\n if (maxURLLength === Infinity && maxItems === Infinity) {\n // escape hatch for quick calcs\n return true;\n }\n if (batchOps.length > maxItems) {\n return false;\n }\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n\n const url = getUrl({\n ...resolvedOpts,\n type,\n path,\n inputs,\n signal: null,\n });\n\n return url.length <= maxURLLength;\n },\n async fetch(batchOps) {\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n\n const batchSignals = allAbortSignals(\n ...batchOps.map((op) => op.signal),\n );\n const abortController = new AbortController();\n abortController.signal.addEventListener(\n 'abort',\n () => {\n for (const op of batchOps) {\n op.releaseSignal();\n }\n },\n { once: true },\n );\n\n const responsePromise = fetchHTTPResponse({\n ...resolvedOpts,\n signal: raceAbortSignals(batchSignals, abortController.signal),\n type,\n contentTypeHeader: 'application/json',\n trpcAcceptHeader: 'application/jsonl',\n trpcAcceptHeaderKey: opts.streamHeader ?? 'trpc-accept',\n getUrl,\n getBody,\n inputs,\n path,\n headers() {\n if (!opts.headers) {\n return {};\n }\n if (typeof opts.headers === 'function') {\n return opts.headers({\n opList: batchOps as NonEmptyArray<BatchStreamOperation>,\n });\n }\n return opts.headers;\n },\n });\n\n const res = await responsePromise;\n\n if (!res.ok) {\n // Server returned a non-2xx response (e.g. batching disabled).\n // The body is plain JSON, not JSONL, so parse it directly and\n // propagate the same error to every operation in the batch.\n const json = (await res.json()) as TRPCResponse;\n if ('error' in json) {\n json.error = resolvedOpts.transformer.output.deserialize(\n json.error,\n );\n }\n\n return batchOps.map((): Promise<HTTPResult> =>\n Promise.resolve({\n json,\n meta: {\n response: res,\n },\n }),\n );\n }\n\n const [head] = await jsonlStreamConsumer<\n Record<string, Promise<any>>\n >({\n // oxlint-disable-next-line typescript/no-non-null-assertion\n from: res.body!,\n deserialize: (data) =>\n resolvedOpts.transformer.output.deserialize(data),\n onError: () => abortController.abort(),\n // An op with nothing left to stream must not hold the batch open.\n onSettled: (settled) => batchOps[Number(settled.key)]?.settle(),\n formatError(opts) {\n const error = opts.error as TRPCErrorShape;\n return TRPCClientError.from({\n error,\n });\n },\n abortController,\n });\n const promises = Object.keys(batchOps).map(\n async (key): Promise<HTTPResult> => {\n let json: TRPCResponse = await Promise.resolve(head[key]);\n\n if ('result' in json) {\n /**\n * Not very pretty, but we need to unwrap nested data as promises\n * Our stream producer will only resolve top-level async values or async values that are directly nested in another async value\n */\n const result = await Promise.resolve(json.result);\n json = {\n result: {\n data: await Promise.resolve(result.data),\n },\n };\n }\n\n return {\n json,\n meta: {\n response: res,\n },\n };\n },\n );\n return promises;\n },\n };\n };\n\n const query = dataLoader(batchLoader('query'));\n const mutation = dataLoader(batchLoader('mutation'));\n\n const loaders = { query, mutation };\n return ({ op }) => {\n return observable((observer) => {\n /* istanbul ignore if -- @preserve */\n if (op.type === 'subscription') {\n throw new Error(\n 'Subscriptions are unsupported by `httpBatchStreamLink` - use `httpSubscriptionLink` or `wsLink`',\n );\n }\n const ac = new AbortController();\n const loader = loaders[op.type];\n const { signal, cleanup } = raceAbortSignalsWithCleanup(\n op.signal,\n ac.signal,\n );\n const promise = loader.load({\n ...op,\n signal,\n releaseSignal: cleanup,\n settle: () => ac.abort(),\n });\n\n let isDone = false;\n let _res = undefined as HTTPResult | undefined;\n promise\n .then((res) => {\n isDone = true;\n _res = res;\n if ('error' in res.json) {\n // A failed op has nothing left to stream, so it must not hold the batch open.\n ac.abort();\n observer.error(\n TRPCClientError.from(res.json, {\n meta: res.meta,\n }),\n );\n return;\n } else if ('result' in res.json) {\n observer.next({\n context: res.meta,\n result: res.json.result,\n });\n observer.complete();\n return;\n }\n\n observer.complete();\n })\n .catch((err) => {\n isDone = true;\n ac.abort();\n observer.error(\n TRPCClientError.from(err, {\n meta: _res?.meta,\n }),\n );\n });\n\n return () => {\n if (!isDone) {\n ac.abort();\n }\n };\n });\n };\n };\n}\n\n/**\n * @deprecated Use {@link httpBatchStreamLink} instead.\n */\nexport const unstable_httpBatchStreamLink = httpBatchStreamLink;\n","import { isObject } from '@trpc/server/unstable-core-do-not-import';\n\nexport function inputWithTrackedEventId(\n input: unknown,\n lastEventId: string | undefined,\n) {\n if (!lastEventId) {\n return input;\n }\n // the server's `isObject` excludes arrays, so spreading one here would corrupt it\n if (input != null && !isObject(input)) {\n return input;\n }\n return {\n ...(input ?? {}),\n lastEventId,\n };\n}\n","import { behaviorSubject, observable } from '@trpc/server/observable';\nimport type { TRPCErrorShape, TRPCResult } from '@trpc/server/rpc';\nimport type {\n AnyClientTypes,\n EventSourceLike,\n inferClientTypes,\n InferrableClientTypes,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n resolvePathSeparator,\n retryableRpcCodes,\n run,\n sseStreamConsumer,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport { raceAbortSignals } from '../internals/signals';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type { TRPCConnectionState } from '../unstable-internals';\nimport { getTransformer, type TransformerOptions } from '../unstable-internals';\nimport { getUrl, type HTTPLinkBaseOptions } from './internals/httpUtils';\nimport {\n resultOf,\n type UrlOptionsWithConnectionParams,\n} from './internals/urlWithConnectionParams';\nimport type { Operation, TRPCLink } from './types';\n\nasync function urlWithConnectionParams(\n opts: UrlOptionsWithConnectionParams,\n): Promise<string> {\n let url = await resultOf(opts.url);\n if (opts.connectionParams) {\n const params = await resultOf(opts.connectionParams);\n\n const prefix = url.includes('?') ? '&' : '?';\n url +=\n prefix + 'connectionParams=' + encodeURIComponent(JSON.stringify(params));\n }\n\n return url;\n}\n\n/**\n * @see https://trpc.io/docs/client/links/httpSubscriptionLink#httpsubscriptionlink-options\n */\ntype HTTPSubscriptionLinkOptions<\n TRoot extends AnyClientTypes,\n TEventSource extends EventSourceLike.AnyConstructor = typeof EventSource,\n> = {\n /**\n * The `EventSource` class to use, for runtimes that don't have one.\n * @see https://trpc.io/docs/client/links/httpSubscriptionLink#custom-headers-through-ponyfill\n */\n EventSource?: TEventSource;\n /**\n * Options passed to the `EventSource`, or a function that returns them for\n * each subscription.\n */\n eventSourceOptions?:\n | EventSourceLike.InitDictOf<TEventSource>\n | ((opts: {\n op: Operation;\n }) =>\n | EventSourceLike.InitDictOf<TEventSource>\n | Promise<EventSourceLike.InitDictOf<TEventSource>>);\n} & Pick<HTTPLinkBaseOptions<TRoot>, 'pathSeparator'> &\n TransformerOptions<TRoot> &\n UrlOptionsWithConnectionParams;\n\n/**\n * A terminating link that runs subscriptions over Server-Sent Events.\n *\n * @see https://trpc.io/docs/client/links/httpSubscriptionLink\n */\nexport function httpSubscriptionLink<\n TInferrable extends InferrableClientTypes,\n TEventSource extends EventSourceLike.AnyConstructor,\n>(\n opts: HTTPSubscriptionLinkOptions<\n inferClientTypes<TInferrable>,\n TEventSource\n >,\n): TRPCLink<TInferrable> {\n const transformer = getTransformer(opts.transformer);\n const pathSeparator = resolvePathSeparator(opts.pathSeparator);\n\n return () => {\n return ({ op }) => {\n return observable((observer) => {\n const { type, path, input } = op;\n\n /* istanbul ignore if -- @preserve */\n if (type !== 'subscription') {\n throw new Error('httpSubscriptionLink only supports subscriptions');\n }\n\n let lastEventId: string | undefined = undefined;\n const ac = new AbortController();\n const signal = raceAbortSignals(op.signal, ac.signal);\n const eventSourceStream = sseStreamConsumer<{\n EventSource: TEventSource;\n data: Partial<{\n id?: string;\n data: unknown;\n }>;\n error: TRPCErrorShape;\n }>({\n url: async () =>\n getUrl({\n transformer,\n url: await urlWithConnectionParams(opts),\n input: inputWithTrackedEventId(input, lastEventId),\n path,\n pathSeparator,\n type,\n signal: null,\n }),\n init: () => resultOf(opts.eventSourceOptions, { op }),\n signal,\n deserialize: (data) => transformer.output.deserialize(data),\n EventSource: opts.EventSource ?? (globalThis.EventSource as never),\n });\n\n const connectionState = behaviorSubject<\n TRPCConnectionState<TRPCClientError<any>>\n >({\n type: 'state',\n state: 'connecting',\n error: null,\n });\n\n const connectionSub = connectionState.subscribe({\n next(state) {\n observer.next({\n result: state,\n });\n },\n });\n run(async () => {\n for await (const chunk of eventSourceStream) {\n switch (chunk.type) {\n case 'ping':\n // do nothing\n break;\n case 'data':\n const chunkData = chunk.data;\n\n let result: TRPCResult<unknown>;\n if (chunkData.id) {\n // if the `tracked()`-helper is used, we always have an `id` field\n lastEventId = chunkData.id;\n result = {\n id: chunkData.id,\n data: chunkData,\n };\n } else {\n result = {\n data: chunkData.data,\n };\n }\n\n observer.next({\n result,\n context: {\n eventSource: chunk.eventSource,\n },\n });\n break;\n case 'connected': {\n observer.next({\n result: {\n type: 'started',\n },\n context: {\n eventSource: chunk.eventSource,\n },\n });\n connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n });\n break;\n }\n case 'serialized-error': {\n const error = TRPCClientError.from({ error: chunk.error });\n\n if (retryableRpcCodes.includes(chunk.error.code)) {\n //\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error,\n });\n break;\n }\n //\n // non-retryable error, cancel the subscription\n throw error;\n }\n case 'connecting': {\n const lastState = connectionState.get();\n\n const error = chunk.event && TRPCClientError.from(chunk.event);\n if (!error && lastState.state === 'connecting') {\n break;\n }\n\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error,\n });\n break;\n }\n case 'timeout': {\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error: new TRPCClientError(\n `Timeout of ${chunk.ms}ms reached while waiting for a response`,\n ),\n });\n }\n }\n }\n observer.next({\n result: {\n type: 'stopped',\n },\n });\n connectionState.next({\n type: 'state',\n state: 'idle',\n error: null,\n });\n observer.complete();\n }).catch((error) => {\n observer.error(TRPCClientError.from(error));\n });\n\n return () => {\n observer.complete();\n ac.abort();\n connectionSub.unsubscribe();\n };\n });\n };\n };\n}\n\n/**\n * @deprecated Use {@link httpSubscriptionLink} instead.\n */\nexport const unstable_httpSubscriptionLink = httpSubscriptionLink;\n","/* istanbul ignore file -- @preserve */\n// We're not actually exporting this link\nimport type { Unsubscribable } from '@trpc/server/observable';\nimport { observable } from '@trpc/server/observable';\nimport type { InferrableClientTypes } from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport type { TRPCClientError } from '../TRPCClientError';\nimport type { Operation, TRPCLink } from './types';\n\ninterface RetryLinkOptions<TInferrable extends InferrableClientTypes> {\n /**\n * The retry function\n */\n retry: (opts: RetryFnOptions<TInferrable>) => boolean;\n /**\n * The delay between retries in ms (defaults to 0)\n */\n retryDelayMs?: (attempt: number) => number;\n}\n\ninterface RetryFnOptions<TInferrable extends InferrableClientTypes> {\n /**\n * The operation that failed\n */\n op: Operation;\n /**\n * The error that occurred\n */\n error: TRPCClientError<TInferrable>;\n /**\n * The number of attempts that have been made (including the first call)\n */\n attempts: number;\n}\n\n/**\n * Retries failed operations. Subscriptions resume from the last tracked event\n * id.\n *\n * @see https://trpc.io/docs/client/links/retryLink\n */\nexport function retryLink<TInferrable extends InferrableClientTypes>(\n opts: RetryLinkOptions<TInferrable>,\n): TRPCLink<TInferrable> {\n // initialized config\n return () => {\n // initialized in app\n return (callOpts) => {\n // initialized for request\n return observable((observer) => {\n let next$: Unsubscribable;\n let currentAttempt = 0;\n let disposed = false;\n let callNextTimeout: ReturnType<typeof setTimeout> | undefined =\n undefined;\n\n let lastEventId: string | undefined = undefined;\n\n attempt(1);\n\n function opWithLastEventId() {\n const op = callOpts.op;\n if (!lastEventId) {\n return op;\n }\n\n return {\n ...op,\n input: inputWithTrackedEventId(op.input, lastEventId),\n };\n }\n\n function attempt(attempts: number) {\n if (disposed) {\n return;\n }\n currentAttempt = attempts;\n const op = opWithLastEventId();\n\n const subscription = callOpts.next(op).subscribe({\n error(error) {\n const shouldRetry = opts.retry({\n op,\n attempts,\n error,\n });\n if (disposed) {\n return;\n }\n if (!shouldRetry) {\n observer.error(error);\n return;\n }\n const delayMs = opts.retryDelayMs?.(attempts) ?? 0;\n if (disposed) {\n return;\n }\n\n if (delayMs <= 0) {\n attempt(attempts + 1);\n return;\n }\n callNextTimeout = setTimeout(\n () => attempt(attempts + 1),\n delayMs,\n );\n },\n next(envelope) {\n //\n if (\n (!envelope.result.type || envelope.result.type === 'data') &&\n envelope.result.id\n ) {\n //\n lastEventId = envelope.result.id;\n }\n\n observer.next(envelope);\n },\n complete() {\n observer.complete();\n },\n });\n\n // A synchronous error may have already subscribed the next attempt.\n if (disposed) {\n subscription.unsubscribe();\n } else if (currentAttempt === attempts) {\n next$ = subscription;\n }\n }\n return () => {\n disposed = true;\n next$.unsubscribe();\n clearTimeout(callNextTimeout);\n };\n });\n };\n };\n}\n","import {\n getTRPCErrorFromUnknown,\n getTRPCErrorShape,\n isTrackedEnvelope,\n} from '@trpc/server';\nimport { behaviorSubject, observable } from '@trpc/server/observable';\nimport { TRPC_ERROR_CODES_BY_KEY, type TRPCResult } from '@trpc/server/rpc';\nimport {\n callProcedure,\n isAbortError,\n isAsyncIterable,\n iteratorResource,\n makeResource,\n retryableRpcCodes,\n run,\n type AnyRouter,\n type ErrorHandlerOptions,\n type inferClientTypes,\n type inferRouterContext,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport {\n abortSignalToPromise,\n raceAbortSignals,\n throwIfAborted,\n} from '../internals/signals';\nimport { getTransformer } from '../internals/transformer';\nimport type { TransformerOptions } from '../internals/transformer';\nimport { isTRPCClientError, TRPCClientError } from '../TRPCClientError';\nimport type { TRPCConnectionState } from './internals/subscriptions';\nimport type { TRPCLink } from './types';\n\n/**\n * Passed to {@link LocalLinkOptions.createContext}.\n */\nexport type LocalLinkCreateContextOptions = {\n /**\n * What tRPC knows about the call, like the `info` that adapters pass to\n * their `createContext`.\n */\n info: {\n /**\n * Aborts when the call is cancelled or unsubscribed. Pass it on to work\n * that creating the context starts, such as `fetch()` calls.\n */\n signal: AbortSignal;\n };\n};\n\n/**\n * Options for {@link localLink}.\n *\n * @see https://trpc.io/docs/client/links/localLink#options\n */\nexport type LocalLinkOptions<TRouter extends AnyRouter> = {\n /**\n * The router to call.\n * @see https://trpc.io/docs/client/links/localLink#router\n */\n router: TRouter;\n /**\n * Creates the context for each call. `info.signal` aborts when the call\n * is cancelled.\n * @see https://trpc.io/docs/client/links/localLink#createcontext\n */\n createContext: (\n opts: LocalLinkCreateContextOptions,\n ) => Promise<inferRouterContext<TRouter>>;\n /**\n * Called when a procedure throws.\n * @see https://trpc.io/docs/client/links/localLink#onerror\n */\n onError?: (opts: ErrorHandlerOptions<inferRouterContext<TRouter>>) => void;\n} & TransformerOptions<inferClientTypes<TRouter>>;\n\n/**\n * A terminating link that calls procedures on a router in the same process,\n * without HTTP.\n *\n * @see https://trpc.io/docs/client/links/localLink\n */\nexport function localLink<TRouter extends AnyRouter>(\n opts: LocalLinkOptions<TRouter>,\n): TRPCLink<TRouter> {\n const transformer = getTransformer(opts.transformer);\n\n const transformChunk = (chunk: unknown) => {\n if (opts.transformer) {\n // assume transformer will do the right thing\n return chunk;\n }\n // Special case for undefined, because `JSON.stringify(undefined)` throws\n if (chunk === undefined) {\n return chunk;\n }\n const serialized = JSON.stringify(transformer.input.serialize(chunk));\n const deserialized = JSON.parse(transformer.output.deserialize(serialized));\n return deserialized;\n };\n\n return () =>\n ({ op }) =>\n observable((observer) => {\n let ctx: inferRouterContext<TRouter> | undefined = undefined;\n const ac = new AbortController();\n\n const signal = raceAbortSignals(op.signal, ac.signal);\n const signalPromise = abortSignalToPromise(signal);\n\n signalPromise.catch(() => {\n // prevent unhandled rejection\n });\n\n let input = op.input;\n async function runProcedure(newInput: unknown): Promise<unknown> {\n input = newInput;\n\n // don't start work for a call that was cancelled before it ran\n throwIfAborted(signal);\n ctx = await opts.createContext({ info: { signal } });\n throwIfAborted(signal);\n\n return callProcedure({\n router: opts.router,\n path: op.path,\n getRawInput: async () => newInput,\n ctx,\n type: op.type,\n signal,\n batchIndex: 0,\n });\n }\n\n function onErrorCallback(cause: unknown) {\n if (isAbortError(cause)) {\n return;\n }\n opts.onError?.({\n error: getTRPCErrorFromUnknown(cause),\n type: op.type,\n path: op.path,\n input,\n ctx,\n });\n }\n\n function coerceToTRPCClientError(cause: unknown) {\n if (isTRPCClientError<TRouter>(cause)) {\n return cause;\n }\n const error = getTRPCErrorFromUnknown(cause);\n\n const shape = getTRPCErrorShape({\n config: opts.router._def._config,\n ctx,\n error,\n input,\n path: op.path,\n type: op.type,\n });\n return TRPCClientError.from(\n { error: transformChunk(shape) },\n { cause: cause instanceof Error ? cause : undefined },\n );\n }\n\n run(async () => {\n switch (op.type) {\n case 'query':\n case 'mutation': {\n const result = await Promise.race([\n runProcedure(op.input),\n signalPromise,\n ]);\n if (!isAsyncIterable(result)) {\n observer.next({\n result: { data: transformChunk(result) },\n });\n observer.complete();\n break;\n }\n\n observer.next({\n result: {\n data: (async function* () {\n await using iterator = iteratorResource(result);\n using _finally = makeResource({}, () => {\n observer.complete();\n });\n try {\n while (true) {\n const res = await Promise.race([\n iterator.next(),\n signalPromise,\n ]);\n if (res.done) {\n return transformChunk(res.value);\n }\n yield transformChunk(res.value);\n }\n } catch (cause) {\n onErrorCallback(cause);\n throw coerceToTRPCClientError(cause);\n }\n })(),\n },\n });\n break;\n }\n case 'subscription': {\n const connectionState = behaviorSubject<\n TRPCConnectionState<TRPCClientError<any>>\n >({\n type: 'state',\n state: 'connecting',\n error: null,\n });\n\n const connectionSub = connectionState.subscribe({\n next(state) {\n observer.next({\n result: state,\n });\n },\n });\n let lastEventId: string | undefined = undefined;\n\n using _finally = makeResource({}, async () => {\n connectionState.next({\n type: 'state',\n state: 'idle',\n error: null,\n });\n connectionSub.unsubscribe();\n });\n\n // returning from here means the stream ended, so this completes\n // below - a throw is left to the `.catch()`, which needs the\n // observer to still be open by the time it runs\n await run(async () => {\n while (true) {\n const result = await runProcedure(\n inputWithTrackedEventId(op.input, lastEventId),\n );\n if (!isAsyncIterable(result)) {\n throw new Error('Expected an async iterable');\n }\n await using iterator = iteratorResource(result);\n\n observer.next({\n result: {\n type: 'started',\n },\n });\n connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n });\n\n // Use a while loop to handle errors and reconnects\n while (true) {\n let res;\n try {\n res = await Promise.race([\n iterator.next(),\n signalPromise,\n ]);\n } catch (cause) {\n if (isAbortError(cause)) {\n return;\n }\n const error = getTRPCErrorFromUnknown(cause);\n\n if (\n !retryableRpcCodes.includes(\n TRPC_ERROR_CODES_BY_KEY[error.code],\n )\n ) {\n throw coerceToTRPCClientError(error);\n }\n\n onErrorCallback(error);\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error: coerceToTRPCClientError(error),\n });\n\n break;\n }\n\n if (res.done) {\n return;\n }\n let chunk: TRPCResult<unknown>;\n if (isTrackedEnvelope(res.value)) {\n lastEventId = res.value[0];\n\n chunk = {\n id: res.value[0],\n data: {\n id: res.value[0],\n data: res.value[1],\n },\n };\n } else {\n chunk = {\n data: res.value,\n };\n }\n\n observer.next({\n result: {\n ...chunk,\n data: transformChunk(chunk.data),\n },\n });\n }\n }\n });\n\n observer.complete();\n break;\n }\n }\n }).catch((cause) => {\n onErrorCallback(cause);\n observer.error(coerceToTRPCClientError(cause));\n });\n\n return () => {\n ac.abort();\n };\n });\n}\n\n/**\n * @deprecated Use {@link localLink} instead.\n * @function\n */\nexport const unstable_localLink = localLink;\n\n/**\n * @deprecated Use {@link localLink} instead. This alias will be removed in a\n * future major release.\n */\nexport const experimental_localLink = localLink;\n","import type { TRPCClientError } from './TRPCClientError';\n\n/**\n * @internal\n */\nexport declare const errorShapeTag: unique symbol;\n\n/**\n * The promise a client's `.query()` or `.mutate()` returns, tagged with\n * the procedure's error shape for `safe()`.\n */\nexport type TRPCTaggedPromise<TData, TErrorShape> = Promise<TData> & {\n readonly [errorShapeTag]: TErrorShape;\n};\n\n/**\n * @internal\n */\nexport type inferSafeError<TErrorShape> = TRPCClientError<{\n errorShape: TErrorShape;\n transformer: boolean;\n}>;\n\n/**\n * What `safe()` resolves to: `[data, undefined]` or `[undefined, error]`.\n * @see https://trpc.io/docs/client/vanilla/error-handling#errors-as-values-with-safe\n */\nexport type SafeResult<TData, TErrorShape> =\n | readonly [data: TData, error: undefined]\n | readonly [data: undefined, error: inferSafeError<TErrorShape>];\n\n/**\n * Awaits a client `.query()` or `.mutate()` call without throwing, and\n * returns a `[data, error]` pair typed with the procedure's error shape.\n *\n * @example\n * ```ts\n * const [post, error] = await safe(client.post.byId.query({ id }));\n * if (error) {\n * console.error(error);\n * }\n *\n * const id = post.id;\n * ```\n * @see https://trpc.io/docs/client/vanilla/error-handling#errors-as-values-with-safe\n */\nexport async function safe<TData, TErrorShape>(\n promise: TRPCTaggedPromise<TData, TErrorShape>,\n): Promise<SafeResult<TData, TErrorShape>> {\n try {\n return [await promise, undefined];\n } catch (cause) {\n return [undefined, cause as inferSafeError<TErrorShape>];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAsFA,MAAM,eAA8B;CAClC;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAoBA,IAAa,oBAAb,MAA0E;CAKxE,YAAY,MAA4C;EAJvC,gBAAA,MAAA,SAAA,KAAA,CAAA;EACD,gBAAA,MAAA,WAAA,KAAA,CAAA;EACR,gBAAA,MAAA,aAAA,KAAA,CAAA;EAGN,KAAK,YAAY;EAEjB,KAAK,UAAU,CAAC;EAGhB,KAAK,QAAQ,KAAK,MAAM,KAAK,SAAS,KAAK,KAAK,OAAO,CAAC;CAC1D;CAEA,SAAsD,MAMnD;;EASD,OARe,YAAwC;GACrD,OAAO,KAAK;GACZ,IAAA,eAAA,eAAA,CAAA,GACK,IAAA,GAAA,CAAA,GAAA;IACH,UAAA,gBAAS,KAAK,aAAA,QAAA,kBAAA,KAAA,IAAA,gBAAW,CAAC;IAC1B,IAAI,EAAE,KAAK;GACb,CAAA;EACF,CACY,CAAC,CAAC,KAAK,MAAM,CAAC;CAC5B;CAEA,MAAc,iBAAsD,MAM/C;EACnB,IAAI;GACF,MAAM,OAAO,KAAK,SAA0B,IAAI;GAKhD,QADc,MADS,oBAA4B,IAAI,EAAA,CAChC,OAAe;EAExC,SAAS,KAAK;GACZ,MAAM,gBAAgB,KAAK,GAAY;EACzC;CACF;;CAEA,MAAa,MAAc,OAAiB,MAA2B;EACrE,OAAO,KAAK,iBAAmC;GAC7C,MAAM;GACN;GACA;GACA,SAAA,SAAA,QAAA,SAAA,KAAA,IAAA,KAAA,IAAS,KAAM;GACf,QAAA,SAAA,QAAA,SAAA,KAAA,IAAA,KAAA,IAAQ,KAAM;EAChB,CAAC;CACH;;CAEA,SAAgB,MAAc,OAAiB,MAA2B;EACxE,OAAO,KAAK,iBAAmC;GAC7C,MAAM;GACN;GACA;GACA,SAAA,SAAA,QAAA,SAAA,KAAA,IAAA,KA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N,IAAI,IAAI,MAAM;UACd,MAAM;WACJ,IAAI,IAAI,MAAM;WACd,MAAM,IAAI,MAAM;UAClB;SACF;QACF,OACE,QAAQ,EACN,MAAM,IAAI,MACZ;QAGF,SAAS,KAAK,EACZ,QAAA,eAAA,eAAA,CAAA,GACK,KAAA,GAAA,CAAA,GAAA,EACH,MAAM,eAAe,MAAM,IAAI,EAAA,CACjC,EACF,CAAC;OACH;;;;;;KAEJ,CAAC;KAED,SAAS,SAAS;KAClB;;;;;;GAEJ;EACF,CAAC,CAAC,CAAC,OAAO,UAAU;GAClB,gBAAgB,KAAK;GACrB,SAAS,MAAM,wBAAwB,KAAK,CAAC;EAC/C,CAAC;EAED,aAAa;GACX,GAAG,MAAM;EACX;CACF,CAAC;AACP;;;;;AAMA,MAAa,qBAAqB;;;;;AAMlC,MAAa,yBAAyB;;;;;;;;;;;;;;;;;AC7StC,eAAsB,KACpB,SACyC;CACzC,IAAI;EACF,OAAO,CAAC,MAAM,SAAS,KAAA,CAAS;CAClC,SAAS,OAAO;EACd,OAAO,CAAC,KAAA,GAAW,KAAoC;CACzD;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/internals/TRPCUntypedClient.ts","../src/createTRPCUntypedClient.ts","../src/createTRPCClient.ts","../src/links/httpBatchStreamLink.ts","../src/internals/inputWithTrackedEventId.ts","../src/links/httpSubscriptionLink.ts","../src/links/retryLink.ts","../src/links/localLink.ts","../src/safe.ts"],"sourcesContent":["import type {\n inferObservableValue,\n Unsubscribable,\n} from '@trpc/server/observable';\nimport {\n observable,\n observableToAsyncIterable,\n observableToPromise,\n share,\n} from '@trpc/server/observable';\nimport type {\n AnyRouter,\n inferAsyncIterableYield,\n InferrableClientTypes,\n Maybe,\n TypeError,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { createChain } from '../links/internals/createChain';\nimport type { TRPCConnectionState } from '../links/internals/subscriptions';\nimport type {\n OperationContext,\n OperationLink,\n TRPCClientRuntime,\n TRPCLink,\n} from '../links/types';\nimport { TRPCClientError } from '../TRPCClientError';\n\ntype TRPCType = 'mutation' | 'query' | 'subscription';\n/** The options of a call made with the untyped client. */\nexport interface TRPCRequestOptions {\n /**\n * Context for the links, such as a flag a `splitLink` reads.\n * @see https://trpc.io/docs/client/links#managing-context\n */\n context?: OperationContext;\n /**\n * Aborts the call. With `httpBatchLink`, the request is only aborted once\n * every call in its batch is, so an aborted call can still get a result.\n */\n signal?: AbortSignal;\n}\n\n/** The callbacks a subscription takes on the client. */\nexport interface TRPCSubscriptionObserver<TValue, TError> {\n /** Called when the link sends a `started` result. */\n onStarted: (opts: { context: OperationContext | undefined }) => void;\n /** Called with each event. */\n onData: (value: inferAsyncIterableYield<TValue>) => void;\n /** Called when the subscription ends with an error. */\n onError: (err: TError) => void;\n /**\n * Called when the link sends a `stopped` result. Not every link sends\n * one; `localLink` doesn't.\n */\n onStopped: () => void;\n /** Called when the subscription's observable completes, for any reason. */\n onComplete: () => void;\n /** Called when the connection connects, drops or reconnects. */\n onConnectionStateChange: (state: TRPCConnectionState<TError>) => void;\n}\n\ntype ObserverKey = keyof TRPCSubscriptionObserver<unknown, unknown>;\n\n/**\n * Subscription options without callbacks: `TOpts` must not have any of the\n * callback keys, not even set to `undefined`.\n * @internal\n */\nexport type TRPCSubscriptionWithoutCallbacks<TOpts> = TOpts & {\n // `keyof` a union only has its shared keys, so this one catches each member\n [TKey in ObserverKey]?: never;\n} & {\n [TKey in keyof TOpts & ObserverKey]: never;\n};\n\n/**\n * Subscription callbacks, at least one of which is defined.\n * @internal\n */\nexport type TRPCSubscriptionCallbacks<TValue, TError> = Partial<\n TRPCSubscriptionObserver<TValue, TError>\n> &\n {\n [TKey in ObserverKey]: Pick<TRPCSubscriptionObserver<TValue, TError>, TKey>;\n }[ObserverKey];\n\nconst observerKeys: ObserverKey[] = [\n 'onStarted',\n 'onData',\n 'onError',\n 'onStopped',\n 'onComplete',\n 'onConnectionStateChange',\n];\n\n/**\n * The options of `createTRPCClient`.\n * @internal\n */\nexport type CreateTRPCClientOptions<TRouter extends InferrableClientTypes> = {\n /**\n * The links each call goes through, in order. The last one must send\n * the call, such as `httpBatchLink`.\n * @see https://trpc.io/docs/client/links\n */\n links: TRPCLink<TRouter>[];\n transformer?: TypeError<'The transformer property has moved to httpLink/httpBatchLink/wsLink'>;\n};\n\n/**\n * A client that calls procedures by path string, without types.\n * `createTRPCClient` wraps one.\n */\nexport class TRPCUntypedClient<TInferrable extends InferrableClientTypes> {\n private readonly links: OperationLink<TInferrable>[];\n public readonly runtime: TRPCClientRuntime;\n private requestId: number;\n\n constructor(opts: CreateTRPCClientOptions<TInferrable>) {\n this.requestId = 0;\n\n this.runtime = {};\n\n // Initialize the links\n this.links = opts.links.map((link) => link(this.runtime));\n }\n\n private $request<TInput = unknown, TOutput = unknown>(opts: {\n type: TRPCType;\n input: TInput;\n path: string;\n context?: OperationContext;\n signal: Maybe<AbortSignal>;\n }) {\n const chain$ = createChain<AnyRouter, TInput, TOutput>({\n links: this.links as OperationLink<any, any, any>[],\n op: {\n ...opts,\n context: opts.context ?? {},\n id: ++this.requestId,\n },\n });\n return chain$.pipe(share());\n }\n\n private async requestAsPromise<TInput = unknown, TOutput = unknown>(opts: {\n type: TRPCType;\n input: TInput;\n path: string;\n context?: OperationContext;\n signal: Maybe<AbortSignal>;\n }): Promise<TOutput> {\n try {\n const req$ = this.$request<TInput, TOutput>(opts);\n type TValue = inferObservableValue<typeof req$>;\n\n const envelope = await observableToPromise<TValue>(req$);\n const data = (envelope.result as any).data;\n return data;\n } catch (err) {\n throw TRPCClientError.from(err as Error);\n }\n }\n /** Calls a query. */\n public query(path: string, input?: unknown, opts?: TRPCRequestOptions) {\n return this.requestAsPromise<unknown, unknown>({\n type: 'query',\n path,\n input,\n context: opts?.context,\n signal: opts?.signal,\n });\n }\n /** Calls a mutation. */\n public mutation(path: string, input?: unknown, opts?: TRPCRequestOptions) {\n return this.requestAsPromise<unknown, unknown>({\n type: 'mutation',\n path,\n input,\n context: opts?.context,\n signal: opts?.signal,\n });\n }\n /**\n * Starts a subscription. With callbacks, returns what stops it. Without,\n * returns an async iterator to read it with `for await`, which `signal`,\n * `break` or `return()` stops. It can be iterated once.\n * @see https://trpc.io/docs/client/vanilla/setup#5-use-subscriptions\n */\n public subscription(\n path: string,\n input: unknown,\n opts: TRPCSubscriptionCallbacks<unknown, TRPCClientError<AnyRouter>> &\n TRPCRequestOptions,\n ): Unsubscribable;\n public subscription<\n TOpts extends TRPCRequestOptions &\n Partial<TRPCSubscriptionObserver<unknown, TRPCClientError<AnyRouter>>> =\n TRPCRequestOptions,\n >(\n path: string,\n input: unknown,\n opts?: TRPCSubscriptionWithoutCallbacks<TOpts>,\n ): AsyncIterableIterator<unknown>;\n public subscription(\n path: string,\n input: unknown,\n opts: Partial<\n TRPCSubscriptionObserver<unknown, TRPCClientError<AnyRouter>>\n > &\n TRPCRequestOptions = {},\n ): Unsubscribable | AsyncIterableIterator<unknown> {\n const hasCallbacks = observerKeys.some(\n (key) => typeof opts[key] === 'function',\n );\n const observable$ = this.$request({\n type: 'subscription',\n path,\n input,\n context: opts.context,\n signal: opts.signal,\n });\n if (!hasCallbacks) {\n const data$ = observable<unknown, TRPCClientError<AnyRouter>>(\n (observer) =>\n observable$.subscribe({\n next(envelope) {\n if (\n envelope.result.type === 'data' ||\n envelope.result.type === undefined\n ) {\n observer.next(envelope.result.data);\n }\n },\n error: (err) => observer.error(err),\n complete: () => observer.complete(),\n }),\n );\n const iterator = observableToAsyncIterable(\n data$,\n opts.signal ?? new AbortController().signal,\n );\n // a second loop over the same iterator would split the data with the\n // first, or end straight away once the first has left\n let iterated = false;\n iterator[Symbol.asyncIterator] = () => {\n if (iterated) {\n throw new Error(\n 'A subscription can only be iterated once. Call subscribe() again for another loop.',\n );\n }\n iterated = true;\n return iterator;\n };\n return iterator;\n }\n return observable$.subscribe({\n next(envelope) {\n switch (envelope.result.type) {\n case 'state': {\n opts.onConnectionStateChange?.(envelope.result);\n break;\n }\n case 'started': {\n opts.onStarted?.({\n context: envelope.context,\n });\n break;\n }\n case 'stopped': {\n opts.onStopped?.();\n break;\n }\n case 'data':\n case undefined: {\n opts.onData?.(envelope.result.data);\n break;\n }\n }\n },\n error(err) {\n opts.onError?.(err);\n },\n complete() {\n opts.onComplete?.();\n },\n });\n }\n}\n","import type { AnyRouter } from '@trpc/server/unstable-core-do-not-import';\nimport type { CreateTRPCClientOptions } from './internals/TRPCUntypedClient';\nimport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\n\n/**\n * Creates a client that calls procedures by path string, without types.\n * Meant for libraries built on tRPC; apps should use `createTRPCClient`.\n */\nexport function createTRPCUntypedClient<TRouter extends AnyRouter>(\n opts: CreateTRPCClientOptions<TRouter>,\n): TRPCUntypedClient<TRouter> {\n return new TRPCUntypedClient(opts);\n}\n\nexport type {\n CreateTRPCClientOptions,\n TRPCRequestOptions,\n} from './internals/TRPCUntypedClient';\nexport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\n","/* oxlint-disable typescript/no-non-null-assertion */\nimport type { Unsubscribable } from '@trpc/server/observable';\nimport type {\n AnyProcedure,\n AnyRouter,\n inferAsyncIterableYield,\n inferClientTypes,\n inferProcedureErrorShape,\n inferProcedureInput,\n InferrableClientTypes,\n inferTransformedProcedureOutput,\n ProcedureType,\n RouterRecord,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n createFlatProxy,\n createRecursiveProxy,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type { CreateTRPCClientOptions } from './createTRPCUntypedClient';\nimport type {\n TRPCSubscriptionCallbacks,\n TRPCSubscriptionObserver,\n TRPCSubscriptionWithoutCallbacks,\n} from './internals/TRPCUntypedClient';\nimport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\nimport type { TRPCProcedureOptions } from './internals/types';\nimport type { TRPCTaggedPromise } from './safe';\nimport type { TRPCClientError } from './TRPCClientError';\n\n/**\n * The type of a client for a router.\n * @deprecated Use {@link TRPCClient} instead. This will be removed in v12.\n * @public\n **/\nexport type inferRouterClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;\n\n/**\n * The type of a client for a router.\n * @deprecated Use {@link TRPCClient} instead. This will be removed in v12.\n * @public\n **/\nexport type CreateTRPCClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;\n\nconst untypedClientSymbol = Symbol.for('trpc_untypedClient');\n\n/**\n * A typed client for a router, as `createTRPCClient` returns it. Each\n * procedure has `.query()`, `.mutate()` or `.subscribe()`.\n * @see https://trpc.io/docs/client/vanilla/infer-types\n * @public\n **/\nexport type TRPCClient<TRouter extends AnyRouter> = DecoratedProcedureRecord<\n {\n transformer: TRouter['_def']['_config']['$types']['transformer'];\n errorShape: TRouter['_def']['_config']['$types']['errorShape'];\n },\n TRouter['_def']['record']\n> & {\n [untypedClientSymbol]: TRPCUntypedClient<TRouter>;\n};\n\n/**\n * A procedure's types, as the client sees them.\n * @internal\n */\nexport type TRPCResolverDef = {\n input: any;\n output: any;\n transformer: boolean;\n errorShape: any;\n};\n\ntype coerceAsyncGeneratorToIterable<T> =\n T extends AsyncGenerator<infer $T, infer $Return, infer $Next>\n ? AsyncIterable<$T, $Return, $Next>\n : T;\n\n/**\n * The `.query()` or `.mutate()` of a procedure on the client.\n * @internal\n */\nexport type Resolver<TDef extends TRPCResolverDef> = (\n input: TDef['input'],\n opts?: TRPCProcedureOptions,\n) => TRPCTaggedPromise<\n coerceAsyncGeneratorToIterable<TDef['output']>,\n TDef['errorShape']\n>;\n\n/**\n * The `.subscribe()` of a subscription procedure on the client.\n * @internal\n */\nexport type SubscriptionResolver<TDef extends TRPCResolverDef> = {\n (\n input: TDef['input'],\n opts: TRPCSubscriptionCallbacks<TDef['output'], TRPCClientError<TDef>> &\n TRPCProcedureOptions,\n ): Unsubscribable;\n <\n TOpts extends TRPCProcedureOptions &\n Partial<TRPCSubscriptionObserver<TDef['output'], TRPCClientError<TDef>>> =\n TRPCProcedureOptions,\n >(\n input: TDef['input'],\n opts?: TRPCSubscriptionWithoutCallbacks<TOpts>,\n ): AsyncIterableIterator<inferAsyncIterableYield<TDef['output']>>;\n};\n\ntype DecorateProcedure<\n TType extends ProcedureType,\n TDef extends TRPCResolverDef,\n> = TType extends 'query'\n ? {\n query: Resolver<TDef>;\n }\n : TType extends 'mutation'\n ? {\n mutate: Resolver<TDef>;\n }\n : TType extends 'subscription'\n ? {\n subscribe: SubscriptionResolver<TDef>;\n }\n : never;\n\n/**\n * @internal\n */\ntype DecoratedProcedureRecord<\n TRoot extends InferrableClientTypes,\n TRecord extends RouterRecord,\n> = {\n [TKey in keyof TRecord]: TRecord[TKey] extends infer $Value\n ? $Value extends AnyProcedure\n ? DecorateProcedure<\n $Value['_def']['type'],\n {\n input: inferProcedureInput<$Value>;\n output: inferTransformedProcedureOutput<\n inferClientTypes<TRoot>,\n $Value\n >;\n errorShape: inferProcedureErrorShape<TRoot, $Value>;\n transformer: inferClientTypes<TRoot>['transformer'];\n }\n >\n : $Value extends RouterRecord\n ? DecoratedProcedureRecord<TRoot, $Value>\n : never\n : never;\n};\n\nconst clientCallTypeMap: Record<\n keyof DecorateProcedure<any, any>,\n ProcedureType\n> = {\n query: 'query',\n mutate: 'mutation',\n subscribe: 'subscription',\n};\n\n/**\n * The procedure type of a client method: `query`, `mutate` or `subscribe`.\n * @internal\n */\nexport const clientCallTypeToProcedureType = (\n clientCallType: string,\n): ProcedureType => {\n return clientCallTypeMap[clientCallType as keyof typeof clientCallTypeMap];\n};\n\n/**\n * Wraps an untyped client in the typed proxy `createTRPCClient` returns.\n * @internal\n */\nexport function createTRPCClientProxy<TRouter extends AnyRouter>(\n client: TRPCUntypedClient<TRouter>,\n): TRPCClient<TRouter> {\n const proxy = createRecursiveProxy<TRPCClient<TRouter>>(({ path, args }) => {\n const pathCopy = [...path];\n const procedureType = clientCallTypeToProcedureType(pathCopy.pop()!);\n\n const fullPath = pathCopy.join('.');\n\n return (client[procedureType] as any)(fullPath, ...(args as any));\n });\n return createFlatProxy<TRPCClient<TRouter>>((key) => {\n if (key === untypedClientSymbol) {\n return client;\n }\n return proxy[key];\n });\n}\n\n/**\n * Creates a typed client for a router. Pass the router's type, and the\n * links that send its calls.\n * @example\n * ```ts\n * const client = createTRPCClient<AppRouter>({\n * links: [httpBatchLink({ url: 'http://localhost:3000/trpc' })],\n * });\n * const post = await client.post.byId.query({ id: '1' });\n * ```\n * @see https://trpc.io/docs/client/vanilla/setup#3-initialize-the-trpc-client\n */\nexport function createTRPCClient<TRouter extends AnyRouter>(\n opts: CreateTRPCClientOptions<TRouter>,\n): TRPCClient<TRouter> {\n const client = new TRPCUntypedClient(opts);\n const proxy = createTRPCClientProxy<TRouter>(client);\n return proxy;\n}\n\n/**\n * The untyped client behind a typed client, which calls procedures by\n * path string.\n * @internal\n */\nexport function getUntypedClient<TRouter extends AnyRouter>(\n client: TRPCClient<TRouter>,\n): TRPCUntypedClient<TRouter> {\n return client[untypedClientSymbol];\n}\n","import type { AnyRouter, ProcedureType } from '@trpc/server';\nimport { observable } from '@trpc/server/observable';\nimport type { TRPCErrorShape, TRPCResponse } from '@trpc/server/rpc';\nimport type { AnyClientTypes } from '@trpc/server/unstable-core-do-not-import';\nimport { jsonlStreamConsumer } from '@trpc/server/unstable-core-do-not-import';\nimport type { BatchLoader } from '../internals/dataLoader';\nimport { dataLoader } from '../internals/dataLoader';\nimport {\n allAbortSignals,\n raceAbortSignals,\n raceAbortSignalsWithCleanup,\n} from '../internals/signals';\nimport type { NonEmptyArray } from '../internals/types';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type { HTTPBatchLinkOptions } from './HTTPBatchLinkOptions';\nimport type { HTTPResult } from './internals/httpUtils';\nimport {\n fetchHTTPResponse,\n getBody,\n getUrl,\n resolveHTTPLinkOptions,\n} from './internals/httpUtils';\nimport type { Operation, TRPCLink } from './types';\n\n/**\n * Options for {@link httpBatchStreamLink}. Takes the same options as\n * `httpBatchLink`, plus `streamHeader`.\n *\n * @see https://trpc.io/docs/client/links/httpBatchStreamLink#options\n */\nexport type HTTPBatchStreamLinkOptions<TRoot extends AnyClientTypes> =\n HTTPBatchLinkOptions<TRoot> & {\n /**\n * Which header to use to signal the server that the client wants a streaming response.\n * - `'trpc-accept'` (default): sends `trpc-accept: application/jsonl` header\n * - `'accept'`: sends `Accept: application/jsonl` header, which can avoid CORS preflight for cross-origin streaming queries. Be aware that `application/jsonl` is not an official MIME type and so this is not completely spec-compliant - you should test that your infrastructure supports this value.\n * @default 'trpc-accept'\n */\n streamHeader?: 'trpc-accept' | 'accept';\n };\n\ntype BatchStreamOperation = Operation & {\n releaseSignal: () => void;\n /** Aborts the op's signal once its response has nothing left to stream */\n settle: () => void;\n};\n\n/**\n * A terminating link that batches calls like `httpBatchLink`, but streams each\n * response back as soon as it is ready.\n *\n * @see https://trpc.io/docs/client/links/httpBatchStreamLink\n */\nexport function httpBatchStreamLink<TRouter extends AnyRouter>(\n opts: HTTPBatchStreamLinkOptions<TRouter['_def']['_config']['$types']>,\n): TRPCLink<TRouter> {\n const resolvedOpts = resolveHTTPLinkOptions(opts);\n const maxURLLength = opts.maxURLLength ?? Infinity;\n const maxItems = opts.maxItems ?? Infinity;\n\n return () => {\n const batchLoader = (\n type: ProcedureType,\n ): BatchLoader<BatchStreamOperation, HTTPResult> => {\n return {\n validate(batchOps) {\n if (maxURLLength === Infinity && maxItems === Infinity) {\n // escape hatch for quick calcs\n return true;\n }\n if (batchOps.length > maxItems) {\n return false;\n }\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n\n const url = getUrl({\n ...resolvedOpts,\n type,\n path,\n inputs,\n signal: null,\n });\n\n return url.length <= maxURLLength;\n },\n async fetch(batchOps) {\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n\n const batchSignals = allAbortSignals(\n ...batchOps.map((op) => op.signal),\n );\n const abortController = new AbortController();\n abortController.signal.addEventListener(\n 'abort',\n () => {\n for (const op of batchOps) {\n op.releaseSignal();\n }\n },\n { once: true },\n );\n\n const responsePromise = fetchHTTPResponse({\n ...resolvedOpts,\n signal: raceAbortSignals(batchSignals, abortController.signal),\n type,\n contentTypeHeader: 'application/json',\n trpcAcceptHeader: 'application/jsonl',\n trpcAcceptHeaderKey: opts.streamHeader ?? 'trpc-accept',\n getUrl,\n getBody,\n inputs,\n path,\n headers() {\n if (!opts.headers) {\n return {};\n }\n if (typeof opts.headers === 'function') {\n return opts.headers({\n opList: batchOps as NonEmptyArray<BatchStreamOperation>,\n });\n }\n return opts.headers;\n },\n });\n\n const res = await responsePromise;\n\n if (!res.ok) {\n // Server returned a non-2xx response (e.g. batching disabled).\n // The body is plain JSON, not JSONL, so parse it directly and\n // propagate the same error to every operation in the batch.\n const json = (await res.json()) as TRPCResponse;\n if ('error' in json) {\n json.error = resolvedOpts.transformer.output.deserialize(\n json.error,\n );\n }\n\n return batchOps.map((): Promise<HTTPResult> =>\n Promise.resolve({\n json,\n meta: {\n response: res,\n },\n }),\n );\n }\n\n const [head] = await jsonlStreamConsumer<\n Record<string, Promise<any>>\n >({\n // oxlint-disable-next-line typescript/no-non-null-assertion\n from: res.body!,\n deserialize: (data) =>\n resolvedOpts.transformer.output.deserialize(data),\n onError: () => abortController.abort(),\n // An op with nothing left to stream must not hold the batch open.\n onSettled: (settled) => batchOps[Number(settled.key)]?.settle(),\n formatError(opts) {\n const error = opts.error as TRPCErrorShape;\n return TRPCClientError.from({\n error,\n });\n },\n abortController,\n });\n const promises = Object.keys(batchOps).map(\n async (key): Promise<HTTPResult> => {\n let json: TRPCResponse = await Promise.resolve(head[key]);\n\n if ('result' in json) {\n /**\n * Not very pretty, but we need to unwrap nested data as promises\n * Our stream producer will only resolve top-level async values or async values that are directly nested in another async value\n */\n const result = await Promise.resolve(json.result);\n json = {\n result: {\n data: await Promise.resolve(result.data),\n },\n };\n }\n\n return {\n json,\n meta: {\n response: res,\n },\n };\n },\n );\n return promises;\n },\n };\n };\n\n const query = dataLoader(batchLoader('query'));\n const mutation = dataLoader(batchLoader('mutation'));\n\n const loaders = { query, mutation };\n return ({ op }) => {\n return observable((observer) => {\n /* istanbul ignore if -- @preserve */\n if (op.type === 'subscription') {\n throw new Error(\n 'Subscriptions are unsupported by `httpBatchStreamLink` - use `httpSubscriptionLink` or `wsLink`',\n );\n }\n const ac = new AbortController();\n const loader = loaders[op.type];\n const { signal, cleanup } = raceAbortSignalsWithCleanup(\n op.signal,\n ac.signal,\n );\n const promise = loader.load({\n ...op,\n signal,\n releaseSignal: cleanup,\n settle: () => ac.abort(),\n });\n\n let isDone = false;\n let _res = undefined as HTTPResult | undefined;\n promise\n .then((res) => {\n isDone = true;\n _res = res;\n if ('error' in res.json) {\n // A failed op has nothing left to stream, so it must not hold the batch open.\n ac.abort();\n observer.error(\n TRPCClientError.from(res.json, {\n meta: res.meta,\n }),\n );\n return;\n } else if ('result' in res.json) {\n observer.next({\n context: res.meta,\n result: res.json.result,\n });\n observer.complete();\n return;\n }\n\n observer.complete();\n })\n .catch((err) => {\n isDone = true;\n ac.abort();\n observer.error(\n TRPCClientError.from(err, {\n meta: _res?.meta,\n }),\n );\n });\n\n return () => {\n if (!isDone) {\n ac.abort();\n }\n };\n });\n };\n };\n}\n\n/**\n * @deprecated Use {@link httpBatchStreamLink} instead.\n */\nexport const unstable_httpBatchStreamLink = httpBatchStreamLink;\n","import { isObject } from '@trpc/server/unstable-core-do-not-import';\n\nexport function inputWithTrackedEventId(\n input: unknown,\n lastEventId: string | undefined,\n) {\n if (!lastEventId) {\n return input;\n }\n // the server's `isObject` excludes arrays, so spreading one here would corrupt it\n if (input != null && !isObject(input)) {\n return input;\n }\n return {\n ...(input ?? {}),\n lastEventId,\n };\n}\n","import { behaviorSubject, observable } from '@trpc/server/observable';\nimport type { TRPCErrorShape, TRPCResult } from '@trpc/server/rpc';\nimport type {\n AnyClientTypes,\n EventSourceLike,\n inferClientTypes,\n InferrableClientTypes,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n resolvePathSeparator,\n retryableRpcCodes,\n run,\n sseStreamConsumer,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport { raceAbortSignals } from '../internals/signals';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type { TRPCConnectionState } from '../unstable-internals';\nimport { getTransformer, type TransformerOptions } from '../unstable-internals';\nimport { getUrl, type HTTPLinkBaseOptions } from './internals/httpUtils';\nimport {\n resultOf,\n type UrlOptionsWithConnectionParams,\n} from './internals/urlWithConnectionParams';\nimport type { Operation, TRPCLink } from './types';\n\nasync function urlWithConnectionParams(\n opts: UrlOptionsWithConnectionParams,\n): Promise<string> {\n let url = await resultOf(opts.url);\n if (opts.connectionParams) {\n const params = await resultOf(opts.connectionParams);\n\n const prefix = url.includes('?') ? '&' : '?';\n url +=\n prefix + 'connectionParams=' + encodeURIComponent(JSON.stringify(params));\n }\n\n return url;\n}\n\n/**\n * @see https://trpc.io/docs/client/links/httpSubscriptionLink#httpsubscriptionlink-options\n */\ntype HTTPSubscriptionLinkOptions<\n TRoot extends AnyClientTypes,\n TEventSource extends EventSourceLike.AnyConstructor = typeof EventSource,\n> = {\n /**\n * The `EventSource` class to use, for runtimes that don't have one.\n * @see https://trpc.io/docs/client/links/httpSubscriptionLink#custom-headers-through-ponyfill\n */\n EventSource?: TEventSource;\n /**\n * Options passed to the `EventSource`, or a function that returns them for\n * each subscription.\n */\n eventSourceOptions?:\n | EventSourceLike.InitDictOf<TEventSource>\n | ((opts: {\n op: Operation;\n }) =>\n | EventSourceLike.InitDictOf<TEventSource>\n | Promise<EventSourceLike.InitDictOf<TEventSource>>);\n} & Pick<HTTPLinkBaseOptions<TRoot>, 'pathSeparator'> &\n TransformerOptions<TRoot> &\n UrlOptionsWithConnectionParams;\n\n/**\n * A terminating link that runs subscriptions over Server-Sent Events.\n *\n * @see https://trpc.io/docs/client/links/httpSubscriptionLink\n */\nexport function httpSubscriptionLink<\n TInferrable extends InferrableClientTypes,\n TEventSource extends EventSourceLike.AnyConstructor,\n>(\n opts: HTTPSubscriptionLinkOptions<\n inferClientTypes<TInferrable>,\n TEventSource\n >,\n): TRPCLink<TInferrable> {\n const transformer = getTransformer(opts.transformer);\n const pathSeparator = resolvePathSeparator(opts.pathSeparator);\n\n return () => {\n return ({ op }) => {\n return observable((observer) => {\n const { type, path, input } = op;\n\n /* istanbul ignore if -- @preserve */\n if (type !== 'subscription') {\n throw new Error('httpSubscriptionLink only supports subscriptions');\n }\n\n let lastEventId: string | undefined = undefined;\n const ac = new AbortController();\n const signal = raceAbortSignals(op.signal, ac.signal);\n const eventSourceStream = sseStreamConsumer<{\n EventSource: TEventSource;\n data: Partial<{\n id?: string;\n data: unknown;\n }>;\n error: TRPCErrorShape;\n }>({\n url: async () =>\n getUrl({\n transformer,\n url: await urlWithConnectionParams(opts),\n input: inputWithTrackedEventId(input, lastEventId),\n path,\n pathSeparator,\n type,\n signal: null,\n }),\n init: () => resultOf(opts.eventSourceOptions, { op }),\n signal,\n deserialize: (data) => transformer.output.deserialize(data),\n EventSource: opts.EventSource ?? (globalThis.EventSource as never),\n });\n\n const connectionState = behaviorSubject<\n TRPCConnectionState<TRPCClientError<any>>\n >({\n type: 'state',\n state: 'connecting',\n error: null,\n });\n\n const connectionSub = connectionState.subscribe({\n next(state) {\n observer.next({\n result: state,\n });\n },\n });\n run(async () => {\n for await (const chunk of eventSourceStream) {\n switch (chunk.type) {\n case 'ping':\n // do nothing\n break;\n case 'data':\n const chunkData = chunk.data;\n\n let result: TRPCResult<unknown>;\n if (chunkData.id) {\n // if the `tracked()`-helper is used, we always have an `id` field\n lastEventId = chunkData.id;\n result = {\n id: chunkData.id,\n data: chunkData,\n };\n } else {\n result = {\n data: chunkData.data,\n };\n }\n\n observer.next({\n result,\n context: {\n eventSource: chunk.eventSource,\n },\n });\n break;\n case 'connected': {\n observer.next({\n result: {\n type: 'started',\n },\n context: {\n eventSource: chunk.eventSource,\n },\n });\n connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n });\n break;\n }\n case 'serialized-error': {\n const error = TRPCClientError.from({ error: chunk.error });\n\n if (retryableRpcCodes.includes(chunk.error.code)) {\n //\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error,\n });\n break;\n }\n //\n // non-retryable error, cancel the subscription\n throw error;\n }\n case 'connecting': {\n const lastState = connectionState.get();\n\n const error = chunk.event && TRPCClientError.from(chunk.event);\n if (!error && lastState.state === 'connecting') {\n break;\n }\n\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error,\n });\n break;\n }\n case 'timeout': {\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error: new TRPCClientError(\n `Timeout of ${chunk.ms}ms reached while waiting for a response`,\n ),\n });\n }\n }\n }\n observer.next({\n result: {\n type: 'stopped',\n },\n });\n connectionState.next({\n type: 'state',\n state: 'idle',\n error: null,\n });\n observer.complete();\n }).catch((error) => {\n observer.error(TRPCClientError.from(error));\n });\n\n return () => {\n observer.complete();\n ac.abort();\n connectionSub.unsubscribe();\n };\n });\n };\n };\n}\n\n/**\n * @deprecated Use {@link httpSubscriptionLink} instead.\n */\nexport const unstable_httpSubscriptionLink = httpSubscriptionLink;\n","/* istanbul ignore file -- @preserve */\n// We're not actually exporting this link\nimport type { Unsubscribable } from '@trpc/server/observable';\nimport { observable } from '@trpc/server/observable';\nimport type { InferrableClientTypes } from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport type { TRPCClientError } from '../TRPCClientError';\nimport type { Operation, TRPCLink } from './types';\n\ninterface RetryLinkOptions<TInferrable extends InferrableClientTypes> {\n /**\n * The retry function\n */\n retry: (opts: RetryFnOptions<TInferrable>) => boolean;\n /**\n * The delay between retries in ms (defaults to 0)\n */\n retryDelayMs?: (attempt: number) => number;\n}\n\ninterface RetryFnOptions<TInferrable extends InferrableClientTypes> {\n /**\n * The operation that failed\n */\n op: Operation;\n /**\n * The error that occurred\n */\n error: TRPCClientError<TInferrable>;\n /**\n * The number of attempts that have been made (including the first call)\n */\n attempts: number;\n}\n\n/**\n * Retries failed operations. Subscriptions resume from the last tracked event\n * id.\n *\n * @see https://trpc.io/docs/client/links/retryLink\n */\nexport function retryLink<TInferrable extends InferrableClientTypes>(\n opts: RetryLinkOptions<TInferrable>,\n): TRPCLink<TInferrable> {\n // initialized config\n return () => {\n // initialized in app\n return (callOpts) => {\n // initialized for request\n return observable((observer) => {\n let next$: Unsubscribable;\n let currentAttempt = 0;\n let disposed = false;\n let callNextTimeout: ReturnType<typeof setTimeout> | undefined =\n undefined;\n\n let lastEventId: string | undefined = undefined;\n\n attempt(1);\n\n function opWithLastEventId() {\n const op = callOpts.op;\n if (!lastEventId) {\n return op;\n }\n\n return {\n ...op,\n input: inputWithTrackedEventId(op.input, lastEventId),\n };\n }\n\n function attempt(attempts: number) {\n if (disposed) {\n return;\n }\n currentAttempt = attempts;\n const op = opWithLastEventId();\n\n const subscription = callOpts.next(op).subscribe({\n error(error) {\n const shouldRetry = opts.retry({\n op,\n attempts,\n error,\n });\n if (disposed) {\n return;\n }\n if (!shouldRetry) {\n observer.error(error);\n return;\n }\n const delayMs = opts.retryDelayMs?.(attempts) ?? 0;\n if (disposed) {\n return;\n }\n\n if (delayMs <= 0) {\n attempt(attempts + 1);\n return;\n }\n callNextTimeout = setTimeout(\n () => attempt(attempts + 1),\n delayMs,\n );\n },\n next(envelope) {\n //\n if (\n (!envelope.result.type || envelope.result.type === 'data') &&\n envelope.result.id\n ) {\n //\n lastEventId = envelope.result.id;\n }\n\n observer.next(envelope);\n },\n complete() {\n observer.complete();\n },\n });\n\n // A synchronous error may have already subscribed the next attempt.\n if (disposed) {\n subscription.unsubscribe();\n } else if (currentAttempt === attempts) {\n next$ = subscription;\n }\n }\n return () => {\n disposed = true;\n next$.unsubscribe();\n clearTimeout(callNextTimeout);\n };\n });\n };\n };\n}\n","import {\n getTRPCErrorFromUnknown,\n getTRPCErrorShape,\n isTrackedEnvelope,\n} from '@trpc/server';\nimport {\n behaviorSubject,\n isObservable,\n observable,\n observableToAsyncIterable,\n} from '@trpc/server/observable';\nimport { TRPC_ERROR_CODES_BY_KEY, type TRPCResult } from '@trpc/server/rpc';\nimport {\n callProcedure,\n isAbortError,\n isAsyncIterable,\n iteratorResource,\n makeResource,\n retryableRpcCodes,\n run,\n type AnyRouter,\n type ErrorHandlerOptions,\n type inferClientTypes,\n type inferRouterContext,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport {\n abortSignalToPromise,\n raceAbortSignals,\n throwIfAborted,\n} from '../internals/signals';\nimport { getTransformer } from '../internals/transformer';\nimport type { TransformerOptions } from '../internals/transformer';\nimport { isTRPCClientError, TRPCClientError } from '../TRPCClientError';\nimport type { TRPCConnectionState } from './internals/subscriptions';\nimport type { TRPCLink } from './types';\n\n/**\n * Passed to {@link LocalLinkOptions.createContext}.\n */\nexport type LocalLinkCreateContextOptions = {\n /**\n * What tRPC knows about the call, like the `info` that adapters pass to\n * their `createContext`.\n */\n info: {\n /**\n * Aborts when the call is cancelled or unsubscribed. Pass it on to work\n * that creating the context starts, such as `fetch()` calls.\n */\n signal: AbortSignal;\n };\n};\n\n/**\n * Options for {@link localLink}.\n *\n * @see https://trpc.io/docs/client/links/localLink#options\n */\nexport type LocalLinkOptions<TRouter extends AnyRouter> = {\n /**\n * The router to call.\n * @see https://trpc.io/docs/client/links/localLink#router\n */\n router: TRouter;\n /**\n * Creates the context for each call. `info.signal` aborts when the call\n * is cancelled.\n * @see https://trpc.io/docs/client/links/localLink#createcontext\n */\n createContext: (\n opts: LocalLinkCreateContextOptions,\n ) => Promise<inferRouterContext<TRouter>>;\n /**\n * Called when a procedure throws.\n * @see https://trpc.io/docs/client/links/localLink#onerror\n */\n onError?: (opts: ErrorHandlerOptions<inferRouterContext<TRouter>>) => void;\n} & TransformerOptions<inferClientTypes<TRouter>>;\n\n/**\n * A terminating link that calls procedures on a router in the same process,\n * without HTTP.\n *\n * @see https://trpc.io/docs/client/links/localLink\n */\nexport function localLink<TRouter extends AnyRouter>(\n opts: LocalLinkOptions<TRouter>,\n): TRPCLink<TRouter> {\n const transformer = getTransformer(opts.transformer);\n\n const transformChunk = (chunk: unknown) => {\n if (opts.transformer) {\n // assume transformer will do the right thing\n return chunk;\n }\n // Special case for undefined, because `JSON.stringify(undefined)` throws\n if (chunk === undefined) {\n return chunk;\n }\n const serialized = JSON.stringify(transformer.input.serialize(chunk));\n const deserialized = JSON.parse(transformer.output.deserialize(serialized));\n return deserialized;\n };\n\n return () =>\n ({ op }) =>\n observable((observer) => {\n let ctx: inferRouterContext<TRouter> | undefined = undefined;\n const ac = new AbortController();\n\n const signal = raceAbortSignals(op.signal, ac.signal);\n const signalPromise = abortSignalToPromise(signal);\n\n signalPromise.catch(() => {\n // prevent unhandled rejection\n });\n\n let input = op.input;\n async function runProcedure(newInput: unknown): Promise<unknown> {\n input = newInput;\n\n // don't start work for a call that was cancelled before it ran\n throwIfAborted(signal);\n ctx = await opts.createContext({ info: { signal } });\n throwIfAborted(signal);\n\n return callProcedure({\n router: opts.router,\n path: op.path,\n getRawInput: async () => newInput,\n ctx,\n type: op.type,\n signal,\n batchIndex: 0,\n });\n }\n\n function onErrorCallback(cause: unknown) {\n if (isAbortError(cause)) {\n return;\n }\n opts.onError?.({\n error: getTRPCErrorFromUnknown(cause),\n type: op.type,\n path: op.path,\n input,\n ctx,\n });\n }\n\n function coerceToTRPCClientError(cause: unknown) {\n if (isTRPCClientError<TRouter>(cause)) {\n return cause;\n }\n const error = getTRPCErrorFromUnknown(cause);\n\n const shape = getTRPCErrorShape({\n config: opts.router._def._config,\n ctx,\n error,\n input,\n path: op.path,\n type: op.type,\n });\n return TRPCClientError.from(\n { error: transformChunk(shape) },\n { cause: cause instanceof Error ? cause : undefined },\n );\n }\n\n run(async () => {\n switch (op.type) {\n case 'query':\n case 'mutation': {\n const result = await Promise.race([\n runProcedure(op.input),\n signalPromise,\n ]);\n if (!isAsyncIterable(result)) {\n observer.next({\n result: { data: transformChunk(result) },\n });\n observer.complete();\n break;\n }\n\n observer.next({\n result: {\n data: (async function* () {\n await using iterator = iteratorResource(result);\n using _finally = makeResource({}, () => {\n observer.complete();\n });\n try {\n while (true) {\n const res = await Promise.race([\n iterator.next(),\n signalPromise,\n ]);\n if (res.done) {\n return transformChunk(res.value);\n }\n yield transformChunk(res.value);\n }\n } catch (cause) {\n onErrorCallback(cause);\n throw coerceToTRPCClientError(cause);\n }\n })(),\n },\n });\n break;\n }\n case 'subscription': {\n const connectionState = behaviorSubject<\n TRPCConnectionState<TRPCClientError<any>>\n >({\n type: 'state',\n state: 'connecting',\n error: null,\n });\n\n const connectionSub = connectionState.subscribe({\n next(state) {\n observer.next({\n result: state,\n });\n },\n });\n let lastEventId: string | undefined = undefined;\n\n using _finally = makeResource({}, async () => {\n connectionState.next({\n type: 'state',\n state: 'idle',\n error: null,\n });\n connectionSub.unsubscribe();\n });\n\n // returning from here means the stream ended, so this completes\n // below - a throw is left to the `.catch()`, which needs the\n // observer to still be open by the time it runs\n await run(async () => {\n while (true) {\n const procedureResult = await runProcedure(\n inputWithTrackedEventId(op.input, lastEventId),\n );\n const result = isObservable(procedureResult)\n ? observableToAsyncIterable(procedureResult, signal)\n : procedureResult;\n if (!isAsyncIterable(result)) {\n throw new Error('Expected an async iterable');\n }\n await using iterator = iteratorResource(result);\n\n observer.next({\n result: {\n type: 'started',\n },\n });\n connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n });\n\n // Use a while loop to handle errors and reconnects\n while (true) {\n let res;\n try {\n res = await Promise.race([\n iterator.next(),\n signalPromise,\n ]);\n } catch (cause) {\n if (isAbortError(cause)) {\n return;\n }\n const error = getTRPCErrorFromUnknown(cause);\n\n if (\n !retryableRpcCodes.includes(\n TRPC_ERROR_CODES_BY_KEY[error.code],\n )\n ) {\n throw coerceToTRPCClientError(error);\n }\n\n onErrorCallback(error);\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error: coerceToTRPCClientError(error),\n });\n\n break;\n }\n\n if (res.done) {\n return;\n }\n let chunk: TRPCResult<unknown>;\n if (isTrackedEnvelope(res.value)) {\n lastEventId = res.value[0];\n\n chunk = {\n id: res.value[0],\n data: {\n id: res.value[0],\n data: res.value[1],\n },\n };\n } else {\n chunk = {\n data: res.value,\n };\n }\n\n observer.next({\n result: {\n ...chunk,\n data: transformChunk(chunk.data),\n },\n });\n }\n }\n });\n\n observer.complete();\n break;\n }\n }\n }).catch((cause) => {\n onErrorCallback(cause);\n observer.error(coerceToTRPCClientError(cause));\n });\n\n return () => {\n ac.abort();\n };\n });\n}\n\n/**\n * @deprecated Use {@link localLink} instead.\n * @function\n */\nexport const unstable_localLink = localLink;\n\n/**\n * @deprecated Use {@link localLink} instead. This alias will be removed in a\n * future major release.\n */\nexport const experimental_localLink = localLink;\n","import type { TRPCClientError } from './TRPCClientError';\n\n/**\n * @internal\n */\nexport declare const errorShapeTag: unique symbol;\n\n/**\n * The promise a client's `.query()` or `.mutate()` returns, tagged with\n * the procedure's error shape for `safe()`.\n */\nexport type TRPCTaggedPromise<TData, TErrorShape> = Promise<TData> & {\n readonly [errorShapeTag]: TErrorShape;\n};\n\n/**\n * @internal\n */\nexport type inferSafeError<TErrorShape> = TRPCClientError<{\n errorShape: TErrorShape;\n transformer: boolean;\n}>;\n\n/**\n * What `safe()` resolves to: `[data, undefined]` or `[undefined, error]`.\n * @see https://trpc.io/docs/client/vanilla/error-handling#errors-as-values-with-safe\n */\nexport type SafeResult<TData, TErrorShape> =\n | readonly [data: TData, error: undefined]\n | readonly [data: undefined, error: inferSafeError<TErrorShape>];\n\n/**\n * Awaits a client `.query()` or `.mutate()` call without throwing, and\n * returns a `[data, error]` pair typed with the procedure's error shape.\n *\n * @example\n * ```ts\n * const [post, error] = await safe(client.post.byId.query({ id }));\n * if (error) {\n * console.error(error);\n * }\n *\n * const id = post.id;\n * ```\n * @see https://trpc.io/docs/client/vanilla/error-handling#errors-as-values-with-safe\n */\nexport async function safe<TData, TErrorShape>(\n promise: TRPCTaggedPromise<TData, TErrorShape>,\n): Promise<SafeResult<TData, TErrorShape>> {\n try {\n return [await promise, undefined];\n } catch (cause) {\n return [undefined, cause as inferSafeError<TErrorShape>];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAsFA,MAAM,eAA8B;CAClC;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAoBA,IAAa,oBAAb,MAA0E;CAKxE,YAAY,MAA4C;EAJvC,gBAAA,MAAA,SAAA,KAAA,CAAA;EACD,gBAAA,MAAA,WAAA,KAAA,CAAA;EACR,gBAAA,MAAA,aAAA,KAAA,CAAA;EAGN,KAAK,YAAY;EAEjB,KAAK,UAAU,CAAC;EAGhB,KAAK,QAAQ,KAAK,MAAM,KAAK,SAAS,KAAK,KAAK,OAAO,CAAC;CAC1D;CAEA,SAAsD,MAMnD;;EASD,OARe,YAAwC;GACrD,OAAO,KAAK;GACZ,IAAA,eAAA,eAAA,CAAA,GACK,IAAA,GAAA,CAAA,GAAA;IACH,UAAA,gBAAS,KAAK,aAAA,QAAA,kBAAA,KAAA,IAAA,gBAAW,CAAC;IAC1B,IAAI,EAAE,KAAK;GACb,CAAA;EACF,CACY,CAAC,CAAC,KAAK,MAAM,CAAC;CAC5B;CAEA,MAAc,iBAAsD,MAM/C;EACnB,IAAI;GACF,MAAM,OAAO,KAAK,SAA0B,IAAI;GAKhD,QADc,MADS,oBAA4B,IAAI,EAAA,CAChC,OAAe;EAExC,SAAS,KAAK;GACZ,MAAM,gBAAgB,KAAK,GAAY;EACzC;CACF;;CAEA,MAAa,MAAc,OAAiB,MAA2B;EACrE,OAAO,KAAK,iBAAmC;GAC7C,MAAM;GACN;GACA;GACA,SAAA,SAAA,QAAA,SAAA,KAAA,IAAA,KAAA,IAAS,KAAM;GACf,QAAA,SAAA,QAAA,SAAA,KAAA,IAAA,KAAA,IAAQ,KAAM;EAChB,CAAC;CACH;;CAEA,SAAgB,MAAc,OAAiB,MAA2B;EACxE,OAAO,KAAK,iBAA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AK;SACtC,CAAC;SAED;QACF;QAEA,IAAI,IAAI,MACN;QAEF,IAAI;QACJ,IAAI,kBAAkB,IAAI,KAAK,GAAG;SAChC,cAAc,IAAI,MAAM;SAExB,QAAQ;UACN,IAAI,IAAI,MAAM;UACd,MAAM;WACJ,IAAI,IAAI,MAAM;WACd,MAAM,IAAI,MAAM;UAClB;SACF;QACF,OACE,QAAQ,EACN,MAAM,IAAI,MACZ;QAGF,SAAS,KAAK,EACZ,QAAA,eAAA,eAAA,CAAA,GACK,KAAA,GAAA,CAAA,GAAA,EACH,MAAM,eAAe,MAAM,IAAI,EAAA,CACjC,EACF,CAAC;OACH;;;;;;KAEJ,CAAC;KAED,SAAS,SAAS;KAClB;;;;;;GAEJ;EACF,CAAC,CAAC,CAAC,OAAO,UAAU;GAClB,gBAAgB,KAAK;GACrB,SAAS,MAAM,wBAAwB,KAAK,CAAC;EAC/C,CAAC;EAED,aAAa;GACX,GAAG,MAAM;EACX;CACF,CAAC;AACP;;;;;AAMA,MAAa,qBAAqB;;;;;AAMlC,MAAa,yBAAyB;;;;;;;;;;;;;;;;;ACrTtC,eAAsB,KACpB,SACyC;CACzC,IAAI;EACF,OAAO,CAAC,MAAM,SAAS,KAAA,CAAS;CAClC,SAAS,OAAO;EACd,OAAO,CAAC,KAAA,GAAW,KAAoC;CACzD;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_wsLink = require("../../wsLink-
|
|
2
|
+
const require_wsLink = require("../../wsLink-vHwF4z7F.cjs");
|
|
3
3
|
exports.createWSClient = require_wsLink.createWSClient;
|
|
4
4
|
exports.jsonEncoder = require_wsLink.jsonEncoder;
|
|
5
5
|
exports.wsLink = require_wsLink.wsLink;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { n as createWSClient, i as jsonEncoder, t as wsLink } from "../../wsLink-
|
|
1
|
+
export { n as createWSClient, i as jsonEncoder, t as wsLink } from "../../wsLink-DSmHMirJ.mjs";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wsLink-CEooxn80.d.cts","names":[],"sources":["../src/links/wsLink/wsClient/encoder.ts","../src/links/internals/urlWithConnectionParams.ts","../src/links/wsLink/wsClient/options.ts","../src/links/wsLink/wsClient/wsClient.ts","../src/links/wsLink/createWsClient.ts","../src/links/wsLink/wsLink.ts"],"mappings":";;;;;;;;;;cAOa,aAAa;;;;KCWd,gBAAgB,KAAK,WAAW,IAAI,QAAQ;UAEvC;;;;EAIf,KAAK;;;;;;;EAQL,mBAAmB,gBAAgB;;;;;;;UCxBpB,+BAA+B;;;;EAI9C,mBAAmB;;;;;EAKnB,gBAAgB;;;;EAIhB;;;;EAIA,WAAW,MAAM;;;;EAIjB,WAAW;IAAU;;;;;EAIrB;;;;;IAKE;;;;;IAKA;;;;;EAKF;;;;IAIE;;;;;IAKA;;;;;IAKA;;;;;;EAMF,uBAAuB;;;;;;cCWZ;;;;WAIK,iBAAiB,gBAC/B,oBAAoB,gBAAgB;UAG9B;UACA;;;;;;;UASA;mBACS;;;;;;UAMT;mBACS;UACT;;;;;UAKA;mBACS;mBAIA;mBACA;mBACA;EAEjB,YAAY,MAAM;;;;;;UA4DV;UAUA;;;;;UAeM;;;;;EAiCD,SAAK;;;;;;;;;;;EAiDX,UACL,MAAM,MAAM,MAAM,OAAO,UACzB,aACA;IAEA,IAAI,KAAK;IACT,aAAa;IACb;wCACD,WAAA,iCAAA,gBAAA,iBAAA,gBAAA;;;;MAwEU;;;;;;;;;;;;;;;;;;UAaH;;;;UAIA;;;;;UAKA;;;;;;UAMA;;;;UAIA;;;;;;;;;;UAUA;;mBAES;;;;;;;;;UAUT;;;;;;;;UAsFA;;;;;;;UA8CA;UAiBA;UASA;;;;UAaA;;;;;;UAWA;;;;;UAaA;UA0BA;UA4MA;
|
|
1
|
+
{"version":3,"file":"wsLink-CEooxn80.d.cts","names":[],"sources":["../src/links/wsLink/wsClient/encoder.ts","../src/links/internals/urlWithConnectionParams.ts","../src/links/wsLink/wsClient/options.ts","../src/links/wsLink/wsClient/wsClient.ts","../src/links/wsLink/createWsClient.ts","../src/links/wsLink/wsLink.ts"],"mappings":";;;;;;;;;;cAOa,aAAa;;;;KCWd,gBAAgB,KAAK,WAAW,IAAI,QAAQ;UAEvC;;;;EAIf,KAAK;;;;;;;EAQL,mBAAmB,gBAAgB;;;;;;;UCxBpB,+BAA+B;;;;EAI9C,mBAAmB;;;;;EAKnB,gBAAgB;;;;EAIhB;;;;EAIA,WAAW,MAAM;;;;EAIjB,WAAW;IAAU;;;;;EAIrB;;;;;IAKE;;;;;IAKA;;;;;EAKF;;;;IAIE;;;;;IAKA;;;;;IAKA;;;;;;EAMF,uBAAuB;;;;;;cCWZ;;;;WAIK,iBAAiB,gBAC/B,oBAAoB,gBAAgB;UAG9B;UACA;;;;;;;UASA;mBACS;;;;;;UAMT;mBACS;UACT;;;;;UAKA;mBACS;mBAIA;mBACA;mBACA;EAEjB,YAAY,MAAM;;;;;;UA4DV;UAUA;;;;;UAeM;;;;;EAiCD,SAAK;;;;;;;;;;;EAiDX,UACL,MAAM,MAAM,MAAM,OAAO,UACzB,aACA;IAEA,IAAI,KAAK;IACT,aAAa;IACb;wCACD,WAAA,iCAAA,gBAAA,iBAAA,gBAAA;;;;MAwEU;;;;;;;;;;;;;;;;;;UAaH;;;;UAIA;;;;;UAKA;;;;;;UAMA;;;;UAIA;;;;;;;;;;UAUA;;mBAES;;;;;;;;;UAUT;;;;;;;;UAsFA;;;;;;;UA8CA;UAiBA;UASA;;;;UAaA;;;;;;UAWA;;;;;UAaA;UA0BA;UA4MA;UA+DA;;;;UASA;;;;;;UAqBA;;;;;UAWA;;;;;;;;iBC36BM,eAAe,MAAM,yBAAsB;;;;KAO/C,sBAAsB,kBAAkB;;;;;;KCIxC,qBAAqB,gBAAgB;;;;EAI/C,QAAQ;IACN,mBAAmB,iBAAiB;;;;;;iBAOxB,OAAO,gBAAgB,WACrC,MAAM,qBAAqB,WAC1B,SAAS"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wsLink-CnVTvoqf.d.mts","names":[],"sources":["../src/links/wsLink/wsClient/encoder.ts","../src/links/internals/urlWithConnectionParams.ts","../src/links/wsLink/wsClient/options.ts","../src/links/wsLink/wsClient/wsClient.ts","../src/links/wsLink/createWsClient.ts","../src/links/wsLink/wsLink.ts"],"mappings":";;;;;;;;;;cAOa,aAAa;;;;KCWd,gBAAgB,KAAK,WAAW,IAAI,QAAQ;UAEvC;;;;EAIf,KAAK;;;;;;;EAQL,mBAAmB,gBAAgB;;;;;;;UCxBpB,+BAA+B;;;;EAI9C,mBAAmB;;;;;EAKnB,gBAAgB;;;;EAIhB;;;;EAIA,WAAW,MAAM;;;;EAIjB,WAAW;IAAU;;;;;EAIrB;;;;;IAKE;;;;;IAKA;;;;;EAKF;;;;IAIE;;;;;IAKA;;;;;IAKA;;;;;;EAMF,uBAAuB;;;;;;cCWZ;;;;WAIK,iBAAiB,gBAC/B,oBAAoB,gBAAgB;UAG9B;UACA;;;;;;;UASA;mBACS;;;;;;UAMT;mBACS;UACT;;;;;UAKA;mBACS;mBAIA;mBACA;mBACA;EAEjB,YAAY,MAAM;;;;;;UA4DV;UAUA;;;;;UAeM;;;;;EAiCD,SAAK;;;;;;;;;;;EAiDX,UACL,MAAM,MAAM,MAAM,OAAO,UACzB,aACA;IAEA,IAAI,KAAK;IACT,aAAa;IACb;wCACD,WAAA,iCAAA,gBAAA,iBAAA,gBAAA;;;;MAwEU;;;;;;;;;;;;;;;;;;UAaH;;;;UAIA;;;;;UAKA;;;;;;UAMA;;;;UAIA;;;;;;;;;;UAUA;;mBAES;;;;;;;;;UAUT;;;;;;;;UAsFA;;;;;;;UA8CA;UAiBA;UASA;;;;UAaA;;;;;;UAWA;;;;;UAaA;UA0BA;UA4MA;
|
|
1
|
+
{"version":3,"file":"wsLink-CnVTvoqf.d.mts","names":[],"sources":["../src/links/wsLink/wsClient/encoder.ts","../src/links/internals/urlWithConnectionParams.ts","../src/links/wsLink/wsClient/options.ts","../src/links/wsLink/wsClient/wsClient.ts","../src/links/wsLink/createWsClient.ts","../src/links/wsLink/wsLink.ts"],"mappings":";;;;;;;;;;cAOa,aAAa;;;;KCWd,gBAAgB,KAAK,WAAW,IAAI,QAAQ;UAEvC;;;;EAIf,KAAK;;;;;;;EAQL,mBAAmB,gBAAgB;;;;;;;UCxBpB,+BAA+B;;;;EAI9C,mBAAmB;;;;;EAKnB,gBAAgB;;;;EAIhB;;;;EAIA,WAAW,MAAM;;;;EAIjB,WAAW;IAAU;;;;;EAIrB;;;;;IAKE;;;;;IAKA;;;;;EAKF;;;;IAIE;;;;;IAKA;;;;;IAKA;;;;;;EAMF,uBAAuB;;;;;;cCWZ;;;;WAIK,iBAAiB,gBAC/B,oBAAoB,gBAAgB;UAG9B;UACA;;;;;;;UASA;mBACS;;;;;;UAMT;mBACS;UACT;;;;;UAKA;mBACS;mBAIA;mBACA;mBACA;EAEjB,YAAY,MAAM;;;;;;UA4DV;UAUA;;;;;UAeM;;;;;EAiCD,SAAK;;;;;;;;;;;EAiDX,UACL,MAAM,MAAM,MAAM,OAAO,UACzB,aACA;IAEA,IAAI,KAAK;IACT,aAAa;IACb;wCACD,WAAA,iCAAA,gBAAA,iBAAA,gBAAA;;;;MAwEU;;;;;;;;;;;;;;;;;;UAaH;;;;UAIA;;;;;UAKA;;;;;;UAMA;;;;UAIA;;;;;;;;;;UAUA;;mBAES;;;;;;;;;UAUT;;;;;;;;UAsFA;;;;;;;UA8CA;UAiBA;UASA;;;;UAaA;;;;;;UAWA;;;;;UAaA;UA0BA;UA4MA;UA+DA;;;;UASA;;;;;;UAqBA;;;;;UAWA;;;;;;;;iBC36BM,eAAe,MAAM,yBAAsB;;;;KAO/C,sBAAsB,kBAAkB;;;;;;KCIxC,qBAAqB,gBAAgB;;;;EAI/C,QAAQ;IACN,mBAAmB,iBAAiB;;;;;;iBAOxB,OAAO,gBAAgB,WACrC,MAAM,qBAAqB,WAC1B,SAAS"}
|
|
@@ -1032,8 +1032,9 @@ var WsClient = class {
|
|
|
1032
1032
|
callUserCallback(() => request.callbacks.next(message));
|
|
1033
1033
|
let completed = true;
|
|
1034
1034
|
if ("result" in message && request.message.method === "subscription") {
|
|
1035
|
-
if (message.result.type === "data")
|
|
1036
|
-
|
|
1035
|
+
if (message.result.type === "data") {
|
|
1036
|
+
if (message.result.id !== void 0) request.message.params.lastEventId = message.result.id;
|
|
1037
|
+
} else if (message.result.type === "started") this.started.add(request.message);
|
|
1037
1038
|
if (message.result.type !== "stopped") completed = false;
|
|
1038
1039
|
}
|
|
1039
1040
|
if (completed) {
|
|
@@ -1138,4 +1139,4 @@ function wsLink(opts) {
|
|
|
1138
1139
|
}
|
|
1139
1140
|
export { jsonEncoder as i, createWSClient as n, resultOf as r, wsLink as t };
|
|
1140
1141
|
|
|
1141
|
-
//# sourceMappingURL=wsLink-
|
|
1142
|
+
//# sourceMappingURL=wsLink-DSmHMirJ.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wsLink-D054Z7rw.mjs","names":[],"sources":["../src/links/wsLink/wsClient/encoder.ts","../src/links/wsLink/wsClient/options.ts","../src/links/internals/urlWithConnectionParams.ts","../src/links/wsLink/wsClient/utils.ts","../src/links/wsLink/wsClient/requestManager.ts","../src/links/wsLink/wsClient/wsConnection.ts","../src/links/wsLink/wsClient/wsClient.ts","../src/links/wsLink/createWsClient.ts","../src/links/wsLink/wsLink.ts"],"sourcesContent":["import type { Encoder } from '@trpc/server/unstable-core-do-not-import';\n\nexport type { Encoder };\n\n/**\n * The default WebSocket encoder. Sends messages as JSON text frames.\n */\nexport const jsonEncoder: Encoder = {\n encode: (data) => JSON.stringify(data),\n decode: (data) => {\n if (typeof data !== 'string') {\n throw new Error(\n 'jsonEncoder received binary data. JSON uses text frames. ' +\n 'Use a binary encoder for binary data.',\n );\n }\n return JSON.parse(data);\n },\n};\n","import type { UrlOptionsWithConnectionParams } from '../../internals/urlWithConnectionParams';\nimport type { Encoder } from './encoder';\n\n/**\n * Options for `createWSClient`.\n *\n * @see https://trpc.io/docs/client/links/wsLink#wslink--createwsclient-options\n */\nexport interface WebSocketClientOptions extends UrlOptionsWithConnectionParams {\n /**\n * The `WebSocket` class to use, for runtimes that don't have one.\n */\n WebSocket?: typeof WebSocket;\n /**\n * The number of milliseconds before a reconnect is attempted.\n * @default {@link exponentialBackoff}\n */\n retryDelayMs?: (attemptIndex: number) => number;\n /**\n * Triggered when a WebSocket connection is established\n */\n onOpen?: () => void;\n /**\n * Triggered when a WebSocket connection encounters an error\n */\n onError?: (evt?: Event) => void;\n /**\n * Triggered when a WebSocket connection is closed\n */\n onClose?: (cause?: { code?: number }) => void;\n /**\n * Lazy mode will close the WebSocket automatically after a period of inactivity (no messages sent or received and no pending requests)\n */\n lazy?: {\n /**\n * Enable lazy mode\n * @default false\n */\n enabled: boolean;\n /**\n * Close the WebSocket after this many milliseconds\n * @default 0\n */\n closeMs: number;\n };\n /**\n * Send ping messages to the server and kill the connection if no pong message is returned\n */\n keepAlive?: {\n /**\n * @default false\n */\n enabled: boolean;\n /**\n * Send a ping message every this many milliseconds\n * @default 5_000\n */\n intervalMs?: number;\n /**\n * Close the WebSocket after this many milliseconds if the server does not respond\n * @default 1_000\n */\n pongTimeoutMs?: number;\n };\n /**\n * Encodes and decodes messages on the wire, for example as a binary format.\n * @default jsonEncoder\n */\n experimental_encoder?: Encoder;\n}\n\n/**\n * Default options for lazy WebSocket connections.\n * Determines whether the connection should be established lazily and defines the delay before closure.\n */\nexport type LazyOptions = Required<NonNullable<WebSocketClientOptions['lazy']>>;\nexport const lazyDefaults: LazyOptions = {\n enabled: false,\n closeMs: 0,\n};\n\n/**\n * Default options for the WebSocket keep-alive mechanism.\n * Configures whether keep-alive is enabled and specifies the timeout and interval for ping-pong messages.\n */\nexport type KeepAliveOptions = Required<\n NonNullable<WebSocketClientOptions['keepAlive']>\n>;\nexport const keepAliveDefaults: KeepAliveOptions = {\n enabled: false,\n pongTimeoutMs: 1_000,\n intervalMs: 5_000,\n};\n\n/**\n * Calculates a delay for exponential backoff based on the retry attempt index.\n * The delay starts at 0 for the first attempt and doubles for each subsequent attempt,\n * capped at 30 seconds.\n */\nexport const exponentialBackoff = (attemptIndex: number) => {\n return attemptIndex === 0 ? 0 : Math.min(1000 * 2 ** attemptIndex, 30000);\n};\n","import { type TRPCRequestInfo } from '@trpc/server/http';\n\n/**\n * Get the result of a value or function that returns a value\n * It also optionally accepts typesafe arguments for the function\n */\nexport const resultOf = <T, TArgs extends any[]>(\n value: T | ((...args: TArgs) => T),\n ...args: TArgs\n): T => {\n return typeof value === 'function'\n ? (value as (...args: TArgs) => T)(...args)\n : value;\n};\n\n/**\n * A value that can be wrapped in callback\n */\nexport type CallbackOrValue<T> = T | (() => T | Promise<T>);\n\nexport interface UrlOptionsWithConnectionParams {\n /**\n * The URL to connect to (can be a function that returns a URL)\n */\n url: CallbackOrValue<string>;\n\n /**\n * Connection params that are available in `createContext()`\n * - For `wsLink`/`wsClient`, these are sent as the first message\n * - For `httpSubscriptionLink`, these are serialized as part of the URL under the `connectionParams` query\n * @see https://trpc.io/docs/server/websockets#connectionParams\n */\n connectionParams?: CallbackOrValue<TRPCRequestInfo['connectionParams']>;\n}\n","import type {\n TRPCConnectionParamsMessage,\n TRPCRequestInfo,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type {\n CallbackOrValue,\n UrlOptionsWithConnectionParams,\n} from '../../internals/urlWithConnectionParams';\nimport { resultOf } from '../../internals/urlWithConnectionParams';\nimport type { Encoder } from './encoder';\n\nexport class TRPCWebSocketClosedError extends Error {\n constructor(opts: { message: string; cause?: unknown }) {\n super(opts.message, {\n cause: opts.cause,\n });\n this.name = 'TRPCWebSocketClosedError';\n Object.setPrototypeOf(this, TRPCWebSocketClosedError.prototype);\n }\n}\n\n/**\n * Calls a user callback, including `connectionState` subscribers. A throw\n * would skip the rest of the client's bookkeeping (e.g. end the reconnect\n * loop, or, with event-emitter based WebSockets such as `ws`, skip the other\n * listeners for that event), so it is rethrown asynchronously instead.\n */\nexport function callUserCallback(callback: () => void) {\n try {\n callback();\n } catch (error) {\n setTimeout(() => {\n throw error;\n });\n }\n}\n\n/**\n * Utility class for managing a timeout that can be started, stopped, and reset.\n * Useful for scenarios where the timeout duration is reset dynamically based on events.\n */\nexport class ResettableTimeout {\n private timeout: ReturnType<typeof setTimeout> | undefined;\n\n constructor(\n private readonly onTimeout: () => void,\n private readonly timeoutMs: number,\n ) {}\n\n /**\n * Resets the current timeout, restarting it with the same duration.\n * Does nothing if no timeout is active.\n */\n public reset() {\n if (!this.timeout) return;\n\n clearTimeout(this.timeout);\n this.timeout = setTimeout(this.onTimeout, this.timeoutMs);\n }\n\n public start() {\n clearTimeout(this.timeout);\n this.timeout = setTimeout(this.onTimeout, this.timeoutMs);\n }\n\n public stop() {\n clearTimeout(this.timeout);\n this.timeout = undefined;\n }\n}\n\n// Ponyfill for Promise.withResolvers https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers\nexport function withResolvers<T>() {\n let resolve: (value: T | PromiseLike<T>) => void;\n let reject: (reason?: any) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n // oxlint-disable-next-line typescript/no-non-null-assertion\n return { promise, resolve: resolve!, reject: reject! };\n}\n\n/**\n * Resolves a WebSocket URL and optionally appends connection parameters.\n *\n * If connectionParams are provided, appends 'connectionParams=1' query parameter.\n */\nexport async function prepareUrl(urlOptions: UrlOptionsWithConnectionParams) {\n const url = await resultOf(urlOptions.url);\n\n if (!urlOptions.connectionParams) return url;\n\n // append `?connectionParams=1` when connection params are used\n const prefix = url.includes('?') ? '&' : '?';\n const connectionParams = `${prefix}connectionParams=1`;\n\n return url + connectionParams;\n}\n\nexport async function buildConnectionMessage(\n connectionParams: CallbackOrValue<TRPCRequestInfo['connectionParams']>,\n encoder: Encoder,\n) {\n const message: TRPCConnectionParamsMessage = {\n method: 'connectionParams',\n data: await resultOf(connectionParams),\n };\n\n return encoder.encode(message);\n}\n","import type { AnyTRPCRouter, inferRouterError } from '@trpc/server';\nimport type { Observer } from '@trpc/server/observable';\nimport type {\n TRPCClientOutgoingMessage,\n TRPCResponseMessage,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type { TRPCClientError } from '../../../TRPCClientError';\nimport { withResolvers } from './utils';\n\nexport type TCallbacks = Observer<\n TRPCResponseMessage<unknown, inferRouterError<AnyTRPCRouter>>,\n TRPCClientError<AnyTRPCRouter>\n>;\n\ntype MessageId = string;\ntype MessageIdLike = string | number | null;\n\n/**\n * Represents a WebSocket request managed by the RequestManager.\n * Combines the network message, a utility promise (`end`) that mirrors the lifecycle\n * handled by `callbacks`, and a set of state monitoring callbacks.\n */\ninterface Request {\n message: TRPCClientOutgoingMessage;\n end: Promise<void>;\n callbacks: TCallbacks;\n /**\n * The socket the request was sent on, or `null` while it's outgoing.\n */\n ws: WebSocket | null;\n /**\n * The socket a subscription is moving to. `ws` keeps delivering until this\n * one confirms the subscription with `started`.\n */\n successor: WebSocket | null;\n /**\n * The event ids `ws` delivered while the subscription was moving, which\n * its successor replays and are dropped from it.\n */\n overlapEventIds: Set<string> | null;\n /**\n * The sockets a subscription moved from, each until everything it sent\n * before the stop has arrived. Their events without ids are still\n * delivered, since the new socket may have started listening after they\n * were sent.\n */\n movedFrom: Set<WebSocket>;\n}\n\n/**\n * Manages WebSocket requests, tracking their lifecycle and providing utility methods\n * for handling outgoing and pending requests.\n *\n * - **Outgoing requests**: Requests that are queued and waiting to be sent.\n * - **Pending requests**: Requests that have been sent and are in flight awaiting a response.\n * For subscriptions, multiple responses may be received until the subscription is closed.\n */\nexport class RequestManager {\n constructor(\n private readonly opts: {\n /**\n * Called when a deletion leaves no outgoing or pending request.\n */\n onIdle: () => void;\n },\n ) {}\n\n /**\n * Stores requests that are outgoing, meaning they are registered but not yet sent over the WebSocket.\n */\n private outgoingRequests = new Array<Request & { id: MessageId }>();\n\n /**\n * Stores requests that are pending (in flight), meaning they have been sent over the WebSocket\n * and are awaiting responses. For subscriptions, this includes requests\n * that may receive multiple responses.\n */\n private pendingRequests: Record<MessageId, Request> = {};\n\n /**\n * Subscriptions sent again under a new id, by their earlier id, while\n * sockets they moved from may still send events under that one.\n */\n private drainingRequests: Record<MessageId, Request> = {};\n\n /**\n * Registers a new request by adding it to the outgoing queue and setting up\n * callbacks for lifecycle events such as completion or error.\n *\n * @param message - The outgoing message to be sent.\n * @param callbacks - Callback functions to observe the request's state.\n * @returns A cleanup function to manually remove the request.\n */\n public register(message: TRPCClientOutgoingMessage, callbacks: TCallbacks) {\n const { promise: end, resolve } = withResolvers<void>();\n\n this.outgoingRequests.push({\n id: String(message.id),\n message,\n end,\n ws: null,\n successor: null,\n overlapEventIds: null,\n movedFrom: new Set(),\n callbacks: {\n next: callbacks.next,\n complete: () => {\n callbacks.complete();\n resolve();\n },\n error: (e) => {\n try {\n callbacks.error(e);\n } finally {\n resolve();\n }\n },\n },\n });\n\n return () => {\n this.delete(message);\n callbacks.complete();\n resolve();\n };\n }\n\n /**\n * Deletes a request from both the outgoing and pending collections, if it exists.\n *\n * Matches the message itself rather than its id: a retry reuses the id, and\n * registers its request before the failed request with that id is deleted.\n */\n public delete(message: TRPCClientOutgoingMessage) {\n const wasInFlight = this.hasRequestsInFlight();\n this.outgoingRequests = this.outgoingRequests.filter(\n (request) => request.message !== message,\n );\n const id = String(message.id);\n if (this.pendingRequests[id]?.message === message) {\n delete this.pendingRequests[id];\n }\n for (const [drainingId, request] of Object.entries(this.drainingRequests)) {\n if (request.message === message) {\n delete this.drainingRequests[drainingId];\n }\n }\n if (wasInFlight && !this.hasRequestsInFlight()) {\n this.opts.onIdle();\n }\n }\n\n /**\n * Moves all outgoing requests to the pending state and clears the outgoing queue.\n *\n * The caller is expected to handle the actual sending of the requests\n * (e.g., sending them over the network) after this method is called.\n *\n * @param ws - The socket the requests are sent on.\n * @returns The list of requests that were transitioned to the pending state.\n */\n public flush(ws: WebSocket | null = null) {\n const requests = this.outgoingRequests;\n this.outgoingRequests = [];\n\n for (const request of requests) {\n request.ws = ws;\n request.successor = null;\n request.movedFrom = new Set();\n this.pendingRequests[request.id] = request;\n }\n return requests;\n }\n\n /**\n * Moves a pending request back to the outgoing queue, to be sent again\n * with `id`. Its earlier id then matches only the sockets it's still\n * draining; see `getDrainingRequest()`.\n */\n public requeue(\n message: TRPCClientOutgoingMessage,\n id: TRPCClientOutgoingMessage['id'],\n ) {\n const earlierId = String(message.id);\n const request = this.pendingRequests[earlierId];\n if (request?.message !== message) return;\n\n delete this.pendingRequests[earlierId];\n if (request.movedFrom.size) this.drainingRequests[earlierId] = request;\n message.id = id;\n this.outgoingRequests.push({\n ...request,\n id: String(id),\n ws: null,\n successor: null,\n overlapEventIds: null,\n movedFrom: new Set(),\n });\n }\n\n /**\n * Retrieves all currently pending requests, which are in flight awaiting responses\n * or handling ongoing subscriptions.\n */\n public getPendingRequests() {\n return Object.values(this.pendingRequests);\n }\n\n /**\n * Retrieves a specific pending request by its message ID.\n */\n public getPendingRequest(messageId: MessageIdLike) {\n if (messageId === null) return null;\n\n return this.pendingRequests[String(messageId)];\n }\n\n /**\n * Retrieves a subscription sent again under a new id by its earlier id,\n * while a socket it moved from may still send events under that one.\n */\n public getDrainingRequest(messageId: MessageIdLike) {\n if (messageId === null) return null;\n\n return this.drainingRequests[String(messageId)];\n }\n\n /**\n * Retrieves the subscriptions sent again under a new id whose earlier id\n * is still in use on a socket they moved from.\n */\n public getDrainingRequests() {\n return Object.values(this.drainingRequests);\n }\n\n /**\n * Forgets the earlier ids of subscriptions no longer draining any socket.\n */\n public deleteDrained() {\n for (const [id, request] of Object.entries(this.drainingRequests)) {\n if (!request.movedFrom.size) delete this.drainingRequests[id];\n }\n }\n\n /**\n * Retrieves all outgoing requests, which are waiting to be sent.\n */\n public getOutgoingRequests() {\n return this.outgoingRequests;\n }\n\n /**\n * Retrieves all requests, both outgoing and pending, with their respective states.\n *\n * @returns An array of all requests with their state (\"outgoing\" or \"pending\").\n */\n public getRequests() {\n return [\n ...this.getOutgoingRequests().map((request) => ({\n state: 'outgoing' as const,\n message: request.message,\n end: request.end,\n callbacks: request.callbacks,\n })),\n ...this.getPendingRequests().map((request) => ({\n state: 'pending' as const,\n message: request.message,\n end: request.end,\n callbacks: request.callbacks,\n })),\n ];\n }\n\n /**\n * Checks if there are any pending requests, including ongoing subscriptions.\n */\n public hasPendingRequests() {\n return this.getPendingRequests().length > 0;\n }\n\n /**\n * Checks if there are any pending subscriptions\n */\n public hasPendingSubscriptions() {\n return this.getPendingRequests().some(\n (request) => request.message.method === 'subscription',\n );\n }\n\n /**\n * Checks if a message is still waiting to be sent.\n */\n public isOutgoing(message: TRPCClientOutgoingMessage) {\n return this.outgoingRequests.some((request) => request.message === message);\n }\n\n /**\n * Checks if there are any outgoing requests waiting to be sent.\n */\n public hasOutgoingRequests() {\n return this.outgoingRequests.length > 0;\n }\n\n /**\n * Checks if any request is outgoing or pending, including subscriptions.\n */\n public hasRequestsInFlight() {\n return this.hasOutgoingRequests() || this.hasPendingRequests();\n }\n}\n","import { behaviorSubject } from '@trpc/server/observable';\nimport type { UrlOptionsWithConnectionParams } from '../../internals/urlWithConnectionParams';\nimport type { Encoder } from './encoder';\nimport {\n buildConnectionMessage,\n prepareUrl,\n TRPCWebSocketClosedError,\n withResolvers,\n} from './utils';\n\n/**\n * Opens a WebSocket connection asynchronously and returns a promise\n * that resolves when the connection is successfully established.\n * The promise rejects if an error occurs during the connection attempt.\n */\nfunction asyncWsOpen(ws: WebSocket) {\n const { promise, resolve, reject } = withResolvers<void>();\n\n ws.addEventListener('open', () => {\n ws.removeEventListener('error', reject);\n resolve();\n });\n ws.addEventListener('error', reject);\n\n return promise;\n}\n\nconst pongCallbacks = new WeakMap<WebSocket, ((() => void) | null)[]>();\n\n/**\n * Sends \"PING\" on `ws` and calls `onPong`, if given, once its \"PONG\"\n * arrives. The server answers in order, so by then everything it sent before\n * it read this \"PING\" has arrived too.\n */\nexport function sendPing(ws: WebSocket, onPong: (() => void) | null) {\n let callbacks = pongCallbacks.get(ws);\n if (!callbacks) {\n const queue: ((() => void) | null)[] = [];\n callbacks = queue;\n pongCallbacks.set(ws, queue);\n ws.addEventListener('message', ({ data }) => {\n if (data === 'PONG') queue.shift()?.();\n });\n }\n callbacks.push(onPong);\n ws.send('PING');\n}\n\ninterface PingPongOptions {\n /**\n * The interval (in milliseconds) between \"PING\" messages.\n */\n intervalMs: number;\n\n /**\n * The timeout (in milliseconds) to wait for a \"PONG\" response before closing the connection.\n */\n pongTimeoutMs: number;\n}\n\n/**\n * Sets up a periodic ping-pong mechanism to keep the WebSocket connection alive.\n *\n * - Sends \"PING\" messages at regular intervals defined by `intervalMs`.\n * - If a \"PONG\" response is not received within the `pongTimeoutMs`, the WebSocket is closed.\n * - The ping timer resets upon receiving any message to maintain activity.\n * - Automatically starts the ping process when the WebSocket connection is opened.\n * - Cleans up timers when the WebSocket is closed.\n *\n * @param ws - The WebSocket instance to manage.\n * @param options - Configuration options for ping-pong intervals and timeouts.\n */\nfunction setupPingInterval(\n ws: WebSocket,\n { intervalMs, pongTimeoutMs }: PingPongOptions,\n onPongTimeout: () => void,\n) {\n let pingTimeout: ReturnType<typeof setTimeout> | undefined;\n let pongTimeout: ReturnType<typeof setTimeout> | undefined;\n\n function start() {\n pingTimeout = setTimeout(() => {\n sendPing(ws, null);\n pongTimeout = setTimeout(() => {\n // A socket that is already closing was closed on purpose.\n if (ws.readyState !== ws.OPEN) return;\n ws.close();\n onPongTimeout();\n }, pongTimeoutMs);\n }, intervalMs);\n }\n\n function reset() {\n clearTimeout(pingTimeout);\n start();\n }\n\n function pong() {\n clearTimeout(pongTimeout);\n reset();\n }\n\n ws.addEventListener('open', start);\n ws.addEventListener('message', ({ data }) => {\n clearTimeout(pingTimeout);\n start();\n\n if (data === 'PONG') {\n pong();\n }\n });\n ws.addEventListener('close', () => {\n clearTimeout(pingTimeout);\n clearTimeout(pongTimeout);\n });\n}\n\nexport interface WebSocketConnectionOptions {\n WebSocketPonyfill?: typeof WebSocket;\n urlOptions: UrlOptionsWithConnectionParams;\n keepAlive: PingPongOptions & {\n enabled: boolean;\n };\n encoder: Encoder;\n /**\n * Called when a keepAlive pong times out, once the socket is closing. Its\n * `close` event can come much later: an unresponsive server never answers\n * the closing handshake.\n */\n onPongTimeout: (ws: WebSocket) => void;\n}\n\n/**\n * Manages a WebSocket connection with support for reconnection, keep-alive mechanisms,\n * and observable state tracking.\n */\nexport class WsConnection {\n static connectCount = 0;\n public id = ++WsConnection.connectCount;\n\n private readonly WebSocketPonyfill: typeof WebSocket;\n private readonly urlOptions: UrlOptionsWithConnectionParams;\n private readonly keepAliveOpts: WebSocketConnectionOptions['keepAlive'];\n private readonly encoder: Encoder;\n private readonly onPongTimeout: WebSocketConnectionOptions['onPongTimeout'];\n public readonly wsObservable = behaviorSubject<WebSocket | null>(null);\n\n constructor(opts: WebSocketConnectionOptions) {\n this.WebSocketPonyfill = opts.WebSocketPonyfill ?? WebSocket;\n if (!this.WebSocketPonyfill) {\n throw new Error(\n \"No WebSocket implementation found - you probably don't want to use this on the server, but if you do you need to pass a `WebSocket`-ponyfill\",\n );\n }\n\n this.urlOptions = opts.urlOptions;\n this.keepAliveOpts = opts.keepAlive;\n this.encoder = opts.encoder;\n this.onPongTimeout = opts.onPongTimeout;\n }\n\n public get ws() {\n return this.wsObservable.get();\n }\n\n private set ws(ws) {\n this.wsObservable.next(ws);\n }\n\n /**\n * Checks if the WebSocket connection is open and ready to communicate.\n */\n public isOpen(): this is { ws: WebSocket } {\n return (\n !!this.ws &&\n this.ws.readyState === this.WebSocketPonyfill.OPEN &&\n !this.openPromise\n );\n }\n\n /**\n * Checks if the WebSocket connection is closed or in the process of closing.\n */\n public isClosed(): this is { ws: WebSocket } {\n return (\n !!this.ws &&\n (this.ws.readyState === this.WebSocketPonyfill.CLOSING ||\n this.ws.readyState === this.WebSocketPonyfill.CLOSED)\n );\n }\n\n /**\n * Manages the WebSocket opening process, ensuring that only one open operation\n * occurs at a time. Tracks the ongoing operation with `openPromise` to avoid\n * redundant calls and ensure proper synchronization.\n *\n * Sets up the keep-alive mechanism and necessary event listeners for the connection.\n *\n * @returns A promise that resolves once the WebSocket connection is successfully opened.\n */\n private openPromise: Promise<void> | null = null;\n public async open() {\n if (this.openPromise) return this.openPromise;\n\n this.id = ++WsConnection.connectCount;\n const wsPromise = prepareUrl(this.urlOptions).then(\n (url) => new this.WebSocketPonyfill(url),\n );\n const openPromise = wsPromise.then(async (ws) => {\n this.ws = ws;\n\n // Set binaryType to handle both text and binary messages consistently\n ws.binaryType = 'arraybuffer';\n\n // Setup ping listener\n ws.addEventListener('message', function ({ data }) {\n if (data === 'PING') {\n this.send('PONG');\n }\n });\n\n const abandoned = withResolvers<never>();\n if (this.keepAliveOpts.enabled) {\n setupPingInterval(ws, this.keepAliveOpts, () => {\n // A pong timeout gives up on an attempt still waiting on its\n // `connectionParams`, so the reconnect doesn't wait on them. The\n // attempt stays in `openPromise` until it rejects, so an `open()`\n // meanwhile, e.g. from `onClose`, gets that rejection instead of\n // starting another attempt on this connection.\n if (this.openPromise === openPromise) {\n abandoned.reject(\n new TRPCWebSocketClosedError({\n message: 'Pong timeout before connectionParams were sent',\n }),\n );\n }\n this.onPongTimeout(ws);\n });\n }\n\n ws.addEventListener('close', () => {\n if (this.ws === ws) {\n this.ws = null;\n }\n });\n\n await asyncWsOpen(ws);\n\n if (this.urlOptions.connectionParams) {\n ws.send(\n await Promise.race([\n buildConnectionMessage(\n this.urlOptions.connectionParams,\n this.encoder,\n ),\n abandoned.promise,\n ]),\n );\n }\n });\n this.openPromise = openPromise;\n\n try {\n await openPromise;\n } finally {\n if (this.openPromise === openPromise) {\n this.openPromise = null;\n }\n }\n }\n\n /**\n * Closes the WebSocket connection gracefully.\n * Waits for any ongoing open operation to complete before closing.\n */\n public async close() {\n try {\n await this.openPromise;\n } finally {\n this.ws?.close();\n }\n }\n}\n\n/**\n * Provides a backward-compatible representation of the connection state.\n */\nexport function backwardCompatibility(connection: WsConnection) {\n if (connection.isOpen()) {\n return {\n id: connection.id,\n state: 'open',\n ws: connection.ws,\n } as const;\n }\n\n if (connection.isClosed()) {\n return {\n id: connection.id,\n state: 'closed',\n ws: connection.ws,\n } as const;\n }\n\n if (!connection.ws) {\n return null;\n }\n\n return {\n id: connection.id,\n state: 'connecting',\n ws: connection.ws,\n } as const;\n}\n","import type { AnyTRPCRouter } from '@trpc/server';\nimport type { BehaviorSubject } from '@trpc/server/observable';\nimport { behaviorSubject, observable } from '@trpc/server/observable';\nimport type {\n CombinedDataTransformer,\n TRPCClientIncomingMessage,\n TRPCClientIncomingRequest,\n TRPCClientOutgoingMessage,\n TRPCResponseMessage,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n isObject,\n run,\n sleep,\n transformResult,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { TRPCClientError } from '../../../TRPCClientError';\nimport type { TRPCConnectionState } from '../../internals/subscriptions';\nimport type { Operation, OperationResultEnvelope } from '../../types';\nimport type { Encoder } from './encoder';\nimport { jsonEncoder } from './encoder';\nimport type { WebSocketClientOptions } from './options';\nimport { exponentialBackoff, keepAliveDefaults, lazyDefaults } from './options';\nimport type { TCallbacks } from './requestManager';\nimport { RequestManager } from './requestManager';\nimport {\n callUserCallback,\n ResettableTimeout,\n TRPCWebSocketClosedError,\n} from './utils';\nimport type { WebSocketConnectionOptions } from './wsConnection';\nimport { backwardCompatibility, sendPing, WsConnection } from './wsConnection';\n\nfunction isRequestId(value: unknown) {\n return (\n value === null || typeof value === 'string' || typeof value === 'number'\n );\n}\n\n/** A result's `type`; a missing one means `'data'`. */\nfunction isResultType(value: unknown) {\n return (\n value === undefined ||\n value === 'data' ||\n value === 'started' ||\n value === 'stopped'\n );\n}\n\n/**\n * A `reconnect` request from the server, or a response: a string, number or\n * `null` `id` and either a `result` object of a known `type` or an `error`.\n * The output transformer may serialize an error to any value, so\n * `transformResult` validates it.\n */\nfunction isIncomingMessage(value: unknown): value is TRPCClientIncomingMessage {\n if (!isObject(value)) return false;\n if ('method' in value) return value['method'] === 'reconnect';\n if (!isRequestId(value['id'])) return false;\n const result = value['result'];\n if (isObject(result)) return isResultType(result['type']);\n return result === undefined && 'error' in value;\n}\n\nfunction decodeIncomingMessage(\n encoder: Encoder,\n data: string | ArrayBuffer | Uint8Array,\n) {\n const message = encoder.decode(data);\n if (!isIncomingMessage(message)) {\n throw new TypeError('Expected a tRPC message');\n }\n return message;\n}\n\n/**\n * A WebSocket client for managing TRPC operations, supporting lazy initialization,\n * reconnection, keep-alive, and request management.\n */\nexport class WsClient {\n /**\n * Observable tracking the current connection state, including errors.\n */\n public readonly connectionState: BehaviorSubject<\n TRPCConnectionState<TRPCClientError<AnyTRPCRouter>>\n >;\n\n private allowReconnect = false;\n private requestManager = new RequestManager({\n onIdle: () => this.startInactivityTimeout(),\n });\n /**\n * The last id sent on the wire. Each request gets its own instead of its\n * `op.id`: a retry reuses the failed attempt's `op.id`, and the server's\n * late frames for that attempt must not reach the retry. A subscription\n * sent again after its socket was lost gets a new one for the same reason.\n */\n private lastRequestId = 0;\n private readonly connectionOptions: WebSocketConnectionOptions;\n /**\n * The connection new requests are sent on. A reconnect replaces it only\n * once the new connection is fully open, `connectionParams` included, so\n * until then requests keep going to the old one.\n */\n private activeConnection: WsConnection;\n private readonly reconnectRetryDelay: (attemptIndex: number) => number;\n private inactivityTimeout: ResettableTimeout;\n /**\n * Whether lazy mode may close the connection once it's idle: from the\n * first `open` until `close()`.\n */\n private inactivityTimeoutEnabled = false;\n private readonly callbacks: Pick<\n WebSocketClientOptions,\n 'onOpen' | 'onClose' | 'onError'\n >;\n private readonly lazyMode: boolean;\n private readonly encoder: Encoder;\n private readonly closeOnPongTimeout = new WeakMap<WebSocket, () => void>();\n\n constructor(opts: WebSocketClientOptions) {\n this.encoder = opts.experimental_encoder ?? jsonEncoder;\n // Initialize callbacks, connection parameters, and options.\n this.callbacks = {\n onOpen: opts.onOpen,\n onClose: opts.onClose,\n onError: opts.onError,\n };\n\n const lazyOptions = {\n ...lazyDefaults,\n ...opts.lazy,\n };\n\n // Set up inactivity timeout for lazy connections. It only runs while no\n // request or subscription is in flight; see `startInactivityTimeout()`.\n this.inactivityTimeout = new ResettableTimeout(() => {\n if (this.requestManager.hasRequestsInFlight()) {\n this.inactivityTimeout.stop();\n return;\n }\n\n this.close().catch(() => null);\n }, lazyOptions.closeMs);\n\n // Initialize the WebSocket connection.\n this.connectionOptions = {\n WebSocketPonyfill: opts.WebSocket,\n urlOptions: opts,\n keepAlive: {\n ...keepAliveDefaults,\n ...opts.keepAlive,\n },\n encoder: this.encoder,\n onPongTimeout: (ws) => this.closeOnPongTimeout.get(ws)?.(),\n };\n this.activeConnection = this.createConnection();\n this.reconnectRetryDelay = opts.retryDelayMs ?? exponentialBackoff;\n\n this.lazyMode = lazyOptions.enabled;\n\n this.connectionState = behaviorSubject<\n TRPCConnectionState<TRPCClientError<AnyTRPCRouter>>\n >({\n type: 'state',\n state: lazyOptions.enabled ? 'idle' : 'connecting',\n error: null,\n });\n\n // Automatically open the connection if lazy mode is disabled.\n if (!this.lazyMode) {\n this.open().catch(() => null);\n }\n }\n\n /**\n * Starts counting down to closing a lazy connection, if nothing is in\n * flight. Called on `open` and whenever the last request or subscription\n * ends, so the timer never has to poll.\n */\n private startInactivityTimeout() {\n if (\n !this.inactivityTimeoutEnabled ||\n this.requestManager.hasRequestsInFlight()\n ) {\n return;\n }\n this.inactivityTimeout.start();\n }\n\n private createConnection() {\n const connection = new WsConnection(this.connectionOptions);\n connection.wsObservable.subscribe({\n next: (ws) => {\n if (!ws) return;\n this.setupWebSocketListeners(ws);\n },\n });\n return connection;\n }\n\n /**\n * Opens the WebSocket connection. Handles reconnection attempts and updates\n * the connection state accordingly.\n */\n private async open() {\n this.allowReconnect = true;\n if (this.reconnecting) return this.reconnecting;\n this.connectionAttemptIndex = 0;\n if (this.connectionState.get().state === 'idle') {\n callUserCallback(() =>\n this.connectionState.next({\n type: 'state',\n state: 'connecting',\n error: null,\n }),\n );\n }\n\n try {\n await this.activeConnection.open();\n } catch (error) {\n this.reconnect(\n new TRPCWebSocketClosedError({\n message: 'Initialization error',\n cause: error,\n }),\n );\n // A socket whose `connectionParams` failed is open, but not usable.\n await this.activeConnection.close().catch(() => null);\n return this.reconnecting;\n }\n }\n\n /**\n * Closes the WebSocket connection and stops managing requests.\n * Ensures all outgoing and pending requests are properly finalized.\n */\n public async close() {\n this.allowReconnect = false;\n this.replacementError = null;\n this.retiredConnection = null;\n this.inactivityTimeoutEnabled = false;\n this.inactivityTimeout.stop();\n\n const requestsToAwait: Promise<void>[] = [];\n for (const request of this.requestManager.getRequests()) {\n if (request.message.method === 'subscription') {\n callUserCallback(() => request.callbacks.complete());\n } else if (request.state === 'outgoing') {\n callUserCallback(() =>\n request.callbacks.error(\n TRPCClientError.from(\n new TRPCWebSocketClosedError({\n message: 'Closed before connection was established',\n }),\n ),\n ),\n );\n } else {\n requestsToAwait.push(request.end);\n }\n }\n\n await Promise.all(requestsToAwait).catch(() => null);\n this.nextConnection?.ws?.close();\n await this.activeConnection.close().catch(() => null);\n\n callUserCallback(() =>\n this.connectionState.next({\n type: 'state',\n state: 'idle',\n error: null,\n }),\n );\n }\n\n /**\n * Method to request the server.\n * Handles data transformation, batching of requests, and subscription lifecycle.\n *\n * @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`.\n * @param transformer - Data transformer for serializing requests and deserializing responses\n * @param lastEventId - Optional ID of the last received event for subscriptions\n *\n * @returns An observable that emits operation results and handles cleanup\n */\n public request({\n op: { type, path, input, signal },\n transformer,\n lastEventId,\n }: {\n op: Pick<Operation, 'id' | 'type' | 'path' | 'input' | 'signal'>;\n transformer: CombinedDataTransformer;\n lastEventId?: string;\n }) {\n return observable<\n OperationResultEnvelope<unknown, TRPCClientError<AnyTRPCRouter>>,\n TRPCClientError<AnyTRPCRouter>\n >((observer) => {\n const message: TRPCClientOutgoingMessage = {\n id: ++this.lastRequestId,\n method: type,\n params: {\n input: transformer.input.serialize(input),\n path,\n lastEventId,\n },\n };\n const abort = this.batchSend(message, {\n ...observer,\n next(event) {\n let transformed: ReturnType<typeof transformResult>;\n try {\n transformed = transformResult(event, transformer.output);\n } catch (cause) {\n observer.error(TRPCClientError.from(cause as Error));\n return;\n }\n\n if (!transformed.ok) {\n observer.error(TRPCClientError.from(transformed.error));\n return;\n }\n\n observer.next({\n result: transformed.result,\n });\n },\n });\n\n const onAbort = () => observer.complete();\n if (signal?.aborted) {\n onAbort();\n } else {\n signal?.addEventListener('abort', onAbort, { once: true });\n }\n\n return () => {\n // A subscription sent again after its socket was lost has a new id.\n const { id } = message;\n const pending = this.requestManager.getPendingRequest(id);\n // Under its earlier ids, it may still be draining other sockets.\n const draining = this.requestManager\n .getDrainingRequests()\n .filter((request) => request.message === message);\n abort();\n\n if (type === 'subscription' && pending) {\n this.stopSubscription(id, pending.ws);\n this.stopSubscription(id, pending.successor);\n }\n this.closeIfDrained(pending?.ws);\n for (const request of [pending, ...draining]) {\n for (const earlier of request?.movedFrom ?? []) {\n this.closeIfDrained(earlier);\n }\n }\n\n signal?.removeEventListener('abort', onAbort);\n };\n });\n }\n\n /**\n * The current WebSocket and its state, or `null` when there is no socket.\n */\n public get connection() {\n return backwardCompatibility(\n this.activeConnection.ws\n ? this.activeConnection\n : (this.nextConnection ?? this.activeConnection),\n );\n }\n\n /**\n * Manages the reconnection process for the WebSocket using retry logic.\n * Ensures that only one reconnection attempt is active at a time by tracking the current\n * reconnection state in the `reconnecting` promise.\n */\n private reconnecting: Promise<void> | null = null;\n /**\n * The connection a reconnect is opening to replace the active one.\n */\n private nextConnection: WsConnection | null = null;\n /**\n * The connection the active one replaced, while it's open. If the active\n * one is lost first, this one serves every request again until the next.\n */\n private retiredConnection: WsConnection | null = null;\n /**\n * Why the latest attempt to replace a socket that's still open failed.\n * It's shown once that socket closes, since until then it serves every\n * request.\n */\n private replacementError: TRPCWebSocketClosedError | null = null;\n /**\n * The retry attempt that opened the current connection.\n */\n private connectionAttemptIndex = 0;\n /**\n * Set when the server rejects the current connection with an `id: null`\n * error, e.g. because `createContext` threw. The server closes the socket\n * right after, so the reconnect that follows carries on with the backoff\n * instead of starting over at attempt 0. Cleared again when the socket\n * receives a result, which proves the connection was accepted. Also set\n * on a keepAlive pong timeout when the socket never received anything.\n * @see https://github.com/trpc/trpc/issues/4774\n */\n private connectionRejected = false;\n /** Subscriptions whose subscriber has seen `started`. */\n private readonly started = new WeakSet<TRPCClientOutgoingMessage>();\n\n /**\n * Opens a new connection, retrying until one opens. While the current\n * socket is open, it keeps serving every request, new ones included, until\n * the new one is fully open, `connectionParams` included.\n *\n * @param closedError - Why the current socket was lost, or `null` when it's\n * still open and serving requests, e.g. on a server-requested reconnect.\n */\n private reconnect(closedError: TRPCWebSocketClosedError | null) {\n if (!this.allowReconnect) {\n return;\n }\n\n if (closedError) {\n const error = this.replacementError ?? closedError;\n this.replacementError = null;\n callUserCallback(() =>\n this.connectionState.next({\n type: 'state',\n state: 'connecting',\n error: TRPCClientError.from(error),\n }),\n );\n }\n if (this.reconnecting) return;\n\n const tryReconnect = async (attemptIndex: number) => {\n try {\n await sleep(this.reconnectRetryDelay(attemptIndex));\n if (this.allowReconnect) {\n const next = this.createConnection();\n this.nextConnection = next;\n try {\n await next.open();\n // `open()` resolves even if the socket closed while its\n // `connectionParams` were pending.\n if (!next.isOpen()) {\n throw new Error('WebSocket closed before it was ready');\n }\n } catch (error) {\n await next.close().catch(() => null);\n throw error;\n } finally {\n this.nextConnection = null;\n }\n\n if (this.allowReconnect) {\n // Read only now: losing the active socket while `next` opened may\n // have restored the one it replaced.\n const previous = this.activeConnection;\n this.activeConnection = next;\n this.retiredConnection = previous.isOpen() ? previous : null;\n this.connectionAttemptIndex = attemptIndex;\n this.replacementError = null;\n this.handOff(previous.ws);\n } else {\n await next.close();\n }\n }\n this.reconnecting = null;\n } catch (error) {\n const closedError = new TRPCWebSocketClosedError({\n message: 'Initialization error',\n cause: error,\n });\n if (this.allowReconnect && this.activeConnection.isOpen()) {\n // The old socket keeps serving every request, so this is shown only\n // once it closes.\n this.replacementError = closedError;\n } else if (this.allowReconnect) {\n callUserCallback(() =>\n this.connectionState.next({\n type: 'state',\n state: 'connecting',\n error: TRPCClientError.from(closedError),\n }),\n );\n }\n await tryReconnect(attemptIndex + 1);\n }\n };\n\n this.reconnecting = tryReconnect(\n this.connectionRejected ? this.connectionAttemptIndex + 1 : 0,\n );\n }\n\n /**\n * Moves the pending subscriptions to the active socket, which has just\n * opened: each is resubscribed with the id of the last event it delivered.\n * A subscription whose old socket is still open keeps delivering from it\n * until the new socket confirms it with `started`; see `confirmMove()`.\n * Closes the previous socket once nothing is left on it.\n */\n private handOff(previous: WebSocket | null) {\n if (\n this.connectionState.get().state !== 'pending' &&\n this.activeConnection.isOpen()\n ) {\n callUserCallback(() =>\n this.connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n }),\n );\n }\n\n const ws = this.activeConnection.ws;\n const subscriptions = this.requestManager\n .getPendingRequests()\n .filter(\n (request) =>\n request.message.method === 'subscription' && request.ws !== ws,\n );\n if (subscriptions.length) {\n this.send(subscriptions.map(({ message }) => message));\n for (const request of subscriptions) {\n // The socket it was moving to hasn't started it, and won't be used.\n this.stopSubscription(request.message.id, request.successor);\n if (request.ws && request.ws.readyState === request.ws.OPEN) {\n request.successor = ws;\n request.overlapEventIds = new Set();\n } else {\n // Its socket was lost, so it starts again.\n this.started.delete(request.message);\n request.ws = ws;\n request.successor = null;\n }\n }\n }\n this.closeIfDrained(previous);\n }\n\n /**\n * Completes a subscription's move once its new socket has confirmed it:\n * stops it on the old socket, whose later messages for it are dropped\n * apart from events without ids, and closes that socket once everything it\n * sent before the stop has arrived and nothing else is left on it.\n */\n private confirmMove(request: {\n message: TRPCClientOutgoingMessage;\n ws: WebSocket | null;\n successor: WebSocket | null;\n movedFrom: Set<WebSocket>;\n }) {\n const previous = request.ws;\n request.ws = request.successor;\n request.successor = null;\n if (previous && this.stopSubscription(request.message.id, previous)) {\n request.movedFrom.add(previous);\n // `stopped` can wait on the procedure, but the \"PONG\" can't.\n sendPing(previous, () => this.releaseMovedFrom(request, previous));\n }\n this.closeIfDrained(previous);\n }\n\n private releaseMovedFrom(\n request: { movedFrom: Set<WebSocket> },\n ws: WebSocket,\n ) {\n if (!request.movedFrom.delete(ws)) return;\n this.requestManager.deleteDrained();\n this.closeIfDrained(ws);\n }\n\n private hasRequestsOn(ws: WebSocket | null) {\n return [\n ...this.requestManager.getPendingRequests(),\n ...this.requestManager.getDrainingRequests(),\n ].some(\n (request) =>\n request.ws === ws || (ws !== null && request.movedFrom.has(ws)),\n );\n }\n\n /**\n * Closes `ws` once it's been replaced and nothing is left on it.\n */\n private closeIfDrained(ws: WebSocket | null | undefined) {\n if (!ws || ws === this.activeConnection.ws) return;\n if (this.hasRequestsOn(ws)) return;\n ws.close();\n }\n\n /**\n * Stops a subscription on the socket it was sent on, if that's still open.\n *\n * @returns Whether the stop was sent.\n */\n private stopSubscription(\n id: TRPCClientOutgoingMessage['id'],\n ws: WebSocket | null,\n ) {\n if (!ws || ws.readyState !== ws.OPEN) return false;\n ws.send(this.encoder.encode({ id, method: 'subscription.stop' }));\n return true;\n }\n\n /**\n * Fails the pending queries and mutations sent on `ws`, and returns its\n * pending subscriptions, which are kept to be sent again.\n */\n private failPendingRequests(ws: WebSocket, cause: unknown) {\n const subscriptions = [];\n for (const request of this.requestManager.getPendingRequests()) {\n const { message, callbacks } = request;\n if (request.ws !== ws) continue;\n if (message.method === 'subscription') {\n subscriptions.push(request);\n continue;\n }\n\n callUserCallback(() =>\n callbacks.error(\n TRPCClientError.from(\n cause ??\n new TRPCWebSocketClosedError({\n message: 'WebSocket closed',\n cause,\n }),\n ),\n ),\n );\n this.requestManager.delete(message);\n }\n return subscriptions;\n }\n\n private setupWebSocketListeners(ws: WebSocket) {\n this.connectionRejected = false;\n\n /**\n * Fails the queries and mutations sent on `ws`. Its subscriptions are\n * sent again on the active socket if that's open, or else by\n * `reconnect()` once the next one opens.\n */\n const handleCloseOrError = (cause: unknown) => {\n if (ws === this.retiredConnection?.ws) this.retiredConnection = null;\n const retired = this.retiredConnection;\n let restored = false;\n if (ws === this.activeConnection.ws && retired?.isOpen()) {\n restored = true;\n // The socket it replaced serves every request again, until the next\n // one opens.\n this.activeConnection = retired;\n this.retiredConnection = null;\n this.replacementError = new TRPCWebSocketClosedError({\n message: 'WebSocket closed',\n cause,\n });\n }\n for (const request of this.requestManager.getPendingRequests()) {\n if (request.successor === ws) {\n // Its old socket still has it.\n request.successor = null;\n request.overlapEventIds = null;\n }\n request.movedFrom.delete(ws);\n }\n for (const request of this.requestManager.getDrainingRequests()) {\n request.movedFrom.delete(ws);\n }\n this.requestManager.deleteDrained();\n const lost = this.failPendingRequests(ws, cause).filter((request) => {\n if (!request.successor) return true;\n // Its new socket has it already.\n request.ws = request.successor;\n request.successor = null;\n return false;\n });\n if (\n ws === this.activeConnection.ws ||\n (this.reconnecting && !this.activeConnection.isOpen())\n ) {\n return;\n }\n\n for (const { message, callbacks } of lost) {\n this.started.delete(message);\n // The active socket may still have its old id, e.g. while stopping it.\n this.requestManager.requeue(message, ++this.lastRequestId);\n this.flushOutgoing(message, callbacks);\n }\n if (restored) this.reconnect(null);\n };\n\n ws.addEventListener('open', () => {\n run(async () => {\n if (this.lazyMode) {\n this.inactivityTimeoutEnabled = true;\n this.startInactivityTimeout();\n }\n\n this.callbacks.onOpen?.();\n\n // A socket opened to replace one that's still open changes nothing\n // the subscribers can see until `handOff()` puts it in use.\n if (\n this.connectionState.get().state === 'pending' ||\n (ws !== this.activeConnection.ws && this.activeConnection.isOpen())\n ) {\n return;\n }\n callUserCallback(() =>\n this.connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n }),\n );\n }).catch((error) => {\n ws.close(3000);\n handleCloseOrError(error);\n });\n });\n\n // Set on the socket's `close` event, or earlier when the client gives up\n // on the socket (a keepAlive pong timeout or an undecodable frame) without\n // waiting for the closing handshake. The socket's later frames and events\n // must not reach the requests resent by then.\n let closed = false;\n let answered = false;\n\n /**\n * Runs the socket's close handling once: `cause` fails its queries and\n * mutations, and `event` goes to `onClose`.\n */\n const handleClose = (\n cause: unknown,\n event: CloseEvent | { code: number },\n ) => {\n if (closed) return;\n closed = true;\n handleCloseOrError(cause);\n callUserCallback(() => this.callbacks.onClose?.(event));\n\n if (\n ws === this.activeConnection.ws &&\n (!this.lazyMode || this.requestManager.hasPendingSubscriptions())\n ) {\n this.reconnect(\n new TRPCWebSocketClosedError({\n message: 'WebSocket closed',\n cause,\n }),\n );\n }\n };\n // What `close` reports when the closing handshake doesn't complete.\n const abandonedEvent = { code: 1006 };\n\n const onMessage = ({ data }: MessageEvent) => {\n if (closed) return;\n answered = true;\n this.inactivityTimeout.reset();\n\n // Handle PING/PONG as text regardless of encoder\n if (['PING', 'PONG'].includes(data)) return;\n\n let incomingMessage: TRPCClientIncomingMessage;\n try {\n incomingMessage = decodeIncomingMessage(this.encoder, data);\n } catch (cause) {\n // The frame may have carried a response, and its request would wait\n // forever, so this socket is treated as lost.\n ws.close();\n handleClose(\n new TRPCWebSocketClosedError({\n message: 'Received a message that could not be decoded',\n cause,\n }),\n abandonedEvent,\n );\n // Rethrown asynchronously by `callUserCallback()` below.\n throw cause;\n }\n if ('method' in incomingMessage) {\n if (ws === this.activeConnection.ws) {\n this.handleIncomingRequest(incomingMessage);\n }\n return;\n }\n\n // A replaced socket still answers its own queries and mutations, but\n // says nothing about the connection the client now uses.\n const isRetired =\n ws !== this.activeConnection.ws && ws !== this.nextConnection?.ws;\n if (\n !isRetired &&\n incomingMessage.id === null &&\n 'error' in incomingMessage\n ) {\n this.connectionRejected = true;\n } else if (!isRetired && 'result' in incomingMessage) {\n // The server only sends results once `createContext` has succeeded,\n // so an earlier `id: null` error on this socket was not a rejection,\n // e.g. the server's reply to a malformed frame.\n this.connectionRejected = false;\n }\n\n this.handleResponseMessage(incomingMessage, ws);\n };\n // With `ws`, a throw from a `message` listener stops the socket from\n // reading any further frames while it stays open.\n ws.addEventListener('message', (event) => {\n callUserCallback(() => onMessage(event));\n });\n\n ws.addEventListener('close', (event) => handleClose(event, event));\n this.closeOnPongTimeout.set(ws, () => {\n // A server that never answered, not even a ping, gets the same backoff\n // as one that rejected the connection.\n if (!answered) this.connectionRejected = true;\n handleClose(abandonedEvent, abandonedEvent);\n });\n\n ws.addEventListener('error', (event) => {\n if (closed) return;\n handleCloseOrError(event);\n callUserCallback(() => this.callbacks.onError?.(event));\n\n if (ws !== this.activeConnection.ws) return;\n\n this.reconnect(\n new TRPCWebSocketClosedError({\n message: 'WebSocket closed',\n cause: event,\n }),\n );\n });\n }\n\n private handleResponseMessage(message: TRPCResponseMessage, ws: WebSocket) {\n const request =\n this.requestManager.getPendingRequest(message.id) ??\n this.requestManager.getDrainingRequest(message.id);\n if (!request) return;\n const result = 'result' in message ? message.result : null;\n if (request.successor === ws) {\n this.confirmMove(request);\n } else if (request.ws !== ws) {\n // A subscription moved to a new socket ignores the old one's frames,\n // apart from events without ids until it's stopped there: those can't\n // be replayed, and the new socket may have started listening after\n // the old one sent them.\n if (request.movedFrom.has(ws)) {\n if (result?.type === 'stopped') {\n this.releaseMovedFrom(request, ws);\n } else if (result?.type === 'data' && result.id === undefined) {\n callUserCallback(() => request.callbacks.next(message));\n }\n }\n return;\n }\n // The subscriber doesn't see a move, even one its old socket didn't\n // live to finish.\n if (result?.type === 'started' && this.started.has(request.message)) {\n return;\n }\n\n if (result?.type === 'data' && result.id !== undefined) {\n const eventId = String(result.id);\n if (request.successor) {\n request.overlapEventIds?.add(eventId);\n } else if (request.overlapEventIds?.delete(eventId)) {\n // Already delivered by the old socket.\n return;\n }\n }\n\n callUserCallback(() => request.callbacks.next(message));\n\n let completed = true;\n if ('result' in message && request.message.method === 'subscription') {\n if (message.result.type === 'data') {\n request.message.params.lastEventId = message.result.id;\n } else if (message.result.type === 'started') {\n this.started.add(request.message);\n }\n\n if (message.result.type !== 'stopped') {\n completed = false;\n }\n }\n\n if (completed) {\n callUserCallback(() => request.callbacks.complete());\n this.requestManager.delete(request.message);\n }\n }\n\n private handleIncomingRequest(message: TRPCClientIncomingRequest) {\n if (message.method === 'reconnect') {\n this.reconnect(null);\n }\n }\n\n /**\n * Sends a message or batch of messages directly to the server.\n */\n private send(\n messageOrMessages: TRPCClientOutgoingMessage | TRPCClientOutgoingMessage[],\n ) {\n if (!this.activeConnection.isOpen()) {\n throw new Error('Active connection is not open');\n }\n\n const messages =\n messageOrMessages instanceof Array\n ? messageOrMessages\n : [messageOrMessages];\n this.activeConnection.ws.send(\n this.encoder.encode(messages.length === 1 ? messages[0] : messages),\n );\n }\n\n /**\n * Groups requests for batch sending.\n *\n * @returns A function to abort the batched request.\n */\n private batchSend(message: TRPCClientOutgoingMessage, callbacks: TCallbacks) {\n // Started again once the last request or subscription ends.\n this.inactivityTimeout.stop();\n this.flushOutgoing(message, callbacks);\n return this.requestManager.register(message, callbacks);\n }\n\n /**\n * Sends `message` with the other outgoing requests once the connection is\n * open, batching those queued in the same tick.\n */\n private flushOutgoing(\n message: TRPCClientOutgoingMessage,\n callbacks: TCallbacks,\n ) {\n run(async () => {\n // During a reconnect, requests go to the old socket while it's open.\n do {\n if (!this.activeConnection.isOpen()) {\n await this.open();\n }\n await sleep(0);\n } while (!this.activeConnection.isOpen() && this.reconnecting);\n\n if (!this.requestManager.hasOutgoingRequests()) return;\n // Another run already sent this request. Each queued request's own run\n // sends it once the new socket opens.\n if (\n !this.activeConnection.isOpen() &&\n !this.requestManager.isOutgoing(message)\n ) {\n return;\n }\n\n const requests = this.requestManager.flush(this.activeConnection.ws);\n try {\n this.send(requests.map((request) => request.message));\n } catch (err) {\n for (const request of requests) {\n this.requestManager.delete(request.message);\n callUserCallback(() =>\n request.callbacks.error(TRPCClientError.from(err as Error)),\n );\n }\n }\n }).catch((err) => {\n this.requestManager.delete(message);\n callUserCallback(() => callbacks.error(TRPCClientError.from(err)));\n });\n }\n}\n","import type { Encoder } from './wsClient/encoder';\nimport { jsonEncoder } from './wsClient/encoder';\nimport type { WebSocketClientOptions } from './wsClient/options';\nimport { WsClient } from './wsClient/wsClient';\n\n/**\n * Opens and manages a WebSocket connection to a tRPC server. Pass it to\n * `wsLink`.\n *\n * @see https://trpc.io/docs/client/links/wsLink#wslink--createwsclient-options\n */\nexport function createWSClient(opts: WebSocketClientOptions) {\n return new WsClient(opts);\n}\n\n/**\n * The client returned by {@link createWSClient}.\n */\nexport type TRPCWebSocketClient = ReturnType<typeof createWSClient>;\n\nexport { jsonEncoder, type Encoder, type WebSocketClientOptions };\n","import type { Unsubscribable } from '@trpc/server/observable';\nimport { observable } from '@trpc/server/observable';\nimport type {\n AnyRouter,\n inferClientTypes,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type { TransformerOptions } from '../../unstable-internals';\nimport { getTransformer } from '../../unstable-internals';\nimport type { TRPCLink } from '../types';\nimport type {\n Encoder,\n TRPCWebSocketClient,\n WebSocketClientOptions,\n} from './createWsClient';\nimport { createWSClient, jsonEncoder } from './createWsClient';\nimport { callUserCallback } from './wsClient/utils';\n\n/**\n * Options for {@link wsLink}.\n *\n * @see https://trpc.io/docs/client/links/wsLink#wslink--createwsclient-options\n */\nexport type WebSocketLinkOptions<TRouter extends AnyRouter> = {\n /**\n * The client made with `createWSClient`.\n */\n client: TRPCWebSocketClient;\n} & TransformerOptions<inferClientTypes<TRouter>>;\n\n/**\n * A terminating link that sends calls over a WebSocket.\n *\n * @see https://trpc.io/docs/client/links/wsLink\n */\nexport function wsLink<TRouter extends AnyRouter>(\n opts: WebSocketLinkOptions<TRouter>,\n): TRPCLink<TRouter> {\n const { client } = opts;\n const transformer = getTransformer(opts.transformer);\n return () => {\n return ({ op }) => {\n return observable((observer) => {\n let connStateSubscription: Unsubscribable | null = null;\n if (op.type === 'subscription') {\n // The current state is sent during `subscribe`, and a throwing\n // `onConnectionStateChange` must not stop the request below from\n // being sent. The client guards the states it sends later.\n let isSubscribing = true;\n connStateSubscription = client.connectionState.subscribe({\n next(result) {\n const emit = () =>\n observer.next({\n result,\n context: op.context,\n });\n if (isSubscribing) {\n callUserCallback(emit);\n } else {\n emit();\n }\n },\n });\n isSubscribing = false;\n }\n\n const requestSubscription = client\n .request({\n op,\n transformer,\n })\n .subscribe(observer);\n\n return () => {\n requestSubscription.unsubscribe();\n connStateSubscription?.unsubscribe();\n };\n });\n };\n };\n}\n\nexport {\n createWSClient,\n jsonEncoder,\n type Encoder,\n type TRPCWebSocketClient,\n type WebSocketClientOptions,\n};\n"],"mappings":";;;;;;;;;AAOA,MAAa,cAAuB;CAClC,SAAS,SAAS,KAAK,UAAU,IAAI;CACrC,SAAS,SAAS;EAChB,IAAI,OAAO,SAAS,UAClB,MAAM,IAAI,MACR,gGAEF;EAEF,OAAO,KAAK,MAAM,IAAI;CACxB;AACF;;AC0DA,MAAa,eAA4B;CACvC,SAAS;CACT,SAAS;AACX;AASA,MAAa,oBAAsC;CACjD,SAAS;CACT,eAAe;CACf,YAAY;AACd;;;;;;AAOA,MAAa,sBAAsB,iBAAyB;CAC1D,OAAO,iBAAiB,IAAI,IAAI,KAAK,IAAI,MAAO,KAAK,cAAc,GAAK;AAC1E;;;;;;AC/FA,MAAa,YACX,OACA,GAAG,SACG;CACN,OAAO,OAAO,UAAU,aACnB,MAAgC,GAAG,IAAI,IACxC;AACN;;ACFA,IAAa,2BAAb,MAAa,iCAAiC,MAAM;CAClD,YAAY,MAA4C;EACtD,MAAM,KAAK,SAAS,EAClB,OAAO,KAAK,MACd,CAAC;EACD,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,yBAAyB,SAAS;CAChE;AACF;;;;;;;AAQA,SAAgB,iBAAiB,UAAsB;CACrD,IAAI;EACF,SAAS;CACX,SAAS,OAAO;EACd,iBAAiB;GACf,MAAM;EACR,CAAC;CACH;AACF;;;;;AAMA,IAAa,oBAAb,MAA+B;CAG7B,YACE,WACA,WACA;EAF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AAiB,EAAE;GACnE,IAAI;IACF,KAAK,KAAK,SAAS,KAAK,YAAY,QAAQ,OAAO,CAAC;GACtD,SAAS,KAAK;IACZ,KAAK,MAAM,WAAW,UAAU;KAC9B,KAAK,eAAe,OAAO,QAAQ,OAAO;KAC1C,uBACE,QAAQ,UAAU,MAAM,gBAAgB,KAAK,GAAY,CAAC,CAC5D;IACF;GACF;EACF,CAAC,CAAC,CAAC,OAAO,QAAQ;GAChB,KAAK,eAAe,OAAO,OAAO;GAClC,uBAAuB,UAAU,MAAM,gBAAgB,KAAK,GAAG,CAAC,CAAC;EACnE,CAAC;CACH;AACF;;;;;;;;AC98BA,SAAgB,eAAe,MAA8B;CAC3D,OAAO,IAAI,SAAS,IAAI;AAC1B;;;;;;;ACqBA,SAAgB,OACd,MACmB;CACnB,MAAM,EAAE,WAAW;CACnB,MAAM,cAAc,eAAe,KAAK,WAAW;CACnD,aAAa;EACX,QAAQ,EAAE,SAAS;GACjB,OAAO,YAAY,aAAa;IAC9B,IAAI,wBAA+C;IACnD,IAAI,GAAG,SAAS,gBAAgB;KAI9B,IAAI,gBAAgB;KACpB,wBAAwB,OAAO,gBAAgB,UAAU,EACvD,KAAK,QAAQ;MACX,MAAM,aACJ,SAAS,KAAK;OACZ;OACA,SAAS,GAAG;MACd,CAAC;MACH,IAAI,eACF,iBAAiB,IAAI;WAErB,KAAK;KAET,EACF,CAAC;KACD,gBAAgB;IAClB;IAEA,MAAM,sBAAsB,OACzB,QAAQ;KACP;KACA;IACF,CAAC,CAAC,CACD,UAAU,QAAQ;IAErB,aAAa;KACX,oBAAoB,YAAY;KAChC,0BAAA,QAAA,0BAAA,KAAA,KAAA,sBAAuB,YAAY;IACrC;GACF,CAAC;EACH;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"wsLink-DSmHMirJ.mjs","names":[],"sources":["../src/links/wsLink/wsClient/encoder.ts","../src/links/wsLink/wsClient/options.ts","../src/links/internals/urlWithConnectionParams.ts","../src/links/wsLink/wsClient/utils.ts","../src/links/wsLink/wsClient/requestManager.ts","../src/links/wsLink/wsClient/wsConnection.ts","../src/links/wsLink/wsClient/wsClient.ts","../src/links/wsLink/createWsClient.ts","../src/links/wsLink/wsLink.ts"],"sourcesContent":["import type { Encoder } from '@trpc/server/unstable-core-do-not-import';\n\nexport type { Encoder };\n\n/**\n * The default WebSocket encoder. Sends messages as JSON text frames.\n */\nexport const jsonEncoder: Encoder = {\n encode: (data) => JSON.stringify(data),\n decode: (data) => {\n if (typeof data !== 'string') {\n throw new Error(\n 'jsonEncoder received binary data. JSON uses text frames. ' +\n 'Use a binary encoder for binary data.',\n );\n }\n return JSON.parse(data);\n },\n};\n","import type { UrlOptionsWithConnectionParams } from '../../internals/urlWithConnectionParams';\nimport type { Encoder } from './encoder';\n\n/**\n * Options for `createWSClient`.\n *\n * @see https://trpc.io/docs/client/links/wsLink#wslink--createwsclient-options\n */\nexport interface WebSocketClientOptions extends UrlOptionsWithConnectionParams {\n /**\n * The `WebSocket` class to use, for runtimes that don't have one.\n */\n WebSocket?: typeof WebSocket;\n /**\n * The number of milliseconds before a reconnect is attempted.\n * @default {@link exponentialBackoff}\n */\n retryDelayMs?: (attemptIndex: number) => number;\n /**\n * Triggered when a WebSocket connection is established\n */\n onOpen?: () => void;\n /**\n * Triggered when a WebSocket connection encounters an error\n */\n onError?: (evt?: Event) => void;\n /**\n * Triggered when a WebSocket connection is closed\n */\n onClose?: (cause?: { code?: number }) => void;\n /**\n * Lazy mode will close the WebSocket automatically after a period of inactivity (no messages sent or received and no pending requests)\n */\n lazy?: {\n /**\n * Enable lazy mode\n * @default false\n */\n enabled: boolean;\n /**\n * Close the WebSocket after this many milliseconds\n * @default 0\n */\n closeMs: number;\n };\n /**\n * Send ping messages to the server and kill the connection if no pong message is returned\n */\n keepAlive?: {\n /**\n * @default false\n */\n enabled: boolean;\n /**\n * Send a ping message every this many milliseconds\n * @default 5_000\n */\n intervalMs?: number;\n /**\n * Close the WebSocket after this many milliseconds if the server does not respond\n * @default 1_000\n */\n pongTimeoutMs?: number;\n };\n /**\n * Encodes and decodes messages on the wire, for example as a binary format.\n * @default jsonEncoder\n */\n experimental_encoder?: Encoder;\n}\n\n/**\n * Default options for lazy WebSocket connections.\n * Determines whether the connection should be established lazily and defines the delay before closure.\n */\nexport type LazyOptions = Required<NonNullable<WebSocketClientOptions['lazy']>>;\nexport const lazyDefaults: LazyOptions = {\n enabled: false,\n closeMs: 0,\n};\n\n/**\n * Default options for the WebSocket keep-alive mechanism.\n * Configures whether keep-alive is enabled and specifies the timeout and interval for ping-pong messages.\n */\nexport type KeepAliveOptions = Required<\n NonNullable<WebSocketClientOptions['keepAlive']>\n>;\nexport const keepAliveDefaults: KeepAliveOptions = {\n enabled: false,\n pongTimeoutMs: 1_000,\n intervalMs: 5_000,\n};\n\n/**\n * Calculates a delay for exponential backoff based on the retry attempt index.\n * The delay starts at 0 for the first attempt and doubles for each subsequent attempt,\n * capped at 30 seconds.\n */\nexport const exponentialBackoff = (attemptIndex: number) => {\n return attemptIndex === 0 ? 0 : Math.min(1000 * 2 ** attemptIndex, 30000);\n};\n","import { type TRPCRequestInfo } from '@trpc/server/http';\n\n/**\n * Get the result of a value or function that returns a value\n * It also optionally accepts typesafe arguments for the function\n */\nexport const resultOf = <T, TArgs extends any[]>(\n value: T | ((...args: TArgs) => T),\n ...args: TArgs\n): T => {\n return typeof value === 'function'\n ? (value as (...args: TArgs) => T)(...args)\n : value;\n};\n\n/**\n * A value that can be wrapped in callback\n */\nexport type CallbackOrValue<T> = T | (() => T | Promise<T>);\n\nexport interface UrlOptionsWithConnectionParams {\n /**\n * The URL to connect to (can be a function that returns a URL)\n */\n url: CallbackOrValue<string>;\n\n /**\n * Connection params that are available in `createContext()`\n * - For `wsLink`/`wsClient`, these are sent as the first message\n * - For `httpSubscriptionLink`, these are serialized as part of the URL under the `connectionParams` query\n * @see https://trpc.io/docs/server/websockets#connectionParams\n */\n connectionParams?: CallbackOrValue<TRPCRequestInfo['connectionParams']>;\n}\n","import type {\n TRPCConnectionParamsMessage,\n TRPCRequestInfo,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type {\n CallbackOrValue,\n UrlOptionsWithConnectionParams,\n} from '../../internals/urlWithConnectionParams';\nimport { resultOf } from '../../internals/urlWithConnectionParams';\nimport type { Encoder } from './encoder';\n\nexport class TRPCWebSocketClosedError extends Error {\n constructor(opts: { message: string; cause?: unknown }) {\n super(opts.message, {\n cause: opts.cause,\n });\n this.name = 'TRPCWebSocketClosedError';\n Object.setPrototypeOf(this, TRPCWebSocketClosedError.prototype);\n }\n}\n\n/**\n * Calls a user callback, including `connectionState` subscribers. A throw\n * would skip the rest of the client's bookkeeping (e.g. end the reconnect\n * loop, or, with event-emitter based WebSockets such as `ws`, skip the other\n * listeners for that event), so it is rethrown asynchronously instead.\n */\nexport function callUserCallback(callback: () => void) {\n try {\n callback();\n } catch (error) {\n setTimeout(() => {\n throw error;\n });\n }\n}\n\n/**\n * Utility class for managing a timeout that can be started, stopped, and reset.\n * Useful for scenarios where the timeout duration is reset dynamically based on events.\n */\nexport class ResettableTimeout {\n private timeout: ReturnType<typeof setTimeout> | undefined;\n\n constructor(\n private readonly onTimeout: () => void,\n private readonly timeoutMs: number,\n ) {}\n\n /**\n * Resets the current timeout, restarting it with the same duration.\n * Does nothing if no timeout is active.\n */\n public reset() {\n if (!this.timeout) return;\n\n clearTimeout(this.timeout);\n this.timeout = setTimeout(this.onTimeout, this.timeoutMs);\n }\n\n public start() {\n clearTimeout(this.timeout);\n this.timeout = setTimeout(this.onTimeout, this.timeoutMs);\n }\n\n public stop() {\n clearTimeout(this.timeout);\n this.timeout = undefined;\n }\n}\n\n// Ponyfill for Promise.withResolvers https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers\nexport function withResolvers<T>() {\n let resolve: (value: T | PromiseLike<T>) => void;\n let reject: (reason?: any) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n // oxlint-disable-next-line typescript/no-non-null-assertion\n return { promise, resolve: resolve!, reject: reject! };\n}\n\n/**\n * Resolves a WebSocket URL and optionally appends connection parameters.\n *\n * If connectionParams are provided, appends 'connectionParams=1' query parameter.\n */\nexport async function prepareUrl(urlOptions: UrlOptionsWithConnectionParams) {\n const url = await resultOf(urlOptions.url);\n\n if (!urlOptions.connectionParams) return url;\n\n // append `?connectionParams=1` when connection params are used\n const prefix = url.includes('?') ? '&' : '?';\n const connectionParams = `${prefix}connectionParams=1`;\n\n return url + connectionParams;\n}\n\nexport async function buildConnectionMessage(\n connectionParams: CallbackOrValue<TRPCRequestInfo['connectionParams']>,\n encoder: Encoder,\n) {\n const message: TRPCConnectionParamsMessage = {\n method: 'connectionParams',\n data: await resultOf(connectionParams),\n };\n\n return encoder.encode(message);\n}\n","import type { AnyTRPCRouter, inferRouterError } from '@trpc/server';\nimport type { Observer } from '@trpc/server/observable';\nimport type {\n TRPCClientOutgoingMessage,\n TRPCResponseMessage,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type { TRPCClientError } from '../../../TRPCClientError';\nimport { withResolvers } from './utils';\n\nexport type TCallbacks = Observer<\n TRPCResponseMessage<unknown, inferRouterError<AnyTRPCRouter>>,\n TRPCClientError<AnyTRPCRouter>\n>;\n\ntype MessageId = string;\ntype MessageIdLike = string | number | null;\n\n/**\n * Represents a WebSocket request managed by the RequestManager.\n * Combines the network message, a utility promise (`end`) that mirrors the lifecycle\n * handled by `callbacks`, and a set of state monitoring callbacks.\n */\ninterface Request {\n message: TRPCClientOutgoingMessage;\n end: Promise<void>;\n callbacks: TCallbacks;\n /**\n * The socket the request was sent on, or `null` while it's outgoing.\n */\n ws: WebSocket | null;\n /**\n * The socket a subscription is moving to. `ws` keeps delivering until this\n * one confirms the subscription with `started`.\n */\n successor: WebSocket | null;\n /**\n * The event ids `ws` delivered while the subscription was moving, which\n * its successor replays and are dropped from it.\n */\n overlapEventIds: Set<string> | null;\n /**\n * The sockets a subscription moved from, each until everything it sent\n * before the stop has arrived. Their events without ids are still\n * delivered, since the new socket may have started listening after they\n * were sent.\n */\n movedFrom: Set<WebSocket>;\n}\n\n/**\n * Manages WebSocket requests, tracking their lifecycle and providing utility methods\n * for handling outgoing and pending requests.\n *\n * - **Outgoing requests**: Requests that are queued and waiting to be sent.\n * - **Pending requests**: Requests that have been sent and are in flight awaiting a response.\n * For subscriptions, multiple responses may be received until the subscription is closed.\n */\nexport class RequestManager {\n constructor(\n private readonly opts: {\n /**\n * Called when a deletion leaves no outgoing or pending request.\n */\n onIdle: () => void;\n },\n ) {}\n\n /**\n * Stores requests that are outgoing, meaning they are registered but not yet sent over the WebSocket.\n */\n private outgoingRequests = new Array<Request & { id: MessageId }>();\n\n /**\n * Stores requests that are pending (in flight), meaning they have been sent over the WebSocket\n * and are awaiting responses. For subscriptions, this includes requests\n * that may receive multiple responses.\n */\n private pendingRequests: Record<MessageId, Request> = {};\n\n /**\n * Subscriptions sent again under a new id, by their earlier id, while\n * sockets they moved from may still send events under that one.\n */\n private drainingRequests: Record<MessageId, Request> = {};\n\n /**\n * Registers a new request by adding it to the outgoing queue and setting up\n * callbacks for lifecycle events such as completion or error.\n *\n * @param message - The outgoing message to be sent.\n * @param callbacks - Callback functions to observe the request's state.\n * @returns A cleanup function to manually remove the request.\n */\n public register(message: TRPCClientOutgoingMessage, callbacks: TCallbacks) {\n const { promise: end, resolve } = withResolvers<void>();\n\n this.outgoingRequests.push({\n id: String(message.id),\n message,\n end,\n ws: null,\n successor: null,\n overlapEventIds: null,\n movedFrom: new Set(),\n callbacks: {\n next: callbacks.next,\n complete: () => {\n callbacks.complete();\n resolve();\n },\n error: (e) => {\n try {\n callbacks.error(e);\n } finally {\n resolve();\n }\n },\n },\n });\n\n return () => {\n this.delete(message);\n callbacks.complete();\n resolve();\n };\n }\n\n /**\n * Deletes a request from both the outgoing and pending collections, if it exists.\n *\n * Matches the message itself rather than its id: a retry reuses the id, and\n * registers its request before the failed request with that id is deleted.\n */\n public delete(message: TRPCClientOutgoingMessage) {\n const wasInFlight = this.hasRequestsInFlight();\n this.outgoingRequests = this.outgoingRequests.filter(\n (request) => request.message !== message,\n );\n const id = String(message.id);\n if (this.pendingRequests[id]?.message === message) {\n delete this.pendingRequests[id];\n }\n for (const [drainingId, request] of Object.entries(this.drainingRequests)) {\n if (request.message === message) {\n delete this.drainingRequests[drainingId];\n }\n }\n if (wasInFlight && !this.hasRequestsInFlight()) {\n this.opts.onIdle();\n }\n }\n\n /**\n * Moves all outgoing requests to the pending state and clears the outgoing queue.\n *\n * The caller is expected to handle the actual sending of the requests\n * (e.g., sending them over the network) after this method is called.\n *\n * @param ws - The socket the requests are sent on.\n * @returns The list of requests that were transitioned to the pending state.\n */\n public flush(ws: WebSocket | null = null) {\n const requests = this.outgoingRequests;\n this.outgoingRequests = [];\n\n for (const request of requests) {\n request.ws = ws;\n request.successor = null;\n request.movedFrom = new Set();\n this.pendingRequests[request.id] = request;\n }\n return requests;\n }\n\n /**\n * Moves a pending request back to the outgoing queue, to be sent again\n * with `id`. Its earlier id then matches only the sockets it's still\n * draining; see `getDrainingRequest()`.\n */\n public requeue(\n message: TRPCClientOutgoingMessage,\n id: TRPCClientOutgoingMessage['id'],\n ) {\n const earlierId = String(message.id);\n const request = this.pendingRequests[earlierId];\n if (request?.message !== message) return;\n\n delete this.pendingRequests[earlierId];\n if (request.movedFrom.size) this.drainingRequests[earlierId] = request;\n message.id = id;\n this.outgoingRequests.push({\n ...request,\n id: String(id),\n ws: null,\n successor: null,\n overlapEventIds: null,\n movedFrom: new Set(),\n });\n }\n\n /**\n * Retrieves all currently pending requests, which are in flight awaiting responses\n * or handling ongoing subscriptions.\n */\n public getPendingRequests() {\n return Object.values(this.pendingRequests);\n }\n\n /**\n * Retrieves a specific pending request by its message ID.\n */\n public getPendingRequest(messageId: MessageIdLike) {\n if (messageId === null) return null;\n\n return this.pendingRequests[String(messageId)];\n }\n\n /**\n * Retrieves a subscription sent again under a new id by its earlier id,\n * while a socket it moved from may still send events under that one.\n */\n public getDrainingRequest(messageId: MessageIdLike) {\n if (messageId === null) return null;\n\n return this.drainingRequests[String(messageId)];\n }\n\n /**\n * Retrieves the subscriptions sent again under a new id whose earlier id\n * is still in use on a socket they moved from.\n */\n public getDrainingRequests() {\n return Object.values(this.drainingRequests);\n }\n\n /**\n * Forgets the earlier ids of subscriptions no longer draining any socket.\n */\n public deleteDrained() {\n for (const [id, request] of Object.entries(this.drainingRequests)) {\n if (!request.movedFrom.size) delete this.drainingRequests[id];\n }\n }\n\n /**\n * Retrieves all outgoing requests, which are waiting to be sent.\n */\n public getOutgoingRequests() {\n return this.outgoingRequests;\n }\n\n /**\n * Retrieves all requests, both outgoing and pending, with their respective states.\n *\n * @returns An array of all requests with their state (\"outgoing\" or \"pending\").\n */\n public getRequests() {\n return [\n ...this.getOutgoingRequests().map((request) => ({\n state: 'outgoing' as const,\n message: request.message,\n end: request.end,\n callbacks: request.callbacks,\n })),\n ...this.getPendingRequests().map((request) => ({\n state: 'pending' as const,\n message: request.message,\n end: request.end,\n callbacks: request.callbacks,\n })),\n ];\n }\n\n /**\n * Checks if there are any pending requests, including ongoing subscriptions.\n */\n public hasPendingRequests() {\n return this.getPendingRequests().length > 0;\n }\n\n /**\n * Checks if there are any pending subscriptions\n */\n public hasPendingSubscriptions() {\n return this.getPendingRequests().some(\n (request) => request.message.method === 'subscription',\n );\n }\n\n /**\n * Checks if a message is still waiting to be sent.\n */\n public isOutgoing(message: TRPCClientOutgoingMessage) {\n return this.outgoingRequests.some((request) => request.message === message);\n }\n\n /**\n * Checks if there are any outgoing requests waiting to be sent.\n */\n public hasOutgoingRequests() {\n return this.outgoingRequests.length > 0;\n }\n\n /**\n * Checks if any request is outgoing or pending, including subscriptions.\n */\n public hasRequestsInFlight() {\n return this.hasOutgoingRequests() || this.hasPendingRequests();\n }\n}\n","import { behaviorSubject } from '@trpc/server/observable';\nimport type { UrlOptionsWithConnectionParams } from '../../internals/urlWithConnectionParams';\nimport type { Encoder } from './encoder';\nimport {\n buildConnectionMessage,\n prepareUrl,\n TRPCWebSocketClosedError,\n withResolvers,\n} from './utils';\n\n/**\n * Opens a WebSocket connection asynchronously and returns a promise\n * that resolves when the connection is successfully established.\n * The promise rejects if an error occurs during the connection attempt.\n */\nfunction asyncWsOpen(ws: WebSocket) {\n const { promise, resolve, reject } = withResolvers<void>();\n\n ws.addEventListener('open', () => {\n ws.removeEventListener('error', reject);\n resolve();\n });\n ws.addEventListener('error', reject);\n\n return promise;\n}\n\nconst pongCallbacks = new WeakMap<WebSocket, ((() => void) | null)[]>();\n\n/**\n * Sends \"PING\" on `ws` and calls `onPong`, if given, once its \"PONG\"\n * arrives. The server answers in order, so by then everything it sent before\n * it read this \"PING\" has arrived too.\n */\nexport function sendPing(ws: WebSocket, onPong: (() => void) | null) {\n let callbacks = pongCallbacks.get(ws);\n if (!callbacks) {\n const queue: ((() => void) | null)[] = [];\n callbacks = queue;\n pongCallbacks.set(ws, queue);\n ws.addEventListener('message', ({ data }) => {\n if (data === 'PONG') queue.shift()?.();\n });\n }\n callbacks.push(onPong);\n ws.send('PING');\n}\n\ninterface PingPongOptions {\n /**\n * The interval (in milliseconds) between \"PING\" messages.\n */\n intervalMs: number;\n\n /**\n * The timeout (in milliseconds) to wait for a \"PONG\" response before closing the connection.\n */\n pongTimeoutMs: number;\n}\n\n/**\n * Sets up a periodic ping-pong mechanism to keep the WebSocket connection alive.\n *\n * - Sends \"PING\" messages at regular intervals defined by `intervalMs`.\n * - If a \"PONG\" response is not received within the `pongTimeoutMs`, the WebSocket is closed.\n * - The ping timer resets upon receiving any message to maintain activity.\n * - Automatically starts the ping process when the WebSocket connection is opened.\n * - Cleans up timers when the WebSocket is closed.\n *\n * @param ws - The WebSocket instance to manage.\n * @param options - Configuration options for ping-pong intervals and timeouts.\n */\nfunction setupPingInterval(\n ws: WebSocket,\n { intervalMs, pongTimeoutMs }: PingPongOptions,\n onPongTimeout: () => void,\n) {\n let pingTimeout: ReturnType<typeof setTimeout> | undefined;\n let pongTimeout: ReturnType<typeof setTimeout> | undefined;\n\n function start() {\n pingTimeout = setTimeout(() => {\n sendPing(ws, null);\n pongTimeout = setTimeout(() => {\n // A socket that is already closing was closed on purpose.\n if (ws.readyState !== ws.OPEN) return;\n ws.close();\n onPongTimeout();\n }, pongTimeoutMs);\n }, intervalMs);\n }\n\n function reset() {\n clearTimeout(pingTimeout);\n start();\n }\n\n function pong() {\n clearTimeout(pongTimeout);\n reset();\n }\n\n ws.addEventListener('open', start);\n ws.addEventListener('message', ({ data }) => {\n clearTimeout(pingTimeout);\n start();\n\n if (data === 'PONG') {\n pong();\n }\n });\n ws.addEventListener('close', () => {\n clearTimeout(pingTimeout);\n clearTimeout(pongTimeout);\n });\n}\n\nexport interface WebSocketConnectionOptions {\n WebSocketPonyfill?: typeof WebSocket;\n urlOptions: UrlOptionsWithConnectionParams;\n keepAlive: PingPongOptions & {\n enabled: boolean;\n };\n encoder: Encoder;\n /**\n * Called when a keepAlive pong times out, once the socket is closing. Its\n * `close` event can come much later: an unresponsive server never answers\n * the closing handshake.\n */\n onPongTimeout: (ws: WebSocket) => void;\n}\n\n/**\n * Manages a WebSocket connection with support for reconnection, keep-alive mechanisms,\n * and observable state tracking.\n */\nexport class WsConnection {\n static connectCount = 0;\n public id = ++WsConnection.connectCount;\n\n private readonly WebSocketPonyfill: typeof WebSocket;\n private readonly urlOptions: UrlOptionsWithConnectionParams;\n private readonly keepAliveOpts: WebSocketConnectionOptions['keepAlive'];\n private readonly encoder: Encoder;\n private readonly onPongTimeout: WebSocketConnectionOptions['onPongTimeout'];\n public readonly wsObservable = behaviorSubject<WebSocket | null>(null);\n\n constructor(opts: WebSocketConnectionOptions) {\n this.WebSocketPonyfill = opts.WebSocketPonyfill ?? WebSocket;\n if (!this.WebSocketPonyfill) {\n throw new Error(\n \"No WebSocket implementation found - you probably don't want to use this on the server, but if you do you need to pass a `WebSocket`-ponyfill\",\n );\n }\n\n this.urlOptions = opts.urlOptions;\n this.keepAliveOpts = opts.keepAlive;\n this.encoder = opts.encoder;\n this.onPongTimeout = opts.onPongTimeout;\n }\n\n public get ws() {\n return this.wsObservable.get();\n }\n\n private set ws(ws) {\n this.wsObservable.next(ws);\n }\n\n /**\n * Checks if the WebSocket connection is open and ready to communicate.\n */\n public isOpen(): this is { ws: WebSocket } {\n return (\n !!this.ws &&\n this.ws.readyState === this.WebSocketPonyfill.OPEN &&\n !this.openPromise\n );\n }\n\n /**\n * Checks if the WebSocket connection is closed or in the process of closing.\n */\n public isClosed(): this is { ws: WebSocket } {\n return (\n !!this.ws &&\n (this.ws.readyState === this.WebSocketPonyfill.CLOSING ||\n this.ws.readyState === this.WebSocketPonyfill.CLOSED)\n );\n }\n\n /**\n * Manages the WebSocket opening process, ensuring that only one open operation\n * occurs at a time. Tracks the ongoing operation with `openPromise` to avoid\n * redundant calls and ensure proper synchronization.\n *\n * Sets up the keep-alive mechanism and necessary event listeners for the connection.\n *\n * @returns A promise that resolves once the WebSocket connection is successfully opened.\n */\n private openPromise: Promise<void> | null = null;\n public async open() {\n if (this.openPromise) return this.openPromise;\n\n this.id = ++WsConnection.connectCount;\n const wsPromise = prepareUrl(this.urlOptions).then(\n (url) => new this.WebSocketPonyfill(url),\n );\n const openPromise = wsPromise.then(async (ws) => {\n this.ws = ws;\n\n // Set binaryType to handle both text and binary messages consistently\n ws.binaryType = 'arraybuffer';\n\n // Setup ping listener\n ws.addEventListener('message', function ({ data }) {\n if (data === 'PING') {\n this.send('PONG');\n }\n });\n\n const abandoned = withResolvers<never>();\n if (this.keepAliveOpts.enabled) {\n setupPingInterval(ws, this.keepAliveOpts, () => {\n // A pong timeout gives up on an attempt still waiting on its\n // `connectionParams`, so the reconnect doesn't wait on them. The\n // attempt stays in `openPromise` until it rejects, so an `open()`\n // meanwhile, e.g. from `onClose`, gets that rejection instead of\n // starting another attempt on this connection.\n if (this.openPromise === openPromise) {\n abandoned.reject(\n new TRPCWebSocketClosedError({\n message: 'Pong timeout before connectionParams were sent',\n }),\n );\n }\n this.onPongTimeout(ws);\n });\n }\n\n ws.addEventListener('close', () => {\n if (this.ws === ws) {\n this.ws = null;\n }\n });\n\n await asyncWsOpen(ws);\n\n if (this.urlOptions.connectionParams) {\n ws.send(\n await Promise.race([\n buildConnectionMessage(\n this.urlOptions.connectionParams,\n this.encoder,\n ),\n abandoned.promise,\n ]),\n );\n }\n });\n this.openPromise = openPromise;\n\n try {\n await openPromise;\n } finally {\n if (this.openPromise === openPromise) {\n this.openPromise = null;\n }\n }\n }\n\n /**\n * Closes the WebSocket connection gracefully.\n * Waits for any ongoing open operation to complete before closing.\n */\n public async close() {\n try {\n await this.openPromise;\n } finally {\n this.ws?.close();\n }\n }\n}\n\n/**\n * Provides a backward-compatible representation of the connection state.\n */\nexport function backwardCompatibility(connection: WsConnection) {\n if (connection.isOpen()) {\n return {\n id: connection.id,\n state: 'open',\n ws: connection.ws,\n } as const;\n }\n\n if (connection.isClosed()) {\n return {\n id: connection.id,\n state: 'closed',\n ws: connection.ws,\n } as const;\n }\n\n if (!connection.ws) {\n return null;\n }\n\n return {\n id: connection.id,\n state: 'connecting',\n ws: connection.ws,\n } as const;\n}\n","import type { AnyTRPCRouter } from '@trpc/server';\nimport type { BehaviorSubject } from '@trpc/server/observable';\nimport { behaviorSubject, observable } from '@trpc/server/observable';\nimport type {\n CombinedDataTransformer,\n TRPCClientIncomingMessage,\n TRPCClientIncomingRequest,\n TRPCClientOutgoingMessage,\n TRPCResponseMessage,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n isObject,\n run,\n sleep,\n transformResult,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { TRPCClientError } from '../../../TRPCClientError';\nimport type { TRPCConnectionState } from '../../internals/subscriptions';\nimport type { Operation, OperationResultEnvelope } from '../../types';\nimport type { Encoder } from './encoder';\nimport { jsonEncoder } from './encoder';\nimport type { WebSocketClientOptions } from './options';\nimport { exponentialBackoff, keepAliveDefaults, lazyDefaults } from './options';\nimport type { TCallbacks } from './requestManager';\nimport { RequestManager } from './requestManager';\nimport {\n callUserCallback,\n ResettableTimeout,\n TRPCWebSocketClosedError,\n} from './utils';\nimport type { WebSocketConnectionOptions } from './wsConnection';\nimport { backwardCompatibility, sendPing, WsConnection } from './wsConnection';\n\nfunction isRequestId(value: unknown) {\n return (\n value === null || typeof value === 'string' || typeof value === 'number'\n );\n}\n\n/** A result's `type`; a missing one means `'data'`. */\nfunction isResultType(value: unknown) {\n return (\n value === undefined ||\n value === 'data' ||\n value === 'started' ||\n value === 'stopped'\n );\n}\n\n/**\n * A `reconnect` request from the server, or a response: a string, number or\n * `null` `id` and either a `result` object of a known `type` or an `error`.\n * The output transformer may serialize an error to any value, so\n * `transformResult` validates it.\n */\nfunction isIncomingMessage(value: unknown): value is TRPCClientIncomingMessage {\n if (!isObject(value)) return false;\n if ('method' in value) return value['method'] === 'reconnect';\n if (!isRequestId(value['id'])) return false;\n const result = value['result'];\n if (isObject(result)) return isResultType(result['type']);\n return result === undefined && 'error' in value;\n}\n\nfunction decodeIncomingMessage(\n encoder: Encoder,\n data: string | ArrayBuffer | Uint8Array,\n) {\n const message = encoder.decode(data);\n if (!isIncomingMessage(message)) {\n throw new TypeError('Expected a tRPC message');\n }\n return message;\n}\n\n/**\n * A WebSocket client for managing TRPC operations, supporting lazy initialization,\n * reconnection, keep-alive, and request management.\n */\nexport class WsClient {\n /**\n * Observable tracking the current connection state, including errors.\n */\n public readonly connectionState: BehaviorSubject<\n TRPCConnectionState<TRPCClientError<AnyTRPCRouter>>\n >;\n\n private allowReconnect = false;\n private requestManager = new RequestManager({\n onIdle: () => this.startInactivityTimeout(),\n });\n /**\n * The last id sent on the wire. Each request gets its own instead of its\n * `op.id`: a retry reuses the failed attempt's `op.id`, and the server's\n * late frames for that attempt must not reach the retry. A subscription\n * sent again after its socket was lost gets a new one for the same reason.\n */\n private lastRequestId = 0;\n private readonly connectionOptions: WebSocketConnectionOptions;\n /**\n * The connection new requests are sent on. A reconnect replaces it only\n * once the new connection is fully open, `connectionParams` included, so\n * until then requests keep going to the old one.\n */\n private activeConnection: WsConnection;\n private readonly reconnectRetryDelay: (attemptIndex: number) => number;\n private inactivityTimeout: ResettableTimeout;\n /**\n * Whether lazy mode may close the connection once it's idle: from the\n * first `open` until `close()`.\n */\n private inactivityTimeoutEnabled = false;\n private readonly callbacks: Pick<\n WebSocketClientOptions,\n 'onOpen' | 'onClose' | 'onError'\n >;\n private readonly lazyMode: boolean;\n private readonly encoder: Encoder;\n private readonly closeOnPongTimeout = new WeakMap<WebSocket, () => void>();\n\n constructor(opts: WebSocketClientOptions) {\n this.encoder = opts.experimental_encoder ?? jsonEncoder;\n // Initialize callbacks, connection parameters, and options.\n this.callbacks = {\n onOpen: opts.onOpen,\n onClose: opts.onClose,\n onError: opts.onError,\n };\n\n const lazyOptions = {\n ...lazyDefaults,\n ...opts.lazy,\n };\n\n // Set up inactivity timeout for lazy connections. It only runs while no\n // request or subscription is in flight; see `startInactivityTimeout()`.\n this.inactivityTimeout = new ResettableTimeout(() => {\n if (this.requestManager.hasRequestsInFlight()) {\n this.inactivityTimeout.stop();\n return;\n }\n\n this.close().catch(() => null);\n }, lazyOptions.closeMs);\n\n // Initialize the WebSocket connection.\n this.connectionOptions = {\n WebSocketPonyfill: opts.WebSocket,\n urlOptions: opts,\n keepAlive: {\n ...keepAliveDefaults,\n ...opts.keepAlive,\n },\n encoder: this.encoder,\n onPongTimeout: (ws) => this.closeOnPongTimeout.get(ws)?.(),\n };\n this.activeConnection = this.createConnection();\n this.reconnectRetryDelay = opts.retryDelayMs ?? exponentialBackoff;\n\n this.lazyMode = lazyOptions.enabled;\n\n this.connectionState = behaviorSubject<\n TRPCConnectionState<TRPCClientError<AnyTRPCRouter>>\n >({\n type: 'state',\n state: lazyOptions.enabled ? 'idle' : 'connecting',\n error: null,\n });\n\n // Automatically open the connection if lazy mode is disabled.\n if (!this.lazyMode) {\n this.open().catch(() => null);\n }\n }\n\n /**\n * Starts counting down to closing a lazy connection, if nothing is in\n * flight. Called on `open` and whenever the last request or subscription\n * ends, so the timer never has to poll.\n */\n private startInactivityTimeout() {\n if (\n !this.inactivityTimeoutEnabled ||\n this.requestManager.hasRequestsInFlight()\n ) {\n return;\n }\n this.inactivityTimeout.start();\n }\n\n private createConnection() {\n const connection = new WsConnection(this.connectionOptions);\n connection.wsObservable.subscribe({\n next: (ws) => {\n if (!ws) return;\n this.setupWebSocketListeners(ws);\n },\n });\n return connection;\n }\n\n /**\n * Opens the WebSocket connection. Handles reconnection attempts and updates\n * the connection state accordingly.\n */\n private async open() {\n this.allowReconnect = true;\n if (this.reconnecting) return this.reconnecting;\n this.connectionAttemptIndex = 0;\n if (this.connectionState.get().state === 'idle') {\n callUserCallback(() =>\n this.connectionState.next({\n type: 'state',\n state: 'connecting',\n error: null,\n }),\n );\n }\n\n try {\n await this.activeConnection.open();\n } catch (error) {\n this.reconnect(\n new TRPCWebSocketClosedError({\n message: 'Initialization error',\n cause: error,\n }),\n );\n // A socket whose `connectionParams` failed is open, but not usable.\n await this.activeConnection.close().catch(() => null);\n return this.reconnecting;\n }\n }\n\n /**\n * Closes the WebSocket connection and stops managing requests.\n * Ensures all outgoing and pending requests are properly finalized.\n */\n public async close() {\n this.allowReconnect = false;\n this.replacementError = null;\n this.retiredConnection = null;\n this.inactivityTimeoutEnabled = false;\n this.inactivityTimeout.stop();\n\n const requestsToAwait: Promise<void>[] = [];\n for (const request of this.requestManager.getRequests()) {\n if (request.message.method === 'subscription') {\n callUserCallback(() => request.callbacks.complete());\n } else if (request.state === 'outgoing') {\n callUserCallback(() =>\n request.callbacks.error(\n TRPCClientError.from(\n new TRPCWebSocketClosedError({\n message: 'Closed before connection was established',\n }),\n ),\n ),\n );\n } else {\n requestsToAwait.push(request.end);\n }\n }\n\n await Promise.all(requestsToAwait).catch(() => null);\n this.nextConnection?.ws?.close();\n await this.activeConnection.close().catch(() => null);\n\n callUserCallback(() =>\n this.connectionState.next({\n type: 'state',\n state: 'idle',\n error: null,\n }),\n );\n }\n\n /**\n * Method to request the server.\n * Handles data transformation, batching of requests, and subscription lifecycle.\n *\n * @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`.\n * @param transformer - Data transformer for serializing requests and deserializing responses\n * @param lastEventId - Optional ID of the last received event for subscriptions\n *\n * @returns An observable that emits operation results and handles cleanup\n */\n public request({\n op: { type, path, input, signal },\n transformer,\n lastEventId,\n }: {\n op: Pick<Operation, 'id' | 'type' | 'path' | 'input' | 'signal'>;\n transformer: CombinedDataTransformer;\n lastEventId?: string;\n }) {\n return observable<\n OperationResultEnvelope<unknown, TRPCClientError<AnyTRPCRouter>>,\n TRPCClientError<AnyTRPCRouter>\n >((observer) => {\n const message: TRPCClientOutgoingMessage = {\n id: ++this.lastRequestId,\n method: type,\n params: {\n input: transformer.input.serialize(input),\n path,\n lastEventId,\n },\n };\n const abort = this.batchSend(message, {\n ...observer,\n next(event) {\n let transformed: ReturnType<typeof transformResult>;\n try {\n transformed = transformResult(event, transformer.output);\n } catch (cause) {\n observer.error(TRPCClientError.from(cause as Error));\n return;\n }\n\n if (!transformed.ok) {\n observer.error(TRPCClientError.from(transformed.error));\n return;\n }\n\n observer.next({\n result: transformed.result,\n });\n },\n });\n\n const onAbort = () => observer.complete();\n if (signal?.aborted) {\n onAbort();\n } else {\n signal?.addEventListener('abort', onAbort, { once: true });\n }\n\n return () => {\n // A subscription sent again after its socket was lost has a new id.\n const { id } = message;\n const pending = this.requestManager.getPendingRequest(id);\n // Under its earlier ids, it may still be draining other sockets.\n const draining = this.requestManager\n .getDrainingRequests()\n .filter((request) => request.message === message);\n abort();\n\n if (type === 'subscription' && pending) {\n this.stopSubscription(id, pending.ws);\n this.stopSubscription(id, pending.successor);\n }\n this.closeIfDrained(pending?.ws);\n for (const request of [pending, ...draining]) {\n for (const earlier of request?.movedFrom ?? []) {\n this.closeIfDrained(earlier);\n }\n }\n\n signal?.removeEventListener('abort', onAbort);\n };\n });\n }\n\n /**\n * The current WebSocket and its state, or `null` when there is no socket.\n */\n public get connection() {\n return backwardCompatibility(\n this.activeConnection.ws\n ? this.activeConnection\n : (this.nextConnection ?? this.activeConnection),\n );\n }\n\n /**\n * Manages the reconnection process for the WebSocket using retry logic.\n * Ensures that only one reconnection attempt is active at a time by tracking the current\n * reconnection state in the `reconnecting` promise.\n */\n private reconnecting: Promise<void> | null = null;\n /**\n * The connection a reconnect is opening to replace the active one.\n */\n private nextConnection: WsConnection | null = null;\n /**\n * The connection the active one replaced, while it's open. If the active\n * one is lost first, this one serves every request again until the next.\n */\n private retiredConnection: WsConnection | null = null;\n /**\n * Why the latest attempt to replace a socket that's still open failed.\n * It's shown once that socket closes, since until then it serves every\n * request.\n */\n private replacementError: TRPCWebSocketClosedError | null = null;\n /**\n * The retry attempt that opened the current connection.\n */\n private connectionAttemptIndex = 0;\n /**\n * Set when the server rejects the current connection with an `id: null`\n * error, e.g. because `createContext` threw. The server closes the socket\n * right after, so the reconnect that follows carries on with the backoff\n * instead of starting over at attempt 0. Cleared again when the socket\n * receives a result, which proves the connection was accepted. Also set\n * on a keepAlive pong timeout when the socket never received anything.\n * @see https://github.com/trpc/trpc/issues/4774\n */\n private connectionRejected = false;\n /** Subscriptions whose subscriber has seen `started`. */\n private readonly started = new WeakSet<TRPCClientOutgoingMessage>();\n\n /**\n * Opens a new connection, retrying until one opens. While the current\n * socket is open, it keeps serving every request, new ones included, until\n * the new one is fully open, `connectionParams` included.\n *\n * @param closedError - Why the current socket was lost, or `null` when it's\n * still open and serving requests, e.g. on a server-requested reconnect.\n */\n private reconnect(closedError: TRPCWebSocketClosedError | null) {\n if (!this.allowReconnect) {\n return;\n }\n\n if (closedError) {\n const error = this.replacementError ?? closedError;\n this.replacementError = null;\n callUserCallback(() =>\n this.connectionState.next({\n type: 'state',\n state: 'connecting',\n error: TRPCClientError.from(error),\n }),\n );\n }\n if (this.reconnecting) return;\n\n const tryReconnect = async (attemptIndex: number) => {\n try {\n await sleep(this.reconnectRetryDelay(attemptIndex));\n if (this.allowReconnect) {\n const next = this.createConnection();\n this.nextConnection = next;\n try {\n await next.open();\n // `open()` resolves even if the socket closed while its\n // `connectionParams` were pending.\n if (!next.isOpen()) {\n throw new Error('WebSocket closed before it was ready');\n }\n } catch (error) {\n await next.close().catch(() => null);\n throw error;\n } finally {\n this.nextConnection = null;\n }\n\n if (this.allowReconnect) {\n // Read only now: losing the active socket while `next` opened may\n // have restored the one it replaced.\n const previous = this.activeConnection;\n this.activeConnection = next;\n this.retiredConnection = previous.isOpen() ? previous : null;\n this.connectionAttemptIndex = attemptIndex;\n this.replacementError = null;\n this.handOff(previous.ws);\n } else {\n await next.close();\n }\n }\n this.reconnecting = null;\n } catch (error) {\n const closedError = new TRPCWebSocketClosedError({\n message: 'Initialization error',\n cause: error,\n });\n if (this.allowReconnect && this.activeConnection.isOpen()) {\n // The old socket keeps serving every request, so this is shown only\n // once it closes.\n this.replacementError = closedError;\n } else if (this.allowReconnect) {\n callUserCallback(() =>\n this.connectionState.next({\n type: 'state',\n state: 'connecting',\n error: TRPCClientError.from(closedError),\n }),\n );\n }\n await tryReconnect(attemptIndex + 1);\n }\n };\n\n this.reconnecting = tryReconnect(\n this.connectionRejected ? this.connectionAttemptIndex + 1 : 0,\n );\n }\n\n /**\n * Moves the pending subscriptions to the active socket, which has just\n * opened: each is resubscribed with the id of the last event it delivered.\n * A subscription whose old socket is still open keeps delivering from it\n * until the new socket confirms it with `started`; see `confirmMove()`.\n * Closes the previous socket once nothing is left on it.\n */\n private handOff(previous: WebSocket | null) {\n if (\n this.connectionState.get().state !== 'pending' &&\n this.activeConnection.isOpen()\n ) {\n callUserCallback(() =>\n this.connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n }),\n );\n }\n\n const ws = this.activeConnection.ws;\n const subscriptions = this.requestManager\n .getPendingRequests()\n .filter(\n (request) =>\n request.message.method === 'subscription' && request.ws !== ws,\n );\n if (subscriptions.length) {\n this.send(subscriptions.map(({ message }) => message));\n for (const request of subscriptions) {\n // The socket it was moving to hasn't started it, and won't be used.\n this.stopSubscription(request.message.id, request.successor);\n if (request.ws && request.ws.readyState === request.ws.OPEN) {\n request.successor = ws;\n request.overlapEventIds = new Set();\n } else {\n // Its socket was lost, so it starts again.\n this.started.delete(request.message);\n request.ws = ws;\n request.successor = null;\n }\n }\n }\n this.closeIfDrained(previous);\n }\n\n /**\n * Completes a subscription's move once its new socket has confirmed it:\n * stops it on the old socket, whose later messages for it are dropped\n * apart from events without ids, and closes that socket once everything it\n * sent before the stop has arrived and nothing else is left on it.\n */\n private confirmMove(request: {\n message: TRPCClientOutgoingMessage;\n ws: WebSocket | null;\n successor: WebSocket | null;\n movedFrom: Set<WebSocket>;\n }) {\n const previous = request.ws;\n request.ws = request.successor;\n request.successor = null;\n if (previous && this.stopSubscription(request.message.id, previous)) {\n request.movedFrom.add(previous);\n // `stopped` can wait on the procedure, but the \"PONG\" can't.\n sendPing(previous, () => this.releaseMovedFrom(request, previous));\n }\n this.closeIfDrained(previous);\n }\n\n private releaseMovedFrom(\n request: { movedFrom: Set<WebSocket> },\n ws: WebSocket,\n ) {\n if (!request.movedFrom.delete(ws)) return;\n this.requestManager.deleteDrained();\n this.closeIfDrained(ws);\n }\n\n private hasRequestsOn(ws: WebSocket | null) {\n return [\n ...this.requestManager.getPendingRequests(),\n ...this.requestManager.getDrainingRequests(),\n ].some(\n (request) =>\n request.ws === ws || (ws !== null && request.movedFrom.has(ws)),\n );\n }\n\n /**\n * Closes `ws` once it's been replaced and nothing is left on it.\n */\n private closeIfDrained(ws: WebSocket | null | undefined) {\n if (!ws || ws === this.activeConnection.ws) return;\n if (this.hasRequestsOn(ws)) return;\n ws.close();\n }\n\n /**\n * Stops a subscription on the socket it was sent on, if that's still open.\n *\n * @returns Whether the stop was sent.\n */\n private stopSubscription(\n id: TRPCClientOutgoingMessage['id'],\n ws: WebSocket | null,\n ) {\n if (!ws || ws.readyState !== ws.OPEN) return false;\n ws.send(this.encoder.encode({ id, method: 'subscription.stop' }));\n return true;\n }\n\n /**\n * Fails the pending queries and mutations sent on `ws`, and returns its\n * pending subscriptions, which are kept to be sent again.\n */\n private failPendingRequests(ws: WebSocket, cause: unknown) {\n const subscriptions = [];\n for (const request of this.requestManager.getPendingRequests()) {\n const { message, callbacks } = request;\n if (request.ws !== ws) continue;\n if (message.method === 'subscription') {\n subscriptions.push(request);\n continue;\n }\n\n callUserCallback(() =>\n callbacks.error(\n TRPCClientError.from(\n cause ??\n new TRPCWebSocketClosedError({\n message: 'WebSocket closed',\n cause,\n }),\n ),\n ),\n );\n this.requestManager.delete(message);\n }\n return subscriptions;\n }\n\n private setupWebSocketListeners(ws: WebSocket) {\n this.connectionRejected = false;\n\n /**\n * Fails the queries and mutations sent on `ws`. Its subscriptions are\n * sent again on the active socket if that's open, or else by\n * `reconnect()` once the next one opens.\n */\n const handleCloseOrError = (cause: unknown) => {\n if (ws === this.retiredConnection?.ws) this.retiredConnection = null;\n const retired = this.retiredConnection;\n let restored = false;\n if (ws === this.activeConnection.ws && retired?.isOpen()) {\n restored = true;\n // The socket it replaced serves every request again, until the next\n // one opens.\n this.activeConnection = retired;\n this.retiredConnection = null;\n this.replacementError = new TRPCWebSocketClosedError({\n message: 'WebSocket closed',\n cause,\n });\n }\n for (const request of this.requestManager.getPendingRequests()) {\n if (request.successor === ws) {\n // Its old socket still has it.\n request.successor = null;\n request.overlapEventIds = null;\n }\n request.movedFrom.delete(ws);\n }\n for (const request of this.requestManager.getDrainingRequests()) {\n request.movedFrom.delete(ws);\n }\n this.requestManager.deleteDrained();\n const lost = this.failPendingRequests(ws, cause).filter((request) => {\n if (!request.successor) return true;\n // Its new socket has it already.\n request.ws = request.successor;\n request.successor = null;\n return false;\n });\n if (\n ws === this.activeConnection.ws ||\n (this.reconnecting && !this.activeConnection.isOpen())\n ) {\n return;\n }\n\n for (const { message, callbacks } of lost) {\n this.started.delete(message);\n // The active socket may still have its old id, e.g. while stopping it.\n this.requestManager.requeue(message, ++this.lastRequestId);\n this.flushOutgoing(message, callbacks);\n }\n if (restored) this.reconnect(null);\n };\n\n ws.addEventListener('open', () => {\n run(async () => {\n if (this.lazyMode) {\n this.inactivityTimeoutEnabled = true;\n this.startInactivityTimeout();\n }\n\n this.callbacks.onOpen?.();\n\n // A socket opened to replace one that's still open changes nothing\n // the subscribers can see until `handOff()` puts it in use.\n if (\n this.connectionState.get().state === 'pending' ||\n (ws !== this.activeConnection.ws && this.activeConnection.isOpen())\n ) {\n return;\n }\n callUserCallback(() =>\n this.connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n }),\n );\n }).catch((error) => {\n ws.close(3000);\n handleCloseOrError(error);\n });\n });\n\n // Set on the socket's `close` event, or earlier when the client gives up\n // on the socket (a keepAlive pong timeout or an undecodable frame) without\n // waiting for the closing handshake. The socket's later frames and events\n // must not reach the requests resent by then.\n let closed = false;\n let answered = false;\n\n /**\n * Runs the socket's close handling once: `cause` fails its queries and\n * mutations, and `event` goes to `onClose`.\n */\n const handleClose = (\n cause: unknown,\n event: CloseEvent | { code: number },\n ) => {\n if (closed) return;\n closed = true;\n handleCloseOrError(cause);\n callUserCallback(() => this.callbacks.onClose?.(event));\n\n if (\n ws === this.activeConnection.ws &&\n (!this.lazyMode || this.requestManager.hasPendingSubscriptions())\n ) {\n this.reconnect(\n new TRPCWebSocketClosedError({\n message: 'WebSocket closed',\n cause,\n }),\n );\n }\n };\n // What `close` reports when the closing handshake doesn't complete.\n const abandonedEvent = { code: 1006 };\n\n const onMessage = ({ data }: MessageEvent) => {\n if (closed) return;\n answered = true;\n this.inactivityTimeout.reset();\n\n // Handle PING/PONG as text regardless of encoder\n if (['PING', 'PONG'].includes(data)) return;\n\n let incomingMessage: TRPCClientIncomingMessage;\n try {\n incomingMessage = decodeIncomingMessage(this.encoder, data);\n } catch (cause) {\n // The frame may have carried a response, and its request would wait\n // forever, so this socket is treated as lost.\n ws.close();\n handleClose(\n new TRPCWebSocketClosedError({\n message: 'Received a message that could not be decoded',\n cause,\n }),\n abandonedEvent,\n );\n // Rethrown asynchronously by `callUserCallback()` below.\n throw cause;\n }\n if ('method' in incomingMessage) {\n if (ws === this.activeConnection.ws) {\n this.handleIncomingRequest(incomingMessage);\n }\n return;\n }\n\n // A replaced socket still answers its own queries and mutations, but\n // says nothing about the connection the client now uses.\n const isRetired =\n ws !== this.activeConnection.ws && ws !== this.nextConnection?.ws;\n if (\n !isRetired &&\n incomingMessage.id === null &&\n 'error' in incomingMessage\n ) {\n this.connectionRejected = true;\n } else if (!isRetired && 'result' in incomingMessage) {\n // The server only sends results once `createContext` has succeeded,\n // so an earlier `id: null` error on this socket was not a rejection,\n // e.g. the server's reply to a malformed frame.\n this.connectionRejected = false;\n }\n\n this.handleResponseMessage(incomingMessage, ws);\n };\n // With `ws`, a throw from a `message` listener stops the socket from\n // reading any further frames while it stays open.\n ws.addEventListener('message', (event) => {\n callUserCallback(() => onMessage(event));\n });\n\n ws.addEventListener('close', (event) => handleClose(event, event));\n this.closeOnPongTimeout.set(ws, () => {\n // A server that never answered, not even a ping, gets the same backoff\n // as one that rejected the connection.\n if (!answered) this.connectionRejected = true;\n handleClose(abandonedEvent, abandonedEvent);\n });\n\n ws.addEventListener('error', (event) => {\n if (closed) return;\n handleCloseOrError(event);\n callUserCallback(() => this.callbacks.onError?.(event));\n\n if (ws !== this.activeConnection.ws) return;\n\n this.reconnect(\n new TRPCWebSocketClosedError({\n message: 'WebSocket closed',\n cause: event,\n }),\n );\n });\n }\n\n private handleResponseMessage(message: TRPCResponseMessage, ws: WebSocket) {\n const request =\n this.requestManager.getPendingRequest(message.id) ??\n this.requestManager.getDrainingRequest(message.id);\n if (!request) return;\n const result = 'result' in message ? message.result : null;\n if (request.successor === ws) {\n this.confirmMove(request);\n } else if (request.ws !== ws) {\n // A subscription moved to a new socket ignores the old one's frames,\n // apart from events without ids until it's stopped there: those can't\n // be replayed, and the new socket may have started listening after\n // the old one sent them.\n if (request.movedFrom.has(ws)) {\n if (result?.type === 'stopped') {\n this.releaseMovedFrom(request, ws);\n } else if (result?.type === 'data' && result.id === undefined) {\n callUserCallback(() => request.callbacks.next(message));\n }\n }\n return;\n }\n // The subscriber doesn't see a move, even one its old socket didn't\n // live to finish.\n if (result?.type === 'started' && this.started.has(request.message)) {\n return;\n }\n\n if (result?.type === 'data' && result.id !== undefined) {\n const eventId = String(result.id);\n if (request.successor) {\n request.overlapEventIds?.add(eventId);\n } else if (request.overlapEventIds?.delete(eventId)) {\n // Already delivered by the old socket.\n return;\n }\n }\n\n callUserCallback(() => request.callbacks.next(message));\n\n let completed = true;\n if ('result' in message && request.message.method === 'subscription') {\n if (message.result.type === 'data') {\n // An event without an id keeps the last tracked id, so a reconnect\n // still resumes after it, as with `httpSubscriptionLink`.\n if (message.result.id !== undefined) {\n request.message.params.lastEventId = message.result.id;\n }\n } else if (message.result.type === 'started') {\n this.started.add(request.message);\n }\n\n if (message.result.type !== 'stopped') {\n completed = false;\n }\n }\n\n if (completed) {\n callUserCallback(() => request.callbacks.complete());\n this.requestManager.delete(request.message);\n }\n }\n\n private handleIncomingRequest(message: TRPCClientIncomingRequest) {\n if (message.method === 'reconnect') {\n this.reconnect(null);\n }\n }\n\n /**\n * Sends a message or batch of messages directly to the server.\n */\n private send(\n messageOrMessages: TRPCClientOutgoingMessage | TRPCClientOutgoingMessage[],\n ) {\n if (!this.activeConnection.isOpen()) {\n throw new Error('Active connection is not open');\n }\n\n const messages =\n messageOrMessages instanceof Array\n ? messageOrMessages\n : [messageOrMessages];\n this.activeConnection.ws.send(\n this.encoder.encode(messages.length === 1 ? messages[0] : messages),\n );\n }\n\n /**\n * Groups requests for batch sending.\n *\n * @returns A function to abort the batched request.\n */\n private batchSend(message: TRPCClientOutgoingMessage, callbacks: TCallbacks) {\n // Started again once the last request or subscription ends.\n this.inactivityTimeout.stop();\n this.flushOutgoing(message, callbacks);\n return this.requestManager.register(message, callbacks);\n }\n\n /**\n * Sends `message` with the other outgoing requests once the connection is\n * open, batching those queued in the same tick.\n */\n private flushOutgoing(\n message: TRPCClientOutgoingMessage,\n callbacks: TCallbacks,\n ) {\n run(async () => {\n // During a reconnect, requests go to the old socket while it's open.\n do {\n if (!this.activeConnection.isOpen()) {\n await this.open();\n }\n await sleep(0);\n } while (!this.activeConnection.isOpen() && this.reconnecting);\n\n if (!this.requestManager.hasOutgoingRequests()) return;\n // Another run already sent this request. Each queued request's own run\n // sends it once the new socket opens.\n if (\n !this.activeConnection.isOpen() &&\n !this.requestManager.isOutgoing(message)\n ) {\n return;\n }\n\n const requests = this.requestManager.flush(this.activeConnection.ws);\n try {\n this.send(requests.map((request) => request.message));\n } catch (err) {\n for (const request of requests) {\n this.requestManager.delete(request.message);\n callUserCallback(() =>\n request.callbacks.error(TRPCClientError.from(err as Error)),\n );\n }\n }\n }).catch((err) => {\n this.requestManager.delete(message);\n callUserCallback(() => callbacks.error(TRPCClientError.from(err)));\n });\n }\n}\n","import type { Encoder } from './wsClient/encoder';\nimport { jsonEncoder } from './wsClient/encoder';\nimport type { WebSocketClientOptions } from './wsClient/options';\nimport { WsClient } from './wsClient/wsClient';\n\n/**\n * Opens and manages a WebSocket connection to a tRPC server. Pass it to\n * `wsLink`.\n *\n * @see https://trpc.io/docs/client/links/wsLink#wslink--createwsclient-options\n */\nexport function createWSClient(opts: WebSocketClientOptions) {\n return new WsClient(opts);\n}\n\n/**\n * The client returned by {@link createWSClient}.\n */\nexport type TRPCWebSocketClient = ReturnType<typeof createWSClient>;\n\nexport { jsonEncoder, type Encoder, type WebSocketClientOptions };\n","import type { Unsubscribable } from '@trpc/server/observable';\nimport { observable } from '@trpc/server/observable';\nimport type {\n AnyRouter,\n inferClientTypes,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type { TransformerOptions } from '../../unstable-internals';\nimport { getTransformer } from '../../unstable-internals';\nimport type { TRPCLink } from '../types';\nimport type {\n Encoder,\n TRPCWebSocketClient,\n WebSocketClientOptions,\n} from './createWsClient';\nimport { createWSClient, jsonEncoder } from './createWsClient';\nimport { callUserCallback } from './wsClient/utils';\n\n/**\n * Options for {@link wsLink}.\n *\n * @see https://trpc.io/docs/client/links/wsLink#wslink--createwsclient-options\n */\nexport type WebSocketLinkOptions<TRouter extends AnyRouter> = {\n /**\n * The client made with `createWSClient`.\n */\n client: TRPCWebSocketClient;\n} & TransformerOptions<inferClientTypes<TRouter>>;\n\n/**\n * A terminating link that sends calls over a WebSocket.\n *\n * @see https://trpc.io/docs/client/links/wsLink\n */\nexport function wsLink<TRouter extends AnyRouter>(\n opts: WebSocketLinkOptions<TRouter>,\n): TRPCLink<TRouter> {\n const { client } = opts;\n const transformer = getTransformer(opts.transformer);\n return () => {\n return ({ op }) => {\n return observable((observer) => {\n let connStateSubscription: Unsubscribable | null = null;\n if (op.type === 'subscription') {\n // The current state is sent during `subscribe`, and a throwing\n // `onConnectionStateChange` must not stop the request below from\n // being sent. The client guards the states it sends later.\n let isSubscribing = true;\n connStateSubscription = client.connectionState.subscribe({\n next(result) {\n const emit = () =>\n observer.next({\n result,\n context: op.context,\n });\n if (isSubscribing) {\n callUserCallback(emit);\n } else {\n emit();\n }\n },\n });\n isSubscribing = false;\n }\n\n const requestSubscription = client\n .request({\n op,\n transformer,\n })\n .subscribe(observer);\n\n return () => {\n requestSubscription.unsubscribe();\n connStateSubscription?.unsubscribe();\n };\n });\n };\n };\n}\n\nexport {\n createWSClient,\n jsonEncoder,\n type Encoder,\n type TRPCWebSocketClient,\n type WebSocketClientOptions,\n};\n"],"mappings":";;;;;;;;;AAOA,MAAa,cAAuB;CAClC,SAAS,SAAS,KAAK,UAAU,IAAI;CACrC,SAAS,SAAS;EAChB,IAAI,OAAO,SAAS,UAClB,MAAM,IAAI,MACR,gGAEF;EAEF,OAAO,KAAK,MAAM,IAAI;CACxB;AACF;;AC0DA,MAAa,eAA4B;CACvC,SAAS;CACT,SAAS;AACX;AASA,MAAa,oBAAsC;CACjD,SAAS;CACT,eAAe;CACf,YAAY;AACd;;;;;;AAOA,MAAa,sBAAsB,iBAAyB;CAC1D,OAAO,iBAAiB,IAAI,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BAAgB;KACpB,wBAAwB,OAAO,gBAAgB,UAAU,EACvD,KAAK,QAAQ;MACX,MAAM,aACJ,SAAS,KAAK;OACZ;OACA,SAAS,GAAG;MACd,CAAC;MACH,IAAI,eACF,iBAAiB,IAAI;WAErB,KAAK;KAET,EACF,CAAC;KACD,gBAAgB;IAClB;IAEA,MAAM,sBAAsB,OACzB,QAAQ;KACP;KACA;IACF,CAAC,CAAC,CACD,UAAU,QAAQ;IAErB,aAAa;KACX,oBAAoB,YAAY;KAChC,0BAAA,QAAA,0BAAA,KAAA,KAAA,sBAAuB,YAAY;IACrC;GACF,CAAC;EACH;CACF;AACF"}
|
|
@@ -1032,8 +1032,9 @@ var WsClient = class {
|
|
|
1032
1032
|
callUserCallback(() => request.callbacks.next(message));
|
|
1033
1033
|
let completed = true;
|
|
1034
1034
|
if ("result" in message && request.message.method === "subscription") {
|
|
1035
|
-
if (message.result.type === "data")
|
|
1036
|
-
|
|
1035
|
+
if (message.result.type === "data") {
|
|
1036
|
+
if (message.result.id !== void 0) request.message.params.lastEventId = message.result.id;
|
|
1037
|
+
} else if (message.result.type === "started") this.started.add(request.message);
|
|
1037
1038
|
if (message.result.type !== "stopped") completed = false;
|
|
1038
1039
|
}
|
|
1039
1040
|
if (completed) {
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@trpc/client",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "11.31.
|
|
5
|
+
"version": "11.31.4",
|
|
6
6
|
"description": "The tRPC client library",
|
|
7
7
|
"author": "KATT",
|
|
8
8
|
"license": "MIT",
|
|
@@ -100,12 +100,12 @@
|
|
|
100
100
|
"skills"
|
|
101
101
|
],
|
|
102
102
|
"peerDependencies": {
|
|
103
|
-
"@trpc/server": "11.31.
|
|
103
|
+
"@trpc/server": "11.31.4",
|
|
104
104
|
"typescript": ">=5.7.2"
|
|
105
105
|
},
|
|
106
106
|
"devDependencies": {
|
|
107
107
|
"@tanstack/intent": "0.5.6",
|
|
108
|
-
"@trpc/server": "11.31.
|
|
108
|
+
"@trpc/server": "11.31.4",
|
|
109
109
|
"@types/isomorphic-fetch": "^0.0.39",
|
|
110
110
|
"@types/node": "^24.19.2",
|
|
111
111
|
"dataloader": "^2.2.3",
|
package/skills/links/SKILL.md
CHANGED
package/src/links/localLink.ts
CHANGED
|
@@ -3,7 +3,12 @@ import {
|
|
|
3
3
|
getTRPCErrorShape,
|
|
4
4
|
isTrackedEnvelope,
|
|
5
5
|
} from '@trpc/server';
|
|
6
|
-
import {
|
|
6
|
+
import {
|
|
7
|
+
behaviorSubject,
|
|
8
|
+
isObservable,
|
|
9
|
+
observable,
|
|
10
|
+
observableToAsyncIterable,
|
|
11
|
+
} from '@trpc/server/observable';
|
|
7
12
|
import { TRPC_ERROR_CODES_BY_KEY, type TRPCResult } from '@trpc/server/rpc';
|
|
8
13
|
import {
|
|
9
14
|
callProcedure,
|
|
@@ -239,9 +244,12 @@ export function localLink<TRouter extends AnyRouter>(
|
|
|
239
244
|
// observer to still be open by the time it runs
|
|
240
245
|
await run(async () => {
|
|
241
246
|
while (true) {
|
|
242
|
-
const
|
|
247
|
+
const procedureResult = await runProcedure(
|
|
243
248
|
inputWithTrackedEventId(op.input, lastEventId),
|
|
244
249
|
);
|
|
250
|
+
const result = isObservable(procedureResult)
|
|
251
|
+
? observableToAsyncIterable(procedureResult, signal)
|
|
252
|
+
: procedureResult;
|
|
245
253
|
if (!isAsyncIterable(result)) {
|
|
246
254
|
throw new Error('Expected an async iterable');
|
|
247
255
|
}
|
|
@@ -887,7 +887,11 @@ export class WsClient {
|
|
|
887
887
|
let completed = true;
|
|
888
888
|
if ('result' in message && request.message.method === 'subscription') {
|
|
889
889
|
if (message.result.type === 'data') {
|
|
890
|
-
|
|
890
|
+
// An event without an id keeps the last tracked id, so a reconnect
|
|
891
|
+
// still resumes after it, as with `httpSubscriptionLink`.
|
|
892
|
+
if (message.result.id !== undefined) {
|
|
893
|
+
request.message.params.lastEventId = message.result.id;
|
|
894
|
+
}
|
|
891
895
|
} else if (message.result.type === 'started') {
|
|
892
896
|
this.started.add(request.message);
|
|
893
897
|
}
|