@coffre/ui 0.1.10 → 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 (167) 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-BP5FY0K1.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-CUQYGCYh.js → account-BocTPU1J.js} +150 -117
  45. package/dist/server/_coffre/assets/{account-DMlUoBxQ.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-CCdSLmvK.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-C05u5ROO.js → auth.device-CMcUISZY.js} +7 -5
  51. package/dist/server/_coffre/assets/{auth.device-BoFM1jcf.js → auth.device-DqO0T-rU.js} +5 -5
  52. package/dist/server/_coffre/assets/{directory-GsnYkse0.js → directory-CyYx6Jx1.js} +87 -112
  53. package/dist/server/_coffre/assets/{use-action-DwEmf58L.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-8yMa7ViM.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-B8zPcS2b.js → principal-page-DQDoXute.js} +51 -42
  65. package/dist/server/_coffre/assets/{projects._project._environment-BZ5Z80V8.js → projects._project._environment-C-yVwC92.js} +168 -248
  66. package/dist/server/_coffre/assets/{projects._project._environment-DdIOc7wx.js → projects._project._environment-D_5R40of.js} +4 -11
  67. package/dist/server/_coffre/assets/{projects._project.index-CuEAUwGn.js → projects._project.index-A2BImFIT.js} +134 -96
  68. package/dist/server/_coffre/assets/{projects._project.index-DvbcU1kh.js → projects._project.index-BPPKxKrt.js} +5 -4
  69. package/dist/server/_coffre/assets/{projects.index-5HI0wOuG.js → projects.index-543IsPzY.js} +57 -55
  70. package/dist/server/_coffre/assets/{react-dom-qCTiwGGR.js → react-dom-bBoJXlK2.js} +417 -51
  71. package/dist/server/_coffre/assets/{router-CQDoql8s.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-BVz78wjP.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-CWs3Mtki.js → tokens._token-aubAUonP.js} +97 -79
  77. package/dist/server/_coffre/assets/{tokens.index-Ck0LN7aC.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-CMwj-VI9.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-fWHv6A30.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/optimistic.ts +233 -0
  102. package/src/lib/queries.ts +393 -0
  103. package/src/lib/use-action.ts +20 -15
  104. package/src/lib/use-change.ts +42 -0
  105. package/src/lib/use-shell.ts +17 -0
  106. package/src/router.tsx +17 -9
  107. package/src/routes/__root.tsx +8 -38
  108. package/src/routes/account.tsx +163 -154
  109. package/src/routes/audit.tsx +51 -72
  110. package/src/routes/auth.device.tsx +4 -2
  111. package/src/routes/login.tsx +3 -2
  112. package/src/routes/projects.$project.$environment.tsx +226 -231
  113. package/src/routes/projects.$project.index.tsx +136 -118
  114. package/src/routes/projects.index.tsx +117 -145
  115. package/src/routes/settings.tsx +7 -7
  116. package/src/routes/tokens.$token.tsx +14 -17
  117. package/src/routes/tokens.index.tsx +8 -4
  118. package/src/routes/unregistered.tsx +3 -2
  119. package/src/routes/users.$user.tsx +4 -4
  120. package/src/routes/users.index.tsx +8 -4
  121. package/src/styles/globals.css +78 -1
  122. package/dist/client/_coffre/assets/account-B48wuSF8.js +0 -1
  123. package/dist/client/_coffre/assets/account-BkNyIDT7.js +0 -2
  124. package/dist/client/_coffre/assets/affordances-CmoY-8Xf.js +0 -1
  125. package/dist/client/_coffre/assets/audit-BvwKYb-5.js +0 -2
  126. package/dist/client/_coffre/assets/audit-D02H-zxS.js +0 -1
  127. package/dist/client/_coffre/assets/auth.device-DYOONgFF.js +0 -2
  128. package/dist/client/_coffre/assets/coffre-BBp7cKVa.js +0 -1
  129. package/dist/client/_coffre/assets/directory-Bu0EIxqI.js +0 -1
  130. package/dist/client/_coffre/assets/globals-Bh2x1gBM.css +0 -1
  131. package/dist/client/_coffre/assets/grants-DavcwofW.js +0 -1
  132. package/dist/client/_coffre/assets/index-CDPlq5rM.js +0 -12
  133. package/dist/client/_coffre/assets/login-C-wTm_t1.js +0 -2
  134. package/dist/client/_coffre/assets/login-CLLv1om9.js +0 -1
  135. package/dist/client/_coffre/assets/offboarding-DWsE2FSa.js +0 -1
  136. package/dist/client/_coffre/assets/page-DbSS7pYH.js +0 -1
  137. package/dist/client/_coffre/assets/preload-helper-DduCCcmc.js +0 -46
  138. package/dist/client/_coffre/assets/principal-page-Bp_iwuSd.js +0 -1
  139. package/dist/client/_coffre/assets/projects._project._environment-BMeX_B8l.js +0 -2
  140. package/dist/client/_coffre/assets/projects._project._environment-CT0A-hIU.js +0 -3
  141. package/dist/client/_coffre/assets/projects._project.index-C_xYOGLT.js +0 -2
  142. package/dist/client/_coffre/assets/projects._project.index-Chcf-cUd.js +0 -1
  143. package/dist/client/_coffre/assets/projects.index-CfOtb1X5.js +0 -2
  144. package/dist/client/_coffre/assets/projects.index-DSjOhLDh.js +0 -1
  145. package/dist/client/_coffre/assets/settings-BC9cUJNK.js +0 -1
  146. package/dist/client/_coffre/assets/settings-Bkj_E21y.js +0 -2
  147. package/dist/client/_coffre/assets/tokens._token-BA0KqvaW.js +0 -1
  148. package/dist/client/_coffre/assets/tokens._token-Dh9jLOkm.js +0 -2
  149. package/dist/client/_coffre/assets/tokens.index-BgAMWkHT.js +0 -2
  150. package/dist/client/_coffre/assets/tokens.index-CHueIAv1.js +0 -1
  151. package/dist/client/_coffre/assets/unregistered-D5go1AfR.js +0 -1
  152. package/dist/client/_coffre/assets/use-action-l__xZDYY.js +0 -1
  153. package/dist/client/_coffre/assets/users._user-Dwqa0gv5.js +0 -1
  154. package/dist/client/_coffre/assets/users._user-xJAb3T6Y.js +0 -2
  155. package/dist/client/_coffre/assets/users.index-BJoF-L37.js +0 -2
  156. package/dist/client/_coffre/assets/users.index-YUjtbTGy.js +0 -1
  157. package/dist/server/_coffre/assets/_tanstack-start-manifest_v-BKg2AlPu.js +0 -133
  158. package/dist/server/_coffre/assets/audit-CThXn2v7.js +0 -74
  159. package/dist/server/_coffre/assets/coffre-C2ANsTAz.js +0 -281
  160. package/dist/server/_coffre/assets/globals-Bh2x1gBM.css +0 -1
  161. package/dist/server/_coffre/assets/grants-B6k4Fu9z.js +0 -243
  162. package/dist/server/_coffre/assets/projects.index-uiomWX_l.js +0 -54
  163. package/dist/server/_coffre/assets/settings-4oRyDizv.js +0 -18
  164. package/dist/server/_coffre/assets/tokens._token-CF_deAwq.js +0 -18
  165. package/dist/server/_coffre/assets/tokens.index-DF_07KEe.js +0 -10
  166. package/dist/server/_coffre/assets/users._user-DUzwkSKT.js +0 -10
  167. package/dist/server/_coffre/assets/users.index-BbuweTwH.js +0 -10
@@ -0,0 +1,1212 @@
1
+ import { i as require_react, s as __toESM } from "./useRouter-CaUSUNsw.js";
2
+ import { D as notifyManager, F as replaceEqualDeep, L as shallowEqualObjects, N as noop, R as shouldThrowError, T as getDefaultState, b as memberRef, c as keys, g as refresh, j as hashKey, k as Subscribable, o as affects, v as Refusal, y as failureMessage } from "./page-D_mO0-sn.js";
3
+ import { f as useQueryClient } from "./suspense-CzYTwxOj.js";
4
+ import { o as announce } from "./row-state-XBtDoIA4.js";
5
+ //#region ../../node_modules/.pnpm/@tanstack+query-core@5.103.1/node_modules/@tanstack/query-core/build/modern/mutationObserver.js
6
+ /**
7
+ * Observes a single mutation and derives a `MutationObserverResult` from it.
8
+ * A framework hook like `useMutation` creates one `MutationObserver` per hook
9
+ * call, keeps it stable across re-renders, calls `setOptions` when the options
10
+ * passed to the hook change, subscribes to it to re-render on updates, and
11
+ * reads `getCurrentResult()` for the value to return. Calling `mutate()`
12
+ * builds a new underlying `Mutation` in the `MutationCache` and executes it.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * const observer = new MutationObserver(queryClient, {
17
+ * mutationFn: (variables: { title: string }) => addPost(variables),
18
+ * })
19
+ * ```
20
+ */
21
+ var MutationObserver = class extends Subscribable {
22
+ #client;
23
+ #currentResult = void 0;
24
+ #currentMutation;
25
+ #mutateOptions;
26
+ constructor(client, options) {
27
+ super();
28
+ this.#client = client;
29
+ this.setOptions(options);
30
+ this.bindMethods();
31
+ this.#updateResult();
32
+ }
33
+ bindMethods() {
34
+ this.mutate = this.mutate.bind(this);
35
+ this.reset = this.reset.bind(this);
36
+ }
37
+ /**
38
+ * Updates the observer's options.
39
+ *
40
+ * If the new `mutationKey` differs from the previous one (and both were
41
+ * defined), the observer is reset, detaching it from the mutation it was
42
+ * observing. Otherwise, if the currently observed mutation is still
43
+ * `pending`, its options are updated in place as well.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * observer.setOptions({
48
+ * mutationFn: (variables: { title: string }) => addPost(variables),
49
+ * onSuccess: (data) => console.log(data),
50
+ * })
51
+ * ```
52
+ */
53
+ setOptions(options) {
54
+ const prevOptions = this.options;
55
+ this.options = this.#client.defaultMutationOptions(options);
56
+ if (!shallowEqualObjects(this.options, prevOptions)) this.#client.getMutationCache().notify({
57
+ type: "observerOptionsUpdated",
58
+ mutation: this.#currentMutation,
59
+ observer: this
60
+ });
61
+ if (prevOptions?.mutationKey && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) this.reset();
62
+ else if (this.#currentMutation?.state.status === "pending") this.#currentMutation.setOptions(this.options);
63
+ }
64
+ onSubscribe() {
65
+ if (this.listeners.size === 1 && this.#currentMutation) {
66
+ this.#currentMutation.addObserver(this);
67
+ this.#updateResult();
68
+ }
69
+ }
70
+ onUnsubscribe() {
71
+ if (!this.hasListeners()) this.#currentMutation?.removeObserver(this);
72
+ }
73
+ /** @internal */
74
+ onMutationUpdate(action) {
75
+ this.#updateResult();
76
+ this.#notify(action);
77
+ }
78
+ /**
79
+ * Returns the observer's current result, derived from the observed
80
+ * mutation's state (or the default, `idle` state if no mutation has been
81
+ * built yet, e.g. before the first `mutate()` call or after `reset()`).
82
+ */
83
+ getCurrentResult() {
84
+ return this.#currentResult;
85
+ }
86
+ /**
87
+ * Detaches the observer from the mutation it is currently observing (if
88
+ * any) and resets the observed result back to its default, `idle` state.
89
+ *
90
+ * This does not cancel an in-flight mutation; the mutation itself keeps
91
+ * running to completion and its own callbacks still fire, but this
92
+ * observer stops reflecting its state and a subsequent `mutate()` call
93
+ * will build a brand new mutation.
94
+ *
95
+ * @example
96
+ * ```ts
97
+ * observer.reset()
98
+ * ```
99
+ *
100
+ * @see {@link MutationObserver#mutate}
101
+ */
102
+ reset() {
103
+ this.#currentMutation?.removeObserver(this);
104
+ this.#currentMutation = void 0;
105
+ this.#updateResult();
106
+ this.#notify();
107
+ }
108
+ /**
109
+ * Builds a new `Mutation` in the `MutationCache` using the observer's
110
+ * current options, detaches this observer from any previously observed
111
+ * mutation, attaches it to the new one, and executes it with the given
112
+ * variables.
113
+ *
114
+ * The optional per-call `options` (`onSuccess`/`onError`/`onSettled`) are
115
+ * invoked once the mutation settles, in addition to any callbacks defined
116
+ * on the observer's own options.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * await observer.mutate(
121
+ * { title: 'New post' },
122
+ * { onSuccess: (data) => console.log(data) },
123
+ * )
124
+ * ```
125
+ */
126
+ mutate(variables, options) {
127
+ this.#mutateOptions = options;
128
+ this.#currentMutation?.removeObserver(this);
129
+ this.#currentMutation = this.#client.getMutationCache().build(this.#client, this.options);
130
+ this.#currentMutation.addObserver(this);
131
+ return this.#currentMutation.execute(variables);
132
+ }
133
+ #updateResult() {
134
+ const state = this.#currentMutation?.state ?? getDefaultState();
135
+ this.#currentResult = {
136
+ ...state,
137
+ isPending: state.status === "pending",
138
+ isSuccess: state.status === "success",
139
+ isError: state.status === "error",
140
+ isIdle: state.status === "idle",
141
+ mutate: this.mutate,
142
+ reset: this.reset
143
+ };
144
+ }
145
+ #notify(action) {
146
+ notifyManager.batch(() => {
147
+ if (this.#mutateOptions && this.hasListeners()) {
148
+ const variables = this.#currentResult.variables;
149
+ const onMutateResult = this.#currentResult.context;
150
+ const context = {
151
+ client: this.#client,
152
+ meta: this.options.meta,
153
+ mutationKey: this.options.mutationKey
154
+ };
155
+ if (action?.type === "success") {
156
+ try {
157
+ this.#mutateOptions.onSuccess?.(action.data, variables, onMutateResult, context);
158
+ } catch (e) {
159
+ Promise.reject(e);
160
+ }
161
+ try {
162
+ this.#mutateOptions.onSettled?.(action.data, null, variables, onMutateResult, context);
163
+ } catch (e) {
164
+ Promise.reject(e);
165
+ }
166
+ } else if (action?.type === "error") {
167
+ try {
168
+ this.#mutateOptions.onError?.(action.error, variables, onMutateResult, context);
169
+ } catch (e) {
170
+ Promise.reject(e);
171
+ }
172
+ try {
173
+ this.#mutateOptions.onSettled?.(void 0, action.error, variables, onMutateResult, context);
174
+ } catch (e) {
175
+ Promise.reject(e);
176
+ }
177
+ }
178
+ }
179
+ this.listeners.forEach((listener) => {
180
+ listener(this.#currentResult);
181
+ });
182
+ });
183
+ }
184
+ };
185
+ //#endregion
186
+ //#region ../../node_modules/.pnpm/@tanstack+react-query@5.103.1_react@19.2.7/node_modules/@tanstack/react-query/build/modern/useMutationState.js
187
+ var import_react = /* @__PURE__ */ __toESM(require_react(), 1);
188
+ function getResult(mutationCache, options) {
189
+ return mutationCache.findAll(options.filters).map((mutation) => options.select ? options.select(mutation) : mutation.state);
190
+ }
191
+ /**
192
+ * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass
193
+ * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation
194
+ * state.
195
+ *
196
+ * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the
197
+ * mutation state.
198
+ * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
199
+ * be used.
200
+ * @returns Will be an Array of whatever `select` returns for each matching mutation.
201
+ *
202
+ * @example
203
+ * Get all variables of all running mutations:
204
+ * ```tsx
205
+ * import { useMutationState } from '@tanstack/react-query'
206
+ *
207
+ * function PendingPosts() {
208
+ * const pendingVariables = useMutationState({
209
+ * filters: { status: 'pending' },
210
+ * select: (mutation) => mutation.state.variables,
211
+ * })
212
+ *
213
+ * return <>{pendingVariables.length} posts saving...</>
214
+ * }
215
+ * ```
216
+ *
217
+ * @example
218
+ * Get all data for specific mutations via the `mutationKey`:
219
+ * ```tsx
220
+ * import { useMutation, useMutationState } from '@tanstack/react-query'
221
+ *
222
+ * const mutationKey = ['posts']
223
+ *
224
+ * function Posts() {
225
+ * // Some mutation that we want to get the state for
226
+ * const mutation = useMutation({
227
+ * mutationKey,
228
+ * mutationFn: createPosts,
229
+ * })
230
+ *
231
+ * const savedPosts = useMutationState({
232
+ * // this mutation key needs to match the mutation key of the given mutation (see above)
233
+ * filters: { mutationKey, status: 'success' },
234
+ * select: (mutation) => mutation.state.data,
235
+ * })
236
+ *
237
+ * return (
238
+ * <button onClick={() => mutation.mutate(['New Post'])}>
239
+ * Create post ({savedPosts.length} saved so far)
240
+ * </button>
241
+ * )
242
+ * }
243
+ * ```
244
+ *
245
+ * @example
246
+ * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
247
+ * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the
248
+ * last item that `useMutationState` returns to get the latest successful invocation:
249
+ * ```tsx
250
+ * import { useMutationState } from '@tanstack/react-query'
251
+ *
252
+ * function LatestPost() {
253
+ * const savedPosts = useMutationState({
254
+ * filters: { mutationKey: ['posts'], status: 'success' },
255
+ * select: (mutation) => mutation.state.data,
256
+ * })
257
+ *
258
+ * const latestSavedPost = savedPosts[savedPosts.length - 1]
259
+ *
260
+ * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>
261
+ * }
262
+ * ```
263
+ */
264
+ function useMutationState(options = {}, queryClient) {
265
+ const mutationCache = useQueryClient(queryClient).getMutationCache();
266
+ const optionsRef = import_react.useRef(options);
267
+ const result = import_react.useRef(null);
268
+ if (result.current === null) result.current = getResult(mutationCache, options);
269
+ import_react.useEffect(() => {
270
+ optionsRef.current = options;
271
+ });
272
+ return import_react.useSyncExternalStore(import_react.useCallback((onStoreChange) => mutationCache.subscribe(() => {
273
+ const nextResult = replaceEqualDeep(result.current, getResult(mutationCache, optionsRef.current));
274
+ if (result.current !== nextResult) {
275
+ result.current = nextResult;
276
+ notifyManager.schedule(onStoreChange);
277
+ }
278
+ }), [mutationCache]), () => result.current, () => result.current);
279
+ }
280
+ //#endregion
281
+ //#region ../../node_modules/.pnpm/@tanstack+react-query@5.103.1_react@19.2.7/node_modules/@tanstack/react-query/build/modern/useMutation.js
282
+ /**
283
+ * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
284
+ * `useMutation` is the hook for that.
285
+ *
286
+ * @see {@link mutationOptions} to share these options across multiple `useMutation` call sites, or to look
287
+ * the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).
288
+ * @param options - The {@link UseMutationOptions} to use — everything you can pass to `useMutation`.
289
+ * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
290
+ * be used.
291
+ * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
292
+ * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
293
+ * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
294
+ * fire only for the latest call you've made, and only while the component is still mounted — unmounting before
295
+ * the mutation settles removes the subscription and prevents them from firing.
296
+ *
297
+ * @example
298
+ * ```tsx
299
+ * import { useMutation, useQueryClient } from '@tanstack/react-query'
300
+ *
301
+ * function AddTodo() {
302
+ * const queryClient = useQueryClient()
303
+ *
304
+ * const addMutation = useMutation({
305
+ * mutationFn: addTodo,
306
+ * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
307
+ * })
308
+ *
309
+ * return (
310
+ * <button
311
+ * onClick={() =>
312
+ * addMutation.mutate('Item', {
313
+ * onError: (error) => console.error('Failed to add item:', error),
314
+ * })
315
+ * }
316
+ * >
317
+ * Add
318
+ * </button>
319
+ * )
320
+ * }
321
+ * ```
322
+ *
323
+ * @example
324
+ * Rendering the mutation's own state, rather than just firing it off:
325
+ * ```tsx
326
+ * import { useMutation, useQueryClient } from '@tanstack/react-query'
327
+ *
328
+ * function AddTodo() {
329
+ * const queryClient = useQueryClient()
330
+ *
331
+ * const addMutation = useMutation({
332
+ * mutationFn: addTodo,
333
+ * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
334
+ * })
335
+ *
336
+ * return (
337
+ * <div>
338
+ * {addMutation.isPending ? (
339
+ * 'Adding todo...'
340
+ * ) : (
341
+ * <>
342
+ * {addMutation.isError ? (
343
+ * <div>An error occurred: {addMutation.error.message}</div>
344
+ * ) : null}
345
+ * <button onClick={() => addMutation.mutate('Item')}>Add</button>
346
+ * </>
347
+ * )}
348
+ * </div>
349
+ * )
350
+ * }
351
+ * ```
352
+ *
353
+ * @example
354
+ * Optimistic update via `onMutate`, rolling back on `onError`:
355
+ * ```tsx
356
+ * import { useMutation, useQueryClient } from '@tanstack/react-query'
357
+ *
358
+ * function AddTodo() {
359
+ * const queryClient = useQueryClient()
360
+ *
361
+ * const addMutation = useMutation({
362
+ * mutationFn: addTodo,
363
+ * onMutate: async (newTodo) => {
364
+ * await queryClient.cancelQueries({ queryKey: ['todos'] })
365
+ * const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
366
+ *
367
+ * queryClient.setQueryData<Array<string>>(['todos'], (old) => [
368
+ * ...(old ?? []),
369
+ * newTodo,
370
+ * ])
371
+ *
372
+ * // Passed to `onError` as `onMutateResult` if the mutation fails.
373
+ * return { previousTodos }
374
+ * },
375
+ * onError: (_err, _newTodo, onMutateResult) => {
376
+ * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
377
+ * },
378
+ * onSettled: () => {
379
+ * queryClient.invalidateQueries({ queryKey: ['todos'] })
380
+ * },
381
+ * })
382
+ *
383
+ * return (
384
+ * <button onClick={() => addMutation.mutate('Item')}>Add</button>
385
+ * )
386
+ * }
387
+ * ```
388
+ *
389
+ * @example
390
+ * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a
391
+ * promise per call instead, so you can wait for all of them when they succeed:
392
+ * ```tsx
393
+ * import { useMutation, useQueryClient } from '@tanstack/react-query'
394
+ *
395
+ * function AddTodos() {
396
+ * const queryClient = useQueryClient()
397
+ *
398
+ * const addMutation = useMutation({
399
+ * mutationFn: addTodo,
400
+ * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
401
+ * })
402
+ *
403
+ * async function handleAddAll(todos: Array<string>) {
404
+ * try {
405
+ * await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
406
+ * } catch (error) {
407
+ * console.error('Failed to add todos:', error)
408
+ * }
409
+ * }
410
+ *
411
+ * return (
412
+ * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
413
+ * Add all
414
+ * </button>
415
+ * )
416
+ * }
417
+ * ```
418
+ *
419
+ * @example
420
+ * If some of the mutations above can fail independently of the others, and you want to know which ones
421
+ * did — rather than losing that information the moment the first one rejects — swap `Promise.all` for
422
+ * `Promise.allSettled`:
423
+ * ```tsx
424
+ * import { useMutation, useQueryClient } from '@tanstack/react-query'
425
+ *
426
+ * function AddTodos() {
427
+ * const queryClient = useQueryClient()
428
+ *
429
+ * const addMutation = useMutation({
430
+ * mutationFn: addTodo,
431
+ * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
432
+ * })
433
+ *
434
+ * async function handleAddAll(todos: Array<string>) {
435
+ * const addResults = await Promise.allSettled(
436
+ * todos.map((todo) => addMutation.mutateAsync(todo)),
437
+ * )
438
+ *
439
+ * addResults.forEach((addResult, index) => {
440
+ * if (addResult.status === 'rejected') {
441
+ * console.error(`Failed to add "${todos[index]}":`, addResult.reason)
442
+ * }
443
+ * })
444
+ * }
445
+ *
446
+ * return (
447
+ * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
448
+ * Add all
449
+ * </button>
450
+ * )
451
+ * }
452
+ * ```
453
+ */
454
+ function useMutation(options, queryClient) {
455
+ const client = useQueryClient(queryClient);
456
+ const [observer] = import_react.useState(() => new MutationObserver(client, options));
457
+ import_react.useEffect(() => {
458
+ observer.setOptions(options);
459
+ }, [observer, options]);
460
+ const result = import_react.useSyncExternalStore(import_react.useCallback((onStoreChange) => observer.subscribe(notifyManager.batchCalls(onStoreChange)), [observer]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
461
+ const mutate = import_react.useCallback((...args) => {
462
+ observer.mutate(args[0], args[1]).catch(noop);
463
+ }, [observer]);
464
+ if (result.error && shouldThrowError(observer.options.throwOnError, [result.error])) throw result.error;
465
+ return {
466
+ ...result,
467
+ mutate,
468
+ mutateAsync: result.mutate
469
+ };
470
+ }
471
+ //#endregion
472
+ //#region src/lib/project-access.ts
473
+ var LEVEL_LABELS = {
474
+ owner: "Owner",
475
+ viewer: "Read",
476
+ developer: "Write"
477
+ };
478
+ function projectAccessOptions(environments) {
479
+ const options = [{
480
+ value: "owner:",
481
+ role: "owner",
482
+ environmentSlug: null,
483
+ label: "Owner"
484
+ }];
485
+ for (const role of ["viewer", "developer"]) options.push({
486
+ value: `${role}:`,
487
+ role,
488
+ environmentSlug: null,
489
+ label: `${LEVEL_LABELS[role]}: all`
490
+ });
491
+ for (const environment of environments) {
492
+ if (environment.details === null || environment.details.archivedAt !== null) continue;
493
+ for (const role of ["viewer", "developer"]) options.push({
494
+ value: `${role}:${environment.slug}`,
495
+ role,
496
+ environmentSlug: environment.slug,
497
+ label: `${LEVEL_LABELS[role]}: ${environment.slug}`
498
+ });
499
+ }
500
+ return options;
501
+ }
502
+ function parseProjectAccess(value) {
503
+ const [role, environmentSlug = ""] = value.split(":", 2);
504
+ if (role !== "owner" && role !== "viewer" && role !== "developer") throw new Error("unknown project access level");
505
+ return {
506
+ role,
507
+ environmentSlug: environmentSlug || null
508
+ };
509
+ }
510
+ function projectAccessLabel(grant) {
511
+ const scope = grant.environmentSlug === null ? "all environments" : grant.environmentSlug;
512
+ if (grant.role === "owner") return "Owner";
513
+ if (grant.role === "viewer") return grant.environmentSlug === null ? "Read: all" : `Read: ${scope}`;
514
+ if (grant.role === "developer") return grant.environmentSlug === null ? "Write: all" : `Write: ${scope}`;
515
+ return `${grant.roleName}: ${scope}`;
516
+ }
517
+ //#endregion
518
+ //#region src/lib/secret-edit-batch.ts
519
+ function secretChangeFor(changes, key) {
520
+ return Object.hasOwn(changes, key) ? changes[key] : void 0;
521
+ }
522
+ /** Return true when one save would give two pending edits the same target. */
523
+ function hasSecretEditConflict(active, drafts, changes) {
524
+ const finalActiveKeys = active.filter((entry) => !secretChangeFor(changes, entry.key)?.archived).map((entry) => secretChangeFor(changes, entry.key)?.key.trim() ?? entry.key);
525
+ if (new Set(finalActiveKeys).size !== finalActiveKeys.length) return true;
526
+ const draftKeys = drafts.map((draft) => draft.key.trim());
527
+ if (new Set(draftKeys).size !== draftKeys.length) return true;
528
+ const valueEditTargets = new Set(active.flatMap((entry) => {
529
+ const change = secretChangeFor(changes, entry.key);
530
+ return change !== void 0 && !change.archived && change.value !== null ? [change.key.trim()] : [];
531
+ }));
532
+ if (draftKeys.some((key) => valueEditTargets.has(key))) return true;
533
+ const archivedKeys = new Set(active.filter((entry) => secretChangeFor(changes, entry.key)?.archived).map((entry) => entry.key));
534
+ return draftKeys.some((key) => archivedKeys.has(key));
535
+ }
536
+ /**
537
+ * Save every pending edit: renames first, one call each, then everything else
538
+ * as one merge patch.
539
+ *
540
+ * The patch is a single transaction, so values, new keys and archives land
541
+ * together or not at all. Renames cannot join it: a merge patch names keys and
542
+ * has no way to move one with its history. A failed rename therefore stops the
543
+ * save before the patch. The renames before it stay done, and every other edit
544
+ * is kept for the retry, a value following its key to the new name.
545
+ */
546
+ async function applySecretEditBatch({ active, drafts, changes, operations }) {
547
+ const remainingChanges = { ...changes };
548
+ const plan = planEdits(active, drafts, changes);
549
+ if (plan instanceof Error) return {
550
+ applied: 0,
551
+ drafts: [...drafts],
552
+ changes: remainingChanges,
553
+ error: plan
554
+ };
555
+ let applied = 0;
556
+ const patch = Object.create(null);
557
+ try {
558
+ for (const { sourceKey, change } of plan) {
559
+ if (change.archived) {
560
+ patch[sourceKey] = null;
561
+ continue;
562
+ }
563
+ const key = change.key.trim();
564
+ if (key !== sourceKey) {
565
+ await operations.rename(sourceKey, key);
566
+ delete remainingChanges[sourceKey];
567
+ applied += 1;
568
+ if (change.value !== null) remainingChanges[key] = {
569
+ key,
570
+ value: change.value,
571
+ archived: false
572
+ };
573
+ }
574
+ if (change.value !== null) patch[key] = change.value;
575
+ }
576
+ for (const draft of drafts) patch[draft.key.trim()] = draft.value;
577
+ const written = Object.keys(patch).length;
578
+ if (written > 0) await operations.write({ ...patch });
579
+ return {
580
+ applied: applied + written,
581
+ drafts: [],
582
+ changes: {},
583
+ error: null
584
+ };
585
+ } catch (error) {
586
+ return {
587
+ applied,
588
+ drafts: [...drafts],
589
+ changes: remainingChanges,
590
+ error
591
+ };
592
+ }
593
+ }
594
+ /**
595
+ * Put dependent renames in an order that frees each destination first.
596
+ * Cycles and archive-then-restore plans fail before the first mutation.
597
+ */
598
+ function planEdits(active, drafts, changes) {
599
+ const activeKeys = new Set(active.map((entry) => entry.key));
600
+ const archivedKeys = new Set(active.filter((entry) => secretChangeFor(changes, entry.key)?.archived).map((entry) => entry.key));
601
+ const restoredByDraft = drafts.find((draft) => archivedKeys.has(draft.key.trim()));
602
+ if (restoredByDraft) return /* @__PURE__ */ new Error(`${restoredByDraft.key.trim()}: cannot archive and write the same key in one save`);
603
+ const renames = /* @__PURE__ */ new Map();
604
+ const otherEdits = [];
605
+ for (const entry of active) {
606
+ const change = secretChangeFor(changes, entry.key);
607
+ if (change === void 0) continue;
608
+ if (!change.archived && change.key.trim() !== entry.key) renames.set(entry.key, change);
609
+ else otherEdits.push({
610
+ sourceKey: entry.key,
611
+ change
612
+ });
613
+ }
614
+ for (const [sourceKey, change] of renames) {
615
+ const destination = change.key.trim();
616
+ if (activeKeys.has(destination) && !renames.has(destination)) return /* @__PURE__ */ new Error(`${sourceKey}: ${destination} is already in use`);
617
+ }
618
+ const orderedRenames = [];
619
+ const freedKeys = /* @__PURE__ */ new Set();
620
+ while (renames.size > 0) {
621
+ const ready = [...renames].find(([, change]) => {
622
+ const destination = change.key.trim();
623
+ return !activeKeys.has(destination) || freedKeys.has(destination);
624
+ });
625
+ if (!ready) return /* @__PURE__ */ new Error("Secret renames contain a cycle. Save them in separate steps.");
626
+ const [sourceKey, change] = ready;
627
+ renames.delete(sourceKey);
628
+ freedKeys.add(sourceKey);
629
+ orderedRenames.push({
630
+ sourceKey,
631
+ change
632
+ });
633
+ }
634
+ return [...orderedRenames, ...otherEdits];
635
+ }
636
+ //#endregion
637
+ //#region src/lib/changes.ts
638
+ /** A list held in a read's `field`, when the read answered. */
639
+ function listOf(queryKey, field, id) {
640
+ return {
641
+ queryKey,
642
+ items: (data) => data?.ok === true ? data[field] ?? [] : [],
643
+ withItems: (data, items) => data?.ok === true ? {
644
+ ...data,
645
+ [field]: items
646
+ } : data,
647
+ id
648
+ };
649
+ }
650
+ var ARCHIVING = {
651
+ pending: "Archiving…",
652
+ done: "archived",
653
+ failed: "Not archived."
654
+ };
655
+ var REVOKING = {
656
+ pending: "Revoking…",
657
+ done: "revoked",
658
+ failed: "Not revoked."
659
+ };
660
+ var saving = (id) => ({
661
+ id,
662
+ kind: "saving"
663
+ });
664
+ var removing = (id) => ({
665
+ id,
666
+ kind: "removing"
667
+ });
668
+ /** A grant's identity, before the server has given it an id: who, and where. */
669
+ function grantId(grant) {
670
+ return `${memberRef(grant.principalType, grant.principalId)}@${grant.environmentSlug ?? ""}`;
671
+ }
672
+ function grantsList(project) {
673
+ return listOf(keys.grants(project), "grants", grantId);
674
+ }
675
+ /** Where a grant applies, as the API names it: `market`, or `market/prod`. */
676
+ function grantPlace(project, environmentSlug) {
677
+ return environmentSlug === null ? project : `${project}/${environmentSlug}`;
678
+ }
679
+ /**
680
+ * Give someone a role at one place. Access is declarative, so asking for what
681
+ * they already hold is not an error, whoever asked first: `existed` says so.
682
+ */
683
+ function grantAccess(client, project) {
684
+ return {
685
+ list: grantsList(project),
686
+ label: (vars) => `${vars.roleName} for ${vars.principalId}`,
687
+ targets: (vars) => [saving(grantId(vars))],
688
+ apply: (grants, vars) => {
689
+ const row = {
690
+ id: `pending:${grantId(vars)}`,
691
+ principalType: vars.principalType,
692
+ principalId: vars.principalId,
693
+ role: vars.role,
694
+ roleName: vars.roleName,
695
+ permissions: [],
696
+ scope: vars.environmentSlug === null ? "project" : "environment",
697
+ environmentSlug: vars.environmentSlug,
698
+ expiresAt: vars.expiresAt
699
+ };
700
+ const id = grantId(vars);
701
+ return grants.some((grant) => grantId(grant) === id) ? grants.map((grant) => grantId(grant) === id ? {
702
+ ...row,
703
+ id: grant.id
704
+ } : grant) : [...grants, row];
705
+ },
706
+ affects: (vars) => affects.access(project, memberRef(vars.principalType, vars.principalId)),
707
+ run: async (vars) => {
708
+ const place = grantPlace(project, vars.environmentSlug);
709
+ const role = vars.role;
710
+ const { changes } = await client.access.set(memberRef(vars.principalType, vars.principalId), { [place]: vars.expiresAt === null ? role : {
711
+ role,
712
+ until: vars.expiresAt
713
+ } });
714
+ return { existed: changes[place] === "unchanged" };
715
+ }
716
+ };
717
+ }
718
+ function revokeGrant(client, project) {
719
+ return {
720
+ list: grantsList(project),
721
+ label: (grant) => `${projectAccessLabel(grant)} for ${grant.principalId}`,
722
+ targets: (grant) => [removing(grantId(grant))],
723
+ removing: REVOKING,
724
+ affects: (grant) => affects.access(project, memberRef(grant.principalType, grant.principalId)),
725
+ run: (grant) => client.access.set(memberRef(grant.principalType, grant.principalId), { [grantPlace(project, grant.environmentSlug)]: null })
726
+ };
727
+ }
728
+ var principalId = (principal) => memberRef(principal.principalType, principal.principalId);
729
+ /** The directory as owners read it: the only ones who change it. */
730
+ var directoryList = listOf([...keys.directory, { owner: true }], "principals", principalId);
731
+ function invite(client) {
732
+ return {
733
+ list: directoryList,
734
+ label: (vars) => vars.principalId,
735
+ targets: (vars) => [saving(principalId(vars))],
736
+ apply: (principals, vars) => principals.some((principal) => principalId(principal) === principalId(vars)) ? principals : [...principals, {
737
+ principalType: vars.principalType,
738
+ principalId: vars.principalId,
739
+ instanceRole: vars.owner ? "owner" : "user",
740
+ isRootAdmin: false
741
+ }],
742
+ affects: () => affects.admission(),
743
+ run: async (vars) => {
744
+ const member = memberRef(vars.principalType, vars.principalId);
745
+ const { members } = await client.members.list();
746
+ if (members.some((entry) => entry.member === member)) throw new Refusal("That principal already exists.");
747
+ await client.members.add(member, { owner: vars.principalType === "user" && vars.owner });
748
+ }
749
+ };
750
+ }
751
+ function changeRole(client) {
752
+ const id = (vars) => memberRef("user", vars.principalId);
753
+ return {
754
+ list: directoryList,
755
+ label: (vars) => `the role of ${vars.principalId}`,
756
+ targets: (vars) => [saving(id(vars))],
757
+ apply: (principals, vars) => principals.map((principal) => principalId(principal) === id(vars) ? {
758
+ ...principal,
759
+ instanceRole: vars.owner ? "owner" : "user"
760
+ } : principal),
761
+ affects: (vars) => affects.role(id(vars)),
762
+ run: (vars) => client.members.add(id(vars), { owner: vars.owner })
763
+ };
764
+ }
765
+ function removeMember(client) {
766
+ return {
767
+ list: directoryList,
768
+ label: (principal) => principal.principalId,
769
+ targets: (principal) => [removing(principalId(principal))],
770
+ affects: (principal) => affects.removal(principalId(principal)),
771
+ run: (principal) => client.members.remove(principalId(principal))
772
+ };
773
+ }
774
+ function revokeCredential(client, serviceId) {
775
+ const member = memberRef("service", serviceId);
776
+ return {
777
+ list: listOf([...keys.credentials(member), { allowed: true }], "tokens", (token) => token.id),
778
+ label: (token) => `token ${token.hint}`,
779
+ targets: (token) => [removing(token.id)],
780
+ removing: REVOKING,
781
+ affects: () => affects.credentials(member),
782
+ run: (token) => client.tokens.revoke(member, token.id)
783
+ };
784
+ }
785
+ function endSession(client) {
786
+ return {
787
+ list: listOf(keys.sessions, "sessions", (session) => session.id),
788
+ label: () => "the session",
789
+ targets: (session) => [removing(session.id)],
790
+ removing: {
791
+ pending: "Ending…",
792
+ done: "ended",
793
+ failed: "Not ended."
794
+ },
795
+ affects: () => affects.sessions(),
796
+ run: (session) => client.sessions.revoke(session.id)
797
+ };
798
+ }
799
+ function unlinkIdentity(client) {
800
+ return {
801
+ list: listOf(keys.identities, "identities", (identity) => identity.id),
802
+ label: (identity) => `the ${identity.label} account`,
803
+ targets: (identity) => [removing(identity.id)],
804
+ removing: {
805
+ pending: "Unlinking…",
806
+ done: "unlinked",
807
+ failed: "Not unlinked."
808
+ },
809
+ affects: () => affects.identities(),
810
+ run: (identity) => client.identities.unlink(identity.id)
811
+ };
812
+ }
813
+ var projectsList = listOf(keys.projects, "projects", (project) => project.slug);
814
+ function createProject(client) {
815
+ return {
816
+ list: projectsList,
817
+ label: (vars) => `project ${vars.slug}`,
818
+ targets: (vars) => [saving(vars.slug)],
819
+ apply: (projects, vars) => [...projects, {
820
+ slug: vars.slug,
821
+ name: vars.name,
822
+ archivedAt: null,
823
+ permissions: [
824
+ "project.manage",
825
+ "environment.manage",
826
+ "grant.manage"
827
+ ],
828
+ environments: [],
829
+ secretCount: null
830
+ }],
831
+ affects: () => affects.places(),
832
+ run: async (vars) => {
833
+ const { created } = await client.projects.create(vars.slug, { name: vars.name });
834
+ if (!created) throw new Refusal(`A project named "${vars.slug}" already exists.`);
835
+ }
836
+ };
837
+ }
838
+ /** One project's environments, held in the project list. */
839
+ function environmentsList(project) {
840
+ const environmentsOf = (data) => data.ok ? data.projects.find((entry) => entry.slug === project)?.environments ?? [] : [];
841
+ return {
842
+ queryKey: keys.projects,
843
+ items: environmentsOf,
844
+ withItems: (data, environments) => data.ok ? {
845
+ ...data,
846
+ projects: data.projects.map((entry) => entry.slug === project ? {
847
+ ...entry,
848
+ environments
849
+ } : entry)
850
+ } : data,
851
+ id: (environment) => environmentId(project, environment.slug)
852
+ };
853
+ }
854
+ function environmentId(project, environment) {
855
+ return `${project}/${environment}`;
856
+ }
857
+ function createEnvironment(client, project) {
858
+ return {
859
+ list: environmentsList(project),
860
+ label: (vars) => `environment ${vars.slug}`,
861
+ targets: (vars) => [saving(environmentId(project, vars.slug))],
862
+ apply: (environments, vars) => [...environments, {
863
+ slug: vars.slug,
864
+ name: vars.name,
865
+ accessible: false,
866
+ details: {
867
+ archivedAt: null,
868
+ secretCount: 0
869
+ }
870
+ }],
871
+ affects: () => affects.places(),
872
+ run: async (vars) => {
873
+ const { created } = await client.environments.create(`${project}/${vars.slug}`, { name: vars.name });
874
+ if (!created) throw new Refusal(`An environment named "${vars.slug}" already exists.`);
875
+ }
876
+ };
877
+ }
878
+ function renameEnvironment(client, project) {
879
+ return {
880
+ list: environmentsList(project),
881
+ label: (vars) => `environment ${vars.from}`,
882
+ targets: (vars) => vars.slug === vars.from ? [saving(environmentId(project, vars.from))] : [saving(environmentId(project, vars.from)), saving(environmentId(project, vars.slug))],
883
+ apply: (environments, vars) => environments.map((environment) => environment.slug === vars.from ? {
884
+ ...environment,
885
+ slug: vars.slug,
886
+ name: vars.name
887
+ } : environment),
888
+ affects: () => affects.places(),
889
+ run: (vars) => client.environments.update(`${project}/${vars.from}`, {
890
+ slug: vars.slug,
891
+ name: vars.name
892
+ })
893
+ };
894
+ }
895
+ /**
896
+ * Archive an environment or bring it back. Archiving ends every read of it,
897
+ * so it waits for the server, as a removal does; restoring shows at once.
898
+ */
899
+ function archiveEnvironment(client, project) {
900
+ const archivedAt = (archived) => archived ? (/* @__PURE__ */ new Date()).toISOString() : null;
901
+ const withArchived = (environment, archived) => environment.details === null ? environment : {
902
+ ...environment,
903
+ details: {
904
+ ...environment.details,
905
+ archivedAt: archivedAt(archived)
906
+ }
907
+ };
908
+ return {
909
+ list: environmentsList(project),
910
+ label: (vars) => `environment ${vars.slug}`,
911
+ targets: (vars) => [vars.archived ? removing(environmentId(project, vars.slug)) : saving(environmentId(project, vars.slug))],
912
+ removing: ARCHIVING,
913
+ apply: (environments, vars) => vars.archived ? environments : environments.map((environment) => environment.slug === vars.slug ? withArchived(environment, false) : environment),
914
+ confirmed: (environments, _vars, archived) => environments.map((environment) => archived.has(environmentId(project, environment.slug)) ? withArchived(environment, true) : environment),
915
+ affects: () => affects.places(),
916
+ run: (vars) => client.environments.update(`${project}/${vars.slug}`, { archived: vars.archived })
917
+ };
918
+ }
919
+ function secretsList(place) {
920
+ return listOf(keys.secrets(place), "keys", (entry) => entry.key);
921
+ }
922
+ /** A save that stopped partway: what is left to retry, as the ledger holds it. */
923
+ var UnsavedEdits = class extends Refusal {
924
+ outcome;
925
+ constructor(outcome) {
926
+ const message = outcome.error instanceof Error ? outcome.error.message : failureMessage(outcome.error);
927
+ super(outcome.applied === 0 ? message : `${message} The renames before it were saved; nothing else was, and the rest is ready to retry.`);
928
+ this.outcome = outcome;
929
+ }
930
+ };
931
+ /**
932
+ * Write the ledger's pending edits, as `applySecretEditBatch` does: renames
933
+ * one by one, then the rest as one patch that lands whole or not at all.
934
+ * New and edited secrets show at once; archived ones stay, struck through,
935
+ * until the server confirms.
936
+ */
937
+ function saveSecrets(client, place, author) {
938
+ const path = `${place.project}/${place.environment}`;
939
+ const edits = (vars) => vars.active.flatMap((entry) => {
940
+ const change = vars.changes[entry.key];
941
+ return change === void 0 ? [] : [{
942
+ entry,
943
+ change
944
+ }];
945
+ });
946
+ return {
947
+ list: secretsList(place),
948
+ label: (vars) => {
949
+ const named = [...vars.drafts.map((draft) => draft.key.trim()), ...edits(vars).map(({ entry }) => entry.key)];
950
+ return named.length === 1 ? named[0] : `${named.length} changes`;
951
+ },
952
+ targets: (vars) => [...vars.drafts.map((draft) => saving(draft.key.trim())), ...edits(vars).flatMap(({ entry, change }) => change.archived ? [removing(entry.key)] : change.key.trim() === entry.key ? [saving(entry.key)] : [saving(entry.key), saving(change.key.trim())])],
953
+ removing: ARCHIVING,
954
+ apply: (entries, vars) => {
955
+ const now = (/* @__PURE__ */ new Date()).toISOString();
956
+ const bumped = (entry, key) => ({
957
+ key,
958
+ archived: false,
959
+ version: (entry?.version ?? 0) + 1,
960
+ updatedAt: now,
961
+ updatedBy: author
962
+ });
963
+ let next = entries.map((entry) => {
964
+ const change = vars.changes[entry.key];
965
+ if (change === void 0 || change.archived) return entry;
966
+ const key = change.key.trim();
967
+ return change.value === null ? {
968
+ ...entry,
969
+ key
970
+ } : bumped(entry, key);
971
+ });
972
+ for (const draft of vars.drafts) {
973
+ const key = draft.key.trim();
974
+ next = next.find((entry) => entry.key === key) === void 0 ? [bumped(void 0, key), ...next] : next.map((entry) => entry.key === key ? bumped(entry, key) : entry);
975
+ }
976
+ return next;
977
+ },
978
+ confirmed: (entries, _vars, archived) => entries.map((entry) => archived.has(entry.key) ? {
979
+ ...entry,
980
+ archived: true
981
+ } : entry),
982
+ affects: () => affects.secrets(place),
983
+ run: async (vars) => {
984
+ const outcome = await applySecretEditBatch({
985
+ active: vars.active,
986
+ drafts: vars.drafts,
987
+ changes: vars.changes,
988
+ operations: {
989
+ rename: async (key, nextKey) => {
990
+ try {
991
+ await client.secrets.rename(`${path}/${key}`, nextKey);
992
+ } catch (error) {
993
+ throw new Refusal(`${key}: ${failureMessage(error)}`);
994
+ }
995
+ },
996
+ write: async (patch) => {
997
+ try {
998
+ await client.secrets.set(path, patch);
999
+ } catch (error) {
1000
+ throw new Refusal(failureMessage(error));
1001
+ }
1002
+ }
1003
+ }
1004
+ });
1005
+ if (outcome.error !== null) throw new UnsavedEdits(outcome);
1006
+ return outcome.applied;
1007
+ }
1008
+ };
1009
+ }
1010
+ /** Restore an archived secret, from the Archived list. */
1011
+ function restoreSecret(client, place) {
1012
+ return {
1013
+ list: secretsList(place),
1014
+ label: (vars) => vars.key,
1015
+ targets: (vars) => [saving(vars.key)],
1016
+ apply: (entries, vars) => entries.map((entry) => entry.key === vars.key ? {
1017
+ ...entry,
1018
+ archived: false
1019
+ } : entry),
1020
+ affects: () => affects.secrets(place),
1021
+ run: (vars) => client.secrets.update(`${place.project}/${place.environment}/${vars.key}`, { archived: false })
1022
+ };
1023
+ }
1024
+ /** Archive one secret, as Undo after a restore does: it stays, struck through, until confirmed. */
1025
+ function archiveSecret(client, place) {
1026
+ return {
1027
+ list: secretsList(place),
1028
+ label: (vars) => vars.key,
1029
+ targets: (vars) => [removing(vars.key)],
1030
+ removing: ARCHIVING,
1031
+ confirmed: (entries, _vars, archived) => entries.map((entry) => archived.has(entry.key) ? {
1032
+ ...entry,
1033
+ archived: true
1034
+ } : entry),
1035
+ affects: () => affects.secrets(place),
1036
+ run: (vars) => client.secrets.update(`${place.project}/${place.environment}/${vars.key}`, { archived: true })
1037
+ };
1038
+ }
1039
+ //#endregion
1040
+ //#region src/lib/optimistic.ts
1041
+ var WORDS = {
1042
+ saving: {
1043
+ pending: "Saving…",
1044
+ done: "saved",
1045
+ failed: "Not saved."
1046
+ },
1047
+ removing: {
1048
+ pending: "Removing…",
1049
+ done: "removed",
1050
+ failed: "Not removed."
1051
+ }
1052
+ };
1053
+ /** Every optimistic change is keyed under this, then its list's key. */
1054
+ var CHANGE = "change";
1055
+ function changeKey(list) {
1056
+ return [CHANGE, ...list];
1057
+ }
1058
+ function changeOptions(queryClient, change) {
1059
+ const { list } = change;
1060
+ const mutationKey = changeKey(list.queryKey);
1061
+ return {
1062
+ mutationKey,
1063
+ mutationFn: change.run,
1064
+ onMutate: async (vars) => {
1065
+ const targets = change.targets(vars);
1066
+ const words = {
1067
+ saving: WORDS.saving,
1068
+ removing: change.removing ?? WORDS.removing
1069
+ };
1070
+ announce(`${change.label(vars)}: ${words[mainKind(targets)].pending}`);
1071
+ await queryClient.cancelQueries({ queryKey: list.queryKey });
1072
+ const previous = queryClient.getQueryData(list.queryKey);
1073
+ if (change.apply !== void 0 && previous !== void 0) {
1074
+ const apply = change.apply;
1075
+ queryClient.setQueryData(list.queryKey, (current) => current === void 0 ? current : list.withItems(current, apply(list.items(current), vars)));
1076
+ }
1077
+ return {
1078
+ previous,
1079
+ targets,
1080
+ words
1081
+ };
1082
+ },
1083
+ onError: (error, vars, context) => {
1084
+ if (context === void 0) return;
1085
+ announce(`${change.label(vars)}: ${context.words[mainKind(context.targets)].failed} ${failureMessage(error)}`, { urgent: true });
1086
+ if (context.previous === void 0 || change.apply === void 0) return;
1087
+ const previous = context.previous;
1088
+ const saved = context.targets.filter((target) => target.kind === "saving").map((target) => target.id);
1089
+ queryClient.setQueryData(list.queryKey, (current) => current === void 0 ? current : revert(list, current, previous, saved));
1090
+ },
1091
+ onSuccess: (_result, vars, context) => {
1092
+ if (context === void 0) return;
1093
+ announce(`${capitalize(change.label(vars))} ${context.words[mainKind(context.targets)].done}`);
1094
+ const gone = new Set(context.targets.filter((target) => target.kind === "removing").map((target) => target.id));
1095
+ if (gone.size > 0) {
1096
+ const confirmed = change.confirmed ?? ((items) => items.filter((item) => !gone.has(list.id(item))));
1097
+ queryClient.setQueryData(list.queryKey, (current) => current === void 0 ? current : list.withItems(current, confirmed(list.items(current), vars, gone)));
1098
+ }
1099
+ },
1100
+ onSettled: (result, _error, vars) => {
1101
+ if (queryClient.isMutating({ mutationKey }) > 1) return;
1102
+ refresh(queryClient, [list.queryKey, ...change.affects(vars, result)]);
1103
+ }
1104
+ };
1105
+ }
1106
+ /**
1107
+ * The list with one change undone: each target as it was before, wherever
1108
+ * it now is, and gone if it was not there. Everything else stays as it is,
1109
+ * including other changes still in flight.
1110
+ */
1111
+ function revert(list, current, previous, targets) {
1112
+ const before = list.items(previous);
1113
+ let items = list.items(current).filter((item) => !targets.includes(list.id(item)));
1114
+ for (const id of targets) {
1115
+ const index = before.findIndex((item) => list.id(item) === id);
1116
+ if (index === -1) continue;
1117
+ const after = before.slice(0, index).filter((item) => items.some((kept) => list.id(kept) === list.id(item))).length;
1118
+ items = [
1119
+ ...items.slice(0, after),
1120
+ before[index],
1121
+ ...items.slice(after)
1122
+ ];
1123
+ }
1124
+ return list.withItems(current, items);
1125
+ }
1126
+ /** What a change mostly does, to word it as a whole: a save, unless it only removes. */
1127
+ function mainKind(targets) {
1128
+ return targets.length > 0 && targets.every((target) => target.kind === "removing") ? "removing" : "saving";
1129
+ }
1130
+ /**
1131
+ * An item's status, from the changes to its list: the latest one that
1132
+ * touches it decides, so retrying clears an old failure.
1133
+ */
1134
+ function itemStatus(changes, id) {
1135
+ let latest;
1136
+ for (const change of changes) {
1137
+ if (change.state.context?.targets.some((target) => target.id === id) !== true) continue;
1138
+ if (latest === void 0 || change.state.submittedAt >= latest.state.submittedAt) latest = change;
1139
+ }
1140
+ const context = latest?.state.context;
1141
+ if (latest === void 0 || context === void 0) return { state: "idle" };
1142
+ const kind = context.targets.find((target) => target.id === id).kind;
1143
+ const words = context.words[kind];
1144
+ if (latest.state.status === "pending") return {
1145
+ state: "pending",
1146
+ kind,
1147
+ words
1148
+ };
1149
+ if (latest.state.status === "error") return {
1150
+ state: "failed",
1151
+ kind,
1152
+ words,
1153
+ error: failureMessage(latest.state.error),
1154
+ mutationId: latest.mutationId
1155
+ };
1156
+ return { state: "idle" };
1157
+ }
1158
+ /**
1159
+ * The adds the server refused whose items are not listed: each is shown as
1160
+ * a row of its own. Asked again and refused again, an add is listed once,
1161
+ * as the latest refusal.
1162
+ */
1163
+ function failedAdds(changes, present) {
1164
+ return changes.flatMap((change) => {
1165
+ const context = change.state.context;
1166
+ if (change.state.status !== "error" || context === void 0) return [];
1167
+ const added = context.targets.filter((target) => target.kind === "saving" && !present.includes(target.id));
1168
+ if (added.length === 0 || added.length < context.targets.length) return [];
1169
+ const status = itemStatus(changes, added[0].id);
1170
+ if (status.state !== "failed" || status.mutationId !== change.mutationId) return [];
1171
+ const ids = added.map((target) => target.id);
1172
+ return [{
1173
+ mutationId: change.mutationId,
1174
+ vars: change.state.variables,
1175
+ ids,
1176
+ status
1177
+ }];
1178
+ });
1179
+ }
1180
+ /** Forget a failure once its row has said so and been dismissed. */
1181
+ function dismiss(queryClient, mutationId) {
1182
+ const cache = queryClient.getMutationCache();
1183
+ const mutation = cache.getAll().find((entry) => entry.mutationId === mutationId);
1184
+ if (mutation !== void 0) cache.remove(mutation);
1185
+ }
1186
+ function capitalize(text) {
1187
+ return text.charAt(0).toUpperCase() + text.slice(1);
1188
+ }
1189
+ //#endregion
1190
+ //#region src/lib/use-change.ts
1191
+ /** Make a change that shows before the server answers (`lib/optimistic.ts`). */
1192
+ function useChange(change) {
1193
+ return useMutation(changeOptions(useQueryClient(), change)).mutate;
1194
+ }
1195
+ /** How each item of a list stands, from the changes made to it here. */
1196
+ function useChangeStatus(list) {
1197
+ const queryClient = useQueryClient();
1198
+ const changes = useMutationState({
1199
+ filters: { mutationKey: changeKey(list) },
1200
+ select: (mutation) => ({
1201
+ mutationId: mutation.mutationId,
1202
+ state: mutation.state
1203
+ })
1204
+ });
1205
+ return {
1206
+ status: (0, import_react.useCallback)((id) => itemStatus(changes, id), [changes]),
1207
+ failedAdds: (0, import_react.useCallback)((present) => failedAdds(changes, present), [changes]),
1208
+ dismiss: (0, import_react.useCallback)((mutationId) => dismiss(queryClient, mutationId), [queryClient])
1209
+ };
1210
+ }
1211
+ //#endregion
1212
+ export { hasSecretEditConflict as C, projectAccessOptions as D, projectAccessLabel as E, unlinkIdentity as S, parseProjectAccess as T, renameEnvironment as _, archiveSecret as a, revokeGrant as b, createProject as c, environmentId as d, grantAccess as f, removeMember as g, projectsList as h, archiveEnvironment as i, directoryList as l, invite as m, useChangeStatus as n, changeRole as o, grantId as p, UnsavedEdits as r, createEnvironment as s, useChange as t, endSession as u, restoreSecret as v, secretChangeFor as w, saveSecrets as x, revokeCredential as y };