@eloxiv/client 0.0.0-stage → 0.1.1

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 (269) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -2
  3. package/dist/Account.d.ts +131 -0
  4. package/dist/Account.d.ts.map +1 -0
  5. package/dist/Account.js +169 -0
  6. package/dist/Account.js.map +1 -0
  7. package/dist/Agent.d.ts +496 -0
  8. package/dist/Agent.d.ts.map +1 -0
  9. package/dist/Agent.js +228 -0
  10. package/dist/Agent.js.map +1 -0
  11. package/dist/AgentSync.d.ts +990 -0
  12. package/dist/AgentSync.d.ts.map +1 -0
  13. package/dist/AgentSync.js +46 -0
  14. package/dist/AgentSync.js.map +1 -0
  15. package/dist/AppState.d.ts +127 -0
  16. package/dist/AppState.d.ts.map +1 -0
  17. package/dist/AppState.js +145 -0
  18. package/dist/AppState.js.map +1 -0
  19. package/dist/AppStateSync.d.ts +193 -0
  20. package/dist/AppStateSync.d.ts.map +1 -0
  21. package/dist/AppStateSync.js +23 -0
  22. package/dist/AppStateSync.js.map +1 -0
  23. package/dist/Auth.d.ts +95 -0
  24. package/dist/Auth.d.ts.map +1 -0
  25. package/dist/Auth.js +139 -0
  26. package/dist/Auth.js.map +1 -0
  27. package/dist/Avatars.d.ts +53 -0
  28. package/dist/Avatars.d.ts.map +1 -0
  29. package/dist/Avatars.js +121 -0
  30. package/dist/Avatars.js.map +1 -0
  31. package/dist/BrowserAnalytics.d.ts +56 -0
  32. package/dist/BrowserAnalytics.d.ts.map +1 -0
  33. package/dist/BrowserAnalytics.js +94 -0
  34. package/dist/BrowserAnalytics.js.map +1 -0
  35. package/dist/Chat.d.ts +712 -0
  36. package/dist/Chat.d.ts.map +1 -0
  37. package/dist/Chat.js +883 -0
  38. package/dist/Chat.js.map +1 -0
  39. package/dist/ChatIntegrity.d.ts +63 -0
  40. package/dist/ChatIntegrity.d.ts.map +1 -0
  41. package/dist/ChatIntegrity.js +89 -0
  42. package/dist/ChatIntegrity.js.map +1 -0
  43. package/dist/ChatSends.d.ts +103 -0
  44. package/dist/ChatSends.d.ts.map +1 -0
  45. package/dist/ChatSends.js +157 -0
  46. package/dist/ChatSends.js.map +1 -0
  47. package/dist/Client.d.ts +113 -0
  48. package/dist/Client.d.ts.map +1 -0
  49. package/dist/Client.js +189 -0
  50. package/dist/Client.js.map +1 -0
  51. package/dist/Collab.d.ts +138 -0
  52. package/dist/Collab.d.ts.map +1 -0
  53. package/dist/Collab.js +454 -0
  54. package/dist/Collab.js.map +1 -0
  55. package/dist/CollabTools.d.ts +129 -0
  56. package/dist/CollabTools.d.ts.map +1 -0
  57. package/dist/CollabTools.js +277 -0
  58. package/dist/CollabTools.js.map +1 -0
  59. package/dist/Connections.d.ts +288 -0
  60. package/dist/Connections.d.ts.map +1 -0
  61. package/dist/Connections.js +316 -0
  62. package/dist/Connections.js.map +1 -0
  63. package/dist/Consent.d.ts +338 -0
  64. package/dist/Consent.d.ts.map +1 -0
  65. package/dist/Consent.js +142 -0
  66. package/dist/Consent.js.map +1 -0
  67. package/dist/Desktop.d.ts +61 -0
  68. package/dist/Desktop.d.ts.map +1 -0
  69. package/dist/Desktop.js +101 -0
  70. package/dist/Desktop.js.map +1 -0
  71. package/dist/Directory.d.ts +36 -0
  72. package/dist/Directory.d.ts.map +1 -0
  73. package/dist/Directory.js +42 -0
  74. package/dist/Directory.js.map +1 -0
  75. package/dist/ErrorReporter.d.ts +48 -0
  76. package/dist/ErrorReporter.d.ts.map +1 -0
  77. package/dist/ErrorReporter.js +70 -0
  78. package/dist/ErrorReporter.js.map +1 -0
  79. package/dist/ExpoSqlite.d.ts +7 -0
  80. package/dist/ExpoSqlite.d.ts.map +1 -0
  81. package/dist/ExpoSqlite.js +7 -0
  82. package/dist/ExpoSqlite.js.map +1 -0
  83. package/dist/FileSync.d.ts +265 -0
  84. package/dist/FileSync.d.ts.map +1 -0
  85. package/dist/FileSync.js +29 -0
  86. package/dist/FileSync.js.map +1 -0
  87. package/dist/FileTables.gen.d.ts +109 -0
  88. package/dist/FileTables.gen.d.ts.map +1 -0
  89. package/dist/FileTables.gen.js +23 -0
  90. package/dist/FileTables.gen.js.map +1 -0
  91. package/dist/Foldkit.d.ts +487 -0
  92. package/dist/Foldkit.d.ts.map +1 -0
  93. package/dist/Foldkit.js +617 -0
  94. package/dist/Foldkit.js.map +1 -0
  95. package/dist/History.d.ts +133 -0
  96. package/dist/History.d.ts.map +1 -0
  97. package/dist/History.js +210 -0
  98. package/dist/History.js.map +1 -0
  99. package/dist/InboxSync.d.ts +428 -0
  100. package/dist/InboxSync.d.ts.map +1 -0
  101. package/dist/InboxSync.js +37 -0
  102. package/dist/InboxSync.js.map +1 -0
  103. package/dist/KernelTables.gen.d.ts +1522 -0
  104. package/dist/KernelTables.gen.d.ts.map +1 -0
  105. package/dist/KernelTables.gen.js +307 -0
  106. package/dist/KernelTables.gen.js.map +1 -0
  107. package/dist/Make.d.ts +75 -0
  108. package/dist/Make.d.ts.map +1 -0
  109. package/dist/Make.js +70 -0
  110. package/dist/Make.js.map +1 -0
  111. package/dist/Models.d.ts +88 -0
  112. package/dist/Models.d.ts.map +1 -0
  113. package/dist/Models.js +80 -0
  114. package/dist/Models.js.map +1 -0
  115. package/dist/Optimistic.d.ts +120 -0
  116. package/dist/Optimistic.d.ts.map +1 -0
  117. package/dist/Optimistic.js +231 -0
  118. package/dist/Optimistic.js.map +1 -0
  119. package/dist/PlatformSync.d.ts +273 -0
  120. package/dist/PlatformSync.d.ts.map +1 -0
  121. package/dist/PlatformSync.js +92 -0
  122. package/dist/PlatformSync.js.map +1 -0
  123. package/dist/Poll.d.ts +113 -0
  124. package/dist/Poll.d.ts.map +1 -0
  125. package/dist/Poll.js +179 -0
  126. package/dist/Poll.js.map +1 -0
  127. package/dist/Preferences.d.ts +18 -0
  128. package/dist/Preferences.d.ts.map +1 -0
  129. package/dist/Preferences.js +22 -0
  130. package/dist/Preferences.js.map +1 -0
  131. package/dist/Proposals.d.ts +29 -0
  132. package/dist/Proposals.d.ts.map +1 -0
  133. package/dist/Proposals.js +41 -0
  134. package/dist/Proposals.js.map +1 -0
  135. package/dist/React.d.ts +17 -0
  136. package/dist/React.d.ts.map +1 -0
  137. package/dist/React.js +17 -0
  138. package/dist/React.js.map +1 -0
  139. package/dist/Reader.d.ts +35 -0
  140. package/dist/Reader.d.ts.map +1 -0
  141. package/dist/Reader.js +136 -0
  142. package/dist/Reader.js.map +1 -0
  143. package/dist/Resources.d.ts +98 -0
  144. package/dist/Resources.d.ts.map +1 -0
  145. package/dist/Resources.js +161 -0
  146. package/dist/Resources.js.map +1 -0
  147. package/dist/Rows.d.ts +4 -0
  148. package/dist/Rows.d.ts.map +1 -0
  149. package/dist/Rows.js +16 -0
  150. package/dist/Rows.js.map +1 -0
  151. package/dist/Runtime.d.ts +254 -0
  152. package/dist/Runtime.d.ts.map +1 -0
  153. package/dist/Runtime.js +1283 -0
  154. package/dist/Runtime.js.map +1 -0
  155. package/dist/RuntimeRuns.d.ts +74 -0
  156. package/dist/RuntimeRuns.d.ts.map +1 -0
  157. package/dist/RuntimeRuns.js +118 -0
  158. package/dist/RuntimeRuns.js.map +1 -0
  159. package/dist/ServicesSync.d.ts +286 -0
  160. package/dist/ServicesSync.d.ts.map +1 -0
  161. package/dist/ServicesSync.js +40 -0
  162. package/dist/ServicesSync.js.map +1 -0
  163. package/dist/Session.d.ts +228 -0
  164. package/dist/Session.d.ts.map +1 -0
  165. package/dist/Session.js +792 -0
  166. package/dist/Session.js.map +1 -0
  167. package/dist/ShareGrant.d.ts +47 -0
  168. package/dist/ShareGrant.d.ts.map +1 -0
  169. package/dist/ShareGrant.js +20 -0
  170. package/dist/ShareGrant.js.map +1 -0
  171. package/dist/Sharing.d.ts +203 -0
  172. package/dist/Sharing.d.ts.map +1 -0
  173. package/dist/Sharing.js +520 -0
  174. package/dist/Sharing.js.map +1 -0
  175. package/dist/Skew.d.ts +52 -0
  176. package/dist/Skew.d.ts.map +1 -0
  177. package/dist/Skew.js +77 -0
  178. package/dist/Skew.js.map +1 -0
  179. package/dist/SpacesSync.d.ts +247 -0
  180. package/dist/SpacesSync.d.ts.map +1 -0
  181. package/dist/SpacesSync.js +30 -0
  182. package/dist/SpacesSync.js.map +1 -0
  183. package/dist/Storage.d.ts +51 -0
  184. package/dist/Storage.d.ts.map +1 -0
  185. package/dist/Storage.js +107 -0
  186. package/dist/Storage.js.map +1 -0
  187. package/dist/Sync.d.ts +48 -0
  188. package/dist/Sync.d.ts.map +1 -0
  189. package/dist/Sync.js +48 -0
  190. package/dist/Sync.js.map +1 -0
  191. package/dist/SyncTables.d.ts +13 -0
  192. package/dist/SyncTables.d.ts.map +1 -0
  193. package/dist/SyncTables.js +13 -0
  194. package/dist/SyncTables.js.map +1 -0
  195. package/dist/Tab.d.ts +36 -0
  196. package/dist/Tab.d.ts.map +1 -0
  197. package/dist/Tab.js +44 -0
  198. package/dist/Tab.js.map +1 -0
  199. package/dist/Transport.d.ts +139 -0
  200. package/dist/Transport.d.ts.map +1 -0
  201. package/dist/Transport.js +232 -0
  202. package/dist/Transport.js.map +1 -0
  203. package/dist/Upload.d.ts +41 -0
  204. package/dist/Upload.d.ts.map +1 -0
  205. package/dist/Upload.js +93 -0
  206. package/dist/Upload.js.map +1 -0
  207. package/dist/WebMcp.d.ts +78 -0
  208. package/dist/WebMcp.d.ts.map +1 -0
  209. package/dist/WebMcp.js +204 -0
  210. package/dist/WebMcp.js.map +1 -0
  211. package/dist/index.d.ts +27 -0
  212. package/dist/index.d.ts.map +1 -0
  213. package/dist/index.js +27 -0
  214. package/dist/index.js.map +1 -0
  215. package/package.json +97 -3
  216. package/src/Account.ts +249 -0
  217. package/src/Agent.ts +387 -0
  218. package/src/AgentSync.ts +59 -0
  219. package/src/AppState.ts +222 -0
  220. package/src/AppStateSync.ts +26 -0
  221. package/src/Auth.ts +225 -0
  222. package/src/Avatars.ts +144 -0
  223. package/src/BrowserAnalytics.ts +133 -0
  224. package/src/Chat.ts +1150 -0
  225. package/src/ChatIntegrity.ts +130 -0
  226. package/src/ChatSends.ts +209 -0
  227. package/src/Client.ts +319 -0
  228. package/src/Collab.ts +524 -0
  229. package/src/CollabTools.ts +381 -0
  230. package/src/Connections.ts +517 -0
  231. package/src/Consent.ts +176 -0
  232. package/src/Desktop.ts +139 -0
  233. package/src/Directory.ts +71 -0
  234. package/src/ErrorReporter.ts +112 -0
  235. package/src/ExpoSqlite.ts +6 -0
  236. package/src/FileSync.ts +34 -0
  237. package/src/FileTables.gen.ts +23 -0
  238. package/src/Foldkit.ts +960 -0
  239. package/src/History.ts +337 -0
  240. package/src/InboxSync.ts +47 -0
  241. package/src/KernelTables.gen.ts +329 -0
  242. package/src/Make.ts +120 -0
  243. package/src/Models.ts +134 -0
  244. package/src/Optimistic.ts +364 -0
  245. package/src/PlatformSync.ts +156 -0
  246. package/src/Poll.ts +227 -0
  247. package/src/Preferences.ts +42 -0
  248. package/src/Proposals.ts +57 -0
  249. package/src/React.ts +26 -0
  250. package/src/Reader.ts +180 -0
  251. package/src/Resources.ts +257 -0
  252. package/src/Rows.ts +16 -0
  253. package/src/Runtime.ts +1442 -0
  254. package/src/RuntimeRuns.ts +180 -0
  255. package/src/ServicesSync.ts +58 -0
  256. package/src/Session.ts +844 -0
  257. package/src/ShareGrant.ts +20 -0
  258. package/src/Sharing.ts +696 -0
  259. package/src/Skew.ts +97 -0
  260. package/src/SpacesSync.ts +61 -0
  261. package/src/Storage.ts +167 -0
  262. package/src/Sync.ts +125 -0
  263. package/src/SyncTables.ts +12 -0
  264. package/src/Tab.ts +59 -0
  265. package/src/Transport.ts +321 -0
  266. package/src/Upload.ts +125 -0
  267. package/src/WebMcp.ts +279 -0
  268. package/src/index.ts +26 -0
  269. package/src/web-globals.d.ts +103 -0
package/src/Sharing.ts ADDED
@@ -0,0 +1,696 @@
1
+ /**
2
+ * Headless sharing and access controllers (`@eloxiv/client/sharing`, the Sharing contract's clients): a record's
3
+ * grants managed optimistically, a change that widens who can read a record held until the person confirms it, an
4
+ * access gate for a record someone was sent to, and deciding access requests. They render nothing: an app's share
5
+ * dialog, its confirmation prompt and its "request access" screen draw their state and call their methods.
6
+ *
7
+ * They call the kernel's `sharing` actions through `call` (an `EloxivClient`'s `call`, or anything with its shape), so
8
+ * every change goes through the one invocation path: the record's own `share` policy decides, an agent's grant waits
9
+ * for its person's consent, and every call is audited. What these controllers add is client-side state, and it fails
10
+ * closed: a held change is never saved unless confirmed, a cancelled or invalidated one never is, an optimistic change
11
+ * the kernel refuses is rolled back, and the gate never says `allowed` unless the kernel just did.
12
+ */
13
+ import type { Grant, Grantee, ShareOutput } from "@eloxiv/contracts"
14
+
15
+ /**
16
+ * Calls a kernel action as an `EloxivClient`'s `call` does: resolves with the call's result envelope
17
+ * (`{ kind: "output", output }`, or `{ kind: "replay", receipt }` for an idempotent replay), or rejects with the
18
+ * action's typed error (`{ _tag, message }`). Pass `actionCall(client)`.
19
+ */
20
+ export type ActionCall = (action: string, input: unknown) => Promise<unknown>
21
+ export type SharingCall = ActionCall
22
+
23
+ /** An `EloxivClient`'s `call` as the controllers take it, for any action (theirs are kernel actions). */
24
+ export const actionCall =
25
+ (client: { readonly call: (...args: never[]) => Promise<unknown> }): ActionCall =>
26
+ (action, input) =>
27
+ (client.call as unknown as (action: string, input: unknown) => Promise<unknown>)(action, input)
28
+
29
+ /**
30
+ * A call answered with a replay receipt instead of an output. The controllers send no idempotency key, so the
31
+ * kernel never replays their calls; a `call` that adds one and gets a replay is refused here, since a receipt
32
+ * carries none of the output the controller would show.
33
+ */
34
+ export class ActionReplayed extends Error {
35
+ readonly _tag = "ActionReplayed"
36
+ readonly action: string
37
+ constructor(action: string) {
38
+ super(`${action} was answered with a replay receipt, not its output`)
39
+ this.action = action
40
+ this.name = "ActionReplayed"
41
+ }
42
+ }
43
+
44
+ /** The output in a call's result envelope; a replay, or anything that is not an envelope, is refused. */
45
+ export const outputOf = (envelope: unknown, action: string): unknown => {
46
+ if (typeof envelope === "object" && envelope !== null) {
47
+ const { kind } = envelope as { readonly kind?: unknown }
48
+ if (kind === "output") return (envelope as { readonly output: unknown }).output
49
+ if (kind === "replay") throw new ActionReplayed(action)
50
+ }
51
+ throw new Error(`${action} did not answer with a result envelope`)
52
+ }
53
+
54
+ /** `call`, resolving with the output alone (`outputOf`). */
55
+ export const outputs =
56
+ (call: ActionCall) =>
57
+ async (action: string, input: unknown): Promise<unknown> =>
58
+ outputOf(await call(action, input), action)
59
+
60
+ export interface RecordRef {
61
+ /** The entity's Cedar type (`Docs::Doc`). */
62
+ readonly entity: string
63
+ readonly id: string
64
+ }
65
+
66
+ /** The error tag a failed call rejected with (`Forbidden`, `ConsentRequired`, ...), if it has one. */
67
+ export const errorTag = (error: unknown): string | undefined =>
68
+ typeof error === "object" && error !== null && typeof (error as { _tag?: unknown })._tag === "string"
69
+ ? (error as { _tag: string })._tag
70
+ : undefined
71
+
72
+ /**
73
+ * Why a requested change was never saved: `dropped` when it was held for confirmation and then cancelled or
74
+ * invalidated (the record changed under it, the controller closed, its maker lost the right to share), `ignored` when
75
+ * it was refused up front (the controller is closed, or its maker may not share the record).
76
+ */
77
+ export class SharingNotSaved extends Error {
78
+ readonly reason: "dropped" | "ignored"
79
+ constructor(reason: "dropped" | "ignored") {
80
+ super(reason === "dropped" ? "The change was not confirmed" : "The change was not applied")
81
+ this.name = "SharingNotSaved"
82
+ this.reason = reason
83
+ }
84
+ }
85
+
86
+ const notSaved = <A>(reason: "dropped" | "ignored"): Promise<A> => {
87
+ const rejected = Promise.reject<A>(new SharingNotSaved(reason))
88
+ // A caller that fires and forgets raises no unhandled rejection; one that awaits still sees it.
89
+ rejected.catch(() => undefined)
90
+ return rejected
91
+ }
92
+
93
+ // ---- Confirming a widening -------------------------------------------------------------------------------------
94
+
95
+ export interface WideningState<V> {
96
+ /** The change waiting for confirmation, or null. Nothing is saved yet. */
97
+ readonly pending: { readonly from: V; readonly to: V } | null
98
+ readonly saving: boolean
99
+ /** Why the last confirmed save failed; the change stays pending, to retry. */
100
+ readonly error: unknown
101
+ }
102
+
103
+ export interface WideningTransition<V> {
104
+ readonly state: WideningState<V>
105
+ /**
106
+ * Change to `to`: at once when it needs no confirmation (the promise settles with the save), or held until
107
+ * `confirm`. A held change's promise resolves once a confirmed save succeeds (after retries) and rejects
108
+ * `SharingNotSaved("dropped")` once it is cancelled or invalidated. While a save runs, the same target joins it and
109
+ * any other is refused (`ignored`).
110
+ */
111
+ readonly request: (to: V) => Promise<void>
112
+ /** Save the held change, if it still describes the current value; a failure keeps it pending with its `error`. */
113
+ readonly confirm: () => Promise<void>
114
+ readonly cancel: () => void
115
+ /** Drop a held change if it no longer applies: the value moved under it, or changing is no longer allowed. */
116
+ readonly revalidate: () => void
117
+ readonly subscribe: (listener: () => void) => () => void
118
+ /** Drop a held change for good; later requests are refused. */
119
+ readonly dispose: () => void
120
+ }
121
+
122
+ /**
123
+ * A state machine for changes that widen access (the ledger's private-to-organisation confirmation): the change that
124
+ * `needsConfirmation(from, to)` says widens is held, nothing saved, until the person confirms; one that narrows, or
125
+ * stays, is saved at once. A held change is dropped (never saved) when cancelled, when the value it was made from
126
+ * moves under it (`current()` is no longer `from`), when `canChange()` turns false, and when disposed.
127
+ */
128
+ export const wideningTransition = <V>(options: {
129
+ readonly current: () => V
130
+ readonly needsConfirmation: (from: V, to: V) => boolean
131
+ readonly apply: (to: V) => Promise<void>
132
+ readonly canChange?: (() => boolean) | undefined
133
+ }): WideningTransition<V> => {
134
+ const listeners = new Set<() => void>()
135
+ const notify = () => {
136
+ for (const listener of listeners) listener()
137
+ }
138
+ interface Held {
139
+ readonly from: V
140
+ readonly to: V
141
+ readonly resolve: () => void
142
+ readonly reject: (error: unknown) => void
143
+ }
144
+ let held: Held | undefined
145
+ let saving: { readonly to: V; readonly promise: Promise<void> } | undefined
146
+ let error: unknown
147
+ let disposed = false
148
+ const canChange = () => !disposed && (options.canChange?.() ?? true)
149
+
150
+ const drop = () => {
151
+ const was = held
152
+ held = undefined
153
+ error = undefined
154
+ if (was !== undefined) was.reject(new SharingNotSaved("dropped"))
155
+ notify()
156
+ }
157
+ const save = (to: V) => {
158
+ const promise = options.apply(to)
159
+ saving = { to, promise }
160
+ notify()
161
+ const settle = () => {
162
+ if (saving?.promise === promise) saving = undefined
163
+ notify()
164
+ }
165
+ promise.then(settle, settle)
166
+ return promise
167
+ }
168
+
169
+ return {
170
+ get state() {
171
+ return {
172
+ pending: held === undefined ? null : { from: held.from, to: held.to },
173
+ saving: saving !== undefined,
174
+ error,
175
+ }
176
+ },
177
+ request: (to) => {
178
+ if (saving !== undefined) return saving.to === to ? saving.promise : notSaved("ignored")
179
+ if (!canChange()) return notSaved("ignored")
180
+ const from = options.current()
181
+ // Back to where it is: nothing to save, and a change held meanwhile no longer stands.
182
+ if (Object.is(from, to)) {
183
+ if (held !== undefined) drop()
184
+ return Promise.resolve()
185
+ }
186
+ if (!options.needsConfirmation(from, to)) {
187
+ if (held !== undefined) drop()
188
+ return save(to)
189
+ }
190
+ if (held !== undefined) drop()
191
+ return new Promise<void>((resolve, reject) => {
192
+ held = { from, to, resolve, reject }
193
+ error = undefined
194
+ notify()
195
+ })
196
+ },
197
+ confirm: () => {
198
+ const current = held
199
+ if (current === undefined) return Promise.resolve()
200
+ if (saving !== undefined) return saving.to === current.to ? saving.promise : notSaved("ignored")
201
+ // A confirmation of a change that no longer describes the record saves nothing.
202
+ if (!canChange() || !Object.is(options.current(), current.from)) {
203
+ drop()
204
+ return notSaved("dropped")
205
+ }
206
+ error = undefined
207
+ const attempt = save(current.to)
208
+ attempt.then(
209
+ () => {
210
+ if (held === current) {
211
+ held = undefined
212
+ notify()
213
+ }
214
+ current.resolve()
215
+ return undefined
216
+ },
217
+ (failure: unknown) => {
218
+ if (held === current) {
219
+ error = failure
220
+ notify()
221
+ }
222
+ },
223
+ )
224
+ return attempt
225
+ },
226
+ cancel: () => {
227
+ if (held !== undefined && saving === undefined) drop()
228
+ },
229
+ revalidate: () => {
230
+ if (held === undefined || saving !== undefined) return
231
+ if (!canChange() || !Object.is(options.current(), held.from)) drop()
232
+ },
233
+ subscribe: (listener) => {
234
+ listeners.add(listener)
235
+ return () => listeners.delete(listener)
236
+ },
237
+ dispose: () => {
238
+ disposed = true
239
+ if (held !== undefined) drop()
240
+ listeners.clear()
241
+ },
242
+ }
243
+ }
244
+
245
+ // ---- A record's grants -----------------------------------------------------------------------------------------
246
+
247
+ /** A grant as the share controller shows it: as the kernel listed it, or optimistic while a change is in flight. */
248
+ export interface ShareRow extends Grant {
249
+ /** `adding` until the kernel accepts a new grant, `removing` until it accepts a revocation. */
250
+ readonly pending: "adding" | "removing" | null
251
+ }
252
+
253
+ export interface ShareState {
254
+ readonly status: "loading" | "ready" | "failed"
255
+ /** Whether the caller may share the record (its `share` policy): false shows nothing of its grants. */
256
+ readonly canManage: boolean
257
+ readonly grants: ReadonlyArray<ShareRow>
258
+ /** A widening grant waiting for confirmation (default: sharing with the whole organisation). */
259
+ readonly held: { readonly grantee: Grantee; readonly permission: string; readonly error: unknown } | null
260
+ /** The last failure (of a load, a share or a revocation), until the next success. */
261
+ readonly error: unknown
262
+ }
263
+
264
+ export interface ShareController {
265
+ readonly state: ShareState
266
+ readonly refresh: () => Promise<void>
267
+ /**
268
+ * Grant a permission. Shown at once as an `adding` row; the kernel's answer replaces it, or a refusal removes it and
269
+ * rejects with the typed error. A widening grant is held (`state.held`) until `confirm`. A new link's token is in
270
+ * the result only, never in the state.
271
+ */
272
+ readonly share: (
273
+ grantee: Grantee,
274
+ permission: string,
275
+ options?: { readonly expiresAt?: string | null | undefined },
276
+ ) => Promise<ShareOutput>
277
+ /** Revoke a grant: shown as `removing` at once, restored with the typed error if the kernel refuses. */
278
+ readonly revoke: (grantId: string) => Promise<void>
279
+ readonly confirm: () => Promise<ShareOutput | undefined>
280
+ readonly cancel: () => void
281
+ readonly subscribe: (listener: () => void) => () => void
282
+ readonly dispose: () => void
283
+ }
284
+
285
+ const granteeOf = (grantee: Grantee): { readonly kind: Grant["kind"]; readonly id: string } =>
286
+ "user" in grantee
287
+ ? { kind: "user", id: grantee.user }
288
+ : "group" in grantee
289
+ ? { kind: "group", id: grantee.group }
290
+ : "org" in grantee
291
+ ? { kind: "org", id: grantee.org }
292
+ : { kind: "link", id: "" }
293
+
294
+ /**
295
+ * By default a grant to the whole organisation widens access and needs confirmation, unless an unexpired one is
296
+ * already there: an expired grant (still listed until the next load) gives no one access, so it never stands in for
297
+ * the confirmation.
298
+ */
299
+ export const widensToOrganisation = (
300
+ grantee: Grantee,
301
+ permission: string,
302
+ grants: ReadonlyArray<ShareRow>,
303
+ now: number = Date.now(),
304
+ ) =>
305
+ "org" in grantee &&
306
+ !grants.some(
307
+ (g) =>
308
+ g.kind === "org" &&
309
+ g.permission === permission &&
310
+ g.pending !== "removing" &&
311
+ (g.expiresAt === null || Date.parse(g.expiresAt) > now),
312
+ )
313
+
314
+ /**
315
+ * A record's grants for someone who may share it, kept in step with the kernel (`sharing.list`, `sharing.grant`,
316
+ * `sharing.revoke`), with optimistic rows reconciled by the kernel's answers. A load that started before a change
317
+ * settled never overwrites it (each load is numbered; only the latest counts, and in-flight rows stay on top).
318
+ */
319
+ export const shareController = (options: {
320
+ readonly call: SharingCall
321
+ readonly record: RecordRef
322
+ /** Whether a grant widens access enough to need confirmation (default: to the whole organisation). */
323
+ readonly needsConfirmation?:
324
+ | ((grantee: Grantee, permission: string, grants: ReadonlyArray<ShareRow>) => boolean)
325
+ | undefined
326
+ /** The clock grants' expiry is read against (default `Date.now`). */
327
+ readonly now?: (() => number) | undefined
328
+ }): ShareController => {
329
+ const { record } = options
330
+ const call = outputs(options.call)
331
+ const now = options.now ?? Date.now
332
+ const needsConfirmation =
333
+ options.needsConfirmation ??
334
+ ((grantee: Grantee, permission: string, grants: ReadonlyArray<ShareRow>) =>
335
+ widensToOrganisation(grantee, permission, grants, now()))
336
+ const listeners = new Set<() => void>()
337
+ const notify = () => {
338
+ for (const listener of listeners) listener()
339
+ }
340
+ let status: ShareState["status"] = "loading"
341
+ let canManage = false
342
+ let listed: ReadonlyArray<Grant> = []
343
+ const adding = new Map<string, ShareRow>()
344
+ const removing = new Set<string>()
345
+ let error: unknown
346
+ let disposed = false
347
+ let loads = 0
348
+ let nextPending = 0
349
+ interface Held {
350
+ readonly grantee: Grantee
351
+ readonly permission: string
352
+ readonly expiresAt: string | null | undefined
353
+ readonly resolve: (output: ShareOutput) => void
354
+ readonly reject: (error: unknown) => void
355
+ saving: boolean
356
+ error: unknown
357
+ }
358
+ let held: Held | undefined
359
+
360
+ const rows = (): ReadonlyArray<ShareRow> => [
361
+ ...listed.map((g): ShareRow => ({
362
+ id: g.id,
363
+ kind: g.kind,
364
+ grantee: g.grantee,
365
+ permission: g.permission,
366
+ grantedBy: g.grantedBy,
367
+ createdAt: g.createdAt,
368
+ expiresAt: g.expiresAt,
369
+ redemptions: g.redemptions,
370
+ pending: removing.has(g.id) ? "removing" : null,
371
+ })),
372
+ ...adding.values(),
373
+ ]
374
+ const dropHeld = () => {
375
+ const was = held
376
+ held = undefined
377
+ if (was !== undefined) was.reject(new SharingNotSaved("dropped"))
378
+ }
379
+
380
+ const refresh = async (): Promise<void> => {
381
+ if (disposed) return
382
+ const load = ++loads
383
+ try {
384
+ const output = (await call("sharing.list", record)) as { readonly grants: ReadonlyArray<Grant> }
385
+ if (load !== loads || disposed) return
386
+ listed = output.grants
387
+ canManage = true
388
+ status = "ready"
389
+ error = undefined
390
+ } catch (failure) {
391
+ if (load !== loads || disposed) return
392
+ // Not theirs to share (or no such record: the same answer): nothing of its grants is shown.
393
+ if (errorTag(failure) === "Forbidden") {
394
+ canManage = false
395
+ listed = []
396
+ status = "ready"
397
+ error = undefined
398
+ } else {
399
+ status = "failed"
400
+ error = failure
401
+ }
402
+ }
403
+ // A held widening no longer applies once they may not share, or the record is already shared that way.
404
+ if (held !== undefined && !held.saving) {
405
+ if (!canManage || !needsConfirmation(held.grantee, held.permission, rows())) dropHeld()
406
+ }
407
+ notify()
408
+ }
409
+
410
+ const save = async (
411
+ grantee: Grantee,
412
+ permission: string,
413
+ expiresAt: string | null | undefined,
414
+ ): Promise<ShareOutput> => {
415
+ const key = `pending:${++nextPending}`
416
+ const who = granteeOf(grantee)
417
+ adding.set(key, {
418
+ id: key,
419
+ kind: who.kind,
420
+ grantee: who.id || key,
421
+ permission,
422
+ grantedBy: "",
423
+ createdAt: new Date().toISOString(),
424
+ expiresAt: expiresAt ?? null,
425
+ redemptions: 0,
426
+ pending: "adding",
427
+ })
428
+ notify()
429
+ try {
430
+ const output = (await call("sharing.grant", {
431
+ ...record,
432
+ grantee,
433
+ permission,
434
+ ...(expiresAt === undefined ? {} : { expiresAt }),
435
+ })) as ShareOutput
436
+ error = undefined
437
+ // Accepted: the row is the kernel's grant now (sharing again returns the same grant), then listed as it is.
438
+ const accepted = adding.get(key)!
439
+ adding.delete(key)
440
+ if (!listed.some((g) => g.id === output.grantId)) {
441
+ listed = [...listed, { ...accepted, id: output.grantId, grantee: who.id || output.grantId }]
442
+ }
443
+ notify()
444
+ await refresh()
445
+ return output
446
+ } catch (failure) {
447
+ adding.delete(key)
448
+ error = failure
449
+ notify()
450
+ throw failure
451
+ }
452
+ }
453
+
454
+ return {
455
+ get state(): ShareState {
456
+ return {
457
+ status,
458
+ canManage,
459
+ grants: rows(),
460
+ held: held === undefined ? null : { grantee: held.grantee, permission: held.permission, error: held.error },
461
+ error,
462
+ }
463
+ },
464
+ refresh,
465
+ share: (grantee, permission, shareOptions) => {
466
+ if (disposed || (status === "ready" && !canManage)) return notSaved("ignored")
467
+ if (needsConfirmation(grantee, permission, rows())) {
468
+ dropHeld()
469
+ return new Promise<ShareOutput>((resolve, reject) => {
470
+ held = {
471
+ grantee,
472
+ permission,
473
+ expiresAt: shareOptions?.expiresAt,
474
+ resolve,
475
+ reject,
476
+ saving: false,
477
+ error: undefined,
478
+ }
479
+ notify()
480
+ })
481
+ }
482
+ return save(grantee, permission, shareOptions?.expiresAt)
483
+ },
484
+ revoke: async (grantId) => {
485
+ if (disposed) return notSaved("ignored")
486
+ removing.add(grantId)
487
+ notify()
488
+ try {
489
+ await call("sharing.revoke", { grantId })
490
+ error = undefined
491
+ await refresh()
492
+ } catch (failure) {
493
+ error = failure
494
+ throw failure
495
+ } finally {
496
+ removing.delete(grantId)
497
+ notify()
498
+ }
499
+ },
500
+ confirm: async () => {
501
+ const current = held
502
+ if (current === undefined || current.saving) return undefined
503
+ if (disposed || !canManage) {
504
+ dropHeld()
505
+ notify()
506
+ return notSaved("dropped")
507
+ }
508
+ current.saving = true
509
+ current.error = undefined
510
+ notify()
511
+ try {
512
+ const output = await save(current.grantee, current.permission, current.expiresAt)
513
+ if (held === current) held = undefined
514
+ current.resolve(output)
515
+ notify()
516
+ return output
517
+ } catch (failure) {
518
+ // Kept pending, with why, to retry or cancel.
519
+ current.saving = false
520
+ current.error = failure
521
+ notify()
522
+ throw failure
523
+ }
524
+ },
525
+ cancel: () => {
526
+ if (held === undefined || held.saving) return
527
+ dropHeld()
528
+ notify()
529
+ },
530
+ subscribe: (listener) => {
531
+ listeners.add(listener)
532
+ return () => listeners.delete(listener)
533
+ },
534
+ dispose: () => {
535
+ disposed = true
536
+ dropHeld()
537
+ listeners.clear()
538
+ },
539
+ }
540
+ }
541
+
542
+ // ---- The access gate -------------------------------------------------------------------------------------------
543
+
544
+ export interface AccessRequestSummary {
545
+ readonly id: string
546
+ readonly permission: string
547
+ readonly status: "pending" | "approved" | "denied"
548
+ readonly updatedAt: string
549
+ }
550
+
551
+ export interface AccessGateState {
552
+ /**
553
+ * `allowed`: the kernel says the caller may read the record now. `unavailable`: they may not, or it does not exist
554
+ * (the kernel never says which). `signed-out`: the call was unauthenticated. `failed`: the check itself failed.
555
+ */
556
+ readonly status: "checking" | "allowed" | "unavailable" | "signed-out" | "failed"
557
+ readonly canShare: boolean
558
+ /** Their latest request for the record, if any. */
559
+ readonly request: AccessRequestSummary | null
560
+ readonly requesting: boolean
561
+ readonly error: unknown
562
+ }
563
+
564
+ export interface AccessGate {
565
+ readonly state: AccessGateState
566
+ readonly check: () => Promise<void>
567
+ /** Ask for a permission (`sharing.requestAccess`), then check again. Rejects with the typed error. */
568
+ readonly requestAccess: (permission: string, message?: string) => Promise<void>
569
+ readonly subscribe: (listener: () => void) => () => void
570
+ readonly dispose: () => void
571
+ }
572
+
573
+ /**
574
+ * The gate in front of a record someone was sent to (`sharing.access`): whether to show it, ask them to sign in, or
575
+ * offer to request access, revealing nothing about a record they may not read. While their request is pending it
576
+ * checks again every `pollMs` (default 30 s); when the record becomes readable (approved, or shared meanwhile)
577
+ * `onAccessGranted` is called once. A check that started earlier never overrides a later one.
578
+ */
579
+ export const accessGate = (options: {
580
+ readonly call: SharingCall
581
+ readonly record: RecordRef
582
+ readonly onAccessGranted?: (() => void) | undefined
583
+ readonly pollMs?: number | undefined
584
+ }): AccessGate => {
585
+ const { record } = options
586
+ const call = outputs(options.call)
587
+ const listeners = new Set<() => void>()
588
+ const notify = () => {
589
+ for (const listener of listeners) listener()
590
+ }
591
+ let state: AccessGateState = {
592
+ status: "checking",
593
+ canShare: false,
594
+ request: null,
595
+ requesting: false,
596
+ error: undefined,
597
+ }
598
+ let checks = 0
599
+ let timer: ReturnType<typeof setTimeout> | undefined
600
+ let disposed = false
601
+ const set = (next: Partial<AccessGateState>) => {
602
+ state = { ...state, ...next }
603
+ notify()
604
+ }
605
+
606
+ const check = async (): Promise<void> => {
607
+ if (disposed) return
608
+ if (timer !== undefined) clearTimeout(timer)
609
+ timer = undefined
610
+ const mine = ++checks
611
+ const was = state.status
612
+ try {
613
+ const output = (await call("sharing.access", record)) as {
614
+ readonly access: "allowed" | "unavailable"
615
+ readonly canShare: boolean
616
+ readonly requests: ReadonlyArray<AccessRequestSummary>
617
+ }
618
+ if (mine !== checks || disposed) return
619
+ set({
620
+ status: output.access === "allowed" ? "allowed" : "unavailable",
621
+ canShare: output.access === "allowed" && output.canShare,
622
+ request: output.requests[0] ?? null,
623
+ error: undefined,
624
+ })
625
+ if (output.access === "allowed" && was !== "allowed") options.onAccessGranted?.()
626
+ if (output.access !== "allowed" && output.requests[0]?.status === "pending") {
627
+ timer = setTimeout(() => void check(), options.pollMs ?? 30_000)
628
+ }
629
+ } catch (failure) {
630
+ if (mine !== checks || disposed) return
631
+ set({
632
+ status: errorTag(failure) === "Unauthenticated" ? "signed-out" : "failed",
633
+ canShare: false,
634
+ error: failure,
635
+ })
636
+ }
637
+ }
638
+
639
+ return {
640
+ get state() {
641
+ return state
642
+ },
643
+ check,
644
+ requestAccess: async (permission, message) => {
645
+ if (disposed) return
646
+ set({ requesting: true, error: undefined })
647
+ try {
648
+ const trimmed = message?.trim()
649
+ await call("sharing.requestAccess", { ...record, permission, ...(trimmed ? { message: trimmed } : {}) })
650
+ set({ requesting: false })
651
+ } catch (failure) {
652
+ set({ requesting: false, error: failure })
653
+ throw failure
654
+ }
655
+ await check()
656
+ },
657
+ subscribe: (listener) => {
658
+ listeners.add(listener)
659
+ return () => listeners.delete(listener)
660
+ },
661
+ dispose: () => {
662
+ disposed = true
663
+ if (timer !== undefined) clearTimeout(timer)
664
+ timer = undefined
665
+ listeners.clear()
666
+ },
667
+ }
668
+ }
669
+
670
+ /**
671
+ * Decide an access request you were asked to decide (`sharing.approveRequest` or `sharing.denyRequest`). The kernel
672
+ * checks, at the moment of deciding, that the request is still pending and that you may still share the record; a
673
+ * decision that is no longer possible comes back as `stale` (decided already, or you lost the right), not as a
674
+ * failure, so a review screen can drop the request. Other failures reject.
675
+ */
676
+ export const decideAccessRequest = async (
677
+ call: SharingCall,
678
+ id: string,
679
+ verdict: "approve" | "deny",
680
+ ): Promise<
681
+ | { readonly outcome: "decided"; readonly status: "approved" | "denied"; readonly grantId: string | null }
682
+ | { readonly outcome: "stale"; readonly error: unknown }
683
+ > => {
684
+ try {
685
+ const action = verdict === "approve" ? "sharing.approveRequest" : "sharing.denyRequest"
686
+ const output = (await outputs(call)(action, { id })) as {
687
+ readonly status: "approved" | "denied"
688
+ readonly grantId: string | null
689
+ }
690
+ return { outcome: "decided", status: output.status, grantId: output.grantId }
691
+ } catch (failure) {
692
+ const tag = errorTag(failure)
693
+ if (tag === "InvalidInput" || tag === "Forbidden") return { outcome: "stale", error: failure }
694
+ throw failure
695
+ }
696
+ }