@coffre/ui 0.1.9 → 0.1.11

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 (168) hide show
  1. package/dist/client/_coffre/assets/account-BJAdDvZf.js +2 -0
  2. package/dist/client/_coffre/assets/account-D0jLpk5c.js +1 -0
  3. package/dist/client/_coffre/assets/affordances-Bq2-oUB5.js +1 -0
  4. package/dist/client/_coffre/assets/audit-C-pcBgKe.js +2 -0
  5. package/dist/client/_coffre/assets/audit-CHGlDeBB.js +1 -0
  6. package/dist/client/_coffre/assets/{auth.device--rDR2F8w.js → auth.device-BndOUjse.js} +1 -1
  7. package/dist/client/_coffre/assets/auth.device-CWHNQn9W.js +2 -0
  8. package/dist/client/_coffre/assets/directory-nDExpkAz.js +1 -0
  9. package/dist/client/_coffre/assets/dist-QVHMLatb.js +1 -0
  10. package/dist/client/_coffre/assets/globals-CKBoTlyH.css +1 -0
  11. package/dist/client/_coffre/assets/grants-CjoOnxzz.js +1 -0
  12. package/dist/client/_coffre/assets/icons-BQ27Ds9u.js +1 -0
  13. package/dist/client/_coffre/assets/index-CUGytaO3.js +12 -0
  14. package/dist/client/_coffre/assets/link-DP8SVWon.js +1 -0
  15. package/dist/client/_coffre/assets/login-CeaxDMcr.js +2 -0
  16. package/dist/client/_coffre/assets/login-DrMgvqZn.js +1 -0
  17. package/dist/client/_coffre/assets/offboarding-CNr_1tnl.js +1 -0
  18. package/dist/client/_coffre/assets/page-CGmvjSy4.js +1 -0
  19. package/dist/client/_coffre/assets/preload-helper-ClBkJ19f.js +1 -0
  20. package/dist/client/_coffre/assets/principal-page-DNLb_q_e.js +1 -0
  21. package/dist/client/_coffre/assets/projects._project._environment-CHzbboGp.js +3 -0
  22. package/dist/client/_coffre/assets/projects._project._environment-DDxu_HHD.js +2 -0
  23. package/dist/client/_coffre/assets/projects._project.index-CIAsjvg6.js +2 -0
  24. package/dist/client/_coffre/assets/projects._project.index-DZ9l6d-1.js +1 -0
  25. package/dist/client/_coffre/assets/projects.index-4eUXreE_.js +1 -0
  26. package/dist/client/_coffre/assets/row-state-ByET1OKX.js +1 -0
  27. package/dist/client/_coffre/assets/settings-D2zp1Ssu.js +1 -0
  28. package/dist/client/_coffre/assets/suspense-C7KwSnTG.js +1 -0
  29. package/dist/client/_coffre/assets/tokens._token-DWmbqzNk.js +2 -0
  30. package/dist/client/_coffre/assets/tokens._token-Dui_4KfS.js +1 -0
  31. package/dist/client/_coffre/assets/tokens.index-CSi5Wxwf.js +1 -0
  32. package/dist/client/_coffre/assets/ui-BdipqGpP.js +46 -0
  33. package/dist/client/_coffre/assets/unregistered-CA7B4C1m.js +1 -0
  34. package/dist/client/_coffre/assets/use-action-DRm9yVhV.js +1 -0
  35. package/dist/client/_coffre/assets/use-change-BRRMJocl.js +1 -0
  36. package/dist/client/_coffre/assets/use-shell-BMGlJ25Q.js +1 -0
  37. package/dist/client/_coffre/assets/useQuery-D__2KBOs.js +1 -0
  38. package/dist/client/_coffre/assets/useSuspenseQuery-CSXyDALB.js +1 -0
  39. package/dist/client/_coffre/assets/users._user-BkNrX7Qf.js +1 -0
  40. package/dist/client/_coffre/assets/users._user-jbSvtdOg.js +2 -0
  41. package/dist/client/_coffre/assets/users.index-CKnQ1G76.js +1 -0
  42. package/dist/server/.vite/manifest.json +343 -246
  43. package/dist/server/_coffre/assets/_tanstack-start-manifest_v-Dx-c3XVk.js +162 -0
  44. package/dist/server/_coffre/assets/{account-CZgVVZTf.js → account-BocTPU1J.js} +150 -117
  45. package/dist/server/_coffre/assets/{account-D7-ZAE2T.js → account-CL8hOGhO.js} +10 -24
  46. package/dist/server/_coffre/assets/{affordances-BNaXjMOb.js → affordances-CKANXDTG.js} +2 -22
  47. package/dist/server/_coffre/assets/{async-local-storage-C0cwgkEr.js → async-local-storage-C10uQtMM.js} +3 -2
  48. package/dist/server/_coffre/assets/{audit-BEbhtsEp.js → audit-Bcka4vA6.js} +46 -16
  49. package/dist/server/_coffre/assets/audit-CSRQYIhu.js +31 -0
  50. package/dist/server/_coffre/assets/{auth.device-w9N3FlNk.js → auth.device-CMcUISZY.js} +7 -5
  51. package/dist/server/_coffre/assets/{auth.device-CMR3csAI.js → auth.device-DqO0T-rU.js} +5 -5
  52. package/dist/server/_coffre/assets/{directory-Dr5X9TB5.js → directory-CyYx6Jx1.js} +87 -112
  53. package/dist/server/_coffre/assets/{use-action-DQUmeH-5.js → dist-CnnV3t2g.js} +3 -48
  54. package/dist/server/_coffre/assets/globals-CKBoTlyH.css +1 -0
  55. package/dist/server/_coffre/assets/grants-CRijabX0.js +158 -0
  56. package/dist/server/_coffre/assets/{page-BdnhpwvH.js → icons-Dy-5ccDF.js} +3 -196
  57. package/dist/server/_coffre/assets/lazyRouteComponent-CqBNCGuZ.js +480 -0
  58. package/dist/server/_coffre/assets/link-42ZWdjzZ.js +422 -0
  59. package/dist/server/_coffre/assets/{login-DUtCQju5.js → login-BI9tzJEy.js} +7 -5
  60. package/dist/server/_coffre/assets/{login-B2njIq_o.js → login-C-v88YwP.js} +2 -2
  61. package/dist/server/_coffre/assets/matchContext-qLfYbC6_.js +56 -0
  62. package/dist/server/_coffre/assets/{offboarding-DY5MarpG.js → offboarding-1H0LavTd.js} +6 -4
  63. package/dist/server/_coffre/assets/page-D_mO0-sn.js +3592 -0
  64. package/dist/server/_coffre/assets/{principal-page-SdG8_zcu.js → principal-page-DQDoXute.js} +51 -42
  65. package/dist/server/_coffre/assets/{projects._project._environment-CUS0VFUe.js → projects._project._environment-C-yVwC92.js} +168 -248
  66. package/dist/server/_coffre/assets/{projects._project._environment-BQIrmE3r.js → projects._project._environment-D_5R40of.js} +4 -11
  67. package/dist/server/_coffre/assets/{projects._project.index-D1NxvBtZ.js → projects._project.index-A2BImFIT.js} +134 -96
  68. package/dist/server/_coffre/assets/{projects._project.index-BjNdR4KC.js → projects._project.index-BPPKxKrt.js} +5 -4
  69. package/dist/server/_coffre/assets/{projects.index-BQDuuh6t.js → projects.index-543IsPzY.js} +62 -54
  70. package/dist/server/_coffre/assets/{react-dom-qCTiwGGR.js → react-dom-bBoJXlK2.js} +417 -51
  71. package/dist/server/_coffre/assets/{router-BUwZOXEH.js → router-CM3vK8QO.js} +376 -92
  72. package/dist/server/_coffre/assets/row-state-XBtDoIA4.js +117 -0
  73. package/dist/server/_coffre/assets/{settings-HOErM3pd.js → settings-BLVU74ym.js} +8 -6
  74. package/dist/server/_coffre/assets/suspense-CzYTwxOj.js +602 -0
  75. package/dist/server/_coffre/assets/tokens._token-B-hBgwBW.js +10 -0
  76. package/dist/server/_coffre/assets/{tokens._token-BZUArbzi.js → tokens._token-aubAUonP.js} +97 -79
  77. package/dist/server/_coffre/assets/{tokens.index-BReCgoV9.js → tokens.index-4D3jwp5v.js} +9 -6
  78. package/dist/server/_coffre/assets/{ui-D_slKpSF.js → ui-BI3Bf72q.js} +7 -836
  79. package/dist/server/_coffre/assets/{unregistered-Z17da4Rc.js → unregistered-CagDxMyw.js} +5 -3
  80. package/dist/server/_coffre/assets/use-action-tzBZvjjQ.js +47 -0
  81. package/dist/server/_coffre/assets/use-change-Dggqxy5y.js +1212 -0
  82. package/dist/server/_coffre/assets/use-shell-CwStDfzX.js +462 -0
  83. package/dist/server/_coffre/assets/useQuery-C6_dBjem.js +8 -0
  84. package/dist/server/_coffre/assets/{useStore-DWGPqzXR.js → useRouter-CaUSUNsw.js} +1 -420
  85. package/dist/server/_coffre/assets/useSuspenseQuery-BuapQt_P.js +117 -0
  86. package/dist/server/_coffre/assets/{users._user-DHTNhQ9o.js → users._user-137WNyxn.js} +4 -5
  87. package/dist/server/_coffre/assets/users._user-C252Iilj.js +10 -0
  88. package/dist/server/_coffre/assets/{users.index-Cfo3ODpX.js → users.index-DQHsfnal.js} +9 -6
  89. package/dist/server/index.js +6 -5
  90. package/package.json +5 -3
  91. package/src/components/directory.tsx +75 -104
  92. package/src/components/grants.tsx +60 -112
  93. package/src/components/principal-page.tsx +54 -67
  94. package/src/components/principal-picker.tsx +7 -16
  95. package/src/components/row-state.tsx +95 -0
  96. package/src/components/service-tokens.tsx +75 -64
  97. package/src/components/shell.tsx +1 -1
  98. package/src/components/syncs.tsx +42 -26
  99. package/src/lib/announce.ts +36 -0
  100. package/src/lib/changes.ts +498 -0
  101. package/src/lib/coffre.ts +3 -2
  102. package/src/lib/optimistic.ts +233 -0
  103. package/src/lib/queries.ts +393 -0
  104. package/src/lib/use-action.ts +20 -15
  105. package/src/lib/use-change.ts +42 -0
  106. package/src/lib/use-shell.ts +17 -0
  107. package/src/router.tsx +17 -9
  108. package/src/routes/__root.tsx +8 -38
  109. package/src/routes/account.tsx +163 -154
  110. package/src/routes/audit.tsx +51 -72
  111. package/src/routes/auth.device.tsx +4 -2
  112. package/src/routes/login.tsx +3 -2
  113. package/src/routes/projects.$project.$environment.tsx +226 -231
  114. package/src/routes/projects.$project.index.tsx +136 -118
  115. package/src/routes/projects.index.tsx +125 -145
  116. package/src/routes/settings.tsx +7 -7
  117. package/src/routes/tokens.$token.tsx +14 -17
  118. package/src/routes/tokens.index.tsx +8 -4
  119. package/src/routes/unregistered.tsx +3 -2
  120. package/src/routes/users.$user.tsx +4 -4
  121. package/src/routes/users.index.tsx +8 -4
  122. package/src/styles/globals.css +78 -1
  123. package/dist/client/_coffre/assets/account-C3rBPdu6.js +0 -2
  124. package/dist/client/_coffre/assets/account-J194gi6l.js +0 -1
  125. package/dist/client/_coffre/assets/affordances-CmoY-8Xf.js +0 -1
  126. package/dist/client/_coffre/assets/audit-BtI9em7Q.js +0 -2
  127. package/dist/client/_coffre/assets/audit-jURfT8Km.js +0 -1
  128. package/dist/client/_coffre/assets/auth.device-viDUwZRT.js +0 -2
  129. package/dist/client/_coffre/assets/coffre-CXkp3Efg.js +0 -1
  130. package/dist/client/_coffre/assets/directory-PEjdb8PS.js +0 -1
  131. package/dist/client/_coffre/assets/globals-Bh2x1gBM.css +0 -1
  132. package/dist/client/_coffre/assets/grants-4mSkXPU4.js +0 -1
  133. package/dist/client/_coffre/assets/index-CD7bvUCb.js +0 -12
  134. package/dist/client/_coffre/assets/login-C-wTm_t1.js +0 -2
  135. package/dist/client/_coffre/assets/login-CLLv1om9.js +0 -1
  136. package/dist/client/_coffre/assets/offboarding-DQ-56W0H.js +0 -1
  137. package/dist/client/_coffre/assets/page-DbSS7pYH.js +0 -1
  138. package/dist/client/_coffre/assets/preload-helper-DduCCcmc.js +0 -46
  139. package/dist/client/_coffre/assets/principal-page-DjH1cUyz.js +0 -1
  140. package/dist/client/_coffre/assets/projects._project._environment-BZnNvENc.js +0 -3
  141. package/dist/client/_coffre/assets/projects._project._environment-CLUpTvi-.js +0 -2
  142. package/dist/client/_coffre/assets/projects._project.index-CWXRo307.js +0 -2
  143. package/dist/client/_coffre/assets/projects._project.index-Dzgf95zv.js +0 -1
  144. package/dist/client/_coffre/assets/projects.index-BG8W91BX.js +0 -2
  145. package/dist/client/_coffre/assets/projects.index-N_kCFBMq.js +0 -1
  146. package/dist/client/_coffre/assets/settings-CNIY0--5.js +0 -1
  147. package/dist/client/_coffre/assets/settings-EimGqlQL.js +0 -2
  148. package/dist/client/_coffre/assets/tokens._token-CkU4dCwo.js +0 -1
  149. package/dist/client/_coffre/assets/tokens._token-Df2R8TF_.js +0 -2
  150. package/dist/client/_coffre/assets/tokens.index-CSf5Mlz8.js +0 -2
  151. package/dist/client/_coffre/assets/tokens.index-DtiWrKVq.js +0 -1
  152. package/dist/client/_coffre/assets/unregistered-D5go1AfR.js +0 -1
  153. package/dist/client/_coffre/assets/use-action-CUvWPRTx.js +0 -1
  154. package/dist/client/_coffre/assets/users._user-CImGVpYj.js +0 -1
  155. package/dist/client/_coffre/assets/users._user-D0JK911L.js +0 -2
  156. package/dist/client/_coffre/assets/users.index-B-7o0KBD.js +0 -1
  157. package/dist/client/_coffre/assets/users.index-BoFWF3mF.js +0 -2
  158. package/dist/server/_coffre/assets/_tanstack-start-manifest_v-CrnrBINO.js +0 -133
  159. package/dist/server/_coffre/assets/audit-wjpo1BWg.js +0 -74
  160. package/dist/server/_coffre/assets/coffre-DMs96kfX.js +0 -280
  161. package/dist/server/_coffre/assets/globals-Bh2x1gBM.css +0 -1
  162. package/dist/server/_coffre/assets/grants-C6UmWE8b.js +0 -243
  163. package/dist/server/_coffre/assets/projects.index-ha7jO4nC.js +0 -54
  164. package/dist/server/_coffre/assets/settings-Cy__khNA.js +0 -18
  165. package/dist/server/_coffre/assets/tokens._token-CmpmtfB_.js +0 -18
  166. package/dist/server/_coffre/assets/tokens.index-B5-4dD4C.js +0 -10
  167. package/dist/server/_coffre/assets/users._user-BKdSQhIg.js +0 -10
  168. package/dist/server/_coffre/assets/users.index-dMn0tlmc.js +0 -10
@@ -0,0 +1,3592 @@
1
+ import { r as require_jsx_runtime, t as useRouter } from "./useRouter-CaUSUNsw.js";
2
+ //#region ../client/dist/index.js
3
+ function initialValues(provider) {
4
+ return Object.fromEntries(provider.fields.map((field) => [field.name, field.type === "text" ? "" : field.initial]));
5
+ }
6
+ /** Whether the rest of the form makes the field meaningful. */
7
+ function isAsked(field, values) {
8
+ if (field.type === "options" || field.when === void 0) return true;
9
+ const picked = values[field.when.field];
10
+ const list = Array.isArray(picked) ? picked : [];
11
+ return list.length === field.when.is.length && field.when.is.every((value) => list.includes(value));
12
+ }
13
+ /** The label of the first required field left empty, or null when the form can be sent. */
14
+ function firstMissing(provider, values) {
15
+ for (const field of provider.fields) {
16
+ if (!isAsked(field, values)) continue;
17
+ const value = values[field.name];
18
+ if ((typeof value === "string" ? value.trim() === "" : (value ?? []).length === 0) && (field.type === "options" || field.optional !== true)) return field.label;
19
+ }
20
+ return null;
21
+ }
22
+ /**
23
+ * The provider's config. Text is trimmed, and an optional field left empty
24
+ * is left out rather than sent as "", which the server rightly refuses.
25
+ */
26
+ function configFromForm(provider, values) {
27
+ const config = {};
28
+ for (const field of provider.fields) {
29
+ if (!isAsked(field, values)) continue;
30
+ const value = values[field.name];
31
+ if (field.type === "options") {
32
+ const picked = Array.isArray(value) ? value : [];
33
+ config[field.name] = field.multiple ? picked : picked[0];
34
+ } else {
35
+ const text = typeof value === "string" ? value.trim() : "";
36
+ if (text !== "") config[field.name] = text;
37
+ }
38
+ }
39
+ return config;
40
+ }
41
+ /** The API's error shape, `{ error, message }`, with the HTTP status. */
42
+ var COFFRE_ERROR = Symbol.for("@coffre/client:CoffreError");
43
+ var CoffreError = class extends Error {
44
+ /**
45
+ * `@coffre/ui`'s prebuilt pages bundle a copy of this class, and a page is
46
+ * handed a client the server made with this package's. So `instanceof`
47
+ * asks for the mark every copy leaves, rather than for this copy's prototype.
48
+ */
49
+ static [Symbol.hasInstance](value) {
50
+ return typeof value === "object" && value !== null && COFFRE_ERROR in value;
51
+ }
52
+ [COFFRE_ERROR] = true;
53
+ status;
54
+ code;
55
+ /** The vault's own code when it refused: `no_grant`, `removed`, `bulk_limit`, ... */
56
+ reason;
57
+ constructor(status, code, message, reason) {
58
+ super(message);
59
+ this.name = "CoffreError";
60
+ this.status = status;
61
+ this.code = code;
62
+ this.reason = reason;
63
+ }
64
+ };
65
+ /** `market/prod/KEY` as route parameters. */
66
+ function place(path) {
67
+ const [project = "", environment = "", key = ""] = path.replace(/^\/+|\/+$/g, "").split("/");
68
+ return {
69
+ project,
70
+ environment,
71
+ key
72
+ };
73
+ }
74
+ function createClient(options) {
75
+ const origin = options.url.replace(/\/+$/, "");
76
+ const transport = options.transport ?? ((request) => fetch(request));
77
+ async function send(method, path, input) {
78
+ const url = new URL(`${origin}/api${path}`);
79
+ const headers = new Headers(await options.headers?.());
80
+ let body;
81
+ if (method === "GET") {
82
+ for (const [name, value] of Object.entries(input ?? {})) if (value !== void 0 && value !== null) url.searchParams.set(name, String(value));
83
+ } else if (input !== void 0) {
84
+ headers.set("content-type", "application/json");
85
+ body = JSON.stringify(input);
86
+ }
87
+ const response = await transport(new Request(url, {
88
+ method,
89
+ headers,
90
+ body
91
+ }));
92
+ const payload = await response.json().catch(() => null);
93
+ if (!response.ok) {
94
+ const error = payload;
95
+ throw new CoffreError(response.status, typeof error?.error === "string" ? error.error : "http_error", typeof error?.message === "string" ? error.message : `request failed with status ${response.status}`, typeof error?.reason === "string" ? error.reason : void 0);
96
+ }
97
+ return payload;
98
+ }
99
+ /** A route key and its parameters as a method and a path. */
100
+ function address(key, params) {
101
+ const [method, pattern] = key.split(" ");
102
+ return [method, pattern.replace(/:(\w+)/g, (_, name) => encodeURIComponent(params[name]))];
103
+ }
104
+ /** Any route by its key: `call('GET /secrets/:project/:environment', { project, environment })`. */
105
+ async function call(key, ...[params, input]) {
106
+ const [method, path] = address(key, params);
107
+ return await send(method, path, input);
108
+ }
109
+ return {
110
+ call,
111
+ /** How this instance signs people in. Answers anyone, signed in or not. */
112
+ auth: () => send("GET", "/auth", void 0),
113
+ /** Who I am, and every place I can reach. */
114
+ me: () => call("GET /me", {}),
115
+ projects: {
116
+ /** With their environments. */
117
+ list: () => call("GET /projects", {}),
118
+ create: (project, input) => call("PUT /projects/:project", { project }, input),
119
+ update: (project, patch) => call("PATCH /projects/:project", { project }, patch)
120
+ },
121
+ environments: {
122
+ create: (path, input) => call("PUT /projects/:project/:environment", place(path), input),
123
+ update: (path, patch) => call("PATCH /projects/:project/:environment", place(path), patch)
124
+ },
125
+ secrets: {
126
+ /** Keys, versions and who changed what; never values. */
127
+ list: (path) => call("GET /secrets/:project/:environment", place(path)),
128
+ /** Decrypts one secret, or every secret in an environment. Logged in your name. */
129
+ reveal: (path) => call("POST /reveals", {}, { path }),
130
+ /** One transaction, a version and an audit entry per key; `null` archives. */
131
+ set: (path, values) => call("PATCH /secrets/:project/:environment", place(path), values),
132
+ /**
133
+ * What `set` would do to each key, `added`, `changed`, `unchanged` or
134
+ * `archived`, and nothing else: no value comes back and nothing is
135
+ * written. Comparing opens the current values, logged as reads.
136
+ */
137
+ dryRun: (path, values) => {
138
+ const [method, route] = address("PATCH /secrets/:project/:environment", place(path));
139
+ return send(method, `${route}?dryRun=1`, values);
140
+ },
141
+ history: (path) => call("GET /secrets/:project/:environment/:key/versions", place(path)),
142
+ /** A new version holding the old one's value. */
143
+ restore: (path, version) => call("POST /secrets/:project/:environment/:key/restore", place(path), { version }),
144
+ rename: (path, key) => call("PATCH /secrets/:project/:environment/:key", place(path), { key }),
145
+ update: (path, patch) => call("PATCH /secrets/:project/:environment/:key", place(path), patch)
146
+ },
147
+ members: {
148
+ /** People and tokens, their role and their access; at a place, those who reach it. */
149
+ list: (path) => call("GET /members", {}, { path }),
150
+ /** What they hold, and what to rotate if they leave. */
151
+ get: (member) => call("GET /members/:member", { member }),
152
+ add: (member, input = {}) => call("PUT /members/:member", { member }, input),
153
+ /** Offboards; returns what to rotate. */
154
+ remove: (member) => call("DELETE /members/:member", { member })
155
+ },
156
+ tokens: {
157
+ list: (member) => call("GET /members/:member/tokens", { member }),
158
+ /** The value is in the answer, and only there. */
159
+ issue: (member, input) => call("POST /members/:member/tokens", { member }, input),
160
+ revoke: (member, id) => call("DELETE /members/:member/tokens/:id", {
161
+ member,
162
+ id
163
+ })
164
+ },
165
+ access: {
166
+ /** What they should hold at each place; the server applies the difference. `null` revokes. */
167
+ set: (member, access) => call("PATCH /access/:member", { member }, access) },
168
+ /** Where I am signed in. Only where coffre runs its own sign-in. */
169
+ sessions: {
170
+ list: () => call("GET /sessions", {}),
171
+ revoke: (id) => call("DELETE /sessions/:id", { id })
172
+ },
173
+ /** The accounts I sign in with. */
174
+ identities: {
175
+ list: () => call("GET /identities", {}),
176
+ unlink: (id) => call("DELETE /identities/:id", { id })
177
+ },
178
+ /** A `coffre login` waiting for someone to approve it, by the code it shows. */
179
+ deviceLogins: {
180
+ get: (code) => call("GET /device-logins/:code", { code }),
181
+ decide: (code, approve) => call("POST /device-logins/:code", { code }, { approve })
182
+ },
183
+ syncs: {
184
+ /** Where a sync can push on this instance, and what each asks for. */
185
+ providers: () => call("GET /syncs/providers", {}),
186
+ list: (path) => call("GET /syncs/:project/:environment", place(path)),
187
+ add: (path, input) => call("POST /syncs/:project/:environment", place(path), input),
188
+ update: (id, patch) => call("PATCH /syncs/by-id/:id", { id }, patch),
189
+ remove: (id) => call("DELETE /syncs/by-id/:id", { id }),
190
+ run: (id) => call("POST /syncs/by-id/:id/runs", { id })
191
+ },
192
+ audit: {
193
+ list: (query = {}) => call("GET /audit", {}, query),
194
+ verify: () => call("GET /audit/verification", {}),
195
+ /** What an escrowed key is checked against: public material, owners and root admins only. */
196
+ keys: () => call("GET /audit/keys", {})
197
+ }
198
+ };
199
+ }
200
+ /**
201
+ * What writing these entries (a parsed `.env` file) would do, from a dry run
202
+ * of the write: the server compares, so no value leaves it, and the values it
203
+ * opens to compare are logged as reads. `changes` is what to pass to
204
+ * `secrets.set`: the keys that differ, so an unchanged value does not become
205
+ * a new version.
206
+ */
207
+ async function planImport(coffre, path, entries) {
208
+ const values = Object.create(null);
209
+ for (const { key, value } of entries) values[key] = value;
210
+ const [listed, compared] = await Promise.allSettled([coffre.secrets.list(path), coffre.secrets.dryRun(path, { ...values })]);
211
+ if (listed.status === "rejected") throw listed.reason;
212
+ if (compared.status === "rejected") throw compared.reason;
213
+ const [{ keys }, dryRun] = [listed.value, compared.value];
214
+ const versions = new Map(keys.map((entry) => [entry.key, entry.version]));
215
+ const plan = [];
216
+ const changes = Object.create(null);
217
+ for (const [key, value] of Object.entries(values)) {
218
+ const action = dryRun.keys[key];
219
+ plan.push({
220
+ key,
221
+ action,
222
+ version: versions.get(key) ?? null
223
+ });
224
+ if (action !== "unchanged") changes[key] = value;
225
+ }
226
+ return {
227
+ plan,
228
+ changes: { ...changes }
229
+ };
230
+ }
231
+ //#endregion
232
+ //#region ../../node_modules/.pnpm/@tanstack+query-core@5.103.1/node_modules/@tanstack/query-core/build/modern/timeoutManager.js
233
+ var defaultTimeoutProvider = {
234
+ setTimeout: (callback, delay) => setTimeout(callback, delay),
235
+ clearTimeout: (timeoutId) => clearTimeout(timeoutId),
236
+ setInterval: (callback, delay) => setInterval(callback, delay),
237
+ clearInterval: (intervalId) => clearInterval(intervalId)
238
+ };
239
+ /**
240
+ * Allows customization of how timeouts are created.
241
+ *
242
+ * @tanstack/query-core makes liberal use of timeouts to implement `staleTime`
243
+ * and `gcTime`. The default TimeoutManager provider uses the platform's global
244
+ * `setTimeout` implementation, which is known to have scalability issues with
245
+ * thousands of timeouts on the event loop.
246
+ *
247
+ * If you hit this limitation, consider providing a custom TimeoutProvider that
248
+ * coalesces timeouts.
249
+ */
250
+ var TimeoutManager = class {
251
+ #provider = defaultTimeoutProvider;
252
+ #providerCalled = false;
253
+ /**
254
+ * `setTimeoutProvider` can be used to set a custom implementation of the
255
+ * `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval` functions,
256
+ * called a `TimeoutProvider`.
257
+ *
258
+ * This may be useful if you notice event loop performance issues with
259
+ * thousands of queries. A custom TimeoutProvider could also support timer
260
+ * delays longer than the global `setTimeout` maximum delay value of about
261
+ * 24 days.
262
+ *
263
+ * It is important to call `setTimeoutProvider` before creating a
264
+ * QueryClient or queries, so that the same provider is used consistently
265
+ * for all timers in the application, since different TimeoutProviders
266
+ * cannot cancel each others' timers.
267
+ *
268
+ * @example
269
+ * ```ts
270
+ * import { timeoutManager, QueryClient } from '@tanstack/query-core'
271
+ * import { CustomTimeoutProvider } from './CustomTimeoutProvider'
272
+ *
273
+ * timeoutManager.setTimeoutProvider(new CustomTimeoutProvider())
274
+ *
275
+ * export const queryClient = new QueryClient()
276
+ * ```
277
+ */
278
+ setTimeoutProvider(provider) {
279
+ this.#provider = provider;
280
+ }
281
+ /**
282
+ * `setTimeout` schedules a callback to run after approximately `delay`
283
+ * milliseconds, like the global `setTimeout` function. The callback can be
284
+ * canceled with `clearTimeout`.
285
+ *
286
+ * It returns a timer ID, which may be a number or an object that can be
287
+ * coerced to a number via `Symbol.toPrimitive`.
288
+ *
289
+ * @example
290
+ * ```ts
291
+ * import { timeoutManager } from '@tanstack/query-core'
292
+ *
293
+ * const timeoutId = timeoutManager.setTimeout(
294
+ * () => console.log('ran at:', new Date()),
295
+ * 1000,
296
+ * )
297
+ *
298
+ * const timeoutIdNumber: number = Number(timeoutId)
299
+ * ```
300
+ */
301
+ setTimeout(callback, delay) {
302
+ return this.#provider.setTimeout(callback, delay);
303
+ }
304
+ /**
305
+ * `clearTimeout` cancels a timeout callback scheduled with `setTimeout`,
306
+ * like the global `clearTimeout` function. It should be called with a
307
+ * timer ID returned by `setTimeout`.
308
+ *
309
+ * @example
310
+ * ```ts
311
+ * import { timeoutManager } from '@tanstack/query-core'
312
+ *
313
+ * const timeoutId = timeoutManager.setTimeout(
314
+ * () => console.log('ran at:', new Date()),
315
+ * 1000,
316
+ * )
317
+ *
318
+ * timeoutManager.clearTimeout(timeoutId)
319
+ * ```
320
+ */
321
+ clearTimeout(timeoutId) {
322
+ this.#provider.clearTimeout(timeoutId);
323
+ }
324
+ /**
325
+ * `setInterval` schedules a callback to be called approximately every
326
+ * `delay` milliseconds, like the global `setInterval` function.
327
+ *
328
+ * Like `setTimeout`, it returns a timer ID, which may be a number or an
329
+ * object that can be coerced to a number via `Symbol.toPrimitive`.
330
+ *
331
+ * @example
332
+ * ```ts
333
+ * import { timeoutManager } from '@tanstack/query-core'
334
+ *
335
+ * const intervalId = timeoutManager.setInterval(
336
+ * () => console.log('ran at:', new Date()),
337
+ * 1000,
338
+ * )
339
+ * ```
340
+ */
341
+ setInterval(callback, delay) {
342
+ return this.#provider.setInterval(callback, delay);
343
+ }
344
+ /**
345
+ * `clearInterval` can be used to cancel an interval, like the global
346
+ * `clearInterval` function. It should be called with an interval ID
347
+ * returned by `setInterval`.
348
+ *
349
+ * @example
350
+ * ```ts
351
+ * import { timeoutManager } from '@tanstack/query-core'
352
+ *
353
+ * const intervalId = timeoutManager.setInterval(
354
+ * () => console.log('ran at:', new Date()),
355
+ * 1000,
356
+ * )
357
+ *
358
+ * timeoutManager.clearInterval(intervalId)
359
+ * ```
360
+ */
361
+ clearInterval(intervalId) {
362
+ this.#provider.clearInterval(intervalId);
363
+ }
364
+ };
365
+ /**
366
+ * Singleton instance of {@link TimeoutManager}, used throughout TanStack Query to schedule and cancel timers.
367
+ */
368
+ var timeoutManager = new TimeoutManager();
369
+ /**
370
+ * In many cases code wants to delay to the next event loop tick; this is not
371
+ * mediated by {@link timeoutManager}.
372
+ *
373
+ * This function is provided to make auditing the `tanstack/query-core` for
374
+ * incorrect use of system `setTimeout` easier.
375
+ */
376
+ function systemSetTimeoutZero(callback) {
377
+ setTimeout(callback, 0);
378
+ }
379
+ //#endregion
380
+ //#region ../../node_modules/.pnpm/@tanstack+query-core@5.103.1/node_modules/@tanstack/query-core/build/modern/utils.js
381
+ /** @deprecated
382
+ * use `environmentManager.isServer()` instead.
383
+ */
384
+ var isServer$1 = typeof window === "undefined" || "Deno" in globalThis;
385
+ function noop() {}
386
+ function functionalUpdate(updater, input) {
387
+ return typeof updater === "function" ? updater(input) : updater;
388
+ }
389
+ function isValidTimeout(value) {
390
+ return typeof value === "number" && value >= 0 && value !== Infinity;
391
+ }
392
+ function timeUntilStale(updatedAt, staleTime) {
393
+ return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
394
+ }
395
+ function resolveQueryValue(value, query) {
396
+ return typeof value === "function" ? value(query) : value;
397
+ }
398
+ /**
399
+ * Checks whether a query matches the given {@link QueryFilters}.
400
+ * Every filter that is specified must match; filters that are left unspecified are ignored.
401
+ *
402
+ * @example
403
+ * ```ts
404
+ * const queryCache = queryClient.getQueryCache()
405
+ *
406
+ * const matchingQueries = queryCache
407
+ * .getAll()
408
+ * .filter((query) => matchQuery({ queryKey: ['posts'] }, query))
409
+ * ```
410
+ */
411
+ function matchQuery(filters, query) {
412
+ const { type = "all", exact, fetchStatus, predicate, queryKey, stale } = filters;
413
+ if (queryKey) {
414
+ if (exact) {
415
+ if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) return false;
416
+ } else if (!partialMatchKey(query.queryKey, queryKey)) return false;
417
+ }
418
+ if (type !== "all") {
419
+ const isActive = query.isActive();
420
+ if (type === "active" && !isActive) return false;
421
+ if (type === "inactive" && isActive) return false;
422
+ }
423
+ if (typeof stale === "boolean" && query.isStale() !== stale) return false;
424
+ if (fetchStatus && fetchStatus !== query.state.fetchStatus) return false;
425
+ if (predicate && !predicate(query)) return false;
426
+ return true;
427
+ }
428
+ /**
429
+ * Checks whether a mutation matches the given {@link MutationFilters}.
430
+ * Every filter that is specified must match; filters that are left unspecified are ignored.
431
+ * If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match.
432
+ *
433
+ * @example
434
+ * ```ts
435
+ * const mutationCache = queryClient.getMutationCache()
436
+ *
437
+ * const matchingMutations = mutationCache
438
+ * .getAll()
439
+ * .filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation))
440
+ * ```
441
+ */
442
+ function matchMutation(filters, mutation) {
443
+ const { exact, status, predicate, mutationKey } = filters;
444
+ if (mutationKey) {
445
+ if (!mutation.options.mutationKey) return false;
446
+ if (exact) {
447
+ if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) return false;
448
+ } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) return false;
449
+ }
450
+ if (status && mutation.state.status !== status) return false;
451
+ if (predicate && !predicate(mutation)) return false;
452
+ return true;
453
+ }
454
+ function hashQueryKeyByOptions(queryKey, options) {
455
+ return (options?.queryKeyHashFn || hashKey)(queryKey);
456
+ }
457
+ /**
458
+ * Default query & mutation keys hash function.
459
+ * Hashes the value into a stable hash.
460
+ *
461
+ * @example
462
+ * ```ts
463
+ * // Object keys are sorted, so key order doesn't affect the hash:
464
+ * hashKey(['todos', { page: 1, filter: 'done' }]) // === '["todos",{"filter":"done","page":1}]'
465
+ * ```
466
+ */
467
+ function hashKey(queryKey) {
468
+ return JSON.stringify(queryKey, (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
469
+ result[key] = val[key];
470
+ return result;
471
+ }, {}) : val);
472
+ }
473
+ function partialMatchKey(a, b) {
474
+ if (a === b) return true;
475
+ if (typeof a !== typeof b) return false;
476
+ if (a && b && typeof a === "object" && typeof b === "object") {
477
+ if (Array.isArray(a) && Array.isArray(b)) {
478
+ if (b.length > a.length) return false;
479
+ for (let i = 0; i < b.length; i++) if (!partialMatchKey(a[i], b[i])) return false;
480
+ return true;
481
+ }
482
+ const bKeys = Object.keys(b);
483
+ for (const key of bKeys) if (!partialMatchKey(a[key], b[key])) return false;
484
+ return true;
485
+ }
486
+ return false;
487
+ }
488
+ var hasOwn = Object.prototype.hasOwnProperty;
489
+ function replaceEqualDeep(a, b, depth = 0) {
490
+ if (a === b) return a;
491
+ if (depth > 500) return b;
492
+ const array = isPlainArray(a) && isPlainArray(b);
493
+ if (!array && !(isPlainObject(a) && isPlainObject(b))) return b;
494
+ const aSize = (array ? a : Object.keys(a)).length;
495
+ const bItems = array ? b : Object.keys(b);
496
+ const bSize = bItems.length;
497
+ const copy = array ? new Array(bSize) : {};
498
+ let equalItems = 0;
499
+ for (let i = 0; i < bSize; i++) {
500
+ const key = array ? i : bItems[i];
501
+ const aItem = a[key];
502
+ const bItem = b[key];
503
+ if (aItem === bItem) {
504
+ copy[key] = aItem;
505
+ if (array ? i < aSize : hasOwn.call(a, key)) equalItems++;
506
+ continue;
507
+ }
508
+ if (aItem === null || bItem === null || typeof aItem !== "object" || typeof bItem !== "object") {
509
+ copy[key] = bItem;
510
+ continue;
511
+ }
512
+ const v = replaceEqualDeep(aItem, bItem, depth + 1);
513
+ copy[key] = v;
514
+ if (v === aItem) equalItems++;
515
+ }
516
+ return aSize === bSize && equalItems === aSize ? a : copy;
517
+ }
518
+ /**
519
+ * Shallow compare objects.
520
+ */
521
+ function shallowEqualObjects(a, b) {
522
+ if (!b || Object.keys(a).length !== Object.keys(b).length) return false;
523
+ for (const key in a) if (a[key] !== b[key]) return false;
524
+ return true;
525
+ }
526
+ function isPlainArray(value) {
527
+ return Array.isArray(value) && value.length === Object.keys(value).length;
528
+ }
529
+ function isPlainObject(o) {
530
+ if (!hasObjectPrototype(o)) return false;
531
+ const objectPrototype = Object.getPrototypeOf(o);
532
+ const ctor = objectPrototype?.constructor;
533
+ if (ctor === void 0) return true;
534
+ if (typeof ctor !== "function") return false;
535
+ const prot = ctor.prototype;
536
+ if (!hasObjectPrototype(prot)) return false;
537
+ if (!prot.hasOwnProperty("isPrototypeOf")) return false;
538
+ if (objectPrototype !== Object.prototype) return false;
539
+ return true;
540
+ }
541
+ function hasObjectPrototype(o) {
542
+ return Object.prototype.toString.call(o) === "[object Object]";
543
+ }
544
+ function sleep(timeout) {
545
+ return new Promise((resolve) => {
546
+ timeoutManager.setTimeout(resolve, timeout);
547
+ });
548
+ }
549
+ function replaceData(prevData, data, options) {
550
+ if (typeof options.structuralSharing === "function") return options.structuralSharing(prevData, data);
551
+ else if (options.structuralSharing !== false) return replaceEqualDeep(prevData, data);
552
+ return data;
553
+ }
554
+ function addToEnd(items, item, max = 0) {
555
+ const newItems = [...items, item];
556
+ return max && newItems.length > max ? newItems.slice(1) : newItems;
557
+ }
558
+ function addToStart(items, item, max = 0) {
559
+ const newItems = [item, ...items];
560
+ return max && newItems.length > max ? newItems.slice(0, -1) : newItems;
561
+ }
562
+ /**
563
+ * Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent
564
+ * to `enabled: false`) while preserving full type inference for the query's data. Unlike `enabled: false`,
565
+ * a query disabled via `skipToken` cannot be triggered with `refetch`.
566
+ *
567
+ * @example
568
+ * ```ts
569
+ * new QueryObserver(queryClient, {
570
+ * queryKey: ['post', postId],
571
+ * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
572
+ * })
573
+ * ```
574
+ */
575
+ var skipToken = Symbol();
576
+ function ensureQueryFn(options, fetchOptions) {
577
+ if (!options.queryFn && fetchOptions?.initialPromise) return () => fetchOptions.initialPromise;
578
+ if (!options.queryFn || options.queryFn === skipToken) return () => Promise.reject(/* @__PURE__ */ new Error(`Missing queryFn: '${options.queryHash}'`));
579
+ return options.queryFn;
580
+ }
581
+ /**
582
+ * Resolves a `throwOnError` option to a boolean.
583
+ * If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller,
584
+ * additional context such as the query or mutation) and its result is returned, allowing the throwing
585
+ * behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined`
586
+ * resolves to `false`).
587
+ *
588
+ * @example
589
+ * ```ts
590
+ * const throwOnError =
591
+ * query.state.error && typeof options.throwOnError === 'function'
592
+ * ? shouldThrowError(options.throwOnError, [query.state.error, query])
593
+ * : options.throwOnError
594
+ * ```
595
+ */
596
+ function shouldThrowError(throwOnError, params) {
597
+ if (typeof throwOnError === "function") return throwOnError(...params);
598
+ return !!throwOnError;
599
+ }
600
+ function addConsumeAwareSignal(object, getSignal, onCancelled) {
601
+ let consumed = false;
602
+ let signal;
603
+ Object.defineProperty(object, "signal", {
604
+ enumerable: true,
605
+ get: () => {
606
+ signal ??= getSignal();
607
+ if (consumed) return signal;
608
+ consumed = true;
609
+ if (signal.aborted) onCancelled();
610
+ else signal.addEventListener("abort", onCancelled, { once: true });
611
+ return signal;
612
+ }
613
+ });
614
+ return object;
615
+ }
616
+ //#endregion
617
+ //#region ../../node_modules/.pnpm/@tanstack+query-core@5.103.1/node_modules/@tanstack/query-core/build/modern/environmentManager.js
618
+ var isServerFn = () => isServer$1;
619
+ /**
620
+ * Returns whether the current runtime should be treated as a server environment.
621
+ */
622
+ var isServer = () => isServerFn();
623
+ //#endregion
624
+ //#region ../../node_modules/.pnpm/@tanstack+query-core@5.103.1/node_modules/@tanstack/query-core/build/modern/subscribable.js
625
+ var Subscribable = class {
626
+ constructor() {
627
+ this.listeners = /* @__PURE__ */ new Set();
628
+ this.subscribe = this.subscribe.bind(this);
629
+ }
630
+ subscribe(listener) {
631
+ this.listeners.add(listener);
632
+ this.onSubscribe();
633
+ return () => {
634
+ this.listeners.delete(listener);
635
+ this.onUnsubscribe();
636
+ };
637
+ }
638
+ hasListeners() {
639
+ return this.listeners.size > 0;
640
+ }
641
+ onSubscribe() {}
642
+ onUnsubscribe() {}
643
+ };
644
+ //#endregion
645
+ //#region ../../node_modules/.pnpm/@tanstack+query-core@5.103.1/node_modules/@tanstack/query-core/build/modern/focusManager.js
646
+ /**
647
+ * The `FocusManager` manages the focus state within TanStack Query.
648
+ *
649
+ * It can be used to change the default event listeners or to manually change the focus state.
650
+ */
651
+ var FocusManager = class extends Subscribable {
652
+ #focused;
653
+ #cleanup;
654
+ #setup;
655
+ constructor() {
656
+ super();
657
+ this.#setup = (onFocus) => {
658
+ if (typeof window !== "undefined" && window.addEventListener) {
659
+ const listener = () => onFocus();
660
+ window.addEventListener("visibilitychange", listener, false);
661
+ return () => {
662
+ window.removeEventListener("visibilitychange", listener);
663
+ };
664
+ }
665
+ };
666
+ }
667
+ onSubscribe() {
668
+ if (!this.#cleanup) this.setEventListener(this.#setup);
669
+ }
670
+ onUnsubscribe() {
671
+ if (!this.hasListeners()) {
672
+ this.#cleanup?.();
673
+ this.#cleanup = void 0;
674
+ }
675
+ }
676
+ /**
677
+ * `setEventListener` can be used to set a custom event listener that will
678
+ * be used to determine the focus state. The provided `setup` function
679
+ * receives a `setFocused` callback: call it with a `boolean` to manually
680
+ * set the focus state, or with no arguments to re-evaluate the current
681
+ * focus state and notify subscribers.
682
+ *
683
+ * @example
684
+ * ```ts
685
+ * import { focusManager } from '@tanstack/query-core'
686
+ *
687
+ * focusManager.setEventListener((handleFocus) => {
688
+ * const listener = () => handleFocus()
689
+ * // Listen to visibilitychange
690
+ * if (typeof window !== 'undefined' && window.addEventListener) {
691
+ * window.addEventListener('visibilitychange', listener, false)
692
+ * }
693
+ *
694
+ * return () => {
695
+ * // Be sure to unsubscribe if a new handler is set
696
+ * window.removeEventListener('visibilitychange', listener)
697
+ * }
698
+ * })
699
+ * ```
700
+ */
701
+ setEventListener(setup) {
702
+ this.#setup = setup;
703
+ this.#cleanup?.();
704
+ this.#cleanup = setup((focused) => {
705
+ if (typeof focused === "boolean") this.setFocused(focused);
706
+ else this.onFocus();
707
+ });
708
+ }
709
+ /**
710
+ * `setFocused` can be used to manually set the focus state. Set `undefined`
711
+ * to fall back to the default focus check.
712
+ *
713
+ * @example
714
+ * ```ts
715
+ * import { focusManager } from '@tanstack/query-core'
716
+ *
717
+ * // Set focused
718
+ * focusManager.setFocused(true)
719
+ *
720
+ * // Set unfocused
721
+ * focusManager.setFocused(false)
722
+ *
723
+ * // Fallback to the default focus check
724
+ * focusManager.setFocused(undefined)
725
+ * ```
726
+ */
727
+ setFocused(focused) {
728
+ if (this.#focused !== focused) {
729
+ this.#focused = focused;
730
+ this.onFocus();
731
+ }
732
+ }
733
+ /**
734
+ * `onFocus` notifies all subscribed listeners with the current focus state.
735
+ */
736
+ onFocus() {
737
+ const isFocused = this.isFocused();
738
+ this.listeners.forEach((listener) => {
739
+ listener(isFocused);
740
+ });
741
+ }
742
+ /**
743
+ * `isFocused` can be used to get the current focus state.
744
+ */
745
+ isFocused() {
746
+ if (typeof this.#focused === "boolean") return this.#focused;
747
+ return globalThis.document?.visibilityState !== "hidden";
748
+ }
749
+ };
750
+ /**
751
+ * Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query.
752
+ */
753
+ var focusManager = new FocusManager();
754
+ //#endregion
755
+ //#region ../../node_modules/.pnpm/@tanstack+query-core@5.103.1/node_modules/@tanstack/query-core/build/modern/notifyManager.js
756
+ /**
757
+ * Default scheduling function used by the notify manager.
758
+ * Schedules the callback with the system's `setTimeout(callback, 0)`.
759
+ */
760
+ var defaultScheduler = systemSetTimeoutZero;
761
+ function createNotifyManager() {
762
+ let queue = [];
763
+ let transactions = 0;
764
+ let notifyFn = (callback) => {
765
+ callback();
766
+ };
767
+ let batchNotifyFn = (callback) => {
768
+ callback();
769
+ };
770
+ let scheduleFn = defaultScheduler;
771
+ const schedule = (callback) => {
772
+ if (transactions) queue.push(callback);
773
+ else scheduleFn(() => {
774
+ notifyFn(callback);
775
+ });
776
+ };
777
+ const flush = () => {
778
+ const originalQueue = queue;
779
+ queue = [];
780
+ if (originalQueue.length) scheduleFn(() => {
781
+ batchNotifyFn(() => {
782
+ originalQueue.forEach((callback) => {
783
+ notifyFn(callback);
784
+ });
785
+ });
786
+ });
787
+ };
788
+ return {
789
+ /**
790
+ * Batches all updates scheduled inside the passed callback.
791
+ * This is mainly used internally to optimize query client updating.
792
+ * Batches can be nested; the queue is only flushed once the outermost `batch` call finishes.
793
+ * The return value of `callback` is passed through.
794
+ */
795
+ batch: (callback) => {
796
+ let result;
797
+ transactions++;
798
+ try {
799
+ result = callback();
800
+ } finally {
801
+ transactions--;
802
+ if (!transactions) flush();
803
+ }
804
+ return result;
805
+ },
806
+ /**
807
+ * All calls to the wrapped function will be batched.
808
+ */
809
+ batchCalls: (callback) => {
810
+ return (...args) => {
811
+ schedule(() => {
812
+ callback(...args);
813
+ });
814
+ };
815
+ },
816
+ /**
817
+ * Schedules a function to be run on the next batch.
818
+ * By default, the batch is run with a `setTimeout`, but this can be configured via `setScheduler`.
819
+ */
820
+ schedule,
821
+ /**
822
+ * Use this method to set a custom notify function.
823
+ * This can be used to for example wrap notifications with `React.act` while running tests.
824
+ */
825
+ setNotifyFunction: (fn) => {
826
+ notifyFn = fn;
827
+ },
828
+ /**
829
+ * Use this method to set a custom function to batch notifications together into a single tick.
830
+ * Framework adapters use this to plug in their own batching primitive, so that a single query
831
+ * update only triggers one re-render instead of one per subscriber.
832
+ *
833
+ * @example
834
+ * ```ts
835
+ * import { notifyManager } from '@tanstack/query-core'
836
+ * import { batch } from 'solid-js'
837
+ *
838
+ * notifyManager.setBatchNotifyFunction(batch)
839
+ * ```
840
+ */
841
+ setBatchNotifyFunction: (fn) => {
842
+ batchNotifyFn = fn;
843
+ },
844
+ /**
845
+ * Configures a custom callback that schedules when the next batch runs.
846
+ * The default behavior is `setTimeout(callback, 0)`.
847
+ *
848
+ * @example
849
+ * ```ts
850
+ * import { notifyManager } from '@tanstack/query-core'
851
+ *
852
+ * // Schedule batches in the next microtask
853
+ * notifyManager.setScheduler(queueMicrotask)
854
+ *
855
+ * // Schedule batches before the next frame is rendered
856
+ * notifyManager.setScheduler(requestAnimationFrame)
857
+ *
858
+ * // Schedule batches some time in the future
859
+ * notifyManager.setScheduler((cb) => setTimeout(cb, 10))
860
+ * ```
861
+ */
862
+ setScheduler: (fn) => {
863
+ scheduleFn = fn;
864
+ }
865
+ };
866
+ }
867
+ /**
868
+ * Handles scheduling and batching callbacks in TanStack Query.
869
+ */
870
+ var notifyManager = createNotifyManager();
871
+ //#endregion
872
+ //#region ../../node_modules/.pnpm/@tanstack+query-core@5.103.1/node_modules/@tanstack/query-core/build/modern/onlineManager.js
873
+ /**
874
+ * The `OnlineManager` manages the online state within TanStack Query. It can
875
+ * be used to change the default event listeners or to manually change the
876
+ * online state.
877
+ *
878
+ * By default, the `onlineManager` assumes an active network connection, and
879
+ * listens to the `online` and `offline` events on the `window` object to
880
+ * detect changes.
881
+ */
882
+ var OnlineManager = class extends Subscribable {
883
+ #online = true;
884
+ #cleanup;
885
+ #setup;
886
+ constructor() {
887
+ super();
888
+ this.#setup = (onOnline) => {
889
+ if (typeof window !== "undefined" && window.addEventListener) {
890
+ const onlineListener = () => onOnline(true);
891
+ const offlineListener = () => onOnline(false);
892
+ window.addEventListener("online", onlineListener, false);
893
+ window.addEventListener("offline", offlineListener, false);
894
+ return () => {
895
+ window.removeEventListener("online", onlineListener);
896
+ window.removeEventListener("offline", offlineListener);
897
+ };
898
+ }
899
+ };
900
+ }
901
+ onSubscribe() {
902
+ if (!this.#cleanup) this.setEventListener(this.#setup);
903
+ }
904
+ onUnsubscribe() {
905
+ if (!this.hasListeners()) {
906
+ this.#cleanup?.();
907
+ this.#cleanup = void 0;
908
+ }
909
+ }
910
+ /**
911
+ * `setEventListener` can be used to set a custom event listener that will
912
+ * be used to determine the online state. The provided `setup` function
913
+ * receives a `setOnline` callback that should be called with a `boolean`
914
+ * whenever the online state changes.
915
+ *
916
+ * @example
917
+ * ```ts
918
+ * import NetInfo from '@react-native-community/netinfo'
919
+ * import { onlineManager } from '@tanstack/query-core'
920
+ *
921
+ * onlineManager.setEventListener((setOnline) => {
922
+ * return NetInfo.addEventListener((state) => {
923
+ * setOnline(!!state.isConnected)
924
+ * })
925
+ * })
926
+ * ```
927
+ */
928
+ setEventListener(setup) {
929
+ this.#setup = setup;
930
+ this.#cleanup?.();
931
+ this.#cleanup = setup(this.setOnline.bind(this));
932
+ }
933
+ /**
934
+ * `setOnline` can be used to manually set the online state.
935
+ *
936
+ * @example
937
+ * ```ts
938
+ * import { onlineManager } from '@tanstack/query-core'
939
+ *
940
+ * // Set to online
941
+ * onlineManager.setOnline(true)
942
+ *
943
+ * // Set to offline
944
+ * onlineManager.setOnline(false)
945
+ * ```
946
+ */
947
+ setOnline(online) {
948
+ if (this.#online !== online) {
949
+ this.#online = online;
950
+ this.listeners.forEach((listener) => {
951
+ listener(online);
952
+ });
953
+ }
954
+ }
955
+ /**
956
+ * `isOnline` can be used to get the current online state.
957
+ */
958
+ isOnline() {
959
+ return this.#online;
960
+ }
961
+ };
962
+ /**
963
+ * Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.
964
+ */
965
+ var onlineManager = new OnlineManager();
966
+ //#endregion
967
+ //#region ../../node_modules/.pnpm/@tanstack+query-core@5.103.1/node_modules/@tanstack/query-core/build/modern/retryer.js
968
+ function defaultRetryDelay(failureCount) {
969
+ return Math.min(1e3 * 2 ** failureCount, 3e4);
970
+ }
971
+ function canFetch(networkMode) {
972
+ return (networkMode ?? "online") === "online" ? onlineManager.isOnline() : true;
973
+ }
974
+ /**
975
+ * The error thrown by a `Retryer` (and surfaced to `query.promise`/`mutation`) when a fetch is cancelled, e.g. via
976
+ * `query.cancel()`. `revert`, if `true`, tells the caller to restore the state the query was in before the fetch
977
+ * started instead of surfacing the error. `silent`, if `true`, tells the caller to suppress this error and instead
978
+ * resolve with the promise of the fetch that triggered the cancellation.
979
+ * @example
980
+ * ```ts
981
+ * query.cancel()
982
+ *
983
+ * try {
984
+ * await query.promise
985
+ * } catch (error) {
986
+ * if (error instanceof CancelledError) {
987
+ * // the fetch was cancelled, e.g. via `query.cancel()`
988
+ * }
989
+ * }
990
+ * ```
991
+ */
992
+ var CancelledError = class extends Error {
993
+ constructor(options) {
994
+ super("CancelledError");
995
+ this.revert = options?.revert;
996
+ this.silent = options?.silent;
997
+ }
998
+ };
999
+ function createRetryer(config) {
1000
+ let isRetryCancelled = false;
1001
+ let failureCount = 0;
1002
+ let continueFn;
1003
+ let status = "pending";
1004
+ let promiseResolve;
1005
+ let promiseReject;
1006
+ const promise = new Promise((resolve, reject) => {
1007
+ promiseResolve = resolve;
1008
+ promiseReject = reject;
1009
+ });
1010
+ promise.catch(noop);
1011
+ const isResolved = () => status !== "pending";
1012
+ const cancel = (cancelOptions) => {
1013
+ if (!isResolved()) {
1014
+ const error = new CancelledError(cancelOptions);
1015
+ reject(error);
1016
+ config.onCancel?.(error);
1017
+ }
1018
+ };
1019
+ const cancelRetry = () => {
1020
+ isRetryCancelled = true;
1021
+ };
1022
+ const continueRetry = () => {
1023
+ isRetryCancelled = false;
1024
+ };
1025
+ const canContinue = () => focusManager.isFocused() && (config.networkMode === "always" || onlineManager.isOnline()) && config.canRun();
1026
+ const canStart = () => canFetch(config.networkMode) && config.canRun();
1027
+ const resolve = (value) => {
1028
+ if (!isResolved()) {
1029
+ continueFn?.();
1030
+ status = "resolved";
1031
+ promiseResolve(value);
1032
+ }
1033
+ };
1034
+ const reject = (value) => {
1035
+ if (!isResolved()) {
1036
+ continueFn?.();
1037
+ status = "rejected";
1038
+ promiseReject(value);
1039
+ }
1040
+ };
1041
+ const pause = () => {
1042
+ return new Promise((continueResolve) => {
1043
+ continueFn = (value) => {
1044
+ if (isResolved() || canContinue()) continueResolve(value);
1045
+ };
1046
+ config.onPause?.();
1047
+ }).then(() => {
1048
+ continueFn = void 0;
1049
+ if (!isResolved()) config.onContinue?.();
1050
+ });
1051
+ };
1052
+ const run = () => {
1053
+ if (isResolved()) return;
1054
+ let promiseOrValue;
1055
+ const initialPromise = failureCount === 0 ? config.initialPromise : void 0;
1056
+ try {
1057
+ promiseOrValue = initialPromise ?? config.fn();
1058
+ } catch (error) {
1059
+ promiseOrValue = Promise.reject(error);
1060
+ }
1061
+ Promise.resolve(promiseOrValue).then(resolve).catch((error) => {
1062
+ if (isResolved()) return;
1063
+ const retry = config.retry ?? (isServer() ? 0 : 3);
1064
+ const retryDelay = config.retryDelay ?? defaultRetryDelay;
1065
+ const delay = typeof retryDelay === "function" ? retryDelay(failureCount, error) : retryDelay;
1066
+ const shouldRetry = retry === true || typeof retry === "number" && failureCount < retry || typeof retry === "function" && retry(failureCount, error);
1067
+ if (isRetryCancelled || !shouldRetry) {
1068
+ reject(error);
1069
+ return;
1070
+ }
1071
+ failureCount++;
1072
+ config.onFail?.(failureCount, error);
1073
+ sleep(delay).then(() => {
1074
+ return canContinue() ? void 0 : pause();
1075
+ }).then(() => {
1076
+ if (isRetryCancelled) reject(error);
1077
+ else run();
1078
+ });
1079
+ });
1080
+ };
1081
+ return {
1082
+ promise,
1083
+ status: () => status,
1084
+ cancel,
1085
+ continue: () => {
1086
+ continueFn?.();
1087
+ return promise;
1088
+ },
1089
+ cancelRetry,
1090
+ continueRetry,
1091
+ canStart,
1092
+ start: () => {
1093
+ if (canStart()) run();
1094
+ else pause().then(run);
1095
+ return promise;
1096
+ }
1097
+ };
1098
+ }
1099
+ //#endregion
1100
+ //#region ../../node_modules/.pnpm/@tanstack+query-core@5.103.1/node_modules/@tanstack/query-core/build/modern/removable.js
1101
+ var Removable = class {
1102
+ #gcTimeout;
1103
+ destroy() {
1104
+ this.clearGcTimeout();
1105
+ }
1106
+ scheduleGc() {
1107
+ this.clearGcTimeout();
1108
+ if (isValidTimeout(this.gcTime)) this.#gcTimeout = timeoutManager.setTimeout(() => {
1109
+ this.optionalRemove();
1110
+ }, this.gcTime);
1111
+ }
1112
+ updateGcTime(newGcTime) {
1113
+ this.gcTime = Math.max(this.gcTime || 0, newGcTime ?? (isServer() ? Infinity : 3e5));
1114
+ }
1115
+ clearGcTimeout() {
1116
+ if (this.#gcTimeout !== void 0) {
1117
+ timeoutManager.clearTimeout(this.#gcTimeout);
1118
+ this.#gcTimeout = void 0;
1119
+ }
1120
+ }
1121
+ };
1122
+ //#endregion
1123
+ //#region ../../node_modules/.pnpm/@tanstack+query-core@5.103.1/node_modules/@tanstack/query-core/build/modern/infiniteQueryBehavior.js
1124
+ function infiniteQueryBehavior(pages) {
1125
+ return { onFetch: (context, query) => {
1126
+ const options = context.options;
1127
+ const direction = context.fetchOptions?.meta?.fetchMore?.direction;
1128
+ const oldPages = context.state.data?.pages || [];
1129
+ const oldPageParams = context.state.data?.pageParams || [];
1130
+ let result = {
1131
+ pages: [],
1132
+ pageParams: []
1133
+ };
1134
+ let currentPage = 0;
1135
+ const fetchFn = async () => {
1136
+ let cancelled = false;
1137
+ const addSignalProperty = (object) => {
1138
+ addConsumeAwareSignal(object, () => context.signal, () => cancelled = true);
1139
+ };
1140
+ const queryFn = ensureQueryFn(context.options, context.fetchOptions);
1141
+ const fetchPage = async (data, param, previous) => {
1142
+ if (cancelled) return Promise.reject(context.signal.reason);
1143
+ if (param == null && data.pages.length) return Promise.resolve(data);
1144
+ const createQueryFnContext = () => {
1145
+ const queryFnContext = {
1146
+ client: context.client,
1147
+ queryKey: context.queryKey,
1148
+ pageParam: param,
1149
+ direction: previous ? "backward" : "forward",
1150
+ meta: context.options.meta
1151
+ };
1152
+ addSignalProperty(queryFnContext);
1153
+ return queryFnContext;
1154
+ };
1155
+ const queryFnContext = createQueryFnContext();
1156
+ const page = await queryFn(queryFnContext);
1157
+ const { maxPages } = context.options;
1158
+ const addTo = previous ? addToStart : addToEnd;
1159
+ return {
1160
+ pages: addTo(data.pages, page, maxPages),
1161
+ pageParams: addTo(data.pageParams, param, maxPages)
1162
+ };
1163
+ };
1164
+ if (direction && oldPages.length) {
1165
+ const previous = direction === "backward";
1166
+ const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
1167
+ const oldData = {
1168
+ pages: oldPages,
1169
+ pageParams: oldPageParams
1170
+ };
1171
+ result = await fetchPage(oldData, pageParamFn(options, oldData), previous);
1172
+ } else {
1173
+ const remainingPages = pages ?? oldPages.length;
1174
+ do {
1175
+ const param = currentPage === 0 ? oldPageParams[0] ?? options.initialPageParam : getNextPageParam(options, result);
1176
+ if (currentPage > 0 && param == null) break;
1177
+ result = await fetchPage(result, param);
1178
+ currentPage++;
1179
+ } while (currentPage < remainingPages);
1180
+ }
1181
+ return result;
1182
+ };
1183
+ if (context.options.persister) context.fetchFn = () => {
1184
+ return context.options.persister?.(fetchFn, {
1185
+ client: context.client,
1186
+ queryKey: context.queryKey,
1187
+ meta: context.options.meta,
1188
+ signal: context.signal
1189
+ }, query);
1190
+ };
1191
+ else context.fetchFn = fetchFn;
1192
+ } };
1193
+ }
1194
+ function getNextPageParam(options, { pages, pageParams }) {
1195
+ const lastIndex = pages.length - 1;
1196
+ return pages.length > 0 ? options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams) : void 0;
1197
+ }
1198
+ function getPreviousPageParam(options, { pages, pageParams }) {
1199
+ return pages.length > 0 ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams) : void 0;
1200
+ }
1201
+ //#endregion
1202
+ //#region ../../node_modules/.pnpm/@tanstack+query-core@5.103.1/node_modules/@tanstack/query-core/build/modern/query.js
1203
+ /**
1204
+ * Represents a single cached query. A `Query` holds the query's key, options,
1205
+ * state (data/error/status), and the observers currently subscribed to it.
1206
+ *
1207
+ * Instances are created and managed internally by `QueryCache`; application
1208
+ * code typically interacts with queries indirectly through `QueryClient` or
1209
+ * a framework hook like `useQuery`. Direct access to a `Query` instance is
1210
+ * possible via `queryCache.find()`/`findAll()` for inspecting cache state.
1211
+ *
1212
+ * @example
1213
+ * ```ts
1214
+ * const queryCache = queryClient.getQueryCache()
1215
+ * const query = queryCache.find({ queryKey: ['posts'] })
1216
+ *
1217
+ * if (query) {
1218
+ * console.log(query.state.dataUpdatedAt)
1219
+ * }
1220
+ * ```
1221
+ */
1222
+ var Query = class extends Removable {
1223
+ #queryType;
1224
+ #initialState;
1225
+ #revertState;
1226
+ #cache;
1227
+ #client;
1228
+ #retryer;
1229
+ #defaultOptions;
1230
+ #abortSignalConsumed;
1231
+ constructor(config) {
1232
+ super();
1233
+ this.#abortSignalConsumed = false;
1234
+ this.#defaultOptions = config.defaultOptions;
1235
+ this.setOptions(config.options);
1236
+ this.observers = [];
1237
+ this.#client = config.client;
1238
+ this.#cache = this.#client.getQueryCache();
1239
+ this.queryKey = config.queryKey;
1240
+ this.queryHash = config.queryHash;
1241
+ this.#initialState = getDefaultState$1(this.options);
1242
+ this.state = config.state ?? this.#initialState;
1243
+ this.scheduleGc();
1244
+ }
1245
+ /**
1246
+ * The `meta` object passed in the query's options, if any.
1247
+ */
1248
+ get meta() {
1249
+ return this.options.meta;
1250
+ }
1251
+ /** @internal */
1252
+ get queryType() {
1253
+ return this.#queryType;
1254
+ }
1255
+ /**
1256
+ * The promise for the currently in-flight fetch, if the query is fetching.
1257
+ * `undefined` when the query is not fetching.
1258
+ */
1259
+ get promise() {
1260
+ return this.#retryer?.promise;
1261
+ }
1262
+ /** @internal */
1263
+ setOptions(options) {
1264
+ this.options = {
1265
+ ...this.#defaultOptions,
1266
+ ...options
1267
+ };
1268
+ if (options?._type) this.#queryType = options._type;
1269
+ this.updateGcTime(this.options.gcTime);
1270
+ if (this.state && this.state.data === void 0) {
1271
+ const defaultState = getDefaultState$1(this.options);
1272
+ if (defaultState.data !== void 0) {
1273
+ this.setState(successState(defaultState.data, defaultState.dataUpdatedAt));
1274
+ this.#initialState = defaultState;
1275
+ }
1276
+ }
1277
+ }
1278
+ optionalRemove() {
1279
+ if (!this.observers.length && this.state.fetchStatus === "idle") this.#cache.remove(this);
1280
+ }
1281
+ /** @internal */
1282
+ setData(newData, options) {
1283
+ const data = replaceData(this.state.data, newData, this.options);
1284
+ this.#dispatch({
1285
+ data,
1286
+ type: "success",
1287
+ dataUpdatedAt: options?.updatedAt,
1288
+ manual: options?.manual
1289
+ });
1290
+ return data;
1291
+ }
1292
+ /**
1293
+ * Merges the given partial state directly into this query's state, notifying observers. Used
1294
+ * by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a
1295
+ * user manually trigger a loading/error state or edit the cached data.
1296
+ */
1297
+ setState(state) {
1298
+ this.#dispatch({
1299
+ type: "setState",
1300
+ state
1301
+ });
1302
+ }
1303
+ /**
1304
+ * Cancels the query's currently in-flight fetch, if any.
1305
+ * - Returns a promise that resolves once the cancellation has settled.
1306
+ * - If no fetch is in progress, resolves immediately.
1307
+ *
1308
+ * @example
1309
+ * ```ts
1310
+ * await query.cancel()
1311
+ * ```
1312
+ */
1313
+ cancel(options) {
1314
+ const promise = this.#retryer?.promise;
1315
+ this.#retryer?.cancel(options);
1316
+ return promise ? promise.then(noop).catch(noop) : Promise.resolve();
1317
+ }
1318
+ /**
1319
+ * Clears the query's garbage collection timeout and silently cancels any
1320
+ * in-flight fetch. Called by `QueryCache` when the query is removed from
1321
+ * the cache.
1322
+ *
1323
+ * @see {@link Query#cancel}
1324
+ */
1325
+ destroy() {
1326
+ super.destroy();
1327
+ this.cancel({ silent: true });
1328
+ }
1329
+ /** @internal */
1330
+ get resetState() {
1331
+ return this.#initialState;
1332
+ }
1333
+ /**
1334
+ * Resets the query back to its initial state (the state it had when it was
1335
+ * first created, e.g. any `initialData`), destroying it first to cancel any
1336
+ * in-flight fetch.
1337
+ */
1338
+ reset() {
1339
+ this.destroy();
1340
+ this.setState(this.resetState);
1341
+ }
1342
+ /**
1343
+ * Returns `true` if the query has at least one observer for which `enabled`
1344
+ * does not resolve to `false`.
1345
+ */
1346
+ isActive() {
1347
+ return this.observers.some((observer) => resolveQueryValue(observer.options.enabled, this) !== false);
1348
+ }
1349
+ /**
1350
+ * Returns `true` if the query is disabled, meaning it will not fetch
1351
+ * automatically.
1352
+ * - If the query has observers, it is disabled when none of them are active
1353
+ * (see `isActive`).
1354
+ * - If the query has no observers, it is disabled when its `queryFn` is
1355
+ * `skipToken` or it has never been fetched.
1356
+ */
1357
+ isDisabled() {
1358
+ if (this.getObserversCount() > 0) return !this.isActive();
1359
+ return this.options.queryFn === skipToken || !this.isFetched();
1360
+ }
1361
+ /**
1362
+ * Returns `true` if the query has been fetched, i.e. it has resolved with
1363
+ * either data or an error at least once.
1364
+ */
1365
+ isFetched() {
1366
+ return this.state.dataUpdateCount + this.state.errorUpdateCount > 0;
1367
+ }
1368
+ /**
1369
+ * Returns `true` if the query has at least one observer configured with
1370
+ * `staleTime: 'static'`, meaning it is treated as never stale.
1371
+ */
1372
+ isStatic() {
1373
+ if (this.getObserversCount() > 0) return this.observers.some((observer) => resolveQueryValue(observer.options.staleTime, this) === "static");
1374
+ return false;
1375
+ }
1376
+ /**
1377
+ * Returns `true` if the query is stale.
1378
+ * - If the query has observers, defers to whether any observer's current
1379
+ * result reports `isStale` (which accounts for each observer's own
1380
+ * `staleTime` and `enabled` state).
1381
+ * - If the query has no observers, it is considered stale when it has no
1382
+ * data or has been invalidated.
1383
+ *
1384
+ * @see {@link Query#isStaleByTime}
1385
+ * @example
1386
+ * ```ts
1387
+ * if (query.isStale()) {
1388
+ * // refetch or otherwise treat the cached data as outdated
1389
+ * }
1390
+ * ```
1391
+ */
1392
+ isStale() {
1393
+ if (this.getObserversCount() > 0) return this.observers.some((observer) => observer.getCurrentResult().isStale);
1394
+ return this.state.data === void 0 || this.state.isInvalidated;
1395
+ }
1396
+ /**
1397
+ * Returns `true` if the query's data is stale relative to the given
1398
+ * `staleTime` (defaults to `0`).
1399
+ * - A query with no data is always stale.
1400
+ * - `staleTime: 'static'` is never stale.
1401
+ * - An invalidated query is always stale.
1402
+ * - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`.
1403
+ *
1404
+ * @see {@link Query#isStale}
1405
+ * @example
1406
+ * ```ts
1407
+ * const isStale = query.isStaleByTime(1000 * 60)
1408
+ * ```
1409
+ */
1410
+ isStaleByTime(staleTime = 0) {
1411
+ if (this.state.data === void 0) return true;
1412
+ if (staleTime === "static") return false;
1413
+ if (this.state.isInvalidated) return true;
1414
+ return !timeUntilStale(this.state.dataUpdatedAt, staleTime);
1415
+ }
1416
+ /** @internal */
1417
+ onFocus() {
1418
+ this.observers.find((x) => x.shouldFetchOnWindowFocus())?.refetch({ cancelRefetch: false });
1419
+ this.#retryer?.continue();
1420
+ }
1421
+ /** @internal */
1422
+ onOnline() {
1423
+ this.observers.find((x) => x.shouldFetchOnReconnect())?.refetch({ cancelRefetch: false });
1424
+ this.#retryer?.continue();
1425
+ }
1426
+ /** @internal */
1427
+ addObserver(observer) {
1428
+ if (!this.observers.includes(observer)) {
1429
+ this.observers.push(observer);
1430
+ this.clearGcTimeout();
1431
+ this.#cache.notify({
1432
+ type: "observerAdded",
1433
+ query: this,
1434
+ observer
1435
+ });
1436
+ }
1437
+ }
1438
+ /** @internal */
1439
+ removeObserver(observer) {
1440
+ const index = this.observers.indexOf(observer);
1441
+ if (index !== -1) {
1442
+ this.observers.splice(index, 1);
1443
+ if (!this.observers.length) {
1444
+ if (this.#retryer) if (this.#abortSignalConsumed || this.state.fetchStatus === "paused" && this.state.status === "pending") this.#retryer.cancel({ revert: true });
1445
+ else this.#retryer.cancelRetry();
1446
+ this.scheduleGc();
1447
+ }
1448
+ this.#cache.notify({
1449
+ type: "observerRemoved",
1450
+ query: this,
1451
+ observer
1452
+ });
1453
+ }
1454
+ }
1455
+ /**
1456
+ * Returns the number of observers currently subscribed to this query.
1457
+ *
1458
+ * @example
1459
+ * ```ts
1460
+ * if (query.getObserversCount() === 0) {
1461
+ * // no component is currently watching this query
1462
+ * }
1463
+ * ```
1464
+ */
1465
+ getObserversCount() {
1466
+ return this.observers.length;
1467
+ }
1468
+ /**
1469
+ * Marks the query as invalidated, unless it is already invalidated. This
1470
+ * updates `state.isInvalidated` and notifies observers, but does not by
1471
+ * itself trigger a refetch.
1472
+ *
1473
+ * @example
1474
+ * ```ts
1475
+ * query.invalidate()
1476
+ * ```
1477
+ */
1478
+ invalidate() {
1479
+ if (!this.state.isInvalidated) this.#dispatch({ type: "invalidate" });
1480
+ }
1481
+ /**
1482
+ * Fetches the query, i.e. runs its `queryFn` (through any configured
1483
+ * retryer/behavior) and updates the query's state with the result.
1484
+ * - If a fetch is already in flight, returns its promise instead of
1485
+ * starting a new one, unless `fetchOptions.cancelRefetch` is set and the
1486
+ * query already has data, in which case the current fetch is silently
1487
+ * cancelled first.
1488
+ * - If `options` is passed, it replaces the query's current options
1489
+ * before fetching.
1490
+ */
1491
+ async fetch(options, fetchOptions) {
1492
+ if (this.state.fetchStatus !== "idle" && this.#retryer?.status() !== "rejected") {
1493
+ if (this.state.data !== void 0 && fetchOptions?.cancelRefetch) this.cancel({ silent: true });
1494
+ else if (this.#retryer) {
1495
+ this.#retryer.continueRetry();
1496
+ return this.#retryer.promise;
1497
+ }
1498
+ }
1499
+ if (options) this.setOptions(options);
1500
+ if (!this.options.queryFn) {
1501
+ const observer = this.observers.find((x) => x.options.queryFn);
1502
+ if (observer) this.setOptions(observer.options);
1503
+ }
1504
+ const abortController = new AbortController();
1505
+ const addSignalProperty = (object) => {
1506
+ Object.defineProperty(object, "signal", {
1507
+ enumerable: true,
1508
+ get: () => {
1509
+ this.#abortSignalConsumed = true;
1510
+ return abortController.signal;
1511
+ }
1512
+ });
1513
+ };
1514
+ const fetchFn = () => {
1515
+ const queryFn = ensureQueryFn(this.options, fetchOptions);
1516
+ const createQueryFnContext = () => {
1517
+ const queryFnContext = {
1518
+ client: this.#client,
1519
+ queryKey: this.queryKey,
1520
+ meta: this.meta
1521
+ };
1522
+ addSignalProperty(queryFnContext);
1523
+ return queryFnContext;
1524
+ };
1525
+ const queryFnContext = createQueryFnContext();
1526
+ this.#abortSignalConsumed = false;
1527
+ if (this.options.persister) return this.options.persister(queryFn, queryFnContext, this);
1528
+ return queryFn(queryFnContext);
1529
+ };
1530
+ const createFetchContext = () => {
1531
+ const context = {
1532
+ fetchOptions,
1533
+ options: this.options,
1534
+ queryKey: this.queryKey,
1535
+ client: this.#client,
1536
+ state: this.state,
1537
+ fetchFn
1538
+ };
1539
+ addSignalProperty(context);
1540
+ return context;
1541
+ };
1542
+ const context = createFetchContext();
1543
+ (this.#queryType === "infinite" ? infiniteQueryBehavior(this.options.pages) : this.options.behavior)?.onFetch(context, this);
1544
+ this.#revertState = this.state;
1545
+ if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== context.fetchOptions?.meta) this.#dispatch({
1546
+ type: "fetch",
1547
+ meta: context.fetchOptions?.meta
1548
+ });
1549
+ const retryer = this.#retryer = createRetryer({
1550
+ initialPromise: fetchOptions?.initialPromise,
1551
+ fn: context.fetchFn,
1552
+ onCancel: (error) => {
1553
+ if (error instanceof CancelledError && error.revert) this.setState({
1554
+ ...this.#revertState,
1555
+ fetchStatus: "idle"
1556
+ });
1557
+ abortController.abort();
1558
+ },
1559
+ onFail: (failureCount, error) => {
1560
+ this.#dispatch({
1561
+ type: "failed",
1562
+ failureCount,
1563
+ error
1564
+ });
1565
+ },
1566
+ onPause: () => {
1567
+ this.#dispatch({ type: "pause" });
1568
+ },
1569
+ onContinue: () => {
1570
+ this.#dispatch({ type: "continue" });
1571
+ },
1572
+ retry: context.options.retry,
1573
+ retryDelay: context.options.retryDelay,
1574
+ networkMode: context.options.networkMode,
1575
+ canRun: () => true
1576
+ });
1577
+ try {
1578
+ const data = await retryer.start();
1579
+ if (data === void 0) throw new Error(`${this.queryHash} data is undefined`);
1580
+ this.setData(data);
1581
+ this.#cache.config.onSuccess?.(data, this);
1582
+ this.#cache.config.onSettled?.(data, this.state.error, this);
1583
+ return data;
1584
+ } catch (error) {
1585
+ if (error instanceof CancelledError) {
1586
+ if (error.silent) return this.#retryer.promise;
1587
+ else if (error.revert) {
1588
+ if (this.state.data === void 0) throw error;
1589
+ return this.state.data;
1590
+ }
1591
+ }
1592
+ this.#dispatch({
1593
+ type: "error",
1594
+ error
1595
+ });
1596
+ this.#cache.config.onError?.(error, this);
1597
+ this.#cache.config.onSettled?.(this.state.data, error, this);
1598
+ throw error;
1599
+ } finally {
1600
+ if (this.#retryer === retryer) this.#retryer = void 0;
1601
+ this.scheduleGc();
1602
+ }
1603
+ }
1604
+ #dispatch(action) {
1605
+ const reducer = (state) => {
1606
+ switch (action.type) {
1607
+ case "failed": return {
1608
+ ...state,
1609
+ fetchFailureCount: action.failureCount,
1610
+ fetchFailureReason: action.error
1611
+ };
1612
+ case "pause": return {
1613
+ ...state,
1614
+ fetchStatus: "paused"
1615
+ };
1616
+ case "continue": return {
1617
+ ...state,
1618
+ fetchStatus: "fetching"
1619
+ };
1620
+ case "fetch": return {
1621
+ ...state,
1622
+ ...fetchState(state.data, this.options),
1623
+ fetchMeta: action.meta ?? null
1624
+ };
1625
+ case "success":
1626
+ const newState = {
1627
+ ...state,
1628
+ ...successState(action.data, action.dataUpdatedAt),
1629
+ dataUpdateCount: state.dataUpdateCount + 1,
1630
+ ...!action.manual && {
1631
+ fetchStatus: "idle",
1632
+ fetchFailureCount: 0,
1633
+ fetchFailureReason: null
1634
+ }
1635
+ };
1636
+ this.#revertState = action.manual ? newState : void 0;
1637
+ return newState;
1638
+ case "error":
1639
+ const error = action.error;
1640
+ return {
1641
+ ...state,
1642
+ error,
1643
+ errorUpdateCount: state.errorUpdateCount + 1,
1644
+ errorUpdatedAt: Date.now(),
1645
+ fetchFailureCount: state.fetchFailureCount + 1,
1646
+ fetchFailureReason: error,
1647
+ fetchStatus: "idle",
1648
+ status: "error",
1649
+ isInvalidated: true
1650
+ };
1651
+ case "invalidate": return {
1652
+ ...state,
1653
+ isInvalidated: true
1654
+ };
1655
+ case "setState": return {
1656
+ ...state,
1657
+ ...action.state
1658
+ };
1659
+ }
1660
+ };
1661
+ this.state = reducer(this.state);
1662
+ notifyManager.batch(() => {
1663
+ this.observers.slice().forEach((observer) => {
1664
+ observer.onQueryUpdate();
1665
+ });
1666
+ this.#cache.notify({
1667
+ query: this,
1668
+ type: "updated",
1669
+ action
1670
+ });
1671
+ });
1672
+ }
1673
+ };
1674
+ function fetchState(data, options) {
1675
+ return {
1676
+ fetchFailureCount: 0,
1677
+ fetchFailureReason: null,
1678
+ fetchStatus: canFetch(options.networkMode) ? "fetching" : "paused",
1679
+ ...data === void 0 && {
1680
+ error: null,
1681
+ status: "pending"
1682
+ }
1683
+ };
1684
+ }
1685
+ function successState(data, dataUpdatedAt) {
1686
+ return {
1687
+ data,
1688
+ dataUpdatedAt: dataUpdatedAt ?? Date.now(),
1689
+ error: null,
1690
+ isInvalidated: false,
1691
+ status: "success"
1692
+ };
1693
+ }
1694
+ function getDefaultState$1(options) {
1695
+ const data = typeof options.initialData === "function" ? options.initialData() : options.initialData;
1696
+ const hasData = data !== void 0;
1697
+ const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
1698
+ return {
1699
+ data,
1700
+ dataUpdateCount: 0,
1701
+ dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
1702
+ error: null,
1703
+ errorUpdateCount: 0,
1704
+ errorUpdatedAt: 0,
1705
+ fetchFailureCount: 0,
1706
+ fetchFailureReason: null,
1707
+ fetchMeta: null,
1708
+ isInvalidated: false,
1709
+ status: hasData ? "success" : "pending",
1710
+ fetchStatus: "idle"
1711
+ };
1712
+ }
1713
+ //#endregion
1714
+ //#region ../../node_modules/.pnpm/@tanstack+query-core@5.103.1/node_modules/@tanstack/query-core/build/modern/mutation.js
1715
+ /**
1716
+ * Represents a single mutation attempt. A `Mutation` holds the mutation's
1717
+ * options, state (data/error/status), and the `MutationObserver`s currently
1718
+ * subscribed to it.
1719
+ *
1720
+ * Instances are created and managed internally by `MutationCache`; application
1721
+ * code typically interacts with mutations indirectly through `QueryClient` or
1722
+ * a framework hook like `useMutation`. Direct access to a `Mutation` instance
1723
+ * is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.
1724
+ *
1725
+ * @example
1726
+ * ```ts
1727
+ * const mutationCache = queryClient.getMutationCache()
1728
+ *
1729
+ * const mutation = mutationCache.find({ mutationKey: ['addPost'] })
1730
+ * ```
1731
+ */
1732
+ var Mutation = class extends Removable {
1733
+ #client;
1734
+ #observers;
1735
+ #mutationCache;
1736
+ #retryer;
1737
+ constructor(config) {
1738
+ super();
1739
+ this.#client = config.client;
1740
+ this.mutationId = config.mutationId;
1741
+ this.#mutationCache = config.mutationCache;
1742
+ this.#observers = [];
1743
+ this.state = config.state || getDefaultState();
1744
+ this.setOptions(config.options);
1745
+ this.scheduleGc();
1746
+ }
1747
+ /** @internal */
1748
+ setOptions(options) {
1749
+ this.options = options;
1750
+ this.updateGcTime(this.options.gcTime);
1751
+ }
1752
+ /**
1753
+ * The `meta` object passed in the mutation's options, if any.
1754
+ */
1755
+ get meta() {
1756
+ return this.options.meta;
1757
+ }
1758
+ /** @internal */
1759
+ addObserver(observer) {
1760
+ if (!this.#observers.includes(observer)) {
1761
+ this.#observers.push(observer);
1762
+ this.clearGcTimeout();
1763
+ this.#mutationCache.notify({
1764
+ type: "observerAdded",
1765
+ mutation: this,
1766
+ observer
1767
+ });
1768
+ }
1769
+ }
1770
+ /** @internal */
1771
+ removeObserver(observer) {
1772
+ this.#observers = this.#observers.filter((x) => x !== observer);
1773
+ this.scheduleGc();
1774
+ this.#mutationCache.notify({
1775
+ type: "observerRemoved",
1776
+ mutation: this,
1777
+ observer
1778
+ });
1779
+ }
1780
+ optionalRemove() {
1781
+ if (!this.#observers.length) if (this.state.status === "pending") this.scheduleGc();
1782
+ else this.#mutationCache.remove(this);
1783
+ }
1784
+ /**
1785
+ * Resumes a mutation that is currently paused or was restored from a
1786
+ * dehydrated, still-`pending` state.
1787
+ *
1788
+ * - If this mutation has an active retryer (it paused mid-attempt, e.g. due
1789
+ * to the network mode or scope-based queuing), its retryer is resumed.
1790
+ * - Otherwise, if the mutation's status is still `pending` (e.g. it was
1791
+ * dehydrated while an attempt was in flight and never got a retryer in
1792
+ * this instance), `execute` is called again with the last known variables.
1793
+ * - Otherwise the mutation has already settled and this resolves immediately
1794
+ * without running anything again.
1795
+ *
1796
+ * @example
1797
+ * ```ts
1798
+ * // typically driven by reconnect handling, e.g. queryClient.resumePausedMutations()
1799
+ * const mutation = mutationCache.find({ mutationKey: ['addPost'] })
1800
+ * await mutation?.continue()
1801
+ * ```
1802
+ *
1803
+ * @see {@link Mutation#execute}
1804
+ */
1805
+ continue() {
1806
+ return this.#retryer?.continue() ?? (this.state.status === "pending" ? this.execute(this.state.variables) : Promise.resolve());
1807
+ }
1808
+ /**
1809
+ * Runs the mutation function for the given variables through a retryer, and
1810
+ * drives the mutation's state and lifecycle callbacks through to settlement.
1811
+ *
1812
+ * If this mutation's state is already `pending` when `execute` is called
1813
+ * (i.e. it was restored, still in-flight, from a dehydrated state), the
1814
+ * `onMutate` step is skipped and a `continue` action is dispatched to
1815
+ * unpause it; otherwise a `pending` action is dispatched first, then the
1816
+ * mutation cache's `onMutate` and the mutation's own `onMutate` option are
1817
+ * awaited in that order, and the resulting context is stored.
1818
+ *
1819
+ * The mutation function is then run (subject to `retry`/`retryDelay`/
1820
+ * `networkMode`, and to the mutation cache's scope-based serialization).
1821
+ * On success, the cache's `onSuccess`/`onSettled` callbacks run before the
1822
+ * mutation's own `onSuccess`/`onSettled` options, a `success` action is
1823
+ * dispatched, and the resolved data is returned. On failure, the same
1824
+ * cache-then-option ordering is used for `onError`/`onSettled`, but each of
1825
+ * those four callbacks is individually caught so that a throwing callback
1826
+ * cannot mask the original error; an `error` action is then dispatched and
1827
+ * the original error is re-thrown.
1828
+ *
1829
+ * @example
1830
+ * ```ts
1831
+ * // Called internally by `MutationObserver.mutate` and `Mutation.continue` —
1832
+ * // applications normally trigger mutations through those, not this method.
1833
+ * const data = await mutation.execute(variables)
1834
+ * ```
1835
+ *
1836
+ * @see {@link Mutation#continue}
1837
+ */
1838
+ async execute(variables) {
1839
+ const onContinue = () => {
1840
+ this.#dispatch({ type: "continue" });
1841
+ };
1842
+ const mutationFnContext = {
1843
+ client: this.#client,
1844
+ meta: this.options.meta,
1845
+ mutationKey: this.options.mutationKey
1846
+ };
1847
+ const retryer = this.#retryer = createRetryer({
1848
+ fn: () => {
1849
+ if (!this.options.mutationFn) return Promise.reject(/* @__PURE__ */ new Error("No mutationFn found"));
1850
+ return this.options.mutationFn(variables, mutationFnContext);
1851
+ },
1852
+ onFail: (failureCount, error) => {
1853
+ this.#dispatch({
1854
+ type: "failed",
1855
+ failureCount,
1856
+ error
1857
+ });
1858
+ },
1859
+ onPause: () => {
1860
+ this.#dispatch({ type: "pause" });
1861
+ },
1862
+ onContinue,
1863
+ retry: this.options.retry ?? 0,
1864
+ retryDelay: this.options.retryDelay,
1865
+ networkMode: this.options.networkMode,
1866
+ canRun: () => this.#mutationCache.canRun(this)
1867
+ });
1868
+ const restored = this.state.status === "pending";
1869
+ const isPaused = !retryer.canStart();
1870
+ try {
1871
+ if (restored) onContinue();
1872
+ else {
1873
+ this.#dispatch({
1874
+ type: "pending",
1875
+ variables,
1876
+ isPaused
1877
+ });
1878
+ if (this.#mutationCache.config.onMutate) await this.#mutationCache.config.onMutate(variables, this, mutationFnContext);
1879
+ const context = await this.options.onMutate?.(variables, mutationFnContext);
1880
+ if (context !== this.state.context) this.#dispatch({
1881
+ type: "pending",
1882
+ context,
1883
+ variables,
1884
+ isPaused
1885
+ });
1886
+ }
1887
+ const data = await retryer.start();
1888
+ await this.#mutationCache.config.onSuccess?.(data, variables, this.state.context, this, mutationFnContext);
1889
+ await this.options.onSuccess?.(data, variables, this.state.context, mutationFnContext);
1890
+ await this.#mutationCache.config.onSettled?.(data, null, this.state.variables, this.state.context, this, mutationFnContext);
1891
+ await this.options.onSettled?.(data, null, variables, this.state.context, mutationFnContext);
1892
+ this.#dispatch({
1893
+ type: "success",
1894
+ data
1895
+ });
1896
+ return data;
1897
+ } catch (error) {
1898
+ try {
1899
+ await this.#mutationCache.config.onError?.(error, variables, this.state.context, this, mutationFnContext);
1900
+ } catch (e) {
1901
+ Promise.reject(e);
1902
+ }
1903
+ try {
1904
+ await this.options.onError?.(error, variables, this.state.context, mutationFnContext);
1905
+ } catch (e) {
1906
+ Promise.reject(e);
1907
+ }
1908
+ try {
1909
+ await this.#mutationCache.config.onSettled?.(void 0, error, this.state.variables, this.state.context, this, mutationFnContext);
1910
+ } catch (e) {
1911
+ Promise.reject(e);
1912
+ }
1913
+ try {
1914
+ await this.options.onSettled?.(void 0, error, variables, this.state.context, mutationFnContext);
1915
+ } catch (e) {
1916
+ Promise.reject(e);
1917
+ }
1918
+ this.#dispatch({
1919
+ type: "error",
1920
+ error
1921
+ });
1922
+ throw error;
1923
+ } finally {
1924
+ if (this.#retryer === retryer) this.#retryer = void 0;
1925
+ this.#mutationCache.runNext(this);
1926
+ }
1927
+ }
1928
+ #dispatch(action) {
1929
+ const reducer = (state) => {
1930
+ switch (action.type) {
1931
+ case "failed": return {
1932
+ ...state,
1933
+ failureCount: action.failureCount,
1934
+ failureReason: action.error
1935
+ };
1936
+ case "pause": return {
1937
+ ...state,
1938
+ isPaused: true
1939
+ };
1940
+ case "continue": return {
1941
+ ...state,
1942
+ isPaused: false
1943
+ };
1944
+ case "pending": return {
1945
+ ...state,
1946
+ context: action.context,
1947
+ data: void 0,
1948
+ failureCount: 0,
1949
+ failureReason: null,
1950
+ error: null,
1951
+ isPaused: action.isPaused,
1952
+ status: "pending",
1953
+ variables: action.variables,
1954
+ submittedAt: Date.now()
1955
+ };
1956
+ case "success": return {
1957
+ ...state,
1958
+ data: action.data,
1959
+ failureCount: 0,
1960
+ failureReason: null,
1961
+ error: null,
1962
+ status: "success",
1963
+ isPaused: false
1964
+ };
1965
+ case "error": return {
1966
+ ...state,
1967
+ data: void 0,
1968
+ error: action.error,
1969
+ failureCount: state.failureCount + 1,
1970
+ failureReason: action.error,
1971
+ isPaused: false,
1972
+ status: "error"
1973
+ };
1974
+ }
1975
+ };
1976
+ this.state = reducer(this.state);
1977
+ notifyManager.batch(() => {
1978
+ this.#observers.forEach((observer) => {
1979
+ observer.onMutationUpdate(action);
1980
+ });
1981
+ this.#mutationCache.notify({
1982
+ mutation: this,
1983
+ type: "updated",
1984
+ action
1985
+ });
1986
+ });
1987
+ }
1988
+ };
1989
+ function getDefaultState() {
1990
+ return {
1991
+ context: void 0,
1992
+ data: void 0,
1993
+ error: null,
1994
+ failureCount: 0,
1995
+ failureReason: null,
1996
+ isPaused: false,
1997
+ status: "idle",
1998
+ variables: void 0,
1999
+ submittedAt: 0
2000
+ };
2001
+ }
2002
+ //#endregion
2003
+ //#region ../../node_modules/.pnpm/@tanstack+query-core@5.103.1/node_modules/@tanstack/query-core/build/modern/mutationCache.js
2004
+ /**
2005
+ * The `MutationCache` is the storage for mutations.
2006
+ *
2007
+ * Normally, you will not interact with the `MutationCache` directly and instead use a
2008
+ * `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of
2009
+ * safe/known updates to the cache, such as mutations being added, removed, or updated.
2010
+ *
2011
+ * @example
2012
+ * ```ts
2013
+ * const unsubscribe = mutationCache.subscribe((event) => {
2014
+ * console.log(event.type, event.mutation)
2015
+ * })
2016
+ * ```
2017
+ */
2018
+ var MutationCache = class extends Subscribable {
2019
+ #mutations;
2020
+ #scopes;
2021
+ #mutationId;
2022
+ constructor(config = {}) {
2023
+ super();
2024
+ this.config = config;
2025
+ this.#mutations = /* @__PURE__ */ new Set();
2026
+ this.#scopes = /* @__PURE__ */ new Map();
2027
+ this.#mutationId = 0;
2028
+ }
2029
+ /** @internal */
2030
+ build(client, options, state) {
2031
+ const mutation = new Mutation({
2032
+ client,
2033
+ mutationCache: this,
2034
+ mutationId: ++this.#mutationId,
2035
+ options: client.defaultMutationOptions(options),
2036
+ state
2037
+ });
2038
+ this.add(mutation);
2039
+ return mutation;
2040
+ }
2041
+ /** @internal */
2042
+ add(mutation) {
2043
+ this.#mutations.add(mutation);
2044
+ const scope = scopeFor(mutation);
2045
+ if (typeof scope === "string") {
2046
+ const scopedMutations = this.#scopes.get(scope);
2047
+ if (scopedMutations) scopedMutations.push(mutation);
2048
+ else this.#scopes.set(scope, [mutation]);
2049
+ }
2050
+ this.notify({
2051
+ type: "added",
2052
+ mutation
2053
+ });
2054
+ }
2055
+ /** @internal */
2056
+ remove(mutation) {
2057
+ if (this.#mutations.delete(mutation)) {
2058
+ const scope = scopeFor(mutation);
2059
+ if (typeof scope === "string") {
2060
+ const scopedMutations = this.#scopes.get(scope);
2061
+ if (scopedMutations) {
2062
+ if (scopedMutations.length > 1) {
2063
+ const index = scopedMutations.indexOf(mutation);
2064
+ if (index !== -1) scopedMutations.splice(index, 1);
2065
+ } else if (scopedMutations[0] === mutation) this.#scopes.delete(scope);
2066
+ }
2067
+ }
2068
+ }
2069
+ this.notify({
2070
+ type: "removed",
2071
+ mutation
2072
+ });
2073
+ }
2074
+ /** @internal */
2075
+ canRun(mutation) {
2076
+ const scope = scopeFor(mutation);
2077
+ if (typeof scope === "string") {
2078
+ const firstPendingMutation = this.#scopes.get(scope)?.find((m) => m.state.status === "pending");
2079
+ return !firstPendingMutation || firstPendingMutation === mutation;
2080
+ } else return true;
2081
+ }
2082
+ /** @internal */
2083
+ runNext(mutation) {
2084
+ const scope = scopeFor(mutation);
2085
+ if (typeof scope === "string") return (this.#scopes.get(scope)?.find((m) => m !== mutation && m.state.isPaused))?.continue() ?? Promise.resolve();
2086
+ else return Promise.resolve();
2087
+ }
2088
+ /**
2089
+ * Removes all mutations from the cache.
2090
+ *
2091
+ * @example
2092
+ * ```ts
2093
+ * const mutationCache = queryClient.getMutationCache()
2094
+ *
2095
+ * mutationCache.clear()
2096
+ * ```
2097
+ */
2098
+ clear() {
2099
+ notifyManager.batch(() => {
2100
+ this.#mutations.forEach((mutation) => {
2101
+ this.notify({
2102
+ type: "removed",
2103
+ mutation
2104
+ });
2105
+ });
2106
+ this.#mutations.clear();
2107
+ this.#scopes.clear();
2108
+ });
2109
+ }
2110
+ /**
2111
+ * Returns all mutations within the cache.
2112
+ *
2113
+ * This is not typically needed for most applications, but can come in handy when needing more
2114
+ * information about a mutation in rare scenarios.
2115
+ *
2116
+ * @example
2117
+ * ```ts
2118
+ * const mutationCache = queryClient.getMutationCache()
2119
+ *
2120
+ * const mutations = mutationCache.getAll()
2121
+ * ```
2122
+ */
2123
+ getAll() {
2124
+ return Array.from(this.#mutations);
2125
+ }
2126
+ /**
2127
+ * A slightly more advanced method that can be used to get an existing mutation instance from
2128
+ * the cache. If the mutation does not exist, `undefined` is returned.
2129
+ *
2130
+ * This is not typically needed for most applications, but can come in handy when needing more
2131
+ * information about a mutation in rare scenarios.
2132
+ *
2133
+ * @see {@link MutationCache#findAll}
2134
+ * @example
2135
+ * ```ts
2136
+ * const mutationCache = queryClient.getMutationCache()
2137
+ *
2138
+ * const mutation = mutationCache.find({ mutationKey: ['addPost'] })
2139
+ * ```
2140
+ */
2141
+ find(filters) {
2142
+ const defaultedFilters = {
2143
+ exact: true,
2144
+ ...filters
2145
+ };
2146
+ return this.getAll().find((mutation) => matchMutation(defaultedFilters, mutation));
2147
+ }
2148
+ /**
2149
+ * An even more advanced method that can be used to get existing mutation instances from the
2150
+ * cache that match the given filters. If no mutations match, an empty array is returned.
2151
+ *
2152
+ * This is not typically needed for most applications, but can come in handy when needing more
2153
+ * information about mutations in rare scenarios.
2154
+ *
2155
+ * @see {@link MutationCache#find}
2156
+ * @example
2157
+ * ```ts
2158
+ * const mutationCache = queryClient.getMutationCache()
2159
+ *
2160
+ * const mutations = mutationCache.findAll({ mutationKey: ['addPost'] })
2161
+ * ```
2162
+ */
2163
+ findAll(filters = {}) {
2164
+ return this.getAll().filter((mutation) => matchMutation(filters, mutation));
2165
+ }
2166
+ /** @internal */
2167
+ notify(event) {
2168
+ notifyManager.batch(() => {
2169
+ this.listeners.forEach((listener) => {
2170
+ listener(event);
2171
+ });
2172
+ });
2173
+ }
2174
+ /** @internal */
2175
+ resumePausedMutations() {
2176
+ const pausedMutations = this.getAll().filter((x) => x.state.isPaused);
2177
+ return notifyManager.batch(() => Promise.all(pausedMutations.map((mutation) => mutation.continue().catch(noop))));
2178
+ }
2179
+ };
2180
+ function scopeFor(mutation) {
2181
+ return mutation.options.scope?.id;
2182
+ }
2183
+ //#endregion
2184
+ //#region ../../node_modules/.pnpm/@tanstack+query-core@5.103.1/node_modules/@tanstack/query-core/build/modern/queryCache.js
2185
+ /**
2186
+ * The `QueryCache` is the storage mechanism for TanStack Query. It stores all the data, meta
2187
+ * information, and state of the queries it contains.
2188
+ *
2189
+ * Normally, you will not interact with the `QueryCache` directly and instead use a `QueryClient`
2190
+ * for a specific cache. You can subscribe to it (inherited from `Subscribable`) to be informed of
2191
+ * safe/known updates to the cache, such as queries being added, removed, or updated — updates made
2192
+ * outside of the cache's own tracked mechanisms (e.g. mutating a query's state object directly) do
2193
+ * not notify subscribers.
2194
+ *
2195
+ * @example
2196
+ * ```ts
2197
+ * const unsubscribe = queryCache.subscribe((event) => {
2198
+ * console.log(event.type, event.query)
2199
+ * })
2200
+ * ```
2201
+ */
2202
+ var QueryCache = class extends Subscribable {
2203
+ #queries;
2204
+ constructor(config = {}) {
2205
+ super();
2206
+ this.config = config;
2207
+ this.#queries = /* @__PURE__ */ new Map();
2208
+ }
2209
+ /**
2210
+ * Returns the existing `Query` instance for the given options' `queryKey`/`queryHash`, or
2211
+ * builds and adds a new one to the cache if none exists yet. Used by framework adapters and
2212
+ * plugins (e.g. broadcast/persistence) that need to get-or-create a `Query` directly, bypassing
2213
+ * the reactive `QueryObserver` machinery.
2214
+ *
2215
+ * @example
2216
+ * ```ts
2217
+ * const queryCache = queryClient.getQueryCache()
2218
+ *
2219
+ * const query = queryCache.build(queryClient, {
2220
+ * queryKey: ['posts'],
2221
+ * queryFn: fetchPosts,
2222
+ * })
2223
+ * ```
2224
+ */
2225
+ build(client, options, state) {
2226
+ const queryKey = options.queryKey;
2227
+ const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);
2228
+ let query = this.get(queryHash);
2229
+ if (!query) {
2230
+ query = new Query({
2231
+ client,
2232
+ queryKey,
2233
+ queryHash,
2234
+ options: client.defaultQueryOptions(options),
2235
+ state,
2236
+ defaultOptions: client.getQueryDefaults(queryKey)
2237
+ });
2238
+ this.add(query);
2239
+ }
2240
+ return query;
2241
+ }
2242
+ /** @internal */
2243
+ add(query) {
2244
+ if (!this.#queries.has(query.queryHash)) {
2245
+ this.#queries.set(query.queryHash, query);
2246
+ this.notify({
2247
+ type: "added",
2248
+ query
2249
+ });
2250
+ }
2251
+ }
2252
+ /**
2253
+ * Destroys the given `Query` and removes it from the cache, notifying subscribers with a
2254
+ * `'removed'` event. A no-op if the query is no longer the one currently stored under its hash
2255
+ * (e.g. it was already replaced). Used by plugins (e.g. the broadcast client) that mirror
2256
+ * removals across `QueryCache` instances.
2257
+ *
2258
+ * @example
2259
+ * ```ts
2260
+ * const queryCache = queryClient.getQueryCache()
2261
+ * const query = queryCache.find({ queryKey: ['posts'] })
2262
+ *
2263
+ * if (query) {
2264
+ * queryCache.remove(query)
2265
+ * }
2266
+ * ```
2267
+ */
2268
+ remove(query) {
2269
+ const queryInMap = this.#queries.get(query.queryHash);
2270
+ if (queryInMap) {
2271
+ query.destroy();
2272
+ if (queryInMap === query) this.#queries.delete(query.queryHash);
2273
+ this.notify({
2274
+ type: "removed",
2275
+ query
2276
+ });
2277
+ }
2278
+ }
2279
+ /**
2280
+ * Removes all queries from the cache.
2281
+ *
2282
+ * @example
2283
+ * ```ts
2284
+ * const queryCache = queryClient.getQueryCache()
2285
+ *
2286
+ * queryCache.clear()
2287
+ * ```
2288
+ */
2289
+ clear() {
2290
+ notifyManager.batch(() => {
2291
+ this.getAll().forEach((query) => {
2292
+ this.remove(query);
2293
+ });
2294
+ });
2295
+ }
2296
+ /**
2297
+ * Returns the `Query` instance stored under the given `queryHash`, or `undefined` if none
2298
+ * exists. Unlike {@link QueryCache#find}, this looks up by the already-computed hash rather
2299
+ * than by `QueryFilters`. Used by plugins (e.g. broadcast/hydration) that already have a hash
2300
+ * to look up directly.
2301
+ *
2302
+ * @example
2303
+ * ```ts
2304
+ * const queryCache = queryClient.getQueryCache()
2305
+ * const queryHash = hashKey(['posts'])
2306
+ *
2307
+ * const query = queryCache.get(queryHash)
2308
+ * ```
2309
+ */
2310
+ get(queryHash) {
2311
+ return this.#queries.get(queryHash);
2312
+ }
2313
+ /**
2314
+ * Returns all queries within the cache.
2315
+ *
2316
+ * @example
2317
+ * ```ts
2318
+ * const queryCache = queryClient.getQueryCache()
2319
+ *
2320
+ * const queries = queryCache.getAll()
2321
+ * ```
2322
+ */
2323
+ getAll() {
2324
+ return [...this.#queries.values()];
2325
+ }
2326
+ /**
2327
+ * A slightly more advanced method that can be used to get an existing query instance from the
2328
+ * cache. This instance not only contains all the state for the query, but all of the instances,
2329
+ * and underlying guts of the query as well. If the query does not exist, `undefined` is
2330
+ * returned.
2331
+ *
2332
+ * This is not typically needed for most applications, but can come in handy when needing more
2333
+ * information about a query in rare scenarios (e.g. looking at `query.state.dataUpdatedAt` to
2334
+ * decide whether a query is fresh enough to be used as an initial value).
2335
+ *
2336
+ * @see {@link QueryCache#findAll}
2337
+ * @example
2338
+ * ```ts
2339
+ * const queryCache = queryClient.getQueryCache()
2340
+ *
2341
+ * const query = queryCache.find({ queryKey: ['posts'] })
2342
+ * ```
2343
+ */
2344
+ find(filters) {
2345
+ const defaultedFilters = {
2346
+ exact: true,
2347
+ ...filters
2348
+ };
2349
+ return this.getAll().find((query) => matchQuery(defaultedFilters, query));
2350
+ }
2351
+ /**
2352
+ * An even more advanced method that can be used to get existing query instances from the cache
2353
+ * that partially match a query key. If no queries match, an empty array is returned.
2354
+ *
2355
+ * This is not typically needed for most applications, but can come in handy when needing more
2356
+ * information about queries in rare scenarios.
2357
+ *
2358
+ * @see {@link QueryCache#find}
2359
+ * @example
2360
+ * ```ts
2361
+ * const queryCache = queryClient.getQueryCache()
2362
+ *
2363
+ * const queries = queryCache.findAll({ queryKey: ['posts'] })
2364
+ * ```
2365
+ */
2366
+ findAll(filters = {}) {
2367
+ const queries = this.getAll();
2368
+ return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries;
2369
+ }
2370
+ /** @internal */
2371
+ notify(event) {
2372
+ notifyManager.batch(() => {
2373
+ this.listeners.forEach((listener) => {
2374
+ listener(event);
2375
+ });
2376
+ });
2377
+ }
2378
+ /** @internal */
2379
+ onFocus() {
2380
+ notifyManager.batch(() => {
2381
+ this.getAll().forEach((query) => {
2382
+ query.onFocus();
2383
+ });
2384
+ });
2385
+ }
2386
+ /** @internal */
2387
+ onOnline() {
2388
+ notifyManager.batch(() => {
2389
+ this.getAll().forEach((query) => {
2390
+ query.onOnline();
2391
+ });
2392
+ });
2393
+ }
2394
+ };
2395
+ //#endregion
2396
+ //#region ../../node_modules/.pnpm/@tanstack+query-core@5.103.1/node_modules/@tanstack/query-core/build/modern/queryClient.js
2397
+ /**
2398
+ * `QueryClient` is used to interact with a cache of queries and mutations. It owns a
2399
+ * `QueryCache` and a `MutationCache` (creating default ones if none are passed in) and holds
2400
+ * the default options that are applied to queries and mutations created through it.
2401
+ *
2402
+ * @example
2403
+ * ```ts
2404
+ * const queryClient = new QueryClient({
2405
+ * defaultOptions: {
2406
+ * queries: {
2407
+ * staleTime: Infinity,
2408
+ * },
2409
+ * },
2410
+ * })
2411
+ *
2412
+ * await queryClient.query({ queryKey: ['posts'], queryFn: fetchPosts })
2413
+ * ```
2414
+ */
2415
+ var QueryClient = class {
2416
+ #queryCache;
2417
+ #mutationCache;
2418
+ #defaultOptions;
2419
+ #queryDefaults;
2420
+ #mutationDefaults;
2421
+ #mountCount;
2422
+ #unsubscribeFocus;
2423
+ #unsubscribeOnline;
2424
+ constructor(config = {}) {
2425
+ this.#queryCache = config.queryCache || new QueryCache();
2426
+ this.#mutationCache = config.mutationCache || new MutationCache();
2427
+ this.#defaultOptions = config.defaultOptions || {};
2428
+ this.#queryDefaults = /* @__PURE__ */ new Map();
2429
+ this.#mutationDefaults = /* @__PURE__ */ new Map();
2430
+ this.#mountCount = 0;
2431
+ }
2432
+ /**
2433
+ * Called by a framework adapter's `QueryClientProvider`-equivalent when it mounts, to start
2434
+ * listening for focus/online events and resume paused mutations. Ref-counted via an internal
2435
+ * mount count, so nested or multiple providers sharing the same `QueryClient` don't tear down
2436
+ * the shared listeners until the last one unmounts.
2437
+ */
2438
+ mount() {
2439
+ this.#mountCount++;
2440
+ if (this.#mountCount !== 1) return;
2441
+ this.#unsubscribeFocus = focusManager.subscribe(async (focused) => {
2442
+ if (focused) {
2443
+ await this.resumePausedMutations();
2444
+ this.#queryCache.onFocus();
2445
+ }
2446
+ });
2447
+ this.#unsubscribeOnline = onlineManager.subscribe(async (online) => {
2448
+ if (online) {
2449
+ await this.resumePausedMutations();
2450
+ this.#queryCache.onOnline();
2451
+ }
2452
+ });
2453
+ }
2454
+ /**
2455
+ * The inverse of {@link QueryClient#mount} — called by a framework adapter's
2456
+ * `QueryClientProvider`-equivalent when it unmounts. Only tears down the focus/online
2457
+ * listeners once the mount count returns to `0`.
2458
+ */
2459
+ unmount() {
2460
+ this.#mountCount--;
2461
+ if (this.#mountCount !== 0) return;
2462
+ this.#unsubscribeFocus?.();
2463
+ this.#unsubscribeFocus = void 0;
2464
+ this.#unsubscribeOnline?.();
2465
+ this.#unsubscribeOnline = void 0;
2466
+ }
2467
+ /**
2468
+ * Returns the number of queries in the cache that are currently fetching, optionally
2469
+ * matching a set of filters. This includes background-fetching, loading new pages, and
2470
+ * loading more infinite query results.
2471
+ *
2472
+ * @example
2473
+ * ```ts
2474
+ * if (queryClient.isFetching()) {
2475
+ * console.log('At least one query is fetching!')
2476
+ * }
2477
+ * ```
2478
+ */
2479
+ isFetching(filters) {
2480
+ return this.#queryCache.findAll({
2481
+ ...filters,
2482
+ fetchStatus: "fetching"
2483
+ }).length;
2484
+ }
2485
+ /**
2486
+ * Returns the number of mutations in the cache that are currently pending, optionally
2487
+ * matching a set of filters.
2488
+ *
2489
+ * @example
2490
+ * ```ts
2491
+ * if (queryClient.isMutating()) {
2492
+ * console.log('At least one mutation is pending!')
2493
+ * }
2494
+ * ```
2495
+ */
2496
+ isMutating(filters) {
2497
+ return this.#mutationCache.findAll({
2498
+ ...filters,
2499
+ status: "pending"
2500
+ }).length;
2501
+ }
2502
+ /**
2503
+ * Imperative (non-reactive) way to retrieve data for a QueryKey.
2504
+ * Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates.
2505
+ *
2506
+ * Hint: Do not use this function inside a component, because it won't receive updates.
2507
+ * Use `useQuery` to create a `QueryObserver` that subscribes to changes.
2508
+ *
2509
+ * @see {@link QueryClient#getQueriesData}
2510
+ */
2511
+ getQueryData(queryKey) {
2512
+ const options = this.defaultQueryOptions({ queryKey });
2513
+ return this.#queryCache.get(options.queryHash)?.state.data;
2514
+ }
2515
+ /**
2516
+ * @deprecated Use queryClient.query({ ...options, staleTime: 'static' }) instead. This method will be removed in the next major version.
2517
+ */
2518
+ ensureQueryData(options) {
2519
+ const defaultedOptions = this.defaultQueryOptions(options);
2520
+ const query = this.#queryCache.build(this, defaultedOptions);
2521
+ const cachedData = query.state.data;
2522
+ if (cachedData === void 0) return this.fetchQuery(options);
2523
+ if (options.revalidateIfStale && query.isStaleByTime(resolveQueryValue(defaultedOptions.staleTime, query))) this.prefetchQuery(defaultedOptions);
2524
+ return Promise.resolve(cachedData);
2525
+ }
2526
+ /**
2527
+ * Imperative (non-reactive) way to retrieve the cached data of multiple queries at once.
2528
+ * Only queries matching the given filters are returned; if none match, an empty array is
2529
+ * returned.
2530
+ *
2531
+ * Because the matched queries can hold data of different shapes (e.g. a broad filter can match
2532
+ * queries with unrelated data types), the `TQueryFnData` generic defaults to `unknown` rather
2533
+ * than being inferred. Passing a more specific type is a convenience for call sites that know
2534
+ * every matched query holds the same shape — it is not checked against the actual cache
2535
+ * contents.
2536
+ *
2537
+ * @see {@link QueryClient#getQueryData}
2538
+ * @example
2539
+ * ```ts
2540
+ * const data = queryClient.getQueriesData({ queryKey: ['posts'] })
2541
+ * ```
2542
+ */
2543
+ getQueriesData(filters) {
2544
+ return this.#queryCache.findAll(filters).map(({ queryKey, state }) => {
2545
+ return [queryKey, state.data];
2546
+ });
2547
+ }
2548
+ /**
2549
+ * Synchronous way to immediately update a query's cached data. If the updater (or the value
2550
+ * passed) resolves to `undefined`, the cache is left untouched and no query is created;
2551
+ * otherwise, if the query does not exist yet, it will be created. To update multiple queries
2552
+ * at once by partially matching query keys, use {@link QueryClient#setQueriesData} instead.
2553
+ *
2554
+ * Updates must be performed immutably: do not mutate `oldData`, or data previously retrieved
2555
+ * via {@link QueryClient#getQueryData}, in place.
2556
+ *
2557
+ * @param queryKey - The query key to set data for.
2558
+ * @param updater - Either the new data, or a function that receives the current data (which
2559
+ * may be `undefined`) and returns the new data.
2560
+ *
2561
+ * @example
2562
+ * ```ts
2563
+ * queryClient.setQueryData(['posts'], newPosts)
2564
+ *
2565
+ * // Or, using an updater function that receives the current data:
2566
+ * queryClient.setQueryData(['posts'], (oldPosts) => [...oldPosts, newPost])
2567
+ * ```
2568
+ */
2569
+ setQueryData(queryKey, updater, options) {
2570
+ const defaultedOptions = this.defaultQueryOptions({ queryKey });
2571
+ const prevData = this.#queryCache.get(defaultedOptions.queryHash)?.state.data;
2572
+ const data = functionalUpdate(updater, prevData);
2573
+ if (data === void 0) return;
2574
+ return this.#queryCache.build(this, defaultedOptions).setData(data, {
2575
+ ...options,
2576
+ manual: true
2577
+ });
2578
+ }
2579
+ /**
2580
+ * Synchronous way to immediately update the cached data of multiple queries at once, using
2581
+ * filters or partial query key matching. Only queries that already exist and match the given
2582
+ * filters are updated; no new cache entries are created. Internally this calls
2583
+ * {@link QueryClient#setQueryData} for each matching query.
2584
+ *
2585
+ * @example
2586
+ * ```ts
2587
+ * queryClient.setQueriesData({ queryKey: ['posts'] }, (oldPosts) =>
2588
+ * oldPosts ? oldPosts.filter((post) => post.id !== deletedId) : oldPosts,
2589
+ * )
2590
+ * ```
2591
+ */
2592
+ setQueriesData(filters, updater, options) {
2593
+ return notifyManager.batch(() => this.#queryCache.findAll(filters).map(({ queryKey }) => [queryKey, this.setQueryData(queryKey, updater, options)]));
2594
+ }
2595
+ /**
2596
+ * Imperative (non-reactive) way to retrieve an existing query's state. If the query does not
2597
+ * exist, `undefined` is returned.
2598
+ *
2599
+ * @example
2600
+ * ```ts
2601
+ * const state = queryClient.getQueryState(['posts'])
2602
+ * console.log(state?.dataUpdatedAt)
2603
+ * ```
2604
+ */
2605
+ getQueryState(queryKey) {
2606
+ const options = this.defaultQueryOptions({ queryKey });
2607
+ return this.#queryCache.get(options.queryHash)?.state;
2608
+ }
2609
+ /**
2610
+ * Removes queries from the cache that match the given filters. Unlike
2611
+ * {@link QueryClient#invalidateQueries} or {@link QueryClient#refetchQueries}, this removes
2612
+ * matching queries from the cache instead of refetching them. Without filters, every query in
2613
+ * the cache is removed.
2614
+ *
2615
+ * @example
2616
+ * ```ts
2617
+ * queryClient.removeQueries({ queryKey: ['posts'], exact: true })
2618
+ * ```
2619
+ */
2620
+ removeQueries(filters) {
2621
+ const queryCache = this.#queryCache;
2622
+ notifyManager.batch(() => {
2623
+ queryCache.findAll(filters).forEach((query) => {
2624
+ queryCache.remove(query);
2625
+ });
2626
+ });
2627
+ }
2628
+ /**
2629
+ * Resets queries matching the given filters back to their initial state (e.g. any
2630
+ * `initialData`), notifying subscribers rather than removing them. Active queries among the
2631
+ * matched set are then refetched, and the returned promise resolves once that refetch settles.
2632
+ *
2633
+ * @example
2634
+ * ```ts
2635
+ * await queryClient.resetQueries({ queryKey: ['posts'], exact: true })
2636
+ * ```
2637
+ */
2638
+ resetQueries(filters, options) {
2639
+ const queryCache = this.#queryCache;
2640
+ return notifyManager.batch(() => {
2641
+ const matched = queryCache.findAll(filters);
2642
+ const queriesToRefetch = new Set(matched);
2643
+ matched.forEach((query) => {
2644
+ query.reset();
2645
+ });
2646
+ return this.refetchQueries({
2647
+ type: "active",
2648
+ predicate: (query) => queriesToRefetch.has(query)
2649
+ }, options);
2650
+ });
2651
+ }
2652
+ /**
2653
+ * Cancels outgoing fetches for queries matching the given filters. Most useful when performing
2654
+ * optimistic updates, since any outgoing refetch that resolves afterwards would otherwise
2655
+ * overwrite the optimistic update. By default (`revert: true`), a cancelled query's data is
2656
+ * reverted to its state before the outgoing fetch started.
2657
+ *
2658
+ * The returned promise never rejects, even if individual cancellations fail.
2659
+ *
2660
+ * @example
2661
+ * ```ts
2662
+ * await queryClient.cancelQueries({ queryKey: ['posts'], exact: true })
2663
+ * ```
2664
+ */
2665
+ cancelQueries(filters, cancelOptions = {}) {
2666
+ const defaultedCancelOptions = {
2667
+ revert: true,
2668
+ ...cancelOptions
2669
+ };
2670
+ const promises = notifyManager.batch(() => this.#queryCache.findAll(filters).map((query) => query.cancel(defaultedCancelOptions)));
2671
+ return Promise.all(promises).then(noop).catch(noop);
2672
+ }
2673
+ /**
2674
+ * Marks queries matching the given filters as invalidated. Unlike
2675
+ * {@link QueryClient#removeQueries}, invalidated queries stay in the cache.
2676
+ *
2677
+ * Unless `filters.refetchType` is `'none'`, matching queries are then refetched via
2678
+ * {@link QueryClient#refetchQueries}, using `filters.refetchType` if set, otherwise
2679
+ * `filters.type`, otherwise `'active'`.
2680
+ *
2681
+ * @example
2682
+ * ```ts
2683
+ * await queryClient.invalidateQueries({ queryKey: ['posts'], refetchType: 'active' })
2684
+ * ```
2685
+ */
2686
+ invalidateQueries(filters, options = {}) {
2687
+ return notifyManager.batch(() => {
2688
+ this.#queryCache.findAll(filters).forEach((query) => {
2689
+ query.invalidate();
2690
+ });
2691
+ if (filters?.refetchType === "none") return Promise.resolve();
2692
+ return this.refetchQueries({
2693
+ ...filters,
2694
+ type: filters?.refetchType ?? filters?.type ?? "active"
2695
+ }, options);
2696
+ });
2697
+ }
2698
+ /**
2699
+ * Refetches queries matching the given filters, regardless of whether they are stale. Without
2700
+ * filters, every query in the cache is refetched. Queries that are disabled, or static (only
2701
+ * have observers with a static `staleTime`), are never refetched.
2702
+ *
2703
+ * By default (`cancelRefetch: true`), a currently running fetch is cancelled before the new
2704
+ * one starts. The returned promise resolves once all matching queries have settled; it does
2705
+ * not reject on individual query failures unless `throwOnError` is set.
2706
+ *
2707
+ * @example
2708
+ * ```ts
2709
+ * // refetch all active queries partially matching a query key:
2710
+ * await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' })
2711
+ * ```
2712
+ */
2713
+ refetchQueries(filters, options = {}) {
2714
+ const fetchOptions = {
2715
+ ...options,
2716
+ cancelRefetch: options.cancelRefetch ?? true
2717
+ };
2718
+ const promises = notifyManager.batch(() => this.#queryCache.findAll(filters).filter((query) => !query.isDisabled() && !query.isStatic()).map((query) => {
2719
+ let promise = query.fetch(void 0, fetchOptions);
2720
+ if (!fetchOptions.throwOnError) promise = promise.catch(noop);
2721
+ return query.state.fetchStatus === "paused" ? Promise.resolve() : promise;
2722
+ }));
2723
+ return Promise.all(promises).then(noop);
2724
+ }
2725
+ /**
2726
+ * Asynchronous method to fetch and cache a query, resolving with the data or throwing with
2727
+ * the error.
2728
+ *
2729
+ * If the query already exists in the cache and its data is not stale (per the given
2730
+ * `staleTime`), the cached data is returned without fetching. Otherwise, the query is fetched
2731
+ * and the promise resolves once the fetch settles. If a `select` function is provided, it is
2732
+ * applied to the data in both cases (cached or freshly fetched) before it is returned.
2733
+ *
2734
+ * Unlike a reactive observer, retries are disabled by default here (`retry: false`) unless
2735
+ * explicitly configured, since there is no component to catch a thrown error and retry through
2736
+ * re-render.
2737
+ *
2738
+ * The accepted options are `QueryObserverOptions` minus the fields that only make sense for a
2739
+ * reactive observer — `enabled`, `refetchInterval`, `refetchIntervalInBackground`,
2740
+ * `refetchOnWindowFocus`, `refetchOnReconnect`, `refetchOnMount`, `retryOnMount`,
2741
+ * `notifyOnChangeProps`, `throwOnError`, `suspense`, and `placeholderData` are not part of this
2742
+ * method's options.
2743
+ *
2744
+ * This method replaces the deprecated `fetchQuery`, and — combined with
2745
+ * `{ staleTime: 'static' }` — the deprecated `ensureQueryData`.
2746
+ *
2747
+ * @example
2748
+ * ```ts
2749
+ * try {
2750
+ * const data = await queryClient.query({ queryKey, queryFn, staleTime: 10000 })
2751
+ * } catch (error) {
2752
+ * console.log(error)
2753
+ * }
2754
+ * ```
2755
+ */
2756
+ async query(options) {
2757
+ const defaultedOptions = this.defaultQueryOptions(options);
2758
+ if (defaultedOptions.retry === void 0) defaultedOptions.retry = false;
2759
+ const query = this.#queryCache.build(this, defaultedOptions);
2760
+ const queryData = query.isStaleByTime(resolveQueryValue(defaultedOptions.staleTime, query)) ? await query.fetch(defaultedOptions) : query.state.data;
2761
+ const select = defaultedOptions.select;
2762
+ if (select) return select(queryData);
2763
+ return queryData;
2764
+ }
2765
+ /**
2766
+ * @deprecated Use queryClient.query(options) instead. This method will be removed in the next major version.
2767
+ */
2768
+ fetchQuery(options) {
2769
+ const defaultedOptions = this.defaultQueryOptions(options);
2770
+ if (defaultedOptions.retry === void 0) defaultedOptions.retry = false;
2771
+ const query = this.#queryCache.build(this, defaultedOptions);
2772
+ return query.isStaleByTime(resolveQueryValue(defaultedOptions.staleTime, query)) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
2773
+ }
2774
+ /**
2775
+ * @deprecated Use queryClient.query(options) instead. You can swallow errors with `.catch(noop)`. This method will be removed in the next major version.
2776
+ */
2777
+ prefetchQuery(options) {
2778
+ return this.fetchQuery(options).then(noop).catch(noop);
2779
+ }
2780
+ /**
2781
+ * Asynchronous method to fetch and cache an infinite query, resolving with an
2782
+ * {@link InfiniteData} object or throwing with the error.
2783
+ *
2784
+ * Behaves like {@link QueryClient#query}, accepting the same options (minus
2785
+ * `initialPageParam`), plus the required `initialPageParam`, and an optional `pages` /
2786
+ * `getNextPageParam` pair used to refetch a fixed number of pages from the start.
2787
+ *
2788
+ * This method replaces the deprecated `fetchInfiniteQuery`, and — combined with
2789
+ * `{ staleTime: 'static' }` — the deprecated `ensureInfiniteQueryData`.
2790
+ *
2791
+ * @example
2792
+ * ```ts
2793
+ * try {
2794
+ * const data = await queryClient.infiniteQuery({ queryKey, queryFn, initialPageParam: 0 })
2795
+ * console.log(data.pages)
2796
+ * } catch (error) {
2797
+ * console.log(error)
2798
+ * }
2799
+ * ```
2800
+ */
2801
+ infiniteQuery(options) {
2802
+ options._type = "infinite";
2803
+ return this.query(options);
2804
+ }
2805
+ /**
2806
+ * @deprecated Use queryClient.infiniteQuery(options) instead. This method will be removed in the next major version.
2807
+ */
2808
+ fetchInfiniteQuery(options) {
2809
+ options._type = "infinite";
2810
+ return this.fetchQuery(options);
2811
+ }
2812
+ /**
2813
+ * @deprecated Use queryClient.infiniteQuery(options) instead. You can swallow errors with `.catch(noop)`. This method will be removed in the next major version.
2814
+ */
2815
+ prefetchInfiniteQuery(options) {
2816
+ return this.fetchInfiniteQuery(options).then(noop).catch(noop);
2817
+ }
2818
+ /**
2819
+ * @deprecated Use queryClient.infiniteQuery({ ...options, staleTime: 'static' }) instead. This method will be removed in the next major version.
2820
+ */
2821
+ ensureInfiniteQueryData(options) {
2822
+ options._type = "infinite";
2823
+ return this.ensureQueryData(options);
2824
+ }
2825
+ /**
2826
+ * Resumes mutations that were paused because there was no network connection. Does nothing
2827
+ * (resolving immediately) if the client is currently offline.
2828
+ *
2829
+ * @example
2830
+ * ```ts
2831
+ * import { QueryClient } from '@tanstack/query-core'
2832
+ *
2833
+ * const queryClient = new QueryClient()
2834
+ * await queryClient.resumePausedMutations()
2835
+ * ```
2836
+ */
2837
+ resumePausedMutations() {
2838
+ if (onlineManager.isOnline()) return this.#mutationCache.resumePausedMutations();
2839
+ return Promise.resolve();
2840
+ }
2841
+ /**
2842
+ * Returns the query cache this client is connected to.
2843
+ *
2844
+ * @example
2845
+ * ```ts
2846
+ * import { QueryClient } from '@tanstack/query-core'
2847
+ *
2848
+ * const queryClient = new QueryClient()
2849
+ * const queryCache = queryClient.getQueryCache()
2850
+ * const queries = queryCache.findAll({ queryKey: ['posts'] })
2851
+ * ```
2852
+ */
2853
+ getQueryCache() {
2854
+ return this.#queryCache;
2855
+ }
2856
+ /**
2857
+ * Returns the mutation cache this client is connected to.
2858
+ *
2859
+ * @example
2860
+ * ```ts
2861
+ * import { QueryClient } from '@tanstack/query-core'
2862
+ *
2863
+ * const queryClient = new QueryClient()
2864
+ * const mutationCache = queryClient.getMutationCache()
2865
+ * const mutations = mutationCache.findAll({ status: 'pending' })
2866
+ * ```
2867
+ */
2868
+ getMutationCache() {
2869
+ return this.#mutationCache;
2870
+ }
2871
+ /**
2872
+ * Returns the default options that were set when creating the client, or via
2873
+ * {@link QueryClient#setDefaultOptions}.
2874
+ *
2875
+ * @example
2876
+ * ```ts
2877
+ * import { QueryClient } from '@tanstack/query-core'
2878
+ *
2879
+ * const queryClient = new QueryClient()
2880
+ * const defaultOptions = queryClient.getDefaultOptions()
2881
+ * ```
2882
+ */
2883
+ getDefaultOptions() {
2884
+ return this.#defaultOptions;
2885
+ }
2886
+ /**
2887
+ * Dynamically sets the default options for this client, overwriting any previously defined
2888
+ * default options.
2889
+ *
2890
+ * @see {@link QueryClient#getDefaultOptions}
2891
+ * @example
2892
+ * ```ts
2893
+ * import { QueryClient } from '@tanstack/query-core'
2894
+ *
2895
+ * const queryClient = new QueryClient()
2896
+ * queryClient.setDefaultOptions({
2897
+ * queries: {
2898
+ * staleTime: Infinity,
2899
+ * },
2900
+ * })
2901
+ * ```
2902
+ */
2903
+ setDefaultOptions(options) {
2904
+ this.#defaultOptions = options;
2905
+ }
2906
+ /**
2907
+ * Sets default options for queries whose query key partially matches the given `queryKey`.
2908
+ *
2909
+ * If several registered query defaults match a given query key, they are merged together in
2910
+ * registration order by {@link QueryClient#getQueryDefaults}, so register defaults from the
2911
+ * most generic key to the least generic one — more specific defaults should be registered
2912
+ * after more generic ones so they take precedence.
2913
+ *
2914
+ * @example
2915
+ * ```ts
2916
+ * queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts })
2917
+ *
2918
+ * await queryClient.query({ queryKey: ['posts'] })
2919
+ * ```
2920
+ */
2921
+ setQueryDefaults(queryKey, options) {
2922
+ this.#queryDefaults.set(hashKey(queryKey), {
2923
+ queryKey,
2924
+ defaultOptions: options
2925
+ });
2926
+ }
2927
+ /**
2928
+ * Returns the default options registered for queries whose query key partially matches the
2929
+ * given `queryKey`, via {@link QueryClient#setQueryDefaults}. If multiple registered defaults
2930
+ * match, they are merged together in registration order.
2931
+ *
2932
+ * @example
2933
+ * ```ts
2934
+ * const defaultOptions = queryClient.getQueryDefaults(['posts'])
2935
+ * ```
2936
+ */
2937
+ getQueryDefaults(queryKey) {
2938
+ const defaults = [...this.#queryDefaults.values()];
2939
+ const result = {};
2940
+ defaults.forEach((queryDefault) => {
2941
+ if (partialMatchKey(queryKey, queryDefault.queryKey)) Object.assign(result, queryDefault.defaultOptions);
2942
+ });
2943
+ return result;
2944
+ }
2945
+ /**
2946
+ * Sets default options for mutations whose mutation key partially matches the given
2947
+ * `mutationKey`. As with {@link QueryClient#setQueryDefaults}, the order of registration
2948
+ * matters when several registered defaults match the same mutation key.
2949
+ *
2950
+ * @see {@link QueryClient#getMutationDefaults}
2951
+ * @example
2952
+ * ```ts
2953
+ * queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost })
2954
+ * ```
2955
+ */
2956
+ setMutationDefaults(mutationKey, options) {
2957
+ this.#mutationDefaults.set(hashKey(mutationKey), {
2958
+ mutationKey,
2959
+ defaultOptions: options
2960
+ });
2961
+ }
2962
+ /**
2963
+ * Returns the default options registered for mutations whose mutation key partially matches
2964
+ * the given `mutationKey`, via {@link QueryClient#setMutationDefaults}. If multiple registered
2965
+ * defaults match, they are merged together in registration order.
2966
+ *
2967
+ * @example
2968
+ * ```ts
2969
+ * const defaultOptions = queryClient.getMutationDefaults(['addPost'])
2970
+ * ```
2971
+ */
2972
+ getMutationDefaults(mutationKey) {
2973
+ const defaults = [...this.#mutationDefaults.values()];
2974
+ const result = {};
2975
+ defaults.forEach((queryDefault) => {
2976
+ if (partialMatchKey(mutationKey, queryDefault.mutationKey)) Object.assign(result, queryDefault.defaultOptions);
2977
+ });
2978
+ return result;
2979
+ }
2980
+ /**
2981
+ * Called by framework adapters (e.g. inside `useQuery`) to resolve the options passed by the
2982
+ * caller into their final, defaulted form: merging `queryClient.setQueryDefaults` for the
2983
+ * given `queryKey`, then the client's own `defaultOptions.queries`, then the caller's options
2984
+ * on top. A no-op if the options are already defaulted (`_defaulted: true`).
2985
+ */
2986
+ defaultQueryOptions(options) {
2987
+ if (options._defaulted) return options;
2988
+ const defaultedOptions = {
2989
+ ...this.#defaultOptions.queries,
2990
+ ...this.getQueryDefaults(options.queryKey),
2991
+ ...options,
2992
+ _defaulted: true
2993
+ };
2994
+ if (!defaultedOptions.queryHash) defaultedOptions.queryHash = hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions);
2995
+ if (defaultedOptions.refetchOnReconnect === void 0) defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== "always";
2996
+ if (defaultedOptions.throwOnError === void 0) defaultedOptions.throwOnError = !!defaultedOptions.suspense;
2997
+ if (!defaultedOptions.networkMode && defaultedOptions.persister) defaultedOptions.networkMode = "offlineFirst";
2998
+ if (defaultedOptions.queryFn === skipToken) defaultedOptions.enabled = false;
2999
+ return defaultedOptions;
3000
+ }
3001
+ /**
3002
+ * The mutation counterpart of {@link QueryClient#defaultQueryOptions}. Called by framework
3003
+ * adapters (e.g. inside `useMutation`) to merge `queryClient.setMutationDefaults` for the
3004
+ * given `mutationKey`, then the client's `defaultOptions.mutations`, then the caller's options
3005
+ * on top. A no-op if the options are already defaulted (`_defaulted: true`).
3006
+ */
3007
+ defaultMutationOptions(options) {
3008
+ if (options?._defaulted) return options;
3009
+ return {
3010
+ ...this.#defaultOptions.mutations,
3011
+ ...options?.mutationKey && this.getMutationDefaults(options.mutationKey),
3012
+ ...options,
3013
+ _defaulted: true
3014
+ };
3015
+ }
3016
+ /**
3017
+ * Clears both the query cache and the mutation cache this client is connected to.
3018
+ *
3019
+ * @example
3020
+ * ```ts
3021
+ * import { QueryClient } from '@tanstack/query-core'
3022
+ *
3023
+ * const queryClient = new QueryClient()
3024
+ * queryClient.clear()
3025
+ * ```
3026
+ */
3027
+ clear() {
3028
+ this.#queryCache.clear();
3029
+ this.#mutationCache.clear();
3030
+ }
3031
+ };
3032
+ //#endregion
3033
+ //#region ../../node_modules/.pnpm/@tanstack+react-query@5.103.1_react@19.2.7/node_modules/@tanstack/react-query/build/modern/queryOptions.js
3034
+ function queryOptions(options) {
3035
+ return options;
3036
+ }
3037
+ //#endregion
3038
+ //#region src/lib/capabilities.ts
3039
+ var NONE = {
3040
+ canManageGrants: false,
3041
+ canReadAudit: false,
3042
+ canCreateProject: false
3043
+ };
3044
+ function deriveUiCapabilities(me, projects) {
3045
+ if (me === null) return NONE;
3046
+ const canManageInstance = me.instanceRole === "owner" || me.instanceRole === "root-admin";
3047
+ return {
3048
+ canManageGrants: canManageInstance,
3049
+ canReadAudit: me.canReadAudit,
3050
+ canCreateProject: canManageInstance
3051
+ };
3052
+ }
3053
+ /** Secret values are available only where the API reports secret.read. */
3054
+ function canRevealSecrets(permissions) {
3055
+ return permissions.includes("secret.read");
3056
+ }
3057
+ //#endregion
3058
+ //#region src/lib/coffre.ts
3059
+ /**
3060
+ * The API as whoever is looking at the page. In the browser this is plain
3061
+ * `fetch` to `/api`, carrying the session cookie; mutations call it straight
3062
+ * from event handlers, and loaders read through `context.client`.
3063
+ */
3064
+ function useCoffre() {
3065
+ return useRouter().options.context.client;
3066
+ }
3067
+ /** A refusal the page words itself, shown as it is. */
3068
+ var Refusal = class extends Error {};
3069
+ /** The HTTP status of an API error; undefined when the request never got an answer. */
3070
+ function statusOf(error) {
3071
+ return error instanceof CoffreError ? error.status : void 0;
3072
+ }
3073
+ /** What to tell the person when a call fails. */
3074
+ function failureMessage(error) {
3075
+ if (error instanceof Refusal) return error.message;
3076
+ if (!(error instanceof CoffreError)) return "The request could not be sent. Nothing was changed.";
3077
+ if (error.status === 401) return "Your session has ended. Sign in again, then retry.";
3078
+ if (error.code === "cross_origin") return "coffre refused a change that did not come from this page. Reload, then retry.";
3079
+ if (error.status === 403) return "You hold no grant that covers this. Someone with grant.manage on the project can add one.";
3080
+ if (error.status === 404) return "Not found. It may have been renamed or archived.";
3081
+ if (error.status === 400 || error.status === 409) return error.message;
3082
+ return "coffre is unavailable. Nothing was read or written.";
3083
+ }
3084
+ function uiFailure(error) {
3085
+ return {
3086
+ ok: false,
3087
+ error: failureMessage(error),
3088
+ signedOut: statusOf(error) === 401
3089
+ };
3090
+ }
3091
+ /** A loader's answer: what it read, or what to say instead. */
3092
+ async function uiResult(operation) {
3093
+ try {
3094
+ return {
3095
+ ok: true,
3096
+ ...await operation()
3097
+ };
3098
+ } catch (error) {
3099
+ return uiFailure(error);
3100
+ }
3101
+ }
3102
+ /** How the API names a member: `user:ada@acme.example`, `token:ci-deploy`. */
3103
+ function memberRef(principalType, principalId) {
3104
+ return `${principalType === "user" ? "user" : "token"}:${principalId}`;
3105
+ }
3106
+ //#endregion
3107
+ //#region src/lib/queries.ts
3108
+ /**
3109
+ * Every read the pages make, cached by TanStack Query: one cache per request
3110
+ * on the server, whose reads the page carries to the browser's, and one in the
3111
+ * browser for the whole visit.
3112
+ *
3113
+ * How fresh a page is. A read is reused for `FRESH_MS`, refetched when the
3114
+ * window regains focus, and refetched at once by any change made here, which
3115
+ * names what it touches (`affects`), so your own changes always show.
3116
+ * Someone else's change shows within that window. Nothing is decided on a
3117
+ * cached read: the server authorizes every call, so a stale screen can offer
3118
+ * an action the server then refuses, never grant one. The audit log and the
3119
+ * chain's verification are the exception, read fresh on every visit: their
3120
+ * whole point is to be current.
3121
+ */
3122
+ var FRESH_MS = 1e4;
3123
+ function createQueryClient() {
3124
+ return new QueryClient({ defaultOptions: { queries: {
3125
+ staleTime: FRESH_MS,
3126
+ refetchOnWindowFocus: true,
3127
+ retry: false
3128
+ } } });
3129
+ }
3130
+ /**
3131
+ * The keys, which `affects` names too. A project's keys start with it, so
3132
+ * one invalidation covers everything read under it.
3133
+ */
3134
+ var keys = {
3135
+ me: ["me"],
3136
+ auth: ["auth"],
3137
+ projects: ["projects"],
3138
+ grants: (project) => ["grants", project],
3139
+ secrets: ({ project, environment }) => [
3140
+ "secrets",
3141
+ project,
3142
+ environment
3143
+ ],
3144
+ syncs: ({ project, environment }) => [
3145
+ "syncs",
3146
+ project,
3147
+ environment
3148
+ ],
3149
+ directory: ["directory"],
3150
+ report: (member) => ["report", member],
3151
+ credentials: (member) => ["credentials", member],
3152
+ identities: ["identities"],
3153
+ sessions: ["sessions"],
3154
+ audit: ["audit"]
3155
+ };
3156
+ /** One member's grants, as rows. */
3157
+ function grantRows(members) {
3158
+ return members.flatMap((member) => member.grants.map((grant) => ({
3159
+ id: grant.id,
3160
+ principalType: member.principalType,
3161
+ principalId: member.principalId,
3162
+ role: grant.role,
3163
+ roleName: grant.roleName,
3164
+ permissions: grant.permissions,
3165
+ scope: grant.environment === null ? "project" : "environment",
3166
+ environmentSlug: grant.environment,
3167
+ expiresAt: grant.expiresAt
3168
+ })));
3169
+ }
3170
+ function listDirectory(client) {
3171
+ return uiResult(async () => {
3172
+ const { members, removed } = await client.members.list();
3173
+ return {
3174
+ principals: members.map(({ principalType, principalId, instanceRole, isRootAdmin, tampered }) => ({
3175
+ principalType,
3176
+ principalId,
3177
+ instanceRole,
3178
+ isRootAdmin,
3179
+ tampered
3180
+ })),
3181
+ removed
3182
+ };
3183
+ });
3184
+ }
3185
+ var readProjects = (client) => uiResult(() => client.projects.list());
3186
+ var queries = {
3187
+ /** Who is looking; null when nobody is signed in. */
3188
+ me: (client) => queryOptions({
3189
+ queryKey: keys.me,
3190
+ queryFn: async () => {
3191
+ try {
3192
+ return await client.me();
3193
+ } catch (error) {
3194
+ if (statusOf(error) === 401) return null;
3195
+ throw error;
3196
+ }
3197
+ }
3198
+ }),
3199
+ /** How this instance signs people in. */
3200
+ auth: (client) => queryOptions({
3201
+ queryKey: keys.auth,
3202
+ queryFn: () => client.auth()
3203
+ }),
3204
+ /** The projects you can see, each with its distinct secret count. */
3205
+ projects: (client) => queryOptions({
3206
+ queryKey: keys.projects,
3207
+ queryFn: () => readProjects(client)
3208
+ }),
3209
+ /** Who holds what in a project, for those who manage its access. */
3210
+ grants: (client, project) => queryOptions({
3211
+ queryKey: keys.grants(project),
3212
+ queryFn: () => uiResult(async () => ({ grants: grantRows((await client.members.list(project)).members) }))
3213
+ }),
3214
+ secrets: (client, place) => queryOptions({
3215
+ queryKey: keys.secrets(place),
3216
+ queryFn: () => uiResult(() => client.secrets.list(`${place.project}/${place.environment}`))
3217
+ }),
3218
+ syncs: (client, place) => queryOptions({
3219
+ queryKey: keys.syncs(place),
3220
+ queryFn: () => uiResult(() => client.syncs.list(`${place.project}/${place.environment}`))
3221
+ }),
3222
+ /**
3223
+ * Everyone in the directory, and who was removed. The API shows grant
3224
+ * managers the members of their projects; the directory pages stay the
3225
+ * owners' own, and asking for anyone else would only log a refusal, so
3226
+ * nobody else is asked.
3227
+ */
3228
+ directory: (client, owner) => queryOptions({
3229
+ queryKey: [...keys.directory, { owner }],
3230
+ queryFn: () => owner ? listDirectory(client) : Promise.resolve({
3231
+ ok: false,
3232
+ error: "Only owners can manage users and service accounts.",
3233
+ signedOut: false
3234
+ })
3235
+ }),
3236
+ /** What one member can reach and has seen; null for anyone but owners, who alone may ask. */
3237
+ report: (client, member, owner) => queryOptions({
3238
+ queryKey: [...keys.report(member), { owner }],
3239
+ queryFn: () => owner ? uiResult(async () => {
3240
+ try {
3241
+ return { report: await client.members.get(member) };
3242
+ } catch (error) {
3243
+ if (statusOf(error) === 404) return { report: null };
3244
+ throw error;
3245
+ }
3246
+ }) : Promise.resolve(null)
3247
+ }),
3248
+ /**
3249
+ * A token's credentials; null where they cannot be listed. Only owners
3250
+ * issue and see them, and only coffre's own sign-in issues any.
3251
+ */
3252
+ credentials: (client, member, allowed) => queryOptions({
3253
+ queryKey: [...keys.credentials(member), { allowed }],
3254
+ queryFn: () => allowed ? uiResult(() => client.tokens.list(member)) : Promise.resolve(null)
3255
+ }),
3256
+ /** The accounts you sign in with, under coffre's own sign-in. */
3257
+ identities: (client) => queryOptions({
3258
+ queryKey: keys.identities,
3259
+ queryFn: () => uiResult(() => client.identities.list())
3260
+ }),
3261
+ /** Where you are signed in, under coffre's own sign-in. */
3262
+ sessions: (client) => queryOptions({
3263
+ queryKey: keys.sessions,
3264
+ queryFn: () => uiResult(() => client.sessions.list())
3265
+ }),
3266
+ /** A page of the log, as filtered: always read fresh. */
3267
+ auditEntries: (client, search) => queryOptions({
3268
+ queryKey: [
3269
+ ...keys.audit,
3270
+ "entries",
3271
+ search
3272
+ ],
3273
+ staleTime: 0,
3274
+ queryFn: () => uiResult(() => client.audit.list({
3275
+ limit: 200,
3276
+ decision: search.decision,
3277
+ actor: search.actorId,
3278
+ detail: search.detail
3279
+ }))
3280
+ }),
3281
+ /**
3282
+ * Whether the log holds: verified on every visit, and never waited for.
3283
+ * It re-reads the whole log, so it takes as long as the log is long; the
3284
+ * page shows the entries first and the verdict when it comes.
3285
+ */
3286
+ auditChain: (client) => queryOptions({
3287
+ queryKey: [...keys.audit, "chain"],
3288
+ staleTime: 0,
3289
+ queryFn: () => verifyChain(client)
3290
+ })
3291
+ };
3292
+ /**
3293
+ * Whether the log holds, or why that is not known. Verifying is for owners:
3294
+ * anyone else reads their projects' part of the log, and a part cannot be
3295
+ * checked as a chain, so for them it is a fact about the page, not a fault.
3296
+ */
3297
+ async function verifyChain(client) {
3298
+ try {
3299
+ const result = await client.audit.verify();
3300
+ return result.ok ? {
3301
+ integrity: "intact",
3302
+ through: result.through,
3303
+ entries: result.entries,
3304
+ checkpoint: result.checkpoint,
3305
+ pending: result.pending ?? 0
3306
+ } : {
3307
+ integrity: "broken",
3308
+ through: result.through,
3309
+ failedAtSeq: result.failedAtSeq,
3310
+ author: result.author,
3311
+ reason: result.reason
3312
+ };
3313
+ } catch (error) {
3314
+ const status = statusOf(error);
3315
+ if (status === 403) return { integrity: "owners-only" };
3316
+ return {
3317
+ integrity: "unknown",
3318
+ problem: status === void 0 ? "the request never got an answer" : `the request failed with HTTP ${status}`
3319
+ };
3320
+ }
3321
+ }
3322
+ /**
3323
+ * Who is looking, how this instance signs people in, and the projects they
3324
+ * can see: what the shell needs on every screen. For someone signed out or
3325
+ * not yet a member the project list is refused, and they get the sign-in or
3326
+ * closed-door page.
3327
+ */
3328
+ function shellOf(auth, me, projects) {
3329
+ const listed = projects.ok ? projects.projects : [];
3330
+ const member = me?.registered === true ? me : null;
3331
+ return {
3332
+ auth,
3333
+ principal: me === null ? null : me.principal,
3334
+ instanceRole: member?.instanceRole ?? null,
3335
+ projects: listed,
3336
+ capabilities: deriveUiCapabilities(member, listed),
3337
+ registrationRequired: me !== null && !me.registered,
3338
+ /** A member the vault refuses: their record failed its integrity check. */
3339
+ accessTampered: me?.tampered === true
3340
+ };
3341
+ }
3342
+ /**
3343
+ * The shell, as every loader reads it: from the cache while fresh, so a
3344
+ * child route never asks again for what the root has.
3345
+ */
3346
+ async function loadShell(queryClient, client) {
3347
+ const [auth, me, projects] = await Promise.all([
3348
+ queryClient.fetchQuery(queries.auth(client)),
3349
+ queryClient.fetchQuery(queries.me(client)),
3350
+ queryClient.fetchQuery(queries.projects(client))
3351
+ ]);
3352
+ return shellOf(auth, me, projects);
3353
+ }
3354
+ /**
3355
+ * One project and, when you manage its access, its grants. A project that is
3356
+ * not there for you fails with no message: the page words that itself.
3357
+ */
3358
+ function projectOf(projects, slug) {
3359
+ if (!projects.ok) return projects;
3360
+ const project = projects.projects.find((entry) => entry.slug === slug);
3361
+ if (project === void 0) return {
3362
+ ok: false,
3363
+ error: null
3364
+ };
3365
+ return {
3366
+ ok: true,
3367
+ project,
3368
+ managesAccess: project.permissions.includes("grant.manage")
3369
+ };
3370
+ }
3371
+ /** What a project page reads: the project list, and its grants when you manage them. */
3372
+ async function loadProject(queryClient, client, slug) {
3373
+ const found = projectOf(await queryClient.fetchQuery(queries.projects(client)), slug);
3374
+ if (found.ok && found.managesAccess) await queryClient.fetchQuery(queries.grants(client, slug));
3375
+ }
3376
+ /** The directory pages' read: the directory, for owners. */
3377
+ async function loadDirectory(queryClient, client) {
3378
+ const shell = await loadShell(queryClient, client);
3379
+ return queryClient.fetchQuery(queries.directory(client, shell.capabilities.canManageGrants));
3380
+ }
3381
+ /**
3382
+ * Everything one user's or token's page reads: the report (owners only), the
3383
+ * grants of every project where you manage access, and a token's
3384
+ * credentials. There is no "grants of this member" call, so each project you
3385
+ * manage is asked for its grants and the page keeps this member's. Projects
3386
+ * where you do not hold grant.manage are skipped rather than asked: the
3387
+ * refusal would land in the audit log as a denial in your name.
3388
+ */
3389
+ async function loadPrincipal(queryClient, client, principalType, principalId) {
3390
+ const shell = await loadShell(queryClient, client);
3391
+ const member = memberRef(principalType, principalId);
3392
+ const owner = shell.capabilities.canManageGrants;
3393
+ await Promise.all([
3394
+ queryClient.fetchQuery(queries.report(client, member, owner)),
3395
+ principalType === "service" ? queryClient.fetchQuery(queries.credentials(client, member, owner && shell.auth.signin !== null)) : null,
3396
+ ...managedProjects(shell.projects).map((project) => queryClient.fetchQuery(queries.grants(client, project.slug)))
3397
+ ]);
3398
+ }
3399
+ function managedProjects(projects) {
3400
+ return projects.filter((project) => project.permissions.includes("grant.manage"));
3401
+ }
3402
+ /**
3403
+ * What each change touches, which `useAction` refetches when it lands. Every
3404
+ * change also lands in the audit log, which is always read fresh.
3405
+ */
3406
+ var affects = {
3407
+ /** A project or environment made, renamed or archived: the tree, and where you hold access. */
3408
+ places: () => [keys.projects, keys.me],
3409
+ /** Secrets written, renamed, restored or archived: the environment, its syncs, which push them, and the counts. */
3410
+ secrets: (place) => [
3411
+ keys.secrets(place),
3412
+ keys.syncs(place),
3413
+ keys.projects
3414
+ ],
3415
+ syncs: (place) => [keys.syncs(place)],
3416
+ /**
3417
+ * Someone's access in a project changed: its grants, their report, and, as
3418
+ * it may be your own, what you can see.
3419
+ */
3420
+ access: (project, member) => [
3421
+ keys.grants(project),
3422
+ keys.report(member),
3423
+ keys.projects,
3424
+ keys.me
3425
+ ],
3426
+ /** Someone let in: the directory. */
3427
+ admission: () => [keys.directory],
3428
+ /**
3429
+ * An instance role changed: the directory, their report, and, as it may be
3430
+ * your own, what you can see and do.
3431
+ */
3432
+ role: (member) => [
3433
+ keys.directory,
3434
+ keys.report(member),
3435
+ keys.me,
3436
+ keys.projects
3437
+ ],
3438
+ /** Someone removed: the directory, their report, and every project's grants, which removal ends. */
3439
+ removal: (member) => [
3440
+ keys.directory,
3441
+ keys.report(member),
3442
+ ["grants"]
3443
+ ],
3444
+ credentials: (member) => [keys.credentials(member)],
3445
+ /** Unlinking an account also ends the sessions it signed in. */
3446
+ identities: () => [keys.identities, keys.sessions],
3447
+ sessions: () => [keys.sessions]
3448
+ };
3449
+ /**
3450
+ * Refetch what a change touched: at once where it is on screen, on next use
3451
+ * elsewhere. Every change lands in the audit log, so the log and its
3452
+ * verification are always among them.
3453
+ */
3454
+ async function refresh(queryClient, touched) {
3455
+ await Promise.all([...touched, keys.audit].map((queryKey) => queryClient.invalidateQueries({ queryKey })));
3456
+ }
3457
+ //#endregion
3458
+ //#region src/components/tile.tsx
3459
+ var import_jsx_runtime = require_jsx_runtime();
3460
+ var HUES = [
3461
+ "blue",
3462
+ "green",
3463
+ "amber",
3464
+ "violet"
3465
+ ];
3466
+ /** The same name always lands on the same tint, on every screen (FNV-1a). */
3467
+ function tileHue(name) {
3468
+ let hash = 2166136261;
3469
+ for (const char of name) hash = Math.imul(hash ^ char.charCodeAt(0), 16777619) >>> 0;
3470
+ return HUES[hash % HUES.length];
3471
+ }
3472
+ /**
3473
+ * A letter on a tint, standing in for a project wherever its name appears.
3474
+ *
3475
+ * It is a recognition aid, not information: the name is always beside it, so
3476
+ * the tile is hidden from assistive technology.
3477
+ */
3478
+ function Tile({ name, size = "sm" }) {
3479
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
3480
+ className: `tile tile-${tileHue(name)}${size === "lg" ? " tile-lg" : ""}`,
3481
+ "aria-hidden": true,
3482
+ children: name.slice(0, 1)
3483
+ });
3484
+ }
3485
+ //#endregion
3486
+ //#region src/components/page.tsx
3487
+ /**
3488
+ * The head of every page: an optional project tile, the title with a muted
3489
+ * aside, one line of description or facts, and the page's own actions.
3490
+ *
3491
+ * Where you are is already in the top bar's path, so the head does not repeat
3492
+ * it; it says what this page is.
3493
+ */
3494
+ function PageHeader({ tile, lead, title, aside, description, meta, actions }) {
3495
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("header", {
3496
+ className: "page-head",
3497
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
3498
+ className: "page-head-text",
3499
+ children: [
3500
+ tile !== void 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Tile, {
3501
+ name: tile,
3502
+ size: "lg"
3503
+ }),
3504
+ lead,
3505
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
3506
+ style: { minWidth: 0 },
3507
+ children: [
3508
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("h1", {
3509
+ className: "page-title",
3510
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: title }), aside !== void 0 && aside !== null && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
3511
+ className: "page-title-aside",
3512
+ children: aside
3513
+ })]
3514
+ }),
3515
+ description !== void 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
3516
+ className: "page-desc",
3517
+ children: description
3518
+ }),
3519
+ meta !== void 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
3520
+ className: "page-meta",
3521
+ children: meta
3522
+ })
3523
+ ]
3524
+ })
3525
+ ]
3526
+ }), actions !== void 0 && actions !== false && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
3527
+ className: "page-actions",
3528
+ children: actions
3529
+ })]
3530
+ });
3531
+ }
3532
+ /** A bordered panel with a titled head; tables inside it run edge to edge. */
3533
+ function Card({ title, description, actions, children, labelledBy, tone }) {
3534
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("section", {
3535
+ className: `card${tone === "danger" ? " card-danger" : ""}`,
3536
+ "aria-labelledby": labelledBy,
3537
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
3538
+ className: "card-head",
3539
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("h2", {
3540
+ className: "card-title",
3541
+ id: labelledBy,
3542
+ children: title
3543
+ }), description !== void 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
3544
+ className: "card-desc",
3545
+ children: description
3546
+ })] }), actions]
3547
+ }), children]
3548
+ });
3549
+ }
3550
+ /** One labelled fact in a card's `dl.facts`. */
3551
+ function Fact({ label, children }) {
3552
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
3553
+ className: "fact",
3554
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("dt", { children: label }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dd", { children })]
3555
+ });
3556
+ }
3557
+ /**
3558
+ * A page that cannot be shown: no access, no such thing, or no session.
3559
+ *
3560
+ * It says which page, why in a sentence, and offers the one useful way out.
3561
+ */
3562
+ function ClosedDoor({ icon, label, title, children, actions }) {
3563
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
3564
+ className: "closed",
3565
+ role: "status",
3566
+ children: [
3567
+ icon !== void 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
3568
+ className: "closed-icon",
3569
+ "aria-hidden": true,
3570
+ children: icon
3571
+ }),
3572
+ label !== void 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
3573
+ className: "closed-label",
3574
+ children: label
3575
+ }),
3576
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h1", {
3577
+ className: "closed-title",
3578
+ children: title
3579
+ }),
3580
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
3581
+ className: "closed-body",
3582
+ children
3583
+ }),
3584
+ actions !== void 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
3585
+ className: "closed-actions",
3586
+ children: actions
3587
+ })
3588
+ ]
3589
+ });
3590
+ }
3591
+ //#endregion
3592
+ export { isServer as A, timeoutManager as B, useCoffre as C, notifyManager as D, fetchState as E, replaceEqualDeep as F, initialValues as G, configFromForm as H, resolveQueryValue as I, isAsked as K, shallowEqualObjects as L, isValidTimeout as M, noop as N, focusManager as O, replaceData as P, shouldThrowError as R, uiResult as S, getDefaultState as T, createClient as U, CoffreError as V, firstMissing as W, shellOf as _, Tile as a, memberRef as b, keys as c, loadProject as d, loadShell as f, refresh as g, queries as h, PageHeader as i, hashKey as j, Subscribable as k, loadDirectory as l, projectOf as m, ClosedDoor as n, affects as o, managedProjects as p, planImport as q, Fact as r, createQueryClient as s, Card as t, loadPrincipal as u, Refusal as v, canRevealSecrets as w, statusOf as x, failureMessage as y, timeUntilStale as z };