{"version":3,"file":"query-BPYwx8gC-sec20261128.js","names":["ReactNode","createContext","useContext","useMemo","RpcClient","createSpaceRpc","rpc","rpcForSpace","SpaceRpc","client","spaceId","SpaceRpcContext","undefined","SpaceRpcProvider","children","parent","value","useSpaceRpc","useBoundSpaceId","createContext","useContext","useMemo","RouterUtils","createTanstackQueryUtils","AppBootstrap","isRetryableError","retryDelayMs","DataTag","QueryKey","QueryClient","useQueryClient","createContext","useContext","useEffect","useRef","useState","RpcClient","createSpaceRpc","rpcForSpace","selectedSpaceId","useBoundSpaceId","queryClient","defaultOptions","queries","staleTime","gcTime","refetchOnMount","refetchOnWindowFocus","retry","failures","error","retryDelay","_failures","SpaceQueries","scopePath","userId","spaceId","scopes","Map","spaceQueries","path","id","join","scope","get","set","spaceSeedKey","bootstrap","queryKey","input","ChatTarget","botId","groupId","lastChatKey","lastChatOf","seed","chat","undefined","groups","some","group","bots","bot","seedOnLeave","previous","latest","Omit","snapshot","selected","thread","QueryUserContext","QueryUserProvider","Provider","useQueryUserId","useSpaceQueries","boundSpaceId","useSave","options","save","Input","rpc","Promise","Saved","stale","onSaved","saved","onFailed","Error","closesScreen","scopeNow","key","saves","setSaves","Record","pending","inFlight","Set","shownScope","current","mounted","run","has","add","now","shown","finish","delete","then","reads","allSettled","map","invalidateQueries","reset","rest","cachedUserId","setQueryUser","clear","createTanstackQueryUtils","createContext","useContext","useState","useRef","__toESM","toArray","stringifyJSON","RECURSIVE_CLIENT_UNWRAP_KEYS","isTypescriptObject","get","isAsyncIteratorObject","rpcForSpace","createSpaceRpc","rpc","retryDelayMs","isRetryableError","require_react","require_jsx_runtime","skipToken","Removable","noop","onlineManager","Subscribable","hashQueryKeyByOptions","useQueryClient","notifyManager","hashKey","createRetryer","functionalUpdate","Query","focusManager","matchMutation","resolveQueryValue","partialMatchKey","matchQuery","Mutation","#client","config","#mutationCache","#observers","getDefaultState","options","observer","x","#retryer","onContinue","#dispatch","mutationFnContext","retryer","variables","restored","isPaused","context","data","error","reducer","action","state","MutationCache","#mutations","#scopes","#mutationId","mutation","client","scope","scopeFor","scopedMutations","index","firstPendingMutation","m","mutations","defaultedFilters","filters","listener","event","pausedMutations","QueryCache","#queries","queryKey","queryHash","query","queries","QueryClient","#queryCache","#defaultOptions","#queryDefaults","#mutationDefaults","#mountCount","#unsubscribeFocus","focused","#unsubscribeOnline","online","defaultedOptions","cachedData","prevData","updater","queryCache","matched","queriesToRefetch","defaultedCancelOptions","cancelOptions","promises","fetchOptions","promise","queryData","select","defaults","result","queryDefault","mutationKey","generateOperationKey","path","createGeneralUtils","experimental_liveQuery","stream","queryFn","last","chunk","experimental_serializableStreamedQuery","hasPreviousData","refetchMode","limitArraySize","prev","maxChunks","shouldUpdateCacheDuringStream","items","maxSize","OPERATION_CONTEXT_SYMBOL","createProcedureUtils","utils","optionsIn","output","pageParam","input","createRouterUtils","generalUtils","procedureUtils","value","target","prop","nextClient","nextUtils","prop2","target2","import_react","import_jsx_runtime","SpaceRpcContext","SpaceRpcProvider","parent","spaceId","useSpaceRpc","useBoundSpaceId","queryClient","failures","scopePath","userId","scopes","spaceQueries","id","spaceSeedKey","lastChatKey","lastChatOf","seed","chat","group","bot","seedOnLeave","selected","snapshot","previous","latest","QueryUserContext","QueryUserProvider","useQueryUserId","useSpaceQueries","boundSpaceId","selectedSpaceId","useSave","scopeNow","saves","setSaves","inFlight","shownScope","mounted","current","key","now","shown","finish","save","reads","stale","closesScreen","onSaved","saved","onFailed","rest","cachedUserId","setQueryUser"],"sources":["../../../../node_modules/.pnpm/@tanstack+query-core@5.107.1/node_modules/@tanstack/query-core/build/modern/mutation.js","../../../../node_modules/.pnpm/@tanstack+query-core@5.107.1/node_modules/@tanstack/query-core/build/modern/mutationCache.js","../../../../node_modules/.pnpm/@tanstack+query-core@5.107.1/node_modules/@tanstack/query-core/build/modern/queryCache.js","../../../../node_modules/.pnpm/@tanstack+query-core@5.107.1/node_modules/@tanstack/query-core/build/modern/queryClient.js","../../../../node_modules/.pnpm/@orpc+tanstack-query@1.16.2_@opentelemetry+api@1.10.0_@orpc+client@1.16.2_@opentelemetr_159694ac7976513c79ec06d23bc8698a/node_modules/@orpc/tanstack-query/dist/index.mjs","../../src/lib/query/space-rpc.tsx","../../src/lib/query/query.ts"],"sourcesContent":["import { notifyManager } from \"./notifyManager.js\";\nimport { createRetryer } from \"./retryer.js\";\nimport { Removable } from \"./removable.js\";\n// src/mutation.ts\n/**\n* Represents a single mutation attempt. A `Mutation` holds the mutation's\n* options, state (data/error/status), and the `MutationObserver`s currently\n* subscribed to it.\n*\n* Instances are created and managed internally by `MutationCache`; application\n* code typically interacts with mutations indirectly through `QueryClient` or\n* a framework hook like `useMutation`. Direct access to a `Mutation` instance\n* is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.\n* @example\n* ```ts\n* const mutationCache = queryClient.getMutationCache()\n*\n* const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n* ```\n*/\nvar Mutation = class extends Removable {\n\t#client;\n\t#observers;\n\t#mutationCache;\n\t#retryer;\n\tconstructor(config) {\n\t\tsuper();\n\t\tthis.#client = config.client;\n\t\tthis.mutationId = config.mutationId;\n\t\tthis.#mutationCache = config.mutationCache;\n\t\tthis.#observers = [];\n\t\tthis.state = config.state || getDefaultState();\n\t\tthis.setOptions(config.options);\n\t\tthis.scheduleGc();\n\t}\n\t/**\n\t* Replaces the mutation's options and applies their `gcTime`.\n\t* @internal\n\t* @param options - The new mutation options.\n\t*/\n\tsetOptions(options) {\n\t\tthis.options = options;\n\t\tthis.updateGcTime(this.options.gcTime);\n\t}\n\t/**\n\t* The `meta` object passed in the mutation's options, if any.\n\t* @returns The mutation's `meta`, or `undefined` if none was set.\n\t*/\n\tget meta() {\n\t\treturn this.options.meta;\n\t}\n\t/**\n\t* Subscribes an observer to the mutation and stops its garbage collection.\n\t* @internal\n\t* @param observer - The observer to add. Adding an observer that is already subscribed does\n\t* nothing.\n\t*/\n\taddObserver(observer) {\n\t\tif (!this.#observers.includes(observer)) {\n\t\t\tthis.#observers.push(observer);\n\t\t\tthis.clearGcTimeout();\n\t\t\tthis.#mutationCache.notify({\n\t\t\t\ttype: \"observerAdded\",\n\t\t\t\tmutation: this,\n\t\t\t\tobserver\n\t\t\t});\n\t\t}\n\t}\n\t/**\n\t* Unsubscribes an observer from the mutation.\n\t* @internal\n\t* @param observer - The observer to remove. Garbage collection is scheduled afterwards.\n\t*/\n\tremoveObserver(observer) {\n\t\tthis.#observers = this.#observers.filter((x) => x !== observer);\n\t\tthis.scheduleGc();\n\t\tthis.#mutationCache.notify({\n\t\t\ttype: \"observerRemoved\",\n\t\t\tmutation: this,\n\t\t\tobserver\n\t\t});\n\t}\n\toptionalRemove() {\n\t\tif (!this.#observers.length) {\n\t\t\tif (this.state.status === \"pending\") this.scheduleGc();\n\t\t\telse this.#mutationCache.remove(this);\n\t\t}\n\t}\n\t/**\n\t* Resumes a mutation that is currently paused or was restored from a\n\t* dehydrated, still-`pending` state.\n\t*\n\t* - If this mutation has an active retryer (it paused mid-attempt, e.g. due\n\t*   to the network mode or scope-based queuing), its retryer is resumed.\n\t* - Otherwise, if the mutation's status is still `pending` (e.g. it was\n\t*   dehydrated while an attempt was in flight and never got a retryer in\n\t*   this instance), `execute` is called again with the last known variables.\n\t* - Otherwise the mutation has already settled and this resolves immediately\n\t*   without running anything again.\n\t* @returns A promise that settles with the resumed mutation: it rejects if the mutation fails.\n\t* It resolves immediately if the mutation has already settled.\n\t* @see {@link Mutation#execute}\n\t* @example\n\t* ```ts\n\t* // typically driven by reconnect handling, e.g. queryClient.resumePausedMutations()\n\t* const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n\t* await mutation?.continue()\n\t* ```\n\t*/\n\tcontinue() {\n\t\treturn this.#retryer?.continue() ?? (this.state.status === \"pending\" ? this.execute(this.state.variables) : Promise.resolve());\n\t}\n\t/**\n\t* Runs the mutation function for the given variables through a retryer, and\n\t* drives the mutation's state and lifecycle callbacks through to settlement.\n\t*\n\t* If this mutation's state is already `pending` when `execute` is called\n\t* (i.e. it was restored, still in-flight, from a dehydrated state), the\n\t* `onMutate` step is skipped and a `continue` action is dispatched to\n\t* unpause it; otherwise a `pending` action is dispatched first, then the\n\t* mutation cache's `onMutate` and the mutation's own `onMutate` option are\n\t* awaited in that order, and the resulting context is stored.\n\t*\n\t* The mutation function is then run (subject to `retry`/`retryDelay`/\n\t* `networkMode`, and to the mutation cache's scope-based serialization).\n\t* On success, the cache's `onSuccess`/`onSettled` callbacks run before the\n\t* mutation's own `onSuccess`/`onSettled` options, a `success` action is\n\t* dispatched, and the resolved data is returned. On failure, the same\n\t* cache-then-option ordering is used for `onError`/`onSettled`, but each of\n\t* those four callbacks is individually caught so that a throwing callback\n\t* cannot mask the original error; an `error` action is then dispatched and\n\t* the original error is re-thrown.\n\t* @param variables - The variables passed to the `mutationFn`.\n\t* @returns A promise that resolves with the mutation's data, or rejects with its error.\n\t* @see {@link Mutation#continue}\n\t* @example\n\t* ```ts\n\t* // Called internally by `MutationObserver.mutate` and `Mutation.continue` —\n\t* // applications normally trigger mutations through those, not this method.\n\t* const data = await mutation.execute(variables)\n\t* ```\n\t*/\n\tasync execute(variables) {\n\t\tconst onContinue = () => {\n\t\t\tthis.#dispatch({ type: \"continue\" });\n\t\t};\n\t\tconst mutationFnContext = {\n\t\t\tclient: this.#client,\n\t\t\tmeta: this.options.meta,\n\t\t\tmutationKey: this.options.mutationKey\n\t\t};\n\t\tconst retryer = this.#retryer = createRetryer({\n\t\t\tfn: () => {\n\t\t\t\tif (!this.options.mutationFn) return Promise.reject(/* @__PURE__ */ new Error(\"No mutationFn found\"));\n\t\t\t\treturn this.options.mutationFn(variables, mutationFnContext);\n\t\t\t},\n\t\t\tonFail: (failureCount, error) => {\n\t\t\t\tthis.#dispatch({\n\t\t\t\t\ttype: \"failed\",\n\t\t\t\t\tfailureCount,\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t},\n\t\t\tonPause: () => {\n\t\t\t\tthis.#dispatch({ type: \"pause\" });\n\t\t\t},\n\t\t\tonContinue,\n\t\t\tretry: this.options.retry ?? 0,\n\t\t\tretryDelay: this.options.retryDelay,\n\t\t\tnetworkMode: this.options.networkMode,\n\t\t\tcanRun: () => this.#mutationCache.canRun(this)\n\t\t});\n\t\tconst restored = this.state.status === \"pending\";\n\t\tconst isPaused = !retryer.canStart();\n\t\ttry {\n\t\t\tif (restored) onContinue();\n\t\t\telse {\n\t\t\t\tthis.#dispatch({\n\t\t\t\t\ttype: \"pending\",\n\t\t\t\t\tvariables,\n\t\t\t\t\tisPaused\n\t\t\t\t});\n\t\t\t\tif (this.#mutationCache.config.onMutate) await this.#mutationCache.config.onMutate(variables, this, mutationFnContext);\n\t\t\t\tconst context = await this.options.onMutate?.(variables, mutationFnContext);\n\t\t\t\tif (context !== this.state.context) this.#dispatch({\n\t\t\t\t\ttype: \"pending\",\n\t\t\t\t\tcontext,\n\t\t\t\t\tvariables,\n\t\t\t\t\tisPaused\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (this.state.isPaused && retryer.canStart()) onContinue();\n\t\t\tconst data = await retryer.start();\n\t\t\tawait this.#mutationCache.config.onSuccess?.(data, variables, this.state.context, this, mutationFnContext);\n\t\t\tawait this.options.onSuccess?.(data, variables, this.state.context, mutationFnContext);\n\t\t\tawait this.#mutationCache.config.onSettled?.(data, null, this.state.variables, this.state.context, this, mutationFnContext);\n\t\t\tawait this.options.onSettled?.(data, null, variables, this.state.context, mutationFnContext);\n\t\t\tthis.#dispatch({\n\t\t\t\ttype: \"success\",\n\t\t\t\tdata\n\t\t\t});\n\t\t\treturn data;\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait this.#mutationCache.config.onError?.(error, variables, this.state.context, this, mutationFnContext);\n\t\t\t} catch (e) {\n\t\t\t\tPromise.reject(e);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait this.options.onError?.(error, variables, this.state.context, mutationFnContext);\n\t\t\t} catch (e) {\n\t\t\t\tPromise.reject(e);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait this.#mutationCache.config.onSettled?.(void 0, error, this.state.variables, this.state.context, this, mutationFnContext);\n\t\t\t} catch (e) {\n\t\t\t\tPromise.reject(e);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait this.options.onSettled?.(void 0, error, variables, this.state.context, mutationFnContext);\n\t\t\t} catch (e) {\n\t\t\t\tPromise.reject(e);\n\t\t\t}\n\t\t\tthis.#dispatch({\n\t\t\t\ttype: \"error\",\n\t\t\t\terror\n\t\t\t});\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tif (this.#retryer === retryer) this.#retryer = void 0;\n\t\t\tthis.#mutationCache.runNext(this);\n\t\t}\n\t}\n\t#dispatch(action) {\n\t\tconst reducer = (state) => {\n\t\t\tswitch (action.type) {\n\t\t\t\tcase \"failed\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\tfailureCount: action.failureCount,\n\t\t\t\t\tfailureReason: action.error\n\t\t\t\t};\n\t\t\t\tcase \"pause\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\tisPaused: true\n\t\t\t\t};\n\t\t\t\tcase \"continue\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\tisPaused: false\n\t\t\t\t};\n\t\t\t\tcase \"pending\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\tcontext: action.context,\n\t\t\t\t\tdata: void 0,\n\t\t\t\t\tfailureCount: 0,\n\t\t\t\t\tfailureReason: null,\n\t\t\t\t\terror: null,\n\t\t\t\t\tisPaused: action.isPaused,\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\tvariables: action.variables,\n\t\t\t\t\tsubmittedAt: Date.now()\n\t\t\t\t};\n\t\t\t\tcase \"success\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\tdata: action.data,\n\t\t\t\t\tfailureCount: 0,\n\t\t\t\t\tfailureReason: null,\n\t\t\t\t\terror: null,\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\tisPaused: false\n\t\t\t\t};\n\t\t\t\tcase \"error\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\tdata: void 0,\n\t\t\t\t\terror: action.error,\n\t\t\t\t\tfailureCount: state.failureCount + 1,\n\t\t\t\t\tfailureReason: action.error,\n\t\t\t\t\tisPaused: false,\n\t\t\t\t\tstatus: \"error\"\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\t\tthis.state = reducer(this.state);\n\t\tnotifyManager.batch(() => {\n\t\t\tthis.#observers.forEach((observer) => {\n\t\t\t\tobserver.onMutationUpdate(action);\n\t\t\t});\n\t\t\tthis.#mutationCache.notify({\n\t\t\t\tmutation: this,\n\t\t\t\ttype: \"updated\",\n\t\t\t\taction\n\t\t\t});\n\t\t});\n\t}\n};\n/**\n* Returns the initial state of a mutation: `'idle'`, with no data, error, or variables.\n* @returns The initial mutation state.\n*/\nfunction getDefaultState() {\n\treturn {\n\t\tcontext: void 0,\n\t\tdata: void 0,\n\t\terror: null,\n\t\tfailureCount: 0,\n\t\tfailureReason: null,\n\t\tisPaused: false,\n\t\tstatus: \"idle\",\n\t\tvariables: void 0,\n\t\tsubmittedAt: 0\n\t};\n}\nexport { Mutation, getDefaultState };\n\n//# sourceMappingURL=mutation.js.map","import { matchMutation, noop } from \"./utils.js\";\nimport { Subscribable } from \"./subscribable.js\";\nimport { notifyManager } from \"./notifyManager.js\";\nimport { Mutation } from \"./mutation.js\";\n// src/mutationCache.ts\n/**\n* The `MutationCache` is the storage for mutations.\n*\n* Normally, you will not interact with the `MutationCache` directly and instead use a\n* `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of\n* safe/known updates to the cache, such as mutations being added, removed, or updated.\n* @example\n* ```ts\n* const unsubscribe = mutationCache.subscribe((event) => {\n*   console.log(event.type, event.mutation)\n* })\n* ```\n*/\nvar MutationCache = class extends Subscribable {\n\t#mutations;\n\t#scopes;\n\t#mutationId;\n\tconstructor(config = {}) {\n\t\tsuper();\n\t\tthis.config = config;\n\t\tthis.#mutations = /* @__PURE__ */ new Set();\n\t\tthis.#scopes = /* @__PURE__ */ new Map();\n\t\tthis.#mutationId = 0;\n\t}\n\t/**\n\t* Creates a mutation and adds it to the cache.\n\t* @internal\n\t* @param client - The client the mutation belongs to, used to default its options.\n\t* @param options - The mutation options. They are defaulted with {@link\n\t* QueryClient#defaultMutationOptions}.\n\t* @param state - The initial state of the mutation, e.g. when restoring a dehydrated mutation.\n\t* @returns The new mutation, already added to the cache.\n\t*/\n\tbuild(client, options, state) {\n\t\tconst mutation = new Mutation({\n\t\t\tclient,\n\t\t\tmutationCache: this,\n\t\t\tmutationId: ++this.#mutationId,\n\t\t\toptions: client.defaultMutationOptions(options),\n\t\t\tstate\n\t\t});\n\t\tthis.add(mutation);\n\t\treturn mutation;\n\t}\n\t/**\n\t* Adds a mutation to the cache.\n\t* @internal\n\t* @param mutation - The mutation to add. If it has a `scope`, it is queued in that scope.\n\t*/\n\tadd(mutation) {\n\t\tthis.#mutations.add(mutation);\n\t\tconst scope = scopeFor(mutation);\n\t\tif (typeof scope === \"string\") {\n\t\t\tconst scopedMutations = this.#scopes.get(scope);\n\t\t\tif (scopedMutations) scopedMutations.push(mutation);\n\t\t\telse this.#scopes.set(scope, [mutation]);\n\t\t}\n\t\tthis.notify({\n\t\t\ttype: \"added\",\n\t\t\tmutation\n\t\t});\n\t}\n\t/**\n\t* Removes a mutation from the cache.\n\t* @internal\n\t* @param mutation - The mutation to remove, also from its scope's queue.\n\t*/\n\tremove(mutation) {\n\t\tif (this.#mutations.delete(mutation)) {\n\t\t\tconst scope = scopeFor(mutation);\n\t\t\tif (typeof scope === \"string\") {\n\t\t\t\tconst scopedMutations = this.#scopes.get(scope);\n\t\t\t\tif (scopedMutations) {\n\t\t\t\t\tif (scopedMutations.length > 1) {\n\t\t\t\t\t\tconst index = scopedMutations.indexOf(mutation);\n\t\t\t\t\t\tif (index !== -1) scopedMutations.splice(index, 1);\n\t\t\t\t\t} else if (scopedMutations[0] === mutation) this.#scopes.delete(scope);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.notify({\n\t\t\ttype: \"removed\",\n\t\t\tmutation\n\t\t});\n\t}\n\t/**\n\t* Checks whether a mutation can run now, given the other mutations in its `scope`.\n\t* @internal\n\t* @param mutation - The mutation to check.\n\t* @returns `true` if the mutation has no `scope`, or no other mutation in its scope is pending\n\t* ahead of it.\n\t*/\n\tcanRun(mutation) {\n\t\tconst scope = scopeFor(mutation);\n\t\tif (typeof scope === \"string\") {\n\t\t\tconst firstPendingMutation = this.#scopes.get(scope)?.find((m) => m.state.status === \"pending\");\n\t\t\treturn !firstPendingMutation || firstPendingMutation === mutation;\n\t\t} else return true;\n\t}\n\t/**\n\t* Continues the next paused mutation in the same `scope` after a mutation finishes.\n\t* @internal\n\t* @param mutation - The mutation that finished.\n\t* @returns A promise that resolves once the next paused mutation in the same scope has continued,\n\t* or immediately if there is none.\n\t*/\n\trunNext(mutation) {\n\t\tconst scope = scopeFor(mutation);\n\t\tif (typeof scope === \"string\") return (this.#scopes.get(scope)?.find((m) => m !== mutation && m.state.isPaused))?.continue() ?? Promise.resolve();\n\t\telse return Promise.resolve();\n\t}\n\t/**\n\t* Removes all mutations from the cache.\n\t* @example\n\t* ```ts\n\t* const mutationCache = queryClient.getMutationCache()\n\t*\n\t* mutationCache.clear()\n\t* ```\n\t*/\n\tclear() {\n\t\tnotifyManager.batch(() => {\n\t\t\tconst mutations = this.getAll();\n\t\t\tthis.#mutations.clear();\n\t\t\tthis.#scopes.clear();\n\t\t\tmutations.forEach((mutation) => {\n\t\t\t\tthis.notify({\n\t\t\t\t\ttype: \"removed\",\n\t\t\t\t\tmutation\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t}\n\t/**\n\t* Returns all mutations within the cache.\n\t*\n\t* This is not typically needed for most applications, but can come in handy when needing more\n\t* information about a mutation in rare scenarios.\n\t* @returns Every mutation in the cache.\n\t* @example\n\t* ```ts\n\t* const mutationCache = queryClient.getMutationCache()\n\t*\n\t* const mutations = mutationCache.getAll()\n\t* ```\n\t*/\n\tgetAll() {\n\t\treturn Array.from(this.#mutations);\n\t}\n\t/**\n\t* A slightly more advanced method that can be used to get an existing mutation instance from\n\t* the cache. If the mutation does not exist, `undefined` is returned.\n\t*\n\t* This is not typically needed for most applications, but can come in handy when needing more\n\t* information about a mutation in rare scenarios.\n\t* @param filters - The filters to match. `exact` defaults to `true`.\n\t* @returns The first matching mutation, or `undefined`.\n\t* @see {@link MutationCache#findAll}\n\t* @example\n\t* ```ts\n\t* const mutationCache = queryClient.getMutationCache()\n\t*\n\t* const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n\t* ```\n\t*/\n\tfind(filters) {\n\t\tconst defaultedFilters = {\n\t\t\texact: true,\n\t\t\t...filters\n\t\t};\n\t\treturn this.getAll().find((mutation) => matchMutation(defaultedFilters, mutation));\n\t}\n\t/**\n\t* An even more advanced method that can be used to get existing mutation instances from the\n\t* cache that match the given filters. If no mutations match, an empty array is returned.\n\t*\n\t* This is not typically needed for most applications, but can come in handy when needing more\n\t* information about mutations in rare scenarios.\n\t* @param filters - The filters to match. Without filters, every mutation is returned.\n\t* @returns The matching mutations.\n\t* @see {@link MutationCache#find}\n\t* @example\n\t* ```ts\n\t* const mutationCache = queryClient.getMutationCache()\n\t*\n\t* const mutations = mutationCache.findAll({ mutationKey: ['addPost'] })\n\t* ```\n\t*/\n\tfindAll(filters = {}) {\n\t\treturn this.getAll().filter((mutation) => matchMutation(filters, mutation));\n\t}\n\t/**\n\t* Notifies every cache listener of an event, in one batch.\n\t* @internal\n\t* @param event - The event passed to every listener.\n\t*/\n\tnotify(event) {\n\t\tnotifyManager.batch(() => {\n\t\t\tthis.listeners.forEach((listener) => {\n\t\t\t\tlistener(event);\n\t\t\t});\n\t\t});\n\t}\n\t/**\n\t* Continues every paused mutation, e.g. when the app comes back online.\n\t* @internal\n\t* @returns A promise that resolves once every paused mutation has continued and settled.\n\t*/\n\tresumePausedMutations() {\n\t\tconst pausedMutations = this.getAll().filter((x) => x.state.isPaused);\n\t\treturn notifyManager.batch(() => Promise.all(pausedMutations.map((mutation) => mutation.continue().catch(noop))));\n\t}\n};\n/**\n* Returns the scope id of a mutation, used to run mutations with the same scope one after another.\n* @param mutation - The mutation to read the scope of.\n* @returns The mutation's `scope.id`, or `undefined` if it has no scope.\n*/\nfunction scopeFor(mutation) {\n\treturn mutation.options.scope?.id;\n}\nexport { MutationCache };\n\n//# sourceMappingURL=mutationCache.js.map","import { hashQueryKeyByOptions, matchQuery } from \"./utils.js\";\nimport { Subscribable } from \"./subscribable.js\";\nimport { notifyManager } from \"./notifyManager.js\";\nimport { Query } from \"./query.js\";\n// src/queryCache.ts\n/**\n* The `QueryCache` is the storage mechanism for TanStack Query. It stores all the data, meta\n* information, and state of the queries it contains.\n*\n* Normally, you will not interact with the `QueryCache` directly and instead use a `QueryClient`\n* for a specific cache. You can subscribe to it (inherited from `Subscribable`) to be informed of\n* safe/known updates to the cache, such as queries being added, removed, or updated — updates made\n* outside of the cache's own tracked mechanisms (e.g. mutating a query's state object directly) do\n* not notify subscribers.\n* @example\n* ```ts\n* const unsubscribe = queryCache.subscribe((event) => {\n*   console.log(event.type, event.query)\n* })\n* ```\n*/\nvar QueryCache = class extends Subscribable {\n\t#queries;\n\tconstructor(config = {}) {\n\t\tsuper();\n\t\tthis.config = config;\n\t\tthis.#queries = /* @__PURE__ */ new Map();\n\t}\n\t/**\n\t* Returns the existing `Query` instance for the given options' `queryKey`/`queryHash`, or\n\t* builds and adds a new one to the cache if none exists yet. Used by framework adapters and\n\t* plugins (e.g. broadcast/persistence) that need to get-or-create a `Query` directly, bypassing\n\t* the reactive `QueryObserver` machinery.\n\t* @param client - The client the query belongs to, used to default its options.\n\t* @param options - The query options, including the `queryKey`. A new query is created with the\n\t* options defaulted by {@link QueryClient#defaultQueryOptions}.\n\t* @param state - The initial state of a newly created query, e.g. when hydrating. Ignored if the\n\t* query already exists.\n\t* @returns The existing or newly created query.\n\t* @example\n\t* ```ts\n\t* const queryCache = queryClient.getQueryCache()\n\t*\n\t* const query = queryCache.build(queryClient, {\n\t*   queryKey: ['posts'],\n\t*   queryFn: fetchPosts,\n\t* })\n\t* ```\n\t*/\n\tbuild(client, options, state) {\n\t\tconst queryKey = options.queryKey;\n\t\tconst queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);\n\t\tlet query = this.get(queryHash);\n\t\tif (!query) {\n\t\t\tquery = new Query({\n\t\t\t\tclient,\n\t\t\t\tqueryKey,\n\t\t\t\tqueryHash,\n\t\t\t\toptions: client.defaultQueryOptions(options),\n\t\t\t\tstate,\n\t\t\t\tdefaultOptions: client.getQueryDefaults(queryKey)\n\t\t\t});\n\t\t\tthis.add(query);\n\t\t}\n\t\treturn query;\n\t}\n\t/**\n\t* Adds a query to the cache.\n\t* @internal\n\t* @param query - The query to add. If a query with the same hash is already cached, nothing\n\t* happens.\n\t*/\n\tadd(query) {\n\t\tif (!this.#queries.has(query.queryHash)) {\n\t\t\tthis.#queries.set(query.queryHash, query);\n\t\t\tthis.notify({\n\t\t\t\ttype: \"added\",\n\t\t\t\tquery\n\t\t\t});\n\t\t}\n\t}\n\t/**\n\t* Destroys the given `Query` and removes it from the cache, notifying subscribers with a\n\t* `'removed'` event. A no-op if the query is no longer the one currently stored under its hash\n\t* (e.g. it was already replaced). Used by plugins (e.g. the broadcast client) that mirror\n\t* removals across `QueryCache` instances.\n\t* @param query - The query to remove.\n\t* @example\n\t* ```ts\n\t* const queryCache = queryClient.getQueryCache()\n\t* const query = queryCache.find({ queryKey: ['posts'] })\n\t*\n\t* if (query) {\n\t*   queryCache.remove(query)\n\t* }\n\t* ```\n\t*/\n\tremove(query) {\n\t\tif (this.#queries.get(query.queryHash) === query) {\n\t\t\tquery.destroy();\n\t\t\tthis.#queries.delete(query.queryHash);\n\t\t\tthis.notify({\n\t\t\t\ttype: \"removed\",\n\t\t\t\tquery\n\t\t\t});\n\t\t}\n\t}\n\t/**\n\t* Removes all queries from the cache.\n\t* @example\n\t* ```ts\n\t* const queryCache = queryClient.getQueryCache()\n\t*\n\t* queryCache.clear()\n\t* ```\n\t*/\n\tclear() {\n\t\tnotifyManager.batch(() => {\n\t\t\tthis.getAll().forEach((query) => {\n\t\t\t\tthis.remove(query);\n\t\t\t});\n\t\t});\n\t}\n\t/**\n\t* Returns the `Query` instance stored under the given `queryHash`, or `undefined` if none\n\t* exists. Unlike {@link QueryCache#find}, this looks up by the already-computed hash rather\n\t* than by `QueryFilters`. Used by plugins (e.g. broadcast/hydration) that already have a hash\n\t* to look up directly.\n\t* @param queryHash - The hash of the query to look up.\n\t* @returns The query stored under the hash, or `undefined`.\n\t* @example\n\t* ```ts\n\t* const queryCache = queryClient.getQueryCache()\n\t* const queryHash = hashKey(['posts'])\n\t*\n\t* const query = queryCache.get(queryHash)\n\t* ```\n\t*/\n\tget(queryHash) {\n\t\treturn this.#queries.get(queryHash);\n\t}\n\t/**\n\t* Returns all queries within the cache.\n\t* @returns Every query in the cache.\n\t* @example\n\t* ```ts\n\t* const queryCache = queryClient.getQueryCache()\n\t*\n\t* const queries = queryCache.getAll()\n\t* ```\n\t*/\n\tgetAll() {\n\t\treturn [...this.#queries.values()];\n\t}\n\t/**\n\t* A slightly more advanced method that can be used to get an existing query instance from the\n\t* cache. This instance not only contains all the state for the query, but all of the instances,\n\t* and underlying guts of the query as well. If the query does not exist, `undefined` is\n\t* returned.\n\t*\n\t* This is not typically needed for most applications, but can come in handy when needing more\n\t* information about a query in rare scenarios (e.g. looking at `query.state.dataUpdatedAt` to\n\t* decide whether a query is fresh enough to be used as an initial value).\n\t* @param filters - The filters to match, including the required `queryKey`. `exact` defaults to\n\t* `true`.\n\t* @returns The first matching query, or `undefined`.\n\t* @see {@link QueryCache#findAll}\n\t* @example\n\t* ```ts\n\t* const queryCache = queryClient.getQueryCache()\n\t*\n\t* const query = queryCache.find({ queryKey: ['posts'] })\n\t* ```\n\t*/\n\tfind(filters) {\n\t\tconst defaultedFilters = {\n\t\t\texact: true,\n\t\t\t...filters\n\t\t};\n\t\treturn this.getAll().find((query) => matchQuery(defaultedFilters, query));\n\t}\n\t/**\n\t* An even more advanced method that can be used to get existing query instances from the cache\n\t* that partially match a query key. If no queries match, an empty array is returned.\n\t*\n\t* This is not typically needed for most applications, but can come in handy when needing more\n\t* information about queries in rare scenarios.\n\t* @param filters - The filters to match. Without filters, every query is returned.\n\t* @returns The matching queries.\n\t* @see {@link QueryCache#find}\n\t* @example\n\t* ```ts\n\t* const queryCache = queryClient.getQueryCache()\n\t*\n\t* const queries = queryCache.findAll({ queryKey: ['posts'] })\n\t* ```\n\t*/\n\tfindAll(filters = {}) {\n\t\tconst queries = this.getAll();\n\t\treturn Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries;\n\t}\n\t/**\n\t* Notifies every cache listener of an event, in one batch.\n\t* @internal\n\t* @param event - The event passed to every listener.\n\t*/\n\tnotify(event) {\n\t\tnotifyManager.batch(() => {\n\t\t\tthis.listeners.forEach((listener) => {\n\t\t\t\tlistener(event);\n\t\t\t});\n\t\t});\n\t}\n\t/**\n\t* Calls {@link Query#onFocus} on every cached query, in one batch.\n\t* @internal\n\t*/\n\tonFocus() {\n\t\tnotifyManager.batch(() => {\n\t\t\tthis.getAll().forEach((query) => {\n\t\t\t\tquery.onFocus();\n\t\t\t});\n\t\t});\n\t}\n\t/**\n\t* Calls {@link Query#onOnline} on every cached query, in one batch.\n\t* @internal\n\t*/\n\tonOnline() {\n\t\tnotifyManager.batch(() => {\n\t\t\tthis.getAll().forEach((query) => {\n\t\t\t\tquery.onOnline();\n\t\t\t});\n\t\t});\n\t}\n};\nexport { QueryCache };\n\n//# sourceMappingURL=queryCache.js.map","import { functionalUpdate, hashKey, hashQueryKeyByOptions, noop, partialMatchKey, resolveQueryValue, skipToken } from \"./utils.js\";\nimport { focusManager } from \"./focusManager.js\";\nimport { notifyManager } from \"./notifyManager.js\";\nimport { onlineManager } from \"./onlineManager.js\";\nimport { MutationCache } from \"./mutationCache.js\";\nimport { QueryCache } from \"./queryCache.js\";\n// src/queryClient.ts\n/**\n* `QueryClient` is used to interact with a cache of queries and mutations. It owns a\n* `QueryCache` and a `MutationCache` (creating default ones if none are passed in) and holds\n* the default options that are applied to queries and mutations created through it.\n* @example\n* ```ts\n* const queryClient = new QueryClient({\n*   defaultOptions: {\n*     queries: {\n*       staleTime: Infinity,\n*     },\n*   },\n* })\n*\n* await queryClient.query({ queryKey: ['posts'], queryFn: fetchPosts })\n* ```\n*/\nvar QueryClient = class {\n\t#queryCache;\n\t#mutationCache;\n\t#defaultOptions;\n\t#queryDefaults;\n\t#mutationDefaults;\n\t#mountCount;\n\t#unsubscribeFocus;\n\t#unsubscribeOnline;\n\tconstructor(config = {}) {\n\t\tthis.#queryCache = config.queryCache || new QueryCache();\n\t\tthis.#mutationCache = config.mutationCache || new MutationCache();\n\t\tthis.#defaultOptions = config.defaultOptions || {};\n\t\tthis.#queryDefaults = /* @__PURE__ */ new Map();\n\t\tthis.#mutationDefaults = /* @__PURE__ */ new Map();\n\t\tthis.#mountCount = 0;\n\t}\n\t/**\n\t* Called by a framework adapter's `QueryClientProvider`-equivalent when it mounts, to start\n\t* listening for focus/online events and resume paused mutations. Ref-counted via an internal\n\t* mount count, so nested or multiple providers sharing the same `QueryClient` don't tear down\n\t* the shared listeners until the last one unmounts.\n\t*/\n\tmount() {\n\t\tthis.#mountCount++;\n\t\tif (this.#mountCount !== 1) return;\n\t\tthis.#unsubscribeFocus = focusManager.subscribe(async (focused) => {\n\t\t\tif (focused) {\n\t\t\t\tawait this.resumePausedMutations();\n\t\t\t\tthis.#queryCache.onFocus();\n\t\t\t}\n\t\t});\n\t\tthis.#unsubscribeOnline = onlineManager.subscribe(async (online) => {\n\t\t\tif (online) {\n\t\t\t\tawait this.resumePausedMutations();\n\t\t\t\tthis.#queryCache.onOnline();\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* The inverse of {@link QueryClient#mount} — called by a framework adapter's\n\t* `QueryClientProvider`-equivalent when it unmounts. Only tears down the focus/online\n\t* listeners once the mount count returns to `0`.\n\t*/\n\tunmount() {\n\t\tthis.#mountCount--;\n\t\tif (this.#mountCount !== 0) return;\n\t\tthis.#unsubscribeFocus?.();\n\t\tthis.#unsubscribeFocus = void 0;\n\t\tthis.#unsubscribeOnline?.();\n\t\tthis.#unsubscribeOnline = void 0;\n\t}\n\t/**\n\t* Returns the number of queries in the cache that are currently fetching, optionally\n\t* matching a set of filters. This includes background-fetching, loading new pages, and\n\t* loading more infinite query results.\n\t* @param filters - Narrows down which fetching queries are counted. Without filters, every\n\t* fetching query is counted.\n\t* @returns The number of matching queries whose `fetchStatus` is `'fetching'`.\n\t* @example\n\t* ```ts\n\t* if (queryClient.isFetching()) {\n\t*   console.log('At least one query is fetching!')\n\t* }\n\t* ```\n\t*/\n\tisFetching(filters) {\n\t\treturn this.#queryCache.findAll({\n\t\t\t...filters,\n\t\t\tfetchStatus: \"fetching\"\n\t\t}).length;\n\t}\n\t/**\n\t* Returns the number of mutations in the cache that are currently pending, optionally\n\t* matching a set of filters.\n\t* @param filters - Narrows down which pending mutations are counted. Without filters, every\n\t* pending mutation is counted.\n\t* @returns The number of matching mutations whose `status` is `'pending'`.\n\t* @example\n\t* ```ts\n\t* if (queryClient.isMutating()) {\n\t*   console.log('At least one mutation is pending!')\n\t* }\n\t* ```\n\t*/\n\tisMutating(filters) {\n\t\treturn this.#mutationCache.findAll({\n\t\t\t...filters,\n\t\t\tstatus: \"pending\"\n\t\t}).length;\n\t}\n\t/**\n\t* Imperative (non-reactive) way to retrieve data for a QueryKey.\n\t* Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates.\n\t*\n\t* Hint: Do not use this function inside a component, because it won't receive updates.\n\t* Use `useQuery` to create a `QueryObserver` that subscribes to changes.\n\t* @param queryKey - The query key of the query to read.\n\t* @returns The cached data for the query, or `undefined` if no query with this key has been observed yet.\n\t* @see {@link QueryClient#getQueriesData}\n\t*/\n\tgetQueryData(queryKey) {\n\t\tconst options = this.defaultQueryOptions({ queryKey });\n\t\treturn this.#queryCache.get(options.queryHash)?.state.data;\n\t}\n\t/**\n\t* Returns the cached data of a query, or fetches it if there is none. With `revalidateIfStale`,\n\t* stale cached data is also refetched in the background.\n\t* @param options - The query options. If the query has no cached data yet, it is fetched with\n\t* these options.\n\t* @returns A promise that resolves to the cached data, or to the fetched data if nothing was\n\t* cached yet.\n\t* @deprecated Use queryClient.query({ ...options, staleTime: 'static' }) instead. This method will be removed in the next major version.\n\t*/\n\tensureQueryData(options) {\n\t\tconst defaultedOptions = this.defaultQueryOptions(options);\n\t\tconst query = this.#queryCache.build(this, defaultedOptions);\n\t\tconst cachedData = query.state.data;\n\t\tif (cachedData === void 0) return this.fetchQuery(options);\n\t\tif (options.revalidateIfStale && query.isStaleByTime(resolveQueryValue(defaultedOptions.staleTime, query))) this.prefetchQuery(defaultedOptions);\n\t\treturn Promise.resolve(cachedData);\n\t}\n\t/**\n\t* Imperative (non-reactive) way to retrieve the cached data of multiple queries at once.\n\t* Only queries matching the given filters are returned; if none match, an empty array is\n\t* returned.\n\t*\n\t* Because the matched queries can hold data of different shapes (e.g. a broad filter can match\n\t* queries with unrelated data types), the `TQueryFnData` generic defaults to `unknown` rather\n\t* than being inferred. Passing a more specific type is a convenience for call sites that know\n\t* every matched query holds the same shape — it is not checked against the actual cache\n\t* contents.\n\t* @param filters - The filters that select which queries to read.\n\t* @returns An array of query key and data pairs. The data is `undefined` for a query with no cached data.\n\t* @see {@link QueryClient#getQueryData}\n\t* @example\n\t* ```ts\n\t* const data = queryClient.getQueriesData({ queryKey: ['posts'] })\n\t* ```\n\t*/\n\tgetQueriesData(filters) {\n\t\treturn this.#queryCache.findAll(filters).map(({ queryKey, state }) => {\n\t\t\treturn [queryKey, state.data];\n\t\t});\n\t}\n\t/**\n\t* Synchronous way to immediately update a query's cached data. If the updater (or the value\n\t* passed) resolves to `undefined`, the cache is left untouched and no query is created;\n\t* otherwise, if the query does not exist yet, it will be created. To update multiple queries\n\t* at once by partially matching query keys, use {@link QueryClient#setQueriesData} instead.\n\t*\n\t* Updates must be performed immutably: do not mutate `oldData`, or data previously retrieved\n\t* via {@link QueryClient#getQueryData}, in place.\n\t* @param queryKey - The query key to set data for.\n\t* @param updater - Either the new data, or a function that receives the current data (which\n\t* may be `undefined`) and returns the new data.\n\t* @param options - Set `updatedAt` to override the timestamp the written data is recorded with.\n\t* @returns The data that was written, or `undefined` if the updater returned `undefined` — in that case\n\t* the write is skipped and the cache is left unchanged.\n\t* @example\n\t* ```ts\n\t* queryClient.setQueryData(['posts'], newPosts)\n\t*\n\t* // Or, using an updater function that receives the current data:\n\t* queryClient.setQueryData(['posts'], (oldPosts) => [...oldPosts, newPost])\n\t* ```\n\t*/\n\tsetQueryData(queryKey, updater, options) {\n\t\tconst defaultedOptions = this.defaultQueryOptions({ queryKey });\n\t\tconst prevData = this.#queryCache.get(defaultedOptions.queryHash)?.state.data;\n\t\tconst data = functionalUpdate(updater, prevData);\n\t\tif (data === void 0) return;\n\t\treturn this.#queryCache.build(this, defaultedOptions).setData(data, {\n\t\t\t...options,\n\t\t\tmanual: true\n\t\t});\n\t}\n\t/**\n\t* Synchronous way to immediately update the cached data of multiple queries at once, using\n\t* filters or partial query key matching. Only queries that already exist and match the given\n\t* filters are updated; no new cache entries are created. Internally this calls\n\t* {@link QueryClient#setQueryData} for each matching query.\n\t* @param filters - The filters that select which existing queries to update.\n\t* @param updater - Either the new data, or a function that receives each matched query's current\n\t* data (which may be `undefined`) and returns the new data.\n\t* @param options - Set `updatedAt` to override the timestamp the written data is recorded with.\n\t* @returns One `[queryKey, data]` tuple per matched query, in the same shape and with the same\n\t* `undefined` case as {@link QueryClient#setQueryData}.\n\t* @example\n\t* ```ts\n\t* queryClient.setQueriesData({ queryKey: ['posts'] }, (oldPosts) =>\n\t*   oldPosts ? oldPosts.filter((post) => post.id !== deletedId) : oldPosts,\n\t* )\n\t* ```\n\t*/\n\tsetQueriesData(filters, updater, options) {\n\t\treturn notifyManager.batch(() => this.#queryCache.findAll(filters).map(({ queryKey }) => [queryKey, this.setQueryData(queryKey, updater, options)]));\n\t}\n\t/**\n\t* Imperative (non-reactive) way to retrieve an existing query's state. If the query does not\n\t* exist, `undefined` is returned.\n\t* @param queryKey - The query key of the query to read.\n\t* @returns The query's state, or `undefined` if no query with this key exists.\n\t* @example\n\t* ```ts\n\t* const state = queryClient.getQueryState(['posts'])\n\t* console.log(state?.dataUpdatedAt)\n\t* ```\n\t*/\n\tgetQueryState(queryKey) {\n\t\tconst options = this.defaultQueryOptions({ queryKey });\n\t\treturn this.#queryCache.get(options.queryHash)?.state;\n\t}\n\t/**\n\t* Removes queries from the cache that match the given filters. Unlike\n\t* {@link QueryClient#invalidateQueries} or {@link QueryClient#refetchQueries}, this removes\n\t* matching queries from the cache instead of refetching them. Without filters, every query in\n\t* the cache is removed.\n\t* @param filters - The filters that select which queries to remove. Without filters, every query\n\t* is removed.\n\t* @example\n\t* ```ts\n\t* queryClient.removeQueries({ queryKey: ['posts'], exact: true })\n\t* ```\n\t*/\n\tremoveQueries(filters) {\n\t\tconst queryCache = this.#queryCache;\n\t\tnotifyManager.batch(() => {\n\t\t\tqueryCache.findAll(filters).forEach((query) => {\n\t\t\t\tqueryCache.remove(query);\n\t\t\t});\n\t\t});\n\t}\n\t/**\n\t* Resets queries matching the given filters back to their initial state (e.g. any\n\t* `initialData`), notifying subscribers rather than removing them. Active queries among the\n\t* matched set are then refetched, and the returned promise resolves once that refetch settles.\n\t* @param filters - The filters that select which queries to reset. Without filters, every query\n\t* is reset.\n\t* @param options - Passed to the refetch of the active matched queries, e.g. `cancelRefetch` and\n\t* `throwOnError`.\n\t* @returns A promise that resolves once the refetch of the active matched queries settles.\n\t* @example\n\t* ```ts\n\t* await queryClient.resetQueries({ queryKey: ['posts'], exact: true })\n\t* ```\n\t*/\n\tresetQueries(filters, options) {\n\t\tconst queryCache = this.#queryCache;\n\t\treturn notifyManager.batch(() => {\n\t\t\tconst matched = queryCache.findAll(filters);\n\t\t\tconst queriesToRefetch = new Set(matched);\n\t\t\tmatched.forEach((query) => {\n\t\t\t\tquery.reset();\n\t\t\t});\n\t\t\treturn this.refetchQueries({\n\t\t\t\ttype: \"active\",\n\t\t\t\tpredicate: (query) => queriesToRefetch.has(query)\n\t\t\t}, options);\n\t\t});\n\t}\n\t/**\n\t* Cancels outgoing fetches for queries matching the given filters. Most useful when performing\n\t* optimistic updates, since any outgoing refetch that resolves afterwards would otherwise\n\t* overwrite the optimistic update. By default (`revert: true`), a cancelled query's data is\n\t* reverted to its state before the outgoing fetch started.\n\t*\n\t* The returned promise never rejects, even if individual cancellations fail.\n\t* @param filters - The filters that select which queries to cancel. Without filters, every query\n\t* is cancelled.\n\t* @param cancelOptions - Passed to each matched query's cancellation. `revert` defaults to\n\t* `true`.\n\t* @returns A promise that resolves once every cancellation has settled.\n\t* @example\n\t* ```ts\n\t* await queryClient.cancelQueries({ queryKey: ['posts'], exact: true })\n\t* ```\n\t*/\n\tcancelQueries(filters, cancelOptions = {}) {\n\t\tconst defaultedCancelOptions = {\n\t\t\trevert: true,\n\t\t\t...cancelOptions\n\t\t};\n\t\tconst promises = notifyManager.batch(() => this.#queryCache.findAll(filters).map((query) => query.cancel(defaultedCancelOptions)));\n\t\treturn Promise.all(promises).then(noop).catch(noop);\n\t}\n\t/**\n\t* Marks queries matching the given filters as invalidated. Unlike\n\t* {@link QueryClient#removeQueries}, invalidated queries stay in the cache.\n\t*\n\t* Unless `filters.refetchType` is `'none'`, matching queries are then refetched via\n\t* {@link QueryClient#refetchQueries}, using `filters.refetchType` if set, otherwise\n\t* `filters.type`, otherwise `'active'`.\n\t* @param filters - The filters that select which queries to invalidate, plus `refetchType` to\n\t* control which of them to refetch afterwards. Without filters, every query is invalidated.\n\t* @param options - Passed to {@link QueryClient#refetchQueries}, e.g. `cancelRefetch` and\n\t* `throwOnError`.\n\t* @returns A promise that resolves once the refetch settles, or immediately if `refetchType` is\n\t* `'none'`.\n\t* @example\n\t* ```ts\n\t* await queryClient.invalidateQueries({ queryKey: ['posts'], refetchType: 'active' })\n\t* ```\n\t*/\n\tinvalidateQueries(filters, options = {}) {\n\t\treturn notifyManager.batch(() => {\n\t\t\tthis.#queryCache.findAll(filters).forEach((query) => {\n\t\t\t\tquery.invalidate();\n\t\t\t});\n\t\t\tif (filters?.refetchType === \"none\") return Promise.resolve();\n\t\t\treturn this.refetchQueries({\n\t\t\t\t...filters,\n\t\t\t\ttype: filters?.refetchType ?? filters?.type ?? \"active\"\n\t\t\t}, options);\n\t\t});\n\t}\n\t/**\n\t* Refetches queries matching the given filters, regardless of whether they are stale. Without\n\t* filters, every query in the cache is refetched. Queries that are disabled, or static (only\n\t* have observers with a static `staleTime`), are never refetched.\n\t*\n\t* By default (`cancelRefetch: true`), a currently running fetch is cancelled before the new\n\t* one starts. The returned promise does not reject on individual query failures unless\n\t* `throwOnError` is `true`.\n\t*\n\t* Initially paused fetches do not delay the returned promise. Their later errors are handled\n\t* even when `throwOnError` is `true`.\n\t* @param filters - The filters that select which queries to refetch. Without filters, every query\n\t* in the cache is included.\n\t* @param options - Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling\n\t* it, and `throwOnError` to `true` to reject when a refetch that was not initially paused fails.\n\t* @returns A promise that resolves once all matching refetches that were not initially paused\n\t* have settled.\n\t* @example\n\t* ```ts\n\t* // refetch all active queries partially matching a query key:\n\t* await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' })\n\t* ```\n\t*/\n\trefetchQueries(filters, options = {}) {\n\t\tconst fetchOptions = {\n\t\t\t...options,\n\t\t\tcancelRefetch: options.cancelRefetch ?? true\n\t\t};\n\t\tconst promises = notifyManager.batch(() => this.#queryCache.findAll(filters).filter((query) => !query.isDisabled() && !query.isStatic()).map((query) => {\n\t\t\tlet promise = query.fetch(void 0, fetchOptions);\n\t\t\tconst isPaused = query.state.fetchStatus === \"paused\";\n\t\t\tif (!fetchOptions.throwOnError || isPaused) promise = promise.catch(noop);\n\t\t\treturn isPaused ? Promise.resolve() : promise;\n\t\t}));\n\t\treturn Promise.all(promises).then(noop);\n\t}\n\t/**\n\t* Asynchronous method to fetch and cache a query, resolving with the data or throwing with\n\t* the error.\n\t*\n\t* If the query already exists in the cache and its data is not stale (per the given\n\t* `staleTime`), the cached data is returned without fetching. Otherwise, the query is fetched\n\t* and the promise resolves once the fetch settles. If a `select` function is provided, it is\n\t* applied to the data in both cases (cached or freshly fetched) before it is returned.\n\t*\n\t* Unlike a reactive observer, retries are disabled by default here (`retry: false`) unless\n\t* explicitly configured, since there is no component to catch a thrown error and retry through\n\t* re-render.\n\t*\n\t* The accepted options are `QueryObserverOptions` minus the fields that only make sense for a\n\t* reactive observer — `enabled`, `refetchInterval`, `refetchIntervalInBackground`,\n\t* `refetchOnWindowFocus`, `refetchOnReconnect`, `refetchOnMount`, `retryOnMount`,\n\t* `notifyOnChangeProps`, `throwOnError`, `suspense`, and `placeholderData` are not part of this\n\t* method's options.\n\t*\n\t* This method replaces the deprecated `fetchQuery`, and — combined with\n\t* `{ staleTime: 'static' }` — the deprecated `ensureQueryData`.\n\t* @param options - The query options, including the `queryKey` and the `queryFn` used if the\n\t* query needs to fetch.\n\t* @returns A promise that resolves to the data, or to the result of `select` if provided. It\n\t* rejects with the error from the fetch or from `select`.\n\t* @example\n\t* ```ts\n\t* try {\n\t*   const data = await queryClient.query({ queryKey, queryFn, staleTime: 10000 })\n\t* } catch (error) {\n\t*   console.log(error)\n\t* }\n\t* ```\n\t*/\n\tasync query(options) {\n\t\tconst defaultedOptions = this.defaultQueryOptions(options);\n\t\tif (defaultedOptions.retry === void 0) defaultedOptions.retry = false;\n\t\tconst query = this.#queryCache.build(this, defaultedOptions);\n\t\tconst queryData = query.isStaleByTime(resolveQueryValue(defaultedOptions.staleTime, query)) ? await query.fetch(defaultedOptions) : query.state.data;\n\t\tconst select = defaultedOptions.select;\n\t\tif (select) return select(queryData);\n\t\treturn queryData;\n\t}\n\t/**\n\t* Fetches and caches a query, or returns its cached data if it isn't stale. Unlike in observers,\n\t* the fetch isn't retried unless `retry` is set.\n\t* @param options - The query options, including the `queryKey` and the `queryFn` used if the\n\t* query needs to fetch.\n\t* @returns A promise that resolves to the cached or fetched data, or rejects with the fetch\n\t* error.\n\t* @deprecated Use queryClient.query(options) instead. This method will be removed in the next major version.\n\t*/\n\tfetchQuery(options) {\n\t\tconst defaultedOptions = this.defaultQueryOptions(options);\n\t\tif (defaultedOptions.retry === void 0) defaultedOptions.retry = false;\n\t\tconst query = this.#queryCache.build(this, defaultedOptions);\n\t\treturn query.isStaleByTime(resolveQueryValue(defaultedOptions.staleTime, query)) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);\n\t}\n\t/**\n\t* Fetches and caches a query like {@link QueryClient#fetchQuery}, but ignores the result and any\n\t* error.\n\t* @param options - The query options, including the `queryKey` and the `queryFn` used if the\n\t* query needs to fetch.\n\t* @returns A promise that resolves once the fetch settles. It never rejects.\n\t* @deprecated Use queryClient.query(options) instead. You can swallow errors with `.catch(noop)`. This method will be removed in the next major version.\n\t*/\n\tprefetchQuery(options) {\n\t\treturn this.fetchQuery(options).then(noop).catch(noop);\n\t}\n\t/**\n\t* Asynchronous method to fetch and cache an infinite query, resolving with an\n\t* {@link InfiniteData} object or throwing with the error.\n\t*\n\t* Behaves like {@link QueryClient#query}, accepting the same options (minus\n\t* `initialPageParam`), plus the required `initialPageParam`, and an optional `pages` /\n\t* `getNextPageParam` pair used to refetch a fixed number of pages from the start.\n\t*\n\t* This method replaces the deprecated `fetchInfiniteQuery`, and — combined with\n\t* `{ staleTime: 'static' }` — the deprecated `ensureInfiniteQueryData`.\n\t* @param options - The infinite query options, including the `queryKey`, the `queryFn`, and the\n\t* `initialPageParam`.\n\t* @returns A promise that resolves to the {@link InfiniteData}, or to the result of `select` if\n\t* provided. It rejects with the error from the fetch or from `select`.\n\t* @example\n\t* ```ts\n\t* try {\n\t*   const data = await queryClient.infiniteQuery({ queryKey, queryFn, initialPageParam: 0 })\n\t*   console.log(data.pages)\n\t* } catch (error) {\n\t*   console.log(error)\n\t* }\n\t* ```\n\t*/\n\tinfiniteQuery(options) {\n\t\toptions._type = \"infinite\";\n\t\treturn this.query(options);\n\t}\n\t/**\n\t* Fetches and caches an infinite query, or returns its cached data if it isn't stale.\n\t* @param options - The infinite query options, including the `queryKey`, the `queryFn`, and the\n\t* `initialPageParam`.\n\t* @returns A promise that resolves to the cached or fetched {@link InfiniteData}, or rejects with\n\t* the fetch error.\n\t* @deprecated Use queryClient.infiniteQuery(options) instead. This method will be removed in the next major version.\n\t*/\n\tfetchInfiniteQuery(options) {\n\t\toptions._type = \"infinite\";\n\t\treturn this.fetchQuery(options);\n\t}\n\t/**\n\t* Fetches and caches an infinite query like {@link QueryClient#fetchInfiniteQuery}, but ignores\n\t* the result and any error.\n\t* @param options - The infinite query options, including the `queryKey`, the `queryFn`, and the\n\t* `initialPageParam`.\n\t* @returns A promise that resolves once the fetch settles. It never rejects.\n\t* @deprecated Use queryClient.infiniteQuery(options) instead. You can swallow errors with `.catch(noop)`. This method will be removed in the next major version.\n\t*/\n\tprefetchInfiniteQuery(options) {\n\t\treturn this.fetchInfiniteQuery(options).then(noop).catch(noop);\n\t}\n\t/**\n\t* Returns the cached data of an infinite query, or fetches it if there is none. With\n\t* `revalidateIfStale`, stale cached data is also refetched in the background.\n\t* @param options - The infinite query options. If the query has no cached data yet, it is fetched\n\t* with these options.\n\t* @returns A promise that resolves to the cached {@link InfiniteData}, or to the fetched data if\n\t* nothing was cached yet.\n\t* @deprecated Use queryClient.infiniteQuery({ ...options, staleTime: 'static' }) instead. This method will be removed in the next major version.\n\t*/\n\tensureInfiniteQueryData(options) {\n\t\toptions._type = \"infinite\";\n\t\treturn this.ensureQueryData(options);\n\t}\n\t/**\n\t* Resumes mutations that were paused because there was no network connection. Does nothing\n\t* (resolving immediately) if the client is currently offline.\n\t* @returns A promise that resolves once the resumed mutations have settled.\n\t* @example\n\t* ```ts\n\t* import { QueryClient } from '@tanstack/query-core'\n\t*\n\t* const queryClient = new QueryClient()\n\t* await queryClient.resumePausedMutations()\n\t* ```\n\t*/\n\tresumePausedMutations() {\n\t\tif (onlineManager.isOnline()) return this.#mutationCache.resumePausedMutations();\n\t\treturn Promise.resolve();\n\t}\n\t/**\n\t* Returns the query cache this client is connected to.\n\t* @returns The {@link QueryCache} instance.\n\t* @example\n\t* ```ts\n\t* import { QueryClient } from '@tanstack/query-core'\n\t*\n\t* const queryClient = new QueryClient()\n\t* const queryCache = queryClient.getQueryCache()\n\t* const queries = queryCache.findAll({ queryKey: ['posts'] })\n\t* ```\n\t*/\n\tgetQueryCache() {\n\t\treturn this.#queryCache;\n\t}\n\t/**\n\t* Returns the mutation cache this client is connected to.\n\t* @returns The {@link MutationCache} instance.\n\t* @example\n\t* ```ts\n\t* import { QueryClient } from '@tanstack/query-core'\n\t*\n\t* const queryClient = new QueryClient()\n\t* const mutationCache = queryClient.getMutationCache()\n\t* const mutations = mutationCache.findAll({ status: 'pending' })\n\t* ```\n\t*/\n\tgetMutationCache() {\n\t\treturn this.#mutationCache;\n\t}\n\t/**\n\t* Returns the default options that were set when creating the client, or via\n\t* {@link QueryClient#setDefaultOptions}.\n\t* @returns The client's current default options.\n\t* @example\n\t* ```ts\n\t* import { QueryClient } from '@tanstack/query-core'\n\t*\n\t* const queryClient = new QueryClient()\n\t* const defaultOptions = queryClient.getDefaultOptions()\n\t* ```\n\t*/\n\tgetDefaultOptions() {\n\t\treturn this.#defaultOptions;\n\t}\n\t/**\n\t* Dynamically sets the default options for this client, overwriting any previously defined\n\t* default options.\n\t* @param options - The new default options for queries and mutations.\n\t* @see {@link QueryClient#getDefaultOptions}\n\t* @example\n\t* ```ts\n\t* import { QueryClient } from '@tanstack/query-core'\n\t*\n\t* const queryClient = new QueryClient()\n\t* queryClient.setDefaultOptions({\n\t*   queries: {\n\t*     staleTime: Infinity,\n\t*   },\n\t* })\n\t* ```\n\t*/\n\tsetDefaultOptions(options) {\n\t\tthis.#defaultOptions = options;\n\t}\n\t/**\n\t* Sets default options for queries whose query key partially matches the given `queryKey`.\n\t*\n\t* If several registered query defaults match a given query key, they are merged together in\n\t* registration order by {@link QueryClient#getQueryDefaults}, so register defaults from the\n\t* most generic key to the least generic one — more specific defaults should be registered\n\t* after more generic ones so they take precedence.\n\t* @param queryKey - The query key that query keys are partially matched against.\n\t* @param options - The default options applied to matching queries.\n\t* @example\n\t* ```ts\n\t* queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts })\n\t*\n\t* await queryClient.query({ queryKey: ['posts'] })\n\t* ```\n\t*/\n\tsetQueryDefaults(queryKey, options) {\n\t\tthis.#queryDefaults.set(hashKey(queryKey), {\n\t\t\tqueryKey,\n\t\t\tdefaultOptions: options\n\t\t});\n\t}\n\t/**\n\t* Returns the default options registered for queries whose query key partially matches the\n\t* given `queryKey`, via {@link QueryClient#setQueryDefaults}. If multiple registered defaults\n\t* match, they are merged together in registration order.\n\t* @param queryKey - The query key to look up registered defaults for.\n\t* @returns The merged default options of every registration that matches, or an empty object if\n\t* none match.\n\t* @example\n\t* ```ts\n\t* const defaultOptions = queryClient.getQueryDefaults(['posts'])\n\t* ```\n\t*/\n\tgetQueryDefaults(queryKey) {\n\t\tconst defaults = [...this.#queryDefaults.values()];\n\t\tconst result = {};\n\t\tdefaults.forEach((queryDefault) => {\n\t\t\tif (partialMatchKey(queryKey, queryDefault.queryKey)) Object.assign(result, queryDefault.defaultOptions);\n\t\t});\n\t\treturn result;\n\t}\n\t/**\n\t* Sets default options for mutations whose mutation key partially matches the given\n\t* `mutationKey`. As with {@link QueryClient#setQueryDefaults}, the order of registration\n\t* matters when several registered defaults match the same mutation key.\n\t* @param mutationKey - The mutation key that mutation keys are partially matched against.\n\t* @param options - The default options applied to matching mutations.\n\t* @see {@link QueryClient#getMutationDefaults}\n\t* @example\n\t* ```ts\n\t* queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost })\n\t* ```\n\t*/\n\tsetMutationDefaults(mutationKey, options) {\n\t\tthis.#mutationDefaults.set(hashKey(mutationKey), {\n\t\t\tmutationKey,\n\t\t\tdefaultOptions: options\n\t\t});\n\t}\n\t/**\n\t* Returns the default options registered for mutations whose mutation key partially matches\n\t* the given `mutationKey`, via {@link QueryClient#setMutationDefaults}. If multiple registered\n\t* defaults match, they are merged together in registration order.\n\t* @param mutationKey - The mutation key to look up registered defaults for.\n\t* @returns The merged default options of every registration that matches, or an empty object if\n\t* none match.\n\t* @example\n\t* ```ts\n\t* const defaultOptions = queryClient.getMutationDefaults(['addPost'])\n\t* ```\n\t*/\n\tgetMutationDefaults(mutationKey) {\n\t\tconst defaults = [...this.#mutationDefaults.values()];\n\t\tconst result = {};\n\t\tdefaults.forEach((queryDefault) => {\n\t\t\tif (partialMatchKey(mutationKey, queryDefault.mutationKey)) Object.assign(result, queryDefault.defaultOptions);\n\t\t});\n\t\treturn result;\n\t}\n\t/**\n\t* Called by framework adapters (e.g. inside `useQuery`) to resolve the options passed by the\n\t* caller into their final, defaulted form: merging the client's own `defaultOptions.queries`,\n\t* then `queryClient.setQueryDefaults` for the given `queryKey`, then the caller's options on\n\t* top. A no-op if the options are already defaulted (`_defaulted: true`).\n\t* @param options - The query options passed by the caller.\n\t* @returns The defaulted options, with `queryHash` and dependent defaults (e.g.\n\t* `refetchOnReconnect`) filled in.\n\t*/\n\tdefaultQueryOptions(options) {\n\t\tif (options._defaulted) return options;\n\t\tconst defaultedOptions = {\n\t\t\t...this.#defaultOptions.queries,\n\t\t\t...this.getQueryDefaults(options.queryKey),\n\t\t\t...options,\n\t\t\t_defaulted: true\n\t\t};\n\t\tif (!defaultedOptions.queryHash) defaultedOptions.queryHash = hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions);\n\t\tif (defaultedOptions.refetchOnReconnect === void 0) defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== \"always\";\n\t\tif (defaultedOptions.throwOnError === void 0) defaultedOptions.throwOnError = !!defaultedOptions.suspense;\n\t\tif (!defaultedOptions.networkMode && defaultedOptions.persister) defaultedOptions.networkMode = \"offlineFirst\";\n\t\tif (defaultedOptions.queryFn === skipToken) defaultedOptions.enabled = false;\n\t\treturn defaultedOptions;\n\t}\n\t/**\n\t* The mutation counterpart of {@link QueryClient#defaultQueryOptions}. Called by framework\n\t* adapters (e.g. inside `useMutation`) to merge the client's `defaultOptions.mutations`, then\n\t* `queryClient.setMutationDefaults` for the given `mutationKey`, then the caller's options on\n\t* top. A no-op if the options are already defaulted (`_defaulted: true`).\n\t* @param options - The mutation options passed by the caller.\n\t* @returns The defaulted options.\n\t*/\n\tdefaultMutationOptions(options) {\n\t\tif (options?._defaulted) return options;\n\t\treturn {\n\t\t\t...this.#defaultOptions.mutations,\n\t\t\t...options?.mutationKey && this.getMutationDefaults(options.mutationKey),\n\t\t\t...options,\n\t\t\t_defaulted: true\n\t\t};\n\t}\n\t/**\n\t* Clears both the query cache and the mutation cache this client is connected to.\n\t* @example\n\t* ```ts\n\t* import { QueryClient } from '@tanstack/query-core'\n\t*\n\t* const queryClient = new QueryClient()\n\t* queryClient.clear()\n\t* ```\n\t*/\n\tclear() {\n\t\tthis.#queryCache.clear();\n\t\tthis.#mutationCache.clear();\n\t}\n};\nexport { QueryClient };\n\n//# sourceMappingURL=queryClient.js.map","import { stringifyJSON, isAsyncIteratorObject, toArray, isTypescriptObject, get } from '@orpc/shared';\nimport { skipToken } from '@tanstack/query-core';\nimport { RECURSIVE_CLIENT_UNWRAP_KEYS } from '@orpc/client';\n\nfunction generateOperationKey(path, state = {}) {\n  return [path, {\n    ...state.input !== void 0 ? { input: state.input } : {},\n    ...state.type !== void 0 ? { type: state.type } : {},\n    ...state.fnOptions !== void 0 ? { fnOptions: state.fnOptions } : {}\n  }];\n}\n\nfunction createGeneralUtils(path) {\n  return {\n    key(options) {\n      return generateOperationKey(path, options);\n    }\n  };\n}\n\nfunction experimental_liveQuery(queryFn) {\n  return async (context) => {\n    const stream = await queryFn(context);\n    let last;\n    for await (const chunk of stream) {\n      if (context.signal.aborted) {\n        throw context.signal.reason;\n      }\n      last = { chunk };\n      context.client.setQueryData(context.queryKey, chunk);\n    }\n    if (!last) {\n      throw new Error(\n        `Live query for ${stringifyJSON(context.queryKey)} did not yield any data. Ensure the query function returns an AsyncIterable with at least one chunk.`\n      );\n    }\n    return last.chunk;\n  };\n}\n\nfunction experimental_serializableStreamedQuery(queryFn, { refetchMode = \"reset\", maxChunks = Number.POSITIVE_INFINITY } = {}) {\n  return async (context) => {\n    const query = context.client.getQueryCache().find({ queryKey: context.queryKey, exact: true });\n    const hasPreviousData = !!query && query.state.data !== void 0;\n    if (hasPreviousData) {\n      if (refetchMode === \"reset\") {\n        query.setState({\n          status: \"pending\",\n          data: void 0,\n          error: null,\n          fetchStatus: \"fetching\"\n        });\n      } else {\n        context.client.setQueryData(\n          context.queryKey,\n          (prev = []) => limitArraySize(prev, maxChunks)\n        );\n      }\n    }\n    let result = [];\n    const stream = await queryFn(context);\n    const shouldUpdateCacheDuringStream = !hasPreviousData || refetchMode !== \"replace\";\n    context.client.setQueryData(\n      context.queryKey,\n      (prev = []) => limitArraySize(prev, maxChunks)\n    );\n    for await (const chunk of stream) {\n      if (context.signal.aborted) {\n        throw context.signal.reason;\n      }\n      result.push(chunk);\n      result = limitArraySize(result, maxChunks);\n      if (shouldUpdateCacheDuringStream) {\n        context.client.setQueryData(\n          context.queryKey,\n          (prev = []) => limitArraySize([...prev, chunk], maxChunks)\n        );\n      }\n    }\n    if (!shouldUpdateCacheDuringStream) {\n      context.client.setQueryData(context.queryKey, result);\n    }\n    const cachedData = context.client.getQueryData(context.queryKey);\n    if (cachedData) {\n      return limitArraySize(cachedData, maxChunks);\n    }\n    return result;\n  };\n}\nfunction limitArraySize(items, maxSize) {\n  if (items.length <= maxSize) {\n    return items;\n  }\n  return items.slice(items.length - maxSize);\n}\n\nconst OPERATION_CONTEXT_SYMBOL = Symbol(\"ORPC_OPERATION_CONTEXT\");\n\nfunction createProcedureUtils(client, options) {\n  const utils = {\n    call: client,\n    queryKey(...[optionsIn = {}]) {\n      optionsIn = { ...options.experimental_defaults?.queryKey, ...optionsIn };\n      const queryKey = optionsIn.queryKey ?? generateOperationKey(options.path, { type: \"query\", input: optionsIn.input });\n      return queryKey;\n    },\n    queryOptions(...[optionsIn = {}]) {\n      optionsIn = { ...options.experimental_defaults?.queryOptions, ...optionsIn };\n      const queryKey = utils.queryKey(optionsIn);\n      return {\n        queryFn: ({ signal }) => {\n          if (optionsIn.input === skipToken) {\n            throw new Error(\"queryFn should not be called with skipToken used as input\");\n          }\n          return client(optionsIn.input, {\n            signal,\n            context: {\n              [OPERATION_CONTEXT_SYMBOL]: {\n                key: queryKey,\n                type: \"query\"\n              },\n              ...optionsIn.context\n            }\n          });\n        },\n        ...optionsIn.input === skipToken ? { enabled: false } : {},\n        ...optionsIn,\n        queryKey\n      };\n    },\n    experimental_streamedKey(...[optionsIn = {}]) {\n      optionsIn = { ...options.experimental_defaults?.experimental_streamedKey, ...optionsIn };\n      const queryKey = optionsIn.queryKey ?? generateOperationKey(options.path, { type: \"streamed\", input: optionsIn.input, fnOptions: optionsIn.queryFnOptions });\n      return queryKey;\n    },\n    experimental_streamedOptions(...[optionsIn = {}]) {\n      optionsIn = { ...options.experimental_defaults?.experimental_streamedOptions, ...optionsIn };\n      const queryKey = utils.experimental_streamedKey(optionsIn);\n      return {\n        queryFn: experimental_serializableStreamedQuery(\n          async ({ signal }) => {\n            if (optionsIn.input === skipToken) {\n              throw new Error(\"queryFn should not be called with skipToken used as input\");\n            }\n            const output = await client(optionsIn.input, {\n              signal,\n              context: {\n                [OPERATION_CONTEXT_SYMBOL]: {\n                  key: queryKey,\n                  type: \"streamed\"\n                },\n                ...optionsIn.context\n              }\n            });\n            if (!isAsyncIteratorObject(output)) {\n              throw new Error(\"streamedQuery requires an event iterator output\");\n            }\n            return output;\n          },\n          optionsIn.queryFnOptions\n        ),\n        ...optionsIn.input === skipToken ? { enabled: false } : {},\n        ...optionsIn,\n        queryKey\n      };\n    },\n    experimental_liveKey(...[optionsIn = {}]) {\n      optionsIn = { ...options.experimental_defaults?.experimental_liveKey, ...optionsIn };\n      const queryKey = optionsIn.queryKey ?? generateOperationKey(options.path, { type: \"live\", input: optionsIn.input });\n      return queryKey;\n    },\n    experimental_liveOptions(...[optionsIn = {}]) {\n      optionsIn = { ...options.experimental_defaults?.experimental_liveOptions, ...optionsIn };\n      const queryKey = utils.experimental_liveKey(optionsIn);\n      return {\n        queryFn: experimental_liveQuery(async ({ signal }) => {\n          if (optionsIn.input === skipToken) {\n            throw new Error(\"queryFn should not be called with skipToken used as input\");\n          }\n          const output = await client(optionsIn.input, {\n            signal,\n            context: {\n              [OPERATION_CONTEXT_SYMBOL]: {\n                key: queryKey,\n                type: \"live\"\n              },\n              ...optionsIn.context\n            }\n          });\n          if (!isAsyncIteratorObject(output)) {\n            throw new Error(\"liveQuery requires an event iterator output\");\n          }\n          return output;\n        }),\n        ...optionsIn.input === skipToken ? { enabled: false } : {},\n        ...optionsIn,\n        queryKey\n      };\n    },\n    infiniteKey(optionsIn) {\n      optionsIn = { ...options.experimental_defaults?.infiniteKey, ...optionsIn };\n      const queryKey = optionsIn.queryKey ?? generateOperationKey(options.path, {\n        type: \"infinite\",\n        input: optionsIn.input === skipToken ? skipToken : optionsIn.input(optionsIn.initialPageParam)\n      });\n      return queryKey;\n    },\n    infiniteOptions(optionsIn) {\n      optionsIn = { ...options.experimental_defaults?.infiniteOptions, ...optionsIn };\n      const queryKey = utils.infiniteKey(optionsIn);\n      return {\n        queryFn: ({ pageParam, signal }) => {\n          if (optionsIn.input === skipToken) {\n            throw new Error(\"queryFn should not be called with skipToken used as input\");\n          }\n          return client(optionsIn.input(pageParam), {\n            signal,\n            context: {\n              [OPERATION_CONTEXT_SYMBOL]: {\n                key: queryKey,\n                type: \"infinite\"\n              },\n              ...optionsIn.context\n            }\n          });\n        },\n        ...optionsIn.input === skipToken ? { enabled: false } : {},\n        ...optionsIn,\n        queryKey\n      };\n    },\n    mutationKey(...[optionsIn = {}]) {\n      optionsIn = { ...options.experimental_defaults?.mutationKey, ...optionsIn };\n      const mutationKey = optionsIn.mutationKey ?? generateOperationKey(options.path, { type: \"mutation\" });\n      return mutationKey;\n    },\n    mutationOptions(...[optionsIn = {}]) {\n      optionsIn = { ...options.experimental_defaults?.mutationOptions, ...optionsIn };\n      const mutationKey = utils.mutationKey(optionsIn);\n      return {\n        mutationFn: (input) => client(input, {\n          context: {\n            [OPERATION_CONTEXT_SYMBOL]: {\n              key: mutationKey,\n              type: \"mutation\"\n            },\n            ...optionsIn.context\n          }\n        }),\n        ...optionsIn,\n        mutationKey\n      };\n    }\n  };\n  return utils;\n}\n\nfunction createRouterUtils(client, options = {}) {\n  const path = toArray(options.path);\n  const generalUtils = createGeneralUtils(path);\n  const procedureUtils = createProcedureUtils(client, {\n    path,\n    experimental_defaults: options.experimental_defaults\n  });\n  const recursive = new Proxy({\n    ...generalUtils,\n    ...procedureUtils\n  }, {\n    get(target, prop) {\n      const value = Reflect.get(target, prop);\n      const nextClient = isTypescriptObject(client) ? Reflect.get(client, prop) : void 0;\n      if (typeof prop !== \"string\" || RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop) || !isTypescriptObject(nextClient)) {\n        return value;\n      }\n      const nextUtils = createRouterUtils(client[prop], {\n        ...options,\n        path: [...path, prop],\n        experimental_defaults: get(options.experimental_defaults, [prop])\n      });\n      if (typeof value !== \"function\") {\n        return nextUtils;\n      }\n      return new Proxy(value, {\n        get(target2, prop2) {\n          if (typeof prop2 !== \"string\" || RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop2)) {\n            return Reflect.get(target2, prop2);\n          }\n          return Reflect.get(nextUtils, prop2);\n        }\n      });\n    }\n  });\n  return recursive;\n}\n\nexport { OPERATION_CONTEXT_SYMBOL, OPERATION_CONTEXT_SYMBOL as TANSTACK_QUERY_OPERATION_CONTEXT_SYMBOL, createGeneralUtils, createProcedureUtils, createRouterUtils, createRouterUtils as createTanstackQueryUtils, experimental_serializableStreamedQuery, generateOperationKey };\n","import type { ReactNode } from \"react\";\nimport { createContext, useContext, useMemo } from \"react\";\nimport type { RpcClient } from \"./rpc\";\nimport { createSpaceRpc, rpc, rpcForSpace } from \"./rpc\";\n\ntype SpaceRpc = { client: RpcClient; spaceId: string | null | undefined };\n\nconst SpaceRpcContext = createContext<SpaceRpc>({ client: rpc, spaceId: undefined });\n\n/** Pins an explicit space; unset scopes inherit their parent or follow selection at the root. */\nexport function SpaceRpcProvider({\n  spaceId,\n  children,\n}: {\n  spaceId: string | null | undefined;\n  children: ReactNode;\n}) {\n  const parent = useContext(SpaceRpcContext);\n  const value = useMemo<SpaceRpc>(\n    () =>\n      spaceId === undefined\n        ? parent\n        : { client: spaceId === null ? createSpaceRpc(null) : rpcForSpace(spaceId), spaceId },\n    [parent, spaceId],\n  );\n  return <SpaceRpcContext.Provider value={value}>{children}</SpaceRpcContext.Provider>;\n}\n\n/** The rpc client for the space these settings act on. */\nexport function useSpaceRpc(): RpcClient {\n  return useContext(SpaceRpcContext).client;\n}\n\n/** The bound space, or undefined when components follow the selected space. */\nexport function useBoundSpaceId(): string | null | undefined {\n  return useContext(SpaceRpcContext).spaceId;\n}\n","import type { RouterUtils } from \"@orpc/tanstack-query\";\nimport { createTanstackQueryUtils } from \"@orpc/tanstack-query\";\nimport type { AppBootstrap } from \"@rakazo/contracts\";\nimport { isRetryableError, retryDelayMs } from \"@rakazo/core\";\nimport type { DataTag, QueryKey } from \"@tanstack/react-query\";\nimport { QueryClient, useQueryClient } from \"@tanstack/react-query\";\nimport { createContext, useContext, useEffect, useRef, useState } from \"react\";\nimport type { RpcClient } from \"./rpc\";\nimport { createSpaceRpc, rpcForSpace, selectedSpaceId } from \"./rpc\";\nimport { useBoundSpaceId } from \"./space-rpc\";\n\n/**\n * Screens paint what they last saw and refresh it in the background, so moving between\n * spaces, chats, and settings sections does not wait on the network again.\n */\nexport const queryClient = new QueryClient({\n  defaultOptions: {\n    queries: {\n      staleTime: 30_000,\n      gcTime: 30 * 60_000,\n      // Screens refresh every time they open, even over a recent read; live updates and\n      // polling keep open ones current.\n      refetchOnMount: \"always\",\n      refetchOnWindowFocus: false,\n      retry: (failures, error) => failures < 1 && isRetryableError(error),\n      retryDelay: (_failures, error) => retryDelayMs(error, 1_000),\n    },\n  },\n});\n\nexport type SpaceQueries = RouterUtils<RpcClient>;\n\nfunction scopePath(userId: string | null, spaceId: string | null): string[] {\n  return [`user:${userId ?? \"\"}`, `space:${spaceId ?? \"\"}`];\n}\n\nconst scopes = new Map<string, SpaceQueries>();\n\n/**\n * Query helpers for one signed-in user in one space. Both are in every key, so cached data never\n * crosses an auth boundary, and each scope's client pins its own space header.\n */\nexport function spaceQueries(userId: string | null, spaceId: string | null): SpaceQueries {\n  const path = scopePath(userId, spaceId);\n  const id = path.join(\"\\n\");\n  let scope = scopes.get(id);\n  if (!scope) {\n    scope = createTanstackQueryUtils(spaceId ? rpcForSpace(spaceId) : createSpaceRpc(null), {\n      path,\n    });\n    scopes.set(id, scope);\n  }\n  return scope;\n}\n\n/**\n * Where a space's last bootstrap is kept. It holds the whole space (bots, groups, account), so\n * it is not keyed by bot: a visited space opens at once through any of its chats.\n */\nexport function spaceSeedKey(userId: string | null, spaceId: string | null) {\n  return spaceQueries(userId, spaceId).bootstrap.queryKey({ input: {} });\n}\n\nexport type ChatTarget =\n  | { botId: string; groupId?: undefined }\n  | { groupId: string; botId?: undefined };\n\n/** Where a space keeps the chat it last had selected, apart from any snapshot that chat loaded. */\nexport function lastChatKey(userId: string | null, spaceId: string | null) {\n  return [...spaceSeedKey(userId, spaceId), \"last-chat\"] as unknown as DataTag<\n    QueryKey,\n    ChatTarget\n  >;\n}\n\n/** The chat a cached space had selected, if the space still lists it. */\nexport function lastChatOf(\n  seed: AppBootstrap | undefined,\n  chat: ChatTarget | undefined,\n): ChatTarget | undefined {\n  if (!seed || !chat) return undefined;\n  if (chat.groupId) {\n    return seed.groups.some((group) => group.id === chat.groupId) ? chat : undefined;\n  }\n  return seed.bots.some((bot) => bot.id === chat.botId) ? chat : undefined;\n}\n\n/**\n * What a space reopens with after the shell leaves it: its latest lists, and the loaded snapshot\n * only when it belongs to the selected chat. A chat picked just before leaving may still show the\n * previous chat's snapshot while its own loads.\n */\nexport function seedOnLeave(\n  previous: AppBootstrap,\n  latest: Omit<AppBootstrap, \"thread\" | \"routines\">,\n  chat: ChatTarget | undefined,\n  snapshot: AppBootstrap[\"thread\"],\n): AppBootstrap {\n  const selected =\n    snapshot &&\n    chat &&\n    (chat.groupId\n      ? snapshot.groupId === chat.groupId\n      : !snapshot.groupId && snapshot.botId === chat.botId);\n  return { ...previous, ...latest, thread: selected ? snapshot : previous.thread };\n}\n\nconst QueryUserContext = createContext<string | null>(null);\n\n/** The signed-in user whose data the screens below may read from the cache. */\nexport const QueryUserProvider = QueryUserContext.Provider;\n\nexport function useQueryUserId(): string | null {\n  return useContext(QueryUserContext);\n}\n\n/** Query helpers for the space these components act on: a bound settings space or the selected one. */\nexport function useSpaceQueries(): SpaceQueries {\n  const userId = useQueryUserId();\n  const boundSpaceId = useBoundSpaceId();\n  const spaceId = boundSpaceId === undefined ? selectedSpaceId() : boundSpaceId;\n  return spaceQueries(userId, spaceId);\n}\n\n/**\n * One save and the reads it makes out of date, under the contract of the mobile hook of the same\n * name. Only the save can fail it: once it succeeds those reads are marked stale and read again,\n * and a read that fails reports itself, never the save. `pending` is set by the same update as the\n * click and lasts until those reads are back, so a control never offers the old state in between.\n * `run` does nothing while a save is in flight, even for a second click in the same tick.\n * A save belongs to the user and space it was started for: the space these components are bound\n * to, or the one selected at the click. `save` writes through the client it receives, which names\n * that space whatever is selected by the time a request leaves. The save holds the controls and\n * reports for as long as the screen shows that user and space. Once the screen has gone or shows\n * another, a save that ends shows nothing and skips `onSaved` and `onFailed`; its request is never\n * cancelled.\n */\nexport function useSave<Input = void, Saved = unknown>(options: {\n  save: (input: Input, rpc: RpcClient) => Promise<Saved>;\n  /** The reads the save makes out of date, which may depend on what was saved. */\n  stale?: readonly QueryKey[] | ((input: Input) => readonly QueryKey[]);\n  onSaved?: (saved: Saved, input: Input) => unknown;\n  /** For a toast or undoing an optimistic change; `error` is for showing the failure inline. */\n  onFailed?: (error: Error, input: Input) => unknown;\n  /** `onSaved` leaves the screen, so a success stays pending instead of offering the controls again. */\n  closesScreen?: boolean;\n}) {\n  const queryClient = useQueryClient();\n  const userId = useQueryUserId();\n  const boundSpaceId = useBoundSpaceId();\n  const scopeNow = () => {\n    const spaceId = boundSpaceId === undefined ? selectedSpaceId() : boundSpaceId;\n    return { spaceId, key: scopePath(userId, spaceId).join(\"\\n\") };\n  };\n  const [saves, setSaves] = useState<\n    Record<string, { input: Input; pending: boolean; error: Error | null }>\n  >({});\n  // React state is a render behind; this is what a second call in the same tick is checked against.\n  const inFlight = useRef(new Set<string>());\n  // What the screen shows by the time a save ends, which can differ from what it was started for.\n  const shownScope = useRef(scopeNow);\n  shownScope.current = scopeNow;\n  const mounted = useRef(false);\n  useEffect(() => {\n    mounted.current = true;\n    return () => {\n      mounted.current = false;\n    };\n  }, []);\n  const current = saves[scopeNow().key];\n  return {\n    run(input: Input) {\n      const { spaceId, key } = scopeNow();\n      if (inFlight.current.has(key)) return;\n      inFlight.current.add(key);\n      setSaves((now) => ({ ...now, [key]: { input, pending: true, error: null } }));\n      const { save, stale = [], onSaved, onFailed, closesScreen } = options;\n      const shown = () => mounted.current && shownScope.current().key === key;\n      const finish = (error: Error | null) => {\n        inFlight.current.delete(key);\n        if (mounted.current)\n          setSaves((now) => ({ ...now, [key]: { input, pending: false, error } }));\n      };\n      const rpc = spaceId ? rpcForSpace(spaceId) : createSpaceRpc(null);\n      void (async () => save(input, rpc))().then(\n        async (saved) => {\n          const reads = typeof stale === \"function\" ? stale(input) : stale;\n          await Promise.allSettled(\n            reads.map((queryKey) => queryClient.invalidateQueries({ queryKey })),\n          );\n          if (!closesScreen || !shown()) finish(null);\n          if (!shown()) return;\n          try {\n            await onSaved?.(saved, input);\n          } catch (error) {\n            // The save went through; what failed came after it, such as leaving the screen. The\n            // controls come back with the reason instead of staying held.\n            finish(error as Error);\n          }\n        },\n        (error: Error) => {\n          finish(error);\n          if (shown()) void onFailed?.(error, input);\n        },\n      );\n    },\n    pending: current?.pending ?? false,\n    /** What the pending or failed save was sent with. */\n    input: current?.input,\n    error: current?.error ?? null,\n    /** Forgets a failure, as when the draft it was about changes. */\n    reset: () => {\n      const { key } = scopeNow();\n      setSaves((now) => {\n        const { [key]: shown, ...rest } = now;\n        return shown && !shown.pending ? rest : now;\n      });\n    },\n  };\n}\n\nlet cachedUserId: string | null | undefined;\n\n/** Forgets everything cached for another user, so sign-out or a switch never shows their data. */\nexport function setQueryUser(userId: string | null): void {\n  if (cachedUserId !== undefined && cachedUserId !== userId) queryClient.clear();\n  cachedUserId = userId;\n}\n"],"ignoreList":[0,1,2,3,4],"mappings":"A,8cAoBA,IAAI6K,EAAW,cAAchB,CAAU,CACtC,GACA,GACA,GACA,GACA,YAAY,EAAQ,CACnB,MAAM,EACN,KAAKiB,GAAUC,EAAO,OACtB,KAAK,WAAaA,EAAO,WACzB,KAAKC,GAAiBD,EAAO,cAC7B,KAAKE,GAAa,CAAC,EACnB,KAAK,MAAQF,EAAO,OAASG,EAAgB,EAC7C,KAAK,WAAWH,EAAO,OAAO,EAC9B,KAAK,WAAW,CACjB,CAMA,WAAW,EAAS,CACnB,KAAK,QAAUI,EACf,KAAK,aAAa,KAAK,QAAQ,MAAM,CACtC,CAKA,IAAI,MAAO,CACV,OAAO,KAAK,QAAQ,IACrB,CAOA,YAAY,EAAU,CAChB,KAAKF,GAAW,SAASG,CAAQ,IACrC,KAAKH,GAAW,KAAKG,CAAQ,EAC7B,KAAK,eAAe,EACpB,KAAKJ,GAAe,OAAO,CAC1B,KAAM,gBACN,SAAU,KACV,UACD,CAAC,EAEH,CAMA,eAAe,EAAU,CACxB,KAAKC,GAAa,KAAKA,GAAW,OAAQ,GAAMI,IAAMD,CAAQ,EAC9D,KAAK,WAAW,EAChB,KAAKJ,GAAe,OAAO,CAC1B,KAAM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