hermium 0.1.9 → 0.2.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 (209) hide show
  1. package/README.md +56 -0
  2. package/bin/hermium.mjs +185 -164
  3. package/dist/api.mjs +3513 -0
  4. package/dist/public/assets/css/index-Dfs9RUU9.css +1 -0
  5. package/dist/public/assets/css/styles-B8p6jk5Z.css +1 -0
  6. package/dist/public/assets/js/ChatInputBlock-Bw7AL70H.js +1 -0
  7. package/dist/public/assets/js/MarkdownMessage-8d7Y6VL-.js +1 -0
  8. package/dist/public/assets/js/base-ui-BvQbAt_1.js +1 -0
  9. package/dist/public/assets/js/chat._sessionId-BG6lVraH.js +1 -0
  10. package/dist/public/assets/js/chat.index-D2zdMPTT.js +1 -0
  11. package/dist/public/assets/js/index-C0AK45FU.js +60 -0
  12. package/dist/public/assets/js/index-Cx5En4FK.js +1 -0
  13. package/dist/public/assets/js/memory-CeSRdTkW.js +3 -0
  14. package/dist/public/assets/js/router-8uDKazL-.js +1 -0
  15. package/dist/public/assets/js/settings-Bc3Y5zXO.js +1 -0
  16. package/dist/public/assets/js/skills-DZv7sA_5.js +1 -0
  17. package/dist/public/assets/js/theme-CPkdkpaj.js +1 -0
  18. package/dist/public/assets/js/usage-DXQsT9_b.js +1 -0
  19. package/dist/public/assets/woff2/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  20. package/dist/public/assets/woff2/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  21. package/dist/public/assets/woff2/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  22. package/dist/public/assets/woff2/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  23. package/dist/public/assets/woff2/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  24. package/dist/public/favicon.ico +0 -0
  25. package/dist/public/logo.png +0 -0
  26. package/package.json +1 -1
  27. package/dist/public/assets/IconAlertCircle-BHkmI3j7.js +0 -1
  28. package/dist/public/assets/IconAlertTriangle-wCJudlVg.js +0 -1
  29. package/dist/public/assets/IconCheck-CFuEh_p7.js +0 -1
  30. package/dist/public/assets/IconLoader2-BIx3OuF9.js +0 -1
  31. package/dist/public/assets/IconRefresh-Dgm93w3T.js +0 -1
  32. package/dist/public/assets/geist-cyrillic-wght-normal-CHSlOQsW.woff2 +0 -0
  33. package/dist/public/assets/geist-latin-ext-wght-normal-DMtmJ5ZE.woff2 +0 -0
  34. package/dist/public/assets/geist-latin-wght-normal-Dm3htQBi.woff2 +0 -0
  35. package/dist/public/assets/index-Bbz3abmO.js +0 -14
  36. package/dist/public/assets/index-CWUaRwcE.js +0 -1
  37. package/dist/public/assets/index-CinLq3cd.js +0 -1
  38. package/dist/public/assets/index-CrQs9n6q.js +0 -29
  39. package/dist/public/assets/index-CtacpN3I.js +0 -1
  40. package/dist/public/assets/index-DY7aE-9s.js +0 -2
  41. package/dist/public/assets/index-DkYGodJj.js +0 -94
  42. package/dist/public/assets/index-DvDLadUx.js +0 -1
  43. package/dist/public/assets/index-U6RcWedt.js +0 -1
  44. package/dist/public/assets/index-_6iFZ0fh.js +0 -1
  45. package/dist/public/assets/index-enFS26SU.js +0 -1
  46. package/dist/public/assets/input-eNcwlDHp.js +0 -1
  47. package/dist/public/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  48. package/dist/public/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  49. package/dist/public/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  50. package/dist/public/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  51. package/dist/public/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  52. package/dist/public/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  53. package/dist/public/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  54. package/dist/public/assets/queries-iHRgZzw2.js +0 -1
  55. package/dist/public/assets/styles-KcflDlA_.css +0 -1
  56. package/dist/public/assets/switch-B1DcZLwL.js +0 -1
  57. package/dist/public/assets/syntax-highlighter-DWPF-A_h.js +0 -6
  58. package/dist/public/assets/textarea-Di_syYTS.js +0 -1
  59. package/dist/public/favicon.png +0 -0
  60. package/dist/public/nous-logo.png +0 -0
  61. package/dist/server/index.mjs +0 -244
  62. package/dist/web-server/__23tanstack-start-plugin-adapters-Cwee5PKy.mjs +0 -6
  63. package/dist/web-server/_chunks/ssr-renderer.mjs +0 -22
  64. package/dist/web-server/_libs/babel__runtime.mjs +0 -237
  65. package/dist/web-server/_libs/bail.mjs +0 -8
  66. package/dist/web-server/_libs/base-ui__react.mjs +0 -9554
  67. package/dist/web-server/_libs/base-ui__utils.mjs +0 -1101
  68. package/dist/web-server/_libs/ccount.mjs +0 -16
  69. package/dist/web-server/_libs/character-entities-legacy.mjs +0 -111
  70. package/dist/web-server/_libs/character-entities.mjs +0 -2130
  71. package/dist/web-server/_libs/character-reference-invalid.mjs +0 -33
  72. package/dist/web-server/_libs/class-variance-authority.mjs +0 -44
  73. package/dist/web-server/_libs/clsx.mjs +0 -16
  74. package/dist/web-server/_libs/comma-separated-tokens.mjs +0 -31
  75. package/dist/web-server/_libs/cookie-es.mjs +0 -44
  76. package/dist/web-server/_libs/croner.mjs +0 -1
  77. package/dist/web-server/_libs/crossws.mjs +0 -1
  78. package/dist/web-server/_libs/decode-named-character-reference+[...].mjs +0 -8
  79. package/dist/web-server/_libs/devlop.mjs +0 -8
  80. package/dist/web-server/_libs/escape-string-regexp.mjs +0 -9
  81. package/dist/web-server/_libs/estree-util-is-identifier-name.mjs +0 -11
  82. package/dist/web-server/_libs/extend.mjs +0 -97
  83. package/dist/web-server/_libs/fault.mjs +0 -1
  84. package/dist/web-server/_libs/floating-ui__core.mjs +0 -663
  85. package/dist/web-server/_libs/floating-ui__dom.mjs +0 -624
  86. package/dist/web-server/_libs/floating-ui__react-dom.mjs +0 -279
  87. package/dist/web-server/_libs/floating-ui__utils.mjs +0 -322
  88. package/dist/web-server/_libs/format.mjs +0 -1
  89. package/dist/web-server/_libs/h3.mjs +0 -408
  90. package/dist/web-server/_libs/hast-util-parse-selector.mjs +0 -39
  91. package/dist/web-server/_libs/hast-util-to-jsx-runtime.mjs +0 -388
  92. package/dist/web-server/_libs/hast-util-whitespace.mjs +0 -10
  93. package/dist/web-server/_libs/hastscript.mjs +0 -200
  94. package/dist/web-server/_libs/highlight.js.mjs +0 -1
  95. package/dist/web-server/_libs/hookable.mjs +0 -1
  96. package/dist/web-server/_libs/html-url-attributes.mjs +0 -26
  97. package/dist/web-server/_libs/inline-style-parser.mjs +0 -142
  98. package/dist/web-server/_libs/is-alphabetical.mjs +0 -7
  99. package/dist/web-server/_libs/is-alphanumerical.mjs +0 -8
  100. package/dist/web-server/_libs/is-decimal.mjs +0 -7
  101. package/dist/web-server/_libs/is-hexadecimal.mjs +0 -7
  102. package/dist/web-server/_libs/is-plain-obj.mjs +0 -10
  103. package/dist/web-server/_libs/isbot.mjs +0 -21
  104. package/dist/web-server/_libs/longest-streak.mjs +0 -25
  105. package/dist/web-server/_libs/lowlight.mjs +0 -1
  106. package/dist/web-server/_libs/markdown-table.mjs +0 -142
  107. package/dist/web-server/_libs/mdast-util-find-and-replace.mjs +0 -109
  108. package/dist/web-server/_libs/mdast-util-from-markdown.mjs +0 -717
  109. package/dist/web-server/_libs/mdast-util-gfm-autolink-literal+[...].mjs +0 -156
  110. package/dist/web-server/_libs/mdast-util-gfm-footnote.mjs +0 -117
  111. package/dist/web-server/_libs/mdast-util-gfm-strikethrough.mjs +0 -54
  112. package/dist/web-server/_libs/mdast-util-gfm-table.mjs +0 -157
  113. package/dist/web-server/_libs/mdast-util-gfm-task-list-item.mjs +0 -77
  114. package/dist/web-server/_libs/mdast-util-gfm.mjs +0 -29
  115. package/dist/web-server/_libs/mdast-util-phrasing.mjs +0 -30
  116. package/dist/web-server/_libs/mdast-util-to-hast.mjs +0 -710
  117. package/dist/web-server/_libs/mdast-util-to-markdown.mjs +0 -798
  118. package/dist/web-server/_libs/mdast-util-to-string.mjs +0 -38
  119. package/dist/web-server/_libs/micromark-core-commonmark.mjs +0 -2259
  120. package/dist/web-server/_libs/micromark-extension-gfm-autolink-literal+[...].mjs +0 -344
  121. package/dist/web-server/_libs/micromark-extension-gfm-footnote+[...].mjs +0 -279
  122. package/dist/web-server/_libs/micromark-extension-gfm-strikethrough+[...].mjs +0 -98
  123. package/dist/web-server/_libs/micromark-extension-gfm-table.mjs +0 -491
  124. package/dist/web-server/_libs/micromark-extension-gfm-tagfilter+[...].mjs +0 -1
  125. package/dist/web-server/_libs/micromark-extension-gfm-task-list-item+[...].mjs +0 -77
  126. package/dist/web-server/_libs/micromark-extension-gfm.mjs +0 -18
  127. package/dist/web-server/_libs/micromark-factory-destination.mjs +0 -94
  128. package/dist/web-server/_libs/micromark-factory-label.mjs +0 -63
  129. package/dist/web-server/_libs/micromark-factory-space.mjs +0 -24
  130. package/dist/web-server/_libs/micromark-factory-title.mjs +0 -65
  131. package/dist/web-server/_libs/micromark-factory-whitespace.mjs +0 -22
  132. package/dist/web-server/_libs/micromark-util-character.mjs +0 -44
  133. package/dist/web-server/_libs/micromark-util-chunked.mjs +0 -36
  134. package/dist/web-server/_libs/micromark-util-classify-character+[...].mjs +0 -12
  135. package/dist/web-server/_libs/micromark-util-combine-extensions+[...].mjs +0 -41
  136. package/dist/web-server/_libs/micromark-util-decode-numeric-character-reference+[...].mjs +0 -19
  137. package/dist/web-server/_libs/micromark-util-decode-string.mjs +0 -21
  138. package/dist/web-server/_libs/micromark-util-encode.mjs +0 -1
  139. package/dist/web-server/_libs/micromark-util-html-tag-name.mjs +0 -69
  140. package/dist/web-server/_libs/micromark-util-normalize-identifier+[...].mjs +0 -6
  141. package/dist/web-server/_libs/micromark-util-resolve-all.mjs +0 -15
  142. package/dist/web-server/_libs/micromark-util-sanitize-uri.mjs +0 -41
  143. package/dist/web-server/_libs/micromark-util-subtokenize.mjs +0 -346
  144. package/dist/web-server/_libs/micromark.mjs +0 -906
  145. package/dist/web-server/_libs/ocache.mjs +0 -1
  146. package/dist/web-server/_libs/ohash.mjs +0 -1
  147. package/dist/web-server/_libs/parse-entities.mjs +0 -245
  148. package/dist/web-server/_libs/property-information.mjs +0 -1210
  149. package/dist/web-server/_libs/react-dom.mjs +0 -10779
  150. package/dist/web-server/_libs/react-markdown.mjs +0 -147
  151. package/dist/web-server/_libs/react-syntax-highlighter.mjs +0 -941
  152. package/dist/web-server/_libs/react.mjs +0 -513
  153. package/dist/web-server/_libs/refractor.mjs +0 -2425
  154. package/dist/web-server/_libs/remark-gfm.mjs +0 -20
  155. package/dist/web-server/_libs/remark-parse.mjs +0 -19
  156. package/dist/web-server/_libs/remark-rehype.mjs +0 -21
  157. package/dist/web-server/_libs/reselect.mjs +0 -1
  158. package/dist/web-server/_libs/rou3.mjs +0 -8
  159. package/dist/web-server/_libs/seroval-plugins.mjs +0 -58
  160. package/dist/web-server/_libs/seroval.mjs +0 -1775
  161. package/dist/web-server/_libs/space-separated-tokens.mjs +0 -11
  162. package/dist/web-server/_libs/srvx.mjs +0 -781
  163. package/dist/web-server/_libs/style-to-js.mjs +0 -72
  164. package/dist/web-server/_libs/style-to-object.mjs +0 -38
  165. package/dist/web-server/_libs/tabler__icons-react.mjs +0 -230
  166. package/dist/web-server/_libs/tanstack__history.mjs +0 -204
  167. package/dist/web-server/_libs/tanstack__query-core.mjs +0 -2552
  168. package/dist/web-server/_libs/tanstack__react-query.mjs +0 -190
  169. package/dist/web-server/_libs/tanstack__react-router.mjs +0 -1120
  170. package/dist/web-server/_libs/tanstack__react-store.mjs +0 -2
  171. package/dist/web-server/_libs/tanstack__router-core.mjs +0 -4288
  172. package/dist/web-server/_libs/tanstack__store.mjs +0 -1
  173. package/dist/web-server/_libs/trim-lines.mjs +0 -41
  174. package/dist/web-server/_libs/trough.mjs +0 -85
  175. package/dist/web-server/_libs/ufo.mjs +0 -54
  176. package/dist/web-server/_libs/unctx.mjs +0 -1
  177. package/dist/web-server/_libs/ungap__structured-clone.mjs +0 -224
  178. package/dist/web-server/_libs/unified.mjs +0 -661
  179. package/dist/web-server/_libs/unist-util-is.mjs +0 -100
  180. package/dist/web-server/_libs/unist-util-position.mjs +0 -27
  181. package/dist/web-server/_libs/unist-util-stringify-position.mjs +0 -27
  182. package/dist/web-server/_libs/unist-util-visit-parents.mjs +0 -83
  183. package/dist/web-server/_libs/unist-util-visit.mjs +0 -24
  184. package/dist/web-server/_libs/unstorage.mjs +0 -1
  185. package/dist/web-server/_libs/use-sync-external-store.mjs +0 -139
  186. package/dist/web-server/_libs/vfile-message.mjs +0 -138
  187. package/dist/web-server/_libs/vfile.mjs +0 -467
  188. package/dist/web-server/_libs/zod.mjs +0 -3915
  189. package/dist/web-server/_libs/zustand.mjs +0 -343
  190. package/dist/web-server/_libs/zwitch.mjs +0 -1
  191. package/dist/web-server/_ssr/index-0n2Z3BPQ.mjs +0 -369
  192. package/dist/web-server/_ssr/index-6itDALOw.mjs +0 -339
  193. package/dist/web-server/_ssr/index-BIRTrOmp.mjs +0 -449
  194. package/dist/web-server/_ssr/index-BPzfADac.mjs +0 -66
  195. package/dist/web-server/_ssr/index-BQE3bF14.mjs +0 -1870
  196. package/dist/web-server/_ssr/index-C5HpvlUP.mjs +0 -190
  197. package/dist/web-server/_ssr/index-C_ZxnypN.mjs +0 -213
  198. package/dist/web-server/_ssr/index-Ca8JFH8f.mjs +0 -612
  199. package/dist/web-server/_ssr/index-DNVESZiA.mjs +0 -513
  200. package/dist/web-server/_ssr/index.mjs +0 -1558
  201. package/dist/web-server/_ssr/input-CqXjTRQg.mjs +0 -20
  202. package/dist/web-server/_ssr/queries-3H_19mUt.mjs +0 -16
  203. package/dist/web-server/_ssr/router-sbsNus0Y.mjs +0 -2093
  204. package/dist/web-server/_ssr/start-HYkvq4Ni.mjs +0 -4
  205. package/dist/web-server/_ssr/switch-usf2F1UM.mjs +0 -33
  206. package/dist/web-server/_ssr/syntax-highlighter-5vezNTce.mjs +0 -62
  207. package/dist/web-server/_ssr/textarea-DfRheWY0.mjs +0 -18
  208. package/dist/web-server/_tanstack-start-manifest_v-DqW-pKEH.mjs +0 -4
  209. package/dist/web-server/index.mjs +0 -597
@@ -1,2552 +0,0 @@
1
- var Subscribable = class {
2
- constructor() {
3
- this.listeners = /* @__PURE__ */ new Set();
4
- this.subscribe = this.subscribe.bind(this);
5
- }
6
- subscribe(listener) {
7
- this.listeners.add(listener);
8
- this.onSubscribe();
9
- return () => {
10
- this.listeners.delete(listener);
11
- this.onUnsubscribe();
12
- };
13
- }
14
- hasListeners() {
15
- return this.listeners.size > 0;
16
- }
17
- onSubscribe() {
18
- }
19
- onUnsubscribe() {
20
- }
21
- };
22
- var FocusManager = class extends Subscribable {
23
- #focused;
24
- #cleanup;
25
- #setup;
26
- constructor() {
27
- super();
28
- this.#setup = (onFocus) => {
29
- if (typeof window !== "undefined" && window.addEventListener) {
30
- const listener = () => onFocus();
31
- window.addEventListener("visibilitychange", listener, false);
32
- return () => {
33
- window.removeEventListener("visibilitychange", listener);
34
- };
35
- }
36
- return;
37
- };
38
- }
39
- onSubscribe() {
40
- if (!this.#cleanup) {
41
- this.setEventListener(this.#setup);
42
- }
43
- }
44
- onUnsubscribe() {
45
- if (!this.hasListeners()) {
46
- this.#cleanup?.();
47
- this.#cleanup = void 0;
48
- }
49
- }
50
- setEventListener(setup) {
51
- this.#setup = setup;
52
- this.#cleanup?.();
53
- this.#cleanup = setup((focused) => {
54
- if (typeof focused === "boolean") {
55
- this.setFocused(focused);
56
- } else {
57
- this.onFocus();
58
- }
59
- });
60
- }
61
- setFocused(focused) {
62
- const changed = this.#focused !== focused;
63
- if (changed) {
64
- this.#focused = focused;
65
- this.onFocus();
66
- }
67
- }
68
- onFocus() {
69
- const isFocused = this.isFocused();
70
- this.listeners.forEach((listener) => {
71
- listener(isFocused);
72
- });
73
- }
74
- isFocused() {
75
- if (typeof this.#focused === "boolean") {
76
- return this.#focused;
77
- }
78
- return globalThis.document?.visibilityState !== "hidden";
79
- }
80
- };
81
- var focusManager = new FocusManager();
82
- var defaultTimeoutProvider = {
83
- // We need the wrapper function syntax below instead of direct references to
84
- // global setTimeout etc.
85
- //
86
- // BAD: `setTimeout: setTimeout`
87
- // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)`
88
- //
89
- // If we use direct references here, then anything that wants to spy on or
90
- // replace the global setTimeout (like tests) won't work since we'll already
91
- // have a hard reference to the original implementation at the time when this
92
- // file was imported.
93
- setTimeout: (callback, delay) => setTimeout(callback, delay),
94
- clearTimeout: (timeoutId) => clearTimeout(timeoutId),
95
- setInterval: (callback, delay) => setInterval(callback, delay),
96
- clearInterval: (intervalId) => clearInterval(intervalId)
97
- };
98
- var TimeoutManager = class {
99
- // We cannot have TimeoutManager<T> as we must instantiate it with a concrete
100
- // type at app boot; and if we leave that type, then any new timer provider
101
- // would need to support the default provider's concrete timer ID, which is
102
- // infeasible across environments.
103
- //
104
- // We settle for type safety for the TimeoutProvider type, and accept that
105
- // this class is unsafe internally to allow for extension.
106
- #provider = defaultTimeoutProvider;
107
- #providerCalled = false;
108
- setTimeoutProvider(provider) {
109
- this.#provider = provider;
110
- }
111
- setTimeout(callback, delay) {
112
- return this.#provider.setTimeout(callback, delay);
113
- }
114
- clearTimeout(timeoutId) {
115
- this.#provider.clearTimeout(timeoutId);
116
- }
117
- setInterval(callback, delay) {
118
- return this.#provider.setInterval(callback, delay);
119
- }
120
- clearInterval(intervalId) {
121
- this.#provider.clearInterval(intervalId);
122
- }
123
- };
124
- var timeoutManager = new TimeoutManager();
125
- function systemSetTimeoutZero(callback) {
126
- setTimeout(callback, 0);
127
- }
128
- var isServer = typeof window === "undefined" || "Deno" in globalThis;
129
- function noop() {
130
- }
131
- function functionalUpdate(updater, input) {
132
- return typeof updater === "function" ? updater(input) : updater;
133
- }
134
- function isValidTimeout(value) {
135
- return typeof value === "number" && value >= 0 && value !== Infinity;
136
- }
137
- function timeUntilStale(updatedAt, staleTime) {
138
- return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
139
- }
140
- function resolveStaleTime(staleTime, query) {
141
- return typeof staleTime === "function" ? staleTime(query) : staleTime;
142
- }
143
- function resolveQueryBoolean(option, query) {
144
- return typeof option === "function" ? option(query) : option;
145
- }
146
- function matchQuery(filters, query) {
147
- const {
148
- type = "all",
149
- exact,
150
- fetchStatus,
151
- predicate,
152
- queryKey,
153
- stale
154
- } = filters;
155
- if (queryKey) {
156
- if (exact) {
157
- if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
158
- return false;
159
- }
160
- } else if (!partialMatchKey(query.queryKey, queryKey)) {
161
- return false;
162
- }
163
- }
164
- if (type !== "all") {
165
- const isActive = query.isActive();
166
- if (type === "active" && !isActive) {
167
- return false;
168
- }
169
- if (type === "inactive" && isActive) {
170
- return false;
171
- }
172
- }
173
- if (typeof stale === "boolean" && query.isStale() !== stale) {
174
- return false;
175
- }
176
- if (fetchStatus && fetchStatus !== query.state.fetchStatus) {
177
- return false;
178
- }
179
- if (predicate && !predicate(query)) {
180
- return false;
181
- }
182
- return true;
183
- }
184
- function matchMutation(filters, mutation) {
185
- const { exact, status, predicate, mutationKey } = filters;
186
- if (mutationKey) {
187
- if (!mutation.options.mutationKey) {
188
- return false;
189
- }
190
- if (exact) {
191
- if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {
192
- return false;
193
- }
194
- } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
195
- return false;
196
- }
197
- }
198
- if (status && mutation.state.status !== status) {
199
- return false;
200
- }
201
- if (predicate && !predicate(mutation)) {
202
- return false;
203
- }
204
- return true;
205
- }
206
- function hashQueryKeyByOptions(queryKey, options) {
207
- const hashFn = options?.queryKeyHashFn || hashKey;
208
- return hashFn(queryKey);
209
- }
210
- function hashKey(queryKey) {
211
- return JSON.stringify(
212
- queryKey,
213
- (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
214
- result[key] = val[key];
215
- return result;
216
- }, {}) : val
217
- );
218
- }
219
- function partialMatchKey(a, b) {
220
- if (a === b) {
221
- return true;
222
- }
223
- if (typeof a !== typeof b) {
224
- return false;
225
- }
226
- if (a && b && typeof a === "object" && typeof b === "object") {
227
- return Object.keys(b).every((key) => partialMatchKey(a[key], b[key]));
228
- }
229
- return false;
230
- }
231
- var hasOwn = Object.prototype.hasOwnProperty;
232
- function replaceEqualDeep(a, b, depth = 0) {
233
- if (a === b) {
234
- return a;
235
- }
236
- if (depth > 500) return b;
237
- const array = isPlainArray(a) && isPlainArray(b);
238
- if (!array && !(isPlainObject(a) && isPlainObject(b))) return b;
239
- const aItems = array ? a : Object.keys(a);
240
- const aSize = aItems.length;
241
- const bItems = array ? b : Object.keys(b);
242
- const bSize = bItems.length;
243
- const copy = array ? new Array(bSize) : {};
244
- let equalItems = 0;
245
- for (let i = 0; i < bSize; i++) {
246
- const key = array ? i : bItems[i];
247
- const aItem = a[key];
248
- const bItem = b[key];
249
- if (aItem === bItem) {
250
- copy[key] = aItem;
251
- if (array ? i < aSize : hasOwn.call(a, key)) equalItems++;
252
- continue;
253
- }
254
- if (aItem === null || bItem === null || typeof aItem !== "object" || typeof bItem !== "object") {
255
- copy[key] = bItem;
256
- continue;
257
- }
258
- const v = replaceEqualDeep(aItem, bItem, depth + 1);
259
- copy[key] = v;
260
- if (v === aItem) equalItems++;
261
- }
262
- return aSize === bSize && equalItems === aSize ? a : copy;
263
- }
264
- function shallowEqualObjects(a, b) {
265
- if (!b || Object.keys(a).length !== Object.keys(b).length) {
266
- return false;
267
- }
268
- for (const key in a) {
269
- if (a[key] !== b[key]) {
270
- return false;
271
- }
272
- }
273
- return true;
274
- }
275
- function isPlainArray(value) {
276
- return Array.isArray(value) && value.length === Object.keys(value).length;
277
- }
278
- function isPlainObject(o) {
279
- if (!hasObjectPrototype(o)) {
280
- return false;
281
- }
282
- const ctor = o.constructor;
283
- if (ctor === void 0) {
284
- return true;
285
- }
286
- const prot = ctor.prototype;
287
- if (!hasObjectPrototype(prot)) {
288
- return false;
289
- }
290
- if (!prot.hasOwnProperty("isPrototypeOf")) {
291
- return false;
292
- }
293
- if (Object.getPrototypeOf(o) !== Object.prototype) {
294
- return false;
295
- }
296
- return true;
297
- }
298
- function hasObjectPrototype(o) {
299
- return Object.prototype.toString.call(o) === "[object Object]";
300
- }
301
- function sleep(timeout) {
302
- return new Promise((resolve) => {
303
- timeoutManager.setTimeout(resolve, timeout);
304
- });
305
- }
306
- function replaceData(prevData, data, options) {
307
- if (typeof options.structuralSharing === "function") {
308
- return options.structuralSharing(prevData, data);
309
- } else if (options.structuralSharing !== false) {
310
- return replaceEqualDeep(prevData, data);
311
- }
312
- return data;
313
- }
314
- function addToEnd(items, item, max = 0) {
315
- const newItems = [...items, item];
316
- return max && newItems.length > max ? newItems.slice(1) : newItems;
317
- }
318
- function addToStart(items, item, max = 0) {
319
- const newItems = [item, ...items];
320
- return max && newItems.length > max ? newItems.slice(0, -1) : newItems;
321
- }
322
- var skipToken = /* @__PURE__ */ Symbol();
323
- function ensureQueryFn(options, fetchOptions) {
324
- if (!options.queryFn && fetchOptions?.initialPromise) {
325
- return () => fetchOptions.initialPromise;
326
- }
327
- if (!options.queryFn || options.queryFn === skipToken) {
328
- return () => Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`));
329
- }
330
- return options.queryFn;
331
- }
332
- function shouldThrowError(throwOnError, params) {
333
- if (typeof throwOnError === "function") {
334
- return throwOnError(...params);
335
- }
336
- return !!throwOnError;
337
- }
338
- function addConsumeAwareSignal(object, getSignal, onCancelled) {
339
- let consumed = false;
340
- let signal;
341
- Object.defineProperty(object, "signal", {
342
- enumerable: true,
343
- get: () => {
344
- signal ??= getSignal();
345
- if (consumed) {
346
- return signal;
347
- }
348
- consumed = true;
349
- if (signal.aborted) {
350
- onCancelled();
351
- } else {
352
- signal.addEventListener("abort", onCancelled, { once: true });
353
- }
354
- return signal;
355
- }
356
- });
357
- return object;
358
- }
359
- var environmentManager = /* @__PURE__ */ (() => {
360
- let isServerFn = () => isServer;
361
- return {
362
- /**
363
- * Returns whether the current runtime should be treated as a server environment.
364
- */
365
- isServer() {
366
- return isServerFn();
367
- },
368
- /**
369
- * Overrides the server check globally.
370
- */
371
- setIsServer(isServerValue) {
372
- isServerFn = isServerValue;
373
- }
374
- };
375
- })();
376
- function pendingThenable() {
377
- let resolve;
378
- let reject;
379
- const thenable = new Promise((_resolve, _reject) => {
380
- resolve = _resolve;
381
- reject = _reject;
382
- });
383
- thenable.status = "pending";
384
- thenable.catch(() => {
385
- });
386
- function finalize(data) {
387
- Object.assign(thenable, data);
388
- delete thenable.resolve;
389
- delete thenable.reject;
390
- }
391
- thenable.resolve = (value) => {
392
- finalize({
393
- status: "fulfilled",
394
- value
395
- });
396
- resolve(value);
397
- };
398
- thenable.reject = (reason) => {
399
- finalize({
400
- status: "rejected",
401
- reason
402
- });
403
- reject(reason);
404
- };
405
- return thenable;
406
- }
407
- var defaultScheduler = systemSetTimeoutZero;
408
- function createNotifyManager() {
409
- let queue = [];
410
- let transactions = 0;
411
- let notifyFn = (callback) => {
412
- callback();
413
- };
414
- let batchNotifyFn = (callback) => {
415
- callback();
416
- };
417
- let scheduleFn = defaultScheduler;
418
- const schedule = (callback) => {
419
- if (transactions) {
420
- queue.push(callback);
421
- } else {
422
- scheduleFn(() => {
423
- notifyFn(callback);
424
- });
425
- }
426
- };
427
- const flush = () => {
428
- const originalQueue = queue;
429
- queue = [];
430
- if (originalQueue.length) {
431
- scheduleFn(() => {
432
- batchNotifyFn(() => {
433
- originalQueue.forEach((callback) => {
434
- notifyFn(callback);
435
- });
436
- });
437
- });
438
- }
439
- };
440
- return {
441
- batch: (callback) => {
442
- let result;
443
- transactions++;
444
- try {
445
- result = callback();
446
- } finally {
447
- transactions--;
448
- if (!transactions) {
449
- flush();
450
- }
451
- }
452
- return result;
453
- },
454
- /**
455
- * All calls to the wrapped function will be batched.
456
- */
457
- batchCalls: (callback) => {
458
- return (...args) => {
459
- schedule(() => {
460
- callback(...args);
461
- });
462
- };
463
- },
464
- schedule,
465
- /**
466
- * Use this method to set a custom notify function.
467
- * This can be used to for example wrap notifications with `React.act` while running tests.
468
- */
469
- setNotifyFunction: (fn) => {
470
- notifyFn = fn;
471
- },
472
- /**
473
- * Use this method to set a custom function to batch notifications together into a single tick.
474
- * By default React Query will use the batch function provided by ReactDOM or React Native.
475
- */
476
- setBatchNotifyFunction: (fn) => {
477
- batchNotifyFn = fn;
478
- },
479
- setScheduler: (fn) => {
480
- scheduleFn = fn;
481
- }
482
- };
483
- }
484
- var notifyManager = createNotifyManager();
485
- var OnlineManager = class extends Subscribable {
486
- #online = true;
487
- #cleanup;
488
- #setup;
489
- constructor() {
490
- super();
491
- this.#setup = (onOnline) => {
492
- if (typeof window !== "undefined" && window.addEventListener) {
493
- const onlineListener = () => onOnline(true);
494
- const offlineListener = () => onOnline(false);
495
- window.addEventListener("online", onlineListener, false);
496
- window.addEventListener("offline", offlineListener, false);
497
- return () => {
498
- window.removeEventListener("online", onlineListener);
499
- window.removeEventListener("offline", offlineListener);
500
- };
501
- }
502
- return;
503
- };
504
- }
505
- onSubscribe() {
506
- if (!this.#cleanup) {
507
- this.setEventListener(this.#setup);
508
- }
509
- }
510
- onUnsubscribe() {
511
- if (!this.hasListeners()) {
512
- this.#cleanup?.();
513
- this.#cleanup = void 0;
514
- }
515
- }
516
- setEventListener(setup) {
517
- this.#setup = setup;
518
- this.#cleanup?.();
519
- this.#cleanup = setup(this.setOnline.bind(this));
520
- }
521
- setOnline(online) {
522
- const changed = this.#online !== online;
523
- if (changed) {
524
- this.#online = online;
525
- this.listeners.forEach((listener) => {
526
- listener(online);
527
- });
528
- }
529
- }
530
- isOnline() {
531
- return this.#online;
532
- }
533
- };
534
- var onlineManager = new OnlineManager();
535
- function defaultRetryDelay(failureCount) {
536
- return Math.min(1e3 * 2 ** failureCount, 3e4);
537
- }
538
- function canFetch(networkMode) {
539
- return (networkMode ?? "online") === "online" ? onlineManager.isOnline() : true;
540
- }
541
- var CancelledError = class extends Error {
542
- constructor(options) {
543
- super("CancelledError");
544
- this.revert = options?.revert;
545
- this.silent = options?.silent;
546
- }
547
- };
548
- function createRetryer(config) {
549
- let isRetryCancelled = false;
550
- let failureCount = 0;
551
- let continueFn;
552
- const thenable = pendingThenable();
553
- const isResolved = () => thenable.status !== "pending";
554
- const cancel = (cancelOptions) => {
555
- if (!isResolved()) {
556
- const error = new CancelledError(cancelOptions);
557
- reject(error);
558
- config.onCancel?.(error);
559
- }
560
- };
561
- const cancelRetry = () => {
562
- isRetryCancelled = true;
563
- };
564
- const continueRetry = () => {
565
- isRetryCancelled = false;
566
- };
567
- const canContinue = () => focusManager.isFocused() && (config.networkMode === "always" || onlineManager.isOnline()) && config.canRun();
568
- const canStart = () => canFetch(config.networkMode) && config.canRun();
569
- const resolve = (value) => {
570
- if (!isResolved()) {
571
- continueFn?.();
572
- thenable.resolve(value);
573
- }
574
- };
575
- const reject = (value) => {
576
- if (!isResolved()) {
577
- continueFn?.();
578
- thenable.reject(value);
579
- }
580
- };
581
- const pause = () => {
582
- return new Promise((continueResolve) => {
583
- continueFn = (value) => {
584
- if (isResolved() || canContinue()) {
585
- continueResolve(value);
586
- }
587
- };
588
- config.onPause?.();
589
- }).then(() => {
590
- continueFn = void 0;
591
- if (!isResolved()) {
592
- config.onContinue?.();
593
- }
594
- });
595
- };
596
- const run = () => {
597
- if (isResolved()) {
598
- return;
599
- }
600
- let promiseOrValue;
601
- const initialPromise = failureCount === 0 ? config.initialPromise : void 0;
602
- try {
603
- promiseOrValue = initialPromise ?? config.fn();
604
- } catch (error) {
605
- promiseOrValue = Promise.reject(error);
606
- }
607
- Promise.resolve(promiseOrValue).then(resolve).catch((error) => {
608
- if (isResolved()) {
609
- return;
610
- }
611
- const retry = config.retry ?? (environmentManager.isServer() ? 0 : 3);
612
- const retryDelay = config.retryDelay ?? defaultRetryDelay;
613
- const delay = typeof retryDelay === "function" ? retryDelay(failureCount, error) : retryDelay;
614
- const shouldRetry = retry === true || typeof retry === "number" && failureCount < retry || typeof retry === "function" && retry(failureCount, error);
615
- if (isRetryCancelled || !shouldRetry) {
616
- reject(error);
617
- return;
618
- }
619
- failureCount++;
620
- config.onFail?.(failureCount, error);
621
- sleep(delay).then(() => {
622
- return canContinue() ? void 0 : pause();
623
- }).then(() => {
624
- if (isRetryCancelled) {
625
- reject(error);
626
- } else {
627
- run();
628
- }
629
- });
630
- });
631
- };
632
- return {
633
- promise: thenable,
634
- status: () => thenable.status,
635
- cancel,
636
- continue: () => {
637
- continueFn?.();
638
- return thenable;
639
- },
640
- cancelRetry,
641
- continueRetry,
642
- canStart,
643
- start: () => {
644
- if (canStart()) {
645
- run();
646
- } else {
647
- pause().then(run);
648
- }
649
- return thenable;
650
- }
651
- };
652
- }
653
- var Removable = class {
654
- #gcTimeout;
655
- destroy() {
656
- this.clearGcTimeout();
657
- }
658
- scheduleGc() {
659
- this.clearGcTimeout();
660
- if (isValidTimeout(this.gcTime)) {
661
- this.#gcTimeout = timeoutManager.setTimeout(() => {
662
- this.optionalRemove();
663
- }, this.gcTime);
664
- }
665
- }
666
- updateGcTime(newGcTime) {
667
- this.gcTime = Math.max(
668
- this.gcTime || 0,
669
- newGcTime ?? (environmentManager.isServer() ? Infinity : 5 * 60 * 1e3)
670
- );
671
- }
672
- clearGcTimeout() {
673
- if (this.#gcTimeout !== void 0) {
674
- timeoutManager.clearTimeout(this.#gcTimeout);
675
- this.#gcTimeout = void 0;
676
- }
677
- }
678
- };
679
- function infiniteQueryBehavior(pages) {
680
- return {
681
- onFetch: (context, query) => {
682
- const options = context.options;
683
- const direction = context.fetchOptions?.meta?.fetchMore?.direction;
684
- const oldPages = context.state.data?.pages || [];
685
- const oldPageParams = context.state.data?.pageParams || [];
686
- let result = { pages: [], pageParams: [] };
687
- let currentPage = 0;
688
- const fetchFn = async () => {
689
- let cancelled = false;
690
- const addSignalProperty = (object) => {
691
- addConsumeAwareSignal(
692
- object,
693
- () => context.signal,
694
- () => cancelled = true
695
- );
696
- };
697
- const queryFn = ensureQueryFn(context.options, context.fetchOptions);
698
- const fetchPage = async (data, param, previous) => {
699
- if (cancelled) {
700
- return Promise.reject(context.signal.reason);
701
- }
702
- if (param == null && data.pages.length) {
703
- return Promise.resolve(data);
704
- }
705
- const createQueryFnContext = () => {
706
- const queryFnContext2 = {
707
- client: context.client,
708
- queryKey: context.queryKey,
709
- pageParam: param,
710
- direction: previous ? "backward" : "forward",
711
- meta: context.options.meta
712
- };
713
- addSignalProperty(queryFnContext2);
714
- return queryFnContext2;
715
- };
716
- const queryFnContext = createQueryFnContext();
717
- const page = await queryFn(queryFnContext);
718
- const { maxPages } = context.options;
719
- const addTo = previous ? addToStart : addToEnd;
720
- return {
721
- pages: addTo(data.pages, page, maxPages),
722
- pageParams: addTo(data.pageParams, param, maxPages)
723
- };
724
- };
725
- if (direction && oldPages.length) {
726
- const previous = direction === "backward";
727
- const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
728
- const oldData = {
729
- pages: oldPages,
730
- pageParams: oldPageParams
731
- };
732
- const param = pageParamFn(options, oldData);
733
- result = await fetchPage(oldData, param, previous);
734
- } else {
735
- const remainingPages = pages ?? oldPages.length;
736
- do {
737
- const param = currentPage === 0 ? oldPageParams[0] ?? options.initialPageParam : getNextPageParam(options, result);
738
- if (currentPage > 0 && param == null) {
739
- break;
740
- }
741
- result = await fetchPage(result, param);
742
- currentPage++;
743
- } while (currentPage < remainingPages);
744
- }
745
- return result;
746
- };
747
- if (context.options.persister) {
748
- context.fetchFn = () => {
749
- return context.options.persister?.(
750
- fetchFn,
751
- {
752
- client: context.client,
753
- queryKey: context.queryKey,
754
- meta: context.options.meta,
755
- signal: context.signal
756
- },
757
- query
758
- );
759
- };
760
- } else {
761
- context.fetchFn = fetchFn;
762
- }
763
- }
764
- };
765
- }
766
- function getNextPageParam(options, { pages, pageParams }) {
767
- const lastIndex = pages.length - 1;
768
- return pages.length > 0 ? options.getNextPageParam(
769
- pages[lastIndex],
770
- pages,
771
- pageParams[lastIndex],
772
- pageParams
773
- ) : void 0;
774
- }
775
- function getPreviousPageParam(options, { pages, pageParams }) {
776
- return pages.length > 0 ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams) : void 0;
777
- }
778
- var Query = class extends Removable {
779
- #queryType;
780
- #initialState;
781
- #revertState;
782
- #cache;
783
- #client;
784
- #retryer;
785
- #defaultOptions;
786
- #abortSignalConsumed;
787
- constructor(config) {
788
- super();
789
- this.#abortSignalConsumed = false;
790
- this.#defaultOptions = config.defaultOptions;
791
- this.setOptions(config.options);
792
- this.observers = [];
793
- this.#client = config.client;
794
- this.#cache = this.#client.getQueryCache();
795
- this.queryKey = config.queryKey;
796
- this.queryHash = config.queryHash;
797
- this.#initialState = getDefaultState$1(this.options);
798
- this.state = config.state ?? this.#initialState;
799
- this.scheduleGc();
800
- }
801
- get meta() {
802
- return this.options.meta;
803
- }
804
- get queryType() {
805
- return this.#queryType;
806
- }
807
- get promise() {
808
- return this.#retryer?.promise;
809
- }
810
- setOptions(options) {
811
- this.options = { ...this.#defaultOptions, ...options };
812
- if (options?._type) {
813
- this.#queryType = options._type;
814
- }
815
- this.updateGcTime(this.options.gcTime);
816
- if (this.state && this.state.data === void 0) {
817
- const defaultState = getDefaultState$1(this.options);
818
- if (defaultState.data !== void 0) {
819
- this.setState(
820
- successState(defaultState.data, defaultState.dataUpdatedAt)
821
- );
822
- this.#initialState = defaultState;
823
- }
824
- }
825
- }
826
- optionalRemove() {
827
- if (!this.observers.length && this.state.fetchStatus === "idle") {
828
- this.#cache.remove(this);
829
- }
830
- }
831
- setData(newData, options) {
832
- const data = replaceData(this.state.data, newData, this.options);
833
- this.#dispatch({
834
- data,
835
- type: "success",
836
- dataUpdatedAt: options?.updatedAt,
837
- manual: options?.manual
838
- });
839
- return data;
840
- }
841
- setState(state) {
842
- this.#dispatch({ type: "setState", state });
843
- }
844
- cancel(options) {
845
- const promise = this.#retryer?.promise;
846
- this.#retryer?.cancel(options);
847
- return promise ? promise.then(noop).catch(noop) : Promise.resolve();
848
- }
849
- destroy() {
850
- super.destroy();
851
- this.cancel({ silent: true });
852
- }
853
- get resetState() {
854
- return this.#initialState;
855
- }
856
- reset() {
857
- this.destroy();
858
- this.setState(this.resetState);
859
- }
860
- isActive() {
861
- return this.observers.some(
862
- (observer) => resolveQueryBoolean(observer.options.enabled, this) !== false
863
- );
864
- }
865
- isDisabled() {
866
- if (this.getObserversCount() > 0) {
867
- return !this.isActive();
868
- }
869
- return this.options.queryFn === skipToken || !this.isFetched();
870
- }
871
- isFetched() {
872
- return this.state.dataUpdateCount + this.state.errorUpdateCount > 0;
873
- }
874
- isStatic() {
875
- if (this.getObserversCount() > 0) {
876
- return this.observers.some(
877
- (observer) => resolveStaleTime(observer.options.staleTime, this) === "static"
878
- );
879
- }
880
- return false;
881
- }
882
- isStale() {
883
- if (this.getObserversCount() > 0) {
884
- return this.observers.some(
885
- (observer) => observer.getCurrentResult().isStale
886
- );
887
- }
888
- return this.state.data === void 0 || this.state.isInvalidated;
889
- }
890
- isStaleByTime(staleTime = 0) {
891
- if (this.state.data === void 0) {
892
- return true;
893
- }
894
- if (staleTime === "static") {
895
- return false;
896
- }
897
- if (this.state.isInvalidated) {
898
- return true;
899
- }
900
- return !timeUntilStale(this.state.dataUpdatedAt, staleTime);
901
- }
902
- onFocus() {
903
- const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus());
904
- observer?.refetch({ cancelRefetch: false });
905
- this.#retryer?.continue();
906
- }
907
- onOnline() {
908
- const observer = this.observers.find((x) => x.shouldFetchOnReconnect());
909
- observer?.refetch({ cancelRefetch: false });
910
- this.#retryer?.continue();
911
- }
912
- addObserver(observer) {
913
- if (!this.observers.includes(observer)) {
914
- this.observers.push(observer);
915
- this.clearGcTimeout();
916
- this.#cache.notify({ type: "observerAdded", query: this, observer });
917
- }
918
- }
919
- removeObserver(observer) {
920
- if (this.observers.includes(observer)) {
921
- this.observers = this.observers.filter((x) => x !== observer);
922
- if (!this.observers.length) {
923
- if (this.#retryer) {
924
- if (this.#abortSignalConsumed || this.#isInitialPausedFetch()) {
925
- this.#retryer.cancel({ revert: true });
926
- } else {
927
- this.#retryer.cancelRetry();
928
- }
929
- }
930
- this.scheduleGc();
931
- }
932
- this.#cache.notify({ type: "observerRemoved", query: this, observer });
933
- }
934
- }
935
- getObserversCount() {
936
- return this.observers.length;
937
- }
938
- #isInitialPausedFetch() {
939
- return this.state.fetchStatus === "paused" && this.state.status === "pending";
940
- }
941
- invalidate() {
942
- if (!this.state.isInvalidated) {
943
- this.#dispatch({ type: "invalidate" });
944
- }
945
- }
946
- async fetch(options, fetchOptions) {
947
- if (this.state.fetchStatus !== "idle" && // If the promise in the retryer is already rejected, we have to definitely
948
- // re-start the fetch; there is a chance that the query is still in a
949
- // pending state when that happens
950
- this.#retryer?.status() !== "rejected") {
951
- if (this.state.data !== void 0 && fetchOptions?.cancelRefetch) {
952
- this.cancel({ silent: true });
953
- } else if (this.#retryer) {
954
- this.#retryer.continueRetry();
955
- return this.#retryer.promise;
956
- }
957
- }
958
- if (options) {
959
- this.setOptions(options);
960
- }
961
- if (!this.options.queryFn) {
962
- const observer = this.observers.find((x) => x.options.queryFn);
963
- if (observer) {
964
- this.setOptions(observer.options);
965
- }
966
- }
967
- const abortController = new AbortController();
968
- const addSignalProperty = (object) => {
969
- Object.defineProperty(object, "signal", {
970
- enumerable: true,
971
- get: () => {
972
- this.#abortSignalConsumed = true;
973
- return abortController.signal;
974
- }
975
- });
976
- };
977
- const fetchFn = () => {
978
- const queryFn = ensureQueryFn(this.options, fetchOptions);
979
- const createQueryFnContext = () => {
980
- const queryFnContext2 = {
981
- client: this.#client,
982
- queryKey: this.queryKey,
983
- meta: this.meta
984
- };
985
- addSignalProperty(queryFnContext2);
986
- return queryFnContext2;
987
- };
988
- const queryFnContext = createQueryFnContext();
989
- this.#abortSignalConsumed = false;
990
- if (this.options.persister) {
991
- return this.options.persister(
992
- queryFn,
993
- queryFnContext,
994
- this
995
- );
996
- }
997
- return queryFn(queryFnContext);
998
- };
999
- const createFetchContext = () => {
1000
- const context2 = {
1001
- fetchOptions,
1002
- options: this.options,
1003
- queryKey: this.queryKey,
1004
- client: this.#client,
1005
- state: this.state,
1006
- fetchFn
1007
- };
1008
- addSignalProperty(context2);
1009
- return context2;
1010
- };
1011
- const context = createFetchContext();
1012
- const behavior = this.#queryType === "infinite" ? infiniteQueryBehavior(
1013
- this.options.pages
1014
- ) : this.options.behavior;
1015
- behavior?.onFetch(context, this);
1016
- this.#revertState = this.state;
1017
- if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== context.fetchOptions?.meta) {
1018
- this.#dispatch({ type: "fetch", meta: context.fetchOptions?.meta });
1019
- }
1020
- this.#retryer = createRetryer({
1021
- initialPromise: fetchOptions?.initialPromise,
1022
- fn: context.fetchFn,
1023
- onCancel: (error) => {
1024
- if (error instanceof CancelledError && error.revert) {
1025
- this.setState({
1026
- ...this.#revertState,
1027
- fetchStatus: "idle"
1028
- });
1029
- }
1030
- abortController.abort();
1031
- },
1032
- onFail: (failureCount, error) => {
1033
- this.#dispatch({ type: "failed", failureCount, error });
1034
- },
1035
- onPause: () => {
1036
- this.#dispatch({ type: "pause" });
1037
- },
1038
- onContinue: () => {
1039
- this.#dispatch({ type: "continue" });
1040
- },
1041
- retry: context.options.retry,
1042
- retryDelay: context.options.retryDelay,
1043
- networkMode: context.options.networkMode,
1044
- canRun: () => true
1045
- });
1046
- try {
1047
- const data = await this.#retryer.start();
1048
- if (data === void 0) {
1049
- if (false) ;
1050
- throw new Error(`${this.queryHash} data is undefined`);
1051
- }
1052
- this.setData(data);
1053
- this.#cache.config.onSuccess?.(data, this);
1054
- this.#cache.config.onSettled?.(
1055
- data,
1056
- this.state.error,
1057
- this
1058
- );
1059
- return data;
1060
- } catch (error) {
1061
- if (error instanceof CancelledError) {
1062
- if (error.silent) {
1063
- return this.#retryer.promise;
1064
- } else if (error.revert) {
1065
- if (this.state.data === void 0) {
1066
- throw error;
1067
- }
1068
- return this.state.data;
1069
- }
1070
- }
1071
- this.#dispatch({
1072
- type: "error",
1073
- error
1074
- });
1075
- this.#cache.config.onError?.(
1076
- error,
1077
- this
1078
- );
1079
- this.#cache.config.onSettled?.(
1080
- this.state.data,
1081
- error,
1082
- this
1083
- );
1084
- throw error;
1085
- } finally {
1086
- this.scheduleGc();
1087
- }
1088
- }
1089
- #dispatch(action) {
1090
- const reducer = (state) => {
1091
- switch (action.type) {
1092
- case "failed":
1093
- return {
1094
- ...state,
1095
- fetchFailureCount: action.failureCount,
1096
- fetchFailureReason: action.error
1097
- };
1098
- case "pause":
1099
- return {
1100
- ...state,
1101
- fetchStatus: "paused"
1102
- };
1103
- case "continue":
1104
- return {
1105
- ...state,
1106
- fetchStatus: "fetching"
1107
- };
1108
- case "fetch":
1109
- return {
1110
- ...state,
1111
- ...fetchState(state.data, this.options),
1112
- fetchMeta: action.meta ?? null
1113
- };
1114
- case "success":
1115
- const newState = {
1116
- ...state,
1117
- ...successState(action.data, action.dataUpdatedAt),
1118
- dataUpdateCount: state.dataUpdateCount + 1,
1119
- ...!action.manual && {
1120
- fetchStatus: "idle",
1121
- fetchFailureCount: 0,
1122
- fetchFailureReason: null
1123
- }
1124
- };
1125
- this.#revertState = action.manual ? newState : void 0;
1126
- return newState;
1127
- case "error":
1128
- const error = action.error;
1129
- return {
1130
- ...state,
1131
- error,
1132
- errorUpdateCount: state.errorUpdateCount + 1,
1133
- errorUpdatedAt: Date.now(),
1134
- fetchFailureCount: state.fetchFailureCount + 1,
1135
- fetchFailureReason: error,
1136
- fetchStatus: "idle",
1137
- status: "error",
1138
- // flag existing data as invalidated if we get a background error
1139
- // note that "no data" always means stale so we can set unconditionally here
1140
- isInvalidated: true
1141
- };
1142
- case "invalidate":
1143
- return {
1144
- ...state,
1145
- isInvalidated: true
1146
- };
1147
- case "setState":
1148
- return {
1149
- ...state,
1150
- ...action.state
1151
- };
1152
- }
1153
- };
1154
- this.state = reducer(this.state);
1155
- notifyManager.batch(() => {
1156
- this.observers.forEach((observer) => {
1157
- observer.onQueryUpdate();
1158
- });
1159
- this.#cache.notify({ query: this, type: "updated", action });
1160
- });
1161
- }
1162
- };
1163
- function fetchState(data, options) {
1164
- return {
1165
- fetchFailureCount: 0,
1166
- fetchFailureReason: null,
1167
- fetchStatus: canFetch(options.networkMode) ? "fetching" : "paused",
1168
- ...data === void 0 && {
1169
- error: null,
1170
- status: "pending"
1171
- }
1172
- };
1173
- }
1174
- function successState(data, dataUpdatedAt) {
1175
- return {
1176
- data,
1177
- dataUpdatedAt: dataUpdatedAt ?? Date.now(),
1178
- error: null,
1179
- isInvalidated: false,
1180
- status: "success"
1181
- };
1182
- }
1183
- function getDefaultState$1(options) {
1184
- const data = typeof options.initialData === "function" ? options.initialData() : options.initialData;
1185
- const hasData = data !== void 0;
1186
- const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
1187
- return {
1188
- data,
1189
- dataUpdateCount: 0,
1190
- dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
1191
- error: null,
1192
- errorUpdateCount: 0,
1193
- errorUpdatedAt: 0,
1194
- fetchFailureCount: 0,
1195
- fetchFailureReason: null,
1196
- fetchMeta: null,
1197
- isInvalidated: false,
1198
- status: hasData ? "success" : "pending",
1199
- fetchStatus: "idle"
1200
- };
1201
- }
1202
- var QueryObserver = class extends Subscribable {
1203
- constructor(client, options) {
1204
- super();
1205
- this.options = options;
1206
- this.#client = client;
1207
- this.#selectError = null;
1208
- this.#currentThenable = pendingThenable();
1209
- this.bindMethods();
1210
- this.setOptions(options);
1211
- }
1212
- #client;
1213
- #currentQuery = void 0;
1214
- #currentQueryInitialState = void 0;
1215
- #currentResult = void 0;
1216
- #currentResultState;
1217
- #currentResultOptions;
1218
- #currentThenable;
1219
- #selectError;
1220
- #selectFn;
1221
- #selectResult;
1222
- // This property keeps track of the last query with defined data.
1223
- // It will be used to pass the previous data and query to the placeholder function between renders.
1224
- #lastQueryWithDefinedData;
1225
- #staleTimeoutId;
1226
- #refetchIntervalId;
1227
- #currentRefetchInterval;
1228
- #trackedProps = /* @__PURE__ */ new Set();
1229
- bindMethods() {
1230
- this.refetch = this.refetch.bind(this);
1231
- }
1232
- onSubscribe() {
1233
- if (this.listeners.size === 1) {
1234
- this.#currentQuery.addObserver(this);
1235
- if (shouldFetchOnMount(this.#currentQuery, this.options)) {
1236
- this.#executeFetch();
1237
- } else {
1238
- this.updateResult();
1239
- }
1240
- this.#updateTimers();
1241
- }
1242
- }
1243
- onUnsubscribe() {
1244
- if (!this.hasListeners()) {
1245
- this.destroy();
1246
- }
1247
- }
1248
- shouldFetchOnReconnect() {
1249
- return shouldFetchOn(
1250
- this.#currentQuery,
1251
- this.options,
1252
- this.options.refetchOnReconnect
1253
- );
1254
- }
1255
- shouldFetchOnWindowFocus() {
1256
- return shouldFetchOn(
1257
- this.#currentQuery,
1258
- this.options,
1259
- this.options.refetchOnWindowFocus
1260
- );
1261
- }
1262
- destroy() {
1263
- this.listeners = /* @__PURE__ */ new Set();
1264
- this.#clearStaleTimeout();
1265
- this.#clearRefetchInterval();
1266
- this.#currentQuery.removeObserver(this);
1267
- }
1268
- setOptions(options) {
1269
- const prevOptions = this.options;
1270
- const prevQuery = this.#currentQuery;
1271
- this.options = this.#client.defaultQueryOptions(options);
1272
- if (this.options.enabled !== void 0 && typeof this.options.enabled !== "boolean" && typeof this.options.enabled !== "function" && typeof resolveQueryBoolean(this.options.enabled, this.#currentQuery) !== "boolean") {
1273
- throw new Error(
1274
- "Expected enabled to be a boolean or a callback that returns a boolean"
1275
- );
1276
- }
1277
- this.#updateQuery();
1278
- this.#currentQuery.setOptions(this.options);
1279
- if (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) {
1280
- this.#client.getQueryCache().notify({
1281
- type: "observerOptionsUpdated",
1282
- query: this.#currentQuery,
1283
- observer: this
1284
- });
1285
- }
1286
- const mounted = this.hasListeners();
1287
- if (mounted && shouldFetchOptionally(
1288
- this.#currentQuery,
1289
- prevQuery,
1290
- this.options,
1291
- prevOptions
1292
- )) {
1293
- this.#executeFetch();
1294
- }
1295
- this.updateResult();
1296
- if (mounted && (this.#currentQuery !== prevQuery || resolveQueryBoolean(this.options.enabled, this.#currentQuery) !== resolveQueryBoolean(prevOptions.enabled, this.#currentQuery) || resolveStaleTime(this.options.staleTime, this.#currentQuery) !== resolveStaleTime(prevOptions.staleTime, this.#currentQuery))) {
1297
- this.#updateStaleTimeout();
1298
- }
1299
- const nextRefetchInterval = this.#computeRefetchInterval();
1300
- if (mounted && (this.#currentQuery !== prevQuery || resolveQueryBoolean(this.options.enabled, this.#currentQuery) !== resolveQueryBoolean(prevOptions.enabled, this.#currentQuery) || nextRefetchInterval !== this.#currentRefetchInterval)) {
1301
- this.#updateRefetchInterval(nextRefetchInterval);
1302
- }
1303
- }
1304
- getOptimisticResult(options) {
1305
- const query = this.#client.getQueryCache().build(this.#client, options);
1306
- const result = this.createResult(query, options);
1307
- if (shouldAssignObserverCurrentProperties(this, result)) {
1308
- this.#currentResult = result;
1309
- this.#currentResultOptions = this.options;
1310
- this.#currentResultState = this.#currentQuery.state;
1311
- }
1312
- return result;
1313
- }
1314
- getCurrentResult() {
1315
- return this.#currentResult;
1316
- }
1317
- trackResult(result, onPropTracked) {
1318
- return new Proxy(result, {
1319
- get: (target, key) => {
1320
- this.trackProp(key);
1321
- onPropTracked?.(key);
1322
- if (key === "promise") {
1323
- this.trackProp("data");
1324
- if (!this.options.experimental_prefetchInRender && this.#currentThenable.status === "pending") {
1325
- this.#currentThenable.reject(
1326
- new Error(
1327
- "experimental_prefetchInRender feature flag is not enabled"
1328
- )
1329
- );
1330
- }
1331
- }
1332
- return Reflect.get(target, key);
1333
- }
1334
- });
1335
- }
1336
- trackProp(key) {
1337
- this.#trackedProps.add(key);
1338
- }
1339
- getCurrentQuery() {
1340
- return this.#currentQuery;
1341
- }
1342
- refetch({ ...options } = {}) {
1343
- return this.fetch({
1344
- ...options
1345
- });
1346
- }
1347
- fetchOptimistic(options) {
1348
- const defaultedOptions = this.#client.defaultQueryOptions(options);
1349
- const query = this.#client.getQueryCache().build(this.#client, defaultedOptions);
1350
- return query.fetch().then(() => this.createResult(query, defaultedOptions));
1351
- }
1352
- fetch(fetchOptions) {
1353
- return this.#executeFetch({
1354
- ...fetchOptions,
1355
- cancelRefetch: fetchOptions.cancelRefetch ?? true
1356
- }).then(() => {
1357
- this.updateResult();
1358
- return this.#currentResult;
1359
- });
1360
- }
1361
- #executeFetch(fetchOptions) {
1362
- this.#updateQuery();
1363
- let promise = this.#currentQuery.fetch(
1364
- this.options,
1365
- fetchOptions
1366
- );
1367
- if (!fetchOptions?.throwOnError) {
1368
- promise = promise.catch(noop);
1369
- }
1370
- return promise;
1371
- }
1372
- #updateStaleTimeout() {
1373
- this.#clearStaleTimeout();
1374
- const staleTime = resolveStaleTime(
1375
- this.options.staleTime,
1376
- this.#currentQuery
1377
- );
1378
- if (environmentManager.isServer() || this.#currentResult.isStale || !isValidTimeout(staleTime)) {
1379
- return;
1380
- }
1381
- const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime);
1382
- const timeout = time + 1;
1383
- this.#staleTimeoutId = timeoutManager.setTimeout(() => {
1384
- if (!this.#currentResult.isStale) {
1385
- this.updateResult();
1386
- }
1387
- }, timeout);
1388
- }
1389
- #computeRefetchInterval() {
1390
- return (typeof this.options.refetchInterval === "function" ? this.options.refetchInterval(this.#currentQuery) : this.options.refetchInterval) ?? false;
1391
- }
1392
- #updateRefetchInterval(nextInterval) {
1393
- this.#clearRefetchInterval();
1394
- this.#currentRefetchInterval = nextInterval;
1395
- if (environmentManager.isServer() || resolveQueryBoolean(this.options.enabled, this.#currentQuery) === false || !isValidTimeout(this.#currentRefetchInterval) || this.#currentRefetchInterval === 0) {
1396
- return;
1397
- }
1398
- this.#refetchIntervalId = timeoutManager.setInterval(() => {
1399
- if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {
1400
- this.#executeFetch();
1401
- }
1402
- }, this.#currentRefetchInterval);
1403
- }
1404
- #updateTimers() {
1405
- this.#updateStaleTimeout();
1406
- this.#updateRefetchInterval(this.#computeRefetchInterval());
1407
- }
1408
- #clearStaleTimeout() {
1409
- if (this.#staleTimeoutId !== void 0) {
1410
- timeoutManager.clearTimeout(this.#staleTimeoutId);
1411
- this.#staleTimeoutId = void 0;
1412
- }
1413
- }
1414
- #clearRefetchInterval() {
1415
- if (this.#refetchIntervalId !== void 0) {
1416
- timeoutManager.clearInterval(this.#refetchIntervalId);
1417
- this.#refetchIntervalId = void 0;
1418
- }
1419
- }
1420
- createResult(query, options) {
1421
- const prevQuery = this.#currentQuery;
1422
- const prevOptions = this.options;
1423
- const prevResult = this.#currentResult;
1424
- const prevResultState = this.#currentResultState;
1425
- const prevResultOptions = this.#currentResultOptions;
1426
- const queryChange = query !== prevQuery;
1427
- const queryInitialState = queryChange ? query.state : this.#currentQueryInitialState;
1428
- const { state } = query;
1429
- let newState = { ...state };
1430
- let isPlaceholderData = false;
1431
- let data;
1432
- if (options._optimisticResults) {
1433
- const mounted = this.hasListeners();
1434
- const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
1435
- const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
1436
- if (fetchOnMount || fetchOptionally) {
1437
- newState = {
1438
- ...newState,
1439
- ...fetchState(state.data, query.options)
1440
- };
1441
- }
1442
- if (options._optimisticResults === "isRestoring") {
1443
- newState.fetchStatus = "idle";
1444
- }
1445
- }
1446
- let { error, errorUpdatedAt, status } = newState;
1447
- data = newState.data;
1448
- let skipSelect = false;
1449
- if (options.placeholderData !== void 0 && data === void 0 && status === "pending") {
1450
- let placeholderData;
1451
- if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) {
1452
- placeholderData = prevResult.data;
1453
- skipSelect = true;
1454
- } else {
1455
- placeholderData = typeof options.placeholderData === "function" ? options.placeholderData(
1456
- this.#lastQueryWithDefinedData?.state.data,
1457
- this.#lastQueryWithDefinedData
1458
- ) : options.placeholderData;
1459
- }
1460
- if (placeholderData !== void 0) {
1461
- status = "success";
1462
- data = replaceData(
1463
- prevResult?.data,
1464
- placeholderData,
1465
- options
1466
- );
1467
- isPlaceholderData = true;
1468
- }
1469
- }
1470
- if (options.select && data !== void 0 && !skipSelect) {
1471
- if (prevResult && data === prevResultState?.data && options.select === this.#selectFn) {
1472
- data = this.#selectResult;
1473
- } else {
1474
- try {
1475
- this.#selectFn = options.select;
1476
- data = options.select(data);
1477
- data = replaceData(prevResult?.data, data, options);
1478
- this.#selectResult = data;
1479
- this.#selectError = null;
1480
- } catch (selectError) {
1481
- this.#selectError = selectError;
1482
- }
1483
- }
1484
- }
1485
- if (this.#selectError) {
1486
- error = this.#selectError;
1487
- data = this.#selectResult;
1488
- errorUpdatedAt = Date.now();
1489
- status = "error";
1490
- }
1491
- const isFetching = newState.fetchStatus === "fetching";
1492
- const isPending = status === "pending";
1493
- const isError = status === "error";
1494
- const isLoading = isPending && isFetching;
1495
- const hasData = data !== void 0;
1496
- const result = {
1497
- status,
1498
- fetchStatus: newState.fetchStatus,
1499
- isPending,
1500
- isSuccess: status === "success",
1501
- isError,
1502
- isInitialLoading: isLoading,
1503
- isLoading,
1504
- data,
1505
- dataUpdatedAt: newState.dataUpdatedAt,
1506
- error,
1507
- errorUpdatedAt,
1508
- failureCount: newState.fetchFailureCount,
1509
- failureReason: newState.fetchFailureReason,
1510
- errorUpdateCount: newState.errorUpdateCount,
1511
- isFetched: query.isFetched(),
1512
- isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount,
1513
- isFetching,
1514
- isRefetching: isFetching && !isPending,
1515
- isLoadingError: isError && !hasData,
1516
- isPaused: newState.fetchStatus === "paused",
1517
- isPlaceholderData,
1518
- isRefetchError: isError && hasData,
1519
- isStale: isStale(query, options),
1520
- refetch: this.refetch,
1521
- promise: this.#currentThenable,
1522
- isEnabled: resolveQueryBoolean(options.enabled, query) !== false
1523
- };
1524
- const nextResult = result;
1525
- if (this.options.experimental_prefetchInRender) {
1526
- const hasResultData = nextResult.data !== void 0;
1527
- const isErrorWithoutData = nextResult.status === "error" && !hasResultData;
1528
- const finalizeThenableIfPossible = (thenable) => {
1529
- if (isErrorWithoutData) {
1530
- thenable.reject(nextResult.error);
1531
- } else if (hasResultData) {
1532
- thenable.resolve(nextResult.data);
1533
- }
1534
- };
1535
- const recreateThenable = () => {
1536
- const pending = this.#currentThenable = nextResult.promise = pendingThenable();
1537
- finalizeThenableIfPossible(pending);
1538
- };
1539
- const prevThenable = this.#currentThenable;
1540
- switch (prevThenable.status) {
1541
- case "pending":
1542
- if (query.queryHash === prevQuery.queryHash) {
1543
- finalizeThenableIfPossible(prevThenable);
1544
- }
1545
- break;
1546
- case "fulfilled":
1547
- if (isErrorWithoutData || nextResult.data !== prevThenable.value) {
1548
- recreateThenable();
1549
- }
1550
- break;
1551
- case "rejected":
1552
- if (!isErrorWithoutData || nextResult.error !== prevThenable.reason) {
1553
- recreateThenable();
1554
- }
1555
- break;
1556
- }
1557
- }
1558
- return nextResult;
1559
- }
1560
- updateResult() {
1561
- const prevResult = this.#currentResult;
1562
- const nextResult = this.createResult(this.#currentQuery, this.options);
1563
- this.#currentResultState = this.#currentQuery.state;
1564
- this.#currentResultOptions = this.options;
1565
- if (this.#currentResultState.data !== void 0) {
1566
- this.#lastQueryWithDefinedData = this.#currentQuery;
1567
- }
1568
- if (shallowEqualObjects(nextResult, prevResult)) {
1569
- return;
1570
- }
1571
- this.#currentResult = nextResult;
1572
- const shouldNotifyListeners = () => {
1573
- if (!prevResult) {
1574
- return true;
1575
- }
1576
- const { notifyOnChangeProps } = this.options;
1577
- const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps;
1578
- if (notifyOnChangePropsValue === "all" || !notifyOnChangePropsValue && !this.#trackedProps.size) {
1579
- return true;
1580
- }
1581
- const includedProps = new Set(
1582
- notifyOnChangePropsValue ?? this.#trackedProps
1583
- );
1584
- if (this.options.throwOnError) {
1585
- includedProps.add("error");
1586
- }
1587
- return Object.keys(this.#currentResult).some((key) => {
1588
- const typedKey = key;
1589
- const changed = this.#currentResult[typedKey] !== prevResult[typedKey];
1590
- return changed && includedProps.has(typedKey);
1591
- });
1592
- };
1593
- this.#notify({ listeners: shouldNotifyListeners() });
1594
- }
1595
- #updateQuery() {
1596
- const query = this.#client.getQueryCache().build(this.#client, this.options);
1597
- if (query === this.#currentQuery) {
1598
- return;
1599
- }
1600
- const prevQuery = this.#currentQuery;
1601
- this.#currentQuery = query;
1602
- this.#currentQueryInitialState = query.state;
1603
- if (this.hasListeners()) {
1604
- prevQuery?.removeObserver(this);
1605
- query.addObserver(this);
1606
- }
1607
- }
1608
- onQueryUpdate() {
1609
- this.updateResult();
1610
- if (this.hasListeners()) {
1611
- this.#updateTimers();
1612
- }
1613
- }
1614
- #notify(notifyOptions) {
1615
- notifyManager.batch(() => {
1616
- if (notifyOptions.listeners) {
1617
- this.listeners.forEach((listener) => {
1618
- listener(this.#currentResult);
1619
- });
1620
- }
1621
- this.#client.getQueryCache().notify({
1622
- query: this.#currentQuery,
1623
- type: "observerResultsUpdated"
1624
- });
1625
- });
1626
- }
1627
- };
1628
- function shouldLoadOnMount(query, options) {
1629
- return resolveQueryBoolean(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === "error" && resolveQueryBoolean(options.retryOnMount, query) === false);
1630
- }
1631
- function shouldFetchOnMount(query, options) {
1632
- return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount);
1633
- }
1634
- function shouldFetchOn(query, options, field) {
1635
- if (resolveQueryBoolean(options.enabled, query) !== false && resolveStaleTime(options.staleTime, query) !== "static") {
1636
- const value = typeof field === "function" ? field(query) : field;
1637
- return value === "always" || value !== false && isStale(query, options);
1638
- }
1639
- return false;
1640
- }
1641
- function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
1642
- return (query !== prevQuery || resolveQueryBoolean(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options);
1643
- }
1644
- function isStale(query, options) {
1645
- return resolveQueryBoolean(options.enabled, query) !== false && query.isStaleByTime(resolveStaleTime(options.staleTime, query));
1646
- }
1647
- function shouldAssignObserverCurrentProperties(observer, optimisticResult) {
1648
- if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) {
1649
- return true;
1650
- }
1651
- return false;
1652
- }
1653
- var Mutation = class extends Removable {
1654
- #client;
1655
- #observers;
1656
- #mutationCache;
1657
- #retryer;
1658
- constructor(config) {
1659
- super();
1660
- this.#client = config.client;
1661
- this.mutationId = config.mutationId;
1662
- this.#mutationCache = config.mutationCache;
1663
- this.#observers = [];
1664
- this.state = config.state || getDefaultState();
1665
- this.setOptions(config.options);
1666
- this.scheduleGc();
1667
- }
1668
- setOptions(options) {
1669
- this.options = options;
1670
- this.updateGcTime(this.options.gcTime);
1671
- }
1672
- get meta() {
1673
- return this.options.meta;
1674
- }
1675
- addObserver(observer) {
1676
- if (!this.#observers.includes(observer)) {
1677
- this.#observers.push(observer);
1678
- this.clearGcTimeout();
1679
- this.#mutationCache.notify({
1680
- type: "observerAdded",
1681
- mutation: this,
1682
- observer
1683
- });
1684
- }
1685
- }
1686
- removeObserver(observer) {
1687
- this.#observers = this.#observers.filter((x) => x !== observer);
1688
- this.scheduleGc();
1689
- this.#mutationCache.notify({
1690
- type: "observerRemoved",
1691
- mutation: this,
1692
- observer
1693
- });
1694
- }
1695
- optionalRemove() {
1696
- if (!this.#observers.length) {
1697
- if (this.state.status === "pending") {
1698
- this.scheduleGc();
1699
- } else {
1700
- this.#mutationCache.remove(this);
1701
- }
1702
- }
1703
- }
1704
- continue() {
1705
- return this.#retryer?.continue() ?? // continuing a mutation assumes that variables are set, mutation must have been dehydrated before
1706
- this.execute(this.state.variables);
1707
- }
1708
- async execute(variables) {
1709
- const onContinue = () => {
1710
- this.#dispatch({ type: "continue" });
1711
- };
1712
- const mutationFnContext = {
1713
- client: this.#client,
1714
- meta: this.options.meta,
1715
- mutationKey: this.options.mutationKey
1716
- };
1717
- this.#retryer = createRetryer({
1718
- fn: () => {
1719
- if (!this.options.mutationFn) {
1720
- return Promise.reject(new Error("No mutationFn found"));
1721
- }
1722
- return this.options.mutationFn(variables, mutationFnContext);
1723
- },
1724
- onFail: (failureCount, error) => {
1725
- this.#dispatch({ type: "failed", failureCount, error });
1726
- },
1727
- onPause: () => {
1728
- this.#dispatch({ type: "pause" });
1729
- },
1730
- onContinue,
1731
- retry: this.options.retry ?? 0,
1732
- retryDelay: this.options.retryDelay,
1733
- networkMode: this.options.networkMode,
1734
- canRun: () => this.#mutationCache.canRun(this)
1735
- });
1736
- const restored = this.state.status === "pending";
1737
- const isPaused = !this.#retryer.canStart();
1738
- try {
1739
- if (restored) {
1740
- onContinue();
1741
- } else {
1742
- this.#dispatch({ type: "pending", variables, isPaused });
1743
- if (this.#mutationCache.config.onMutate) {
1744
- await this.#mutationCache.config.onMutate(
1745
- variables,
1746
- this,
1747
- mutationFnContext
1748
- );
1749
- }
1750
- const context = await this.options.onMutate?.(
1751
- variables,
1752
- mutationFnContext
1753
- );
1754
- if (context !== this.state.context) {
1755
- this.#dispatch({
1756
- type: "pending",
1757
- context,
1758
- variables,
1759
- isPaused
1760
- });
1761
- }
1762
- }
1763
- const data = await this.#retryer.start();
1764
- await this.#mutationCache.config.onSuccess?.(
1765
- data,
1766
- variables,
1767
- this.state.context,
1768
- this,
1769
- mutationFnContext
1770
- );
1771
- await this.options.onSuccess?.(
1772
- data,
1773
- variables,
1774
- this.state.context,
1775
- mutationFnContext
1776
- );
1777
- await this.#mutationCache.config.onSettled?.(
1778
- data,
1779
- null,
1780
- this.state.variables,
1781
- this.state.context,
1782
- this,
1783
- mutationFnContext
1784
- );
1785
- await this.options.onSettled?.(
1786
- data,
1787
- null,
1788
- variables,
1789
- this.state.context,
1790
- mutationFnContext
1791
- );
1792
- this.#dispatch({ type: "success", data });
1793
- return data;
1794
- } catch (error) {
1795
- try {
1796
- await this.#mutationCache.config.onError?.(
1797
- error,
1798
- variables,
1799
- this.state.context,
1800
- this,
1801
- mutationFnContext
1802
- );
1803
- } catch (e) {
1804
- void Promise.reject(e);
1805
- }
1806
- try {
1807
- await this.options.onError?.(
1808
- error,
1809
- variables,
1810
- this.state.context,
1811
- mutationFnContext
1812
- );
1813
- } catch (e) {
1814
- void Promise.reject(e);
1815
- }
1816
- try {
1817
- await this.#mutationCache.config.onSettled?.(
1818
- void 0,
1819
- error,
1820
- this.state.variables,
1821
- this.state.context,
1822
- this,
1823
- mutationFnContext
1824
- );
1825
- } catch (e) {
1826
- void Promise.reject(e);
1827
- }
1828
- try {
1829
- await this.options.onSettled?.(
1830
- void 0,
1831
- error,
1832
- variables,
1833
- this.state.context,
1834
- mutationFnContext
1835
- );
1836
- } catch (e) {
1837
- void Promise.reject(e);
1838
- }
1839
- this.#dispatch({ type: "error", error });
1840
- throw error;
1841
- } finally {
1842
- this.#mutationCache.runNext(this);
1843
- }
1844
- }
1845
- #dispatch(action) {
1846
- const reducer = (state) => {
1847
- switch (action.type) {
1848
- case "failed":
1849
- return {
1850
- ...state,
1851
- failureCount: action.failureCount,
1852
- failureReason: action.error
1853
- };
1854
- case "pause":
1855
- return {
1856
- ...state,
1857
- isPaused: true
1858
- };
1859
- case "continue":
1860
- return {
1861
- ...state,
1862
- isPaused: false
1863
- };
1864
- case "pending":
1865
- return {
1866
- ...state,
1867
- context: action.context,
1868
- data: void 0,
1869
- failureCount: 0,
1870
- failureReason: null,
1871
- error: null,
1872
- isPaused: action.isPaused,
1873
- status: "pending",
1874
- variables: action.variables,
1875
- submittedAt: Date.now()
1876
- };
1877
- case "success":
1878
- return {
1879
- ...state,
1880
- data: action.data,
1881
- failureCount: 0,
1882
- failureReason: null,
1883
- error: null,
1884
- status: "success",
1885
- isPaused: false
1886
- };
1887
- case "error":
1888
- return {
1889
- ...state,
1890
- data: void 0,
1891
- error: action.error,
1892
- failureCount: state.failureCount + 1,
1893
- failureReason: action.error,
1894
- isPaused: false,
1895
- status: "error"
1896
- };
1897
- }
1898
- };
1899
- this.state = reducer(this.state);
1900
- notifyManager.batch(() => {
1901
- this.#observers.forEach((observer) => {
1902
- observer.onMutationUpdate(action);
1903
- });
1904
- this.#mutationCache.notify({
1905
- mutation: this,
1906
- type: "updated",
1907
- action
1908
- });
1909
- });
1910
- }
1911
- };
1912
- function getDefaultState() {
1913
- return {
1914
- context: void 0,
1915
- data: void 0,
1916
- error: null,
1917
- failureCount: 0,
1918
- failureReason: null,
1919
- isPaused: false,
1920
- status: "idle",
1921
- variables: void 0,
1922
- submittedAt: 0
1923
- };
1924
- }
1925
- var MutationCache = class extends Subscribable {
1926
- constructor(config = {}) {
1927
- super();
1928
- this.config = config;
1929
- this.#mutations = /* @__PURE__ */ new Set();
1930
- this.#scopes = /* @__PURE__ */ new Map();
1931
- this.#mutationId = 0;
1932
- }
1933
- #mutations;
1934
- #scopes;
1935
- #mutationId;
1936
- build(client, options, state) {
1937
- const mutation = new Mutation({
1938
- client,
1939
- mutationCache: this,
1940
- mutationId: ++this.#mutationId,
1941
- options: client.defaultMutationOptions(options),
1942
- state
1943
- });
1944
- this.add(mutation);
1945
- return mutation;
1946
- }
1947
- add(mutation) {
1948
- this.#mutations.add(mutation);
1949
- const scope = scopeFor(mutation);
1950
- if (typeof scope === "string") {
1951
- const scopedMutations = this.#scopes.get(scope);
1952
- if (scopedMutations) {
1953
- scopedMutations.push(mutation);
1954
- } else {
1955
- this.#scopes.set(scope, [mutation]);
1956
- }
1957
- }
1958
- this.notify({ type: "added", mutation });
1959
- }
1960
- remove(mutation) {
1961
- if (this.#mutations.delete(mutation)) {
1962
- const scope = scopeFor(mutation);
1963
- if (typeof scope === "string") {
1964
- const scopedMutations = this.#scopes.get(scope);
1965
- if (scopedMutations) {
1966
- if (scopedMutations.length > 1) {
1967
- const index = scopedMutations.indexOf(mutation);
1968
- if (index !== -1) {
1969
- scopedMutations.splice(index, 1);
1970
- }
1971
- } else if (scopedMutations[0] === mutation) {
1972
- this.#scopes.delete(scope);
1973
- }
1974
- }
1975
- }
1976
- }
1977
- this.notify({ type: "removed", mutation });
1978
- }
1979
- canRun(mutation) {
1980
- const scope = scopeFor(mutation);
1981
- if (typeof scope === "string") {
1982
- const mutationsWithSameScope = this.#scopes.get(scope);
1983
- const firstPendingMutation = mutationsWithSameScope?.find(
1984
- (m) => m.state.status === "pending"
1985
- );
1986
- return !firstPendingMutation || firstPendingMutation === mutation;
1987
- } else {
1988
- return true;
1989
- }
1990
- }
1991
- runNext(mutation) {
1992
- const scope = scopeFor(mutation);
1993
- if (typeof scope === "string") {
1994
- const foundMutation = this.#scopes.get(scope)?.find((m) => m !== mutation && m.state.isPaused);
1995
- return foundMutation?.continue() ?? Promise.resolve();
1996
- } else {
1997
- return Promise.resolve();
1998
- }
1999
- }
2000
- clear() {
2001
- notifyManager.batch(() => {
2002
- this.#mutations.forEach((mutation) => {
2003
- this.notify({ type: "removed", mutation });
2004
- });
2005
- this.#mutations.clear();
2006
- this.#scopes.clear();
2007
- });
2008
- }
2009
- getAll() {
2010
- return Array.from(this.#mutations);
2011
- }
2012
- find(filters) {
2013
- const defaultedFilters = { exact: true, ...filters };
2014
- return this.getAll().find(
2015
- (mutation) => matchMutation(defaultedFilters, mutation)
2016
- );
2017
- }
2018
- findAll(filters = {}) {
2019
- return this.getAll().filter((mutation) => matchMutation(filters, mutation));
2020
- }
2021
- notify(event) {
2022
- notifyManager.batch(() => {
2023
- this.listeners.forEach((listener) => {
2024
- listener(event);
2025
- });
2026
- });
2027
- }
2028
- resumePausedMutations() {
2029
- const pausedMutations = this.getAll().filter((x) => x.state.isPaused);
2030
- return notifyManager.batch(
2031
- () => Promise.all(
2032
- pausedMutations.map((mutation) => mutation.continue().catch(noop))
2033
- )
2034
- );
2035
- }
2036
- };
2037
- function scopeFor(mutation) {
2038
- return mutation.options.scope?.id;
2039
- }
2040
- var MutationObserver = class extends Subscribable {
2041
- #client;
2042
- #currentResult = void 0;
2043
- #currentMutation;
2044
- #mutateOptions;
2045
- constructor(client, options) {
2046
- super();
2047
- this.#client = client;
2048
- this.setOptions(options);
2049
- this.bindMethods();
2050
- this.#updateResult();
2051
- }
2052
- bindMethods() {
2053
- this.mutate = this.mutate.bind(this);
2054
- this.reset = this.reset.bind(this);
2055
- }
2056
- setOptions(options) {
2057
- const prevOptions = this.options;
2058
- this.options = this.#client.defaultMutationOptions(options);
2059
- if (!shallowEqualObjects(this.options, prevOptions)) {
2060
- this.#client.getMutationCache().notify({
2061
- type: "observerOptionsUpdated",
2062
- mutation: this.#currentMutation,
2063
- observer: this
2064
- });
2065
- }
2066
- if (prevOptions?.mutationKey && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) {
2067
- this.reset();
2068
- } else if (this.#currentMutation?.state.status === "pending") {
2069
- this.#currentMutation.setOptions(this.options);
2070
- }
2071
- }
2072
- onUnsubscribe() {
2073
- if (!this.hasListeners()) {
2074
- this.#currentMutation?.removeObserver(this);
2075
- }
2076
- }
2077
- onMutationUpdate(action) {
2078
- this.#updateResult();
2079
- this.#notify(action);
2080
- }
2081
- getCurrentResult() {
2082
- return this.#currentResult;
2083
- }
2084
- reset() {
2085
- this.#currentMutation?.removeObserver(this);
2086
- this.#currentMutation = void 0;
2087
- this.#updateResult();
2088
- this.#notify();
2089
- }
2090
- mutate(variables, options) {
2091
- this.#mutateOptions = options;
2092
- this.#currentMutation?.removeObserver(this);
2093
- this.#currentMutation = this.#client.getMutationCache().build(this.#client, this.options);
2094
- this.#currentMutation.addObserver(this);
2095
- return this.#currentMutation.execute(variables);
2096
- }
2097
- #updateResult() {
2098
- const state = this.#currentMutation?.state ?? getDefaultState();
2099
- this.#currentResult = {
2100
- ...state,
2101
- isPending: state.status === "pending",
2102
- isSuccess: state.status === "success",
2103
- isError: state.status === "error",
2104
- isIdle: state.status === "idle",
2105
- mutate: this.mutate,
2106
- reset: this.reset
2107
- };
2108
- }
2109
- #notify(action) {
2110
- notifyManager.batch(() => {
2111
- if (this.#mutateOptions && this.hasListeners()) {
2112
- const variables = this.#currentResult.variables;
2113
- const onMutateResult = this.#currentResult.context;
2114
- const context = {
2115
- client: this.#client,
2116
- meta: this.options.meta,
2117
- mutationKey: this.options.mutationKey
2118
- };
2119
- if (action?.type === "success") {
2120
- try {
2121
- this.#mutateOptions.onSuccess?.(
2122
- action.data,
2123
- variables,
2124
- onMutateResult,
2125
- context
2126
- );
2127
- } catch (e) {
2128
- void Promise.reject(e);
2129
- }
2130
- try {
2131
- this.#mutateOptions.onSettled?.(
2132
- action.data,
2133
- null,
2134
- variables,
2135
- onMutateResult,
2136
- context
2137
- );
2138
- } catch (e) {
2139
- void Promise.reject(e);
2140
- }
2141
- } else if (action?.type === "error") {
2142
- try {
2143
- this.#mutateOptions.onError?.(
2144
- action.error,
2145
- variables,
2146
- onMutateResult,
2147
- context
2148
- );
2149
- } catch (e) {
2150
- void Promise.reject(e);
2151
- }
2152
- try {
2153
- this.#mutateOptions.onSettled?.(
2154
- void 0,
2155
- action.error,
2156
- variables,
2157
- onMutateResult,
2158
- context
2159
- );
2160
- } catch (e) {
2161
- void Promise.reject(e);
2162
- }
2163
- }
2164
- }
2165
- this.listeners.forEach((listener) => {
2166
- listener(this.#currentResult);
2167
- });
2168
- });
2169
- }
2170
- };
2171
- var QueryCache = class extends Subscribable {
2172
- constructor(config = {}) {
2173
- super();
2174
- this.config = config;
2175
- this.#queries = /* @__PURE__ */ new Map();
2176
- }
2177
- #queries;
2178
- build(client, options, state) {
2179
- const queryKey = options.queryKey;
2180
- const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);
2181
- let query = this.get(queryHash);
2182
- if (!query) {
2183
- query = new Query({
2184
- client,
2185
- queryKey,
2186
- queryHash,
2187
- options: client.defaultQueryOptions(options),
2188
- state,
2189
- defaultOptions: client.getQueryDefaults(queryKey)
2190
- });
2191
- this.add(query);
2192
- }
2193
- return query;
2194
- }
2195
- add(query) {
2196
- if (!this.#queries.has(query.queryHash)) {
2197
- this.#queries.set(query.queryHash, query);
2198
- this.notify({
2199
- type: "added",
2200
- query
2201
- });
2202
- }
2203
- }
2204
- remove(query) {
2205
- const queryInMap = this.#queries.get(query.queryHash);
2206
- if (queryInMap) {
2207
- query.destroy();
2208
- if (queryInMap === query) {
2209
- this.#queries.delete(query.queryHash);
2210
- }
2211
- this.notify({ type: "removed", query });
2212
- }
2213
- }
2214
- clear() {
2215
- notifyManager.batch(() => {
2216
- this.getAll().forEach((query) => {
2217
- this.remove(query);
2218
- });
2219
- });
2220
- }
2221
- get(queryHash) {
2222
- return this.#queries.get(queryHash);
2223
- }
2224
- getAll() {
2225
- return [...this.#queries.values()];
2226
- }
2227
- find(filters) {
2228
- const defaultedFilters = { exact: true, ...filters };
2229
- return this.getAll().find(
2230
- (query) => matchQuery(defaultedFilters, query)
2231
- );
2232
- }
2233
- findAll(filters = {}) {
2234
- const queries = this.getAll();
2235
- return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries;
2236
- }
2237
- notify(event) {
2238
- notifyManager.batch(() => {
2239
- this.listeners.forEach((listener) => {
2240
- listener(event);
2241
- });
2242
- });
2243
- }
2244
- onFocus() {
2245
- notifyManager.batch(() => {
2246
- this.getAll().forEach((query) => {
2247
- query.onFocus();
2248
- });
2249
- });
2250
- }
2251
- onOnline() {
2252
- notifyManager.batch(() => {
2253
- this.getAll().forEach((query) => {
2254
- query.onOnline();
2255
- });
2256
- });
2257
- }
2258
- };
2259
- var QueryClient = class {
2260
- #queryCache;
2261
- #mutationCache;
2262
- #defaultOptions;
2263
- #queryDefaults;
2264
- #mutationDefaults;
2265
- #mountCount;
2266
- #unsubscribeFocus;
2267
- #unsubscribeOnline;
2268
- constructor(config = {}) {
2269
- this.#queryCache = config.queryCache || new QueryCache();
2270
- this.#mutationCache = config.mutationCache || new MutationCache();
2271
- this.#defaultOptions = config.defaultOptions || {};
2272
- this.#queryDefaults = /* @__PURE__ */ new Map();
2273
- this.#mutationDefaults = /* @__PURE__ */ new Map();
2274
- this.#mountCount = 0;
2275
- }
2276
- mount() {
2277
- this.#mountCount++;
2278
- if (this.#mountCount !== 1) return;
2279
- this.#unsubscribeFocus = focusManager.subscribe(async (focused) => {
2280
- if (focused) {
2281
- await this.resumePausedMutations();
2282
- this.#queryCache.onFocus();
2283
- }
2284
- });
2285
- this.#unsubscribeOnline = onlineManager.subscribe(async (online) => {
2286
- if (online) {
2287
- await this.resumePausedMutations();
2288
- this.#queryCache.onOnline();
2289
- }
2290
- });
2291
- }
2292
- unmount() {
2293
- this.#mountCount--;
2294
- if (this.#mountCount !== 0) return;
2295
- this.#unsubscribeFocus?.();
2296
- this.#unsubscribeFocus = void 0;
2297
- this.#unsubscribeOnline?.();
2298
- this.#unsubscribeOnline = void 0;
2299
- }
2300
- isFetching(filters) {
2301
- return this.#queryCache.findAll({ ...filters, fetchStatus: "fetching" }).length;
2302
- }
2303
- isMutating(filters) {
2304
- return this.#mutationCache.findAll({ ...filters, status: "pending" }).length;
2305
- }
2306
- /**
2307
- * Imperative (non-reactive) way to retrieve data for a QueryKey.
2308
- * Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates.
2309
- *
2310
- * Hint: Do not use this function inside a component, because it won't receive updates.
2311
- * Use `useQuery` to create a `QueryObserver` that subscribes to changes.
2312
- */
2313
- getQueryData(queryKey) {
2314
- const options = this.defaultQueryOptions({ queryKey });
2315
- return this.#queryCache.get(options.queryHash)?.state.data;
2316
- }
2317
- ensureQueryData(options) {
2318
- const defaultedOptions = this.defaultQueryOptions(options);
2319
- const query = this.#queryCache.build(this, defaultedOptions);
2320
- const cachedData = query.state.data;
2321
- if (cachedData === void 0) {
2322
- return this.fetchQuery(options);
2323
- }
2324
- if (options.revalidateIfStale && query.isStaleByTime(resolveStaleTime(defaultedOptions.staleTime, query))) {
2325
- void this.prefetchQuery(defaultedOptions);
2326
- }
2327
- return Promise.resolve(cachedData);
2328
- }
2329
- getQueriesData(filters) {
2330
- return this.#queryCache.findAll(filters).map(({ queryKey, state }) => {
2331
- const data = state.data;
2332
- return [queryKey, data];
2333
- });
2334
- }
2335
- setQueryData(queryKey, updater, options) {
2336
- const defaultedOptions = this.defaultQueryOptions({ queryKey });
2337
- const query = this.#queryCache.get(
2338
- defaultedOptions.queryHash
2339
- );
2340
- const prevData = query?.state.data;
2341
- const data = functionalUpdate(updater, prevData);
2342
- if (data === void 0) {
2343
- return void 0;
2344
- }
2345
- return this.#queryCache.build(this, defaultedOptions).setData(data, { ...options, manual: true });
2346
- }
2347
- setQueriesData(filters, updater, options) {
2348
- return notifyManager.batch(
2349
- () => this.#queryCache.findAll(filters).map(({ queryKey }) => [
2350
- queryKey,
2351
- this.setQueryData(queryKey, updater, options)
2352
- ])
2353
- );
2354
- }
2355
- getQueryState(queryKey) {
2356
- const options = this.defaultQueryOptions({ queryKey });
2357
- return this.#queryCache.get(
2358
- options.queryHash
2359
- )?.state;
2360
- }
2361
- removeQueries(filters) {
2362
- const queryCache = this.#queryCache;
2363
- notifyManager.batch(() => {
2364
- queryCache.findAll(filters).forEach((query) => {
2365
- queryCache.remove(query);
2366
- });
2367
- });
2368
- }
2369
- resetQueries(filters, options) {
2370
- const queryCache = this.#queryCache;
2371
- return notifyManager.batch(() => {
2372
- queryCache.findAll(filters).forEach((query) => {
2373
- query.reset();
2374
- });
2375
- return this.refetchQueries(
2376
- {
2377
- type: "active",
2378
- ...filters
2379
- },
2380
- options
2381
- );
2382
- });
2383
- }
2384
- cancelQueries(filters, cancelOptions = {}) {
2385
- const defaultedCancelOptions = { revert: true, ...cancelOptions };
2386
- const promises = notifyManager.batch(
2387
- () => this.#queryCache.findAll(filters).map((query) => query.cancel(defaultedCancelOptions))
2388
- );
2389
- return Promise.all(promises).then(noop).catch(noop);
2390
- }
2391
- invalidateQueries(filters, options = {}) {
2392
- return notifyManager.batch(() => {
2393
- this.#queryCache.findAll(filters).forEach((query) => {
2394
- query.invalidate();
2395
- });
2396
- if (filters?.refetchType === "none") {
2397
- return Promise.resolve();
2398
- }
2399
- return this.refetchQueries(
2400
- {
2401
- ...filters,
2402
- type: filters?.refetchType ?? filters?.type ?? "active"
2403
- },
2404
- options
2405
- );
2406
- });
2407
- }
2408
- refetchQueries(filters, options = {}) {
2409
- const fetchOptions = {
2410
- ...options,
2411
- cancelRefetch: options.cancelRefetch ?? true
2412
- };
2413
- const promises = notifyManager.batch(
2414
- () => this.#queryCache.findAll(filters).filter((query) => !query.isDisabled() && !query.isStatic()).map((query) => {
2415
- let promise = query.fetch(void 0, fetchOptions);
2416
- if (!fetchOptions.throwOnError) {
2417
- promise = promise.catch(noop);
2418
- }
2419
- return query.state.fetchStatus === "paused" ? Promise.resolve() : promise;
2420
- })
2421
- );
2422
- return Promise.all(promises).then(noop);
2423
- }
2424
- fetchQuery(options) {
2425
- const defaultedOptions = this.defaultQueryOptions(options);
2426
- if (defaultedOptions.retry === void 0) {
2427
- defaultedOptions.retry = false;
2428
- }
2429
- const query = this.#queryCache.build(this, defaultedOptions);
2430
- return query.isStaleByTime(
2431
- resolveStaleTime(defaultedOptions.staleTime, query)
2432
- ) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
2433
- }
2434
- prefetchQuery(options) {
2435
- return this.fetchQuery(options).then(noop).catch(noop);
2436
- }
2437
- fetchInfiniteQuery(options) {
2438
- options._type = "infinite";
2439
- return this.fetchQuery(options);
2440
- }
2441
- prefetchInfiniteQuery(options) {
2442
- return this.fetchInfiniteQuery(options).then(noop).catch(noop);
2443
- }
2444
- ensureInfiniteQueryData(options) {
2445
- options._type = "infinite";
2446
- return this.ensureQueryData(options);
2447
- }
2448
- resumePausedMutations() {
2449
- if (onlineManager.isOnline()) {
2450
- return this.#mutationCache.resumePausedMutations();
2451
- }
2452
- return Promise.resolve();
2453
- }
2454
- getQueryCache() {
2455
- return this.#queryCache;
2456
- }
2457
- getMutationCache() {
2458
- return this.#mutationCache;
2459
- }
2460
- getDefaultOptions() {
2461
- return this.#defaultOptions;
2462
- }
2463
- setDefaultOptions(options) {
2464
- this.#defaultOptions = options;
2465
- }
2466
- setQueryDefaults(queryKey, options) {
2467
- this.#queryDefaults.set(hashKey(queryKey), {
2468
- queryKey,
2469
- defaultOptions: options
2470
- });
2471
- }
2472
- getQueryDefaults(queryKey) {
2473
- const defaults = [...this.#queryDefaults.values()];
2474
- const result = {};
2475
- defaults.forEach((queryDefault) => {
2476
- if (partialMatchKey(queryKey, queryDefault.queryKey)) {
2477
- Object.assign(result, queryDefault.defaultOptions);
2478
- }
2479
- });
2480
- return result;
2481
- }
2482
- setMutationDefaults(mutationKey, options) {
2483
- this.#mutationDefaults.set(hashKey(mutationKey), {
2484
- mutationKey,
2485
- defaultOptions: options
2486
- });
2487
- }
2488
- getMutationDefaults(mutationKey) {
2489
- const defaults = [...this.#mutationDefaults.values()];
2490
- const result = {};
2491
- defaults.forEach((queryDefault) => {
2492
- if (partialMatchKey(mutationKey, queryDefault.mutationKey)) {
2493
- Object.assign(result, queryDefault.defaultOptions);
2494
- }
2495
- });
2496
- return result;
2497
- }
2498
- defaultQueryOptions(options) {
2499
- if (options._defaulted) {
2500
- return options;
2501
- }
2502
- const defaultedOptions = {
2503
- ...this.#defaultOptions.queries,
2504
- ...this.getQueryDefaults(options.queryKey),
2505
- ...options,
2506
- _defaulted: true
2507
- };
2508
- if (!defaultedOptions.queryHash) {
2509
- defaultedOptions.queryHash = hashQueryKeyByOptions(
2510
- defaultedOptions.queryKey,
2511
- defaultedOptions
2512
- );
2513
- }
2514
- if (defaultedOptions.refetchOnReconnect === void 0) {
2515
- defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== "always";
2516
- }
2517
- if (defaultedOptions.throwOnError === void 0) {
2518
- defaultedOptions.throwOnError = !!defaultedOptions.suspense;
2519
- }
2520
- if (!defaultedOptions.networkMode && defaultedOptions.persister) {
2521
- defaultedOptions.networkMode = "offlineFirst";
2522
- }
2523
- if (defaultedOptions.queryFn === skipToken) {
2524
- defaultedOptions.enabled = false;
2525
- }
2526
- return defaultedOptions;
2527
- }
2528
- defaultMutationOptions(options) {
2529
- if (options?._defaulted) {
2530
- return options;
2531
- }
2532
- return {
2533
- ...this.#defaultOptions.mutations,
2534
- ...options?.mutationKey && this.getMutationDefaults(options.mutationKey),
2535
- ...options,
2536
- _defaulted: true
2537
- };
2538
- }
2539
- clear() {
2540
- this.#queryCache.clear();
2541
- this.#mutationCache.clear();
2542
- }
2543
- };
2544
- export {
2545
- MutationObserver as M,
2546
- QueryObserver as Q,
2547
- noop as a,
2548
- QueryClient as b,
2549
- environmentManager as e,
2550
- notifyManager as n,
2551
- shouldThrowError as s
2552
- };