@trpc/tanstack-react-query
Version:
TanStack React Query Integration for tRPC
1,005 lines (1,004 loc) • 37.4 kB
JavaScript
//#region \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
let react = require("react");
react = __toESM(react, 1);
let _trpc_client = require("@trpc/client");
let _trpc_server = require("@trpc/server");
let _tanstack_react_query = require("@tanstack/react-query");
let _trpc_server_unstable_core_do_not_import = require("@trpc/server/unstable-core-do-not-import");
//#region \0@oxc-project+runtime@0.149.0/helpers/esm/typeof.js
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
return typeof o;
} : function(o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, _typeof(o);
}
//#endregion
//#region \0@oxc-project+runtime@0.149.0/helpers/esm/toPrimitive.js
function toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != _typeof(i)) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
//#endregion
//#region \0@oxc-project+runtime@0.149.0/helpers/esm/toPropertyKey.js
function toPropertyKey(t) {
var i = toPrimitive(t, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
//#endregion
//#region \0@oxc-project+runtime@0.149.0/helpers/esm/defineProperty.js
function _defineProperty(e, r, t) {
return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[r] = t, e;
}
//#endregion
//#region \0@oxc-project+runtime@0.149.0/helpers/esm/objectSpread2.js
function ownKeys(e, r) {
var t = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
r && (o = o.filter(function(r) {
return Object.getOwnPropertyDescriptor(e, r).enumerable;
})), t.push.apply(t, o);
}
return t;
}
function _objectSpread2(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys(Object(t), !0).forEach(function(r) {
_defineProperty(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
//#endregion
//#region \0@oxc-project+runtime@0.149.0/helpers/esm/asyncIterator.js
function _asyncIterator(r) {
var n, t, o, e = 2;
for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) {
if (t && null != (n = r[t])) return n.call(r);
if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));
t = "@@asyncIterator", o = "@@iterator";
}
throw new TypeError("Object is not async iterable");
}
function AsyncFromSyncIterator(r) {
function AsyncFromSyncIteratorContinuation(r) {
if (Object(r) !== r) return Promise.reject(/* @__PURE__ */ new TypeError(r + " is not an object."));
var n = r.done;
return Promise.resolve(r.value).then(function(r) {
return {
value: r,
done: n
};
});
}
return AsyncFromSyncIterator = function AsyncFromSyncIterator(r) {
this.s = r, this.n = r.next;
}, AsyncFromSyncIterator.prototype = {
s: null,
n: null,
next: function next() {
return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
},
"return": function _return(r) {
var n = this.s["return"];
return void 0 === n ? Promise.resolve({
value: r,
done: !0
}) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
},
"throw": function _throw(r) {
var n = this.s["return"];
return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
}
}, new AsyncFromSyncIterator(r);
}
//#endregion
//#region \0@oxc-project+runtime@0.149.0/helpers/esm/objectWithoutPropertiesLoose.js
function _objectWithoutPropertiesLoose(r, e) {
if (null == r) return {};
var t = {};
for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
if (e.includes(n)) continue;
t[n] = r[n];
}
return t;
}
//#endregion
//#region \0@oxc-project+runtime@0.149.0/helpers/esm/objectWithoutProperties.js
function _objectWithoutProperties(e, t) {
if (null == e) return {};
var o, r, i = _objectWithoutPropertiesLoose(e, t);
if (Object.getOwnPropertySymbols) {
var s = Object.getOwnPropertySymbols(e);
for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
}
return i;
}
//#endregion
//#region src/internals/utils.ts
const _excluded = ["cursor", "direction"];
/**
* @internal
*/
function createTRPCOptionsResult(value) {
return { path: value.path.join(".") };
}
function isPrefixedQueryKey(queryKey) {
return queryKey.length >= 3;
}
function readQueryKey(queryKey) {
if (isPrefixedQueryKey(queryKey)) return {
type: "prefixed",
prefix: queryKey[0],
path: queryKey[1],
args: queryKey[2]
};
else return {
type: "unprefixed",
prefix: void 0,
path: queryKey[0],
args: queryKey[1]
};
}
/**
* @internal
*/
function getClientArgs(queryKey, opts, infiniteParams) {
var _queryKeyData$args;
const queryKeyData = readQueryKey(queryKey);
let input = (_queryKeyData$args = queryKeyData.args) === null || _queryKeyData$args === void 0 ? void 0 : _queryKeyData$args.input;
if (infiniteParams) {
var _queryKeyData$args$in, _queryKeyData$args2;
input = _objectSpread2(_objectSpread2(_objectSpread2({}, (_queryKeyData$args$in = (_queryKeyData$args2 = queryKeyData.args) === null || _queryKeyData$args2 === void 0 ? void 0 : _queryKeyData$args2.input) !== null && _queryKeyData$args$in !== void 0 ? _queryKeyData$args$in : {}), infiniteParams.pageParam !== void 0 ? { cursor: infiniteParams.pageParam } : {}), {}, { direction: infiniteParams.direction });
}
return [
queryKeyData.path.join("."),
input,
opts === null || opts === void 0 ? void 0 : opts.trpc
];
}
/**
* @internal
*/
async function buildQueryFromAsyncIterable(asyncIterable, queryClient, queryKey) {
const query = queryClient.getQueryCache().build(queryClient, { queryKey });
query.setState({
data: [],
status: "success"
});
const aggregate = [];
var _iteratorAbruptCompletion = false;
var _didIteratorError = false;
var _iteratorError;
try {
for (var _iterator = _asyncIterator(asyncIterable), _step; _iteratorAbruptCompletion = !(_step = await _iterator.next()).done; _iteratorAbruptCompletion = false) {
const value = _step.value;
aggregate.push(value);
query.setState({ data: [...aggregate] });
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (_iteratorAbruptCompletion && _iterator.return != null) await _iterator.return();
} finally {
if (_didIteratorError) throw _iteratorError;
}
}
return aggregate;
}
/**
* To allow easy interactions with groups of related queries, such as
* invalidating all queries of a router, we use an array as the path when
* storing in tanstack query.
*
* @internal
*/
function getQueryKeyInternal(opts) {
const key = (0, _trpc_server_unstable_core_do_not_import.run)(() => {
const { input, type } = opts;
const splitPath = opts.path.flatMap((part) => part.split("."));
if (typeof input === "undefined" && type === "any") return splitPath.length ? [splitPath] : [];
if (type === "infinite" && (0, _trpc_server_unstable_core_do_not_import.isObject)(input) && ("direction" in input || "cursor" in input)) {
const { cursor: _, direction: __ } = input;
return [splitPath, {
input: _objectWithoutProperties(input, _excluded),
type: "infinite"
}];
}
return [splitPath, _objectSpread2(_objectSpread2({}, typeof input !== "undefined" && input !== _tanstack_react_query.skipToken && { input }), type && type !== "any" && { type })];
});
if (opts.prefix) key.unshift([opts.prefix]);
return key;
}
/**
* @internal
*/
function getMutationKeyInternal(opts) {
const key = [opts.path.flatMap((part) => part.split("."))];
if (opts.prefix) key.unshift([opts.prefix]);
return key;
}
/**
* @internal
*/
function unwrapLazyArg(valueOrLazy) {
return (0, _trpc_server_unstable_core_do_not_import.isFunction)(valueOrLazy) ? valueOrLazy() : valueOrLazy;
}
//#endregion
//#region src/internals/handles.ts
/**
* @internal
*/
function readHandle(handle, prefix) {
var _data$args, _data$prefix$, _data$prefix, _data$args2;
const queryKey = handle === null || handle === void 0 ? void 0 : handle.queryKey;
if (!Array.isArray(queryKey)) throw new Error(`Expected a tRPC handle from \`.unstable_$prefetch()\` / \`.unstable_$ensure()\` / \`.unstable_$fetch()\`, got ${JSON.stringify(handle)}`);
const data = readQueryKey(queryKey);
const type = (_data$args = data.args) === null || _data$args === void 0 ? void 0 : _data$args.type;
if (type !== "query" && type !== "infinite") throw new Error(`Expected a tRPC handle from \`.unstable_$prefetch()\` / \`.unstable_$ensure()\` / \`.unstable_$fetch()\`, got a key of type ${String(type)} for "${data.path.join(".")}"`);
if (((_data$prefix$ = (_data$prefix = data.prefix) === null || _data$prefix === void 0 ? void 0 : _data$prefix[0]) !== null && _data$prefix$ !== void 0 ? _data$prefix$ : void 0) !== prefix) {
var _data$prefix2;
throw new Error(`The handle for "${data.path.join(".")}" was created with keyPrefix ${JSON.stringify((_data$prefix2 = data.prefix) === null || _data$prefix2 === void 0 ? void 0 : _data$prefix2[0])}, but this proxy uses ${JSON.stringify(prefix)}`);
}
return {
type,
path: data.path,
input: (_data$args2 = data.args) === null || _data$args2 === void 0 ? void 0 : _data$args2.input,
queryKey
};
}
/**
* A prefetch during render runs on every render, so it follows the rule of
* TanStack's `usePrefetchQuery`: start only a query the cache has no state for.
* Stale data is refetched by the reader's observer, and an error stays until
* the reader's error boundary resets it: restarting it here would suspend the
* reader again.
*/
function needsRenderPrefetch(queryClient, options) {
return !queryClient.getQueryState(options.queryKey);
}
/**
* @internal
*/
function startHandle(opts) {
var _readQueryKey$args;
const { queryClient, options, kind, verb, inRender } = opts;
const input = (_readQueryKey$args = readQueryKey(options.queryKey).args) === null || _readQueryKey$args === void 0 ? void 0 : _readQueryKey$args.input;
const handle = {
queryKey: options.queryKey,
input
};
if (kind === "infinite" && options.initialPageParam != null) handle["initialCursor"] = options.initialPageParam;
if (inRender) {
if (needsRenderPrefetch(queryClient, options)) kind === "infinite" ? queryClient.prefetchInfiniteQuery(options) : queryClient.prefetchQuery(options);
return handle;
}
const toHandle = () => handle;
if (kind === "infinite") switch (verb) {
case "prefetch":
queryClient.prefetchInfiniteQuery(options);
return handle;
case "ensure": return queryClient.ensureInfiniteQueryData(_objectSpread2(_objectSpread2({}, options), {}, { revalidateIfStale: true })).then(toHandle);
case "fetch": return queryClient.fetchInfiniteQuery(options).then(toHandle);
}
switch (verb) {
case "prefetch":
queryClient.prefetchQuery(options);
return handle;
case "ensure": return queryClient.ensureQueryData(_objectSpread2(_objectSpread2({}, options), {}, { revalidateIfStale: true })).then(toHandle);
case "fetch": return queryClient.fetchQuery(options).then(toHandle);
}
}
/**
* @internal
*/
function isServerEnvironment() {
return typeof window === "undefined" || "Deno" in globalThis;
}
const warnedNotHydrated = /* @__PURE__ */ new Set();
function warnIfNotHydrated(path, queryFn) {
return (context) => {
if (isServerEnvironment()) {
const queryHash = (0, _tanstack_react_query.hashKey)(context.queryKey);
if (!warnedNotHydrated.has(queryHash)) {
warnedNotHydrated.add(queryHash);
console.warn(`[@trpc/tanstack-react-query] The handle for "${path.join(".")}" is being fetched again during server rendering: the query it refers to isn't in this QueryClient. Render the reading component inside <HydrateClient> or <HydrationBoundary>, and don't return handles from server functions or server actions. See https://trpc.io/docs/client/tanstack-react-query/handles#where-handles-dont-work`);
}
}
return queryFn(context);
};
}
const watchedHydrations = /* @__PURE__ */ new WeakSet();
/**
* A query dehydrated as pending that later rejects reaches the browser as a
* redacted error, before any `retry` from `unstable_$fromHandle()` applies. Refetch such
* a query once so error boundaries see a `TRPCClientError` from this client.
*/
function refetchRejectedHydration(queryClient, options) {
if (isServerEnvironment()) return;
const query = queryClient.getQueryCache().find({
queryKey: options.queryKey,
exact: true
});
const promise = query === null || query === void 0 ? void 0 : query.promise;
if (!query || !promise || query.state.data !== void 0 || query.state.fetchStatus === "idle" || watchedHydrations.has(promise)) return;
watchedHydrations.add(promise);
promise.catch((error) => {
if ((0, _trpc_client.isTRPCClientError)(error) || (0, _tanstack_react_query.isCancelledError)(error) || query.state.fetchStatus !== "idle") return;
query.fetch(queryClient.defaultQueryOptions(options)).catch(() => {});
});
}
/**
* @internal
*/
function prepareHandleRead(queryClient, handle, options) {
var _globalThis$process;
if (((_globalThis$process = globalThis.process) === null || _globalThis$process === void 0 || (_globalThis$process = _globalThis$process.env) === null || _globalThis$process === void 0 ? void 0 : _globalThis$process["NODE_ENV"]) !== "production" && typeof options.queryFn === "function") options.queryFn = warnIfNotHydrated(handle.path, options.queryFn);
refetchRejectedHydration(queryClient, options);
return options;
}
//#endregion
//#region src/internals/infiniteQueryOptions.ts
function trpcInfiniteQueryOptions(args) {
var _opts$initialCursor;
const { input, query, path, queryKey, opts } = args;
const inputIsSkipToken = input === _tanstack_react_query.skipToken;
const queryFn = async (queryFnContext) => {
var _opts$trpc;
const actualOpts = _objectSpread2(_objectSpread2({}, opts), {}, { trpc: _objectSpread2(_objectSpread2({}, opts === null || opts === void 0 ? void 0 : opts.trpc), (opts === null || opts === void 0 || (_opts$trpc = opts.trpc) === null || _opts$trpc === void 0 ? void 0 : _opts$trpc.abortOnUnmount) ? { signal: queryFnContext.signal } : { signal: null }) });
return await query(...getClientArgs(queryKey, actualOpts, {
direction: queryFnContext.direction,
pageParam: queryFnContext.pageParam
}));
};
return Object.assign((0, _tanstack_react_query.infiniteQueryOptions)(_objectSpread2(_objectSpread2({}, opts !== null && opts !== void 0 ? opts : {}), {}, {
queryKey,
queryFn: inputIsSkipToken ? _tanstack_react_query.skipToken : queryFn,
initialPageParam: (_opts$initialCursor = opts === null || opts === void 0 ? void 0 : opts.initialCursor) !== null && _opts$initialCursor !== void 0 ? _opts$initialCursor : input === null || input === void 0 ? void 0 : input.cursor
})), { trpc: createTRPCOptionsResult({ path }) });
}
//#endregion
//#region src/internals/mutationOptions.ts
/**
* @internal
*/
function trpcMutationOptions(args) {
var _opts$keyPrefix, _overrides$onSuccess;
const { mutate, path, prefix, opts, overrides } = args;
const queryClient = unwrapLazyArg(args.queryClient);
const mutationKey = getMutationKeyInternal({
path,
prefix: (_opts$keyPrefix = opts === null || opts === void 0 ? void 0 : opts.keyPrefix) !== null && _opts$keyPrefix !== void 0 ? _opts$keyPrefix : prefix
});
const defaultOpts = queryClient.defaultMutationOptions(queryClient.getMutationDefaults(mutationKey));
const mutationSuccessOverride = (_overrides$onSuccess = overrides === null || overrides === void 0 ? void 0 : overrides.onSuccess) !== null && _overrides$onSuccess !== void 0 ? _overrides$onSuccess : ((options) => options.originalFn());
const mutationFn = async (input) => {
return await mutate(...getClientArgs([...mutationKey, { input }], opts));
};
return _objectSpread2(_objectSpread2({}, opts), {}, {
mutationKey,
mutationFn,
onSuccess(...args) {
var _ref, _opts$meta;
const originalFn = () => {
var _opts$onSuccess, _opts$onSuccess2, _defaultOpts$onSucces;
return (_opts$onSuccess = opts === null || opts === void 0 || (_opts$onSuccess2 = opts.onSuccess) === null || _opts$onSuccess2 === void 0 ? void 0 : _opts$onSuccess2.call(opts, ...args)) !== null && _opts$onSuccess !== void 0 ? _opts$onSuccess : defaultOpts === null || defaultOpts === void 0 || (_defaultOpts$onSucces = defaultOpts.onSuccess) === null || _defaultOpts$onSucces === void 0 ? void 0 : _defaultOpts$onSucces.call(defaultOpts, ...args);
};
return mutationSuccessOverride({
originalFn,
queryClient,
meta: (_ref = (_opts$meta = opts === null || opts === void 0 ? void 0 : opts.meta) !== null && _opts$meta !== void 0 ? _opts$meta : defaultOpts === null || defaultOpts === void 0 ? void 0 : defaultOpts.meta) !== null && _ref !== void 0 ? _ref : {}
});
},
trpc: createTRPCOptionsResult({ path })
});
}
//#endregion
//#region src/internals/queryOptions.ts
/**
* @internal
*/
function trpcQueryOptions(args) {
const { input, query, path, queryKey, opts } = args;
const queryClient = unwrapLazyArg(args.queryClient);
const inputIsSkipToken = input === _tanstack_react_query.skipToken;
const queryFn = async (queryFnContext) => {
var _opts$trpc;
const actualOpts = _objectSpread2(_objectSpread2({}, opts), {}, { trpc: _objectSpread2(_objectSpread2({}, opts === null || opts === void 0 ? void 0 : opts.trpc), (opts === null || opts === void 0 || (_opts$trpc = opts.trpc) === null || _opts$trpc === void 0 ? void 0 : _opts$trpc.abortOnUnmount) ? { signal: queryFnContext.signal } : { signal: null }) });
const queryKey = queryFnContext.queryKey;
const result = await query(...getClientArgs(queryKey, actualOpts));
if ((0, _trpc_server_unstable_core_do_not_import.isAsyncIterable)(result)) return buildQueryFromAsyncIterable(result, queryClient, queryKey);
return result;
};
return Object.assign((0, _tanstack_react_query.queryOptions)(_objectSpread2(_objectSpread2({}, opts), {}, {
queryKey,
queryFn: inputIsSkipToken ? _tanstack_react_query.skipToken : queryFn
})), { trpc: createTRPCOptionsResult({ path }) });
}
//#endregion
//#region src/internals/subscriptionOptions.ts
/**
* @internal
*/
const trpcSubscriptionOptions = (args) => {
const { subscribe, path, queryKey, input, opts = {} } = args;
const enabled = "enabled" in opts ? !!opts.enabled : input !== _tanstack_react_query.skipToken;
const _subscribe = (innerOpts) => {
return subscribe(path.join("."), input === _tanstack_react_query.skipToken ? void 0 : input, innerOpts);
};
return _objectSpread2(_objectSpread2({}, opts), {}, {
enabled,
subscribe: _subscribe,
queryKey,
trpc: createTRPCOptionsResult({ path })
});
};
/**
* Runs a subscription while the component is mounted.
*
* @example
* ```ts
* const trpc = useTRPC();
* const sub = useSubscription(
* trpc.chat.onMessage.subscriptionOptions({ roomId }),
* );
* ```
*
* @see https://trpc.io/docs/client/tanstack-react-query/usage#subscriptionOptions
*/
function useSubscription(opts) {
const optsRef = react.useRef(opts);
optsRef.current = opts;
const trackedProps = react.useRef(/* @__PURE__ */ new Set([]));
const addTrackedProp = react.useCallback((key) => {
trackedProps.current.add(key);
}, []);
const currentSubscriptionRef = react.useRef(() => {});
const reset = react.useCallback(() => {
var _currentSubscriptionR;
(_currentSubscriptionR = currentSubscriptionRef.current) === null || _currentSubscriptionR === void 0 || _currentSubscriptionR.call(currentSubscriptionRef);
updateState(getInitialState);
if (!opts.enabled) return;
let isUnsubscribed = false;
let isEnded = false;
const setEnded = () => {
if (isEnded) return;
isEnded = true;
updateState((prev) => _objectSpread2(_objectSpread2({}, prev), {}, {
status: "idle",
data: void 0,
error: null
}));
};
const subscription = opts.subscribe({
onStarted: () => {
var _optsRef$current$onSt, _optsRef$current;
(_optsRef$current$onSt = (_optsRef$current = optsRef.current).onStarted) === null || _optsRef$current$onSt === void 0 || _optsRef$current$onSt.call(_optsRef$current);
updateState((prev) => _objectSpread2(_objectSpread2({}, prev), {}, {
status: "pending",
error: null
}));
},
onData: (data) => {
var _optsRef$current$onDa, _optsRef$current2;
(_optsRef$current$onDa = (_optsRef$current2 = optsRef.current).onData) === null || _optsRef$current$onDa === void 0 || _optsRef$current$onDa.call(_optsRef$current2, data);
updateState((prev) => _objectSpread2(_objectSpread2({}, prev), {}, {
status: "pending",
data,
error: null
}));
},
onError: (error) => {
var _optsRef$current$onEr, _optsRef$current3;
(_optsRef$current$onEr = (_optsRef$current3 = optsRef.current).onError) === null || _optsRef$current$onEr === void 0 || _optsRef$current$onEr.call(_optsRef$current3, error);
updateState((prev) => _objectSpread2(_objectSpread2({}, prev), {}, {
status: "error",
error
}));
},
onStopped: () => {
var _optsRef$current$onSt2, _optsRef$current4;
if (isUnsubscribed) return;
setEnded();
(_optsRef$current$onSt2 = (_optsRef$current4 = optsRef.current).onStopped) === null || _optsRef$current$onSt2 === void 0 || _optsRef$current$onSt2.call(_optsRef$current4);
},
onComplete: () => {
var _optsRef$current$onCo, _optsRef$current5;
if (isUnsubscribed) return;
setEnded();
(_optsRef$current$onCo = (_optsRef$current5 = optsRef.current).onComplete) === null || _optsRef$current$onCo === void 0 || _optsRef$current$onCo.call(_optsRef$current5);
},
onConnectionStateChange: (result) => {
var _optsRef$current$onCo2, _optsRef$current6;
(_optsRef$current$onCo2 = (_optsRef$current6 = optsRef.current).onConnectionStateChange) === null || _optsRef$current$onCo2 === void 0 || _optsRef$current$onCo2.call(_optsRef$current6, result);
updateState((prev) => {
switch (result.state) {
case "connecting": return _objectSpread2(_objectSpread2({}, prev), {}, {
status: "connecting",
error: result.error
});
case "pending": return prev;
case "idle": return _objectSpread2(_objectSpread2({}, prev), {}, {
status: "idle",
data: void 0,
error: null
});
}
});
}
});
currentSubscriptionRef.current = () => {
isUnsubscribed = true;
subscription.unsubscribe();
};
}, [(0, _tanstack_react_query.hashKey)(opts.queryKey), opts.enabled]);
const getInitialState = react.useCallback(() => {
return opts.enabled ? {
data: void 0,
error: null,
status: "connecting",
reset
} : {
data: void 0,
error: null,
status: "idle",
reset
};
}, [opts.enabled, reset]);
const resultRef = react.useRef(getInitialState());
const [state, setState] = react.useState(trackResult(resultRef, addTrackedProp));
state.reset = reset;
const updateState = react.useCallback((callback) => {
const prev = resultRef.current;
const next = resultRef.current = callback(prev);
let shouldUpdate = false;
for (const key of trackedProps.current) if (prev[key] !== next[key]) {
shouldUpdate = true;
break;
}
if (shouldUpdate) setState(trackResult(resultRef, addTrackedProp));
}, [addTrackedProp]);
react.useEffect(() => {
if (!opts.enabled) return;
reset();
return () => {
var _currentSubscriptionR2;
(_currentSubscriptionR2 = currentSubscriptionRef.current) === null || _currentSubscriptionR2 === void 0 || _currentSubscriptionR2.call(currentSubscriptionRef);
};
}, [reset, opts.enabled]);
return state;
}
function trackResult(result, onTrackResult) {
return new Proxy(result.current, { get(_target, prop) {
onTrackResult(prop);
return result.current[prop];
} });
}
//#endregion
//#region src/internals/createOptionsProxy.ts
/**
* Marks the `useTRPC()` proxy, whose handle verbs run during render
* @internal
*/
const renderHandleVerbs = Symbol("renderHandleVerbs");
/**
* Creates the options proxy without React context. Works on the server too.
*
* @example
* ```ts
* export const trpc = createTRPCOptionsProxy<AppRouter>({
* client: trpcClient,
* queryClient,
* });
* ```
*
* @see https://trpc.io/docs/client/tanstack-react-query/setup#3c-set-up-without-react-context
* @see https://trpc.io/docs/client/tanstack-react-query/server-components#5-create-a-trpc-caller-for-server-components
*/
function createTRPCOptionsProxy(opts) {
const prefix = opts.keyPrefix;
const callIt = (type) => {
return (path, input, trpcOpts) => {
if ("router" in opts) return Promise.resolve(unwrapLazyArg(opts.ctx)).then((ctx) => (0, _trpc_server.callTRPCProcedure)({
router: opts.router,
path,
getRawInput: async () => input,
ctx,
type,
signal: void 0,
batchIndex: 0
}));
return (opts.client instanceof _trpc_client.TRPCUntypedClient ? opts.client : (0, _trpc_client.getUntypedClient)(opts.client))[type](path, input, trpcOpts);
};
};
return (0, _trpc_server.createTRPCRecursiveProxy)(({ args, path: _path }) => {
const path = [..._path];
const utilName = path.pop();
const [arg1, arg2] = args;
const startQueryHandle = (kind, verb) => {
const inRender = opts[renderHandleVerbs] === true;
if (inRender && verb !== "prefetch") throw new Error(`\`${[...path, utilName].join(".")}()\` on \`useTRPC()\` waits for its query, which a render can't. Start queries in components with \`unstable_$prefetch\` or \`unstable_$prefetchInfinite\`, and wait where you read the handle, with \`useSuspenseQuery\`. See https://trpc.io/docs/client/tanstack-react-query/handles#in-render`);
const options = kind === "infinite" ? trpcInfiniteQueryOptions({
input: arg1,
opts: arg2,
path,
queryClient: opts.queryClient,
queryKey: getQueryKeyInternal({
path,
input: arg1,
type: "infinite",
prefix
}),
query: callIt("query")
}) : trpcQueryOptions({
input: arg1,
opts: arg2,
path,
queryClient: opts.queryClient,
queryKey: getQueryKeyInternal({
path,
input: arg1,
type: "query",
prefix
}),
query: callIt("query")
});
return startHandle({
queryClient: unwrapLazyArg(opts.queryClient),
options,
kind,
verb,
inRender
});
};
return {
"~types": void 0,
pathKey: () => {
return getQueryKeyInternal({
path,
type: "any",
prefix
});
},
pathFilter: () => {
return _objectSpread2(_objectSpread2({}, arg1), {}, { queryKey: getQueryKeyInternal({
path,
type: "any",
prefix
}) });
},
queryOptions: () => {
return trpcQueryOptions({
input: arg1,
opts: arg2,
path,
queryClient: opts.queryClient,
queryKey: getQueryKeyInternal({
path,
input: arg1,
type: "query",
prefix
}),
query: callIt("query")
});
},
queryKey: () => {
return getQueryKeyInternal({
path,
input: arg1,
type: "query",
prefix
});
},
queryFilter: () => {
return _objectSpread2(_objectSpread2({}, arg2), {}, { queryKey: getQueryKeyInternal({
path,
input: arg1,
type: "query",
prefix
}) });
},
infiniteQueryOptions: () => {
return trpcInfiniteQueryOptions({
input: arg1,
opts: arg2,
path,
queryClient: opts.queryClient,
queryKey: getQueryKeyInternal({
path,
input: arg1,
type: "infinite",
prefix
}),
query: callIt("query")
});
},
infiniteQueryKey: () => {
return getQueryKeyInternal({
path,
input: arg1,
type: "infinite",
prefix
});
},
infiniteQueryFilter: () => {
return _objectSpread2(_objectSpread2({}, arg2), {}, { queryKey: getQueryKeyInternal({
path,
input: arg1,
type: "infinite",
prefix
}) });
},
unstable_$fromHandle: () => {
const handle = readHandle(arg1, prefix);
const options = handle.type === "infinite" ? trpcInfiniteQueryOptions({
input: handle.input,
opts: _objectSpread2({ initialCursor: arg1.initialCursor }, arg2),
path: handle.path,
queryClient: opts.queryClient,
queryKey: handle.queryKey,
query: callIt("query")
}) : trpcQueryOptions({
input: handle.input,
opts: arg2,
path: handle.path,
queryClient: opts.queryClient,
queryKey: handle.queryKey,
query: callIt("query")
});
return prepareHandleRead(unwrapLazyArg(opts.queryClient), handle, options);
},
unstable_$prefetch: () => startQueryHandle("query", "prefetch"),
unstable_$ensure: () => startQueryHandle("query", "ensure"),
unstable_$fetch: () => startQueryHandle("query", "fetch"),
unstable_$prefetchInfinite: () => startQueryHandle("infinite", "prefetch"),
unstable_$ensureInfinite: () => startQueryHandle("infinite", "ensure"),
unstable_$fetchInfinite: () => startQueryHandle("infinite", "fetch"),
mutationOptions: () => {
var _opts$overrides;
return trpcMutationOptions({
opts: arg1,
path,
prefix,
queryClient: opts.queryClient,
mutate: callIt("mutation"),
overrides: (_opts$overrides = opts.overrides) === null || _opts$overrides === void 0 ? void 0 : _opts$overrides.mutations
});
},
mutationKey: () => {
return getMutationKeyInternal({
path,
prefix
});
},
subscriptionOptions: () => {
return trpcSubscriptionOptions({
opts: arg2,
path,
input: arg1,
queryKey: getQueryKeyInternal({
path,
input: arg1,
type: "any",
prefix
}),
subscribe: callIt("subscription")
});
}
}[utilName]();
});
}
//#endregion
//#region src/internals/Context.tsx
/**
* Creates a `TRPCProvider` and the `useTRPC` and `useTRPCClient` hooks for
* your router.
*
* @example
* ```ts
* export const { TRPCProvider, useTRPC, useTRPCClient } =
* createTRPCContext<AppRouter>();
* ```
*
* @see https://trpc.io/docs/client/tanstack-react-query/setup#3a-set-up-the-trpc-context-provider
*/
function createTRPCContext() {
const TRPCClientContext = react.createContext(null);
const TRPCContext = react.createContext(null);
const TRPCProvider = (props) => {
const value = react.useMemo(() => createTRPCOptionsProxy({
client: props.trpcClient,
queryClient: props.queryClient,
keyPrefix: props.keyPrefix,
[renderHandleVerbs]: true
}), [
props.trpcClient,
props.queryClient,
props.keyPrefix
]);
return /* @__PURE__ */ react.createElement(TRPCClientContext.Provider, { value: props.trpcClient }, /* @__PURE__ */ react.createElement(TRPCContext.Provider, { value }, props.children));
};
TRPCProvider.displayName = "TRPCProvider";
function useTRPC() {
const utils = react.useContext(TRPCContext);
if (!utils) throw new Error("useTRPC() can only be used inside of a <TRPCProvider>");
return utils;
}
function useTRPCClient() {
const client = react.useContext(TRPCClientContext);
if (!client) throw new Error("useTRPCClient() can only be used inside of a <TRPCProvider>");
return client;
}
return {
TRPCProvider,
useTRPC,
useTRPCClient
};
}
//#endregion
//#region src/internals/hydration.ts
/**
* Keyed by the request's `QueryClient`, so one server render's boundaries
* share it and the next request starts over.
*/
const sentByClient = /* @__PURE__ */ new WeakMap();
function sentEntries(queryClient) {
let sent = sentByClient.get(queryClient);
if (!sent) {
sent = {
queries: /* @__PURE__ */ new Map(),
mutations: /* @__PURE__ */ new WeakSet(),
watchingPending: false
};
sentByClient.set(queryClient, sent);
}
return sent;
}
/**
* A query sent pending carries its request's promise, so the data that
* request writes is already on its way. Record it once it lands: the query
* drops its promise after settling, so it can't be compared later.
*/
function watchPendingSends(queryClient, sent) {
if (sent.watchingPending) return;
sent.watchingPending = true;
queryClient.getQueryCache().subscribe((event) => {
if (event.type !== "updated" || event.action.type !== "success" || event.action.manual) return;
const entry = sent.queries.get(event.query.queryHash);
if ((entry === null || entry === void 0 ? void 0 : entry.promise) && entry.promise === event.query.promise) {
entry.dataUpdatedAt = event.query.state.dataUpdatedAt;
entry.promise = void 0;
}
});
}
function isAlreadySent(query, sent) {
return sent !== void 0 && query.state.dataUpdatedAt <= sent.dataUpdatedAt;
}
/**
* Dehydrate what the client's `dehydrate` defaults select, minus entries an
* earlier call already sent for this client with the same or newer data.
* @internal
*/
function dehydrateUnsent(queryClient) {
var _defaults$shouldDehyd, _defaults$shouldDehyd2;
const defaults = queryClient.getDefaultOptions().dehydrate;
const shouldDehydrateQuery = (_defaults$shouldDehyd = defaults === null || defaults === void 0 ? void 0 : defaults.shouldDehydrateQuery) !== null && _defaults$shouldDehyd !== void 0 ? _defaults$shouldDehyd : _tanstack_react_query.defaultShouldDehydrateQuery;
const shouldDehydrateMutation = (_defaults$shouldDehyd2 = defaults === null || defaults === void 0 ? void 0 : defaults.shouldDehydrateMutation) !== null && _defaults$shouldDehyd2 !== void 0 ? _defaults$shouldDehyd2 : _tanstack_react_query.defaultShouldDehydrateMutation;
const sent = sentEntries(queryClient);
return (0, _tanstack_react_query.dehydrate)(queryClient, {
shouldDehydrateQuery: (query) => {
if (isAlreadySent(query, sent.queries.get(query.queryHash)) || !shouldDehydrateQuery(query)) return false;
const promise = query.state.status === "pending" ? query.promise : void 0;
if (promise) watchPendingSends(queryClient, sent);
sent.queries.set(query.queryHash, {
dataUpdatedAt: query.state.dataUpdatedAt,
promise
});
return true;
},
shouldDehydrateMutation: (mutation) => {
if (sent.mutations.has(mutation) || !shouldDehydrateMutation(mutation)) return false;
sent.mutations.add(mutation);
return true;
}
});
}
//#endregion
//#region src/internals/HydrateClient.tsx
/**
* Create a `HydrateClient` server component for the request's `QueryClient`.
* It sends the queries started so far in this request to the browser,
* pending ones as promises that stream in as they settle. A query an earlier
* `HydrateClient` already sent is skipped, so nesting them is fine.
*
* React Server Components only: the package resolves to the server build
* through the `react-server` export condition.
*
* @see https://trpc.io/docs/client/tanstack-react-query/handles#hydrate-client
*/
function unstable_createHydrateClient(_queryClient) {
function HydrateClient() {
throw new Error("`HydrateClient` from `unstable_createHydrateClient()` works only in React Server Components. Render it from a server component; in client components, use TanStack Query's `HydrationBoundary`.");
}
return HydrateClient;
}
/**
* `unstable_createHydrateClient` for the `react-server` export condition.
* @internal
*/
function createHydrateClientReactServer(queryClient) {
function HydrateClient(props) {
return /* @__PURE__ */ react.createElement(_tanstack_react_query.HydrationBoundary, { state: dehydrateUnsent(unwrapLazyArg(queryClient)) }, props.children);
}
return HydrateClient;
}
//#endregion
Object.defineProperty(exports, "createHydrateClientReactServer", {
enumerable: true,
get: function() {
return createHydrateClientReactServer;
}
});
Object.defineProperty(exports, "createTRPCContext", {
enumerable: true,
get: function() {
return createTRPCContext;
}
});
Object.defineProperty(exports, "createTRPCOptionsProxy", {
enumerable: true,
get: function() {
return createTRPCOptionsProxy;
}
});
Object.defineProperty(exports, "unstable_createHydrateClient", {
enumerable: true,
get: function() {
return unstable_createHydrateClient;
}
});
Object.defineProperty(exports, "useSubscription", {
enumerable: true,
get: function() {
return useSubscription;
}
});