@coffre/ui 0.1.10 → 0.1.12

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 (172) hide show
  1. package/dist/client/_coffre/assets/account-CyJDFhek.js +2 -0
  2. package/dist/client/_coffre/assets/account-DHSs5h2f.js +1 -0
  3. package/dist/client/_coffre/assets/affordances-BQD5B421.js +1 -0
  4. package/dist/client/_coffre/assets/audit-Bcyp_dU1.js +2 -0
  5. package/dist/client/_coffre/assets/audit-rMy9mU9Q.js +1 -0
  6. package/dist/client/_coffre/assets/auth.device-DuvaComb.js +1 -0
  7. package/dist/client/_coffre/assets/auth.device-yBt_sLZW.js +2 -0
  8. package/dist/client/_coffre/assets/directory-C4BMGC7-.js +1 -0
  9. package/dist/client/_coffre/assets/dist-BNkBTkxj.js +1 -0
  10. package/dist/client/_coffre/assets/globals-BJkzu6T5.css +1 -0
  11. package/dist/client/_coffre/assets/grants-CyDW25eX.js +1 -0
  12. package/dist/client/_coffre/assets/icons-BRl8DlXW.js +1 -0
  13. package/dist/client/_coffre/assets/index-CA1mtrIx.js +12 -0
  14. package/dist/client/_coffre/assets/link-CqlAJWBd.js +1 -0
  15. package/dist/client/_coffre/assets/login-B73b6bsJ.js +1 -0
  16. package/dist/client/_coffre/assets/login-BO1KAGPU.js +2 -0
  17. package/dist/client/_coffre/assets/offboarding--5vSKNHv.js +1 -0
  18. package/dist/client/_coffre/assets/page-Dngv8FMr.js +1 -0
  19. package/dist/client/_coffre/assets/preload-helper-DBha3tys.js +1 -0
  20. package/dist/client/_coffre/assets/principal-page-C4qDD-d8.js +1 -0
  21. package/dist/client/_coffre/assets/projects._project._environment-eBKxOZ0_.js +2 -0
  22. package/dist/client/_coffre/assets/projects._project._environment-or_AX6o5.js +3 -0
  23. package/dist/client/_coffre/assets/projects._project.index-DHdXfEh-.js +2 -0
  24. package/dist/client/_coffre/assets/projects._project.index-iynQgenH.js +1 -0
  25. package/dist/client/_coffre/assets/projects.index-CGW8mRil.js +1 -0
  26. package/dist/client/_coffre/assets/row-state-BlarvG7E.js +1 -0
  27. package/dist/client/_coffre/assets/settings-D-7RJIDf.js +1 -0
  28. package/dist/client/_coffre/assets/suspense-q_eJaZ18.js +1 -0
  29. package/dist/client/_coffre/assets/tokens._token-0u7midqA.js +2 -0
  30. package/dist/client/_coffre/assets/tokens._token-C53NqScg.js +1 -0
  31. package/dist/client/_coffre/assets/tokens.index-DBZTLnbi.js +1 -0
  32. package/dist/client/_coffre/assets/ui-BPWFJNz7.js +46 -0
  33. package/dist/client/_coffre/assets/unregistered-CLhgtwUt.js +1 -0
  34. package/dist/client/_coffre/assets/use-action-LULgF26O.js +1 -0
  35. package/dist/client/_coffre/assets/use-change-Bd6NZJj9.js +1 -0
  36. package/dist/client/_coffre/assets/use-shell-Dx92Huhb.js +1 -0
  37. package/dist/client/_coffre/assets/useQuery-BIIZz1CB.js +1 -0
  38. package/dist/client/_coffre/assets/useSuspenseQuery-tP9HFZ8w.js +1 -0
  39. package/dist/client/_coffre/assets/users._user-BXtaL8Ee.js +2 -0
  40. package/dist/client/_coffre/assets/users._user-CNYVkXaY.js +1 -0
  41. package/dist/client/_coffre/assets/users.index-Cs9tibIv.js +1 -0
  42. package/dist/server/.vite/manifest.json +342 -246
  43. package/dist/server/_coffre/assets/_tanstack-start-manifest_v-T9tMsCwo.js +162 -0
  44. package/dist/server/_coffre/assets/{account-CUQYGCYh.js → account-BUhhOS5-.js} +150 -117
  45. package/dist/server/_coffre/assets/{account-DMlUoBxQ.js → account-B_h55GCs.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-B8Ck358-.js} +46 -16
  49. package/dist/server/_coffre/assets/audit-DFsXfeAQ.js +31 -0
  50. package/dist/server/_coffre/assets/{auth.device-BoFM1jcf.js → auth.device-BXf_JjT7.js} +5 -5
  51. package/dist/server/_coffre/assets/{auth.device-C05u5ROO.js → auth.device-cqjWACvB.js} +7 -5
  52. package/dist/server/_coffre/assets/{directory-GsnYkse0.js → directory-C9SfNgpM.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-BJkzu6T5.css +1 -0
  55. package/dist/server/_coffre/assets/grants--315KmXu.js +158 -0
  56. package/dist/server/_coffre/assets/{page-BdnhpwvH.js → icons-CWsTEfpn.js} +125 -436
  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-CQSkYW_D.js} +7 -5
  60. package/dist/server/_coffre/assets/{login-B2njIq_o.js → login-LBpXXfsQ.js} +2 -2
  61. package/dist/server/_coffre/assets/matchContext-qLfYbC6_.js +56 -0
  62. package/dist/server/_coffre/assets/{offboarding-8yMa7ViM.js → offboarding-CykelNis.js} +11 -79
  63. package/dist/server/_coffre/assets/page-BGeDoQO5.js +3531 -0
  64. package/dist/server/_coffre/assets/{principal-page-B8zPcS2b.js → principal-page-CRdoAQOq.js} +51 -42
  65. package/dist/server/_coffre/assets/{projects._project._environment-DdIOc7wx.js → projects._project._environment-BXU1Mee5.js} +4 -11
  66. package/dist/server/_coffre/assets/{projects._project._environment-BZ5Z80V8.js → projects._project._environment-BrDqn8kW.js} +129 -748
  67. package/dist/server/_coffre/assets/{projects._project.index-CuEAUwGn.js → projects._project.index-CAxBU4tY.js} +134 -96
  68. package/dist/server/_coffre/assets/{projects._project.index-DvbcU1kh.js → projects._project.index-CYyUVTCl.js} +5 -4
  69. package/dist/server/_coffre/assets/{projects.index-5HI0wOuG.js → projects.index-D6ZoDE_0.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-Bu2qtyqw.js} +376 -92
  72. package/dist/server/_coffre/assets/row-state-CAItu3n_.js +117 -0
  73. package/dist/server/_coffre/assets/{settings-BVz78wjP.js → settings-ByeF6hBa.js} +8 -6
  74. package/dist/server/_coffre/assets/suspense-beD01bb8.js +602 -0
  75. package/dist/server/_coffre/assets/tokens._token-CM01QPCq.js +10 -0
  76. package/dist/server/_coffre/assets/{tokens._token-CWs3Mtki.js → tokens._token-D2E4P3Qc.js} +97 -79
  77. package/dist/server/_coffre/assets/{tokens.index-Ck0LN7aC.js → tokens.index-Cmrgn3mU.js} +9 -6
  78. package/dist/server/_coffre/assets/{ui-D_slKpSF.js → ui-DvlGkmaH.js} +7 -836
  79. package/dist/server/_coffre/assets/{unregistered-Z17da4Rc.js → unregistered-DSArejP9.js} +5 -3
  80. package/dist/server/_coffre/assets/use-action-C2wz34kq.js +47 -0
  81. package/dist/server/_coffre/assets/use-change-CJpGSNIq.js +1212 -0
  82. package/dist/server/_coffre/assets/use-shell-C3iYcyP1.js +462 -0
  83. package/dist/server/_coffre/assets/useQuery-ChxaQ4Cb.js +8 -0
  84. package/dist/server/_coffre/assets/{useStore-DWGPqzXR.js → useRouter-CaUSUNsw.js} +1 -420
  85. package/dist/server/_coffre/assets/useSuspenseQuery-BjAmlGZl.js +117 -0
  86. package/dist/server/_coffre/assets/users._user-BVeR9fZP.js +10 -0
  87. package/dist/server/_coffre/assets/{users._user-CMwj-VI9.js → users._user-Cih2Etf4.js} +4 -5
  88. package/dist/server/_coffre/assets/{users.index-fWHv6A30.js → users.index-Bo2_a95G.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/icons.tsx +0 -34
  94. package/src/components/offboarding.tsx +1 -52
  95. package/src/components/principal-page.tsx +54 -67
  96. package/src/components/principal-picker.tsx +7 -16
  97. package/src/components/row-state.tsx +95 -0
  98. package/src/components/service-tokens.tsx +75 -64
  99. package/src/components/shell.tsx +1 -1
  100. package/src/lib/announce.ts +36 -0
  101. package/src/lib/changes.ts +498 -0
  102. package/src/lib/coffre.ts +1 -1
  103. package/src/lib/optimistic.ts +233 -0
  104. package/src/lib/queries.ts +385 -0
  105. package/src/lib/use-action.ts +20 -15
  106. package/src/lib/use-change.ts +42 -0
  107. package/src/lib/use-shell.ts +17 -0
  108. package/src/router.tsx +17 -9
  109. package/src/routes/__root.tsx +8 -38
  110. package/src/routes/account.tsx +163 -154
  111. package/src/routes/audit.tsx +51 -72
  112. package/src/routes/auth.device.tsx +4 -2
  113. package/src/routes/login.tsx +3 -2
  114. package/src/routes/projects.$project.$environment.tsx +223 -238
  115. package/src/routes/projects.$project.index.tsx +136 -118
  116. package/src/routes/projects.index.tsx +117 -145
  117. package/src/routes/settings.tsx +7 -7
  118. package/src/routes/tokens.$token.tsx +14 -17
  119. package/src/routes/tokens.index.tsx +8 -4
  120. package/src/routes/unregistered.tsx +3 -2
  121. package/src/routes/users.$user.tsx +4 -4
  122. package/src/routes/users.index.tsx +8 -4
  123. package/src/shared/models.ts +1 -5
  124. package/src/styles/globals.css +80 -50
  125. package/dist/client/_coffre/assets/account-B48wuSF8.js +0 -1
  126. package/dist/client/_coffre/assets/account-BkNyIDT7.js +0 -2
  127. package/dist/client/_coffre/assets/affordances-CmoY-8Xf.js +0 -1
  128. package/dist/client/_coffre/assets/audit-BvwKYb-5.js +0 -2
  129. package/dist/client/_coffre/assets/audit-D02H-zxS.js +0 -1
  130. package/dist/client/_coffre/assets/auth.device-BP5FY0K1.js +0 -1
  131. package/dist/client/_coffre/assets/auth.device-DYOONgFF.js +0 -2
  132. package/dist/client/_coffre/assets/coffre-BBp7cKVa.js +0 -1
  133. package/dist/client/_coffre/assets/directory-Bu0EIxqI.js +0 -1
  134. package/dist/client/_coffre/assets/globals-Bh2x1gBM.css +0 -1
  135. package/dist/client/_coffre/assets/grants-DavcwofW.js +0 -1
  136. package/dist/client/_coffre/assets/index-CDPlq5rM.js +0 -12
  137. package/dist/client/_coffre/assets/login-C-wTm_t1.js +0 -2
  138. package/dist/client/_coffre/assets/login-CLLv1om9.js +0 -1
  139. package/dist/client/_coffre/assets/offboarding-DWsE2FSa.js +0 -1
  140. package/dist/client/_coffre/assets/page-DbSS7pYH.js +0 -1
  141. package/dist/client/_coffre/assets/preload-helper-DduCCcmc.js +0 -46
  142. package/dist/client/_coffre/assets/principal-page-Bp_iwuSd.js +0 -1
  143. package/dist/client/_coffre/assets/projects._project._environment-BMeX_B8l.js +0 -2
  144. package/dist/client/_coffre/assets/projects._project._environment-CT0A-hIU.js +0 -3
  145. package/dist/client/_coffre/assets/projects._project.index-C_xYOGLT.js +0 -2
  146. package/dist/client/_coffre/assets/projects._project.index-Chcf-cUd.js +0 -1
  147. package/dist/client/_coffre/assets/projects.index-CfOtb1X5.js +0 -2
  148. package/dist/client/_coffre/assets/projects.index-DSjOhLDh.js +0 -1
  149. package/dist/client/_coffre/assets/settings-BC9cUJNK.js +0 -1
  150. package/dist/client/_coffre/assets/settings-Bkj_E21y.js +0 -2
  151. package/dist/client/_coffre/assets/tokens._token-BA0KqvaW.js +0 -1
  152. package/dist/client/_coffre/assets/tokens._token-Dh9jLOkm.js +0 -2
  153. package/dist/client/_coffre/assets/tokens.index-BgAMWkHT.js +0 -2
  154. package/dist/client/_coffre/assets/tokens.index-CHueIAv1.js +0 -1
  155. package/dist/client/_coffre/assets/unregistered-D5go1AfR.js +0 -1
  156. package/dist/client/_coffre/assets/use-action-l__xZDYY.js +0 -1
  157. package/dist/client/_coffre/assets/users._user-Dwqa0gv5.js +0 -1
  158. package/dist/client/_coffre/assets/users._user-xJAb3T6Y.js +0 -2
  159. package/dist/client/_coffre/assets/users.index-BJoF-L37.js +0 -2
  160. package/dist/client/_coffre/assets/users.index-YUjtbTGy.js +0 -1
  161. package/dist/server/_coffre/assets/_tanstack-start-manifest_v-BKg2AlPu.js +0 -133
  162. package/dist/server/_coffre/assets/audit-CThXn2v7.js +0 -74
  163. package/dist/server/_coffre/assets/coffre-C2ANsTAz.js +0 -281
  164. package/dist/server/_coffre/assets/globals-Bh2x1gBM.css +0 -1
  165. package/dist/server/_coffre/assets/grants-B6k4Fu9z.js +0 -243
  166. package/dist/server/_coffre/assets/projects.index-uiomWX_l.js +0 -54
  167. package/dist/server/_coffre/assets/settings-4oRyDizv.js +0 -18
  168. package/dist/server/_coffre/assets/tokens._token-CF_deAwq.js +0 -18
  169. package/dist/server/_coffre/assets/tokens.index-DF_07KEe.js +0 -10
  170. package/dist/server/_coffre/assets/users._user-DUzwkSKT.js +0 -10
  171. package/dist/server/_coffre/assets/users.index-BbuweTwH.js +0 -10
  172. package/src/components/syncs.tsx +0 -581
@@ -0,0 +1,233 @@
1
+ import type { Mutation, MutationOptions, QueryClient, QueryKey } from '@tanstack/react-query';
2
+
3
+ import { announce } from './announce.ts';
4
+ import { failureMessage } from './coffre.ts';
5
+ import { refresh } from './queries.ts';
6
+
7
+ /**
8
+ * Changes that show before the server answers.
9
+ *
10
+ * An add or an edit shows at once, as it will be, marked as saving; a removal
11
+ * keeps its row, struck through, until the server confirms it, since access
12
+ * must never look gone while it still holds. Either way, if the server
13
+ * refuses, the list goes back to what it was and the row says why
14
+ * (`failureMessage`: the API's own sentence where it gives one), until
15
+ * dismissed or retried.
16
+ *
17
+ * Several changes can be in flight at once, so a failure undoes its own
18
+ * items only, not the whole list as it was when it started; and the list is
19
+ * read back from the server once the last change to it has landed, so one
20
+ * landing does not erase another still on its way.
21
+ */
22
+
23
+ /** What a row is waiting for. */
24
+ export type Pending = 'saving' | 'removing';
25
+
26
+ /** One item a change touches, and how. */
27
+ export type Target = { id: string; kind: Pending };
28
+
29
+ /** How a change is worded on its row: "Archiving…", "Not archived." */
30
+ export type Words = { pending: string; done: string; failed: string };
31
+
32
+ const WORDS: Record<Pending, Words> = {
33
+ saving: { pending: 'Saving…', done: 'saved', failed: 'Not saved.' },
34
+ removing: { pending: 'Removing…', done: 'removed', failed: 'Not removed.' },
35
+ };
36
+
37
+ /** How one cached query holds a list of items, each with an identity. */
38
+ export type ListShape<TData, TItem> = {
39
+ queryKey: QueryKey;
40
+ items: (data: TData) => TItem[];
41
+ withItems: (data: TData, items: TItem[]) => TData;
42
+ id: (item: TItem) => string;
43
+ };
44
+
45
+ export type Change<TData, TItem, TVars, TResult> = {
46
+ list: ListShape<TData, TItem>;
47
+ /** What the change is called, for the screen reader: "access for dev@acme.example". */
48
+ label: (vars: TVars) => string;
49
+ /**
50
+ * The items it touches, whose rows show it: saved ones as they will be,
51
+ * removed ones as they are until confirmed. A rename touches both names.
52
+ */
53
+ targets: (vars: TVars) => Target[];
54
+ /** How removals are worded, when not as removals: archiving, revoking. */
55
+ removing?: Words;
56
+ /** The items as they will be once the saves land; removals are left for the server. */
57
+ apply?: (items: TItem[], vars: TVars) => TItem[];
58
+ /** The items once the server confirms; by default, without those removed. Archiving keeps them, archived. */
59
+ confirmed?: (items: TItem[], vars: TVars, removed: ReadonlySet<string>) => TItem[];
60
+ /** Anything else it touches, refetched once it lands (`affects` in `queries.ts`). */
61
+ affects: (vars: TVars, result: TResult | undefined) => QueryKey[];
62
+ run: (vars: TVars) => Promise<TResult>;
63
+ };
64
+
65
+ /** What `onMutate` keeps: the list as it was, and what the rows should show. */
66
+ export type ChangeContext = { previous: unknown; targets: Target[]; words: Record<Pending, Words> };
67
+
68
+ /** Every optimistic change is keyed under this, then its list's key. */
69
+ export const CHANGE = 'change';
70
+
71
+ export function changeKey(list: QueryKey): QueryKey {
72
+ return [CHANGE, ...list];
73
+ }
74
+
75
+ export function changeOptions<TData, TItem, TVars, TResult>(
76
+ queryClient: QueryClient,
77
+ change: Change<TData, TItem, TVars, TResult>,
78
+ ): MutationOptions<TResult, unknown, TVars, ChangeContext> {
79
+ const { list } = change;
80
+ const mutationKey = changeKey(list.queryKey);
81
+ return {
82
+ mutationKey,
83
+ mutationFn: change.run,
84
+ onMutate: async (vars) => {
85
+ const targets = change.targets(vars);
86
+ const words = { saving: WORDS.saving, removing: change.removing ?? WORDS.removing };
87
+ announce(`${change.label(vars)}: ${words[mainKind(targets)].pending}`);
88
+ // A read already on its way would land over the change.
89
+ await queryClient.cancelQueries({ queryKey: list.queryKey });
90
+ const previous = queryClient.getQueryData<TData>(list.queryKey);
91
+ if (change.apply !== undefined && previous !== undefined) {
92
+ const apply = change.apply;
93
+ queryClient.setQueryData<TData>(list.queryKey, (current) =>
94
+ current === undefined ? current : list.withItems(current, apply(list.items(current), vars)),
95
+ );
96
+ }
97
+ return { previous, targets, words };
98
+ },
99
+ onError: (error, vars, context) => {
100
+ if (context === undefined) return;
101
+ announce(
102
+ `${change.label(vars)}: ${context.words[mainKind(context.targets)].failed} ${failureMessage(error)}`,
103
+ { urgent: true },
104
+ );
105
+ if (context.previous === undefined || change.apply === undefined) return;
106
+ const previous = context.previous as TData;
107
+ const saved = context.targets.filter((target) => target.kind === 'saving').map((target) => target.id);
108
+ queryClient.setQueryData<TData>(list.queryKey, (current) =>
109
+ current === undefined ? current : revert(list, current, previous, saved),
110
+ );
111
+ },
112
+ onSuccess: (_result, vars, context) => {
113
+ if (context === undefined) return;
114
+ announce(`${capitalize(change.label(vars))} ${context.words[mainKind(context.targets)].done}`);
115
+ // Confirmed: the rows removed can go now, before the list is read back.
116
+ const gone = new Set(
117
+ context.targets.filter((target) => target.kind === 'removing').map((target) => target.id),
118
+ );
119
+ if (gone.size > 0) {
120
+ const confirmed =
121
+ change.confirmed ?? ((items: TItem[]) => items.filter((item) => !gone.has(list.id(item))));
122
+ queryClient.setQueryData<TData>(list.queryKey, (current) =>
123
+ current === undefined ? current : list.withItems(current, confirmed(list.items(current), vars, gone)),
124
+ );
125
+ }
126
+ },
127
+ onSettled: (result, _error, vars) => {
128
+ // This one still counts as in flight here.
129
+ if (queryClient.isMutating({ mutationKey }) > 1) return;
130
+ // Not awaited: the row settles when the server answers, and the list
131
+ // is read back behind it.
132
+ void refresh(queryClient, [list.queryKey, ...change.affects(vars, result)]);
133
+ },
134
+ };
135
+ }
136
+
137
+ /**
138
+ * The list with one change undone: each target as it was before, wherever
139
+ * it now is, and gone if it was not there. Everything else stays as it is,
140
+ * including other changes still in flight.
141
+ */
142
+ export function revert<TData, TItem>(
143
+ list: ListShape<TData, TItem>,
144
+ current: TData,
145
+ previous: TData,
146
+ targets: string[],
147
+ ): TData {
148
+ const before = list.items(previous);
149
+ let items = list.items(current).filter((item) => !targets.includes(list.id(item)));
150
+ for (const id of targets) {
151
+ const index = before.findIndex((item) => list.id(item) === id);
152
+ if (index === -1) continue;
153
+ // Back where it was, counting only what is still there before it.
154
+ const after = before
155
+ .slice(0, index)
156
+ .filter((item) => items.some((kept) => list.id(kept) === list.id(item))).length;
157
+ items = [...items.slice(0, after), before[index]!, ...items.slice(after)];
158
+ }
159
+ return list.withItems(current, items);
160
+ }
161
+
162
+ /** What a change mostly does, to word it as a whole: a save, unless it only removes. */
163
+ function mainKind(targets: Target[]): Pending {
164
+ return targets.length > 0 && targets.every((target) => target.kind === 'removing') ? 'removing' : 'saving';
165
+ }
166
+
167
+ /** What a row shows: nothing, a change on its way, or one the server refused. */
168
+ export type ItemStatus =
169
+ | { state: 'idle' }
170
+ | { state: 'pending'; kind: Pending; words: Words }
171
+ | { state: 'failed'; kind: Pending; words: Words; error: string; mutationId: number };
172
+
173
+ type Tracked = Pick<Mutation<unknown, unknown, unknown, ChangeContext>, 'mutationId' | 'state'>;
174
+
175
+ /**
176
+ * An item's status, from the changes to its list: the latest one that
177
+ * touches it decides, so retrying clears an old failure.
178
+ */
179
+ export function itemStatus(changes: readonly Tracked[], id: string): ItemStatus {
180
+ let latest: Tracked | undefined;
181
+ for (const change of changes) {
182
+ if (change.state.context?.targets.some((target) => target.id === id) !== true) continue;
183
+ if (latest === undefined || change.state.submittedAt >= latest.state.submittedAt) latest = change;
184
+ }
185
+ const context = latest?.state.context;
186
+ if (latest === undefined || context === undefined) return { state: 'idle' };
187
+ const kind = context.targets.find((target) => target.id === id)!.kind;
188
+ const words = context.words[kind];
189
+ if (latest.state.status === 'pending') return { state: 'pending', kind, words };
190
+ if (latest.state.status === 'error') {
191
+ const error = failureMessage(latest.state.error);
192
+ return { state: 'failed', kind, words, error, mutationId: latest.mutationId };
193
+ }
194
+ return { state: 'idle' };
195
+ }
196
+
197
+ /** A refused add: no row is left to say so, so it gets one of its own. */
198
+ export type FailedAdd<TVars> = {
199
+ mutationId: number;
200
+ vars: TVars;
201
+ /** The ids it would have added. */
202
+ ids: string[];
203
+ status: Extract<ItemStatus, { state: 'failed' }>;
204
+ };
205
+
206
+ /**
207
+ * The adds the server refused whose items are not listed: each is shown as
208
+ * a row of its own. Asked again and refused again, an add is listed once,
209
+ * as the latest refusal.
210
+ */
211
+ export function failedAdds<TVars>(changes: readonly Tracked[], present: readonly string[]): FailedAdd<TVars>[] {
212
+ return changes.flatMap((change) => {
213
+ const context = change.state.context;
214
+ if (change.state.status !== 'error' || context === undefined) return [];
215
+ const added = context.targets.filter((target) => target.kind === 'saving' && !present.includes(target.id));
216
+ if (added.length === 0 || added.length < context.targets.length) return [];
217
+ const status = itemStatus(changes, added[0]!.id);
218
+ if (status.state !== 'failed' || status.mutationId !== change.mutationId) return [];
219
+ const ids = added.map((target) => target.id);
220
+ return [{ mutationId: change.mutationId, vars: change.state.variables as TVars, ids, status }];
221
+ });
222
+ }
223
+
224
+ /** Forget a failure once its row has said so and been dismissed. */
225
+ export function dismiss(queryClient: QueryClient, mutationId: number): void {
226
+ const cache = queryClient.getMutationCache();
227
+ const mutation = cache.getAll().find((entry) => entry.mutationId === mutationId);
228
+ if (mutation !== undefined) cache.remove(mutation);
229
+ }
230
+
231
+ function capitalize(text: string): string {
232
+ return text.charAt(0).toUpperCase() + text.slice(1);
233
+ }
@@ -0,0 +1,385 @@
1
+ import type { AuthInfo, CoffreClient, Member } from '@coffre/client';
2
+ import { QueryClient, queryOptions, type QueryKey } from '@tanstack/react-query';
3
+
4
+ import { deriveUiCapabilities } from './capabilities.ts';
5
+ import { memberRef, statusOf, uiResult } from './coffre.ts';
6
+ import type { DirectoryPrincipal, GrantRow, Me, ProjectSummary } from '../shared/models';
7
+
8
+ /**
9
+ * Every read the pages make, cached by TanStack Query: one cache per request
10
+ * on the server, whose reads the page carries to the browser's, and one in the
11
+ * browser for the whole visit.
12
+ *
13
+ * How fresh a page is. A read is reused for `FRESH_MS`, refetched when the
14
+ * window regains focus, and refetched at once by any change made here, which
15
+ * names what it touches (`affects`), so your own changes always show.
16
+ * Someone else's change shows within that window. Nothing is decided on a
17
+ * cached read: the server authorizes every call, so a stale screen can offer
18
+ * an action the server then refuses, never grant one. The audit log and the
19
+ * chain's verification are the exception, read fresh on every visit: their
20
+ * whole point is to be current.
21
+ */
22
+ export const FRESH_MS = 10_000;
23
+
24
+ export function createQueryClient(): QueryClient {
25
+ return new QueryClient({
26
+ defaultOptions: {
27
+ queries: {
28
+ staleTime: FRESH_MS,
29
+ refetchOnWindowFocus: true,
30
+ // A read either answers or says why it cannot (`uiResult`), so a
31
+ // throw is a fault, and asking again would only repeat it.
32
+ retry: false,
33
+ },
34
+ },
35
+ });
36
+ }
37
+
38
+ type Place = { project: string; environment: string };
39
+
40
+ /**
41
+ * The keys, which `affects` names too. A project's keys start with it, so
42
+ * one invalidation covers everything read under it.
43
+ */
44
+ export const keys = {
45
+ me: ['me'],
46
+ auth: ['auth'],
47
+ projects: ['projects'],
48
+ grants: (project: string) => ['grants', project],
49
+ secrets: ({ project, environment }: Place) => ['secrets', project, environment],
50
+ directory: ['directory'],
51
+ report: (member: string) => ['report', member],
52
+ credentials: (member: string) => ['credentials', member],
53
+ identities: ['identities'],
54
+ sessions: ['sessions'],
55
+ audit: ['audit'],
56
+ } satisfies Record<string, QueryKey | ((...args: never[]) => QueryKey)>;
57
+
58
+ /** One member's grants, as rows. */
59
+ function grantRows(members: Member[]): GrantRow[] {
60
+ return members.flatMap((member) =>
61
+ member.grants.map((grant) => ({
62
+ id: grant.id,
63
+ principalType: member.principalType,
64
+ principalId: member.principalId,
65
+ role: grant.role,
66
+ roleName: grant.roleName,
67
+ permissions: grant.permissions,
68
+ scope: grant.environment === null ? ('project' as const) : ('environment' as const),
69
+ environmentSlug: grant.environment,
70
+ expiresAt: grant.expiresAt,
71
+ })),
72
+ );
73
+ }
74
+
75
+ function listDirectory(client: CoffreClient) {
76
+ return uiResult(async () => {
77
+ const { members, removed } = await client.members.list();
78
+ const principals: DirectoryPrincipal[] = members.map(
79
+ ({ principalType, principalId, instanceRole, isRootAdmin, tampered }) => ({
80
+ principalType,
81
+ principalId,
82
+ instanceRole,
83
+ isRootAdmin,
84
+ tampered,
85
+ }),
86
+ );
87
+ return { principals, removed };
88
+ });
89
+ }
90
+
91
+ const readProjects = (client: CoffreClient) => uiResult(() => client.projects.list());
92
+
93
+ /** The projects you can see, or why they could not be listed. */
94
+ export type ProjectsResult = Awaited<ReturnType<typeof readProjects>>;
95
+
96
+ export type AuditSearch = { decision?: 'deny'; actorId?: string; detail?: '1' };
97
+
98
+ export const AUDIT_PAGE_SIZE = 200;
99
+
100
+ export const queries = {
101
+ /** Who is looking; null when nobody is signed in. */
102
+ me: (client: CoffreClient) =>
103
+ queryOptions({
104
+ queryKey: keys.me,
105
+ queryFn: async (): Promise<Me | null> => {
106
+ try {
107
+ return await client.me();
108
+ } catch (error) {
109
+ if (statusOf(error) === 401) return null;
110
+ throw error;
111
+ }
112
+ },
113
+ }),
114
+
115
+ /** How this instance signs people in. */
116
+ auth: (client: CoffreClient) => queryOptions({ queryKey: keys.auth, queryFn: (): Promise<AuthInfo> => client.auth() }),
117
+
118
+ /** The projects you can see, each with its distinct secret count. */
119
+ projects: (client: CoffreClient) =>
120
+ queryOptions({ queryKey: keys.projects, queryFn: () => readProjects(client) }),
121
+
122
+ /** Who holds what in a project, for those who manage its access. */
123
+ grants: (client: CoffreClient, project: string) =>
124
+ queryOptions({
125
+ queryKey: keys.grants(project),
126
+ queryFn: () => uiResult(async () => ({ grants: grantRows((await client.members.list(project)).members) })),
127
+ }),
128
+
129
+ secrets: (client: CoffreClient, place: Place) =>
130
+ queryOptions({
131
+ queryKey: keys.secrets(place),
132
+ queryFn: () => uiResult(() => client.secrets.list(`${place.project}/${place.environment}`)),
133
+ }),
134
+
135
+ /**
136
+ * Everyone in the directory, and who was removed. The API shows grant
137
+ * managers the members of their projects; the directory pages stay the
138
+ * owners' own, and asking for anyone else would only log a refusal, so
139
+ * nobody else is asked.
140
+ */
141
+ directory: (client: CoffreClient, owner: boolean) =>
142
+ queryOptions({
143
+ queryKey: [...keys.directory, { owner }],
144
+ queryFn: () =>
145
+ owner
146
+ ? listDirectory(client)
147
+ : Promise.resolve({
148
+ ok: false as const,
149
+ error: 'Only owners can manage users and service accounts.',
150
+ signedOut: false,
151
+ }),
152
+ }),
153
+
154
+ /** What one member can reach and has seen; null for anyone but owners, who alone may ask. */
155
+ report: (client: CoffreClient, member: string, owner: boolean) =>
156
+ queryOptions({
157
+ queryKey: [...keys.report(member), { owner }],
158
+ queryFn: () =>
159
+ owner
160
+ ? uiResult(async () => {
161
+ try {
162
+ return { report: await client.members.get(member) };
163
+ } catch (error) {
164
+ // No such member is an answer, not a failure.
165
+ if (statusOf(error) === 404) return { report: null };
166
+ throw error;
167
+ }
168
+ })
169
+ : Promise.resolve(null),
170
+ }),
171
+
172
+ /**
173
+ * A token's credentials; null where they cannot be listed. Only owners
174
+ * issue and see them, and only coffre's own sign-in issues any.
175
+ */
176
+ credentials: (client: CoffreClient, member: string, allowed: boolean) =>
177
+ queryOptions({
178
+ queryKey: [...keys.credentials(member), { allowed }],
179
+ queryFn: () => (allowed ? uiResult(() => client.tokens.list(member)) : Promise.resolve(null)),
180
+ }),
181
+
182
+ /** The accounts you sign in with, under coffre's own sign-in. */
183
+ identities: (client: CoffreClient) =>
184
+ queryOptions({ queryKey: keys.identities, queryFn: () => uiResult(() => client.identities.list()) }),
185
+
186
+ /** Where you are signed in, under coffre's own sign-in. */
187
+ sessions: (client: CoffreClient) =>
188
+ queryOptions({ queryKey: keys.sessions, queryFn: () => uiResult(() => client.sessions.list()) }),
189
+
190
+ /** A page of the log, as filtered: always read fresh. */
191
+ auditEntries: (client: CoffreClient, search: AuditSearch) =>
192
+ queryOptions({
193
+ queryKey: [...keys.audit, 'entries', search],
194
+ staleTime: 0,
195
+ // Detail is left out by the server unless asked for, and counted.
196
+ queryFn: () =>
197
+ uiResult(() =>
198
+ client.audit.list({
199
+ limit: AUDIT_PAGE_SIZE,
200
+ decision: search.decision,
201
+ actor: search.actorId,
202
+ detail: search.detail,
203
+ }),
204
+ ),
205
+ }),
206
+
207
+ /**
208
+ * Whether the log holds: verified on every visit, and never waited for.
209
+ * It re-reads the whole log, so it takes as long as the log is long; the
210
+ * page shows the entries first and the verdict when it comes.
211
+ */
212
+ auditChain: (client: CoffreClient) =>
213
+ queryOptions({ queryKey: [...keys.audit, 'chain'], staleTime: 0, queryFn: () => verifyChain(client) }),
214
+ };
215
+
216
+ /**
217
+ * Whether the log holds, or why that is not known. Verifying is for owners:
218
+ * anyone else reads their projects' part of the log, and a part cannot be
219
+ * checked as a chain, so for them it is a fact about the page, not a fault.
220
+ */
221
+ async function verifyChain(client: CoffreClient) {
222
+ try {
223
+ const result = await client.audit.verify();
224
+ return result.ok
225
+ ? {
226
+ integrity: 'intact' as const,
227
+ through: result.through,
228
+ entries: result.entries,
229
+ checkpoint: result.checkpoint,
230
+ pending: result.pending ?? 0,
231
+ }
232
+ : {
233
+ integrity: 'broken' as const,
234
+ through: result.through,
235
+ failedAtSeq: result.failedAtSeq,
236
+ author: result.author,
237
+ reason: result.reason,
238
+ };
239
+ } catch (error) {
240
+ const status = statusOf(error);
241
+ if (status === 403) return { integrity: 'owners-only' as const };
242
+ return {
243
+ integrity: 'unknown' as const,
244
+ problem: status === undefined ? 'the request never got an answer' : `the request failed with HTTP ${status}`,
245
+ };
246
+ }
247
+ }
248
+
249
+ export type ChainResult = Awaited<ReturnType<typeof verifyChain>>;
250
+
251
+ /**
252
+ * Who is looking, how this instance signs people in, and the projects they
253
+ * can see: what the shell needs on every screen. For someone signed out or
254
+ * not yet a member the project list is refused, and they get the sign-in or
255
+ * closed-door page.
256
+ */
257
+ export function shellOf(
258
+ auth: AuthInfo,
259
+ me: Me | null,
260
+ projects: ProjectsResult,
261
+ ) {
262
+ const listed = projects.ok ? projects.projects : [];
263
+ const member: Me | null = me?.registered === true ? me : null;
264
+ return {
265
+ auth,
266
+ principal: me === null ? null : me.principal,
267
+ instanceRole: member?.instanceRole ?? null,
268
+ projects: listed,
269
+ capabilities: deriveUiCapabilities(member, listed),
270
+ registrationRequired: me !== null && !me.registered,
271
+ /** A member the vault refuses: their record failed its integrity check. */
272
+ accessTampered: me?.tampered === true,
273
+ };
274
+ }
275
+
276
+ export type Shell = ReturnType<typeof shellOf>;
277
+
278
+ /**
279
+ * The shell, as every loader reads it: from the cache while fresh, so a
280
+ * child route never asks again for what the root has.
281
+ */
282
+ export async function loadShell(queryClient: QueryClient, client: CoffreClient): Promise<Shell> {
283
+ const [auth, me, projects] = await Promise.all([
284
+ queryClient.fetchQuery(queries.auth(client)),
285
+ queryClient.fetchQuery(queries.me(client)),
286
+ queryClient.fetchQuery(queries.projects(client)),
287
+ ]);
288
+ return shellOf(auth, me, projects);
289
+ }
290
+
291
+ /**
292
+ * One project and, when you manage its access, its grants. A project that is
293
+ * not there for you fails with no message: the page words that itself.
294
+ */
295
+ export function projectOf(projects: ProjectsResult, slug: string) {
296
+ if (!projects.ok) return projects;
297
+ const project = projects.projects.find((entry) => entry.slug === slug);
298
+ if (project === undefined) return { ok: false as const, error: null };
299
+ return { ok: true as const, project, managesAccess: project.permissions.includes('grant.manage') };
300
+ }
301
+
302
+ /** What a project page reads: the project list, and its grants when you manage them. */
303
+ export async function loadProject(queryClient: QueryClient, client: CoffreClient, slug: string) {
304
+ const found = projectOf(await queryClient.fetchQuery(queries.projects(client)), slug);
305
+ if (found.ok && found.managesAccess) await queryClient.fetchQuery(queries.grants(client, slug));
306
+ }
307
+
308
+ /** The directory pages' read: the directory, for owners. */
309
+ export async function loadDirectory(queryClient: QueryClient, client: CoffreClient) {
310
+ const shell = await loadShell(queryClient, client);
311
+ return queryClient.fetchQuery(queries.directory(client, shell.capabilities.canManageGrants));
312
+ }
313
+
314
+ /**
315
+ * Everything one user's or token's page reads: the report (owners only), the
316
+ * grants of every project where you manage access, and a token's
317
+ * credentials. There is no "grants of this member" call, so each project you
318
+ * manage is asked for its grants and the page keeps this member's. Projects
319
+ * where you do not hold grant.manage are skipped rather than asked: the
320
+ * refusal would land in the audit log as a denial in your name.
321
+ */
322
+ export async function loadPrincipal(
323
+ queryClient: QueryClient,
324
+ client: CoffreClient,
325
+ principalType: 'user' | 'service',
326
+ principalId: string,
327
+ ) {
328
+ const shell = await loadShell(queryClient, client);
329
+ const member = memberRef(principalType, principalId);
330
+ const owner = shell.capabilities.canManageGrants;
331
+ await Promise.all([
332
+ queryClient.fetchQuery(queries.report(client, member, owner)),
333
+ principalType === 'service'
334
+ ? queryClient.fetchQuery(queries.credentials(client, member, owner && shell.auth.signin !== null))
335
+ : null,
336
+ ...managedProjects(shell.projects).map((project) => queryClient.fetchQuery(queries.grants(client, project.slug))),
337
+ ]);
338
+ }
339
+
340
+ export function managedProjects(projects: ProjectSummary[]): ProjectSummary[] {
341
+ return projects.filter((project) => project.permissions.includes('grant.manage'));
342
+ }
343
+
344
+ /**
345
+ * What each change touches, which `useAction` refetches when it lands. Every
346
+ * change also lands in the audit log, which is always read fresh.
347
+ */
348
+ export const affects = {
349
+ /** A project or environment made, renamed or archived: the tree, and where you hold access. */
350
+ places: (): QueryKey[] => [keys.projects, keys.me],
351
+ /** Secrets written, renamed, restored or archived: the environment and the counts. */
352
+ secrets: (place: Place): QueryKey[] => [keys.secrets(place), keys.projects],
353
+ /**
354
+ * Someone's access in a project changed: its grants, their report, and, as
355
+ * it may be your own, what you can see.
356
+ */
357
+ access: (project: string, member: string): QueryKey[] => [
358
+ keys.grants(project),
359
+ keys.report(member),
360
+ keys.projects,
361
+ keys.me,
362
+ ],
363
+ /** Someone let in: the directory. */
364
+ admission: (): QueryKey[] => [keys.directory],
365
+ /**
366
+ * An instance role changed: the directory, their report, and, as it may be
367
+ * your own, what you can see and do.
368
+ */
369
+ role: (member: string): QueryKey[] => [keys.directory, keys.report(member), keys.me, keys.projects],
370
+ /** Someone removed: the directory, their report, and every project's grants, which removal ends. */
371
+ removal: (member: string): QueryKey[] => [keys.directory, keys.report(member), ['grants']],
372
+ credentials: (member: string): QueryKey[] => [keys.credentials(member)],
373
+ /** Unlinking an account also ends the sessions it signed in. */
374
+ identities: (): QueryKey[] => [keys.identities, keys.sessions],
375
+ sessions: (): QueryKey[] => [keys.sessions],
376
+ };
377
+
378
+ /**
379
+ * Refetch what a change touched: at once where it is on screen, on next use
380
+ * elsewhere. Every change lands in the audit log, so the log and its
381
+ * verification are always among them.
382
+ */
383
+ export async function refresh(queryClient: QueryClient, touched: QueryKey[]): Promise<void> {
384
+ await Promise.all([...touched, keys.audit].map((queryKey) => queryClient.invalidateQueries({ queryKey })));
385
+ }
@@ -1,30 +1,35 @@
1
+ import { useQueryClient, type QueryKey } from '@tanstack/react-query';
1
2
  import { useState } from 'react';
2
- import { useRouter } from '@tanstack/react-router';
3
3
 
4
4
  import { failureMessage } from './coffre';
5
+ import { refresh } from './queries';
5
6
 
6
7
  /**
7
- * Run a change against the API, then refresh what is on screen. A failed
8
- * call leaves the page as it was and says why, in `error`.
8
+ * Run a change against the API, then refetch what it touched. A failed call
9
+ * leaves the page as it was and says why, in `error`.
9
10
  *
10
- * `router.invalidate()` is this app's replacement for Next's
11
- * `revalidatePath`. The difference worth knowing: `revalidatePath` named the
12
- * routes to refresh and got it wrong quietly when a mutation touched more than
13
- * the page it was called from -- renaming a project had to remember to
14
- * revalidate both `/` and `/:project`. Invalidating refetches every mounted
15
- * loader instead, so the sidebar's project tree stays honest without anyone
16
- * having to remember it exists.
11
+ * Each change names what it touches (`affects` in `lib/queries.ts`), and
12
+ * those queries are refetched before the change counts as done: at once where
13
+ * they are on screen, such as the sidebar's project tree, and on next use
14
+ * where they are not. So your own change always shows, and nothing else is
15
+ * asked for again.
17
16
  */
18
17
  export function useAction() {
19
- const router = useRouter();
18
+ const queryClient = useQueryClient();
20
19
  const [pending, setPending] = useState(false);
21
20
  const [error, setError] = useState<string | null>(null);
22
21
 
23
22
  async function run<T>(
24
23
  fn: () => Promise<T>,
25
- // `unknown` rather than `void`, so a one-expression callback can end in
26
- // `toast.success(...)` -- which returns an id -- without a block body.
27
- onSuccess?: (result: T) => unknown,
24
+ {
25
+ affects,
26
+ onSuccess,
27
+ }: {
28
+ affects: QueryKey[] | ((result: T) => QueryKey[]);
29
+ // `unknown` rather than `void`, so a one-expression callback can end in
30
+ // `toast.success(...)` -- which returns an id -- without a block body.
31
+ onSuccess?: (result: T) => unknown;
32
+ },
28
33
  ): Promise<void> {
29
34
  setPending(true);
30
35
  let result: T;
@@ -38,7 +43,7 @@ export function useAction() {
38
43
 
39
44
  setError(null);
40
45
  try {
41
- await router.invalidate();
46
+ await refresh(queryClient, typeof affects === 'function' ? affects(result) : affects);
42
47
  await onSuccess?.(result);
43
48
  } catch {
44
49
  setError('The change was saved, but the page could not refresh. Reload before you retry.');