{"version":3,"sources":["../src/index.ts","../src/mutation-store.ts","../src/tree-map.ts","../src/utils.ts","../src/mutation-options.ts","../src/use-mutation.ts","../src/define-mutation.ts","../src/define-query.ts","../src/query-store.ts","../src/query-options.ts","../src/use-query.ts","../src/devtools/plugin.ts","../src/pinia-colada.ts","../src/plugins/query-hooks.ts","../src/infinite-query.ts"],"sourcesContent":["/**\n * Pinia Colada\n * @module @pinia/colada\n */\nexport { defineMutation } from './define-mutation'\nexport {\n  type _ReduceContext,\n  useMutation,\n  type UseMutationReturn,\n} from './use-mutation'\n\nexport { defineQuery } from './define-query'\nexport { useQuery, type UseQueryReturn } from './use-query'\n\n// export { type UseQueryKeyList } from './query-keys'\n\nexport type {\n  _DataState_Base,\n  AsyncStatus,\n  DataState,\n  DataState_Error,\n  DataState_Pending,\n  DataState_Success,\n  DataStateStatus,\n} from './data-state'\nexport { type EntryKey } from './entry-options'\nexport type {\n  RefetchOnControl,\n  UseQueryOptions,\n  UseQueryOptionsGlobal,\n  UseQueryOptionsWithDefaults,\n} from './query-options'\n\nexport type {\n  UseMutationOptions,\n  // UseMutationOptionsGlobal,\n} from './mutation-options'\n\nexport { PiniaColada } from './pinia-colada'\nexport type { PiniaColadaOptions } from './pinia-colada'\n\nexport {\n  PiniaColadaQueryHooksPlugin,\n  type PiniaColadaQueryHooksPluginOptions,\n} from './plugins/query-hooks'\n\nexport {\n  hydrateQueryCache,\n  type QueryCache,\n  serializeQueryCache,\n  serializeTreeMap,\n  useQueryCache,\n  type UseQueryEntry,\n  type UseQueryEntryExtensions,\n  type UseQueryEntryFilter,\n} from './query-store'\n\nexport { type EntryNodeKey, TreeMapNode } from './tree-map'\n\nexport { type _Awaitable, type _EmptyObject, type _MaybeArray, toCacheKey } from './utils'\n\nexport type { TypesConfig } from './types-extension'\n\nexport type { PiniaColadaPlugin, PiniaColadaPluginContext } from './plugins'\n\nexport { useInfiniteQuery, type UseInfiniteQueryOptions } from './infinite-query'\n","import type { ComponentInternalInstance, EffectScope, ShallowRef } from 'vue'\nimport type { AsyncStatus, DataState, DataStateStatus } from './data-state'\nimport type { EntryNodeKey } from './tree-map'\nimport { defineStore, skipHydrate } from 'pinia'\nimport { customRef, getCurrentScope, shallowRef } from 'vue'\nimport { TreeMapNode } from './tree-map'\nimport type { _EmptyObject } from './utils'\nimport { isSameArray, noop, stringifyFlatObject, toCacheKey, toValueWithArgs } from './utils'\nimport type { _ReduceContext, UseMutationGlobalContext } from './use-mutation'\nimport { useMutationOptions } from './mutation-options'\nimport type { UseMutationOptions } from './mutation-options'\nimport type { EntryKey } from './entry-options'\n\n/**\n * A mutation entry in the cache.\n */\nexport interface UseMutationEntry<\n  TResult = unknown,\n  TVars = unknown,\n  TError = unknown,\n  TContext extends Record<any, any> = _EmptyObject,\n> {\n  /**\n   * The state of the mutation. Contains the data, error and status.\n   */\n  state: ShallowRef<DataState<TResult, TError>>\n\n  /**\n   * The async status of the mutation.\n   */\n  asyncStatus: ShallowRef<AsyncStatus>\n\n  /**\n   * When was this data fetched the last time in ms\n   */\n  when: number\n\n  /**\n   * The serialized key associated with this mutation entry.\n   */\n  key: EntryNodeKey[] | undefined\n\n  /**\n   * The variables used to call the mutation.\n   */\n  vars: ShallowRef<TVars | undefined>\n\n  options: UseMutationOptions<TResult, TVars, TError, TContext>\n\n  pending: symbol | null\n\n  /**\n   * Component `__hmrId` to track wrong usage of `useQuery` and warn the user.\n   * @internal\n   */\n  __hmr?: {\n    id?: string\n    deps?: Set<EffectScope | ComponentInternalInstance>\n    skip?: boolean\n  }\n}\n\n/**\n * Filter to get mutation entries from the cache.\n */\nexport interface UseMutationEntryFilter {\n  /**\n   * A key to filter the entries.\n   */\n  key?: EntryKey\n\n  /**\n   * If true, it will only match the exact key, not the children.\n   *\n   * @example\n   * ```ts\n   * { key: ['a'], exact: true }\n   *  // will match ['a'] but not ['a', 'b'], while\n   * { key: ['a'] }\n   * // will match both\n   * ```\n   */\n  exact?: boolean\n\n  /**\n   * If defined, it will only return the entries with the given status.\n   */\n  status?: DataStateStatus\n\n  /**\n   * Pass a predicate to filter the entries. This will be executed for each entry matching the other filters.\n   * @param entry - entry to filter\n   */\n  predicate?: (entry: UseMutationEntry) => boolean\n}\n\nfunction createMutationEntry<\n  TResult = unknown,\n  TVars = unknown,\n  TError = unknown,\n  TContext extends Record<any, any> = _EmptyObject,\n>(\n  options: UseMutationOptions<TResult, TVars, TError, TContext>,\n  key: EntryNodeKey[] | undefined,\n  vars?: TVars,\n): UseMutationEntry<TResult, TVars, TError, TContext> {\n  return {\n    state: shallowRef<DataState<TResult, TError>>({\n      status: 'pending',\n      data: undefined,\n      error: null,\n    }),\n    asyncStatus: shallowRef<AsyncStatus>('idle'),\n    when: 0,\n    vars: shallowRef(vars),\n    key,\n    options,\n    pending: null,\n  }\n}\n\nexport const useMutationCache = /* @__PURE__ */ defineStore('_pc_mutation', ({ action }) => {\n  // We have two versions of the cache, one that track changes and another that doesn't so the actions can be used\n  // inside computed properties\n  // We have two versions of the cache, one that track changes and another that doesn't so the actions can be used\n  // inside computed properties\n  const cachesRaw = new TreeMapNode<UseMutationEntry<unknown, any, unknown, any>>()\n  let triggerCache!: () => void\n  const caches = skipHydrate(\n    customRef(\n      (track, trigger) =>\n        (triggerCache = trigger) && {\n          // eslint-disable-next-line no-sequences\n          get: () => (track(), cachesRaw),\n          set:\n            process.env.NODE_ENV !== 'production'\n              ? () => {\n                  console.error(\n                    `[@pinia/colada]: The mutation cache instance cannot be set directly, it must be modified. This will fail in production.`,\n                  )\n                }\n              : noop,\n        },\n    ),\n  )\n\n  // this allows use to attach reactive effects to the scope later on\n  const scope = getCurrentScope()!\n\n  const globalOptions = useMutationOptions()\n  const defineMutationMap = new WeakMap<() => unknown, unknown>()\n\n  function ensure<\n    TResult = unknown,\n    TVars = unknown,\n    TError = unknown,\n    TContext extends Record<any, any> = _EmptyObject,\n  >(\n    options: UseMutationOptions<TResult, TVars, TError, TContext>,\n  ): UseMutationEntry<TResult, TVars, TError, TContext>\n  function ensure<\n    TResult = unknown,\n    TVars = unknown,\n    TError = unknown,\n    TContext extends Record<any, any> = _EmptyObject,\n  >(\n    options: UseMutationOptions<TResult, TVars, TError, TContext>,\n    entry: UseMutationEntry<TResult, TVars, TError, TContext>,\n    vars: NoInfer<TVars>,\n  ): UseMutationEntry<TResult, TVars, TError, TContext>\n\n  function ensure<\n    TResult = unknown,\n    TVars = unknown,\n    TError = unknown,\n    TContext extends Record<any, any> = _EmptyObject,\n  >(\n    options: UseMutationOptions<TResult, TVars, TError, TContext>,\n    entry?: UseMutationEntry<TResult, TVars, TError, TContext>,\n    vars?: NoInfer<TVars>,\n  ): UseMutationEntry<TResult, TVars, TError, TContext> {\n    const key = vars && toValueWithArgs(options.key, vars)?.map(stringifyFlatObject)\n\n    if (!entry) {\n      entry = createMutationEntry(options, key)\n      if (key) {\n        cachesRaw.set(\n          key,\n          // @ts-expect-error: function types with generics are incompatible\n          entry,\n        )\n        triggerCache()\n      }\n      // TODO: store it somewhere during dev mode to show in devtools\n      return createMutationEntry(options, key)\n    }\n    // reuse the entry when no key is provided\n    if (key) {\n      // update key\n      if (!entry.key) {\n        entry.key = key\n      } else if (!isSameArray(entry.key, key)) {\n        entry = createMutationEntry(\n          options,\n          key,\n          // the type NonNullable<TVars> is not assignable to TVars\n          vars as TVars,\n        )\n        cachesRaw.set(\n          key,\n          // @ts-expect-error: function types with generics are incompatible\n          entry,\n        )\n        triggerCache()\n      }\n    }\n\n    return entry\n  }\n\n  /**\n   * Ensures a query created with {@link defineMutation} is present in the cache. If it's not, it creates a new one.\n   * @param fn - function that defines the query\n   */\n  const ensureDefinedMutation = action(<T>(fn: () => T) => {\n    let defineMutationResult = defineMutationMap.get(fn)\n    if (!defineMutationResult) {\n      defineMutationMap.set(fn, (defineMutationResult = scope.run(fn)))\n    }\n\n    return defineMutationResult\n  })\n\n  /**\n   * Sets the state of a query entry in the cache and updates the\n   * {@link UseQueryEntry['pending']['when'] | `when` property}. This action is\n   * called every time the cache state changes and can be used by plugins to\n   * detect changes.\n   *\n   * @param entry - the entry of the query to set the state\n   * @param state - the new state of the entry\n   */\n  const setEntryState = action(\n    <\n      TResult = unknown,\n      TVars = unknown,\n      TError = unknown,\n      TContext extends Record<any, any> = _EmptyObject,\n    >(\n      entry: UseMutationEntry<TResult, TVars, TError, TContext>,\n      // NOTE: NoInfer ensures correct inference of TResult and TError\n      state: DataState<NoInfer<TResult>, NoInfer<TError>>,\n    ) => {\n      entry.state.value = state\n      entry.when = Date.now()\n    },\n  )\n\n  /**\n   * Removes a query entry from the cache if it has a key. If it doesn't then it does nothing.\n   *\n   * @param entry - the entry of the query to remove\n   */\n  const remove = action((entry: UseMutationEntry) => {\n    if (entry.key != null) {\n      cachesRaw.delete(entry.key)\n      triggerCache()\n    }\n  })\n\n  /**\n   * Returns all the entries in the cache that match the filters.\n   *\n   * @param filters - filters to apply to the entries\n   */\n  const getEntries = action((filters: UseMutationEntryFilter = {}): UseMutationEntry[] => {\n    const node = filters.key ? caches.value.find(toCacheKey(filters.key)) : caches.value\n\n    if (!node) return []\n\n    return (filters.exact ? (node.value ? [node.value] : []) : [...node]).filter(\n      (entry) =>\n        (filters.status == null || entry.state.value.status === filters.status)\n        && (!filters.predicate || filters.predicate(entry)),\n    )\n  })\n\n  async function mutate<\n    TResult = unknown,\n    TVars = unknown,\n    TError = unknown,\n    TContext extends Record<any, any> = _EmptyObject,\n  >(\n    currentEntry: UseMutationEntry<TResult, TVars, TError, TContext>,\n    vars: NoInfer<TVars>,\n  ): Promise<TResult> {\n    currentEntry.asyncStatus.value = 'loading'\n    currentEntry.vars.value = vars\n\n    // TODO: AbortSignal that is aborted when the mutation is called again so we can throw in pending\n    let currentData: TResult | undefined\n    let currentError: TError | undefined\n    type OnMutateContext = Parameters<\n      Required<UseMutationOptions<TResult, TVars, TError, TContext>>['onMutate']\n    >['1']\n    type OnSuccessContext = Parameters<\n      Required<UseMutationOptions<TResult, TVars, TError, TContext>>['onSuccess']\n    >['2']\n    type OnErrorContext = Parameters<\n      Required<UseMutationOptions<TResult, TVars, TError, TContext>>['onError']\n    >['2']\n    const { options } = currentEntry\n\n    let context: OnMutateContext | OnErrorContext | OnSuccessContext = {}\n\n    const currentCall = (currentEntry.pending = Symbol())\n    try {\n      const globalOnMutateContext = globalOptions.onMutate?.(vars)\n\n      context\n        = (globalOnMutateContext instanceof Promise\n          ? await globalOnMutateContext\n          : globalOnMutateContext) || {}\n\n      const onMutateContext = (await options.onMutate?.(\n        vars,\n        context,\n        // NOTE: the cast makes it easier to write without extra code. It's safe because { ...null, ...undefined } works and TContext must be a Record<any, any>\n      )) as _ReduceContext<TContext>\n\n      // we set the context here so it can be used by other hooks\n      context = {\n        ...context,\n        ...onMutateContext,\n        // NOTE: needed for onSuccess cast\n      } satisfies OnSuccessContext\n\n      const newData = (currentData = await options.mutation(vars, context as OnSuccessContext))\n\n      await globalOptions.onSuccess?.(newData, vars, context as OnSuccessContext)\n      await options.onSuccess?.(\n        newData,\n        vars,\n        // NOTE: cast is safe because of the satisfies above\n        // using a spread also works\n        context as OnSuccessContext,\n      )\n\n      if (currentEntry.pending === currentCall) {\n        setEntryState(currentEntry, {\n          status: 'success',\n          data: newData,\n          error: null,\n        })\n      }\n    } catch (newError: unknown) {\n      currentError = newError as TError\n      await globalOptions.onError?.(currentError, vars, context)\n      await options.onError?.(currentError, vars, context)\n      if (currentEntry.pending === currentCall) {\n        setEntryState(currentEntry, {\n          status: 'error',\n          data: currentEntry.state.value.data,\n          error: currentError,\n        })\n      }\n      throw newError\n    } finally {\n      // TODO: should we catch and log it?\n      await globalOptions.onSettled?.(currentData, currentError, vars, context)\n      await options.onSettled?.(currentData, currentError, vars, context)\n      if (currentEntry.pending === currentCall) {\n        currentEntry.asyncStatus.value = 'idle'\n      }\n    }\n\n    return currentData\n  }\n\n  return {\n    caches,\n    ensure,\n    ensureDefinedMutation,\n    mutate,\n    remove,\n\n    setEntryState,\n    getEntries,\n  }\n})\n","import type { UseQueryOptionsWithDefaults } from './query-options'\n\n/**\n * Key type for nodes in the tree map. Differently from {@link EntryKey}, this type is serializable to JSON.\n */\nexport type EntryNodeKey = string | number\n\n/**\n * Internal data structure used to store the data of `useQuery()`. `T` should be serializable to JSON.\n * @internal\n */\nexport class TreeMapNode<T = unknown> {\n  value: T | undefined\n  children?: Map<EntryNodeKey, TreeMapNode<T>>\n\n  constructor()\n  constructor(keys: EntryNodeKey[], value: T | undefined)\n  constructor(...args: [] | [EntryNodeKey[], T]) {\n    if (args.length) {\n      this.set(...args)\n    }\n  }\n\n  /**\n   * Sets the value while building the tree\n   *\n   * @param keys - key as an array\n   * @param value - value to set\n   */\n  set(keys: EntryNodeKey[], value?: T) {\n    if (keys.length === 0) {\n      this.value = value\n    } else {\n      // this.children ??= new Map<EntryNodeKey,\n      const [top, ...otherKeys] = keys as [top: EntryNodeKey, ...otherKeys: EntryNodeKey[]]\n      const node: TreeMapNode<T> | undefined = this.children?.get(top)\n      if (node) {\n        node.set(otherKeys, value)\n      } else {\n        this.children ??= new Map()\n        this.children.set(top, new TreeMapNode(otherKeys, value))\n      }\n    }\n  }\n\n  /**\n   * Finds the node at the given path of keys.\n   *\n   * @param keys - path of keys\n   */\n  find(keys: EntryNodeKey[]): TreeMapNode<T> | undefined {\n    if (keys.length === 0) {\n      return this\n    } else {\n      const [top, ...otherKeys] = keys as [top: EntryNodeKey, ...otherKeys: EntryNodeKey[]]\n      return this.children?.get(top)?.find(otherKeys)\n    }\n  }\n\n  /**\n   * Gets the value at the given path of keys.\n   *\n   * @param keys - path of keys\n   */\n  get(keys: EntryNodeKey[]): T | undefined {\n    return this.find(keys)?.value\n  }\n\n  /**\n   * Delete the node at the given path of keys and all its children.\n   *\n   * @param keys - path of keys\n   */\n  delete(keys: EntryNodeKey[]) {\n    if (keys.length === 1) {\n      this.children?.delete(keys[0]!)\n    } else {\n      const [top, ...otherKeys] = keys as [top: EntryNodeKey, ...otherKeys: EntryNodeKey[]]\n      this.children?.get(top)?.delete(otherKeys)\n    }\n  }\n\n  /**\n   * Iterates over the node values if not null or undefined and all its children. Goes in depth first order. Allows a `for (const of node)` loop.\n   */\n  * [Symbol.iterator](): IterableIterator<T> {\n    if (this.value != null) {\n      yield this.value\n    }\n    if (this.children) {\n      for (const child of this.children.values()) {\n        yield *child\n      }\n    }\n  }\n}\n\n// NOTE: this function is outside of TreeMapNode because it's only needed for SSR apps and shouldn't add to the bundle\n// size if they are client only\n/**\n * Revives and appends a serialized node to the tree.\n *\n * @param parent - parent node\n * @param serializedEntryNode serialized entry\n * @param serializedEntryNode.0 entry key\n * @param serializedEntryNode.1 entry data value\n * @param serializedEntryNode.2 entry children\n * @param createNodeValue - function to create the node value\n * @param parentKey parent key\n */\nexport function appendSerializedNodeToTree<T>(\n  parent: TreeMapNode<T>,\n  [key, value, children]: UseQueryEntryNodeSerialized,\n  createNodeValue: (\n    key: EntryNodeKey[],\n    options?: UseQueryOptionsWithDefaults<unknown, unknown> | null,\n    initialData?: unknown,\n    error?: unknown | null,\n    when?: number,\n  ) => T,\n  parentKey: EntryNodeKey[] = [],\n) {\n  parent.children ??= new Map()\n  const entryKey = [...parentKey, key]\n  const node = new TreeMapNode<T>(\n    [],\n    // NOTE: this could happen outside of an effect scope but since it's only for client side hydration, it should be\n    // fine to have global shallowRefs as they can still be cleared when needed\n    value && createNodeValue(entryKey, null, ...value),\n  )\n  parent.children.set(key, node)\n  if (children) {\n    for (const child of children) {\n      appendSerializedNodeToTree(node, child, createNodeValue, entryKey)\n    }\n  }\n}\n\n/**\n * Raw data of a query entry. Can be serialized from the server and used to hydrate the store.\n * @internal\n */\nexport type _UseQueryEntryNodeValueSerialized<TResult = unknown, TError = unknown> = [\n  /**\n   * The data returned by the query.\n   */\n  data: TResult | undefined,\n\n  /**\n   * The error thrown by the query.\n   */\n  error: TError | null,\n\n  /**\n   * When was this data fetched the last time in ms\n   */\n  when?: number,\n]\n\n/**\n * Serialized version of a query entry node.\n * @internal\n */\nexport type UseQueryEntryNodeSerialized = [\n  key: EntryNodeKey,\n  value: undefined | _UseQueryEntryNodeValueSerialized,\n  children?: UseQueryEntryNodeSerialized[],\n]\n\n// -------------------------------------\n// --- Below are debugging internals ---\n// -------------------------------------\n/* v8 ignore start */\n\n/**\n * Calculates the size of the node and all its children. Used in tests.\n *\n * @internal\n * @param node - The node to calculate the size of\n * @returns The size of the node and all its children\n */\nexport function entryNodeSize(node: TreeMapNode): number {\n  return (\n    (node.children?.size ?? 0)\n    + [...(node.children?.values() || [])].reduce((acc, child) => acc + entryNodeSize(child), 0)\n  )\n}\n\n/**\n * Logs the tree to the console. Used in tests.\n * @internal\n *\n * @param tree - tree to log\n * @param log - function to log the tree\n */\nexport function logTree(\n  tree: TreeMapNode,\n\n  log: (str: string) => any = console.log,\n) {\n  log(printTreeMap(tree))\n}\n\nconst MAX_LEVEL = 1000\nfunction printTreeMap(\n  tree: TreeMapNode | TreeMapNode['children'],\n  level = 0,\n  parentPre = '',\n  treeStr = '',\n): string {\n  // end of recursion\n  if (typeof tree !== 'object' || level >= MAX_LEVEL) return ''\n\n  if (tree instanceof Map) {\n    const total = tree.size\n    let index = 0\n    for (const [key, child] of tree) {\n      const hasNext = index++ < total - 1\n      const { children } = child\n\n      treeStr += `${`${parentPre}${hasNext ? '├' : '└'}${`─${(children?.size ?? 0) > 0 ? '┬' : ''}`} `}${key}${child.value != null ? ` · ${String(child.value)}` : ''}\\n`\n\n      if (children) {\n        treeStr += printTreeMap(children, level + 1, `${parentPre}${hasNext ? '│' : ' '} `)\n      }\n    }\n  } else {\n    const children = tree.children\n    treeStr = `${String(\n      typeof tree.value === 'object' && tree.value ? JSON.stringify(tree.value) : '<root>',\n    )}\\n`\n    if (children) {\n      treeStr += printTreeMap(children, level + 1)\n    }\n  }\n\n  return treeStr\n}\n/* v8 ignore stop */\n","import { computed, getCurrentScope, onScopeDispose } from 'vue'\nimport type { MaybeRefOrGetter, Ref, ShallowRef } from 'vue'\nimport type { EntryKey } from './entry-options'\nimport type { EntryNodeKey } from './tree-map'\nimport type { QueryCache } from './query-store'\nimport type { UseQueryOptions } from './query-options'\n\n/**\n * Adds an event listener to Window that is automatically removed on scope dispose.\n */\nexport function useEventListener<E extends keyof WindowEventMap>(\n  target: Window,\n  event: E,\n  listener: (this: Window, ev: WindowEventMap[E]) => any,\n  options?: boolean | AddEventListenerOptions,\n): void\n\n/**\n * Adds an event listener to Document that is automatically removed on scope dispose.\n */\nexport function useEventListener<E extends keyof DocumentEventMap>(\n  target: Document,\n  event: E,\n  listener: (this: Document, ev: DocumentEventMap[E]) => any,\n  options?: boolean | AddEventListenerOptions,\n): void\n\nexport function useEventListener(\n  target: Document | Window | EventTarget,\n  event: string,\n  listener: (this: EventTarget, ev: Event) => any,\n  options?: boolean | AddEventListenerOptions,\n) {\n  target.addEventListener(event, listener, options)\n  if (getCurrentScope()) {\n    onScopeDispose(() => {\n      target.removeEventListener(event, listener)\n    })\n  }\n}\n\nexport const IS_CLIENT = typeof window !== 'undefined'\n\n/**\n * Type that represents a value that can be an array or a single value.\n * @internal\n */\nexport type _MaybeArray<T> = T | T[]\n\n/**\n * Type that represents a value that can be a function or a single value. Used for `defineQuery()` and\n * `defineMutation()`.\n * @internal\n */\nexport type _MaybeFunction<T, Args extends any[] = []> = T | ((...args: Args) => T)\n\n/**\n * Transforms a value or a function that returns a value to a value.\n * @param valFn either a value or a function that returns a value\n * @param args  arguments to pass to the function if `valFn` is a function\n */\nexport function toValueWithArgs<T, Args extends any[]>(\n  valFn: T | ((...args: Args) => T),\n  ...args: Args\n): T {\n  return typeof valFn === 'function' ? (valFn as (...args: Args) => T)(...args) : valFn\n}\n\n/**\n * Type that represents a value that can be a promise or a single value.\n * @internal\n */\nexport type _Awaitable<T> = T | Promise<T>\n\n/**\n * Flattens an object type for readability.\n * @internal\n */\nexport type _Simplify<T> = { [K in keyof T]: T[K] }\n\n/**\n * Converts a value to an array if necessary.\n *\n * @param value - value to convert\n */\nexport const toArray = <T>(value: _MaybeArray<T>): T[] => (Array.isArray(value) ? value : [value])\n\nexport type _JSONPrimitive = string | number | boolean | null | undefined\n\n/**\n * Utility type to represent a flat object that can be stringified with `JSON.stringify` no matter the order of keys.\n * @internal\n */\nexport interface _ObjectFlat {\n  [key: string]: _JSONPrimitive | Array<_JSONPrimitive>\n}\n\n/**\n * Stringifies an object no matter the order of keys. This is used to create a hash for a given object. It only works\n * with flat objects. It can contain arrays of primitives only. `undefined` values are skipped.\n *\n * @param obj - object to stringify\n */\nexport function stringifyFlatObject(obj: _ObjectFlat | _JSONPrimitive): string {\n  return obj && typeof obj === 'object' ? JSON.stringify(obj, Object.keys(obj).sort()) : String(obj)\n}\n\n/**\n * Creates a {@link QueryCache}'s `caches` key from an entry's {@link UseQueryOptions#key}.\n * @param key - key of the entry\n */\nexport const toCacheKey = (key: EntryKey): EntryNodeKey[] => key.map(stringifyFlatObject)\n\n/**\n * Merges two types when the second one can be null | undefined. Allows to safely use the returned type for { ...a,\n * ...undefined, ...null }\n * @internal\n */\nexport type _MergeObjects<Obj, MaybeNull> = MaybeNull extends undefined | null | void\n  ? Obj\n  : _Simplify<Obj & MaybeNull>\n\n/**\n * @internal\n */\nexport const noop = () => {}\n\n/**\n * Wraps a getter to be used as a ref. This is useful when you want to use a getter as a ref but you need to modify the\n * value.\n *\n * @internal\n * @param other - getter of the ref to compute\n * @returns a wrapper around a writable getter that can be used as a ref\n */\nexport const computedRef = <T>(other: () => Ref<T>): ShallowRef<T> =>\n  computed({\n    get: () => other().value,\n    set: (value) => (other().value = value),\n  })\n\n/**\n * Renames a property in an object type.\n */\nexport type _RenameProperty<T, Key extends keyof T, NewKey extends string> = {\n  [P in keyof T as P extends Key ? NewKey : P]: T[P]\n}\n\n/**\n * Type safe version of `Object.assign` that allows to set all properties of a reactive object at once. Used to set\n * {@link DataState} properties in a type safe way.\n */\nexport const setReactiveValue = Object.assign as <T>(value: T, ...args: T[]) => T\n\n/**\n * To avoid using `{}`\n * @internal\n */\nexport interface _EmptyObject {}\n\n/**\n * Compares two arrays to check if they are the same. Used for keys.\n *\n * @param arr1 - first array to compare\n * @param arr2 - second array to compare\n */\nexport function isSameArray(arr1: unknown[], arr2: unknown[]): boolean {\n  if (arr1.length !== arr2.length) return false\n  for (let i = 0; i < arr1.length; i++) {\n    if (arr1[i] !== arr2[i]) return false\n  }\n  return true\n}\n\n/**\n * Dev only warning that is only shown once.\n */\nconst warnedMessages = new Set<string>()\n\n/**\n * Warns only once. This should only be used in dev\n * @param message - Message to show\n * @param id - Unique id for the message, defaults to the message\n */\nexport function warnOnce(message: string, id: string = message) {\n  if (warnedMessages.has(id)) return\n  warnedMessages.add(id)\n  console.warn(`[@pinia/colada]: ${message}`)\n}\n\n/**\n * Removes the `MaybeRefOrGetter` wrapper from all fields of an object.\n * @internal\n */\nexport type _RemoveMaybeRef<T> = {\n  [K in keyof T]: T[K] extends MaybeRefOrGetter<infer U>\n    ? MaybeRefOrGetter<U> extends T[K]\n      ? U\n      : T[K]\n    : T[K]\n}\n","import { inject } from 'vue'\nimport type { InjectionKey } from 'vue'\nimport type { ErrorDefault } from './types-extension'\nimport type { _ReduceContext, _MutationKey, UseMutationGlobalContext } from './use-mutation'\nimport type { _EmptyObject, _Awaitable } from './utils'\n\n/**\n * Options for mutations that can be globally overridden.\n */\nexport interface UseMutationOptionsGlobal {\n  /**\n   * Runs before a mutation is executed. It can return a value that will be\n   * passed to `mutation`, `onSuccess`, `onError` and `onSettled`. If it\n   * returns a promise, it will be awaited before running `mutation`.\n   */\n  onMutate?: (\n    /**\n     * The variables passed to the mutation.\n     */\n    vars: unknown,\n  ) => _Awaitable<UseMutationGlobalContext | undefined | void | null>\n\n  /**\n   * Runs when a mutation is successful.\n   */\n  onSuccess?: (\n    /**\n     * The result of the mutation.\n     */\n    data: unknown,\n    /**\n     * The variables passed to the mutation.\n     */\n    vars: unknown,\n    /**\n     * The merged context from `onMutate` and the global context.\n     */\n    context: UseMutationGlobalContext,\n  ) => unknown\n\n  /**\n   * Runs when a mutation encounters an error.\n   */\n  onError?: (\n    /**\n     * The error thrown by the mutation.\n     */\n    error: unknown,\n    /**\n     * The variables passed to the mutation.\n     */\n    vars: unknown,\n    /**\n     * The merged context from `onMutate` and the global context. Properties returned by `onMutate` can be `undefined`\n     * if `onMutate` throws.\n     */\n    context:\n      | Partial<Record<keyof UseMutationGlobalContext, never>>\n      // this is the success case where everything is defined\n      // undefined if global onMutate throws\n      | UseMutationGlobalContext,\n  ) => unknown\n\n  /**\n   * Runs after the mutation is settled, regardless of the result.\n   */\n  onSettled?: (\n    /**\n     * The result of the mutation. `undefined` when a mutation failed.\n     */\n    data: unknown | undefined,\n    /**\n     * The error thrown by the mutation. `undefined` if the mutation was successful.\n     */\n    error: unknown | undefined,\n    /**\n     * The variables passed to the mutation.\n     */\n    vars: unknown,\n    /**\n     * The merged context from `onMutate` and the global context. Properties returned by `onMutate` can be `undefined`\n     * if `onMutate` throws.\n     */\n    context:\n      | Partial<Record<keyof UseMutationGlobalContext, never>>\n      // this is the success case where everything is defined\n      // undefined if global onMutate throws\n      | UseMutationGlobalContext,\n  ) => unknown\n}\n\n/**\n * Options to create a mutation.\n */\nexport interface UseMutationOptions<\n  TResult = unknown,\n  TVars = void,\n  TError = ErrorDefault,\n  TContext extends Record<any, any> = _EmptyObject,\n> {\n  /**\n   * The key of the mutation. If the mutation is successful, it will invalidate the mutation with the same key and refetch it\n   */\n  mutation: (vars: TVars, context: _ReduceContext<NoInfer<TContext>>) => Promise<TResult>\n\n  /**\n   * Optional key to identify the mutation globally and access it through other\n   * helpers like `useMutationState()`. If you don't need to reference the\n   * mutation elsewhere, you should ignore this option.\n   */\n  key?: _MutationKey<NoInfer<TVars>>\n\n  /**\n   * Runs before the mutation is executed. **It should be placed before `mutation()` for `context` to be inferred**. It\n   * can return a value that will be passed to `mutation`, `onSuccess`, `onError` and `onSettled`. If it returns a\n   * promise, it will be awaited before running `mutation`.\n   *\n   * @example\n   * ```ts\n   * useMutation({\n   * // must appear before `mutation` for `{ foo: string }` to be inferred\n   * // within `mutation`\n   *   onMutate() {\n   *     return { foo: 'bar' }\n   *   },\n   *   mutation: (id: number, { foo }) => {\n   *     console.log(foo) // bar\n   *     return fetch(`/api/todos/${id}`)\n   *   },\n   *   onSuccess(context) {\n   *     console.log(context.foo) // bar\n   *   },\n   * })\n   * ```\n   */\n  onMutate?: (\n    /**\n     * The variables passed to the mutation.\n     */\n    vars: NoInfer<TVars>,\n    context: UseMutationGlobalContext,\n  ) => _Awaitable<TContext | undefined | void | null>\n\n  /**\n   * Runs if the mutation is successful.\n   */\n  onSuccess?: (\n    /**\n     * The result of the mutation.\n     */\n    data: NoInfer<TResult>,\n    /**\n     * The variables passed to the mutation.\n     */\n    vars: NoInfer<TVars>,\n    /**\n     * The merged context from `onMutate` and the global context.\n     */\n    context: UseMutationGlobalContext & _ReduceContext<NoInfer<TContext>>,\n  ) => unknown\n\n  /**\n   * Runs if the mutation encounters an error.\n   */\n  onError?: (\n    /**\n     * The error thrown by the mutation.\n     */\n    error: TError,\n    /**\n     * The variables passed to the mutation.\n     */\n    vars: NoInfer<TVars>,\n    /**\n     * The merged context from `onMutate` and the global context. Properties returned by `onMutate` can be `undefined`\n     * if `onMutate` throws.\n     */\n    context:\n      | (Partial<Record<keyof UseMutationGlobalContext, never>> &\n          Partial<Record<keyof _ReduceContext<NoInfer<TContext>>, never>>)\n      // this is the success case where everything is defined\n      // undefined if global onMutate throws\n      | (UseMutationGlobalContext & _ReduceContext<NoInfer<TContext>>),\n  ) => unknown\n\n  /**\n   * Runs after the mutation is settled, regardless of the result.\n   */\n  onSettled?: (\n    /**\n     * The result of the mutation. `undefined` if the mutation failed.\n     */\n    data: NoInfer<TResult> | undefined,\n    /**\n     * The error thrown by the mutation. `undefined` if the mutation was successful.\n     */\n    error: TError | undefined,\n    /**\n     * The variables passed to the mutation.\n     */\n    vars: NoInfer<TVars>,\n    /**\n     * The merged context from `onMutate` and the global context. Properties returned by `onMutate` can be `undefined`\n     * if `onMutate` throws.\n     */\n    context:\n      | (Partial<Record<keyof UseMutationGlobalContext, never>> &\n          Partial<Record<keyof _ReduceContext<NoInfer<TContext>>, never>>)\n      // this is the success case where everything is defined\n      // undefined if global onMutate throws\n      | (UseMutationGlobalContext & _ReduceContext<NoInfer<TContext>>),\n  ) => unknown\n}\n\nexport const USE_MUTATION_OPTIONS_KEY: InjectionKey<UseMutationOptionsGlobal>\n  = process.env.NODE_ENV !== 'production' ? Symbol('useMutationOptions') : Symbol()\n\n/**\n * Injects the global query options.\n * @internal\n */\nexport const useMutationOptions = (): UseMutationOptionsGlobal =>\n  inject(USE_MUTATION_OPTIONS_KEY, {})\n","import type { ComputedRef, ShallowRef } from 'vue'\nimport type { AsyncStatus, DataState, DataStateStatus } from './data-state'\nimport type { EntryKey } from './entry-options'\nimport type { ErrorDefault } from './types-extension'\nimport { computed, shallowRef } from 'vue'\nimport { useMutationCache } from './mutation-store'\nimport type { UseMutationEntry } from './mutation-store'\nimport { noop } from './utils'\nimport type { _EmptyObject } from './utils'\nimport type { UseMutationOptions } from './mutation-options'\n\n/**\n * Valid keys for a mutation. Similar to query keys.\n * @see {@link EntryKey}\n * @internal\n */\nexport type _MutationKey<TVars> = EntryKey | ((vars: TVars) => EntryKey)\n\n/**\n * Removes the nullish types from the context type to make `A & TContext` work instead of yield `never`.\n * @internal\n */\nexport type _ReduceContext<TContext> = TContext extends void | null | undefined\n  ? _EmptyObject\n  : Record<any, any> extends TContext\n    ? _EmptyObject\n    : TContext\n\n/**\n * Context object returned by a global `onMutate` function that is merged with the context returned by a local\n * `onMutate`.\n * @example\n * ```ts\n * declare module '@pinia/colada' {\n *   export interface UseMutationGlobalContext {\n *     router: Router // from vue-router\n *   }\n * }\n *\n * // add the `router` to the context\n * app.use(MutationPlugin, {\n *   onMutate() {\n *     return { router }\n *   },\n * })\n * ```\n */\nexport interface UseMutationGlobalContext {}\n\n// export const USE_MUTATIONS_DEFAULTS = {} satisfies Partial<UseMutationsOptions>\n\nexport interface UseMutationReturn<TResult, TVars, TError> {\n  key?: EntryKey | ((vars: NoInfer<TVars>) => EntryKey)\n\n  /**\n   * The combined state of the mutation. Contains its data, error, and status. It enables type narrowing based on the {@link UseMutationReturn.status}.\n   */\n  state: ComputedRef<DataState<TResult, TError>>\n\n  /**\n   * The status of the mutation.\n   * @see {@link DataStateStatus}\n   */\n  status: ShallowRef<DataStateStatus>\n\n  /**\n   * Status of the mutation. Becomes `'loading'` while the mutation is being fetched, is `'idle'` otherwise.\n   */\n  asyncStatus: ShallowRef<AsyncStatus>\n\n  /**\n   * The result of the mutation. `undefined` if the mutation has not been called yet.\n   */\n  data: ShallowRef<TResult | undefined>\n\n  /**\n   * The error of the mutation. `null` if the mutation has not been called yet or if it was successful.\n   */\n  error: ShallowRef<TError | null>\n\n  /**\n   * Whether the mutation is currently executing.\n   */\n  isLoading: ComputedRef<boolean>\n\n  /**\n   * The variables passed to the mutation. They are initially `undefined` and change every time the mutation is called.\n   */\n  variables: ShallowRef<TVars | undefined>\n\n  /**\n   * Calls the mutation and returns a promise with the result.\n   *\n   * @param vars - parameters to pass to the mutation\n   */\n  mutateAsync: unknown | void extends TVars\n    ? () => Promise<TResult>\n    : (vars: TVars) => Promise<TResult>\n\n  /**\n   * Calls the mutation without returning a promise to avoid unhandled promise rejections.\n   *\n   * @param args - parameters to pass to the mutation\n   */\n  mutate: (...args: unknown | void extends TVars ? [] : [vars: TVars]) => void\n\n  /**\n   * Resets the state of the mutation to its initial state.\n   */\n  reset: () => void\n}\n\n/**\n * Setups a mutation.\n *\n * @param options - Options to create the mutation\n * @example\n * ```ts\n * const queryCache = useQueryCache()\n * const { mutate, status, error } = useMutation({\n *   mutation: (id: number) => fetch(`/api/todos/${id}`),\n *   onSuccess() {\n *     queryCache.invalidateQueries('todos')\n *   },\n * })\n * ```\n */\nexport function useMutation<\n  TResult,\n  TVars = void,\n  TError = ErrorDefault,\n  TContext extends Record<any, any> = _EmptyObject,\n>(\n  options: UseMutationOptions<TResult, TVars, TError, TContext>,\n): UseMutationReturn<TResult, TVars, TError> {\n  const mutationCache = useMutationCache()\n  // always create an initial entry with no key (cannot be computed without vars)\n  const entry = shallowRef<UseMutationEntry<TResult, TVars, TError, TContext>>(\n    mutationCache.ensure(options),\n  )\n\n  const state = computed(() => entry.value.state.value)\n  const status = computed(() => state.value.status)\n  const data = computed(() => state.value.data)\n  const error = computed(() => state.value.error)\n  const asyncStatus = computed(() => entry.value.asyncStatus.value)\n  const variables = computed(() => entry.value.vars.value)\n\n  async function mutateAsync(vars: TVars): Promise<TResult> {\n    // either create a new entry, transform the initial one with the correct keys, or reuse the same if keys are undefined\n    return mutationCache.mutate(\n      (entry.value = mutationCache.ensure(options, entry.value, vars)),\n      vars,\n    )\n  }\n\n  function mutate(vars: NoInfer<TVars>) {\n    mutateAsync(vars).catch(noop)\n  }\n\n  function reset() {\n    mutationCache.setEntryState(entry.value, {\n      status: 'pending',\n      data: undefined,\n      error: null,\n    })\n    entry.value.asyncStatus.value = 'idle'\n  }\n\n  return {\n    state,\n    data,\n    isLoading: computed(() => asyncStatus.value === 'loading'),\n    status,\n    variables,\n    asyncStatus,\n    error,\n    // @ts-expect-error: because of the conditional type in UseMutationReturn\n    // it would be nice to find a type-only refactor that works\n    mutate,\n    // @ts-expect-error: same as above\n    mutateAsync,\n    reset,\n  }\n}\n","import { useMutationCache } from './mutation-store'\nimport type { ErrorDefault } from './types-extension'\nimport { useMutation } from './use-mutation'\nimport type { UseMutationReturn } from './use-mutation'\nimport type { UseMutationOptions } from './mutation-options'\nimport type { _EmptyObject } from './utils'\n\n/**\n * Define a mutation with the given options. Similar to `useMutation(options)` but allows you to reuse the mutation in\n * multiple places.\n *\n * @param options - the options to define the mutation\n * @example\n * ```ts\n * const useCreateTodo = defineMutation({\n *   mutation: (todoText: string) =>\n *     fetch('/api/todos', {\n *       method: 'POST',\n *       body: JSON.stringify({ text: todoText }),\n *     }),\n * })\n * ```\n */\nexport function defineMutation<\n  TResult,\n  TVars = void,\n  TError = ErrorDefault,\n  TContext extends Record<any, any> = _EmptyObject,\n>(\n  options: UseMutationOptions<TResult, TVars, TError, TContext>,\n): () => UseMutationReturn<TResult, TVars, TError>\n\n/**\n * Define a mutation with a function setup. Allows to return arbitrary values from the mutation function, create\n * contextual refs, rename the returned values, etc.\n *\n * @param setup - a function to setup the mutation\n * @example\n * ```ts\n * const useCreateTodo = defineMutation(() => {\n *   const todoText = ref('')\n *   const { data, mutate, ...rest } = useMutation({\n *     mutation: () =>\n *       fetch('/api/todos', {\n *         method: 'POST',\n *         body: JSON.stringify({ text: todoText.value }),\n *       }),\n *   })\n *   // expose the todoText ref and rename other methods for convenience\n *   return { ...rest, createTodo: mutate, todo: data, todoText }\n * })\n * ```\n */\nexport function defineMutation<T>(setup: () => T): () => T\nexport function defineMutation(\n  optionsOrSetup: UseMutationOptions | (() => unknown),\n): () => unknown {\n  const setupFn\n    = typeof optionsOrSetup === 'function' ? optionsOrSetup : () => useMutation(optionsOrSetup)\n  return () => {\n    // TODO: provide a way to clean them up `mutationCache.clear()`\n    const mutationCache = useMutationCache()\n    return mutationCache.ensureDefinedMutation(setupFn)\n  }\n}\n","import { getCurrentInstance, getCurrentScope, onScopeDispose, toValue } from 'vue'\nimport type { EffectScope } from 'vue'\nimport type { UseQueryOptions } from './query-options'\nimport { useQueryCache } from './query-store'\nimport type { ErrorDefault } from './types-extension'\nimport type { UseQueryReturn } from './use-query'\nimport { useQuery } from './use-query'\nimport type { _RemoveMaybeRef } from './utils'\n\n/**\n * The current effect scope where the function returned by `defineQuery` is being called. This allows `useQuery()` to know if it should be attached to an effect scope or not\n */\nlet currentDefineQueryEffect: undefined | EffectScope\n\n/**\n * Options to define a query with `defineQuery()`. Similar to {@link UseQueryOptions} but disallows reactive values as\n * `defineQuery()` is used outside of an effect scope.\n */\nexport interface DefineQueryOptions<TResult = unknown, TError = ErrorDefault>\n  extends _RemoveMaybeRef<UseQueryOptions<TResult, TError>> {}\n\n// NOTE: no setter because it cannot be set outside of defineQuery()\n\n/**\n * Gets the current defineQuery effect scope. This is used internally by `useQuery` to attach the effect to the query\n * entry dependency list.\n * @internal\n */\nexport function getCurrentDefineQueryEffect() {\n  return currentDefineQueryEffect\n}\n\n/**\n * Define a query with the given options. Similar to `useQuery(options)` but allows you to reuse the query in multiple\n * places. It only allow static values in options. If you need dynamic values, use the function version.\n *\n * @param options - the options to define the query\n * @example\n * ```ts\n * const useTodoList = defineQuery({\n *   key: ['todos'],\n *   query: () => fetch('/api/todos', { method: 'GET' }),\n * })\n * ```\n */\nexport function defineQuery<TResult, TError = ErrorDefault>(\n  options: DefineQueryOptions<TResult, TError>,\n): () => UseQueryReturn<TResult, TError>\n\n/**\n * Define a query with a setup function. Allows to return arbitrary values from the query function, create contextual\n * refs, rename the returned values, etc. The setup function will be called only once, like stores, and **must be\n * synchronous**.\n *\n * @param setup - a function to setup the query\n * @example\n * ```ts\n * const useFilteredTodos = defineQuery(() => {\n *   const todoFilter = ref<'all' | 'finished' | 'unfinished'>('all')\n *   const { data, ...rest } = useQuery({\n *    key: ['todos', { filter: todoFilter.value }],\n *     query: () =>\n *       fetch(`/api/todos?filter=${todoFilter.value}`, { method: 'GET' }),\n *   })\n *   // expose the todoFilter ref and rename data for convenience\n *   return { ...rest, todoList: data, todoFilter }\n * })\n * ```\n */\nexport function defineQuery<T>(setup: () => T): () => T\nexport function defineQuery(optionsOrSetup: DefineQueryOptions | (() => unknown)): () => unknown {\n  const setupFn\n    = typeof optionsOrSetup === 'function' ? optionsOrSetup : () => useQuery(optionsOrSetup)\n\n  let hasBeenEnsured: boolean | undefined\n  return () => {\n    const queryCache = useQueryCache()\n    // preserve any current effect to account for nested usage of these functions\n    const previousEffect = currentDefineQueryEffect\n    const currentScope = getCurrentInstance() || (currentDefineQueryEffect = getCurrentScope())\n\n    const [entries, ret, scope] = queryCache.ensureDefinedQuery(setupFn)\n\n    // subsequent calls to the composable returned by useQuery will not trigger the `useQuery()`,\n    // this ensures the refetchOnMount option is respected\n    if (hasBeenEnsured) {\n      entries.forEach((entry) => {\n        // TODO: should happen in useQuery and defineQuery\n        if (entry.options?.refetchOnMount && toValue(entry.options.enabled)) {\n          if (toValue(entry.options.refetchOnMount) === 'always') {\n            queryCache.fetch(entry)\n          } else {\n            queryCache.refresh(entry)\n          }\n        }\n      })\n    }\n    hasBeenEnsured = true\n\n    // NOTE: most of the time this should be set, so maybe we should show a dev warning\n    // if it's not set instead\n    if (currentScope) {\n      entries.forEach((entry) => {\n        queryCache.track(entry, currentScope)\n        if (process.env.NODE_ENV !== 'production') {\n          entry.__hmr ??= {}\n          entry.__hmr.skip = true\n        }\n      })\n      onScopeDispose(() => {\n        // if all entries become inactive, we pause the scope\n        // to avoid triggering the effects within useQuery. This immitates the behavior\n        // of a component that unmounts\n        if (\n          entries.every((entry) => {\n            queryCache.untrack(entry, currentScope)\n            return !entry.active\n          })\n        ) {\n          scope.pause()\n        }\n      })\n    }\n\n    // reset the previous effect\n    currentDefineQueryEffect = previousEffect\n\n    return ret\n  }\n}\n","import { defineStore, getActivePinia, skipHydrate } from 'pinia'\nimport {\n  customRef,\n  effectScope,\n  getCurrentInstance,\n  getCurrentScope,\n  hasInjectionContext,\n  markRaw,\n  shallowRef,\n  toValue,\n} from 'vue'\nimport type { App, ComponentInternalInstance, EffectScope, ShallowRef } from 'vue'\nimport type { AsyncStatus, DataState, DataState_Success, DataStateStatus } from './data-state'\nimport type { EntryKey } from './entry-options'\nimport { useQueryOptions } from './query-options'\nimport type { UseQueryOptions, UseQueryOptionsWithDefaults } from './query-options'\nimport type {\n  _UseQueryEntryNodeValueSerialized,\n  EntryNodeKey,\n  UseQueryEntryNodeSerialized,\n} from './tree-map'\nimport { appendSerializedNodeToTree, TreeMapNode } from './tree-map'\nimport type { ErrorDefault } from './types-extension'\nimport { noop, toCacheKey, toValueWithArgs, warnOnce } from './utils'\n\n/**\n * Allows defining extensions to the query entry that are returned by `useQuery()`.\n */\n\nexport interface UseQueryEntryExtensions<\n  TResult,\n  /* eslint-disable-next-line unused-imports/no-unused-vars */\n  TError,\n  /* eslint-disable-next-line unused-imports/no-unused-vars */\n  TDataInitial extends TResult | undefined = TResult | undefined,\n> {}\n\n/**\n * NOTE: Entries could be classes but the point of having all functions within the store is to allow plugins to hook\n * into actions.\n */\n\n/**\n * A query entry in the cache.\n */\nexport interface UseQueryEntry<\n  TResult = unknown,\n  TError = unknown,\n  TDataInitial extends TResult | undefined = TResult | undefined,\n> {\n  /**\n   * The state of the query. Contains the data, error and status.\n   */\n  state: ShallowRef<DataState<TResult, TError, TDataInitial>>\n\n  /**\n   * A placeholder `data` that is initially shown while the query is loading for the first time. This will also show the\n   * `status` as `success` until the query finishes loading (no matter the outcome).\n   */\n  placeholderData: TDataInitial | TResult | null | undefined\n\n  /**\n   * The status of the query.\n   */\n  asyncStatus: ShallowRef<AsyncStatus>\n\n  /**\n   * When was this data set in the entry for the last time in ms. It can also\n   * be 0 if the entry has been invalidated.\n   */\n  when: number\n\n  /**\n   * The serialized key associated with this query entry.\n   */\n  key: EntryNodeKey[]\n\n  /**\n   * Components and effects scopes that use this query entry.\n   */\n  deps: Set<EffectScope | ComponentInternalInstance>\n\n  /**\n   * Timeout id that scheduled a garbage collection. It is set here to clear it when the entry is used by a different component\n   */\n  gcTimeout: ReturnType<typeof setTimeout> | undefined\n\n  /**\n   * The current pending request.\n   */\n  pending: null | {\n    /**\n     * The abort controller used to cancel the request and which `signal` is passed to the query function.\n     */\n    abortController: AbortController\n    /**\n     * The promise created by `queryCache.fetch` that is currently pending.\n     */\n    refreshCall: Promise<DataState<TResult, TError, TDataInitial>>\n    /**\n     * When was this `pending` object created.\n     */\n    when: number\n  }\n\n  /**\n   * Options used to create the query. They can be `null` during hydration but are needed for fetching. This is why\n   * `store.ensure()` sets this property. Note these options might be shared by multiple query entries when the key is\n   * dynamic and that's why some methods like {@link fetch} receive the options as an argument.\n   */\n  options: UseQueryOptionsWithDefaults<TResult, TError, TDataInitial> | null\n\n  /**\n   * Whether the data is stale or not, requires `options.staleTime` to be set.\n   */\n  readonly stale: boolean\n\n  /**\n   * Whether the query is currently being used by a Component or EffectScope (e.g. a store).\n   */\n  readonly active: boolean\n\n  /**\n   * Extensions to the query entry added by plugins.\n   */\n  ext: UseQueryEntryExtensions<TResult, TError, TDataInitial>\n\n  /**\n   * Component `__hmrId` to track wrong usage of `useQuery` and warn the user.\n   * @internal\n   */\n  __hmr?: {\n    id?: string\n    deps?: Set<EffectScope | ComponentInternalInstance>\n    skip?: boolean\n  }\n}\n\n/**\n * Returns whether the entry is using a placeholder data.\n *\n * @template TDataInitial - Initial data type\n * @param entry - entry to check\n */\nexport function isEntryUsingPlaceholderData<TDataInitial>(\n  entry: UseQueryEntry<unknown, unknown, TDataInitial> | undefined | null,\n): entry is UseQueryEntry<unknown, unknown, TDataInitial> & { placeholderData: TDataInitial } {\n  return entry?.placeholderData != null && entry.state.value.status === 'pending'\n}\n\n/**\n * Filter to get entries from the cache.\n */\nexport interface UseQueryEntryFilter {\n  /**\n   * A key to filter the entries.\n   */\n  key?: EntryKey\n\n  /**\n   * If true, it will only match the exact key, not the children.\n   *\n   * @example\n   * ```ts\n   * { key: ['a'], exact: true }\n   *  // will match ['a'] but not ['a', 'b'], while\n   * { key: ['a'] }\n   * // will match both\n   * ```\n   */\n  exact?: boolean\n\n  /**\n   * If `true` or `false`, it will only return entries that match the stale status. If set to `null` or `undefined`, it matches both.\n   * Requires `entry.options` to be set.\n   */\n  stale?: boolean | null\n\n  /**\n   * If `true` or `false`, it will only return entries that match the active status. If set to `null` or `undefined`, it matches both.\n   */\n  active?: boolean | null\n\n  /**\n   * If it has a non _nullish_ value, it only returns the entries with the given status.\n   */\n  status?: DataStateStatus | null\n\n  /**\n   * Pass a predicate to filter the entries. This will be executed for each entry matching the other filters.\n   * @param entry - entry to filter\n   */\n  predicate?: (entry: UseQueryEntry) => boolean\n}\n\n/**\n * Empty starting object for extensions that allows to detect when to update.\n * @internal\n */\nexport const START_EXT = {}\n\n/**\n * UseQueryEntry method to serialize the entry to JSON.\n *\n * @param entry - entry to serialize\n * @param entry.when - when the data was fetched the last time\n * @param entry.state - data state of the entry\n * @param entry.state.value - value of the data state\n * @returns Serialized version of the entry\n */\nexport const queryEntry_toJSON: <TResult, TError>(\n  entry: UseQueryEntry<TResult, TError>,\n) => _UseQueryEntryNodeValueSerialized<TResult, TError> = ({ state: { value }, when }) => [\n  value.data,\n  value.error,\n  when,\n]\n// TODO: errors are not serializable by default. We should provide a way to serialize custom errors and, by default provide one that serializes the name and message\n\n/**\n * UseQueryEntry method to serialize the entry to a string.\n *\n * @internal\n * @param entry - entry to serialize\n * @returns Stringified version of the entry\n */\nexport const queryEntry_toString: <TResult, TError>(\n  entry: UseQueryEntry<TResult, TError>,\n) => string = (entry) => String(queryEntry_toJSON(entry))\n\n/**\n * The id of the store used for queries.\n * @internal\n */\nexport const QUERY_STORE_ID = '_pc_query'\n\n/**\n * A query entry that is defined with {@link defineQuery}.\n * @internal\n */\ntype DefineQueryEntry = [entries: UseQueryEntry[], returnValue: unknown, effect: EffectScope]\n\n/**\n * Composable to get the cache of the queries. As any other composable, it can be used inside the `setup` function of a\n * component, within another composable, or in injectable contexts like stores and navigation guards.\n */\nexport const useQueryCache = /* @__PURE__ */ defineStore(QUERY_STORE_ID, ({ action }) => {\n  // We have two versions of the cache, one that track changes and another that doesn't so the actions can be used\n  // inside computed properties\n  const cachesRaw = new TreeMapNode<UseQueryEntry<unknown, unknown, unknown>>()\n  let triggerCache!: () => void\n  const caches = skipHydrate(\n    customRef(\n      (track, trigger) =>\n        (triggerCache = trigger) && {\n          // eslint-disable-next-line no-sequences\n          get: () => (track(), cachesRaw),\n          set:\n            process.env.NODE_ENV !== 'production'\n              ? () => {\n                  console.error(\n                    `[@pinia/colada]: The query cache instance cannot be set directly, it must be modified. This will fail in production.`,\n                  )\n                }\n              : noop,\n        },\n    ),\n  )\n\n  // this version of the cache cannot be hydrated because it would miss all of the actions\n  // and plugins won't be able to hook into entry creation and fetching\n  // this allows use to attach reactive effects to the scope later on\n  const scope = getCurrentScope()!\n  const app: App<unknown>\n    // @ts-expect-error: internal\n    = getActivePinia()!._a\n\n  if (process.env.NODE_ENV !== 'production') {\n    if (!hasInjectionContext()) {\n      warnOnce(\n        `useQueryCache() was called outside of an injection context (component setup, store, navigation guard) You will get a warning about \"inject\" being used incorrectly from Vue. Make sure to use it only in allowed places.\\n`\n          + `See https://vuejs.org/guide/reusability/composables.html#usage-restrictions`,\n      )\n    }\n  }\n\n  const optionDefaults = useQueryOptions()\n\n  const create = action(\n    <TResult, TError, TDataInitial extends TResult | undefined>(\n      key: EntryNodeKey[],\n      options: UseQueryOptionsWithDefaults<TResult, TError, TDataInitial> | null = null,\n      initialData?: TDataInitial,\n      error: TError | null = null,\n      when: number = 0,\n    ): UseQueryEntry<TResult, TError, TDataInitial> =>\n      scope.run(() => {\n        const state = shallowRef<DataState<TResult, TError, TDataInitial>>(\n          // @ts-expect-error: to make the code shorter we are using one declaration instead of multiple ternaries\n          {\n            // NOTE: we could move the `initialData` parameter before `options` and make it required\n            // but that would force `create` call in `setQueryData` to pass an extra `undefined` argument\n            data: initialData as TDataInitial,\n            error,\n            status: error ? 'error' : initialData !== undefined ? 'success' : 'pending',\n          },\n        )\n        const asyncStatus = shallowRef<AsyncStatus>('idle')\n        // we markRaw to avoid unnecessary vue traversal\n        return markRaw<UseQueryEntry<TResult, TError, TDataInitial>>({\n          key,\n          state,\n          placeholderData: null,\n          when,\n          asyncStatus,\n          pending: null,\n          // this set can contain components and effects and worsen the performance\n          // and create weird warnings\n          deps: markRaw(new Set()),\n          gcTimeout: undefined,\n          // eslint-disable-next-line ts/ban-ts-comment\n          // @ts-ignore: some plugins are adding properties to the entry type\n          ext: START_EXT,\n          options,\n          get stale() {\n            return !this.when || Date.now() >= this.when + this.options!.staleTime\n          },\n          get active() {\n            return this.deps.size > 0\n          },\n        } satisfies UseQueryEntry<TResult, TError, TDataInitial>)\n      })!,\n  )\n\n  // keep track of the entry being defined so we can add the queries in ensure\n  // this allows us to refresh the entry when a defined query is used again\n  // and refetchOnMount is true\n  let currentDefineQueryEntry: DefineQueryEntry | undefined | null\n  const defineQueryMap = new WeakMap<() => unknown, DefineQueryEntry>()\n\n  /**\n   * Ensures a query created with {@link defineQuery} is present in the cache. If it's not, it creates a new one.\n   * @param fn - function that defines the query\n   */\n  const ensureDefinedQuery = action(<T>(fn: () => T) => {\n    let defineQueryEntry = defineQueryMap.get(fn)\n    if (!defineQueryEntry) {\n      // create the entry first\n      currentDefineQueryEntry = defineQueryEntry = [[], null, scope.run(() => effectScope())!]\n      // then run it so it can add the queries to the entry\n      // we use the app context for injections and the scope for effects\n      defineQueryEntry[1] = app.runWithContext(() => defineQueryEntry![2].run(fn)!)\n      currentDefineQueryEntry = null\n      defineQueryMap.set(fn, defineQueryEntry)\n    } else {\n      // ensure the scope is active so effects computing inside `useQuery()` run (e.g. the entry computed)\n      defineQueryEntry[2].resume()\n      // if the entry already exists, we know the queries inside\n      // we should consider as if they are activated again\n      defineQueryEntry[0] = defineQueryEntry[0].map((oldEntry) =>\n        // the entries' key might have changed (e.g. Nuxt navigation)\n        // so we need to ensure them again\n        oldEntry.options ? ensure(oldEntry.options, oldEntry) : oldEntry,\n      )\n    }\n\n    return defineQueryEntry\n  })\n\n  /**\n   * Tracks an effect or component that uses a query.\n   *\n   * @param entry - the entry of the query\n   * @param effect - the effect or component to untrack\n   *\n   * @see {@link untrack}\n   */\n  function track(\n    entry: UseQueryEntry,\n    effect: EffectScope | ComponentInternalInstance | null | undefined,\n  ) {\n    if (!effect) return\n    entry.deps.add(effect)\n    // clearTimeout ignores anything that isn't a timerId\n    clearTimeout(entry.gcTimeout)\n    entry.gcTimeout = undefined\n    triggerCache()\n  }\n\n  /**\n   * Untracks an effect or component that uses a query.\n   *\n   * @param entry - the entry of the query\n   * @param effect - the effect or component to untrack\n   *\n   * @see {@link track}\n   */\n  function untrack(\n    entry: UseQueryEntry,\n    effect: EffectScope | ComponentInternalInstance | undefined | null,\n  ) {\n    // avoid clearing an existing timeout\n    if (!effect || !entry.deps.has(effect)) return\n\n    entry.deps.delete(effect)\n    triggerCache()\n\n    // schedule a garbage collection if the entry is not active\n    if (entry.deps.size > 0 || !entry.options) return\n    clearTimeout(entry.gcTimeout)\n    // avoid setting a timeout with false, Infinity or NaN\n    if ((Number.isFinite as (val: unknown) => val is number)(entry.options.gcTime)) {\n      entry.gcTimeout = setTimeout(() => {\n        remove(entry)\n      }, entry.options.gcTime)\n    }\n  }\n\n  /**\n   * Invalidates, cancel, and refetches (in parallel) all active queries in the\n   * cache that match the filters. If you need to further control which queries\n   * are invalidated, canceled, and/or refetched, you can use the filters, you\n   * can direcly call {@link invalidate} on {@link getEntries}:\n   *\n   * ```ts\n   * // instead of doing\n   * await queryCache.invalidateQueries(filters)\n   * await Promise.all(queryCache.getEntries(filters).map(entry => {\n   *   queryCache.invalidate(entry)\n   *   // this is the default behavior of invalidateQueries\n   *   // return entry.active && queryCache.fetch(entry)\n   *   // here to refetch everything, even non active queries\n   *   return queryCache.fetch(entry)\n   * })\n   * ```\n   *\n   * @param filters - filters to apply to the entries\n   *\n   * @see {@link invalidate}\n   * @see {@link cancel}\n   */\n  const invalidateQueries = action((filters?: UseQueryEntryFilter): Promise<unknown> => {\n    return Promise.all(\n      getEntries({\n        active: true,\n        ...filters,\n      }).map((entry) => {\n        invalidate(entry)\n        return toValue(entry.options?.enabled) && fetch(entry)\n      }),\n    )\n  })\n\n  /**\n   * Returns all the entries in the cache that match the filters.\n   *\n   * @param filters - filters to apply to the entries\n   */\n  const getEntries = action((filters: UseQueryEntryFilter = {}): UseQueryEntry[] => {\n    const node = filters.key ? caches.value.find(toCacheKey(filters.key)) : caches.value\n\n    if (!node) return []\n\n    return (filters.exact ? (node.value ? [node.value] : []) : [...node]).filter(\n      (entry) =>\n        (filters.stale == null || entry.stale === filters.stale)\n        && (filters.active == null || entry.active === filters.active)\n        && (!filters.status || entry.state.value.status === filters.status)\n        && (!filters.predicate || filters.predicate(entry)),\n    )\n  })\n\n  /**\n   * Ensures a query entry is present in the cache. If it's not, it creates a new one. The resulting entry is required\n   * to call other methods like {@link fetch}, {@link refresh}, or {@link invalidate}.\n   *\n   * @param opts - options to create the query\n   * @param previousEntry - the previous entry that was associated with the same options\n   */\n  const ensure = action(\n    <\n      TResult = unknown,\n      TError = ErrorDefault,\n      TDataInitial extends TResult | undefined = undefined,\n    >(\n      opts: UseQueryOptions<TResult, TError, TDataInitial>,\n      previousEntry?: UseQueryEntry<TResult, TError, TDataInitial>,\n    ): UseQueryEntry<TResult, TError, TDataInitial> => {\n      const options: UseQueryOptionsWithDefaults<TResult, TError, TDataInitial> = {\n        ...optionDefaults,\n        ...opts,\n      }\n      const key = toCacheKey(toValue(options.key))\n\n      if (process.env.NODE_ENV !== 'production' && key.length === 0) {\n        throw new Error(\n          `useQuery() was called with an empty array as the key. It must have at least one element.`,\n        )\n      }\n\n      // Since ensure() is called within a computed, we cannot let Vue track cache, so we use the raw version instead\n      let entry = cachesRaw.get(key) as UseQueryEntry<TResult, TError, TDataInitial> | undefined\n      // ensure the state\n      if (!entry) {\n        cachesRaw.set(key, (entry = create(key, options, options.initialData?.())))\n        // the placeholderData is only used if the entry is initially loading\n        if (options.placeholderData && entry.state.value.status === 'pending') {\n          entry.placeholderData = toValueWithArgs(\n            options.placeholderData,\n            // pass the previous entry placeholder data if it was in placeholder state\n            // NOTE: the build needs a cast or it thinks it's never\n            isEntryUsingPlaceholderData(previousEntry)\n              ? previousEntry.placeholderData\n              : (previousEntry as UseQueryEntry<TResult, TError, TDataInitial> | undefined)?.state.value.data,\n          )\n        }\n        triggerCache()\n      }\n\n      // warn against using the same key for different functions\n      // this only applies outside of HMR since during HMR, the `useQuery()` will be called\n      // when remounting the component and it's essential to update the options.\n      // in other scenarios, it's a mistake\n      if (process.env.NODE_ENV !== 'production') {\n        const currentInstance = getCurrentInstance()\n        if (currentInstance) {\n          entry.__hmr ??= {}\n\n          entry.__hmr.deps ??= new Set()\n          entry.__hmr.id\n            // @ts-expect-error: internal property\n            = currentInstance.type?.__hmrId\n            // @ts-expect-error: for Vue 2 support\n            ?? currentInstance.proxy?._uid\n          if (\n            entry.__hmr.id == null\n            && process.env.NODE_ENV !== 'test'\n            && typeof document !== 'undefined'\n          ) {\n            warnOnce(\n              `Found a nullish hmr id. This is probably a bug. Please report it to pinia-colada with a boiled down reproduction. Thank you!`,\n            )\n          }\n        }\n      }\n\n      // we set it every time to ensure we are using up to date key getters and others options\n      entry.options = options\n\n      // extend the entry with plugins the first time only\n      if (entry.ext === START_EXT) {\n        entry.ext = {} as UseQueryEntryExtensions<TResult, TError>\n        extend(entry)\n      }\n\n      // if this query was defined within a defineQuery call, add it to the list\n      currentDefineQueryEntry?.[0].push(entry)\n\n      return entry\n    },\n  )\n\n  /**\n   * Action called when an entry is ensured for the first time to allow plugins to extend it.\n   *\n   * @param _entry - the entry of the query to extend\n   */\n  const extend = action(\n    <TResult = unknown, TError = ErrorDefault>(_entry: UseQueryEntry<TResult, TError>) => {},\n  )\n\n  /**\n   * Invalidates and cancels a query entry. It effectively sets the `when` property to `0` and {@link cancel | cancels} the pending request.\n   *\n   * @param entry - the entry of the query to invalidate\n   *\n   * @see {@link cancel}\n   */\n  const invalidate = action((entry: UseQueryEntry) => {\n    // will force a fetch next time\n    entry.when = 0\n    // ignores the pending query\n    cancel(entry)\n  })\n\n  /**\n   * Ensures the current data is fresh. If the data is stale or if the status is 'error', calls {@link fetch}, if not\n   * return the current data. Can only be called if the entry has been initialized with `useQuery()` and has options.\n   *\n   * @param entry - the entry of the query to refresh\n   * @param options - the options to use for the fetch\n   *\n   * @see {@link fetch}\n   */\n  const refresh = action(\n    async <TResult, TError, TDataInitial extends TResult | undefined>(\n      entry: UseQueryEntry<TResult, TError, TDataInitial>,\n      options = entry.options,\n    ): Promise<DataState<TResult, TError, TDataInitial>> => {\n      if (process.env.NODE_ENV !== 'production' && !options) {\n        throw new Error(\n          `\"entry.refresh()\" was called but the entry has no options. This is probably a bug, report it to pinia-colada with a boiled down example to reproduce it. Thank you!`,\n        )\n      }\n\n      if (entry.state.value.error || entry.stale) {\n        return entry.pending?.refreshCall ?? fetch(entry, options)\n      }\n\n      return entry.state.value\n    },\n  )\n\n  /**\n   * Fetch an entry. Ignores fresh data and triggers a new fetch. Can only be called if the entry has options.\n   *\n   * @param entry - the entry of the query to fetch\n   * @param options - the options to use for the fetch\n   */\n  const fetch = action(\n    async <TResult, TError, TDataInitial extends TResult | undefined>(\n      entry: UseQueryEntry<TResult, TError, TDataInitial>,\n      options = entry.options,\n    ): Promise<DataState<TResult, TError, TDataInitial>> => {\n      if (process.env.NODE_ENV !== 'production' && !options) {\n        throw new Error(\n          `\"entry.fetch()\" was called but the entry has no options. This is probably a bug, report it to pinia-colada with a boiled down example to reproduce it. Thank you!`,\n        )\n      }\n\n      entry.asyncStatus.value = 'loading'\n\n      const abortController = new AbortController()\n      const { signal } = abortController\n      // Abort any ongoing request without a reason to keep `AbortError` even with\n      // signal.throwIfAborted() in the query function\n      entry.pending?.abortController.abort()\n\n      const pendingCall = (entry.pending = {\n        abortController,\n        // wrapping with async allows us to catch synchronous errors too\n        refreshCall: (async () => options!.query({ signal }))()\n          .then((data) => {\n            if (pendingCall === entry.pending) {\n              setEntryState(entry, {\n                data,\n                error: null,\n                status: 'success',\n              })\n            }\n            return entry.state.value\n          })\n          .catch((error) => {\n            if (\n              pendingCall === entry.pending\n              && error\n              // when the error is an abort error, it means the request was cancelled\n              // we should just ignore the result of the query but not error\n              && error.name !== 'AbortError'\n            ) {\n              setEntryState(entry, {\n                status: 'error',\n                data: entry.state.value.data,\n                error,\n              })\n            }\n\n            // always propagate up the error\n            throw error\n            // NOTE: other options included returning an ongoing request if the error was a cancellation but it seems not worth it\n          })\n          .finally(() => {\n            entry.asyncStatus.value = 'idle'\n            if (pendingCall === entry.pending) {\n              // update the time amounts based on the current request\n              // NOTE: Normally these should be the same everywhere but the\n              // same query could be instantiated with different options\n              // entry.gcTime = options!.gcTime\n              // entry.staleTime = options!.staleTime\n              entry.pending = null\n              // there are cases when the result is ignored, in that case, we still\n              // do not have a real result so we keep the placeholder data\n              if (entry.state.value.status !== 'pending') {\n                // reset the placeholder data to free up memory\n                entry.placeholderData = null\n              }\n              entry.when = Date.now()\n            }\n          }),\n        when: Date.now(),\n      })\n\n      return pendingCall.refreshCall\n    },\n  )\n\n  /**\n   * Cancels an entry's query if it's currently pending. This will effectively abort the `AbortSignal` of the query and any\n   * pending request will be ignored.\n   *\n   * @param entry - the entry of the query to cancel\n   * @param reason - the reason passed to the abort controller\n   */\n  const cancel = action((entry: UseQueryEntry, reason?: unknown) => {\n    entry.pending?.abortController.abort(reason)\n    // eagerly set the status to idle because the abort signal might not\n    // be consumed by the user's query\n    entry.asyncStatus.value = 'idle'\n    entry.pending = null\n  })\n\n  /**\n   * Cancels queries if they are currently pending. This will effectively abort the `AbortSignal` of the query and any\n   * pending request will be ignored.\n   *\n   * @param filters - filters to apply to the entries\n   * @param reason - the reason passed to the abort controller\n   *\n   * @see {@link cancel}\n   */\n  const cancelQueries = action((filters?: UseQueryEntryFilter, reason?: unknown) => {\n    getEntries(filters).forEach((entry) => cancel(entry, reason))\n  })\n\n  /**\n   * Sets the state of a query entry in the cache and updates the\n   * {@link UseQueryEntry['pending']['when'] | `when` property}. This action is\n   * called every time the cache state changes and can be used by plugins to\n   * detect changes.\n   *\n   * @param entry - the entry of the query to set the state\n   * @param state - the new state of the entry\n   */\n  const setEntryState = action(\n    <TResult, TError>(\n      entry: UseQueryEntry<TResult, TError>,\n      // NOTE: NoInfer ensures correct inference of TResult and TError\n      state: DataState<NoInfer<TResult>, NoInfer<TError>>,\n    ) => {\n      entry.state.value = state\n      entry.when = Date.now()\n      // if we need to, we could schedule a garbage collection here but I don't\n      // see why would one create entries that are not used (not tracked immediately after)\n    },\n  )\n\n  /**\n   * Set the data of a query entry in the cache. It assumes an already successfully fetched entry.\n   *\n   * @param key - the key of the query\n   * @param data - the new data to set\n   *\n   * @see {@link setEntryState}\n   */\n  const setQueryData = action(\n    <TResult = unknown>(\n      key: EntryKey,\n      data: TResult | ((oldData: TResult | undefined) => TResult),\n    ) => {\n      const cacheKey = toCacheKey(key)\n      let entry = cachesRaw.get(cacheKey) as UseQueryEntry<TResult> | undefined\n\n      // if the entry doesn't exist, we create it to set the data\n      // it cannot be refreshed or fetched since the options\n      // will be missing\n      if (!entry) {\n        cachesRaw.set(cacheKey, (entry = create<TResult, any, TResult | undefined>(cacheKey)))\n      }\n\n      setEntryState(entry, {\n        // if we don't cast, this is not technically correct\n        // the user is responsible for setting the data\n        ...(entry.state.value as DataState_Success<TResult>),\n        data: toValueWithArgs(data, entry.state.value.data),\n      })\n      triggerCache()\n    },\n  )\n\n  /**\n   * Gets the data of a query entry in the cache based on the key of the query.\n   *\n   * @param key - the key of the query\n   */\n  function getQueryData<TResult = unknown>(key: EntryKey): TResult | undefined {\n    return caches.value.get(toCacheKey(key))?.state.value.data as TResult | undefined\n  }\n\n  /**\n   * Removes a query entry from the cache.\n   *\n   * @param entry - the entry of the query to remove\n   */\n  const remove = action((entry: UseQueryEntry) => {\n    cachesRaw.delete(entry.key)\n    triggerCache()\n  })\n\n  return {\n    caches,\n\n    ensureDefinedQuery,\n    /**\n     * Scope to track effects and components that use the query cache.\n     * @internal\n     */\n    _s: markRaw(scope),\n    setQueryData,\n    getQueryData,\n\n    invalidateQueries,\n    cancelQueries,\n\n    // Actions for entries\n    invalidate,\n    fetch,\n    refresh,\n    ensure,\n    extend,\n    track,\n    untrack,\n    cancel,\n    create,\n    remove,\n    setEntryState,\n    getEntries,\n  }\n})\n\n/**\n * The cache of the queries. It's the store returned by {@link useQueryCache}.\n */\nexport type QueryCache = ReturnType<typeof useQueryCache>\n\n/**\n * Transform a tree into a compressed array.\n * @param root - root node of the tree\n * @returns Array representation of the tree\n */\nexport function serializeTreeMap(root: TreeMapNode<UseQueryEntry>): UseQueryEntryNodeSerialized[] {\n  return root.children ? [...root.children.entries()].map(_serialize) : []\n}\n\n/**\n * Internal function to recursively transform the tree into a compressed array.\n * @internal\n */\nfunction _serialize([key, tree]: [\n  key: EntryNodeKey,\n  tree: TreeMapNode<UseQueryEntry>,\n]): UseQueryEntryNodeSerialized {\n  return [\n    key,\n    tree.value && queryEntry_toJSON(tree.value),\n    tree.children && [...tree.children.entries()].map(_serialize),\n  ]\n}\n\n/**\n * Hydrates the query cache with the serialized cache. Used during SSR.\n * @param queryCache - query cache\n * @param serializedCache - serialized cache\n */\nexport function hydrateQueryCache(\n  queryCache: QueryCache,\n  serializedCache: UseQueryEntryNodeSerialized[],\n) {\n  for (const entryData of serializedCache) {\n    appendSerializedNodeToTree(queryCache.caches, entryData, queryCache.create)\n  }\n}\n\n/**\n * Serializes the query cache to a compressed array. Used during SSR.\n * @param queryCache - query cache\n */\nexport function serializeQueryCache(queryCache: QueryCache): UseQueryEntryNodeSerialized[] {\n  return serializeTreeMap(queryCache.caches)\n}\n","import { inject } from 'vue'\nimport type { InjectionKey, MaybeRefOrGetter } from 'vue'\nimport type { EntryKey } from './entry-options'\nimport type { ErrorDefault } from './types-extension'\n\n/**\n * Possible values for `refetchOnMount`, `refetchOnWindowFocus`, and `refetchOnReconnect`.\n * `true` refetches if data is stale (calles `refresh()`), `false` never refetches, `'always'` always refetches.\n */\nexport type RefetchOnControl = boolean | 'always'\n\n/**\n * Options for queries that can be globally overridden.\n */\nexport interface UseQueryOptionsGlobal {\n  /**\n   * Whether the query should be enabled or not. If `false`, the query will not be executed until `refetch()` or\n   * `refresh()` is called. If it becomes `true`, the query will be refreshed.\n   */\n  enabled?: MaybeRefOrGetter<boolean>\n\n  /**\n   * Time in ms after which the data is considered stale and will be refreshed on next read.\n   * @default 5000 (5 seconds)\n   */\n  staleTime?: number\n\n  /**\n   * Time in ms after which, once the data is no longer being used, it will be garbage collected to free resources. Set to `false` to disable garbage collection.\n   * @default 300_000 (5 minutes)\n   */\n  gcTime?: number | false\n\n  /**\n   * Whether to refetch the query when the component is mounted.\n   * @default true\n   */\n  refetchOnMount?: MaybeRefOrGetter<RefetchOnControl>\n\n  /**\n   * Whether to refetch the query when the window regains focus.\n   * @default true\n   */\n  refetchOnWindowFocus?: MaybeRefOrGetter<RefetchOnControl>\n\n  /**\n   * Whether to refetch the query when the network reconnects.\n   * @default true\n   */\n  refetchOnReconnect?: MaybeRefOrGetter<RefetchOnControl>\n\n  /**\n   * A placeholder data that is initially shown while the query is loading for the first time. This will also show the\n   * `status` as `success` until the query finishes loading (no matter the outcome of the query). Note: unlike with\n   * `initialData`, the placeholder does not change the cache state.\n   */\n  placeholderData?: (previousData: unknown) => any // any allows us to not worry about the types when merging options\n}\n\n/**\n * Context object passed to the `query` function of `useQuery()`.\n * @see {@link UseQueryOptions}\n */\nexport interface UseQueryFnContext {\n  /**\n   * `AbortSignal` instance attached to the query call. If the call becomes outdated (e.g. due to a new call with the\n   * same key), the signal will be aborted.\n   */\n  signal: AbortSignal\n}\n\n/**\n * Options for `useQuery()`. Can be extended by plugins.\n *\n * @example\n * ```ts\n * // use-query-plugin.d.ts\n * export {} // needed\n * declare module '@pinia/colada' {\n *   interface UseQueryOptions {\n *     // Whether to refresh the data when the component is mounted.\n *     refreshOnMount?: boolean\n *   }\n * }\n * ```\n */\nexport interface UseQueryOptions<\n  TResult = unknown,\n  // eslint-disable-next-line unused-imports/no-unused-vars\n  TError = ErrorDefault,\n  TDataInitial extends TResult | undefined = TResult | undefined,\n> extends Pick<\n    UseQueryOptionsGlobal,\n    | 'gcTime'\n    | 'enabled'\n    | 'refetchOnMount'\n    | 'refetchOnReconnect'\n    | 'refetchOnWindowFocus'\n    | 'staleTime'\n  > {\n  /**\n   * The key used to identify the query. Array of primitives **without** reactive values or a reactive array or getter.\n   * It should be treaded as an array of dependencies of your queries, e.g. if you use the `route.params.id` property,\n   * it should also be part of the key:\n   *\n   * ```ts\n   * import { useRoute } from 'vue-router'\n   * import { useQuery } from '@pinia/colada'\n   *\n   * const route = useRoute()\n   * const { data } = useQuery({\n   *   // pass a getter function (or computed, ref, etc.) to ensure reactivity\n   *   key: () => ['user', route.params.id],\n   *   query: () => fetchUser(route.params.id),\n   * })\n   * ```\n   */\n  key: MaybeRefOrGetter<EntryKey>\n\n  /**\n   * The function that will be called to fetch the data. It **must** be async.\n   */\n  query: (context: UseQueryFnContext) => Promise<TResult>\n\n  /**\n   * The data which is initially set to the query while the query is loading for the first time.\n   * Note: unlike with `placeholderData`, setting the initial data changes the state of the query (it will be set to `success`).\n   */\n  initialData?: () => TDataInitial\n\n  /**\n   * A placeholder data that is initially shown while the query is loading for the first time. This will also show the\n   * `status` as `success` until the query finishes loading (no matter the outcome of the query). Note: unlike with\n   * `initialData`, the placeholder does not change the cache state.\n   */\n  placeholderData?:\n    | NoInfer<TDataInitial>\n    | NoInfer<TResult>\n    // NOTE: the generic here allows to make UseQueryOptions<T> assignable to UseQueryOptions<unknown>\n    // https://www.typescriptlang.org/play/?#code/JYOwLgpgTgZghgYwgAgPIAczAPYgM4A8AKsgLzICuIA1iNgO4gB8yA3gFDLICOAXMgAoAlGRYAFKNgC2wPBGJNOydAH5eSrgHpNyABZwAbqADmyMLpRwoxilIjhkAIygQ41PMmBgNyAD6CBdBcjbAo8ABE4MDh+ADlsAEkQGGgFP0oQABMIGFAITJFSFniklKgFIR9tZCJdWWQDaDwcEGR6bCh3Kp1-AWISCAAPSCyPIiZA4JwwyOj+IhJ-KmzckHzCliJKgF92dlBIWEQUAFFwKABPYjIM2gZmNiVsTBa8fgwsXEJx9JAKABt-uxduwYFQEJ9WggAPr2MCXBQCZ6Qt5oF5fNL+P6AoT8M7wq4-DhcFxgChQVqsZDI17IXa7BBfMDIDzkNb0ZAAZQgYAI+MuE0qeAAdHBMpkBDC4ZcBMSuDx+HA8BcQAhBBtkAAWABMABofOh+AIQBrWgBCNkA-7IFTIVoAKmQ2uQ-E1wKElSAA\n    | (<T extends TResult>(\n        previousData: T | undefined,\n      ) => NoInfer<TDataInitial> | NoInfer<TResult> | undefined)\n}\n\n/**\n * Default options for `useQuery()`. Modifying this object will affect all the queries that don't override these\n */\nexport const USE_QUERY_DEFAULTS = {\n  staleTime: 1000 * 5, // 5 seconds\n  gcTime: (1000 * 60 * 5) as NonNullable<UseQueryOptions['gcTime']>, // 5 minutes\n  // avoid type narrowing to `true`\n  refetchOnWindowFocus: true as NonNullable<UseQueryOptions['refetchOnWindowFocus']>,\n  refetchOnReconnect: true as NonNullable<UseQueryOptions['refetchOnReconnect']>,\n  refetchOnMount: true as NonNullable<UseQueryOptions['refetchOnMount']>,\n  enabled: true as MaybeRefOrGetter<boolean>,\n} satisfies UseQueryOptionsGlobal\n\nexport type UseQueryOptionsWithDefaults<\n  TResult = unknown,\n  TError = ErrorDefault,\n  TDataInitial extends TResult | undefined = undefined,\n> = UseQueryOptions<TResult, TError, TDataInitial> & typeof USE_QUERY_DEFAULTS\n\n/**\n * Global default options for `useQuery()`.\n * @internal\n */\nexport type UseQueryOptionsGlobalDefaults = UseQueryOptionsGlobal & typeof USE_QUERY_DEFAULTS\n\nexport const USE_QUERY_OPTIONS_KEY: InjectionKey<UseQueryOptionsGlobalDefaults>\n  = process.env.NODE_ENV !== 'production' ? Symbol('useQueryOptions') : Symbol()\n\n/**\n * Injects the global query options.\n * @internal\n */\nexport const useQueryOptions = (): UseQueryOptionsGlobalDefaults =>\n  inject(USE_QUERY_OPTIONS_KEY, USE_QUERY_DEFAULTS)\n","import type { ComputedRef, Ref, ShallowRef } from 'vue'\nimport {\n  computed,\n  getCurrentInstance,\n  getCurrentScope,\n  isRef,\n  onMounted,\n  onScopeDispose,\n  onServerPrefetch,\n  onUnmounted,\n  toValue,\n  watch,\n} from 'vue'\nimport { IS_CLIENT, useEventListener } from './utils'\nimport type { UseQueryEntry, UseQueryEntryExtensions } from './query-store'\nimport { isEntryUsingPlaceholderData, useQueryCache } from './query-store'\nimport { useQueryOptions } from './query-options'\nimport type { UseQueryOptions, UseQueryOptionsWithDefaults } from './query-options'\nimport type { ErrorDefault } from './types-extension'\nimport { getCurrentDefineQueryEffect } from './define-query'\nimport type { AsyncStatus, DataState, DataStateStatus, DataState_Success } from './data-state'\n\n// TODO: Rename TResult to TData for consistency\n\n/**\n * Return type of `useQuery()`.\n */\nexport interface UseQueryReturn<\n  TResult = unknown,\n  TError = ErrorDefault,\n  TDataInitial extends TResult | undefined = undefined,\n> extends UseQueryEntryExtensions<TResult, TError, TDataInitial> {\n  /**\n   * The state of the query. Contains its data, error, and status.\n   */\n  state: ComputedRef<DataState<TResult, TError, TDataInitial>>\n\n  /**\n   * Status of the query. Becomes `'loading'` while the query is being fetched, is `'idle'` otherwise.\n   */\n  asyncStatus: ComputedRef<AsyncStatus>\n\n  /**\n   * The last successful data resolved by the query. Alias for `state.value.data`.\n   *\n   * @see {@link state}\n   */\n  data: ShallowRef<TResult | TDataInitial>\n\n  /**\n   * The error rejected by the query. Alias for `state.value.error`.\n   *\n   * @see {@link state}\n   */\n  error: ShallowRef<TError | null>\n\n  /**\n   * The status of the query. Alias for `state.value.status`.\n   *\n   * @see {@link state}\n   * @see {@link DataStateStatus}\n   */\n  status: ShallowRef<DataStateStatus>\n\n  /**\n   * Returns whether the request is still pending its first call. Alias for `status.value === 'pending'`\n   */\n  isPending: ComputedRef<boolean>\n\n  /**\n   * Returns whether the `data` is the `placeholderData`.\n   */\n  isPlaceholderData: ComputedRef<boolean>\n\n  /**\n   * Returns whether the request is currently fetching data. Alias for `asyncStatus.value === 'loading'`\n   */\n  isLoading: ShallowRef<boolean>\n\n  /**\n   * Ensures the current data is fresh. If the data is stale, refetch, if not return as is.\n   * @param throwOnError - whether to throw an error if the refresh fails. Defaults to `false`\n   * @returns a promise that resolves when the refresh is done\n   */\n  refresh: (throwOnError?: boolean) => Promise<DataState<TResult, TError, TDataInitial>>\n\n  /**\n   * Ignores fresh data and triggers a new fetch\n   * @param throwOnError - whether to throw an error if the fetch fails. Defaults to `false`\n   * @returns a promise that resolves when the fetch is done\n   */\n  refetch: (throwOnError?: boolean) => Promise<DataState<TResult, TError, TDataInitial>>\n}\n\n/**\n * Ensures and return a shared query state based on the `key` option.\n *\n * @param _options - The options of the query\n */\nexport function useQuery<\n  TResult,\n  TError = ErrorDefault,\n  TDataInitial extends TResult | undefined = undefined,\n>(\n  _options: UseQueryOptions<TResult, TError, TDataInitial>,\n): UseQueryReturn<TResult, TError, TDataInitial> {\n  const queryCache = useQueryCache()\n  const optionDefaults = useQueryOptions()\n  // const effect = (getActivePinia() as any)._e as EffectScope\n  const hasCurrentInstance = getCurrentInstance()\n  const currentEffect = getCurrentDefineQueryEffect() || getCurrentScope()\n\n  const options = {\n    ...optionDefaults,\n    ..._options,\n  } satisfies UseQueryOptionsWithDefaults<TResult, TError, TDataInitial>\n  const { refetchOnMount, refetchOnReconnect, refetchOnWindowFocus, enabled } = options\n\n  // NOTE: here we used to check if the same key was previously called with a different query\n  // but it ended up creating too many false positives and was removed. We could add it back\n  // to at least warn against the cases shown in https://pinia-colada.esm.dev/guide/queries.html#Reusable-Queries\n\n  // This plain variable is not reactive and allows us to use the currentEntry\n  // without triggering watchers and creating entries. It is used during\n  // unmounting and mounting\n  let lastEntry: UseQueryEntry<TResult, TError, TDataInitial>\n  const entry = computed(() =>\n    // NOTE: there should be a `paused` property on the effect later on\n    // if the effect is paused, we don't want to compute the entry because its key\n    // might be referencing unedfined values\n    // https://github.com/posva/pinia-colada/issues/227\n    // @ts-expect-error: _isPaused is private\n    currentEffect?._isPaused\n      ? lastEntry!\n      : (lastEntry = queryCache.ensure<TResult, TError, TDataInitial>(options, lastEntry)),\n  )\n  // we compute the entry here and reuse this across\n  lastEntry = entry.value\n\n  // adapter that returns the entry state\n  const errorCatcher = () => entry.value.state.value\n  const refresh = (throwOnError?: boolean) =>\n    queryCache.refresh(entry.value, options).catch(\n      // true is not allowed but it works per spec as only callable onRejected are used\n      // https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-performpromisethen\n      // In other words `Promise.rejects('ok').catch(true)` still rejects\n      // anything other than `true` falls back to the `errorCatcher`\n      (throwOnError as false | undefined) || errorCatcher,\n    )\n  const refetch = (throwOnError?: boolean) =>\n    queryCache.fetch(entry.value, options).catch(\n      // same as above\n      (throwOnError as false | undefined) || errorCatcher,\n    )\n  const isPlaceholderData = computed(() => isEntryUsingPlaceholderData(entry.value))\n  const state = computed<DataState<TResult, TError, TDataInitial>>(() =>\n    isPlaceholderData.value\n      ? ({\n          status: 'success',\n          data: entry.value.placeholderData!,\n          error: null,\n        } satisfies DataState_Success<TResult>)\n      : entry.value.state.value,\n  )\n\n  // TODO: find a way to allow a custom implementation for the returned value\n  const extensions = {} as Record<string, any>\n  for (const key in lastEntry.ext) {\n    extensions[key] = computed<unknown>({\n      get: () =>\n        toValue<unknown>(entry.value.ext[key as keyof UseQueryEntryExtensions<TResult, TError>]),\n      set(value) {\n        const target = entry.value.ext[key as keyof UseQueryEntryExtensions<TResult, TError>]\n        if (isRef(target)) {\n          ;(target as Ref | ShallowRef).value = value\n        } else {\n          ;(entry.value.ext[key as keyof UseQueryEntryExtensions<TResult, TError>] as unknown)\n            = value\n        }\n      },\n    })\n  }\n\n  const queryReturn = {\n    ...(extensions as UseQueryEntryExtensions<TResult, TError, TDataInitial>),\n    state,\n\n    status: computed(() => state.value.status),\n    data: computed(() => state.value.data),\n    error: computed(() => entry.value.state.value.error),\n    asyncStatus: computed(() => entry.value.asyncStatus.value),\n\n    isPlaceholderData,\n    isPending: computed(() => state.value.status === 'pending'),\n    isLoading: computed(() => entry.value.asyncStatus.value === 'loading'),\n\n    refresh,\n    refetch,\n  } satisfies UseQueryReturn<TResult, TError, TDataInitial>\n\n  if (hasCurrentInstance) {\n    // only happens on server, app awaits this\n    onServerPrefetch(async () => {\n      if (toValue(enabled)) await refresh(true)\n    })\n  }\n\n  // should we be watching entry\n  // NOTE: this avoids fetching initially during SSR but it could be refactored to only use the watcher\n  let isActive = false\n  if (hasCurrentInstance) {\n    onMounted(() => {\n      isActive = true\n      queryCache.track(lastEntry, hasCurrentInstance)\n    })\n    onUnmounted(() => {\n      // remove instance from Set of refs\n      queryCache.untrack(lastEntry, hasCurrentInstance)\n    })\n  } else {\n    isActive = true\n    if (currentEffect) {\n      queryCache.track(lastEntry, currentEffect)\n      onScopeDispose(() => {\n        queryCache.untrack(lastEntry, currentEffect)\n      })\n    }\n  }\n\n  watch(\n    entry,\n    (entry, previousEntry) => {\n      if (!isActive) return\n      if (previousEntry) {\n        queryCache.untrack(previousEntry, hasCurrentInstance)\n        queryCache.untrack(previousEntry, currentEffect)\n      }\n      // track the current effect and component\n      queryCache.track(entry, hasCurrentInstance)\n      queryCache.track(entry, currentEffect)\n\n      // TODO: does this trigger after unmount?\n      if (toValue(enabled)) refresh()\n    },\n    {\n      immediate: true,\n    },\n  )\n\n  // avoid adding a watcher if enabled cannot change\n  if (typeof enabled !== 'boolean') {\n    watch(enabled, (newEnabled) => {\n      // no need to check for the previous value since the watcher will only trigger if the value changed\n      if (newEnabled) refresh()\n    })\n  }\n\n  // only happens on client\n  // we could also call fetch instead but forcing a refresh is more interesting\n  if (hasCurrentInstance) {\n    onMounted(() => {\n      if (\n        (refetchOnMount\n          // always fetch initially if no value is present\n          || queryReturn.status.value === 'pending')\n        && toValue(enabled)\n      ) {\n        if (refetchOnMount === 'always') {\n          refetch()\n        } else {\n          refresh()\n        }\n      }\n    })\n  }\n  // TODO: we could save the time it was fetched to avoid fetching again. This is useful to not refetch during SSR app but do refetch in SSG apps if the data is stale. Careful with timers and timezones\n\n  if (IS_CLIENT) {\n    if (refetchOnWindowFocus) {\n      useEventListener(document, 'visibilitychange', () => {\n        if (document.visibilityState === 'visible' && toValue(enabled)) {\n          if (toValue(refetchOnWindowFocus) === 'always') {\n            refetch()\n          } else {\n            refresh()\n          }\n        }\n      })\n    }\n\n    if (refetchOnReconnect) {\n      useEventListener(window, 'online', () => {\n        if (toValue(enabled)) {\n          if (toValue(refetchOnReconnect) === 'always') {\n            refetch()\n          } else {\n            refresh()\n          }\n        }\n      })\n    }\n  }\n\n  return queryReturn\n}\n","import { setupDevtoolsPlugin } from '@vue/devtools-api'\nimport { watch } from 'vue'\nimport type { App } from 'vue'\nimport type { Pinia } from 'pinia'\nimport { useQueryCache } from '../query-store'\nimport type { AsyncStatus, DataStateStatus } from '../data-state'\n\nconst QUERY_INSPECTOR_ID = 'pinia-colada-queries'\nconst ID_SEPARATOR = '\\0'\n\nfunction debounce(fn: () => void, delay: number) {\n  let timeout: ReturnType<typeof setTimeout>\n  return () => {\n    clearTimeout(timeout)\n    timeout = setTimeout(fn, delay)\n  }\n}\n\nexport function addDevtools(app: App, pinia: Pinia) {\n  const queryCache = useQueryCache(pinia)\n\n  setupDevtoolsPlugin(\n    {\n      id: 'dev.esm.pinia-colada',\n      app,\n      label: 'Pinia Colada',\n      packageName: 'pinia-colada',\n      homepage: 'https://pinia-colada.esm.dev/',\n      logo: 'https://pinia-colada.esm.dev/logo.svg',\n      componentStateTypes: [],\n    },\n    (api) => {\n      const updateQueryInspectorTree = debounce(() => {\n        api.sendInspectorTree(QUERY_INSPECTOR_ID)\n        api.sendInspectorState(QUERY_INSPECTOR_ID)\n      }, 100)\n\n      api.addInspector({\n        id: QUERY_INSPECTOR_ID,\n        label: 'Pinia Queries',\n        icon: 'storage',\n        noSelectionText: 'Select a query entry to inspect it',\n        treeFilterPlaceholder: 'Filter query entries',\n        stateFilterPlaceholder: 'Find within the query entry',\n        actions: [\n          {\n            icon: 'refresh',\n            action: updateQueryInspectorTree,\n            tooltip: 'Sync',\n          },\n        ],\n      })\n\n      let stopWatcher = () => {}\n\n      api.on.getInspectorState((payload) => {\n        if (payload.app !== app) return\n        if (payload.inspectorId === QUERY_INSPECTOR_ID) {\n          const entry = queryCache.getEntries({\n            key: payload.nodeId.split(ID_SEPARATOR),\n            exact: true,\n          })[0]\n          if (!entry) {\n            payload.state = {\n              Error: [\n                {\n                  key: 'error',\n                  value: new Error(`Query entry ${payload.nodeId} not found`),\n                  editable: false,\n                },\n              ],\n            }\n            return\n          }\n\n          stopWatcher()\n          stopWatcher = watch(\n            () => [entry.state.value, entry.asyncStatus.value],\n            () => {\n              api.sendInspectorState(QUERY_INSPECTOR_ID)\n            },\n          )\n\n          const state = entry.state.value\n\n          payload.state = {\n            state: [\n              { key: 'data', value: state.data, editable: true },\n              { key: 'error', value: state.error, editable: true },\n              { key: 'status', value: state.status, editable: true },\n              { key: 'asyncStatus', value: entry.asyncStatus.value, editable: true },\n            ],\n            entry: [\n              { key: 'key', value: entry.key, editable: false },\n              { key: 'options', value: entry.options, editable: true },\n            ],\n          }\n        }\n      })\n\n      api.on.editInspectorState((payload) => {\n        if (payload.app !== app) return\n        if (payload.inspectorId === QUERY_INSPECTOR_ID) {\n          const entry = queryCache.getEntries({\n            key: payload.nodeId.split(ID_SEPARATOR),\n            exact: true,\n          })[0]\n          if (!entry) return\n          const path = payload.path.slice()\n          payload.set(entry, path, payload.state.value)\n          api.sendInspectorState(QUERY_INSPECTOR_ID)\n        }\n      })\n\n      const QUERY_FILTER_RE = /\\b(active|inactive|stale|fresh|exact|loading|idle)\\b/gi\n\n      api.on.getInspectorTree((payload) => {\n        if (payload.app !== app) return\n\n        if (payload.inspectorId === QUERY_INSPECTOR_ID) {\n          const filters = payload.filter.match(QUERY_FILTER_RE)\n          // strip the filters from the query\n          const filter = (\n            filters ? payload.filter.replace(QUERY_FILTER_RE, '') : payload.filter\n          ).trim()\n\n          const active = filters?.includes('active')\n            ? true\n            : filters?.includes('inactive')\n              ? false\n              : undefined\n          const stale = filters?.includes('stale')\n            ? true\n            : filters?.includes('fresh')\n              ? false\n              : undefined\n          const asyncStatus = filters?.includes('loading')\n            ? 'loading'\n            : filters?.includes('idle')\n              ? 'idle'\n              : undefined\n\n          payload.rootNodes = queryCache\n            .getEntries({\n              active,\n              stale,\n              exact: filters?.includes('exact'),\n              predicate(entry) {\n                // filter out by asyncStatus\n                if (asyncStatus && entry.asyncStatus.value !== asyncStatus) return false\n                if (filter) {\n                  // TODO: fuzzy match between entry.key.join('/') and the filter\n                  return entry.key.some((key) => String(key).includes(filter))\n                }\n                return true\n              },\n            })\n            .map((entry) => {\n              const id = entry.key.join(ID_SEPARATOR)\n              const label = entry.key.join('/')\n              const asyncStatus = entry.asyncStatus.value\n              const state = entry.state.value\n\n              const tags: InspectorNodeTag[] = [\n                ASYNC_STATUS_TAG[asyncStatus],\n                STATUS_TAG[state.status],\n                // useful for testing colors\n                // ASYNC_STATUS_TAG.idle,\n                // ASYNC_STATUS_TAG.fetching,\n                // STATUS_TAG.pending,\n                // STATUS_TAG.success,\n                // STATUS_TAG.error,\n              ]\n              if (!entry.active) {\n                tags.push({\n                  label: 'inactive',\n                  textColor: 0,\n                  backgroundColor: 0xAAAAAA,\n                  tooltip: 'The query is not being used anywhere',\n                })\n              }\n              return {\n                id,\n                label,\n                name: label,\n                tags,\n              }\n            })\n        }\n      })\n\n      queryCache.$onAction(({ name, after, onError }) => {\n        if (\n          name === 'invalidate' // includes cancel\n          || name === 'fetch' // includes refresh\n          || name === 'setEntryState' // includes set data\n          || name === 'remove'\n          || name === 'untrack'\n          || name === 'track'\n          || name === 'ensure' // includes create\n        ) {\n          updateQueryInspectorTree()\n          after(updateQueryInspectorTree)\n          onError(updateQueryInspectorTree)\n        }\n      })\n\n      // update the devtools too\n      api.notifyComponentUpdate()\n      api.sendInspectorTree(QUERY_INSPECTOR_ID)\n      api.sendInspectorState(QUERY_INSPECTOR_ID)\n    },\n  )\n\n  // TODO: custom tab?\n\n  // addCustomTab({\n  //   name: 'pinia-colada',\n  //   title: 'Pinia Colada',\n  //   icon: 'https://pinia-colada.esm.dev/logo.svg',\n  //   view: {\n  //     type: 'sfc',\n  //     sfc: DevtoolsPanel,\n  //     // type: 'vnode',\n  //     // vnode: h('p', ['hello world']),\n  //     // vnode: createVNode(DevtoolsPanel),\n  //   },\n  //   category: 'modules',\n  // })\n\n  // window.addEventListener('message', (event) => {\n  //   const data = event.data\n  //   if (data != null && typeof data === 'object' && data.id === 'pinia-colada-devtools') {\n  //     console.log('message', event)\n  //   }\n  // })\n}\n\ninterface InspectorNodeTag {\n  label: string\n  textColor: number\n  backgroundColor: number\n  tooltip?: string\n}\n\n/**\n * Tags for the different states of a query\n */\nconst STATUS_TAG: Record<DataStateStatus, InspectorNodeTag> = {\n  pending: {\n    label: 'pending',\n    textColor: 0,\n    backgroundColor: 0xFF9D23,\n    tooltip: `The query hasn't resolved yet`,\n  },\n  success: {\n    label: 'success',\n    textColor: 0,\n    backgroundColor: 0x16C47F,\n    tooltip: 'The query resolved successfully',\n  },\n  error: {\n    label: 'error',\n    textColor: 0,\n    backgroundColor: 0xF93827,\n    tooltip: 'The query rejected with an error',\n  },\n}\n\n/**\n * Tags for the different states of a query\n */\nconst ASYNC_STATUS_TAG: Record<AsyncStatus, InspectorNodeTag> = {\n  idle: {\n    label: 'idle',\n    textColor: 0,\n    backgroundColor: 0xAAAAAA,\n    tooltip: 'The query is not fetching',\n  },\n  loading: {\n    label: 'fetching',\n    textColor: 0xFFFFFF,\n    backgroundColor: 0x578FCA,\n    tooltip: 'The query is currently fetching',\n  },\n}\n","import type { App, Plugin } from 'vue'\nimport type { Pinia } from 'pinia'\nimport type { UseQueryOptionsGlobal } from './query-options'\nimport { USE_QUERY_DEFAULTS, USE_QUERY_OPTIONS_KEY } from './query-options'\nimport { useQueryCache } from './query-store'\nimport type { PiniaColadaPlugin } from './plugins'\nimport { addDevtools } from './devtools/plugin'\nimport { USE_MUTATION_OPTIONS_KEY } from './mutation-options'\nimport type { UseMutationOptionsGlobal } from './mutation-options'\n\n/**\n * Options for the Pinia Colada plugin.\n */\nexport interface PiniaColadaOptions {\n  /**\n   * Pinia instance to use. This is only needed if installing before the Pinia plugin.\n   */\n  pinia?: Pinia\n\n  /**\n   * Pinia Colada plugins to install.\n   */\n  plugins?: PiniaColadaPlugin[]\n\n  /**\n   * Global options for queries. These will apply to all `useQuery()`, `defineQuery()`, etc.\n   */\n  queryOptions?: UseQueryOptionsGlobal\n\n  /**\n   * Global options for mutations. These will apply to all `useMutation()`, `defineMutation()`, etc.\n   */\n  mutationOptions?: UseMutationOptionsGlobal\n}\n\n/**\n * Plugin that installs the Query and Mutation plugins alongside some extra plugins.\n *\n * @see {@link QueryPlugin} to only install the Query plugin.\n *\n * @param app - Vue App\n * @param options - Pinia Colada options\n */\nexport const PiniaColada: Plugin<PiniaColadaOptions> = (\n  app: App,\n  options: PiniaColadaOptions = {},\n): void => {\n  const { pinia = app.config.globalProperties.$pinia, plugins, queryOptions, mutationOptions = {} } = options\n\n  app.provide(USE_QUERY_OPTIONS_KEY, {\n    ...USE_QUERY_DEFAULTS,\n    ...queryOptions,\n  })\n\n  app.provide(USE_MUTATION_OPTIONS_KEY, mutationOptions)\n\n  if (process.env.NODE_ENV !== 'production' && !pinia) {\n    throw new Error(\n      '[@pinia/colada] root pinia plugin not detected. Make sure you install pinia before installing the \"PiniaColada\" plugin or to manually pass the pinia instance.',\n    )\n  }\n\n  if (typeof document !== 'undefined' && process.env.NODE_ENV === 'development') {\n    addDevtools(app, pinia)\n  }\n\n  // install plugins\n  const queryCache = useQueryCache(pinia)\n  plugins?.forEach((plugin) =>\n    plugin({\n      scope: queryCache._s,\n      queryCache,\n      pinia,\n    }),\n  )\n}\n","import type { UseQueryEntry } from '../query-store'\nimport type { PiniaColadaPlugin } from '.'\n\n/**\n * Options for {@link PiniaColadaQueryHooksPlugin}.\n */\nexport interface PiniaColadaQueryHooksPluginOptions {\n  /**\n   * Global handler for when a query is successful.\n   *\n   * @param data - data returned by the query\n   */\n  onSuccess?: <TResult = unknown>(data: TResult, entry: UseQueryEntry<TResult, unknown>) => unknown\n\n  /**\n   * Global handler for when a query is settled (either successfully or with an error). Will await for the `onSuccess`\n   * or `onError` handlers to resolve if they return a promise.\n   *\n   * @param data - data returned by the query if any\n   * @param error - error thrown if any\n   */\n  onSettled?: <TResult = unknown, TError = unknown>(\n    data: TResult | undefined,\n    error: TError | null,\n    entry: UseQueryEntry<TResult, TError>,\n  ) => unknown\n\n  /**\n   * Global error handler for all queries.\n   *\n   * @param error - error thrown\n   */\n  onError?: <TError = unknown>(error: TError, entry: UseQueryEntry<unknown, TError>) => unknown\n}\n\n/**\n * Allows to add global hooks to all queries:\n * - `onSuccess`: called when a query is successful\n * - `onError`: called when a query throws an error\n * - `onSettled`: called when a query is settled (either successfully or with an error)\n * @param options - Pinia Colada Query Hooks plugin options\n *\n * @example\n * ```ts\n * import { PiniaColada, PiniaColadaQueryHooksPlugin } from '@pinia/colada'\n *\n * const app = createApp(App)\n * // app setup with other plugins\n * app.use(PiniaColada, {\n *   plugins: [\n *     PiniaColadaQueryHooksPlugin({\n *       onError(error, entry) {\n *         // ...\n *       },\n *     }),\n *   ],\n * })\n * ```\n */\nexport function PiniaColadaQueryHooksPlugin(\n  options: PiniaColadaQueryHooksPluginOptions,\n): PiniaColadaPlugin {\n  return ({ queryCache }) => {\n    queryCache.$onAction(({ name, after, onError, args }) => {\n      if (name === 'fetch') {\n        const [entry] = args\n        after(async ({ data }) => {\n          await options.onSuccess?.(data, entry)\n          options.onSettled?.(data, null, entry)\n        })\n\n        onError(async (error) => {\n          await options.onError?.(error, entry)\n          options.onSettled?.(undefined, error, entry)\n        })\n      }\n    })\n  }\n}\n","import { toValue } from 'vue'\nimport type { UseQueryFnContext, UseQueryOptions } from './query-options'\nimport { useQuery } from './use-query'\nimport type { ErrorDefault } from './types-extension'\n\n/**\n * Options for {@link useInfiniteQuery}.\n *\n * @experimental See https://github.com/posva/pinia-colada/issues/178\n */\nexport interface UseInfiniteQueryOptions<\n  TResult,\n  TError,\n  TDataInitial extends TResult | undefined = TResult | undefined,\n  TPages = unknown,\n> extends Omit<\n    UseQueryOptions<TResult, TError, TDataInitial>,\n    'query' | 'initialData' | 'placeholderData'\n  > {\n  /**\n   * The function that will be called to fetch the data. It **must** be async.\n   */\n  query: (pages: NoInfer<TPages>, context: UseQueryFnContext) => Promise<TResult>\n  initialPage: TPages | (() => TPages)\n  merge: (result: NoInfer<TPages>, current: NoInfer<TResult>) => NoInfer<TPages>\n}\n\n/**\n * Store and merge paginated data into a single cache entry. Allows to handle\n * infinite scrolling. This is an **experimental** API and is subject to\n * change.\n *\n * @param options - Options to configure the infinite query.\n *\n * @experimental See https://github.com/posva/pinia-colada/issues/178\n */\nexport function useInfiniteQuery<TResult, TError = ErrorDefault, TPage = unknown>(\n  options: UseInfiniteQueryOptions<TResult, TError, TResult | undefined, TPage>,\n) {\n  let pages: TPage = toValue(options.initialPage)\n\n  const { refetch, refresh, ...query } = useQuery<TPage, TError, TPage>({\n    ...options,\n    initialData: () => pages,\n    // since we hijack the query function and augment the data, we cannot refetch the data\n    // like usual\n    staleTime: Infinity,\n    async query(context) {\n      const data: TResult = await options.query(pages, context)\n      return (pages = options.merge(pages, data))\n    },\n  })\n\n  return {\n    ...query,\n    loadMore: () => refetch(),\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGA,mBAAyC;AACzC,IAAAA,cAAuD;;;ACOhD,IAAM,cAAN,MAAM,aAAyB;AAAA,EACpC;AAAA,EACA;AAAA,EAIA,eAAe,MAAgC;AAC7C,QAAI,KAAK,QAAQ;AACf,WAAK,IAAI,GAAG,IAAI;AAAA,IAClB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,IAAI,MAAsB,OAAW;AACnC,QAAI,KAAK,WAAW,GAAG;AACrB,WAAK,QAAQ;AAAA,IACf,OAAO;AAEL,YAAM,CAAC,KAAK,GAAG,SAAS,IAAI;AAC5B,YAAM,OAAmC,KAAK,UAAU,IAAI,GAAG;AAC/D,UAAI,MAAM;AACR,aAAK,IAAI,WAAW,KAAK;AAAA,MAC3B,OAAO;AACL,aAAK,aAAa,oBAAI,IAAI;AAC1B,aAAK,SAAS,IAAI,KAAK,IAAI,aAAY,WAAW,KAAK,CAAC;AAAA,MAC1D;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,KAAK,MAAkD;AACrD,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BACd,SACA;AACA,MAAI,YAAe,sBAAQ,QAAQ,WAAW;AAE9C,QAAM,EAAE,SAAS,SAAS,GAAG,MAAM,IAAI,SAA+B;AAAA,IACpE,GAAG;AAAA,IACH,aAAa,MAAM;AAAA;AAAA;AAAA,IAGnB,WAAW;AAAA,IACX,MAAM,MAAM,SAAS;AACnB,YAAM,OAAgB,MAAM,QAAQ,MAAM,OAAO,OAAO;AACxD,aAAQ,QAAQ,QAAQ,MAAM,OAAO,IAAI;AAAA,IAC3C;AAAA,EACF,CAAC;AAED,SAAO;AAAA,IACL,GAAG;AAAA,IACH,UAAU,MAAM,QAAQ;AAAA,EAC1B;AACF;","names":["import_vue","import_vue","import_vue","import_vue","import_pinia","import_vue","import_vue","track","import_vue","entry","import_vue","asyncStatus","import_vue"]}