@uniqbit/mate-core 1.0.0-canary.8 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
  2. package/package.json +5 -4
  3. package/src/cli/commands/artifact/delivery/link.ts +1 -1
  4. package/src/cli/commands/artifact/delivery/output.ts +10 -1
  5. package/src/cli/commands/artifact/delivery/resolve.ts +3 -2
  6. package/src/cli/commands/artifact/delivery/submit.ts +9 -4
  7. package/src/cli/commands/artifact/delivery/take.ts +12 -9
  8. package/src/cli/commands/artifact/finish/command.ts +16 -14
  9. package/src/cli/commands/artifact/finish/engine.ts +8 -8
  10. package/src/cli/commands/artifact/project/command.ts +2 -3
  11. package/src/cli/commands/companion/hub.ts +11 -6
  12. package/src/cli/commands/companion/link.ts +173 -46
  13. package/src/cli/commands/doctor.ts +17 -0
  14. package/src/cli/commands/report/contract.ts +0 -17
  15. package/src/cli/commands/studio/access.ts +4 -0
  16. package/src/cli/commands/studio/actions.ts +35 -2
  17. package/src/cli/commands/studio/mcp-manager.ts +162 -0
  18. package/src/cli/commands/studio/routes.ts +12 -0
  19. package/src/cli/commands/studio/selection.ts +44 -11
  20. package/src/cli/commands/studio/server.ts +246 -2
  21. package/src/cli/commands/studio/services.ts +26 -0
  22. package/src/cli/commands/studio/terminal-launch.ts +21 -4
  23. package/src/cli/commands/studio/terminal.ts +3 -14
  24. package/src/cli/commands/studio/work-requests.ts +9 -0
  25. package/src/cli/commands/studio/work.ts +473 -0
  26. package/src/cli/commands/vscode/release-vsix.json +2 -2
  27. package/src/cli/commands/working/cleanup.ts +1 -18
  28. package/src/cli/companion-link-wizard.tsx +158 -91
  29. package/src/cli/usage.ts +1 -1
  30. package/src/create-mate.ts +4 -1
  31. package/src/lib/agent-credential.ts +131 -0
  32. package/src/lib/credential-kinds.ts +7 -0
  33. package/src/lib/delivery/merge-git.ts +16 -0
  34. package/src/lib/delivery/record-delivery.ts +12 -6
  35. package/src/lib/delivery/record.ts +5 -0
  36. package/src/lib/delivery/refresh.ts +34 -6
  37. package/src/lib/delivery/staging/refs.ts +9 -4
  38. package/src/lib/delivery/staging/submit.ts +81 -22
  39. package/src/lib/mcp-manager/resolve.ts +88 -0
  40. package/src/lib/mcp-manager/store.ts +133 -0
  41. package/src/lib/mcp-manager/types.ts +72 -0
  42. package/src/lib/mcp-manager/validate.ts +242 -0
  43. package/src/lib/opencode-server.ts +2 -17
  44. package/src/lib/orchestrator/config-store.ts +30 -7
  45. package/src/lib/orchestrator/engine-floor.ts +16 -4
  46. package/src/lib/orchestrator/engine-guard.ts +7 -1
  47. package/src/lib/orchestrator/repo-local-store.ts +14 -0
  48. package/src/lib/orchestrator/repository-link.ts +80 -52
  49. package/src/lib/orchestrator/root-context.ts +17 -1
  50. package/src/lib/orchestrator/types.ts +4 -0
  51. package/src/lib/studio-chat/agent.ts +139 -0
  52. package/src/lib/studio-chat/companion-context.ts +136 -0
  53. package/src/lib/studio-chat/credential.ts +79 -0
  54. package/src/lib/studio-chat/harness-chat-agent.ts +334 -0
  55. package/src/lib/studio-chat/host-sandbox.ts +578 -0
  56. package/src/lib/studio-chat/prepare-bridges.ts +95 -0
  57. package/src/lib/studio-chat/session.ts +15 -0
  58. package/src/lib/studio-chat/turns.ts +112 -0
  59. package/src/lib/workset/claims.ts +85 -0
  60. package/src/lib/workset/execution.ts +71 -0
  61. package/src/lib/workset/git-transaction.ts +74 -0
  62. package/src/lib/workset/groups.ts +176 -0
  63. package/src/lib/workset/inventory.ts +196 -0
  64. package/src/lib/workset/projection.ts +237 -0
  65. package/src/lib/workset/record.ts +101 -36
  66. package/src/lib/workset/repositories.ts +24 -0
  67. package/src/lib/workset/sharing.ts +951 -0
  68. package/src/lib/workset/stages.ts +50 -14
  69. package/src/lib/workset/transactions.ts +158 -0
  70. package/src/runtime/companion-git-state.ts +1 -0
  71. package/src/runtime/companion-guidance.ts +2 -2
  72. package/src/runtime/forge-remote.ts +6 -0
  73. package/src/runtime/host-process.ts +28 -0
  74. package/src/runtime/secret-guard.ts +18 -1
  75. package/src/runtime/secret-patterns.ts +4 -3
  76. package/src/runtime/submitted-arrivals.ts +28 -2
  77. package/src/runtime/workflow/turn.ts +14 -12
  78. package/src/runtime/write-atomic.ts +2 -2
  79. package/src/studio.ts +61 -0
  80. package/src/templates/capabilities/openspec-cap/mate-full/schema.yaml +1 -1
  81. package/src/templates/capabilities/openspec-cap/mate-full/templates/proposal.md +1 -1
  82. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +3 -2
  83. package/src/templates/mate-skills/agents/mate-submit-change/SKILL.md +5 -3
  84. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +3 -2
  85. package/src/templates/mate-skills/claude/mate-submit-change/SKILL.md +5 -3
  86. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +12 -12
  87. package/src/tools/setup/capabilities/mcp-manager.ts +73 -0
  88. package/src/tools/setup/context-services.ts +35 -6
  89. package/src/tools/setup/dynamic-plugins/audiences.ts +3 -2
  90. package/src/tools/setup/dynamic-plugins/declarations.ts +0 -26
  91. package/src/tools/setup/engine.ts +55 -3
  92. package/src/tools/setup/plugin.ts +14 -0
  93. package/src/tools/setup/plugins/gitignore.ts +1 -0
  94. package/src/tools/setup/providers/claude-format.ts +40 -7
  95. package/src/tools/setup/providers/claude.ts +38 -3
  96. package/src/tools/setup/providers/opencode-format.ts +13 -3
  97. package/src/tools/setup/providers/opencode.ts +7 -18
  98. package/src/tools/setup/providers/relative-path-warnings.ts +26 -0
  99. package/studio-dist/THIRD-PARTY-NOTICES.md +297 -0
  100. package/studio-dist/client/THIRD-PARTY-LICENSES.md +4294 -0
  101. package/studio-dist/client/assets/DialogTitle-DOhjDa7H.js +1 -0
  102. package/studio-dist/client/assets/app-CG3vCgyA.css +2 -0
  103. package/studio-dist/client/assets/bundle-mjs-CdK3cBzO.js +1 -0
  104. package/studio-dist/client/assets/button-upSzkd-q.js +1 -0
  105. package/studio-dist/client/assets/chat-DbaMXb8H.js +157 -0
  106. package/studio-dist/client/assets/cn-BCnYnarL.js +1 -0
  107. package/studio-dist/client/assets/combobox-cP9OsRf2.js +1 -0
  108. package/studio-dist/client/assets/{companion-view-C_N237bf.js → companion-view-B54_Lj0S.js} +1 -1
  109. package/studio-dist/client/assets/fields-DNZ4a89M.js +1 -0
  110. package/studio-dist/client/assets/friction-DgEimeDB.js +1 -0
  111. package/studio-dist/client/assets/getting-started-BTfYCt5s.js +1 -0
  112. package/studio-dist/client/assets/{getting-started-djaQeWlu.js → getting-started-CAszmdDJ.js} +1 -1
  113. package/studio-dist/client/assets/getting-started._topic-CHJMf0pa.js +1 -0
  114. package/studio-dist/client/assets/getting-started.index-MR6HftWs.js +1 -0
  115. package/studio-dist/client/assets/{graph-canvas-ySGKMhmk.js → graph-canvas-BdNk2F9O.js} +1 -1
  116. package/studio-dist/client/assets/graph-hRijsC89.js +2 -0
  117. package/studio-dist/client/assets/guides-CwFnh08E.js +1 -0
  118. package/studio-dist/client/assets/highlighted-body-JLMTFACH-BcroQey-.js +1 -0
  119. package/studio-dist/client/assets/index-D5oGyvG8.js +41 -0
  120. package/studio-dist/client/assets/{markdown-view-jMiaBTSO.js → markdown-view-CJ8JsLb7.js} +1 -1
  121. package/studio-dist/client/assets/marked.esm-vFuq1cCd.js +65 -0
  122. package/studio-dist/client/assets/mcp-BE9M-bkO.js +4 -0
  123. package/studio-dist/client/assets/mermaid-WFAXDIZX-BjSsakrn.js +1 -0
  124. package/studio-dist/client/assets/panel-CDQ6Lryw.js +1 -0
  125. package/studio-dist/client/assets/plugins._service._view-DRVPUAWN.js +1 -0
  126. package/studio-dist/client/assets/{prepaint-CKsXyJOR.js → prepaint-sD_LlrDN.js} +1 -1
  127. package/studio-dist/client/assets/{queries-Dfp5deWj.js → queries-COL925ML.js} +1 -1
  128. package/studio-dist/client/assets/react-dom-K3Hp2Cdj.js +1 -0
  129. package/studio-dist/client/assets/{react-BYUSgtBs.js → react-h2xQ_NSp.js} +1 -1
  130. package/studio-dist/client/assets/reports-BClsojkb.js +1 -0
  131. package/studio-dist/client/assets/routes-CJQ2MAej.js +1 -0
  132. package/studio-dist/client/assets/search-DhWdEiKT.js +1 -0
  133. package/studio-dist/client/assets/select-B2FsN9FY.js +1 -0
  134. package/studio-dist/client/assets/skills-SoUHk77W.js +1 -0
  135. package/studio-dist/client/assets/{specs-BrCOjOch.js → specs-C_tZnAvF.js} +1 -1
  136. package/studio-dist/client/assets/specs-view-C6t3Y5IT.js +1 -0
  137. package/studio-dist/client/assets/steps-CF3-Zpmh.js +1 -0
  138. package/studio-dist/client/assets/{store-C3vJq8Wj.js → store-pY9gU4uS.js} +1 -1
  139. package/studio-dist/client/assets/studio-X7bnFrRe.js +36 -0
  140. package/studio-dist/client/assets/studio-queries-CKtAnIKP.js +2 -0
  141. package/studio-dist/client/assets/usage-BaaqUpTG.js +55 -0
  142. package/studio-dist/client/assets/useAnchoredPopupScrollLock-BspHR7Wt.js +1 -0
  143. package/studio-dist/client/assets/useBlocker-BQOfcu_f.js +1 -0
  144. package/studio-dist/client/assets/useMutation-DKeEoP5S.js +1 -0
  145. package/studio-dist/client/assets/useOpenInteractionType-CtaZCaFT.js +1 -0
  146. package/studio-dist/client/assets/usePopupHandleStore-Bc7Q4bnF.js +1 -0
  147. package/studio-dist/client/assets/vault-sAPFUnPN.js +1 -0
  148. package/studio-dist/client/assets/{warnings-CqOOGlPD.js → warnings-D7YY1HSG.js} +1 -1
  149. package/studio-dist/client/assets/work-BZek_LGB.js +5 -0
  150. package/studio-dist/client/assets/workflow-N5boHXFz.js +1 -0
  151. package/studio-dist/server/THIRD-PARTY-LICENSES.md +4371 -0
  152. package/studio-dist/server/assets/DialogTitle-DnKSl2V0.js +421 -0
  153. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-gVfW5vIV.js → __23tanstack-start-server-fn-resolver-Bli9bpSB.js} +38 -18
  154. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +91 -59
  155. package/studio-dist/server/assets/{actions-D8erOphH.js → actions-CHEFA1i9.js} +33 -1
  156. package/studio-dist/server/assets/{cn-FXJAM0KO.js → bundle-mjs-Ot6dQ8Pq.js} +1 -2056
  157. package/studio-dist/server/assets/{button-D6bvrFmm.js → button-BqA1urbl.js} +14 -7
  158. package/studio-dist/server/assets/chat-zl332Tvu.js +49486 -0
  159. package/studio-dist/server/assets/cn-B0fl6NWK.js +2057 -0
  160. package/studio-dist/server/assets/{combobox-D2MbYV1O.js → combobox-iTjvPCtS.js} +7 -6
  161. package/studio-dist/server/assets/{companion-view-Mf1ANbMb.js → companion-view-DIQ6AFIY.js} +2 -2
  162. package/studio-dist/server/assets/{companions-Dr6IpNAb.js → companions-aVwjRL8j.js} +1 -1
  163. package/studio-dist/server/assets/{fields-B4mAPETz.js → fields-BMap2_Ju.js} +10 -3
  164. package/studio-dist/server/assets/{friction-CWOTjpCV.js → friction-BER50hoD.js} +2 -2
  165. package/studio-dist/server/assets/{friction-9a5S1m7U.js → friction-BPs9KWdq.js} +8 -8
  166. package/studio-dist/server/assets/{getting-started-RU6tYU2Q.js → getting-started-DGfRVmZ_.js} +2 -2
  167. package/studio-dist/server/assets/{getting-started._topic-C02HGrC6.js → getting-started._topic-BgrBA4Vj.js} +2 -2
  168. package/studio-dist/server/assets/{getting-started.index-EzLRosbb.js → getting-started.index-BaFfQ9Mn.js} +2 -2
  169. package/studio-dist/server/assets/{graph-CZ2H9Fzr.js → graph-Cgzlrv3P.js} +8 -8
  170. package/studio-dist/server/assets/{graph-B11ITte0.js → graph-DODpuOy_.js} +1 -1
  171. package/studio-dist/server/assets/{graph-canvas-rP5TT14Z.js → graph-canvas-DW_zU1nA.js} +2 -2
  172. package/studio-dist/server/assets/{guides-BGftp4wf.js → guides-CA_EMG7E.js} +1 -1
  173. package/studio-dist/server/assets/{guides-B8HdeK_C.js → guides-D0SpoD32.js} +1 -1
  174. package/studio-dist/server/assets/{guides.server-DqFQAStf.js → guides.server-DJjQuy03.js} +1 -1
  175. package/studio-dist/server/assets/highlighted-body-JLMTFACH-BeHllu-r.js +41 -0
  176. package/studio-dist/server/assets/{markdown-view-CArpV-CS.js → markdown-view-CvVBGMZV.js} +1 -1
  177. package/studio-dist/server/assets/mcp-BU0fLYyJ.js +1103 -0
  178. package/studio-dist/server/assets/mcp-manager-D9YctTQe.js +50 -0
  179. package/studio-dist/server/assets/mermaid-WFAXDIZX-B1yDN6vG.js +1 -0
  180. package/studio-dist/server/assets/{panel-DR0iq46J.js → panel-D1K6Bsux.js} +4 -32
  181. package/studio-dist/server/assets/{plugins._service._view-n7u2k5dF.js → plugins._service._view-DdO1nELF.js} +4 -4
  182. package/studio-dist/server/assets/{prepaint-B28ClcPN.js → prepaint-BB3dwSmz.js} +1 -1
  183. package/studio-dist/server/assets/{queries-D-yVP9i0.js → queries-BwiDxQy5.js} +1 -1
  184. package/studio-dist/server/assets/{react-CiBZPDs8.js → react-B2cLiz-i.js} +1 -1
  185. package/studio-dist/server/assets/{reports-C2SmTgqh.js → reports-9Pr7Bz6o.js} +7 -7
  186. package/studio-dist/server/assets/{reports-B9k98oE6.js → reports-Cc9M3phM.js} +1 -1
  187. package/studio-dist/server/assets/{router-CPt0TAk_.js → router-DcWe0J7Y.js} +827 -548
  188. package/studio-dist/server/assets/{routes-CwH8LEy2.js → routes-BEXxl0py.js} +8 -8
  189. package/studio-dist/server/assets/{search-b-yQesv3.js → search-bltT7gwy.js} +39 -7
  190. package/studio-dist/server/assets/{select-C3i6TTX-.js → select-CZvHgGCi.js} +7 -6
  191. package/studio-dist/server/assets/{shell-CagqZZMZ.js → shell-BQ0vMKXN.js} +13 -4
  192. package/studio-dist/server/assets/{skills-DGg0mWDM.js → skills-Be_52h0i.js} +1 -1
  193. package/studio-dist/server/assets/{skills-C21Mg_8-.js → skills-BpGGUl6L.js} +8 -8
  194. package/studio-dist/server/assets/{specs-DetoMiaB.js → specs-CCGgXE-V.js} +5 -5
  195. package/studio-dist/server/assets/{specs-view-CmbfLDwN.js → specs-view-DtL5JxYM.js} +12 -11
  196. package/studio-dist/server/assets/{steps-D1tYAyWZ.js → steps-BWFSO6dM.js} +1 -1
  197. package/studio-dist/server/assets/{store-aC-I6f6o.js → store-X7yLPp7v.js} +1 -1
  198. package/studio-dist/server/assets/{studio-queries-Dqf-3nzj.js → studio-queries-ur1ygXi3.js} +117 -13
  199. package/studio-dist/server/assets/{studio-qRvQjRpz.js → studio-qzH-UETC.js} +1555 -179
  200. package/studio-dist/server/assets/{usage-Cwle9-xY.js → usage-C1o0DLzS.js} +1 -1
  201. package/studio-dist/server/assets/{usage-CS4CBK9D.js → usage-DWbSPrPD.js} +10 -9
  202. package/studio-dist/server/assets/{useAnchoredPopupScrollLock-BjMNgXv9.js → useAnchoredPopupScrollLock-DLDmv6kM.js} +4 -135
  203. package/studio-dist/server/assets/useBlocker-CQtANHK8.js +111 -0
  204. package/studio-dist/server/assets/{useMutation-DpBIuWXt.js → useMutation-NjlA8oFY.js} +2 -2
  205. package/studio-dist/server/assets/useOpenInteractionType-CZYscfOb.js +136 -0
  206. package/studio-dist/server/assets/usePopupHandleStore-DEEXJYv0.js +26 -0
  207. package/studio-dist/server/assets/{vault-CEBBRLMb.js → vault-B_kfi1h-.js} +1 -1
  208. package/studio-dist/server/assets/{vault-DVQidlId.js → vault-dL79JlKH.js} +8 -115
  209. package/studio-dist/server/assets/{views-UgO0Qz_g.js → views-BSGH56lb.js} +3 -3
  210. package/studio-dist/server/assets/{warnings-C7hgXpdk.js → warnings-DtUVPV-k.js} +2 -2
  211. package/studio-dist/server/assets/work-D789VXGH.js +110 -0
  212. package/studio-dist/server/assets/work-DsCEfhmK.js +3817 -0
  213. package/studio-dist/server/assets/work-requests-BLhOmQFO.js +11 -0
  214. package/studio-dist/server/assets/{workflow-6dZZ1ofw.js → workflow-BOZ2sRYg.js} +9 -9
  215. package/studio-dist/server/server.js +3 -3
  216. package/wrappers/bin/openspec +87 -2
  217. package/studio-dist/client/assets/app-ggXJ_QVh.css +0 -2
  218. package/studio-dist/client/assets/button-amJ3g5oD.js +0 -1
  219. package/studio-dist/client/assets/cn-BQPKiwI4.js +0 -1
  220. package/studio-dist/client/assets/combobox-CJ7aGFid.js +0 -1
  221. package/studio-dist/client/assets/fields-BAiGkJ5N.js +0 -1
  222. package/studio-dist/client/assets/friction-DqOU59v7.js +0 -1
  223. package/studio-dist/client/assets/getting-started-yp42dj5S.js +0 -1
  224. package/studio-dist/client/assets/getting-started._topic-C9zVXz_m.js +0 -1
  225. package/studio-dist/client/assets/getting-started.index-DWbDKICP.js +0 -1
  226. package/studio-dist/client/assets/graph-BYaD_5Bq.js +0 -2
  227. package/studio-dist/client/assets/guides-D6T6W_jV.js +0 -1
  228. package/studio-dist/client/assets/index-Qx7reRPD.js +0 -40
  229. package/studio-dist/client/assets/panel-C4bf_h2W.js +0 -1
  230. package/studio-dist/client/assets/plugins._service._view-y6f2FDAB.js +0 -1
  231. package/studio-dist/client/assets/reports-JFSwSueq.js +0 -1
  232. package/studio-dist/client/assets/routes-BdOWSgzK.js +0 -1
  233. package/studio-dist/client/assets/search-CXosfvYh.js +0 -1
  234. package/studio-dist/client/assets/select-BHYYWPhK.js +0 -1
  235. package/studio-dist/client/assets/skills-Bo9FLsBd.js +0 -1
  236. package/studio-dist/client/assets/specs-view-CdE2rlli.js +0 -1
  237. package/studio-dist/client/assets/steps-CKUno4lh.js +0 -1
  238. package/studio-dist/client/assets/studio-0ueISxwP.js +0 -100
  239. package/studio-dist/client/assets/studio-queries-BflKt9va.js +0 -2
  240. package/studio-dist/client/assets/usage-BLsLy0nN.js +0 -55
  241. package/studio-dist/client/assets/useAnchoredPopupScrollLock-DC7f8GOp.js +0 -1
  242. package/studio-dist/client/assets/useMutation-uJUrejsi.js +0 -1
  243. package/studio-dist/client/assets/vault-BB1B_OhR.js +0 -1
  244. package/studio-dist/client/assets/workflow-BFzmI-06.js +0 -1
@@ -0,0 +1,2057 @@
1
+ import { n as require_react, o as __toESM, t as require_jsx_runtime } from "./jsx-runtime-Bt0s0YKS.js";
2
+ import { $ as resolveQueryValue, B as fetchSignal, G as isValidTimeout, I as addConsumeAwareSignal, L as addToEnd, R as addToStart, W as isServer$1, Y as noop, Z as replaceData, at as systemSetTimeoutZero, et as shallowEqualObjects, it as timeUntilStale, nt as skipToken, ot as timeoutManager, rt as sleep, tt as shouldThrowError, z as ensureQueryFn } from "./studio-queries-ur1ygXi3.js";
3
+ import { n as clsx, t as twMerge } from "./bundle-mjs-Ot6dQ8Pq.js";
4
+ // ../../node_modules/.bun/@tanstack+react-query@5.105.3+cef22a3c7e8b4cef/node_modules/@tanstack/react-query/build/modern/QueryClientProvider.js
5
+ var import_react = /* @__PURE__ */ __toESM(require_react(), 1);
6
+ var import_jsx_runtime = require_jsx_runtime();
7
+ /**
8
+ * The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it.
9
+ */
10
+ var QueryClientContext = import_react.createContext(void 0);
11
+ /**
12
+ * The `useQueryClient` hook returns the current `QueryClient` instance.
13
+ * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
14
+ * be used.
15
+ * @returns The current `QueryClient` instance.
16
+ * @throws {Error} If no `queryClient` argument is passed and no `QueryClientProvider` is found in the
17
+ * component tree.
18
+ */
19
+ var useQueryClient = (queryClient) => {
20
+ const client = import_react.useContext(QueryClientContext);
21
+ if (queryClient) return queryClient;
22
+ if (!client) throw new Error("No QueryClient set, use QueryClientProvider to set one");
23
+ return client;
24
+ };
25
+ /**
26
+ * Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also
27
+ * calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to
28
+ * focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or
29
+ * comes back online).
30
+ * @param props - The `client` to provide, and the `children` that get access to it.
31
+ * @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`.
32
+ * @example
33
+ * ```tsx
34
+ * import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
35
+ *
36
+ * const queryClient = new QueryClient()
37
+ *
38
+ * function App() {
39
+ * return <QueryClientProvider client={queryClient}>...</QueryClientProvider>
40
+ * }
41
+ * ```
42
+ */
43
+ var QueryClientProvider = ({ client, children }) => {
44
+ import_react.useEffect(() => {
45
+ client.mount();
46
+ return () => {
47
+ client.unmount();
48
+ };
49
+ }, [client]);
50
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(QueryClientContext.Provider, {
51
+ value: client,
52
+ children
53
+ });
54
+ };
55
+ // ../../node_modules/.bun/@tanstack+query-core@5.105.3/node_modules/@tanstack/query-core/build/modern/environmentManager.js
56
+ var isServerFn = () => isServer$1;
57
+ /**
58
+ * Returns whether the current runtime should be treated as a server environment.
59
+ * @returns `true` if the runtime is treated as a server.
60
+ */
61
+ var isServer = () => isServerFn();
62
+ // ../../node_modules/.bun/@tanstack+query-core@5.105.3/node_modules/@tanstack/query-core/build/modern/subscribable.js
63
+ /**
64
+ * The base class behind everything in Query that you can subscribe to: `QueryCache`, `MutationCache`,
65
+ * the observers, and the `FocusManager`/`OnlineManager` behind `focusManager` and `onlineManager`.
66
+ * Subclasses decide what a listener receives and when it is called.
67
+ */
68
+ var Subscribable = class {
69
+ constructor() {
70
+ this.listeners = /* @__PURE__ */ new Set();
71
+ this.subscribe = this.subscribe.bind(this);
72
+ }
73
+ /**
74
+ * Registers a listener to be called on every update this object notifies about. Returns a function
75
+ * that removes the listener again — call it to stop listening. The base class never drops a listener
76
+ * on its own, though some subclasses clear all of theirs in `destroy()`.
77
+ * @param listener - Called on each update, with whatever the subclass passes to its subscribers.
78
+ * @returns A function that removes the listener.
79
+ * @example
80
+ * ```ts
81
+ * const unsubscribe = subscribable.subscribe(() => {
82
+ * // react to the update
83
+ * })
84
+ *
85
+ * unsubscribe()
86
+ * ```
87
+ */
88
+ subscribe(listener) {
89
+ this.listeners.add(listener);
90
+ this.onSubscribe();
91
+ return () => {
92
+ this.listeners.delete(listener);
93
+ this.onUnsubscribe();
94
+ };
95
+ }
96
+ /**
97
+ * Returns `true` while at least one listener is registered, `false` once they have all unsubscribed.
98
+ * @returns `true` if at least one listener is registered.
99
+ */
100
+ hasListeners() {
101
+ return this.listeners.size > 0;
102
+ }
103
+ /**
104
+ * Called after a listener is added. Does nothing here; subclasses override it, e.g. to start
105
+ * tracking what they observe once the first listener subscribes.
106
+ */
107
+ onSubscribe() {}
108
+ /**
109
+ * Called after a listener is removed. Does nothing here; subclasses override it, e.g. to clean up
110
+ * once the last listener unsubscribes.
111
+ */
112
+ onUnsubscribe() {}
113
+ };
114
+ // ../../node_modules/.bun/@tanstack+query-core@5.105.3/node_modules/@tanstack/query-core/build/modern/focusManager.js
115
+ /**
116
+ * The `FocusManager` manages the focus state within TanStack Query.
117
+ *
118
+ * It can be used to change the default event listeners or to manually change the focus state.
119
+ */
120
+ var FocusManager = class extends Subscribable {
121
+ #focused;
122
+ #cleanup;
123
+ #setup;
124
+ constructor() {
125
+ super();
126
+ this.#setup = (onFocus) => {
127
+ if (typeof window !== "undefined" && window.addEventListener) {
128
+ const listener = () => onFocus();
129
+ window.addEventListener("visibilitychange", listener, false);
130
+ return () => {
131
+ window.removeEventListener("visibilitychange", listener);
132
+ };
133
+ }
134
+ };
135
+ }
136
+ onSubscribe() {
137
+ if (!this.#cleanup) this.setEventListener(this.#setup);
138
+ }
139
+ onUnsubscribe() {
140
+ if (!this.hasListeners()) {
141
+ this.#cleanup?.();
142
+ this.#cleanup = void 0;
143
+ }
144
+ }
145
+ /**
146
+ * `setEventListener` can be used to set a custom event listener that will
147
+ * be used to determine the focus state. The provided `setup` function
148
+ * receives a `setFocused` callback: call it with a `boolean` to manually
149
+ * set the focus state, or with no arguments to re-evaluate the current
150
+ * focus state and notify subscribers.
151
+ * @param setup - Receives the `setFocused` callback, registers the event listener, and may return
152
+ * a cleanup function that is called when the listener is replaced or no longer needed.
153
+ * @example
154
+ * ```ts
155
+ * import { focusManager } from '@tanstack/query-core'
156
+ *
157
+ * focusManager.setEventListener((handleFocus) => {
158
+ * const listener = () => handleFocus()
159
+ * // Listen to visibilitychange
160
+ * if (typeof window !== 'undefined' && window.addEventListener) {
161
+ * window.addEventListener('visibilitychange', listener, false)
162
+ * }
163
+ *
164
+ * return () => {
165
+ * // Be sure to unsubscribe if a new handler is set
166
+ * window.removeEventListener('visibilitychange', listener)
167
+ * }
168
+ * })
169
+ * ```
170
+ */
171
+ setEventListener(setup) {
172
+ this.#setup = setup;
173
+ this.#cleanup?.();
174
+ this.#cleanup = setup((focused) => {
175
+ if (typeof focused === "boolean") this.setFocused(focused);
176
+ else this.onFocus();
177
+ });
178
+ }
179
+ /**
180
+ * `setFocused` can be used to manually set the focus state. Set `undefined`
181
+ * to fall back to the default focus check.
182
+ * @param focused - The focus state, or `undefined` to use the default focus check.
183
+ * @example
184
+ * ```ts
185
+ * import { focusManager } from '@tanstack/query-core'
186
+ *
187
+ * // Set focused
188
+ * focusManager.setFocused(true)
189
+ *
190
+ * // Set unfocused
191
+ * focusManager.setFocused(false)
192
+ *
193
+ * // Fallback to the default focus check
194
+ * focusManager.setFocused(undefined)
195
+ * ```
196
+ */
197
+ setFocused(focused) {
198
+ if (this.#focused !== focused) {
199
+ this.#focused = focused;
200
+ this.onFocus();
201
+ }
202
+ }
203
+ /**
204
+ * `onFocus` notifies all subscribed listeners with the current focus state.
205
+ */
206
+ onFocus() {
207
+ const isFocused = this.isFocused();
208
+ this.listeners.forEach((listener) => {
209
+ listener(isFocused);
210
+ });
211
+ }
212
+ /**
213
+ * `isFocused` can be used to get the current focus state.
214
+ * @returns The focus state set with `setFocused`, or otherwise whether the document is visible.
215
+ */
216
+ isFocused() {
217
+ if (typeof this.#focused === "boolean") return this.#focused;
218
+ return globalThis.document?.visibilityState !== "hidden";
219
+ }
220
+ };
221
+ /**
222
+ * Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query.
223
+ */
224
+ var focusManager = new FocusManager();
225
+ // ../../node_modules/.bun/@tanstack+query-core@5.105.3/node_modules/@tanstack/query-core/build/modern/notifyManager.js
226
+ /**
227
+ * Default scheduling function used by the notify manager.
228
+ * Schedules the callback with the system's `setTimeout(callback, 0)`.
229
+ */
230
+ var defaultScheduler = systemSetTimeoutZero;
231
+ /**
232
+ * Creates a notify manager, which schedules and batches notifications to subscribers. Query uses a
233
+ * single instance of it, exported as {@link notifyManager}.
234
+ * @returns A new notify manager.
235
+ */
236
+ function createNotifyManager() {
237
+ let queue = [];
238
+ let transactions = 0;
239
+ let notifyFn = (callback) => {
240
+ callback();
241
+ };
242
+ let batchNotifyFn = (callback) => {
243
+ callback();
244
+ };
245
+ let scheduleFn = defaultScheduler;
246
+ const schedule = (callback) => {
247
+ if (transactions) queue.push(callback);
248
+ else scheduleFn(() => {
249
+ notifyFn(callback);
250
+ });
251
+ };
252
+ const flush = () => {
253
+ const originalQueue = queue;
254
+ queue = [];
255
+ if (originalQueue.length) scheduleFn(() => {
256
+ batchNotifyFn(() => {
257
+ originalQueue.forEach((callback) => {
258
+ notifyFn(callback);
259
+ });
260
+ });
261
+ });
262
+ };
263
+ return {
264
+ /**
265
+ * Batches all updates scheduled inside the passed callback.
266
+ * This is mainly used internally to optimize query client updating.
267
+ * Batches can be nested; the queue is only flushed once the outermost `batch` call finishes.
268
+ * The return value of `callback` is passed through.
269
+ * @param callback - The function to run in the batch.
270
+ * @returns The return value of `callback`.
271
+ */
272
+ batch: (callback) => {
273
+ let result;
274
+ transactions++;
275
+ try {
276
+ result = callback();
277
+ } finally {
278
+ transactions--;
279
+ if (!transactions) flush();
280
+ }
281
+ return result;
282
+ },
283
+ /**
284
+ * All calls to the wrapped function will be batched.
285
+ * @param callback - The function to wrap.
286
+ * @returns A function that schedules a call to `callback` with the given arguments.
287
+ */
288
+ batchCalls: (callback) => {
289
+ return (...args) => {
290
+ schedule(() => {
291
+ callback(...args);
292
+ });
293
+ };
294
+ },
295
+ /**
296
+ * Schedules a function to be run on the next batch.
297
+ * By default, the batch is run with a `setTimeout`, but this can be configured via `setScheduler`.
298
+ */
299
+ schedule,
300
+ /**
301
+ * Use this method to set a custom notify function.
302
+ * This can be used to for example wrap notifications with `React.act` while running tests.
303
+ * @param fn - Receives each notification callback and must call it.
304
+ */
305
+ setNotifyFunction: (fn) => {
306
+ notifyFn = fn;
307
+ },
308
+ /**
309
+ * Use this method to set a custom function to batch notifications together into a single tick.
310
+ * Framework adapters use this to plug in their own batching primitive, so that a single query
311
+ * update only triggers one re-render instead of one per subscriber.
312
+ * @param fn - Receives a function that runs a batch of notifications and must call it.
313
+ * @example
314
+ * ```ts
315
+ * import { notifyManager } from '@tanstack/query-core'
316
+ * import { batch } from 'solid-js'
317
+ *
318
+ * notifyManager.setBatchNotifyFunction(batch)
319
+ * ```
320
+ */
321
+ setBatchNotifyFunction: (fn) => {
322
+ batchNotifyFn = fn;
323
+ },
324
+ /**
325
+ * Configures a custom callback that schedules when the next batch runs.
326
+ * The default behavior is `setTimeout(callback, 0)`.
327
+ * @param fn - Receives a callback that runs the next batch, and schedules it.
328
+ * @example
329
+ * ```ts
330
+ * import { notifyManager } from '@tanstack/query-core'
331
+ *
332
+ * // Schedule batches in the next microtask
333
+ * notifyManager.setScheduler(queueMicrotask)
334
+ *
335
+ * // Schedule batches before the next frame is rendered
336
+ * notifyManager.setScheduler(requestAnimationFrame)
337
+ *
338
+ * // Schedule batches some time in the future
339
+ * notifyManager.setScheduler((cb) => setTimeout(cb, 10))
340
+ * ```
341
+ */
342
+ setScheduler: (fn) => {
343
+ scheduleFn = fn;
344
+ }
345
+ };
346
+ }
347
+ /**
348
+ * Handles scheduling and batching callbacks in TanStack Query.
349
+ */
350
+ var notifyManager = createNotifyManager();
351
+ // ../../node_modules/.bun/@tanstack+query-core@5.105.3/node_modules/@tanstack/query-core/build/modern/onlineManager.js
352
+ /**
353
+ * The `OnlineManager` manages the online state within TanStack Query. It can
354
+ * be used to change the default event listeners or to manually change the
355
+ * online state.
356
+ *
357
+ * By default, the `onlineManager` assumes an active network connection, and
358
+ * listens to the `online` and `offline` events on the `window` object to
359
+ * detect changes.
360
+ */
361
+ var OnlineManager = class extends Subscribable {
362
+ #online = true;
363
+ #cleanup;
364
+ #setup;
365
+ constructor() {
366
+ super();
367
+ this.#setup = (onOnline) => {
368
+ if (typeof window !== "undefined" && window.addEventListener) {
369
+ const onlineListener = () => onOnline(true);
370
+ const offlineListener = () => onOnline(false);
371
+ window.addEventListener("online", onlineListener, false);
372
+ window.addEventListener("offline", offlineListener, false);
373
+ return () => {
374
+ window.removeEventListener("online", onlineListener);
375
+ window.removeEventListener("offline", offlineListener);
376
+ };
377
+ }
378
+ };
379
+ }
380
+ onSubscribe() {
381
+ if (!this.#cleanup) this.setEventListener(this.#setup);
382
+ }
383
+ onUnsubscribe() {
384
+ if (!this.hasListeners()) {
385
+ this.#cleanup?.();
386
+ this.#cleanup = void 0;
387
+ }
388
+ }
389
+ /**
390
+ * `setEventListener` can be used to set a custom event listener that will
391
+ * be used to determine the online state. The provided `setup` function
392
+ * receives a `setOnline` callback that should be called with a `boolean`
393
+ * whenever the online state changes.
394
+ * @param setup - Receives the `setOnline` callback, registers the event listener, and may return
395
+ * a cleanup function that is called when the listener is replaced or no longer needed.
396
+ * @example
397
+ * ```ts
398
+ * import NetInfo from '@react-native-community/netinfo'
399
+ * import { onlineManager } from '@tanstack/query-core'
400
+ *
401
+ * onlineManager.setEventListener((setOnline) => {
402
+ * return NetInfo.addEventListener((state) => {
403
+ * setOnline(!!state.isConnected)
404
+ * })
405
+ * })
406
+ * ```
407
+ */
408
+ setEventListener(setup) {
409
+ this.#setup = setup;
410
+ this.#cleanup?.();
411
+ this.#cleanup = setup(this.setOnline.bind(this));
412
+ }
413
+ /**
414
+ * `setOnline` can be used to manually set the online state.
415
+ * @param online - The online state.
416
+ * @example
417
+ * ```ts
418
+ * import { onlineManager } from '@tanstack/query-core'
419
+ *
420
+ * // Set to online
421
+ * onlineManager.setOnline(true)
422
+ *
423
+ * // Set to offline
424
+ * onlineManager.setOnline(false)
425
+ * ```
426
+ */
427
+ setOnline(online) {
428
+ if (this.#online !== online) {
429
+ this.#online = online;
430
+ this.listeners.forEach((listener) => {
431
+ listener(online);
432
+ });
433
+ }
434
+ }
435
+ /**
436
+ * `isOnline` can be used to get the current online state.
437
+ * @returns `true` if online.
438
+ */
439
+ isOnline() {
440
+ return this.#online;
441
+ }
442
+ };
443
+ /**
444
+ * Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.
445
+ */
446
+ var onlineManager = new OnlineManager();
447
+ // ../../node_modules/.bun/@tanstack+query-core@5.105.3/node_modules/@tanstack/query-core/build/modern/retryer.js
448
+ /**
449
+ * The default `retryDelay`: doubles with every failure, starting at 1 second, up to 30 seconds.
450
+ * @param failureCount - The number of failures so far.
451
+ * @returns The delay before the next retry, in milliseconds.
452
+ */
453
+ function defaultRetryDelay(failureCount) {
454
+ return Math.min(1e3 * 2 ** failureCount, 3e4);
455
+ }
456
+ /**
457
+ * Checks whether a fetch can run for the given network mode.
458
+ * @param networkMode - The `networkMode` option. Defaults to `'online'`.
459
+ * @returns `true` if the network mode is not `'online'`, or if it is and the client is online.
460
+ */
461
+ function canFetch(networkMode) {
462
+ return (networkMode ?? "online") === "online" ? onlineManager.isOnline() : true;
463
+ }
464
+ /**
465
+ * The error thrown by a `Retryer` (and surfaced to `query.promise`/`mutation`) when a fetch is cancelled, e.g. via
466
+ * `query.cancel()`. `revert`, if `true`, tells the caller to restore the state the query was in before the fetch
467
+ * started instead of surfacing the error. `silent`, if `true`, tells the caller to suppress this error and instead
468
+ * resolve with the promise of the fetch that triggered the cancellation.
469
+ * @example
470
+ * ```ts
471
+ * query.cancel()
472
+ *
473
+ * try {
474
+ * await query.promise
475
+ * } catch (error) {
476
+ * if (error instanceof CancelledError) {
477
+ * // the fetch was cancelled, e.g. via `query.cancel()`
478
+ * }
479
+ * }
480
+ * ```
481
+ */
482
+ var CancelledError = class extends Error {
483
+ constructor(options) {
484
+ super("CancelledError");
485
+ this.revert = options?.revert;
486
+ this.silent = options?.silent;
487
+ }
488
+ };
489
+ /**
490
+ * Creates a retryer, which runs a function and retries it on failure according to the `retry` and
491
+ * `retryDelay` options. It pauses while the network mode doesn't allow fetching or `canRun` returns
492
+ * `false`, and can be cancelled. Queries and mutations use it to run their `queryFn` and
493
+ * `mutationFn`.
494
+ * @param config - The function to run, the retry options, and the callbacks for failures, pausing,
495
+ * continuing, and cancellation.
496
+ * @returns The retryer, whose `promise` settles with the result of the function.
497
+ */
498
+ function createRetryer(config) {
499
+ let isRetryCancelled = false;
500
+ let failureCount = 0;
501
+ let continueFn;
502
+ let status = "pending";
503
+ let promiseResolve;
504
+ let promiseReject;
505
+ const promise = new Promise((resolve, reject) => {
506
+ promiseResolve = resolve;
507
+ promiseReject = reject;
508
+ });
509
+ promise.catch(noop);
510
+ const isResolved = () => status !== "pending";
511
+ const cancel = (cancelOptions) => {
512
+ if (!isResolved()) {
513
+ const error = new CancelledError(cancelOptions);
514
+ reject(error);
515
+ config.onCancel?.(error);
516
+ }
517
+ };
518
+ const cancelRetry = () => {
519
+ isRetryCancelled = true;
520
+ };
521
+ const continueRetry = () => {
522
+ isRetryCancelled = false;
523
+ };
524
+ const canContinue = () => focusManager.isFocused() && (config.networkMode === "always" || onlineManager.isOnline()) && config.canRun();
525
+ const canStart = () => canFetch(config.networkMode) && config.canRun();
526
+ const resolve = (value) => {
527
+ if (!isResolved()) {
528
+ continueFn?.();
529
+ status = "resolved";
530
+ promiseResolve(value);
531
+ }
532
+ };
533
+ const reject = (value) => {
534
+ if (!isResolved()) {
535
+ continueFn?.();
536
+ status = "rejected";
537
+ promiseReject(value);
538
+ }
539
+ };
540
+ const pause = (canResume) => {
541
+ return new Promise((continueResolve) => {
542
+ continueFn = (value) => {
543
+ if (isResolved() || canResume()) continueResolve(value);
544
+ };
545
+ config.onPause?.();
546
+ }).then(() => {
547
+ continueFn = void 0;
548
+ if (!isResolved()) config.onContinue?.();
549
+ });
550
+ };
551
+ const run = () => {
552
+ if (isResolved()) return;
553
+ let promiseOrValue;
554
+ const initialPromise = failureCount === 0 ? config.initialPromise : void 0;
555
+ try {
556
+ promiseOrValue = initialPromise ?? config.fn();
557
+ } catch (error) {
558
+ promiseOrValue = Promise.reject(error);
559
+ }
560
+ Promise.resolve(promiseOrValue).then(resolve).catch((error) => {
561
+ if (isResolved()) return;
562
+ const retry = config.retry ?? (isServer() ? 0 : 3);
563
+ const retryDelay = config.retryDelay ?? defaultRetryDelay;
564
+ const delay = typeof retryDelay === "function" ? retryDelay(failureCount, error) : retryDelay;
565
+ const shouldRetry = retry === true || typeof retry === "number" && failureCount < retry || typeof retry === "function" && retry(failureCount, error);
566
+ if (isRetryCancelled || !shouldRetry) {
567
+ reject(error);
568
+ return;
569
+ }
570
+ failureCount++;
571
+ config.onFail?.(failureCount, error);
572
+ sleep(delay).then(() => {
573
+ return isResolved() || canContinue() ? void 0 : pause(canContinue);
574
+ }).then(() => {
575
+ if (isRetryCancelled) reject(error);
576
+ else run();
577
+ });
578
+ });
579
+ };
580
+ return {
581
+ promise,
582
+ status: () => status,
583
+ cancel,
584
+ continue: () => {
585
+ continueFn?.();
586
+ return promise;
587
+ },
588
+ cancelRetry,
589
+ continueRetry,
590
+ canStart,
591
+ start: () => {
592
+ if (canStart()) run();
593
+ else pause(canStart).then(run);
594
+ return promise;
595
+ }
596
+ };
597
+ }
598
+ // ../../node_modules/.bun/@tanstack+query-core@5.105.3/node_modules/@tanstack/query-core/build/modern/removable.js
599
+ /**
600
+ * The base class for cache entries that are garbage collected once nothing is using them —
601
+ * `Query` and `Mutation` both extend it. `gcTime` controls how long an unused entry is kept.
602
+ */
603
+ var Removable = class {
604
+ #gcTimeout;
605
+ /**
606
+ * Clears the pending garbage collection timeout, so the entry is no longer scheduled for removal.
607
+ * A subclass may override this to release what it holds on to as well — `Query` also cancels any
608
+ * in-flight fetch.
609
+ */
610
+ destroy() {
611
+ this.clearGcTimeout();
612
+ }
613
+ /**
614
+ * Schedules the entry to be removed from its cache after `gcTime`, replacing any timeout scheduled
615
+ * before. Nothing is scheduled if `gcTime` is `Infinity`.
616
+ */
617
+ scheduleGc() {
618
+ this.clearGcTimeout();
619
+ if (isValidTimeout(this.gcTime)) this.#gcTimeout = timeoutManager.setTimeout(() => {
620
+ this.optionalRemove();
621
+ }, this.gcTime);
622
+ }
623
+ /**
624
+ * Updates `gcTime`, keeping the longest one seen so far. Without a value, it defaults to 5 minutes
625
+ * on the client and `Infinity` on the server.
626
+ * @param newGcTime - The `gcTime` from the latest options, if any.
627
+ */
628
+ updateGcTime(newGcTime) {
629
+ this.gcTime = Math.max(this.gcTime || 0, newGcTime ?? (isServer() ? Infinity : 3e5));
630
+ }
631
+ /**
632
+ * Cancels the scheduled removal, if there is one.
633
+ */
634
+ clearGcTimeout() {
635
+ if (this.#gcTimeout !== void 0) {
636
+ timeoutManager.clearTimeout(this.#gcTimeout);
637
+ this.#gcTimeout = void 0;
638
+ }
639
+ }
640
+ };
641
+ // ../../node_modules/.bun/@tanstack+query-core@5.105.3/node_modules/@tanstack/query-core/build/modern/infiniteQueryBehavior.js
642
+ /**
643
+ * Creates the behavior that fetches the pages of an infinite query: the next or previous page for
644
+ * `fetchNextPage`/`fetchPreviousPage`, or all pages again from the start on a refetch.
645
+ * @param pages - The number of pages to fetch from the start when all pages are fetched again,
646
+ * e.g. from the `pages` option of `queryClient.infiniteQuery`. Defaults to the number of cached
647
+ * pages.
648
+ * @returns The query behavior to set on an infinite query.
649
+ */
650
+ function infiniteQueryBehavior(pages) {
651
+ return { onFetch: (context, query) => {
652
+ const options = context.options;
653
+ const direction = context.fetchOptions?.meta?.fetchMore?.direction;
654
+ const oldPages = context.state.data?.pages || [];
655
+ const oldPageParams = context.state.data?.pageParams || [];
656
+ let result = {
657
+ pages: [],
658
+ pageParams: []
659
+ };
660
+ let currentPage = 0;
661
+ const fetchFn = async () => {
662
+ let cancelled = false;
663
+ const signalContext = context;
664
+ const addSignalProperty = (object) => {
665
+ addConsumeAwareSignal(object, () => context.signal, () => cancelled = true, signalContext[fetchSignal]);
666
+ };
667
+ const queryFn = ensureQueryFn(context.options, context.fetchOptions);
668
+ const fetchPage = async (data, param, previous) => {
669
+ if (cancelled) return Promise.reject(context.signal.reason);
670
+ if (param == null && data.pages.length) return Promise.resolve(data);
671
+ const createQueryFnContext = () => {
672
+ const queryFnContext = {
673
+ client: context.client,
674
+ queryKey: context.queryKey,
675
+ pageParam: param,
676
+ direction: previous ? "backward" : "forward",
677
+ meta: context.options.meta
678
+ };
679
+ addSignalProperty(queryFnContext);
680
+ return queryFnContext;
681
+ };
682
+ const queryFnContext = createQueryFnContext();
683
+ const page = await queryFn(queryFnContext);
684
+ const { maxPages } = context.options;
685
+ const addTo = previous ? addToStart : addToEnd;
686
+ return {
687
+ pages: addTo(data.pages, page, maxPages),
688
+ pageParams: addTo(data.pageParams, param, maxPages)
689
+ };
690
+ };
691
+ if (direction && oldPages.length) {
692
+ const previous = direction === "backward";
693
+ const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
694
+ const oldData = {
695
+ pages: oldPages,
696
+ pageParams: oldPageParams
697
+ };
698
+ result = await fetchPage(oldData, pageParamFn(options, oldData), previous);
699
+ } else {
700
+ const remainingPages = pages ?? oldPages.length;
701
+ do {
702
+ const param = currentPage === 0 ? oldPageParams[0] === void 0 ? options.initialPageParam : oldPageParams[0] : getNextPageParam(options, result);
703
+ if (currentPage > 0 && param == null) break;
704
+ result = await fetchPage(result, param);
705
+ currentPage++;
706
+ } while (currentPage < remainingPages);
707
+ }
708
+ return result;
709
+ };
710
+ if (context.options.persister) context.fetchFn = () => {
711
+ return context.options.persister?.(fetchFn, {
712
+ client: context.client,
713
+ queryKey: context.queryKey,
714
+ meta: context.options.meta,
715
+ signal: context.signal
716
+ }, query);
717
+ };
718
+ else context.fetchFn = fetchFn;
719
+ } };
720
+ }
721
+ /**
722
+ * Computes the page param of the page after the last one, with the `getNextPageParam` option.
723
+ * @param options - The infinite query options.
724
+ * @param data - The current pages and page params.
725
+ * @returns The next page param, or `undefined` if there are no pages yet.
726
+ */
727
+ function getNextPageParam(options, { pages, pageParams }) {
728
+ const lastIndex = pages.length - 1;
729
+ return pages.length > 0 ? options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams) : void 0;
730
+ }
731
+ /**
732
+ * Computes the page param of the page before the first one, with the `getPreviousPageParam`
733
+ * option.
734
+ * @param options - The infinite query options.
735
+ * @param data - The current pages and page params.
736
+ * @returns The previous page param, or `undefined` if there are no pages yet or no
737
+ * `getPreviousPageParam` option.
738
+ */
739
+ function getPreviousPageParam(options, { pages, pageParams }) {
740
+ return pages.length > 0 ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams) : void 0;
741
+ }
742
+ // ../../node_modules/.bun/@tanstack+query-core@5.105.3/node_modules/@tanstack/query-core/build/modern/query.js
743
+ /**
744
+ * Represents a single cached query. A `Query` holds the query's key, options,
745
+ * state (data/error/status), and the observers currently subscribed to it.
746
+ *
747
+ * Instances are created and managed internally by `QueryCache`; application
748
+ * code typically interacts with queries indirectly through `QueryClient` or
749
+ * a framework hook like `useQuery`. Direct access to a `Query` instance is
750
+ * possible via `queryCache.find()`/`findAll()` for inspecting cache state.
751
+ * @example
752
+ * ```ts
753
+ * const queryCache = queryClient.getQueryCache()
754
+ * const query = queryCache.find({ queryKey: ['posts'] })
755
+ *
756
+ * if (query) {
757
+ * console.log(query.state.dataUpdatedAt)
758
+ * }
759
+ * ```
760
+ */
761
+ var Query = class extends Removable {
762
+ #queryType;
763
+ #initialState;
764
+ #revertState;
765
+ #cache;
766
+ #client;
767
+ #retryer;
768
+ #fetchPromise;
769
+ #defaultOptions;
770
+ #abortSignalConsumed;
771
+ constructor(config) {
772
+ super();
773
+ this.#abortSignalConsumed = false;
774
+ this.#defaultOptions = config.defaultOptions;
775
+ this.setOptions(config.options);
776
+ this.observers = [];
777
+ this.#client = config.client;
778
+ this.#cache = this.#client.getQueryCache();
779
+ this.queryKey = config.queryKey;
780
+ this.queryHash = config.queryHash;
781
+ this.#initialState = getDefaultState(this.options);
782
+ this.state = config.state ?? this.#initialState;
783
+ this.scheduleGc();
784
+ }
785
+ /**
786
+ * The `meta` object passed in the query's options, if any.
787
+ * @returns The query's `meta`, or `undefined` if none was set.
788
+ */
789
+ get meta() {
790
+ return this.options.meta;
791
+ }
792
+ /**
793
+ * `'infinite'` for an infinite query, otherwise `undefined`.
794
+ * @internal
795
+ * @returns The type of the query, set from the `_type` option (e.g. `'infinite'`).
796
+ */
797
+ get queryType() {
798
+ return this.#queryType;
799
+ }
800
+ /**
801
+ * The promise for the currently in-flight fetch, if the query is fetching.
802
+ * `undefined` when the query is not fetching.
803
+ * @returns The promise of the in-flight fetch, or `undefined`.
804
+ */
805
+ get promise() {
806
+ return this.#retryer?.promise;
807
+ }
808
+ /**
809
+ * Replaces the query's options and applies their `gcTime`. If the query has no data yet, it gets
810
+ * the `initialData` from the new options, if any.
811
+ * @internal
812
+ * @param options - The new query options, merged on top of the query's default options.
813
+ */
814
+ setOptions(options) {
815
+ this.options = {
816
+ ...this.#defaultOptions,
817
+ ...options
818
+ };
819
+ if (options?._type) this.#queryType = options._type;
820
+ this.updateGcTime(this.options.gcTime);
821
+ if (this.state && this.state.data === void 0) {
822
+ const defaultState = getDefaultState(this.options);
823
+ if (defaultState.data !== void 0) {
824
+ this.setState(successState(defaultState.data, defaultState.dataUpdatedAt));
825
+ this.#initialState = defaultState;
826
+ }
827
+ }
828
+ }
829
+ optionalRemove() {
830
+ if (!this.observers.length && this.state.fetchStatus === "idle") this.#cache.remove(this);
831
+ }
832
+ /**
833
+ * Writes new data to the query and marks it as successfully fetched.
834
+ * @internal
835
+ * @param newData - The data to write. Structural sharing with the current data is applied.
836
+ * @param options - Set `updatedAt` to override the timestamp, and `manual` to mark the write as
837
+ * manual (e.g. from `queryClient.setQueryData`).
838
+ * @returns The data that was written.
839
+ */
840
+ setData(newData, options) {
841
+ const data = replaceData(this.state.data, newData, this.options);
842
+ this.#dispatch({
843
+ data,
844
+ type: "success",
845
+ dataUpdatedAt: options?.updatedAt,
846
+ manual: options?.manual
847
+ });
848
+ return data;
849
+ }
850
+ /**
851
+ * Merges the given partial state directly into this query's state, notifying observers. Used
852
+ * by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a
853
+ * user manually trigger a loading/error state or edit the cached data.
854
+ * @param state - The partial state to merge into the query's state.
855
+ */
856
+ setState(state) {
857
+ this.#dispatch({
858
+ type: "setState",
859
+ state
860
+ });
861
+ }
862
+ /**
863
+ * Cancels the query's currently in-flight fetch, if any.
864
+ * - Returns a promise that resolves once the cancellation has settled.
865
+ * - If no fetch is in progress, resolves immediately.
866
+ * @param options - Set `revert` to restore the state from before the fetch started, and `silent`
867
+ * to suppress the cancellation error when a new fetch replaces the cancelled one.
868
+ * @returns A promise that resolves once the cancellation has settled.
869
+ * @example
870
+ * ```ts
871
+ * await query.cancel()
872
+ * ```
873
+ */
874
+ cancel(options) {
875
+ const promise = this.#retryer?.promise;
876
+ this.#retryer?.cancel(options);
877
+ return promise ? promise.then(noop).catch(noop) : Promise.resolve();
878
+ }
879
+ /**
880
+ * Clears the query's garbage collection timeout and silently cancels any
881
+ * in-flight fetch. Called by `QueryCache` when the query is removed from
882
+ * the cache.
883
+ * @see {@link Query#cancel}
884
+ */
885
+ destroy() {
886
+ super.destroy();
887
+ this.cancel({ silent: true });
888
+ }
889
+ /**
890
+ * The state the query was created with.
891
+ * @internal
892
+ * @returns The state the query had when it was first created, used by {@link Query#reset}.
893
+ */
894
+ get resetState() {
895
+ return this.#initialState;
896
+ }
897
+ /**
898
+ * Resets the query back to its initial state (the state it had when it was
899
+ * first created, e.g. any `initialData`), destroying it first to cancel any
900
+ * in-flight fetch.
901
+ */
902
+ reset() {
903
+ this.destroy();
904
+ this.setState(this.resetState);
905
+ }
906
+ /**
907
+ * Returns `true` if the query has at least one observer for which `enabled`
908
+ * does not resolve to `false`.
909
+ * @returns `true` if the query has an enabled observer.
910
+ */
911
+ isActive() {
912
+ return this.observers.some((observer) => resolveQueryValue(observer.options.enabled, this) !== false);
913
+ }
914
+ /**
915
+ * Returns `true` if the query is disabled, meaning it will not fetch
916
+ * automatically.
917
+ * - If the query has observers, it is disabled when none of them are active
918
+ * (see `isActive`).
919
+ * - If the query has no observers, it is disabled when its `queryFn` is
920
+ * `skipToken` or it has never been fetched.
921
+ * @returns `true` if the query is disabled.
922
+ */
923
+ isDisabled() {
924
+ if (this.getObserversCount() > 0) return !this.isActive();
925
+ return this.options.queryFn === skipToken || !this.isFetched();
926
+ }
927
+ /**
928
+ * Returns `true` if the query has been fetched, i.e. it has resolved with
929
+ * either data or an error at least once.
930
+ * @returns `true` if the query has been fetched.
931
+ */
932
+ isFetched() {
933
+ return this.state.dataUpdateCount + this.state.errorUpdateCount > 0;
934
+ }
935
+ /**
936
+ * Returns `true` if the query has data and at least one observer configured with
937
+ * `staleTime: 'static'`, meaning it is treated as never stale.
938
+ * @returns `true` if the query is static.
939
+ */
940
+ isStatic() {
941
+ if (this.state.data === void 0) return false;
942
+ if (this.getObserversCount() > 0) return this.observers.some((observer) => resolveQueryValue(observer.options.staleTime, this) === "static");
943
+ return false;
944
+ }
945
+ /**
946
+ * Returns `true` if the query is stale.
947
+ * - If the query has observers, defers to whether any observer's current
948
+ * result reports `isStale` (which accounts for each observer's own
949
+ * `staleTime` and `enabled` state).
950
+ * - If the query has no observers, it is considered stale when it has no
951
+ * data or has been invalidated.
952
+ * @returns `true` if the query is stale.
953
+ * @see {@link Query#isStaleByTime}
954
+ * @example
955
+ * ```ts
956
+ * if (query.isStale()) {
957
+ * // refetch or otherwise treat the cached data as outdated
958
+ * }
959
+ * ```
960
+ */
961
+ isStale() {
962
+ if (this.getObserversCount() > 0) return this.observers.some((observer) => observer.getCurrentResult().isStale);
963
+ return this.state.data === void 0 || this.state.isInvalidated;
964
+ }
965
+ /**
966
+ * Returns `true` if the query's data is stale relative to the given
967
+ * `staleTime` (defaults to `0`).
968
+ * - A query with no data is always stale.
969
+ * - `staleTime: 'static'` is never stale.
970
+ * - An invalidated query is always stale.
971
+ * - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`.
972
+ * @param staleTime - The time, in milliseconds, after which data is considered stale, or
973
+ * `'static'` to never treat existing data as stale. A query without data is stale either way.
974
+ * @returns `true` if the query's data is stale.
975
+ * @see {@link Query#isStale}
976
+ * @example
977
+ * ```ts
978
+ * const isStale = query.isStaleByTime(60 * 1000)
979
+ * ```
980
+ */
981
+ isStaleByTime(staleTime = 0) {
982
+ if (this.state.data === void 0) return true;
983
+ if (staleTime === "static") return false;
984
+ if (this.state.isInvalidated) return true;
985
+ return !timeUntilStale(this.state.dataUpdatedAt, staleTime);
986
+ }
987
+ /**
988
+ * Refetches the query when the window regains focus, if an observer wants that, and continues a
989
+ * paused fetch.
990
+ * @internal
991
+ */
992
+ onFocus() {
993
+ this.observers.find((x) => x.shouldFetchOnWindowFocus())?.refetch({ cancelRefetch: false });
994
+ this.#retryer?.continue();
995
+ }
996
+ /**
997
+ * Refetches the query when the app reconnects, if an observer wants that, and continues a paused
998
+ * fetch.
999
+ * @internal
1000
+ */
1001
+ onOnline() {
1002
+ this.observers.find((x) => x.shouldFetchOnReconnect())?.refetch({ cancelRefetch: false });
1003
+ this.#retryer?.continue();
1004
+ }
1005
+ /**
1006
+ * Subscribes an observer to the query and stops its garbage collection.
1007
+ * @internal
1008
+ * @param observer - The observer to add. Adding an observer that is already subscribed does
1009
+ * nothing.
1010
+ */
1011
+ addObserver(observer) {
1012
+ if (!this.observers.includes(observer)) {
1013
+ this.observers.push(observer);
1014
+ this.clearGcTimeout();
1015
+ this.#cache.notify({
1016
+ type: "observerAdded",
1017
+ query: this,
1018
+ observer
1019
+ });
1020
+ }
1021
+ }
1022
+ /**
1023
+ * Unsubscribes an observer from the query.
1024
+ * @internal
1025
+ * @param observer - The observer to remove. When the last observer is removed, the in-flight
1026
+ * fetch is cancelled if its abort signal was consumed (otherwise only its retries are stopped),
1027
+ * and garbage collection is scheduled.
1028
+ */
1029
+ removeObserver(observer) {
1030
+ const index = this.observers.indexOf(observer);
1031
+ if (index !== -1) {
1032
+ this.observers.splice(index, 1);
1033
+ if (!this.observers.length) {
1034
+ if (this.#retryer) {
1035
+ if (this.#abortSignalConsumed || this.state.fetchStatus === "paused" && this.state.status === "pending") this.#retryer.cancel({ revert: true });
1036
+ else this.#retryer.cancelRetry();
1037
+ }
1038
+ this.scheduleGc();
1039
+ }
1040
+ this.#cache.notify({
1041
+ type: "observerRemoved",
1042
+ query: this,
1043
+ observer
1044
+ });
1045
+ }
1046
+ }
1047
+ /**
1048
+ * Returns the number of observers currently subscribed to this query.
1049
+ * @returns The number of observers.
1050
+ * @example
1051
+ * ```ts
1052
+ * if (query.getObserversCount() === 0) {
1053
+ * // no component is currently watching this query
1054
+ * }
1055
+ * ```
1056
+ */
1057
+ getObserversCount() {
1058
+ return this.observers.length;
1059
+ }
1060
+ /**
1061
+ * Marks the query as invalidated, unless it is already invalidated. This
1062
+ * updates `state.isInvalidated` and notifies observers, but does not by
1063
+ * itself trigger a refetch.
1064
+ * @example
1065
+ * ```ts
1066
+ * query.invalidate()
1067
+ * ```
1068
+ */
1069
+ invalidate() {
1070
+ if (!this.state.isInvalidated) this.#dispatch({ type: "invalidate" });
1071
+ }
1072
+ /**
1073
+ * Fetches the query, i.e. runs its `queryFn` (through any configured
1074
+ * retryer/behavior) and updates the query's state with the result.
1075
+ * - If a fetch is already in flight, returns its promise instead of
1076
+ * starting a new one, unless `fetchOptions.cancelRefetch` is set and the
1077
+ * query already has data, in which case the current fetch is silently
1078
+ * cancelled first.
1079
+ * - If `options` is passed, it replaces the query's current options
1080
+ * before fetching.
1081
+ * @param options - Query options that replace the query's current options before fetching. They
1082
+ * are not applied when an in-flight fetch is reused.
1083
+ * @param fetchOptions - Set `cancelRefetch` to cancel an in-flight fetch first (only if the query
1084
+ * already has data), and `meta` to pass extra information to the query's behavior.
1085
+ * @returns A promise that resolves with the fetched data, or rejects with the fetch error. If the
1086
+ * fetch is cancelled with `revert` while the query has data, it resolves with the restored data
1087
+ * instead.
1088
+ */
1089
+ async fetch(options, fetchOptions) {
1090
+ if (this.state.fetchStatus !== "idle" && this.#retryer?.status() !== "rejected") {
1091
+ if (this.state.data !== void 0 && fetchOptions?.cancelRefetch) this.cancel({ silent: true });
1092
+ else if (this.#retryer && this.#fetchPromise) {
1093
+ this.#retryer.continueRetry();
1094
+ return this.#fetchPromise;
1095
+ }
1096
+ }
1097
+ if (options) this.setOptions(options);
1098
+ if (!this.options.queryFn) {
1099
+ const observer = this.observers.find((x) => x.options.queryFn);
1100
+ if (observer) this.setOptions(observer.options);
1101
+ }
1102
+ const abortController = new AbortController();
1103
+ const addSignalProperty = (object) => {
1104
+ Object.defineProperties(object, {
1105
+ [fetchSignal]: {
1106
+ value: abortController.signal,
1107
+ enumerable: true
1108
+ },
1109
+ signal: {
1110
+ enumerable: true,
1111
+ get: () => {
1112
+ this.#abortSignalConsumed = true;
1113
+ return abortController.signal;
1114
+ }
1115
+ }
1116
+ });
1117
+ };
1118
+ const fetchFn = () => {
1119
+ const queryFn = ensureQueryFn(this.options, fetchOptions);
1120
+ const createQueryFnContext = () => {
1121
+ const queryFnContext = {
1122
+ client: this.#client,
1123
+ queryKey: this.queryKey,
1124
+ meta: this.meta
1125
+ };
1126
+ addSignalProperty(queryFnContext);
1127
+ return queryFnContext;
1128
+ };
1129
+ const queryFnContext = createQueryFnContext();
1130
+ this.#abortSignalConsumed = false;
1131
+ if (this.options.persister) return this.options.persister(queryFn, queryFnContext, this);
1132
+ return queryFn(queryFnContext);
1133
+ };
1134
+ const createFetchContext = () => {
1135
+ const context = {
1136
+ fetchOptions,
1137
+ options: this.options,
1138
+ queryKey: this.queryKey,
1139
+ client: this.#client,
1140
+ state: this.state,
1141
+ fetchFn
1142
+ };
1143
+ addSignalProperty(context);
1144
+ return context;
1145
+ };
1146
+ const context = createFetchContext();
1147
+ (this.#queryType === "infinite" ? infiniteQueryBehavior(this.options.pages) : this.options.behavior)?.onFetch(context, this);
1148
+ this.#revertState = this.state;
1149
+ if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== context.fetchOptions?.meta) this.#dispatch({
1150
+ type: "fetch",
1151
+ meta: context.fetchOptions?.meta
1152
+ });
1153
+ const retryer = this.#retryer = createRetryer({
1154
+ initialPromise: fetchOptions?.initialPromise,
1155
+ fn: context.fetchFn,
1156
+ onCancel: (error) => {
1157
+ if (error instanceof CancelledError && error.revert) this.setState({
1158
+ ...this.#revertState,
1159
+ fetchStatus: "idle"
1160
+ });
1161
+ abortController.abort();
1162
+ },
1163
+ onFail: (failureCount, error) => {
1164
+ this.#dispatch({
1165
+ type: "failed",
1166
+ failureCount,
1167
+ error
1168
+ });
1169
+ },
1170
+ onPause: () => {
1171
+ this.#dispatch({ type: "pause" });
1172
+ },
1173
+ onContinue: () => {
1174
+ this.#dispatch({ type: "continue" });
1175
+ },
1176
+ retry: context.options.retry,
1177
+ retryDelay: context.options.retryDelay,
1178
+ networkMode: context.options.networkMode,
1179
+ canRun: () => true
1180
+ });
1181
+ const fetchPromise = (async () => {
1182
+ try {
1183
+ const data = await retryer.promise;
1184
+ if (data === void 0) throw new Error(`${this.queryHash} data is undefined`);
1185
+ this.setData(data);
1186
+ this.#cache.config.onSuccess?.(data, this);
1187
+ this.#cache.config.onSettled?.(data, this.state.error, this);
1188
+ return data;
1189
+ } catch (error) {
1190
+ if (error instanceof CancelledError) {
1191
+ if (error.silent) {
1192
+ if (this.#retryer !== retryer && this.#fetchPromise) return this.#fetchPromise;
1193
+ throw error;
1194
+ } else if (error.revert) {
1195
+ if (this.state.data === void 0) throw error;
1196
+ return this.state.data;
1197
+ }
1198
+ }
1199
+ this.#dispatch({
1200
+ type: "error",
1201
+ error
1202
+ });
1203
+ this.#cache.config.onError?.(error, this);
1204
+ this.#cache.config.onSettled?.(this.state.data, error, this);
1205
+ throw error;
1206
+ } finally {
1207
+ if (this.#retryer === retryer) {
1208
+ this.#retryer = void 0;
1209
+ this.#fetchPromise = void 0;
1210
+ }
1211
+ this.scheduleGc();
1212
+ }
1213
+ })();
1214
+ this.#fetchPromise = fetchPromise;
1215
+ retryer.start();
1216
+ return fetchPromise;
1217
+ }
1218
+ #dispatch(action) {
1219
+ const reducer = (state) => {
1220
+ switch (action.type) {
1221
+ case "failed": return {
1222
+ ...state,
1223
+ fetchFailureCount: action.failureCount,
1224
+ fetchFailureReason: action.error
1225
+ };
1226
+ case "pause": return {
1227
+ ...state,
1228
+ fetchStatus: "paused"
1229
+ };
1230
+ case "continue": return {
1231
+ ...state,
1232
+ fetchStatus: "fetching"
1233
+ };
1234
+ case "fetch": return {
1235
+ ...state,
1236
+ ...fetchState(state.data, this.options),
1237
+ fetchMeta: action.meta ?? null
1238
+ };
1239
+ case "success":
1240
+ const newState = {
1241
+ ...state,
1242
+ ...successState(action.data, action.dataUpdatedAt),
1243
+ dataUpdateCount: state.dataUpdateCount + 1,
1244
+ ...!action.manual && {
1245
+ fetchStatus: "idle",
1246
+ fetchFailureCount: 0,
1247
+ fetchFailureReason: null
1248
+ }
1249
+ };
1250
+ this.#revertState = action.manual ? newState : void 0;
1251
+ return newState;
1252
+ case "error":
1253
+ const error = action.error;
1254
+ return {
1255
+ ...state,
1256
+ error,
1257
+ errorUpdateCount: state.errorUpdateCount + 1,
1258
+ errorUpdatedAt: Date.now(),
1259
+ fetchFailureCount: state.fetchFailureCount + 1,
1260
+ fetchFailureReason: error,
1261
+ fetchStatus: "idle",
1262
+ status: "error",
1263
+ isInvalidated: true
1264
+ };
1265
+ case "invalidate": return {
1266
+ ...state,
1267
+ isInvalidated: true
1268
+ };
1269
+ case "setState": return {
1270
+ ...state,
1271
+ ...action.state
1272
+ };
1273
+ }
1274
+ };
1275
+ this.state = reducer(this.state);
1276
+ notifyManager.batch(() => {
1277
+ this.observers.slice().forEach((observer) => {
1278
+ observer.onQueryUpdate();
1279
+ });
1280
+ this.#cache.notify({
1281
+ query: this,
1282
+ type: "updated",
1283
+ action
1284
+ });
1285
+ });
1286
+ }
1287
+ };
1288
+ /**
1289
+ * Returns the state changes applied when a query starts fetching.
1290
+ * @param data - The query's current data. If it is `undefined`, the query is also reset to
1291
+ * `'pending'` with no error.
1292
+ * @param options - The query options, whose `networkMode` decides whether the query is `'fetching'`
1293
+ * or `'paused'`.
1294
+ * @returns The partial query state for a starting fetch.
1295
+ */
1296
+ function fetchState(data, options) {
1297
+ return {
1298
+ fetchFailureCount: 0,
1299
+ fetchFailureReason: null,
1300
+ fetchStatus: canFetch(options.networkMode) ? "fetching" : "paused",
1301
+ ...data === void 0 && {
1302
+ error: null,
1303
+ status: "pending"
1304
+ }
1305
+ };
1306
+ }
1307
+ /**
1308
+ * Returns the state changes applied when a query receives data.
1309
+ * @param data - The new data.
1310
+ * @param dataUpdatedAt - The timestamp the data is recorded with. Defaults to the current time.
1311
+ * @returns The partial query state for a successful update.
1312
+ */
1313
+ function successState(data, dataUpdatedAt) {
1314
+ return {
1315
+ data,
1316
+ dataUpdatedAt: dataUpdatedAt ?? Date.now(),
1317
+ error: null,
1318
+ isInvalidated: false,
1319
+ status: "success"
1320
+ };
1321
+ }
1322
+ /**
1323
+ * Returns the initial state of a query, based on its `initialData` and `initialDataUpdatedAt`
1324
+ * options.
1325
+ * @param options - The query options.
1326
+ * @returns The initial query state: `'success'` if `initialData` is set, otherwise `'pending'`.
1327
+ */
1328
+ function getDefaultState(options) {
1329
+ const data = typeof options.initialData === "function" ? options.initialData() : options.initialData;
1330
+ const hasData = data !== void 0;
1331
+ const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
1332
+ return {
1333
+ data,
1334
+ dataUpdateCount: 0,
1335
+ dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
1336
+ error: null,
1337
+ errorUpdateCount: 0,
1338
+ errorUpdatedAt: 0,
1339
+ fetchFailureCount: 0,
1340
+ fetchFailureReason: null,
1341
+ fetchMeta: null,
1342
+ isInvalidated: false,
1343
+ status: hasData ? "success" : "pending",
1344
+ fetchStatus: "idle"
1345
+ };
1346
+ }
1347
+ // ../../node_modules/.bun/@tanstack+query-core@5.105.3/node_modules/@tanstack/query-core/build/modern/queryObserver.js
1348
+ /**
1349
+ * A `QueryObserver` watches a single query in the `QueryCache` and computes a
1350
+ * `QueryObserverResult` from its state, recomputing and notifying subscribers
1351
+ * whenever the underlying query (or the observer's options) changes. It is
1352
+ * the primitive that framework adapters (e.g. `useQuery`) build their hooks
1353
+ * on top of, but it can also be used directly to observe and switch between
1354
+ * queries outside of any framework.
1355
+ * @example
1356
+ * ```ts
1357
+ * const observer = new QueryObserver(queryClient, {
1358
+ * queryKey: ['posts'],
1359
+ * queryFn: fetchPosts,
1360
+ * })
1361
+ *
1362
+ * const unsubscribe = observer.subscribe((result) => {
1363
+ * console.log(result.data)
1364
+ * })
1365
+ * ```
1366
+ */
1367
+ var QueryObserver = class extends Subscribable {
1368
+ #client;
1369
+ #currentQuery = void 0;
1370
+ #currentQueryInitialState = void 0;
1371
+ #currentResult = void 0;
1372
+ #currentResultState;
1373
+ #currentResultOptions;
1374
+ #selectError;
1375
+ #selectFn;
1376
+ #selectResult;
1377
+ #lastQueryWithDefinedData;
1378
+ #staleTimeoutId;
1379
+ #refetchIntervalId;
1380
+ #currentRefetchInterval;
1381
+ #trackedProps = /* @__PURE__ */ new Set();
1382
+ constructor(client, options) {
1383
+ super();
1384
+ this.options = options;
1385
+ this.#client = client;
1386
+ this.#selectError = null;
1387
+ this.bindMethods();
1388
+ this.setOptions(options);
1389
+ }
1390
+ /**
1391
+ * Binds the methods of the result (`refetch`) to the observer, so they keep working when destructured
1392
+ * from it. Subclasses override it to bind their own result methods as well.
1393
+ */
1394
+ bindMethods() {
1395
+ this.refetch = this.refetch.bind(this);
1396
+ }
1397
+ onSubscribe() {
1398
+ if (this.listeners.size === 1) {
1399
+ this.#currentQuery.addObserver(this);
1400
+ if (shouldFetchOnMount(this.#currentQuery, this.options)) this.#executeFetch();
1401
+ else this.updateResult();
1402
+ this.#updateTimers();
1403
+ }
1404
+ }
1405
+ onUnsubscribe() {
1406
+ if (!this.hasListeners()) this.destroy();
1407
+ }
1408
+ /**
1409
+ * Returns whether the observed query is currently stale and configured
1410
+ * (via the `refetchOnReconnect` option) to refetch when the network
1411
+ * reconnects.
1412
+ * @returns `true` if the observer should refetch the query on reconnect.
1413
+ */
1414
+ shouldFetchOnReconnect() {
1415
+ return shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnReconnect);
1416
+ }
1417
+ /**
1418
+ * Returns whether the observed query is currently stale and configured
1419
+ * (via the `refetchOnWindowFocus` option) to refetch when the window
1420
+ * regains focus.
1421
+ * @returns `true` if the observer should refetch the query on window focus.
1422
+ */
1423
+ shouldFetchOnWindowFocus() {
1424
+ return shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnWindowFocus);
1425
+ }
1426
+ /**
1427
+ * Stops observing the current query: clears all listeners, cancels the
1428
+ * stale and refetch-interval timers, and removes this observer from the
1429
+ * query it was observing.
1430
+ */
1431
+ destroy() {
1432
+ this.listeners = /* @__PURE__ */ new Set();
1433
+ this.#clearStaleTimeout();
1434
+ this.#clearRefetchInterval();
1435
+ this.#currentQuery.removeObserver(this);
1436
+ }
1437
+ /**
1438
+ * Updates the observer's options. This will re-resolve the query being
1439
+ * observed (switching to a different query if the `queryKey` changed),
1440
+ * trigger a fetch if the new options require one and the observer has
1441
+ * subscribers, recompute the current result, and reschedule the stale and
1442
+ * refetch-interval timers as needed.
1443
+ * @param options - The new observer options. They are defaulted with {@link
1444
+ * QueryClient#defaultQueryOptions} before being applied.
1445
+ * @throws {Error} If `enabled` is neither a boolean nor a function.
1446
+ * @example
1447
+ * ```ts
1448
+ * observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) })
1449
+ * // later: switch to a different query, reusing the same observer
1450
+ * observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) })
1451
+ * ```
1452
+ */
1453
+ setOptions(options) {
1454
+ const prevOptions = this.options;
1455
+ const prevQuery = this.#currentQuery;
1456
+ this.options = this.#client.defaultQueryOptions(options);
1457
+ if (this.options.enabled !== void 0 && typeof this.options.enabled !== "boolean" && typeof this.options.enabled !== "function" && typeof resolveQueryValue(this.options.enabled, this.#currentQuery) !== "boolean") throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");
1458
+ this.#updateQuery();
1459
+ this.#currentQuery.setOptions(this.options);
1460
+ if (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) this.#client.getQueryCache().notify({
1461
+ type: "observerOptionsUpdated",
1462
+ query: this.#currentQuery,
1463
+ observer: this
1464
+ });
1465
+ const mounted = this.hasListeners();
1466
+ if (mounted && shouldFetchOptionally(this.#currentQuery, prevQuery, this.options, prevOptions)) this.#executeFetch();
1467
+ this.updateResult();
1468
+ if (mounted && (this.#currentQuery !== prevQuery || resolveQueryValue(this.options.enabled, this.#currentQuery) !== resolveQueryValue(prevOptions.enabled, this.#currentQuery) || resolveQueryValue(this.options.staleTime, this.#currentQuery) !== resolveQueryValue(prevOptions.staleTime, this.#currentQuery))) this.#updateStaleTimeout();
1469
+ const nextRefetchInterval = this.#computeRefetchInterval();
1470
+ if (mounted && (this.#currentQuery !== prevQuery || resolveQueryValue(this.options.enabled, this.#currentQuery) !== resolveQueryValue(prevOptions.enabled, this.#currentQuery) || nextRefetchInterval !== this.#currentRefetchInterval)) this.#updateRefetchInterval(nextRefetchInterval);
1471
+ }
1472
+ /**
1473
+ * Computes the result the observer would produce for the given (already-defaulted) options
1474
+ * right now, building the underlying `Query` if it doesn't exist yet, without waiting for a
1475
+ * subscription callback. Called by framework adapters on every render (e.g. `useQuery`) so the
1476
+ * returned value is available synchronously, ahead of `setOptions` triggering an actual fetch.
1477
+ * @param options - The defaulted observer options to compute the result for.
1478
+ * @returns The result for the given options.
1479
+ */
1480
+ getOptimisticResult(options) {
1481
+ const query = this.#client.getQueryCache().build(this.#client, options);
1482
+ const result = this.createResult(query, options);
1483
+ if (!shallowEqualObjects(this.getCurrentResult(), result)) {
1484
+ this.#currentResult = result;
1485
+ this.#currentResultOptions = this.options;
1486
+ this.#currentResultState = this.#currentQuery.state;
1487
+ }
1488
+ return result;
1489
+ }
1490
+ /**
1491
+ * Returns the most recently computed `QueryObserverResult` for the
1492
+ * observed query. This is a point-in-time read; to be notified of updates
1493
+ * as they happen, subscribe to the observer instead (its inherited
1494
+ * `subscribe` method).
1495
+ * @returns The observer's latest result.
1496
+ * @example
1497
+ * ```ts
1498
+ * const result = observer.getCurrentResult()
1499
+ * console.log(result.status, result.data)
1500
+ * ```
1501
+ */
1502
+ getCurrentResult() {
1503
+ return this.#currentResult;
1504
+ }
1505
+ /**
1506
+ * Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via
1507
+ * {@link QueryObserver#trackProp} (and an optional `onPropTracked` callback). Used by framework
1508
+ * adapters when `notifyOnChangeProps` is not set, to implement its default "only re-render on
1509
+ * properties you actually read" behavior.
1510
+ * @param result - The result to wrap.
1511
+ * @param onPropTracked - Called with the name of each property that is read.
1512
+ * @returns A proxy of `result` that tracks property reads.
1513
+ */
1514
+ trackResult(result, onPropTracked) {
1515
+ return new Proxy(result, { get: (target, key) => {
1516
+ this.trackProp(key);
1517
+ onPropTracked?.(key);
1518
+ return Reflect.get(target, key);
1519
+ } });
1520
+ }
1521
+ /**
1522
+ * Records that the given `QueryObserverResult` property was read, so a subsequent update only
1523
+ * notifies this observer if a tracked property actually changed. Normally called indirectly via
1524
+ * {@link QueryObserver#trackResult}'s proxy; exposed directly for adapters that track property
1525
+ * access themselves (e.g. through their own reactivity system) instead of via the proxy.
1526
+ * @param key - The name of the property that was read.
1527
+ */
1528
+ trackProp(key) {
1529
+ this.#trackedProps.add(key);
1530
+ }
1531
+ /**
1532
+ * Returns the `Query` instance this observer is currently observing.
1533
+ * @returns The observed query.
1534
+ */
1535
+ getCurrentQuery() {
1536
+ return this.#currentQuery;
1537
+ }
1538
+ /**
1539
+ * Refetches the observed query and returns a promise that resolves with
1540
+ * the resulting `QueryObserverResult`.
1541
+ * @param options - Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling
1542
+ * it, and `throwOnError` to `true` to reject when the refetch fails.
1543
+ * @returns A promise that resolves with the result after the refetch.
1544
+ * @example
1545
+ * ```ts
1546
+ * const result = await observer.refetch({ cancelRefetch: false })
1547
+ * console.log(result.data)
1548
+ * ```
1549
+ */
1550
+ refetch({ ...options } = {}) {
1551
+ return this.fetch({ ...options });
1552
+ }
1553
+ /**
1554
+ * Fetches a query defined by the given options without affecting this
1555
+ * observer's own tracked query or result, and returns a promise that
1556
+ * resolves with the `QueryObserverResult` for that fetch. This is useful
1557
+ * for prefetching data that another observer (e.g. a query about to be
1558
+ * navigated to) will need, ahead of time.
1559
+ * @param options - The observer options of the query to fetch.
1560
+ * @returns A promise that resolves with the result for the fetched query.
1561
+ * @example
1562
+ * ```ts
1563
+ * const result = await observer.fetchOptimistic({
1564
+ * queryKey: ['posts', 2],
1565
+ * queryFn: () => fetchPost(2),
1566
+ * })
1567
+ * console.log(result.data)
1568
+ * ```
1569
+ */
1570
+ fetchOptimistic(options) {
1571
+ const defaultedOptions = this.#client.defaultQueryOptions(options);
1572
+ const query = this.#client.getQueryCache().build(this.#client, defaultedOptions);
1573
+ let unsubscribe = () => {};
1574
+ let resolveEarly;
1575
+ const cachePromise = new Promise((resolve) => {
1576
+ resolveEarly = resolve;
1577
+ unsubscribe = this.#client.getQueryCache().subscribe((event) => {
1578
+ if (event.type === "updated" && event.query.queryHash === query.queryHash && query.state.data !== void 0) {
1579
+ unsubscribe();
1580
+ resolve(this.createResult(query, defaultedOptions));
1581
+ }
1582
+ });
1583
+ });
1584
+ return Promise.race([query.fetch(defaultedOptions).then(() => {
1585
+ const result = this.createResult(query, defaultedOptions);
1586
+ resolveEarly?.(result);
1587
+ return result;
1588
+ }).finally(() => {
1589
+ unsubscribe();
1590
+ }), cachePromise]);
1591
+ }
1592
+ /**
1593
+ * Fetches the observed query and updates the result once the fetch settles. Used by `refetch` and,
1594
+ * in `InfiniteQueryObserver`, to fetch more pages.
1595
+ * @param fetchOptions - Options for this fetch. `cancelRefetch` defaults to `true`.
1596
+ * @returns A promise that resolves with the updated result.
1597
+ */
1598
+ fetch(fetchOptions) {
1599
+ return this.#executeFetch({
1600
+ ...fetchOptions,
1601
+ cancelRefetch: fetchOptions.cancelRefetch ?? true
1602
+ }).then(() => {
1603
+ this.updateResult();
1604
+ return this.#currentResult;
1605
+ });
1606
+ }
1607
+ #executeFetch(fetchOptions) {
1608
+ this.#updateQuery();
1609
+ let promise = this.#currentQuery.fetch(this.options, fetchOptions);
1610
+ if (!fetchOptions?.throwOnError) promise = promise.catch(noop);
1611
+ return promise;
1612
+ }
1613
+ #shouldScheduleTimer(timeout) {
1614
+ return !isServer() && resolveQueryValue(this.options.enabled, this.#currentQuery) !== false && isValidTimeout(timeout);
1615
+ }
1616
+ #updateStaleTimeout() {
1617
+ this.#clearStaleTimeout();
1618
+ const staleTime = resolveQueryValue(this.options.staleTime, this.#currentQuery);
1619
+ if (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) return;
1620
+ const timeout = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime) + 1;
1621
+ this.#staleTimeoutId = timeoutManager.setTimeout(() => {
1622
+ if (!this.#currentResult.isStale) this.updateResult();
1623
+ }, timeout);
1624
+ }
1625
+ #computeRefetchInterval() {
1626
+ return resolveQueryValue(this.options.refetchInterval, this.#currentQuery) ?? false;
1627
+ }
1628
+ #updateRefetchInterval(nextInterval) {
1629
+ this.#clearRefetchInterval();
1630
+ this.#currentRefetchInterval = nextInterval;
1631
+ if (this.#currentRefetchInterval === 0 || !this.#shouldScheduleTimer(this.#currentRefetchInterval)) return;
1632
+ this.#refetchIntervalId = timeoutManager.setInterval(() => {
1633
+ if (this.options.refetchIntervalInBackground || focusManager.isFocused()) this.#executeFetch();
1634
+ }, this.#currentRefetchInterval);
1635
+ }
1636
+ #updateTimers() {
1637
+ this.#updateStaleTimeout();
1638
+ this.#updateRefetchInterval(this.#computeRefetchInterval());
1639
+ }
1640
+ #clearStaleTimeout() {
1641
+ if (this.#staleTimeoutId !== void 0) {
1642
+ timeoutManager.clearTimeout(this.#staleTimeoutId);
1643
+ this.#staleTimeoutId = void 0;
1644
+ }
1645
+ }
1646
+ #clearRefetchInterval() {
1647
+ if (this.#refetchIntervalId !== void 0) {
1648
+ timeoutManager.clearInterval(this.#refetchIntervalId);
1649
+ this.#refetchIntervalId = void 0;
1650
+ }
1651
+ }
1652
+ /**
1653
+ * Computes the result for a query and options from the query's state, applying `select`,
1654
+ * `placeholderData`, and the derived flags. Subclasses override it to add their own fields.
1655
+ * @param query - The query to compute the result for.
1656
+ * @param options - The observer options to compute the result with.
1657
+ * @returns The computed result.
1658
+ */
1659
+ createResult(query, options) {
1660
+ const prevQuery = this.#currentQuery;
1661
+ const prevOptions = this.options;
1662
+ const prevResult = this.#currentResult;
1663
+ const prevResultState = this.#currentResultState;
1664
+ const prevResultOptions = this.#currentResultOptions;
1665
+ const queryInitialState = query !== prevQuery ? query.state : this.#currentQueryInitialState;
1666
+ const { state } = query;
1667
+ let newState = { ...state };
1668
+ let isPlaceholderData = false;
1669
+ let data;
1670
+ if (options._optimisticResults) {
1671
+ const mounted = this.hasListeners();
1672
+ const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
1673
+ const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
1674
+ if (fetchOnMount || fetchOptionally) newState = {
1675
+ ...newState,
1676
+ ...fetchState(state.data, query.options)
1677
+ };
1678
+ if (options._optimisticResults === "isRestoring") newState.fetchStatus = "idle";
1679
+ }
1680
+ let { error, errorUpdatedAt, status } = newState;
1681
+ data = newState.data;
1682
+ let skipSelect = false;
1683
+ if (options.placeholderData !== void 0 && data === void 0 && status === "pending") {
1684
+ let placeholderData;
1685
+ if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) {
1686
+ placeholderData = prevResult.data;
1687
+ skipSelect = true;
1688
+ } else placeholderData = typeof options.placeholderData === "function" ? options.placeholderData(this.#lastQueryWithDefinedData?.state.data, this.#lastQueryWithDefinedData) : options.placeholderData;
1689
+ if (placeholderData !== void 0) {
1690
+ status = "success";
1691
+ data = replaceData(prevResult?.data, placeholderData, options);
1692
+ isPlaceholderData = true;
1693
+ }
1694
+ }
1695
+ if (options.select && data !== void 0 && !skipSelect) {
1696
+ if (prevResult && data === prevResultState?.data && options.select === this.#selectFn) data = this.#selectResult;
1697
+ else try {
1698
+ this.#selectFn = options.select;
1699
+ data = options.select(data);
1700
+ data = replaceData(prevResult?.data, data, options);
1701
+ this.#selectResult = data;
1702
+ this.#selectError = null;
1703
+ } catch (selectError) {
1704
+ this.#selectError = selectError;
1705
+ }
1706
+ } else if (data === void 0) this.#selectError = null;
1707
+ if (this.#selectError) {
1708
+ error = this.#selectError;
1709
+ data = this.#selectResult;
1710
+ errorUpdatedAt = Date.now();
1711
+ status = "error";
1712
+ isPlaceholderData = false;
1713
+ }
1714
+ const isFetching = newState.fetchStatus === "fetching";
1715
+ const isPending = status === "pending";
1716
+ const isError = status === "error";
1717
+ const isLoading = isPending && isFetching;
1718
+ const hasData = data !== void 0;
1719
+ return {
1720
+ status,
1721
+ fetchStatus: newState.fetchStatus,
1722
+ isPending,
1723
+ isSuccess: status === "success",
1724
+ isError,
1725
+ isInitialLoading: isLoading,
1726
+ isLoading,
1727
+ data,
1728
+ dataUpdatedAt: newState.dataUpdatedAt,
1729
+ error,
1730
+ errorUpdatedAt,
1731
+ failureCount: newState.fetchFailureCount,
1732
+ failureReason: newState.fetchFailureReason,
1733
+ errorUpdateCount: newState.errorUpdateCount,
1734
+ isFetched: query.isFetched(),
1735
+ isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount,
1736
+ isFetching,
1737
+ isRefetching: isFetching && !isPending,
1738
+ isLoadingError: isError && !hasData,
1739
+ isPaused: newState.fetchStatus === "paused",
1740
+ isPlaceholderData,
1741
+ isRefetchError: isError && hasData,
1742
+ isStale: isStale(query, options),
1743
+ refetch: this.refetch,
1744
+ isEnabled: resolveQueryValue(options.enabled, query) !== false
1745
+ };
1746
+ }
1747
+ /**
1748
+ * Recomputes and stores the current result from the current query/options, notifying listeners
1749
+ * if it changed. Framework adapters call this right after subscribing to make sure no query
1750
+ * update was missed in the gap between creating the observer and subscribing to it.
1751
+ */
1752
+ updateResult() {
1753
+ const prevResult = this.#currentResult;
1754
+ const nextResult = this.createResult(this.#currentQuery, this.options);
1755
+ this.#currentResultState = this.#currentQuery.state;
1756
+ this.#currentResultOptions = this.options;
1757
+ if (this.#currentResultState.data !== void 0) this.#lastQueryWithDefinedData = this.#currentQuery;
1758
+ if (shallowEqualObjects(nextResult, prevResult)) return;
1759
+ this.#currentResult = nextResult;
1760
+ const shouldNotifyListeners = () => {
1761
+ if (!prevResult) return true;
1762
+ const { notifyOnChangeProps } = this.options;
1763
+ const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps;
1764
+ if (notifyOnChangePropsValue === "all" || !notifyOnChangePropsValue && !this.#trackedProps.size) return true;
1765
+ if (this.options.throwOnError && this.#currentResult.error !== prevResult.error) return true;
1766
+ for (const key of notifyOnChangePropsValue ?? this.#trackedProps) if (this.#currentResult[key] !== prevResult[key]) return true;
1767
+ return false;
1768
+ };
1769
+ const notifyListeners = shouldNotifyListeners();
1770
+ notifyManager.batch(() => {
1771
+ if (notifyListeners) this.listeners.forEach((listener) => {
1772
+ listener(this.#currentResult);
1773
+ });
1774
+ this.#client.getQueryCache().notify({
1775
+ query: this.#currentQuery,
1776
+ type: "observerResultsUpdated"
1777
+ });
1778
+ });
1779
+ }
1780
+ #updateQuery() {
1781
+ const query = this.#client.getQueryCache().build(this.#client, this.options);
1782
+ if (query === this.#currentQuery) return;
1783
+ const prevQuery = this.#currentQuery;
1784
+ this.#currentQuery = query;
1785
+ this.#currentQueryInitialState = query.state;
1786
+ if (this.hasListeners()) {
1787
+ prevQuery?.removeObserver(this);
1788
+ query.addObserver(this);
1789
+ }
1790
+ }
1791
+ /**
1792
+ * Updates the observer's result when the observed query changes, and reschedules its timers if it
1793
+ * has listeners.
1794
+ * @internal
1795
+ */
1796
+ onQueryUpdate() {
1797
+ this.updateResult();
1798
+ if (this.hasListeners()) this.#updateTimers();
1799
+ }
1800
+ };
1801
+ /**
1802
+ * Checks whether a query has no data yet and should do its initial load when an observer mounts.
1803
+ * @param query - The query to check.
1804
+ * @param options - The observer options.
1805
+ * @returns `true` if the query is enabled, has no data, and isn't in an error state with
1806
+ * `retryOnMount: false`.
1807
+ */
1808
+ function shouldLoadOnMount(query, options) {
1809
+ return resolveQueryValue(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === "error" && resolveQueryValue(options.retryOnMount, query) === false);
1810
+ }
1811
+ /**
1812
+ * Checks whether a query should fetch when an observer mounts: either for its initial load, or
1813
+ * because it has data and `refetchOnMount` asks for a refetch.
1814
+ * @param query - The query to check.
1815
+ * @param options - The observer options.
1816
+ * @returns `true` if the query should fetch on mount.
1817
+ */
1818
+ function shouldFetchOnMount(query, options) {
1819
+ return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount);
1820
+ }
1821
+ /**
1822
+ * Checks whether a query should fetch for a `refetchOnMount`, `refetchOnWindowFocus`, or
1823
+ * `refetchOnReconnect` option.
1824
+ * @param query - The query to check.
1825
+ * @param options - The observer options.
1826
+ * @param field - The value of the option to check.
1827
+ * @returns `true` if the query is enabled, not static, and the option is `'always'`, or is not
1828
+ * `false` and the query is stale.
1829
+ */
1830
+ function shouldFetchOn(query, options, field) {
1831
+ if (resolveQueryValue(options.enabled, query) !== false && resolveQueryValue(options.staleTime, query) !== "static") {
1832
+ const value = resolveQueryValue(field, query);
1833
+ return value === "always" || value !== false && isStale(query, options);
1834
+ }
1835
+ return false;
1836
+ }
1837
+ /**
1838
+ * Checks whether a query should fetch after the observer's options change.
1839
+ * @param query - The query observed with the new options.
1840
+ * @param prevQuery - The query observed with the previous options.
1841
+ * @param options - The new observer options.
1842
+ * @param prevOptions - The previous observer options.
1843
+ * @returns `true` if the query changed or was disabled before, it isn't a suspense query in an
1844
+ * error state, and it is stale.
1845
+ */
1846
+ function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
1847
+ return (query !== prevQuery || resolveQueryValue(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options);
1848
+ }
1849
+ /**
1850
+ * Checks whether a query is stale for the given observer options.
1851
+ * @param query - The query to check.
1852
+ * @param options - The observer options, whose `enabled` and `staleTime` are used.
1853
+ * @returns `true` if the query is enabled and its data is stale for `staleTime`.
1854
+ */
1855
+ function isStale(query, options) {
1856
+ return resolveQueryValue(options.enabled, query) !== false && query.isStaleByTime(resolveQueryValue(options.staleTime, query));
1857
+ }
1858
+ // ../../node_modules/.bun/@tanstack+react-query@5.105.3+cef22a3c7e8b4cef/node_modules/@tanstack/react-query/build/modern/IsRestoringProvider.js
1859
+ var IsRestoringContext = import_react.createContext(false);
1860
+ /**
1861
+ * If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to
1862
+ * check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid
1863
+ * race conditions between the restore and mounting queries.
1864
+ * @returns `true` while a persisted client is being restored, `false` otherwise.
1865
+ */
1866
+ var useIsRestoring = () => import_react.useContext(IsRestoringContext);
1867
+ IsRestoringContext.Provider;
1868
+ // ../../node_modules/.bun/@tanstack+react-query@5.105.3+cef22a3c7e8b4cef/node_modules/@tanstack/react-query/build/modern/QueryErrorResetBoundary.js
1869
+ /**
1870
+ * Creates the value shared through the boundary's context, which tracks whether a reset was
1871
+ * requested.
1872
+ * @returns The `clearReset`, `isReset`, and `reset` functions of the boundary.
1873
+ */
1874
+ function createValue() {
1875
+ let isReset = false;
1876
+ return {
1877
+ /**
1878
+ * Clears the reset state, so queries know not to try again until the boundary is reset again.
1879
+ */
1880
+ clearReset: () => {
1881
+ isReset = false;
1882
+ },
1883
+ /**
1884
+ * Resets any query errors within the boundary, so queries know they can try again.
1885
+ */
1886
+ reset: () => {
1887
+ isReset = true;
1888
+ },
1889
+ /**
1890
+ * Returns whether the boundary has been reset and not yet cleared.
1891
+ * @returns `true` if the boundary has been reset and not yet cleared.
1892
+ */
1893
+ isReset: () => {
1894
+ return isReset;
1895
+ }
1896
+ };
1897
+ }
1898
+ var QueryErrorResetBoundaryContext = import_react.createContext(createValue());
1899
+ /**
1900
+ * This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary
1901
+ * defined it will reset them globally.
1902
+ * @returns The boundary's {@link QueryErrorResetBoundaryValue}.
1903
+ * @example
1904
+ * ```tsx
1905
+ * import { ErrorBoundary } from 'react-error-boundary'
1906
+ * import { useQueryErrorResetBoundary } from '@tanstack/react-query'
1907
+ *
1908
+ * function App({ children }: { children: React.ReactNode }) {
1909
+ * const { reset } = useQueryErrorResetBoundary()
1910
+ *
1911
+ * return (
1912
+ * <ErrorBoundary
1913
+ * onReset={reset}
1914
+ * fallbackRender={({ resetErrorBoundary }) => (
1915
+ * <div>
1916
+ * There was an error!
1917
+ * <button onClick={() => resetErrorBoundary()}>Try again</button>
1918
+ * </div>
1919
+ * )}
1920
+ * >
1921
+ * {children}
1922
+ * </ErrorBoundary>
1923
+ * )
1924
+ * }
1925
+ * ```
1926
+ */
1927
+ var useQueryErrorResetBoundary = () => import_react.useContext(QueryErrorResetBoundaryContext);
1928
+ // ../../node_modules/.bun/@tanstack+react-query@5.105.3+cef22a3c7e8b4cef/node_modules/@tanstack/react-query/build/modern/errorBoundaryUtils.js
1929
+ /**
1930
+ * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`),
1931
+ * unless the error boundary has been reset, so a remount doesn't retry the failed query before the
1932
+ * user resets the boundary. Mutates the options.
1933
+ * @param options - The defaulted query options to adjust.
1934
+ * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.
1935
+ * @param query - The query, used to evaluate a `throwOnError` function against its error.
1936
+ */
1937
+ var ensurePreventErrorBoundaryRetry = (options, errorResetBoundary, query) => {
1938
+ const throwOnError = query?.state.status === "error" && typeof options.throwOnError === "function" ? shouldThrowError(options.throwOnError, [query.state.error, query]) : options.throwOnError;
1939
+ if (options.suspense || throwOnError) {
1940
+ if (!errorResetBoundary.isReset()) options.retryOnMount = false;
1941
+ }
1942
+ };
1943
+ /**
1944
+ * Clears the reset state of the error boundary after the component mounts, so later errors are
1945
+ * thrown to the boundary again.
1946
+ * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.
1947
+ */
1948
+ var useClearResetErrorBoundary = (errorResetBoundary) => {
1949
+ import_react.useEffect(() => {
1950
+ errorResetBoundary.clearReset();
1951
+ }, [errorResetBoundary]);
1952
+ };
1953
+ /**
1954
+ * Checks whether the query error should be thrown to the nearest error boundary: the query errored
1955
+ * and isn't fetching, the boundary hasn't been reset, and either `suspense` is enabled with no data
1956
+ * or `throwOnError` says so.
1957
+ * @param params - The observer `result`, the `errorResetBoundary`, the `throwOnError` option, the
1958
+ * `query`, and the `suspense` option.
1959
+ * @returns `true` if the error should be thrown.
1960
+ */
1961
+ var getHasError = ({ result, errorResetBoundary, throwOnError, query, suspense }) => {
1962
+ return result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && (suspense && result.data === void 0 || shouldThrowError(throwOnError, [result.error, query]));
1963
+ };
1964
+ // ../../node_modules/.bun/@tanstack+react-query@5.105.3+cef22a3c7e8b4cef/node_modules/@tanstack/react-query/build/modern/suspense.js
1965
+ /**
1966
+ * The default `throwOnError` of the suspense hooks: throws the error to the nearest error boundary
1967
+ * only if the query has no data to show.
1968
+ * @param _error - The error of the query. Unused.
1969
+ * @param query - The query that errored.
1970
+ * @returns `true` if the query has no data.
1971
+ */
1972
+ var defaultThrowOnError = (_error, query) => query.state.data === void 0;
1973
+ /**
1974
+ * Raises `staleTime` and a numeric `gcTime` to at least 1000ms when `suspense` is enabled, so a
1975
+ * component that remounts after suspending doesn't refetch right away or find the query garbage
1976
+ * collected. A `'static'` `staleTime` is kept as is. Mutates the options.
1977
+ * @param defaultedOptions - The defaulted query options to adjust.
1978
+ */
1979
+ var ensureSuspenseTimers = (defaultedOptions) => {
1980
+ if (defaultedOptions.suspense) {
1981
+ const MIN_SUSPENSE_TIME_MS = 1e3;
1982
+ const clamp = (value) => value === "static" ? value : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS);
1983
+ const originalStaleTime = defaultedOptions.staleTime;
1984
+ defaultedOptions.staleTime = typeof originalStaleTime === "function" ? (...args) => clamp(originalStaleTime(...args)) : clamp(originalStaleTime);
1985
+ if (typeof defaultedOptions.gcTime === "number") defaultedOptions.gcTime = Math.max(defaultedOptions.gcTime, MIN_SUSPENSE_TIME_MS);
1986
+ }
1987
+ };
1988
+ /**
1989
+ * Checks whether a query should suspend: `suspense` is enabled and the result is still `pending`.
1990
+ * @param defaultedOptions - The defaulted query options, if any.
1991
+ * @param result - The current result of the observer.
1992
+ * @returns `true` if the component should suspend.
1993
+ */
1994
+ var shouldSuspend = (defaultedOptions, result) => defaultedOptions?.suspense && result.isPending;
1995
+ /**
1996
+ * Fetches the query for a suspending component, without affecting the observer's own result. If
1997
+ * the fetch fails, the reset state of the error boundary is cleared, so the error is thrown to it.
1998
+ * @param defaultedOptions - The defaulted query options to fetch with.
1999
+ * @param observer - The observer of the query.
2000
+ * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.
2001
+ * @returns A promise that resolves once the fetch settles. It never rejects.
2002
+ */
2003
+ var fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).catch(() => {
2004
+ errorResetBoundary.clearReset();
2005
+ });
2006
+ // ../../node_modules/.bun/@tanstack+react-query@5.105.3+cef22a3c7e8b4cef/node_modules/@tanstack/react-query/build/modern/useBaseQuery.js
2007
+ /**
2008
+ * Base implementation shared by `useQuery`, `useInfiniteQuery`, `useSuspenseQuery`, and
2009
+ * `useSuspenseInfiniteQuery`.
2010
+ * @param options - The options passed to the calling hook.
2011
+ * @param Observer - The observer class from query-core (`QueryObserver` or
2012
+ * `InfiniteQueryObserver`).
2013
+ * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest
2014
+ * context will be used.
2015
+ * @returns The query result, tracking which properties are read unless `notifyOnChangeProps` is
2016
+ * set.
2017
+ * @throws {Error} If `options` is not an object (outside production), or the query error when it should be
2018
+ * thrown to the nearest error boundary (see `throwOnError`). While suspending, it throws a promise instead.
2019
+ */
2020
+ function useBaseQuery(options, Observer, queryClient) {
2021
+ const isRestoring = useIsRestoring();
2022
+ const errorResetBoundary = useQueryErrorResetBoundary();
2023
+ const client = useQueryClient(queryClient);
2024
+ const defaultedOptions = client.defaultQueryOptions(options);
2025
+ const query = client.getQueryCache().get(defaultedOptions.queryHash);
2026
+ const subscribed = options.subscribed !== false;
2027
+ defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : subscribed ? "optimistic" : void 0;
2028
+ ensureSuspenseTimers(defaultedOptions);
2029
+ ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query);
2030
+ useClearResetErrorBoundary(errorResetBoundary);
2031
+ const [observer] = import_react.useState(() => new Observer(client, defaultedOptions));
2032
+ const result = observer.getOptimisticResult(defaultedOptions);
2033
+ import_react.useEffect(() => {
2034
+ observer.setOptions(defaultedOptions);
2035
+ }, [defaultedOptions, observer]);
2036
+ const shouldSubscribe = !isRestoring && subscribed;
2037
+ import_react.useSyncExternalStore(import_react.useCallback((onStoreChange) => {
2038
+ const unsubscribe = shouldSubscribe ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) : noop;
2039
+ observer.updateResult();
2040
+ return unsubscribe;
2041
+ }, [observer, shouldSubscribe]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
2042
+ if (shouldSuspend(defaultedOptions, result)) throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary);
2043
+ if (getHasError({
2044
+ result,
2045
+ errorResetBoundary,
2046
+ throwOnError: defaultedOptions.throwOnError,
2047
+ query,
2048
+ suspense: defaultedOptions.suspense
2049
+ })) throw result.error;
2050
+ return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;
2051
+ }
2052
+ // src/lib/cn.ts
2053
+ /** Joins class names, letting a later Tailwind utility replace a conflicting earlier one. */
2054
+ function cn(...inputs) {
2055
+ return twMerge(clsx(inputs));
2056
+ }
2057
+ export { Query as a, onlineManager as c, Subscribable as d, QueryClientProvider as f, QueryObserver as i, notifyManager as l, useBaseQuery as n, Removable as o, useQueryClient as p, defaultThrowOnError as r, createRetryer as s, cn as t, focusManager as u };