@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/Runtime.ts ADDED
@@ -0,0 +1,1442 @@
1
+ /**
2
+ * The client core (decision 14): one portable, framework-free runtime that owns the guarantees every client needs
3
+ * and none should implement twice. It holds the person's session (the shared `sessionController`), the selected
4
+ * organisation with a **generation**, the replica of `{ person, organisation, session }` (`connectSync`, its storage
5
+ * injected), live named queries (`materialize` and listeners, snapshots copied out and tagged with their
6
+ * generation), optimistic writes (the app's generated mutators through `write`: predicted, then confirmed, rejected
7
+ * after the rollback, or not confirmed), non-optimistic action calls (`makeClient`), and teardown: an organisation
8
+ * change, a sign-out or `needs-auth` destroys every view and closes the replica before anything of the next context
9
+ * is emitted, and late results of an older generation are dropped.
10
+ *
11
+ * Its events are the LocalClient contract's (`Event`, without the per-stream `seq`), so the daemon serves it as
12
+ * LocalClient v1 unchanged; an in-process client (a JavaScript host) can listen to it directly. Runs wherever the
13
+ * root SDK runs: no DOM, no Node built-ins (the portable rule pack covers it).
14
+ *
15
+ * const runtime = makeClientRuntime({ kernelUrl, zeroUrl, schema, queries, mutators, modules, sessionStore })
16
+ * runtime.onEvent((event) => ...)
17
+ * await runtime.start()
18
+ * const { id } = await runtime.subscribe({ query: "hello.greetings" }, "window-1")
19
+ * await runtime.write({ mutator: "hello.greet", input: { message: "Hi", visibility: "org" } }, "window-1")
20
+ */
21
+ import {
22
+ ActionFailed,
23
+ actionRegistry,
24
+ actionResult,
25
+ CLIENT_VERSION_HEADER,
26
+ Forbidden,
27
+ IDEMPOTENCY_HEADER,
28
+ InvalidInput,
29
+ InvocationError,
30
+ MAKE_ACTIONS_PATH,
31
+ MAKE_MODULE_PREFIX,
32
+ NotSignedIn,
33
+ SignInFailed,
34
+ StaleGeneration,
35
+ UnknownMutator,
36
+ UnknownQuery,
37
+ UnknownSubscription,
38
+ type AnyModuleContract,
39
+ type EngineReadiness,
40
+ type LocalClientEvent,
41
+ type LocalClientSessionState,
42
+ } from "@eloxiv/contracts"
43
+ import { Exit, Schema } from "effect"
44
+ import { changePassword as changeAccountPassword, type verifyTwoFactor } from "./Account.ts"
45
+ import { AuthError, listOrganizations, signOut as revokeSession, type OrganizationMembership } from "./Auth.ts"
46
+ import { makeClient } from "./Client.ts"
47
+ import { copyRows } from "./Rows.ts"
48
+ import { beginDesktopSignIn, completeDesktopSignIn, type DesktopSignIn } from "./Desktop.ts"
49
+ import { runErrorOf, runFollower } from "./RuntimeRuns.ts"
50
+ import { write as optimisticWrite, WriteNotConfirmed } from "./Optimistic.ts"
51
+ import {
52
+ sessionController,
53
+ type RememberedContext,
54
+ type RevocationStatus,
55
+ type RevocationStore,
56
+ type SessionState,
57
+ type SessionStore,
58
+ } from "./Session.ts"
59
+ import { connectSync, ORG_HEADER, type SyncClient, type SyncSchema, type SyncStorage } from "./Sync.ts"
60
+
61
+ /** A LocalClient event without its stream's `seq`, and the client it is for (`undefined`: every client). */
62
+ export type RuntimeEvent = (LocalClientEvent extends infer E ? (E extends unknown ? Omit<E, "seq"> : never) : never) & {
63
+ readonly owner?: string | undefined
64
+ }
65
+
66
+ export interface ClientRuntimeOptions<S extends SyncSchema = SyncSchema> {
67
+ /** The kernel's base URL (`http://localhost:4100`). */
68
+ readonly kernelUrl: string
69
+ /** zero-cache's URL (`http://localhost:4848`). */
70
+ readonly zeroUrl: string
71
+ /** The app's sync schema, named queries and mutators (`eloxiv.sync.ts`). */
72
+ readonly schema: S
73
+ readonly queries: object
74
+ readonly mutators?: object | undefined
75
+ /** The app's module contracts (`eloxiv.modules.ts`): its typed actions. */
76
+ readonly modules: ReadonlyArray<AnyModuleContract>
77
+ /** Where the person's session token is kept between launches (the daemon's secret store). */
78
+ readonly sessionStore: SessionStore
79
+ /** Replica storage (default memory): one store per person and organisation (`sqliteStorage` on desktop). */
80
+ readonly storage?: SyncStorage | undefined
81
+ /** The app build's version, sent with calls and writes. */
82
+ readonly clientVersion?: string | undefined
83
+ /** Retries of the session's checks and revocation (`sessionController`). */
84
+ readonly retry?: { readonly attempts?: number; readonly baseMs?: number } | undefined
85
+ /** How often to check a session the kernel could not be reached to check (ms, default 5 s). */
86
+ readonly recheckMs?: number | undefined
87
+ /**
88
+ * How long the launch's check of a stored session with a remembered context waits before the remembered replica is
89
+ * opened offline (ms, default 3 s; `sessionController`'s `offlineProbeMs`). The check goes on in the background.
90
+ * The same deadline bounds the listing of that session's organisations once the kernel accepted it: unanswered by
91
+ * then, the remembered organisation opens, and the listing reconciles it when it comes.
92
+ */
93
+ readonly offlineProbeMs?: number | undefined
94
+ readonly log?: ((line: string) => void) | undefined
95
+ /** How a followed run's event stream reconnects to the kernel (ms; the chat SDK's default 500, doubling to 10 000). */
96
+ readonly runReconnect?: { readonly base: number; readonly max: number } | undefined
97
+ /**
98
+ * A durable sign-out (a browser's storage, `sessionController`'s `revocations`): a sign-out keeps its revocation
99
+ * here before the person is signed out, and pending ones are retried at start, every `revocationRetryMs` (15 s)
100
+ * and on `retryRevocations`, each attempt waiting `revocationTimeoutMs` (10 s), until the kernel confirms them.
101
+ */
102
+ readonly revocations?: RevocationStore | undefined
103
+ readonly revocationTimeoutMs?: number | undefined
104
+ readonly revocationRetryMs?: number | undefined
105
+ /**
106
+ * Which organisation a newly adopted session starts in (default: `previous`, the organisation selected before when
107
+ * the same person's session is adopted again, while they still belong to it; else their first).
108
+ */
109
+ readonly initialOrg?: ((context: InitialOrgContext) => string | null) | undefined
110
+ }
111
+
112
+ /** What `initialOrg` chooses from: the person, their organisations, and the one selected before (same person). */
113
+ export interface InitialOrgContext {
114
+ readonly user: { readonly id: string; readonly email: string; readonly name: string }
115
+ readonly organizations: ReadonlyArray<OrganizationMembership>
116
+ readonly previous: string | null
117
+ }
118
+
119
+ type Listener = (rows: unknown, status: string, error?: unknown) => void
120
+ interface View {
121
+ addListener(listener: Listener): () => void
122
+ destroy(): void
123
+ }
124
+
125
+ interface Subscription {
126
+ readonly id: string
127
+ readonly owner: string
128
+ readonly generation: number
129
+ readonly view: View
130
+ }
131
+
132
+ interface OpenReplica {
133
+ readonly zero: SyncClient
134
+ readonly generation: number
135
+ readonly stop: () => void
136
+ }
137
+
138
+ /** Every callable leaf of a query or mutator registry, by its dotted name. */
139
+ const leaves = (registry: object, field: "queryName" | "mutatorName"): Map<string, (args?: unknown) => unknown> => {
140
+ const found = new Map<string, (args?: unknown) => unknown>()
141
+ const walk = (node: unknown, path: ReadonlyArray<string>) => {
142
+ if (node === null || (typeof node !== "object" && typeof node !== "function")) return
143
+ const named = (node as Record<string, unknown>)[field]
144
+ if (typeof node === "function" && typeof named === "string") {
145
+ found.set(named, node as (args?: unknown) => unknown)
146
+ return
147
+ }
148
+ for (const [key, child] of Object.entries(node)) {
149
+ if (key === "~") continue
150
+ walk(child, [...path, key])
151
+ }
152
+ }
153
+ walk(registry, [])
154
+ return found
155
+ }
156
+
157
+ const errorText = (error: unknown): string => {
158
+ if (error instanceof Error) return error.message
159
+ const message = (error as { readonly message?: unknown } | undefined)?.message
160
+ return typeof message === "string" ? message : JSON.stringify(error)
161
+ }
162
+
163
+ const encodeInvocationError = Schema.encodeUnknownSync(InvocationError)
164
+ const decodeInvocationError = Schema.decodeUnknownExit(InvocationError)
165
+
166
+ /** The kernel's typed error, as it travels (`{ _tag, message, ... }`), or `ActionFailed` for anything else. */
167
+ export const invocationErrorOf = (action: string, error: unknown): InvocationError => {
168
+ const decoded = decodeInvocationError(
169
+ typeof error === "object" && error !== null && "_tag" in error ? safeEncode(error) : error,
170
+ )
171
+ return Exit.isSuccess(decoded) ? decoded.value : new ActionFailed({ action, message: errorText(error) })
172
+ }
173
+ /** A failed query's cause: the kernel's typed error a sync server's refusal carries (`details`), else the error. */
174
+ const queryErrorOf = (error: unknown): unknown => {
175
+ const details = (error as { readonly details?: unknown } | undefined)?.details
176
+ return typeof details === "object" && details !== null && "_tag" in details ? details : error
177
+ }
178
+ const safeEncode = (error: object): unknown => {
179
+ try {
180
+ return encodeInvocationError(error)
181
+ } catch {
182
+ return { ...error }
183
+ }
184
+ }
185
+
186
+ /** Web Crypto, read from `globalThis` (the root SDK declares no DOM types). */
187
+ const webCrypto = (globalThis as { readonly crypto?: { randomUUID?: () => string } }).crypto
188
+ const randomId = () =>
189
+ typeof webCrypto?.randomUUID === "function"
190
+ ? webCrypto.randomUUID()
191
+ : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
192
+
193
+ const CONNECTION: Record<string, "connecting" | "connected" | "disconnected" | "needsAuth"> = {
194
+ initializing: "connecting",
195
+ connecting: "connecting",
196
+ connected: "connected",
197
+ disconnected: "disconnected",
198
+ error: "disconnected",
199
+ closed: "disconnected",
200
+ "needs-auth": "needsAuth",
201
+ }
202
+
203
+ export const makeClientRuntime = <const S extends SyncSchema>(options: ClientRuntimeOptions<S>) => {
204
+ const log = options.log ?? (() => undefined)
205
+ const controller = sessionController({
206
+ baseUrl: options.kernelUrl,
207
+ store: options.sessionStore,
208
+ retry: options.retry,
209
+ revocations: options.revocations,
210
+ revocationTimeoutMs: options.revocationTimeoutMs,
211
+ offlineProbeMs: options.offlineProbeMs,
212
+ })
213
+ const queries = leaves(options.queries, "queryName")
214
+ const mutators = leaves(options.mutators ?? {}, "mutatorName")
215
+ const registry = actionRegistry(options.modules)
216
+ const listeners = new Set<(event: RuntimeEvent) => void>()
217
+
218
+ let generation = 0
219
+ let orgId: string | null = null
220
+ let organizations: ReadonlyArray<OrganizationMembership> = []
221
+ let signingIn = false
222
+ /**
223
+ * The current sign-in attempt: advanced by a new sign-in, a cancellation, a sign-out and `close`, so an attempt
224
+ * whose redemption finishes afterwards adopts nothing (and its session is revoked).
225
+ */
226
+ let signInEpoch = 0
227
+ const attempts = new WeakMap<DesktopSignIn, number>()
228
+ /** A redeemed sign-in being adopted (its account checked): a sign-out waits until it is adopted or revoked. */
229
+ let adoptingSignIn: Promise<unknown> | undefined
230
+ let closed = false
231
+ let replica: OpenReplica | undefined
232
+ /**
233
+ * An offline start (`SessionStore.recall`): the stored session the kernel could not be reached to check, and the
234
+ * person and organisation its store remembered for it. While it holds (the check `unavailable`), the session is
235
+ * reported signed in as that person in that organisation and their replica is open from disk; the check's answer
236
+ * ends it (reconciled when the kernel accepts the token, torn down when it refuses it).
237
+ */
238
+ let offline: { readonly token: string; readonly context: RememberedContext } | undefined
239
+ /** The token the current context was made for (a new one is a new context). */
240
+ let contextToken: string | undefined
241
+ /** The person the current context was made for (a session of theirs adopted again keeps its organisation). */
242
+ let contextUser: string | undefined
243
+ /** A token the sync server refused (`needs-auth`): no replica is opened for it again. */
244
+ let refusedToken: string | undefined
245
+ let lastSession = ""
246
+ let lastConnection: string | undefined
247
+ let recheck: ReturnType<typeof setTimeout> | undefined
248
+ const subscriptions = new Map<string, Subscription>()
249
+ /** Writes in flight: their owner and generation. */
250
+ const writes = new Map<string, { readonly owner: string; readonly generation: number }>()
251
+ /** Context changes run one at a time, in order. */
252
+ let transition: Promise<unknown> = Promise.resolve()
253
+ /** The adoption of a new session in progress (its organisations listed, then its first context). */
254
+ let adopting: Promise<void> = Promise.resolve()
255
+
256
+ /** The token calls and the replica use: the checked session's, or an offline start's stored one. */
257
+ const currentToken = (): string | undefined => controller.token() ?? offline?.token
258
+ /** Whether a context can be open: a checked session, or an offline start. */
259
+ const contextOpen = () => controller.state().status === "authenticated" || offline !== undefined
260
+
261
+ const client = makeClient({
262
+ baseUrl: options.kernelUrl,
263
+ modules: options.modules,
264
+ token: currentToken,
265
+ orgId: () => orgId ?? undefined,
266
+ clientVersion: options.clientVersion,
267
+ })
268
+
269
+ /** Agent runs followed for their owners (LocalClient 1.1.0): every one stopped when the context resets. */
270
+ const runs = runFollower({
271
+ kernelUrl: options.kernelUrl,
272
+ clientVersion: options.clientVersion,
273
+ token: currentToken,
274
+ reconnect: options.runReconnect,
275
+ log,
276
+ })
277
+
278
+ const emit = (event: RuntimeEvent) => {
279
+ if (closed) return
280
+ for (const listener of listeners) {
281
+ try {
282
+ listener(event)
283
+ } catch (error) {
284
+ log(`a runtime listener failed: ${errorText(error)}`)
285
+ }
286
+ }
287
+ }
288
+
289
+ /** An event of `of` (a generation): sent only while that generation is current. */
290
+ const emitFor = (of: number, event: RuntimeEvent) => {
291
+ if (of === generation) emit(event)
292
+ }
293
+
294
+ const sessionState = (state: SessionState = controller.state()): LocalClientSessionState => {
295
+ switch (state.status) {
296
+ case "authenticated":
297
+ return {
298
+ state: "signedIn",
299
+ user: { id: state.account.id, email: state.account.email, name: state.account.name },
300
+ organizations: organizations.map((o) => ({ orgId: o.orgId, name: o.name, roles: [...o.roles] })),
301
+ orgId,
302
+ generation,
303
+ }
304
+ case "signing-out":
305
+ return { state: "signingOut" }
306
+ case "unavailable":
307
+ // An offline start: the remembered person, in the remembered organisation, until the check answers.
308
+ if (offline !== undefined) {
309
+ return {
310
+ state: "signedIn",
311
+ user: { ...offline.context.user },
312
+ organizations: organizations.map((o) => ({ orgId: o.orgId, name: o.name, roles: [...o.roles] })),
313
+ orgId,
314
+ generation,
315
+ offline: true,
316
+ }
317
+ }
318
+ return signingIn ? { state: "signingIn" } : { state: "signedOut" }
319
+ default:
320
+ return signingIn ? { state: "signingIn" } : { state: "signedOut" }
321
+ }
322
+ }
323
+
324
+ /** Context changes under way: their session is announced after their `context` event, never before it. */
325
+ let resetting = 0
326
+ /** The token whose context was last announced: a session adopted since is announced with its own context. */
327
+ let announcedToken: string | undefined
328
+ const emitSession = () => {
329
+ if (resetting > 0) return
330
+ const state = controller.state()
331
+ if (state.status === "authenticated" && state.token !== announcedToken) return
332
+ const session = sessionState()
333
+ // The listing's status is part of what was announced: its arrival (or a new reason) reaches listeners even when
334
+ // the session it lists is the one announced already (a one-organisation account's reconnect).
335
+ const text = JSON.stringify([session, organizationsProblem ?? null, lateListing ?? null])
336
+ if (text === lastSession) return
337
+ lastSession = text
338
+ emit({ type: "session", session })
339
+ }
340
+
341
+ const destroyViews = (which: (subscription: Subscription) => boolean) => {
342
+ for (const subscription of subscriptions.values()) {
343
+ if (!which(subscription)) continue
344
+ subscriptions.delete(subscription.id)
345
+ try {
346
+ subscription.view.destroy()
347
+ } catch {
348
+ // The replica closed first: its views went with it.
349
+ }
350
+ }
351
+ }
352
+
353
+ const closeReplica = async () => {
354
+ const open = replica
355
+ replica = undefined
356
+ lastConnection = undefined
357
+ if (open === undefined) return
358
+ open.stop()
359
+ await open.zero.close().catch((error: unknown) => log(`closing the replica failed: ${errorText(error)}`))
360
+ }
361
+
362
+ const openReplica = (): OpenReplica => {
363
+ if (closed) throw new NotSignedIn({ message: "The client has stopped" })
364
+ if (replica !== undefined) return replica
365
+ const token = currentToken()
366
+ const state = controller.state()
367
+ const userId = state.status === "authenticated" ? state.account.id : offline?.context.user.id
368
+ if (token === undefined || userId === undefined || orgId === null) {
369
+ throw new NotSignedIn({ message: "Sign in and select an organisation first" })
370
+ }
371
+ if (token === refusedToken) throw new NotSignedIn({ message: "The sync server refused this session" })
372
+ const zero = connectSync({
373
+ server: options.zeroUrl,
374
+ schema: options.schema,
375
+ userId,
376
+ token,
377
+ orgId,
378
+ storage: options.storage,
379
+ mutators: options.mutators as never,
380
+ clientVersion: options.clientVersion,
381
+ }) as unknown as SyncClient
382
+ const of = generation
383
+ const source = (
384
+ zero as unknown as {
385
+ readonly connection: {
386
+ readonly state: {
387
+ readonly current: { readonly name: string }
388
+ subscribe(listener: (state: { readonly name: string }) => void): () => void
389
+ }
390
+ }
391
+ }
392
+ ).connection.state
393
+ const onState = (current: { readonly name: string }) => {
394
+ if (of !== generation || replica?.zero !== zero) return
395
+ const mapped = CONNECTION[current.name] ?? "disconnected"
396
+ if (mapped !== lastConnection) {
397
+ lastConnection = mapped
398
+ emitFor(of, { type: "connection", state: mapped })
399
+ }
400
+ if (mapped === "needsAuth") void needsAuth(token)
401
+ }
402
+ const stop = source.subscribe(onState)
403
+ replica = { zero, generation: of, stop }
404
+ onState(source.current)
405
+ return replica
406
+ }
407
+
408
+ /**
409
+ * Reset the context: a new generation, every view destroyed and every write forgotten, the replica closed, and
410
+ * only then `context` and `session` sent; a replica for the new organisation is opened afterwards.
411
+ */
412
+ const reset = (
413
+ reason: "org" | "signOut" | "needsAuth",
414
+ next: string | null,
415
+ reopen = true,
416
+ /** Whether the request is still the current session's when its turn comes (refused `StaleGeneration` if not). */
417
+ still?: () => boolean,
418
+ ): Promise<number> => {
419
+ const run = async () => {
420
+ // Stopped: a reset queued (or an adoption finished) after `close` opens nothing.
421
+ if (closed) return generation
422
+ if (still !== undefined && !still()) throw overtaken()
423
+ // The session this context is for: storage and reopening after an await happen only while it still is.
424
+ const token = currentToken()
425
+ const same = () => !closed && currentToken() === token
426
+ resetting += 1
427
+ try {
428
+ generation += 1
429
+ orgId = next
430
+ destroyViews(() => true)
431
+ runs.stopAll()
432
+ writes.clear()
433
+ await closeReplica()
434
+ } finally {
435
+ resetting -= 1
436
+ }
437
+ announcedToken = controller.token()
438
+ // What an offline start would reopen follows the context, durably, before the change is announced: the new
439
+ // organisation, or none when the kernel's own listing left the person in none.
440
+ if (next !== null) await rememberContext(next, token)
441
+ else if (reason === "org" && organizationsProblem === undefined) await forgetRememberedContext(token)
442
+ emit({ type: "context", generation, reason })
443
+ emitSession()
444
+ if (reopen && same() && next !== null && contextOpen()) {
445
+ try {
446
+ openReplica()
447
+ } catch (error) {
448
+ log(`opening the replica failed: ${errorText(error)}`)
449
+ }
450
+ }
451
+ return generation
452
+ }
453
+ const done = transition.then(run, run)
454
+ transition = done.catch(() => undefined)
455
+ return done
456
+ }
457
+
458
+ /** A request of a session that no longer owns the runtime (signed out, another person's since): nothing changed. */
459
+ const overtaken = () =>
460
+ new StaleGeneration({ generation, message: "The session changed while the organisation was selected" })
461
+
462
+ /** Wait for the adoption and the context changes requested so far. */
463
+ const settled = async () => {
464
+ await adopting
465
+ await transition
466
+ }
467
+
468
+ const needsAuth = async (token: string) => {
469
+ if (refusedToken === token) return
470
+ refusedToken = token
471
+ log("the sync server refused the session (needs-auth)")
472
+ await reset("needsAuth", orgId, false)
473
+ const state = await controller.invalidate()
474
+ if (state.status === "authenticated" && state.token !== token) return
475
+ if (state.status === "authenticated") {
476
+ // The kernel still accepts it: one more replica, with the refusal remembered if it comes again.
477
+ refusedToken = undefined
478
+ try {
479
+ openReplica()
480
+ } catch (error) {
481
+ log(`reopening the replica failed: ${errorText(error)}`)
482
+ }
483
+ }
484
+ }
485
+
486
+ /**
487
+ * A new session (signed in, or found stored and checked): its organisations, and the one `initialOrg` chooses (by
488
+ * default the one selected before when it is the same person's session again, or the one its store remembers for
489
+ * this token, else the first) selected.
490
+ */
491
+ const adopted = async (token: string) => {
492
+ const state = controller.state()
493
+ const account = state.status === "authenticated" && state.token === token ? state.account : undefined
494
+ // Another person (an offline start's, or a session signed in over another's): the previous person's context closes
495
+ // now, in a new generation, before this person's organisations are awaited, so nothing of theirs stays live or
496
+ // reported meanwhile.
497
+ const handoff =
498
+ account !== undefined &&
499
+ contextUser !== undefined &&
500
+ account.id !== contextUser &&
501
+ (orgId !== null || replica !== undefined || subscriptions.size > 0)
502
+ contextToken = token
503
+ refusedToken = undefined
504
+ offline = undefined
505
+ /** This session still owns the runtime: what was awaited is applied only then. */
506
+ const owns = () => !closed && controller.token() === token && contextToken === token
507
+ if (handoff) {
508
+ forgetListing()
509
+ await reset("signOut", null, false, owns)
510
+ }
511
+ const person = adoptedPerson()
512
+ const listing = listFor(token)
513
+ const remembered = person.previous === null ? await recallFor(token) : undefined
514
+ if (!owns()) return
515
+ // A session its store remembers a context for (a launch's): a listing that does not come in time opens it.
516
+ const fallback = remembered !== undefined && remembered.user.id === person.user?.id ? remembered : undefined
517
+ const answer = fallback === undefined ? await listing : await withinProbe(listing)
518
+ if (!owns()) return
519
+ if (answer === undefined) {
520
+ organizations = [{ ...fallback!.organization, roles: [...fallback!.organization.roles] }]
521
+ lateListing = "The kernel has not listed your organisations yet"
522
+ await reset("org", fallback!.organization.orgId, true, owns)
523
+ void listing
524
+ .then((late) => settleLate(token, late, owns))
525
+ .catch((error: unknown) => log(`listing organisations failed: ${errorText(error)}`))
526
+ return
527
+ }
528
+ keepListing(answer)
529
+ const previous =
530
+ person.previous ??
531
+ (remembered !== undefined && remembered.user.id === person.user?.id ? remembered.organization.orgId : null)
532
+ await reset("org", chooseOrg({ user: person.user, previous }), true, owns)
533
+ }
534
+
535
+ /** `work`'s answer, or `undefined` when it has not come within `offlineProbeMs`. */
536
+ const withinProbe = async <A>(work: Promise<A>): Promise<A | undefined> => {
537
+ let timer: ReturnType<typeof setTimeout> | undefined
538
+ const deadline = new Promise<undefined>((resolve) => {
539
+ timer = setTimeout(() => resolve(undefined), options.offlineProbeMs ?? 3_000)
540
+ })
541
+ try {
542
+ return await Promise.race([work, deadline])
543
+ } finally {
544
+ clearTimeout(timer)
545
+ }
546
+ }
547
+ /** A listing that came after the deadline opened the remembered organisation, while its session owns the runtime. */
548
+ let lateListing: string | undefined
549
+ const settleLate = async (token: string, listing: Awaited<ReturnType<typeof listFor>>, owns: () => boolean) => {
550
+ if (!owns()) return
551
+ lateListing = undefined
552
+ const shown = organizations
553
+ keepListing(listing)
554
+ if (listing.problem !== undefined) {
555
+ // Still unknown: the remembered organisation stays, and the listing is retried.
556
+ organizations = shown
557
+ emitSession()
558
+ return
559
+ }
560
+ if (orgId !== null && organizations.some((o) => o.orgId === orgId)) {
561
+ await rememberContext(orgId, token)
562
+ emitSession()
563
+ return
564
+ }
565
+ const state = controller.state()
566
+ await reset(
567
+ "org",
568
+ chooseOrg({ user: state.status === "authenticated" ? state.account : undefined, previous: null }),
569
+ true,
570
+ owns,
571
+ )
572
+ }
573
+
574
+ /** The context the store remembers for `token` (`SessionStore.recall`), or none. */
575
+ const recallFor = async (token: string): Promise<RememberedContext | undefined> => {
576
+ if (options.sessionStore.recall === undefined) return undefined
577
+ try {
578
+ return await options.sessionStore.recall(token)
579
+ } catch (error) {
580
+ log(`recalling the session's context failed: ${errorText(error)}`)
581
+ return undefined
582
+ }
583
+ }
584
+
585
+ /**
586
+ * Keep the context now open (a checked session's person and organisation) for an offline start. When it cannot be
587
+ * kept, the one remembered before (perhaps an organisation the person has left) is forgotten instead.
588
+ */
589
+ const rememberContext = async (org: string, token: string | undefined = controller.token()) => {
590
+ const state = controller.state()
591
+ const organization = organizations.find((o) => o.orgId === org)
592
+ if (
593
+ options.sessionStore.remember === undefined ||
594
+ state.status !== "authenticated" ||
595
+ state.token !== token ||
596
+ organization === undefined
597
+ ) {
598
+ return
599
+ }
600
+ const context: RememberedContext = {
601
+ user: { id: state.account.id, email: state.account.email, name: state.account.name },
602
+ organization: { orgId: organization.orgId, name: organization.name, roles: [...organization.roles] },
603
+ }
604
+ try {
605
+ await options.sessionStore.remember(state.token, context)
606
+ } catch (error) {
607
+ log(`remembering the session's context failed: ${errorText(error)}`)
608
+ await forgetRememberedContext(token)
609
+ }
610
+ }
611
+
612
+ /**
613
+ * The kernel listed the person's organisations and none is selected (they belong to none now): an offline start
614
+ * must not reopen the one remembered for this session (`SessionStore.forgetContext`; the session itself is kept).
615
+ */
616
+ const forgetRememberedContext = async (token: string | undefined = controller.token()) => {
617
+ const state = controller.state()
618
+ if (options.sessionStore.forgetContext === undefined || state.status !== "authenticated" || state.token !== token) {
619
+ return
620
+ }
621
+ await options.sessionStore
622
+ .forgetContext(state.token)
623
+ .catch((error: unknown) => log(`forgetting the session's remembered context failed: ${errorText(error)}`))
624
+ }
625
+
626
+ /**
627
+ * An offline start: the kernel could not be reached to check the stored session, and its store remembers the
628
+ * context last open with that token. Only that person's replica of that organisation is opened (from disk), never
629
+ * for a token a sign-out left pending; the check goes on (`recheckMs`) and its answer ends it.
630
+ */
631
+ let openingOffline = false
632
+ const openOffline = async () => {
633
+ if (openingOffline) return
634
+ openingOffline = true
635
+ try {
636
+ const unchecked = () => !closed && controller.state().status === "unavailable" && contextToken === undefined
637
+ const token = await options.sessionStore.load().catch(() => undefined)
638
+ // A token the kernel refused in this process is never reopened, even while the store still holds it.
639
+ if (token === undefined || controller.isRefused(token) || !unchecked()) return
640
+ const context = await recallFor(token)
641
+ if (context === undefined || !unchecked()) return
642
+ // A revocation store that cannot be read counts as holding the token: nothing is reopened for it.
643
+ const pending = options.revocations === undefined ? [] : await options.revocations.load().catch(() => [token])
644
+ if (pending.includes(token) || !unchecked()) return
645
+ offline = { token, context }
646
+ contextToken = token
647
+ contextUser = context.user.id
648
+ organizations = [{ ...context.organization, roles: [...context.organization.roles] }]
649
+ log("the kernel cannot be reached: the remembered replica is opened offline")
650
+ await reset("org", context.organization.orgId, true, () => offline?.token === token)
651
+ } finally {
652
+ openingOffline = false
653
+ }
654
+ }
655
+
656
+ /**
657
+ * The kernel accepted an offline start's token: its organisations are listed, and the remembered organisation stays
658
+ * selected (same generation, same replica, which reconnects and reconciles by itself) while the person still belongs
659
+ * to it; otherwise one is chosen in a new context. While they cannot be listed, the remembered one stays.
660
+ *
661
+ * Nothing waits on the listing: calls (`subscribe`, `write`, `call`) go on in the open context meanwhile (reads from
662
+ * the replica, writes to it, pushed as its connection allows), `organizationsStatus()` is `unavailable` until it
663
+ * comes, and its answer is applied only while the same offline start's session still owns the runtime.
664
+ */
665
+ let reconciling: typeof offline
666
+ const reconcile = (token: string) => {
667
+ const was = offline
668
+ if (was === undefined || reconciling === was) return
669
+ reconciling = was
670
+ lateListing = "The kernel has not listed your organisations yet"
671
+ // The same context, now checked: announced at once (no longer `offline`), its organisations still to come.
672
+ if (orgId !== null) announcedToken = token
673
+ emitSession()
674
+ // A 401 is applied even if the check went `unavailable` again meanwhile, while this offline start still owns the
675
+ // runtime (its replica is still open); an answer listing organisations still needs the checked session (`reconciled`).
676
+ const stillOffline = () => !closed && offline === was && contextToken === token
677
+ void listFor(token, stillOffline)
678
+ .then((listing) => reconciled(token, was, listing))
679
+ .catch((error: unknown) => log(`reconciling the offline session failed: ${errorText(error)}`))
680
+ .finally(() => {
681
+ if (reconciling === was) reconciling = undefined
682
+ })
683
+ }
684
+ const reconciled = async (
685
+ token: string,
686
+ was: NonNullable<typeof offline>,
687
+ listing: Awaited<ReturnType<typeof listFor>>,
688
+ ) => {
689
+ const state = controller.state()
690
+ if (closed || offline !== was) return
691
+ if (state.status !== "authenticated" || state.token !== token || contextToken !== token) return
692
+ offline = undefined
693
+ lateListing = undefined
694
+ announcedToken = token
695
+ keepListing(listing)
696
+ if (listing.problem !== undefined) {
697
+ organizations = [was.context.organization]
698
+ emitSession()
699
+ return
700
+ }
701
+ const member = orgId !== null && organizations.some((o) => o.orgId === orgId)
702
+ if (member && state.account.id === was.context.user.id) {
703
+ await rememberContext(orgId!)
704
+ emitSession()
705
+ return
706
+ }
707
+ const owns = () => !closed && controller.token() === token && contextToken === token
708
+ await reset("org", chooseOrg({ user: state.account, previous: null }), true, owns)
709
+ }
710
+
711
+ /**
712
+ * Why the person's organisations could not be listed (a transient failure: their memberships are unknown, not
713
+ * none), until a listing succeeds; it is retried on a timer (`recheckMs`) and by `start`.
714
+ */
715
+ let organizationsProblem: string | undefined
716
+ let organizationsRetry: ReturnType<typeof setTimeout> | undefined
717
+ /** The listing a session's retries share (by its token: another session's retry never stands in for its own). */
718
+ let relisting: { readonly token: string | undefined; readonly promise: Promise<void> } | undefined
719
+ const listFor = async (
720
+ token: string,
721
+ /** The caller holds `token` unchecked (an offline start's reconcile): a 401 is applied while it still does. */
722
+ owns?: () => boolean,
723
+ ): Promise<{ readonly listed: ReadonlyArray<OrganizationMembership>; readonly problem: string | undefined }> => {
724
+ try {
725
+ return { listed: await listOrganizations(options.kernelUrl, token), problem: undefined }
726
+ } catch (error) {
727
+ log(`listing organisations failed: ${errorText(error)}`)
728
+ // The kernel refused the session itself: torn down like a refused check, never retried as a listing failure
729
+ // (the caller sees the session gone and applies nothing).
730
+ if (refusesSession(error)) await controller.refuse(token, owns)
731
+ return { listed: [], problem: errorText(error) }
732
+ }
733
+ }
734
+ /** A 401: the kernel no longer accepts the session (not a listing that failed). */
735
+ const refusesSession = (error: unknown) => error instanceof AuthError && error.status === 401
736
+ /** The current session's listing kept (inside the session's ownership): a failure is retried. */
737
+ const keepListing = (listing: Awaited<ReturnType<typeof listFor>>) => {
738
+ organizations = listing.listed
739
+ organizationsProblem = listing.problem
740
+ if (organizationsRetry !== undefined) clearTimeout(organizationsRetry)
741
+ organizationsRetry = undefined
742
+ if (listing.problem !== undefined && !closed) {
743
+ organizationsRetry = setTimeout(() => {
744
+ organizationsRetry = undefined
745
+ void relist()
746
+ }, options.recheckMs ?? 5_000)
747
+ }
748
+ }
749
+ const forgetListing = () => {
750
+ lateListing = undefined
751
+ keepListing({ listed: [], problem: undefined })
752
+ }
753
+ /**
754
+ * List the current session's organisations again after a failure: once they come, its organisation is chosen (as
755
+ * for a new session) in a new context; while they still fail, retried. Calls made together share one listing.
756
+ */
757
+ const relist = (): Promise<void> => {
758
+ const token = controller.token()
759
+ if (relisting !== undefined && relisting.token === token) return relisting.promise
760
+ const promise: Promise<void> = (async () => {
761
+ if (closed || organizationsProblem === undefined || token === undefined || token !== contextToken) return
762
+ const listing = await listFor(token)
763
+ const current = () => !closed && controller.token() === token && contextToken === token
764
+ if (!current()) return
765
+ keepListing(listing)
766
+ if (listing.problem !== undefined) return
767
+ const state = controller.state()
768
+ const user = state.status === "authenticated" ? state.account : undefined
769
+ await reset("org", chooseOrg({ user, previous: orgId }), true, current)
770
+ })()
771
+ .catch((error: unknown) => log(`listing organisations again failed: ${errorText(error)}`))
772
+ .finally(() => {
773
+ if (relisting?.promise === promise) relisting = undefined
774
+ })
775
+ relisting = { token, promise }
776
+ return promise
777
+ }
778
+ /** Who the adopted session is, and the organisation selected before when it is the same person's again. */
779
+ const adoptedPerson = () => {
780
+ const state = controller.state()
781
+ const user = state.status === "authenticated" ? state.account : undefined
782
+ const previous = user?.id === contextUser ? orgId : null
783
+ contextUser = user?.id
784
+ return { user, previous }
785
+ }
786
+ /** The organisation a session starts in: `initialOrg`'s choice when it is one of theirs, else the default's. */
787
+ const chooseOrg = (person: {
788
+ readonly user: InitialOrgContext["user"] | undefined
789
+ readonly previous: string | null
790
+ }) => {
791
+ const member = (id: string | null | undefined): id is string =>
792
+ typeof id === "string" && organizations.some((o) => o.orgId === id)
793
+ return [initialChoice(person), person.previous, organizations[0]?.orgId].find(member) ?? null
794
+ }
795
+ const initialChoice = (person: {
796
+ readonly user: InitialOrgContext["user"] | undefined
797
+ readonly previous: string | null
798
+ }) => {
799
+ if (person.user === undefined || options.initialOrg === undefined) return null
800
+ try {
801
+ return options.initialOrg({ user: person.user, organizations, previous: person.previous })
802
+ } catch (error) {
803
+ log(`choosing the organisation failed: ${errorText(error)}`)
804
+ return null
805
+ }
806
+ }
807
+
808
+ const onSession = (state: SessionState) => {
809
+ if (closed) return
810
+ if (recheck !== undefined) {
811
+ clearTimeout(recheck)
812
+ recheck = undefined
813
+ }
814
+ if (state.status === "authenticated" && state.token !== contextToken) {
815
+ signingIn = false
816
+ adopting = adopted(state.token).catch((error: unknown) => log(`adopting the session failed: ${errorText(error)}`))
817
+ return
818
+ }
819
+ if (state.status === "authenticated" && offline !== undefined && state.token === offline.token) {
820
+ // In the background: calls made meanwhile never wait on the listing (`reconcile`).
821
+ reconcile(state.token)
822
+ return
823
+ }
824
+ if (state.status !== "unavailable") offline = undefined
825
+ if (state.status === "unauthenticated" && contextToken !== undefined) {
826
+ // The kernel refused the session (or it was signed out): nothing of it may stay.
827
+ contextToken = undefined
828
+ forgetListing()
829
+ void reset("needsAuth", null, false)
830
+ return
831
+ }
832
+ if (state.status === "unavailable") {
833
+ recheck = setTimeout(() => void controller.refresh(), options.recheckMs ?? 5_000)
834
+ if (contextToken === undefined && options.sessionStore.recall !== undefined) {
835
+ adopting = openOffline().catch((error: unknown) =>
836
+ log(`opening the replica offline failed: ${errorText(error)}`),
837
+ )
838
+ }
839
+ }
840
+ emitSession()
841
+ }
842
+ const unsubscribeSession = controller.subscribe(onSession)
843
+
844
+ // A durable sign-out's pending revocations, retried on a timer while any is left (`revocations`).
845
+ let revocationTimer: ReturnType<typeof setTimeout> | undefined
846
+ const retryRevocations = async () => {
847
+ if (revocationTimer !== undefined) clearTimeout(revocationTimer)
848
+ revocationTimer = undefined
849
+ const outcome = await controller.retryRevocations()
850
+ if (outcome.stillPending) scheduleRevocations()
851
+ return outcome
852
+ }
853
+ const scheduleRevocations = () => {
854
+ if (closed || revocationTimer !== undefined || options.revocations === undefined) return
855
+ revocationTimer = setTimeout(() => {
856
+ revocationTimer = undefined
857
+ void retryRevocations().catch((error: unknown) => log(`retrying revocations failed: ${errorText(error)}`))
858
+ }, options.revocationRetryMs ?? 15_000)
859
+ }
860
+ const unsubscribeRevocation = controller.subscribeRevocation((status) => {
861
+ if (status === "pending") scheduleRevocations()
862
+ })
863
+
864
+ /**
865
+ * Adopt a session a password or two-factor sign-in obtains, as the current sign-in attempt: one abandoned while it
866
+ * completes (a sign-out, another sign-in, `close`) adopts nothing, and its session is revoked. The kernel's own
867
+ * errors (`AuthError`, `TwoFactorRequired`, `UnsavedSignOut`) are thrown as they are, for the caller to show.
868
+ */
869
+ const signInWith = async (obtain: (guard: { readonly current: () => boolean }) => Promise<boolean>) => {
870
+ if (closed) throw new SignInFailed({ message: "The client has stopped" })
871
+ if (controller.state().status === "authenticated") {
872
+ throw new SignInFailed({ message: "A person is already signed in: sign out first" })
873
+ }
874
+ const attempt = ++signInEpoch
875
+ const current = () => !closed && attempt === signInEpoch
876
+ const adoption = obtain({ current })
877
+ const waiting = adoption.catch(() => undefined)
878
+ adoptingSignIn = waiting
879
+ try {
880
+ if (!(await adoption)) {
881
+ throw new SignInFailed({ message: "The sign-in was cancelled while it completed; its session was revoked" })
882
+ }
883
+ } finally {
884
+ if (adoptingSignIn === waiting) adoptingSignIn = undefined
885
+ }
886
+ await settled()
887
+ }
888
+
889
+ const requireContext = () => {
890
+ if (!contextOpen() || orgId === null) {
891
+ throw new NotSignedIn({ message: "Sign in and select an organisation first" })
892
+ }
893
+ }
894
+ /** A request the client made in generation `expected` (its precondition): refused, with nothing run, in another. */
895
+ const requireGeneration = (expected: number | undefined) => {
896
+ if (expected !== undefined && expected !== generation) {
897
+ throw new StaleGeneration({ generation, message: `The context changed (made in ${expected}): nothing was run` })
898
+ }
899
+ }
900
+
901
+ /** The headers of a call as the person in the selected organisation. */
902
+ const callHeaders = (idempotencyKey: string | undefined): Record<string, string> => {
903
+ const token = currentToken()
904
+ return {
905
+ "content-type": "application/json",
906
+ ...(token === undefined ? {} : { authorization: `Bearer ${token}` }),
907
+ ...(orgId === null ? {} : { [ORG_HEADER]: orgId }),
908
+ ...(options.clientVersion === undefined ? {} : { [CLIENT_VERSION_HEADER]: options.clientVersion }),
909
+ ...(idempotencyKey === undefined ? {} : { [IDEMPOTENCY_HEADER]: idempotencyKey }),
910
+ }
911
+ }
912
+
913
+ /** A MAKE module's or kernel action over HTTP, as the person in the organisation: its envelope or typed error. */
914
+ const httpCall = async (action: string, input: unknown, idempotencyKey: string | undefined) => {
915
+ const path = action.startsWith(MAKE_MODULE_PREFIX) ? MAKE_ACTIONS_PATH : "/api/actions"
916
+ const response = await fetch(`${options.kernelUrl}${path}/${encodeURIComponent(action)}`, {
917
+ method: "POST",
918
+ headers: callHeaders(idempotencyKey),
919
+ body: JSON.stringify(input ?? {}),
920
+ })
921
+ const text = await response.text()
922
+ let body: unknown
923
+ try {
924
+ body = text.length === 0 ? {} : JSON.parse(text)
925
+ } catch {
926
+ throw new ActionFailed({ action, message: `The kernel answered ${response.status} with no JSON` })
927
+ }
928
+ if (!response.ok) throw invocationErrorOf(action, body)
929
+ return body
930
+ }
931
+
932
+ return {
933
+ /** The protocol-facing app description: its named queries, mutators and actions. */
934
+ app: {
935
+ queries: [...queries.keys()].sort(),
936
+ mutators: [...mutators.keys()].sort(),
937
+ actions: [...registry.keys(), "make.view", "make.renderView"].sort(),
938
+ },
939
+ /**
940
+ * Check a stored session (once at start): when it holds, the first organisation is selected. Called again, it
941
+ * also lists the person's organisations again when they could not be listed (`organizationsStatus`).
942
+ */
943
+ start: async (): Promise<LocalClientSessionState> => {
944
+ // Pending revocations of earlier sign-outs (a durable sign-out a reload interrupted) are retried meanwhile.
945
+ if (options.revocations !== undefined) {
946
+ void retryRevocations().catch((error: unknown) => log(`retrying revocations failed: ${errorText(error)}`))
947
+ }
948
+ await controller.start()
949
+ emitSession()
950
+ await settled()
951
+ await relist()
952
+ await settled()
953
+ return sessionState()
954
+ },
955
+ session: (): LocalClientSessionState => sessionState(),
956
+ /**
957
+ * Whether the signed-in person's organisations were listed (`listed`), or could not be (`unavailable`, and why):
958
+ * then the session's empty `organizations` are unknown, not none, and they are listed again on a timer
959
+ * (`recheckMs`) and by `start`; once they come, an organisation is selected in a new context.
960
+ */
961
+ organizationsStatus: ():
962
+ | { readonly status: "listed" }
963
+ | { readonly status: "unavailable"; readonly reason: string } =>
964
+ organizationsProblem === undefined && lateListing === undefined
965
+ ? { status: "listed" }
966
+ : { status: "unavailable", reason: organizationsProblem ?? lateListing! },
967
+ generation: (): number => generation,
968
+ onEvent: (listener: (event: RuntimeEvent) => void): (() => void) => {
969
+ listeners.add(listener)
970
+ return () => void listeners.delete(listener)
971
+ },
972
+
973
+ /** Start a desktop sign-in for `redirectUri`: the login to keep (its verifier never leaves the caller). */
974
+ beginSignIn: async (redirectUri: string): Promise<DesktopSignIn> => {
975
+ if (controller.state().status === "authenticated") {
976
+ throw new SignInFailed({ message: "A person is already signed in: sign out first" })
977
+ }
978
+ const login = await beginDesktopSignIn({ redirectUri })
979
+ if (closed) throw new SignInFailed({ message: "The client has stopped" })
980
+ attempts.set(login, ++signInEpoch)
981
+ signingIn = true
982
+ emitSession()
983
+ return login
984
+ },
985
+ /** The browser came back with a code for `login`: redeem it and adopt the session. */
986
+ completeSignIn: async (login: DesktopSignIn, received: { readonly code: string; readonly state: string }) => {
987
+ const attempt = attempts.get(login)
988
+ attempts.delete(login)
989
+ const current = () => !closed && attempt !== undefined && attempt === signInEpoch
990
+ if (!current()) throw new SignInFailed({ message: "This sign-in was cancelled or replaced" })
991
+ const abandoned = () =>
992
+ new SignInFailed({ message: "The sign-in was cancelled while it completed; its session was revoked" })
993
+ let adoption: Promise<boolean> | undefined
994
+ try {
995
+ const session = await completeDesktopSignIn(options.kernelUrl, login, received)
996
+ if (!current()) {
997
+ // Signed out, cancelled, replaced or stopped while the code was redeemed: the session must not stay live.
998
+ await revokeSession(options.kernelUrl, session.token).catch((error: unknown) =>
999
+ log(`revoking an abandoned sign-in's session failed: ${errorText(error)}`),
1000
+ )
1001
+ throw abandoned()
1002
+ }
1003
+ // Abandoned while its account is checked (or the check fails): the controller stores and reports nothing,
1004
+ // and revokes the session; the attempt is adopted only while it is still current.
1005
+ adoption = controller.adopt(session, { current })
1006
+ adoptingSignIn = adoption.catch(() => undefined)
1007
+ if (!(await adoption)) throw abandoned()
1008
+ } catch (error) {
1009
+ if (current()) {
1010
+ signingIn = false
1011
+ emitSession()
1012
+ }
1013
+ if (error instanceof SignInFailed) throw error
1014
+ throw new SignInFailed({ message: `The sign-in could not be completed: ${errorText(error)}` })
1015
+ } finally {
1016
+ if (adoption !== undefined) adoptingSignIn = undefined
1017
+ }
1018
+ await settled()
1019
+ },
1020
+ /** A started sign-in was abandoned (expired, refused). */
1021
+ cancelSignIn: () => {
1022
+ signInEpoch += 1
1023
+ if (!signingIn) return
1024
+ signingIn = false
1025
+ emitSession()
1026
+ },
1027
+
1028
+ /**
1029
+ * Select an organisation the person belongs to: a new generation (its `context` and `session` events sent). One
1030
+ * whose session ended while it ran (a sign-out, another person's sign-in, `close`) changes nothing and is refused
1031
+ * with `StaleGeneration`.
1032
+ */
1033
+ selectOrg: async (next: string): Promise<number> => {
1034
+ await settled()
1035
+ const token = controller.token()
1036
+ if (token === undefined && offline !== undefined) {
1037
+ // An offline start: the memberships cannot be checked, so the remembered organisation stays.
1038
+ throw new ActionFailed({
1039
+ action: "client.selectOrg",
1040
+ message: "Cannot reach the kernel; try again when online",
1041
+ })
1042
+ }
1043
+ if (token === undefined) throw new NotSignedIn({ message: "Sign in first" })
1044
+ let listed: ReadonlyArray<OrganizationMembership>
1045
+ try {
1046
+ listed = await listOrganizations(options.kernelUrl, token)
1047
+ } catch (error) {
1048
+ if (!refusesSession(error)) throw error
1049
+ // The kernel refused the session: torn down, as a refused check would.
1050
+ await controller.refuse(token)
1051
+ throw new NotSignedIn({ message: "Your session has ended: sign in again" })
1052
+ }
1053
+ const current = () => !closed && controller.token() === token && contextToken === token
1054
+ if (!current()) throw overtaken()
1055
+ // The listing is the kernel's answer: an offline start's reconcile still waiting on its own applies nothing.
1056
+ offline = undefined
1057
+ keepListing({ listed, problem: undefined })
1058
+ lateListing = undefined
1059
+ if (!organizations.some((o) => o.orgId === next)) {
1060
+ // The listing is authoritative: one that no longer has the open organisation resets it before refusing.
1061
+ if (orgId !== null && !organizations.some((o) => o.orgId === orgId)) {
1062
+ const state = controller.state()
1063
+ await reset(
1064
+ "org",
1065
+ chooseOrg({ user: state.status === "authenticated" ? state.account : undefined, previous: null }),
1066
+ true,
1067
+ current,
1068
+ )
1069
+ }
1070
+ throw new Forbidden({ action: "client.selectOrg", message: `You are not a member of ${next}` })
1071
+ }
1072
+ return reset("org", next, true, current)
1073
+ },
1074
+
1075
+ /**
1076
+ * Sign out: reads stop at once (`signingOut`), the context is reset (every view destroyed, the replica closed),
1077
+ * and the revocation is sent and retried; resolves once the kernel confirmed it.
1078
+ */
1079
+ signOut: async (): Promise<void> => {
1080
+ signInEpoch += 1
1081
+ // A redeemed session being adopted is abandoned (the epoch advanced): wait until the controller revoked it.
1082
+ if (adoptingSignIn !== undefined) await adoptingSignIn
1083
+ const state = controller.state()
1084
+ // Unauthenticated is not proof that nothing is stored: a stored session is revoked and forgotten below.
1085
+ if (
1086
+ (state.status === "unauthenticated" || state.status === "loading") &&
1087
+ (await options.sessionStore.load()) === undefined
1088
+ ) {
1089
+ signingIn = false
1090
+ emitSession()
1091
+ return
1092
+ }
1093
+ // An offline start's token is known here even when the store cannot be read now: it is the one revoked.
1094
+ const revoking = controller.signOut(offline?.token)
1095
+ revoking.catch(() => undefined)
1096
+ contextToken = undefined
1097
+ offline = undefined
1098
+ forgetListing()
1099
+ await reset("signOut", null, false)
1100
+ try {
1101
+ await revoking
1102
+ } catch (error) {
1103
+ throw new SignInFailed({ message: `The sign-out was not confirmed (try again): ${errorText(error)}` })
1104
+ }
1105
+ emitSession()
1106
+ },
1107
+
1108
+ /** Run a named query live for `owner`; its snapshots arrive as `rows` events of the current generation. */
1109
+ subscribe: async (
1110
+ request: {
1111
+ readonly query: string
1112
+ readonly args?: unknown
1113
+ readonly id?: string | undefined
1114
+ /** In process: refused (`StaleGeneration`) unless the context is still this generation. */
1115
+ readonly generation?: number | undefined
1116
+ },
1117
+ owner: string,
1118
+ ): Promise<{ readonly id: string; readonly generation: number }> => {
1119
+ await settled()
1120
+ requireContext()
1121
+ requireGeneration(request.generation)
1122
+ const query = queries.get(request.query)
1123
+ if (query === undefined) throw new UnknownQuery({ query: request.query, message: `No query ${request.query}` })
1124
+ const id = request.id ?? randomId()
1125
+ if (subscriptions.has(id)) throw new InvalidInput({ message: `A subscription ${id} already exists` })
1126
+ let named: unknown
1127
+ try {
1128
+ named = request.args === undefined ? query() : query(request.args)
1129
+ } catch (error) {
1130
+ throw new InvalidInput({ message: `Invalid arguments for ${request.query}: ${errorText(error)}` })
1131
+ }
1132
+ const open = openReplica()
1133
+ const of = generation
1134
+ const view = (open.zero as unknown as { materialize(query: unknown): View }).materialize(named)
1135
+ subscriptions.set(id, { id, owner, generation: of, view })
1136
+ // Snapshots are sent after the answer is made, so a client hears its id before its rows.
1137
+ setTimeout(() => {
1138
+ if (!subscriptions.has(id)) return
1139
+ view.addListener((data, status, error) => {
1140
+ if (!subscriptions.has(id)) return
1141
+ emitFor(of, {
1142
+ type: "rows",
1143
+ subscription: id,
1144
+ generation: of,
1145
+ status: (["unknown", "cached", "complete", "error"].includes(status) ? status : "unknown") as
1146
+ | "unknown"
1147
+ | "cached"
1148
+ | "complete"
1149
+ | "error",
1150
+ rows: copyRows(data) as never,
1151
+ ...(error === undefined
1152
+ ? {}
1153
+ : // The error as it travels (`{ _tag, message, ... }`), like a rejected write's.
1154
+ { error: encodeInvocationError(invocationErrorOf(request.query, queryErrorOf(error))) as never }),
1155
+ owner,
1156
+ })
1157
+ })
1158
+ }, 0)
1159
+ return { id, generation: of }
1160
+ },
1161
+ /** Stop one of `owner`'s subscriptions. */
1162
+ unsubscribe: (id: string, owner: string) => {
1163
+ const subscription = subscriptions.get(id)
1164
+ if (subscription === undefined || subscription.owner !== owner) {
1165
+ throw new UnknownSubscription({ id, message: `No subscription ${id}` })
1166
+ }
1167
+ destroyViews((s) => s.id === id)
1168
+ },
1169
+ /** Stop every subscription of `owner` (its stream closed). */
1170
+ unsubscribeAll: (owner: string) => destroyViews((s) => s.owner === owner),
1171
+ /** The subscriptions `owner` holds (diagnostics and tests). */
1172
+ subscriptionsOf: (owner: string): ReadonlyArray<string> =>
1173
+ [...subscriptions.values()].filter((s) => s.owner === owner).map((s) => s.id),
1174
+
1175
+ /**
1176
+ * An optimistic write through the app's mutator: resolves once the prediction is in the replica (`predicted`
1177
+ * sent); its outcome follows as a `write` event. An input the action refuses is refused here (`InvalidInput`),
1178
+ * with nothing predicted or sent.
1179
+ */
1180
+ write: async (
1181
+ request: {
1182
+ readonly mutator: string
1183
+ readonly input: unknown
1184
+ readonly id?: string | undefined
1185
+ /** Refused (`StaleGeneration`), nothing predicted or sent, unless the context is still this generation. */
1186
+ readonly generation?: number | undefined
1187
+ },
1188
+ owner: string,
1189
+ ): Promise<{ readonly id: string; readonly generation: number }> => {
1190
+ await settled()
1191
+ requireContext()
1192
+ requireGeneration(request.generation)
1193
+ const mutator = mutators.get(request.mutator)
1194
+ if (mutator === undefined) {
1195
+ throw new UnknownMutator({ mutator: request.mutator, message: `No optimistic mutator ${request.mutator}` })
1196
+ }
1197
+ const id = request.id ?? randomId()
1198
+ if (writes.has(id)) throw new InvalidInput({ message: `A write ${id} is already in flight` })
1199
+ const open = openReplica()
1200
+ const of = generation
1201
+ let pending: ReturnType<typeof optimisticWrite>
1202
+ try {
1203
+ pending = optimisticWrite(open.zero as never, mutator(request.input) as never)
1204
+ } catch (error) {
1205
+ throw new InvalidInput({ message: `Invalid input for ${request.mutator}: ${errorText(error)}` })
1206
+ }
1207
+ writes.set(id, { owner, generation: of })
1208
+ let predicted = true
1209
+ try {
1210
+ await pending.client
1211
+ } catch (error) {
1212
+ // Offline (or closed): nothing was predicted; the write is reported not confirmed, after this answer.
1213
+ if (!(error instanceof WriteNotConfirmed)) {
1214
+ writes.delete(id)
1215
+ throw invocationErrorOf(request.mutator, error)
1216
+ }
1217
+ predicted = false
1218
+ }
1219
+ const settle = (phase: "confirmed" | "rejected" | "notConfirmed", extra: Record<string, unknown> = {}) => {
1220
+ const known = writes.get(id)
1221
+ writes.delete(id)
1222
+ if (known === undefined || known.generation !== of) return
1223
+ emitFor(of, { type: "write", id, generation: of, phase, ...extra, owner })
1224
+ }
1225
+ if (!predicted) {
1226
+ setTimeout(
1227
+ () => settle("notConfirmed", { message: "The replica is offline: nothing was predicted or sent" }),
1228
+ 0,
1229
+ )
1230
+ return { id, generation: of }
1231
+ }
1232
+ emitFor(of, { type: "write", id, generation: of, phase: "predicted", owner })
1233
+ pending.server.then(
1234
+ () => settle("confirmed"),
1235
+ (error: unknown) =>
1236
+ error instanceof WriteNotConfirmed
1237
+ ? settle("notConfirmed", { message: error.message })
1238
+ : settle("rejected", { error: encodeInvocationError(invocationErrorOf(request.mutator, error)) }),
1239
+ )
1240
+ return { id, generation: of }
1241
+ },
1242
+
1243
+ /**
1244
+ * Call an action (not optimistically) as the person in the selected organisation: its result envelope as it
1245
+ * travels. An app action goes through the typed client; `make.*` and MAKE modules' actions over HTTP. A call
1246
+ * whose context changed while it ran is answered `StaleGeneration` naming its own generation (it may have run).
1247
+ * Made for generation `expected` while another is current, it is refused with `StaleGeneration` naming the current
1248
+ * one, and nothing is run.
1249
+ */
1250
+ call: async (action: string, input: unknown, idempotencyKey?: string, expected?: number): Promise<unknown> => {
1251
+ await settled()
1252
+ requireContext()
1253
+ requireGeneration(expected)
1254
+ const of = generation
1255
+ const contract = registry.get(action)
1256
+ let envelope: unknown
1257
+ try {
1258
+ if (contract === undefined) {
1259
+ envelope = await httpCall(action, input, idempotencyKey)
1260
+ } else {
1261
+ const decoded = Schema.decodeUnknownExit(contract.input as Schema.Codec<unknown, unknown>)(input ?? {})
1262
+ if (Exit.isFailure(decoded)) {
1263
+ throw new InvalidInput({ message: `Invalid input for ${action}: ${String(decoded.cause)}` })
1264
+ }
1265
+ const result = await client.call(action as never, decoded.value as never, { idempotencyKey })
1266
+ envelope = Schema.encodeUnknownSync(actionResult(contract) as unknown as Schema.Codec<unknown, unknown>)(
1267
+ result,
1268
+ )
1269
+ }
1270
+ } catch (error) {
1271
+ if (of !== generation) {
1272
+ throw new StaleGeneration({ generation: of, message: "The context changed while the call ran" })
1273
+ }
1274
+ throw invocationErrorOf(action, error)
1275
+ }
1276
+ if (of !== generation) {
1277
+ throw new StaleGeneration({ generation: of, message: "The context changed while the call ran" })
1278
+ }
1279
+ return envelope
1280
+ },
1281
+
1282
+ /**
1283
+ * Follow an agent run's events for `owner` (LocalClient 1.1.0), as the person in the selected organisation: they
1284
+ * arrive as `run` events of the current generation (each stored event once, streamed text as it comes), ending
1285
+ * after `run-finished`, or with the kernel's refusal (`error`). The stream reconnects to the kernel by itself; a
1286
+ * context reset ends it.
1287
+ */
1288
+ followRun: async (
1289
+ request: { readonly runId: string; readonly after?: number | undefined; readonly id?: string | undefined },
1290
+ owner: string,
1291
+ ): Promise<{ readonly id: string; readonly generation: number }> => {
1292
+ await settled()
1293
+ requireContext()
1294
+ const id = request.id ?? randomId()
1295
+ if (runs.has(id)) throw new InvalidInput({ message: `A run subscription ${id} already exists` })
1296
+ const of = generation
1297
+ runs.follow(
1298
+ { id, runId: request.runId, after: request.after ?? -1 },
1299
+ {
1300
+ owner,
1301
+ generation: of,
1302
+ orgId: orgId!,
1303
+ deliver: (delivery, alive) =>
1304
+ // After the answer is made (as a row subscription's snapshots), so a client hears its id first; nothing of
1305
+ // a subscription stopped meanwhile (unfollowed, its stream closed or replaced).
1306
+ setTimeout(() => {
1307
+ if (!alive()) return
1308
+ emitFor(
1309
+ of,
1310
+ delivery.kind === "event"
1311
+ ? { type: "run", subscription: id, generation: of, event: delivery.event, owner }
1312
+ : {
1313
+ type: "run",
1314
+ subscription: id,
1315
+ generation: of,
1316
+ // The error as it travels (`{ _tag, message, ... }`), like a rejected write's.
1317
+ error: encodeInvocationError(
1318
+ invocationErrorOf("agent.events", runErrorOf(delivery.error)),
1319
+ ) as never,
1320
+ owner,
1321
+ },
1322
+ )
1323
+ }, 0),
1324
+ },
1325
+ )
1326
+ return { id, generation: of }
1327
+ },
1328
+ /** Stop following one of `owner`'s runs. */
1329
+ unfollowRun: (id: string, owner: string) => {
1330
+ if (!runs.stop(id, owner)) throw new UnknownSubscription({ id, message: `No run subscription ${id}` })
1331
+ },
1332
+ /** Stop following every run of `owner` (its stream closed). */
1333
+ unfollowAll: (owner: string) => runs.stopOwner(owner),
1334
+ /** The runs `owner` follows (diagnostics and tests). */
1335
+ runsOf: (owner: string): ReadonlyArray<string> => runs.of(owner),
1336
+ /**
1337
+ * Whether the person's agent can answer in the selected organisation (the kernel's readiness, as the chat SDK
1338
+ * asks it): `unknown` when the kernel could not be asked; a refusal of the caller is its typed error.
1339
+ */
1340
+ agentReadiness: async (): Promise<EngineReadiness> => {
1341
+ await settled()
1342
+ requireContext()
1343
+ try {
1344
+ return await runs.readiness(orgId!)
1345
+ } catch (error) {
1346
+ throw invocationErrorOf("agent.readiness", error)
1347
+ }
1348
+ },
1349
+
1350
+ // -- In-process sign-in methods and session details (a JavaScript host: the web shell) ---------------------
1351
+
1352
+ /**
1353
+ * Sign in with email and password and adopt the session (its organisations listed and one selected before this
1354
+ * resolves). Rejects with the kernel's error as it is: `AuthError` (wrong credentials), `TwoFactorRequired` (finish
1355
+ * with `completeTwoFactor`), `UnsavedSignOut` (a durable sign-out's revocation only memory holds); `SignInFailed`
1356
+ * when a person is already signed in or the attempt was abandoned while it completed.
1357
+ */
1358
+ signInWithPassword: (credentials: { readonly email: string; readonly password: string }): Promise<void> =>
1359
+ signInWith((guard) => controller.signIn(credentials, guard)),
1360
+ /** Finish a password sign-in that `TwoFactorRequired` interrupted (its challenge and a code). */
1361
+ completeTwoFactor: (input: Parameters<typeof verifyTwoFactor>[1]): Promise<void> =>
1362
+ signInWith((guard) => controller.completeTwoFactor(input, guard)),
1363
+ /**
1364
+ * Change the signed-in person's password. When the kernel rotates the session, the new token is adopted (the
1365
+ * same person's, so their organisation stays selected, in a new generation); the old one is never reported again.
1366
+ * A rotation answered after the session it rotates ended (a sign-out, `close`) is not adopted: it rejects with
1367
+ * `SignInFailed`, and the rotated session is revoked.
1368
+ */
1369
+ changePassword: async (input: {
1370
+ readonly currentPassword: string
1371
+ readonly newPassword: string
1372
+ readonly revokeOtherSessions?: boolean
1373
+ }): Promise<void> => {
1374
+ await settled()
1375
+ const state = controller.state()
1376
+ if (state.status !== "authenticated") throw new NotSignedIn({ message: "Sign in first" })
1377
+ const { token } = await changeAccountPassword(options.kernelUrl, state.token, input)
1378
+ if (token === state.token) return
1379
+ const user = { id: state.account.id, email: state.account.email, name: state.account.name }
1380
+ // Adopted only while the session it rotates still owns the runtime: one answered after a sign-out, another
1381
+ // session or `close` adopts nothing, and the rotated session is discarded (revoked unless another holds it).
1382
+ const current = () => !closed && controller.token() === state.token
1383
+ if (!(await controller.adopt({ token, user }, { current }))) {
1384
+ throw new SignInFailed({ message: "The session changed while the password was changed" })
1385
+ }
1386
+ await settled()
1387
+ },
1388
+ /**
1389
+ * The session's bearer token, for an in-process host's own requests (a screen's HTTP calls): never sent in an
1390
+ * event, and `undefined` while nobody is signed in.
1391
+ */
1392
+ token: (): string | undefined => currentToken(),
1393
+ /**
1394
+ * The session check's own state: `loading` before the stored session is checked, `unavailable` (and why), and
1395
+ * `signing-out` with `error` while a sign-out that failed waits to be tried again (`signOut`).
1396
+ */
1397
+ sessionStatus: (): {
1398
+ readonly status: SessionState["status"]
1399
+ readonly reason?: string | undefined
1400
+ readonly error?: string | undefined
1401
+ } => {
1402
+ const state = controller.state()
1403
+ if (state.status === "unavailable") return { status: state.status, reason: state.reason }
1404
+ // A sign-out that failed (`SignOutNotSaved`, or a revocation not confirmed): the host offers to try again.
1405
+ if (state.status === "signing-out" && state.error !== undefined)
1406
+ return { status: state.status, error: state.error }
1407
+ return { status: state.status }
1408
+ },
1409
+ /** Where the last durable sign-out's revocation stands (`revocations`). */
1410
+ revocation: (): RevocationStatus => controller.revocationStatus(),
1411
+ onRevocation: (listener: (status: RevocationStatus) => void): (() => void) =>
1412
+ controller.subscribeRevocation((status) => {
1413
+ if (!closed) listener(status)
1414
+ }),
1415
+ /** Try every pending revocation once more now (the network came back). */
1416
+ retryRevocations: () => retryRevocations(),
1417
+
1418
+ /** Stop: every view destroyed, the replica closed, nothing more emitted. */
1419
+ close: async () => {
1420
+ if (closed) return
1421
+ closed = true
1422
+ signInEpoch += 1
1423
+ signingIn = false
1424
+ if (recheck !== undefined) clearTimeout(recheck)
1425
+ if (organizationsRetry !== undefined) clearTimeout(organizationsRetry)
1426
+ if (revocationTimer !== undefined) clearTimeout(revocationTimer)
1427
+ unsubscribeRevocation()
1428
+ unsubscribeSession()
1429
+ controller.dispose()
1430
+ // A context change already running finishes first (queued ones and late adoptions open nothing now).
1431
+ await transition
1432
+ destroyViews(() => true)
1433
+ runs.stopAll()
1434
+ writes.clear()
1435
+ await closeReplica()
1436
+ await client.dispose().catch(() => undefined)
1437
+ listeners.clear()
1438
+ },
1439
+ }
1440
+ }
1441
+
1442
+ export type ClientRuntime = ReturnType<typeof makeClientRuntime>