@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/Foldkit.ts ADDED
@@ -0,0 +1,960 @@
1
+ /**
2
+ * Foldkit bindings for the replica and the action client (`@eloxiv/client/foldkit`, decision 10), so a Foldkit
3
+ * shell reaches sync only through Eloxiv's client (decision 9). The headless SDK (`@eloxiv/client`) does not load
4
+ * Foldkit; this entry needs `foldkit` in the app.
5
+ *
6
+ * Zero keeps replication, local storage, queued optimistic writes and reconciliation. These bindings put its
7
+ * lifetimes and results into The Elm Architecture, with no second entity cache:
8
+ *
9
+ * - **Credentials stay out of the Elm state** (`Credentials`): the Model, Messages and Command arguments name a
10
+ * session by an opaque handle; the bearer token lives in a store outside the program, read by Commands and the
11
+ * replica's resource when they run, so DevTools, traces and diagnostics never see it.
12
+ * - **The replica is a ManagedResource** (`replicaResources`): the Model says whose replica should be open, in which
13
+ * organisation and under which session (`ReplicaRequirements`, the session's handle); the runtime opens it when that
14
+ * becomes known,
15
+ * closes it (its WebSocket included) when it changes or ends, and reports each transition as a Message
16
+ * (`onOpened` with the replica's `ReplicaKey`, `onClosed`, `onFailed`). A switch closes one replica before the
17
+ * next opens.
18
+ * - **Live queries are Subscriptions** (`liveQuery`): while the Model holds an open replica's key, a named query's
19
+ * results arrive as Messages carrying that key, copied out of Zero's view (rows typed by the entity's row
20
+ * schema, never a second declaration of its fields). Update keeps only snapshots of the replica the Model holds
21
+ * (`receive`), so a snapshot from a closed replica is dropped, never rendered.
22
+ * - **Connection state is a Subscription** (`connectionState`): `needs-auth`, `error` and the rest arrive as Messages.
23
+ * - **Writes are Effects for Commands.** `writeOptimistic` applies an action's prediction to the replica the Command
24
+ * names (refusing any other: `ReplicaUnavailable`) and waits for the server: it fails with the invocation's typed
25
+ * error (`Forbidden`, `InvalidInput`, ...) once the replica has dropped the prediction, or `WriteNotConfirmed`
26
+ * when the replica closes first. `callAction` calls an action through the typed client in the Command's own
27
+ * fiber. Cancellation is explicit: interrupting a Command abandons its wait and aborts an action call's request;
28
+ * it never takes back a write the replica has already queued, which the server still runs once (or refuses) and
29
+ * the replica still reconciles.
30
+ * - **Collaborative documents are Subscriptions** (`collabDocument`): while the Model names a record and a session,
31
+ * its document is open and every change arrives as a snapshot Message (text, status, presence); Commands edit it
32
+ * (`editCollabText`, `setCollabPresence`). The Y.Doc stays in the runtime, never in the Model.
33
+ */
34
+ import { InvocationError, type AnyModuleContract } from "@eloxiv/contracts"
35
+ import type { MutateRequest, QueryRequest } from "@rocicorp/zero"
36
+ import { Deferred, Effect, Option, Queue, Schema, type Scope, Stream } from "effect"
37
+ import { ManagedResource } from "foldkit"
38
+ import type { ActionInput, ActionName, ActionOutput, EloxivClient } from "./Client.ts"
39
+ import { applyTextEdits, connectCollab, type CollabConnection, type CollabTextEdit } from "./Collab.ts"
40
+ import { write, WriteNotConfirmed as WriteNotConfirmedError } from "./Optimistic.ts"
41
+ import { copyRows } from "./Rows.ts"
42
+ import type { ClientRuntime, RuntimeEvent } from "./Runtime.ts"
43
+ import type { RevocationStatus } from "./Session.ts"
44
+ import { connectSync, type SyncClient, type SyncSchema, type SyncStorage } from "./Sync.ts"
45
+
46
+ // ---------------------------------------------------------------------------------------------------------------
47
+ // Credentials
48
+
49
+ /**
50
+ * Bearer tokens held outside the Elm state, each named by an opaque handle that the Model, Messages and Command
51
+ * arguments carry instead. A handle reveals nothing about its token; `forget` drops a token for good.
52
+ */
53
+ export interface Credentials {
54
+ /** Holds a token and returns the handle that names it. */
55
+ readonly keep: (token: string) => string
56
+ /** The token a handle names, while it is held. */
57
+ readonly token: (handle: string) => string | undefined
58
+ readonly forget: (handle: string) => void
59
+ }
60
+
61
+ export const makeCredentials = (): Credentials => {
62
+ const tokens = new Map<string, string>()
63
+ let next = 0
64
+ return {
65
+ keep: (token) => {
66
+ next += 1
67
+ const handle = `session-${next}`
68
+ tokens.set(handle, token)
69
+ return handle
70
+ },
71
+ token: (handle) => tokens.get(handle),
72
+ forget: (handle) => void tokens.delete(handle),
73
+ }
74
+ }
75
+
76
+ // ---------------------------------------------------------------------------------------------------------------
77
+ // The replica
78
+
79
+ /** Whose replica should be open: one user, in one organisation, under one session (its handle, never its token). */
80
+ export const ReplicaRequirements = Schema.Struct({
81
+ userId: Schema.String,
82
+ orgId: Schema.String,
83
+ session: Schema.String,
84
+ })
85
+ export type ReplicaRequirements = typeof ReplicaRequirements.Type
86
+
87
+ /**
88
+ * An opened replica's identity: its user and organisation, and which opening it is (each opening gets a new
89
+ * number, so a replica reopened for the same user and organisation is a different one). It never holds the token.
90
+ */
91
+ export const ReplicaKey = Schema.Struct({
92
+ userId: Schema.String,
93
+ orgId: Schema.String,
94
+ opening: Schema.Number,
95
+ })
96
+ export type ReplicaKey = typeof ReplicaKey.Type
97
+
98
+ export const sameReplica = (a: ReplicaKey, b: ReplicaKey): boolean =>
99
+ a.userId === b.userId && a.orgId === b.orgId && a.opening === b.opening
100
+
101
+ /** The replica as the Model records it: none, being opened for an organisation, open, or failed to open. */
102
+ export const ReplicaState = Schema.Union([
103
+ Schema.TaggedStruct("Closed", {}),
104
+ Schema.TaggedStruct("Opening", { orgId: Schema.String }),
105
+ Schema.TaggedStruct("Open", { key: ReplicaKey }),
106
+ Schema.TaggedStruct("Failed", { orgId: Schema.String, message: Schema.String }),
107
+ ])
108
+ export type ReplicaState = typeof ReplicaState.Type
109
+ export const ReplicaClosed: ReplicaState = { _tag: "Closed" }
110
+ export const ReplicaOpening = (orgId: string): ReplicaState => ({ _tag: "Opening", orgId })
111
+
112
+ /** The key of the replica the Model holds open, if any. */
113
+ export const openReplica = (state: ReplicaState): Option.Option<ReplicaKey> =>
114
+ state._tag === "Open" ? Option.some(state.key) : Option.none()
115
+
116
+ /**
117
+ * A replica this adapter opened itself (`replicaResources`, deprecated): its key and the Zero client, typed by the
118
+ * app's schema.
119
+ */
120
+ export interface OpenReplica<S extends SyncSchema = SyncSchema> {
121
+ readonly key: ReplicaKey
122
+ readonly zero: SyncClient<S>
123
+ /** Completed when the replica is closed: waits on its writes stop waiting. */
124
+ readonly closed: Deferred.Deferred<void>
125
+ }
126
+
127
+ /**
128
+ * The ClientRuntime's replica of one generation (`runtimeReplica`): the runtime owns it (opening, closing, live
129
+ * queries, writes); this names which context a Command or Subscription acts in. `key.opening` is the generation.
130
+ */
131
+ export interface RuntimeReplica {
132
+ readonly key: ReplicaKey
133
+ readonly runtime: ClientRuntime
134
+ /** The runtime client its subscriptions and writes are made as. */
135
+ readonly owner: string
136
+ /** Completed when the Model let go of this generation: waits on its writes stop waiting. */
137
+ readonly closed: Deferred.Deferred<void>
138
+ }
139
+
140
+ /** The replica's ManagedResource identity: Commands and Subscriptions reach the open replica through it. */
141
+ export const Replica = ManagedResource.tag<OpenReplica<any>>()("@eloxiv/client/Replica")
142
+ export type ReplicaService = ManagedResource.ServiceOf<typeof Replica>
143
+ /** The same identity (one `ReplicaService`), holding the runtime's replica: what `runtimeReplica` provides. */
144
+ const RuntimeReplicaTag = ManagedResource.tag<RuntimeReplica>()("@eloxiv/client/Replica")
145
+
146
+ const isRuntimeReplica = (replica: OpenReplica<any> | RuntimeReplica): replica is RuntimeReplica => "runtime" in replica
147
+
148
+ /** Opening the replica failed (for the organisation it was opened for). */
149
+ export class ReplicaOpenFailed extends Schema.TaggedError<ReplicaOpenFailed>()("ReplicaOpenFailed", {
150
+ orgId: Schema.String,
151
+ message: Schema.String,
152
+ }) {}
153
+
154
+ let openings = 0
155
+
156
+ export interface ReplicaOptions<Model, Message, S extends SyncSchema> {
157
+ /** zero-cache's URL. */
158
+ readonly server: string
159
+ /** The app's generated sync schema (`schema` from `eloxiv.sync.ts`). */
160
+ readonly schema: S
161
+ /** The app's mutators (`mutators` from `eloxiv.sync.ts`), for `writeOptimistic`. */
162
+ readonly mutators?: unknown
163
+ /** Replica storage: `"idb"` in browsers and webviews (the default here), `"mem"`, or a store provider. */
164
+ readonly storage?: SyncStorage | undefined
165
+ /** This build's version, sent with each pushed write. */
166
+ readonly clientVersion?: string | undefined
167
+ /** Which replica the Model wants open: `Option.none()` while there is no session or no organisation yet. */
168
+ readonly requirements: (model: Model) => Option.Option<ReplicaRequirements>
169
+ /** Where the requirements' session handle is resolved to its token, when the replica opens. */
170
+ readonly credentials: Credentials
171
+ readonly onOpened: (key: ReplicaKey) => Message
172
+ readonly onClosed: () => Message
173
+ readonly onFailed: (failure: { readonly orgId: string; readonly message: string }) => Message
174
+ }
175
+
176
+ /**
177
+ * The replica as a Foldkit ManagedResource record, for `makeApplication({ managedResources })` (combine it with an
178
+ * app's own through `ManagedResource.aggregate`). Opening it connects to zero-cache; releasing it closes Zero,
179
+ * which closes its WebSocket, and ends every wait on its writes.
180
+ *
181
+ * @deprecated A second implementation of the replica's lifetime beside the client core's: use `runtimeReplica` over
182
+ * one `makeClientRuntime` (`@eloxiv/client/runtime`), which owns the session, the organisation's generation, the
183
+ * replica, live queries and writes for every client. `liveQuery`, `writeOptimistic` and `connectionState` work
184
+ * over either.
185
+ */
186
+ export const replicaResources = <Model, Message, const S extends SyncSchema>(
187
+ options: ReplicaOptions<Model, Message, S>,
188
+ ) =>
189
+ ManagedResource.make<Model, Message>()((entry) => ({
190
+ eloxivReplica: entry(Schema.Option(ReplicaRequirements), {
191
+ resource: Replica,
192
+ modelToMaybeRequirements: options.requirements,
193
+ acquire: (requirements: ReplicaRequirements) =>
194
+ Effect.gen(function* () {
195
+ const closed = yield* Deferred.make<void>()
196
+ const token = options.credentials.token(requirements.session)
197
+ if (token === undefined) {
198
+ return yield* new ReplicaOpenFailed({ orgId: requirements.orgId, message: "The session has ended" })
199
+ }
200
+ const zero = yield* Effect.try({
201
+ try: () =>
202
+ connectSync({
203
+ server: options.server,
204
+ schema: options.schema,
205
+ userId: requirements.userId,
206
+ token,
207
+ orgId: requirements.orgId,
208
+ storage: options.storage ?? "idb",
209
+ mutators: options.mutators as never,
210
+ clientVersion: options.clientVersion,
211
+ }),
212
+ catch: (error) => new ReplicaOpenFailed({ orgId: requirements.orgId, message: messageOf(error) }),
213
+ })
214
+ openings += 1
215
+ const replica: OpenReplica<S> = {
216
+ key: { userId: requirements.userId, orgId: requirements.orgId, opening: openings },
217
+ zero,
218
+ closed,
219
+ }
220
+ return replica
221
+ }),
222
+ release: (replica: OpenReplica<S>) =>
223
+ Deferred.succeed(replica.closed, undefined).pipe(
224
+ Effect.andThen(Effect.promise(() => replica.zero.close().catch(() => undefined))),
225
+ ),
226
+ onAcquired: (replica: OpenReplica<S>) => options.onOpened(replica.key),
227
+ onReleased: () => options.onClosed(),
228
+ onAcquireError: (error: unknown) =>
229
+ options.onFailed(
230
+ error instanceof ReplicaOpenFailed
231
+ ? { orgId: error.orgId, message: error.message }
232
+ : { orgId: "", message: messageOf(error) },
233
+ ),
234
+ }),
235
+ }))
236
+
237
+ const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error))
238
+
239
+ /** Which generation of the runtime's context the Model wants to act in: one person, one organisation. */
240
+ export const RuntimeReplicaRequirements = Schema.Struct({
241
+ userId: Schema.String,
242
+ orgId: Schema.String,
243
+ generation: Schema.Number,
244
+ })
245
+ export type RuntimeReplicaRequirements = typeof RuntimeReplicaRequirements.Type
246
+
247
+ export interface RuntimeReplicaOptions<Model, Message> {
248
+ /** The program's one client core: it opens and closes the replica itself, on its context changes. */
249
+ readonly runtime: ClientRuntime
250
+ /** The runtime client this program's subscriptions and writes are made as (default `foldkit`). */
251
+ readonly owner?: string | undefined
252
+ /** The generation the Model acts in, once the runtime has announced it (`Option.none()` before, and between). */
253
+ readonly requirements: (model: Model) => Option.Option<RuntimeReplicaRequirements>
254
+ readonly onOpened: (key: ReplicaKey) => Message
255
+ readonly onClosed: () => Message
256
+ readonly onFailed: (failure: { readonly orgId: string; readonly message: string }) => Message
257
+ }
258
+
259
+ /**
260
+ * The ClientRuntime's replica as a Foldkit ManagedResource record (`makeApplication({ managedResources })`): the
261
+ * runtime owns the replica's lifetime (an organisation change, a sign-out or `needs-auth` destroys its views and closes
262
+ * it before anything of the next context is emitted), and this resource names the generation the Model acts in, so
263
+ * Commands and Subscriptions reach it through `ReplicaService` as before: `liveQuery` runs a named query through
264
+ * `runtime.subscribe`, `writeOptimistic` writes through `runtime.write`, both refused for another generation. The key's
265
+ * `opening` is the generation; `onOpened` reports it once the Model's requirements are taken, `onClosed` when they go.
266
+ */
267
+ export const runtimeReplica = <Model, Message>(options: RuntimeReplicaOptions<Model, Message>) =>
268
+ ManagedResource.make<Model, Message>()((entry) => ({
269
+ eloxivReplica: entry(Schema.Option(RuntimeReplicaRequirements), {
270
+ resource: RuntimeReplicaTag,
271
+ modelToMaybeRequirements: options.requirements,
272
+ acquire: (requirements: RuntimeReplicaRequirements) =>
273
+ Effect.map(Deferred.make<void>(), (closed): RuntimeReplica => ({
274
+ key: { userId: requirements.userId, orgId: requirements.orgId, opening: requirements.generation },
275
+ runtime: options.runtime,
276
+ owner: options.owner ?? "foldkit",
277
+ closed,
278
+ })),
279
+ release: (replica: RuntimeReplica) => Deferred.succeed(replica.closed, undefined).pipe(Effect.asVoid),
280
+ onAcquired: (replica: RuntimeReplica) => options.onOpened(replica.key),
281
+ onReleased: () => options.onClosed(),
282
+ onAcquireError: (error: unknown) => options.onFailed({ orgId: "", message: messageOf(error) }),
283
+ }),
284
+ }))
285
+
286
+ /**
287
+ * The runtime's events as a Foldkit Subscription entry, for a `Subscription.make` record: while it runs, `toMessage`
288
+ * turns each event (and, first, the runtime's current state, `initial`) into Messages; `rows` and `write` events are
289
+ * left to `liveQuery` and `writeOptimistic`. The adapter's one way the runtime's session, context and connection reach
290
+ * a Model.
291
+ */
292
+ export const runtimeEvents = <Message>(options: {
293
+ readonly runtime: ClientRuntime
294
+ /** What the Model should hear when the Subscription starts (the session as it stands, say). */
295
+ readonly initial: () => ReadonlyArray<Message>
296
+ readonly toMessage: (event: RuntimeEvent) => Message | undefined
297
+ /** Revocation changes of a durable sign-out, when the Model shows them. */
298
+ readonly onRevocation?: ((status: RevocationStatus) => Message) | undefined
299
+ }) => ({
300
+ dependenciesSchema: Schema.Struct({}),
301
+ modelToDependencies: (_model: unknown) => ({}),
302
+ dependenciesToStream: (): Stream.Stream<Message> =>
303
+ Stream.callback<Message>((queue) =>
304
+ Effect.acquireRelease(
305
+ Effect.sync(() => {
306
+ const offer = (message: Message | undefined) => {
307
+ if (message !== undefined) Queue.offerUnsafe(queue, message)
308
+ }
309
+ const stopEvents = options.runtime.onEvent((event) => {
310
+ if (event.type !== "rows" && event.type !== "write") offer(options.toMessage(event))
311
+ })
312
+ const stopRevocation =
313
+ options.onRevocation === undefined
314
+ ? () => undefined
315
+ : options.runtime.onRevocation((status) => offer(options.onRevocation!(status)))
316
+ for (const message of options.initial()) offer(message)
317
+ return () => {
318
+ stopEvents()
319
+ stopRevocation()
320
+ }
321
+ }),
322
+ (stop) => Effect.sync(stop),
323
+ ).pipe(Effect.andThen(Effect.never)),
324
+ ),
325
+ })
326
+
327
+ /**
328
+ * The runtime's session behind an opaque handle in `credentials`, for Models, Messages and Command arguments: the
329
+ * same handle while the token is the same, a new one when it changes (a new sign-in, a rotated session), and the old
330
+ * handle forgotten then, or when nobody is signed in, so a Command still holding it reads no token.
331
+ */
332
+ export const runtimeSessionHandle = (runtime: ClientRuntime, credentials: Credentials) => {
333
+ let current: { readonly token: string; readonly handle: string } | undefined
334
+ return (): string | undefined => {
335
+ const token = runtime.token()
336
+ if (current?.token === token) return current?.handle
337
+ if (current !== undefined) credentials.forget(current.handle)
338
+ current = token === undefined ? undefined : { token, handle: credentials.keep(token) }
339
+ return current?.handle
340
+ }
341
+ }
342
+
343
+ /** The open replica, if it is the one `key` names; `ReplicaUnavailable` otherwise. */
344
+ export class ReplicaUnavailable extends Schema.TaggedError<ReplicaUnavailable>()("ReplicaUnavailable", {
345
+ message: Schema.String,
346
+ }) {}
347
+
348
+ export const replicaFor = (
349
+ key: ReplicaKey,
350
+ ): Effect.Effect<OpenReplica | RuntimeReplica, ReplicaUnavailable, ReplicaService> =>
351
+ Replica.get.pipe(
352
+ Effect.catchTag("ResourceNotAvailable", () =>
353
+ Effect.fail(new ReplicaUnavailable({ message: "No replica is open" })),
354
+ ),
355
+ // Either kind under the one identity: the adapter's own (`replicaResources`) or the runtime's (`runtimeReplica`).
356
+ Effect.map((replica) => replica as OpenReplica | RuntimeReplica),
357
+ Effect.flatMap((replica) =>
358
+ sameReplica(replica.key, key)
359
+ ? Effect.succeed(replica)
360
+ : Effect.fail(
361
+ new ReplicaUnavailable({
362
+ message: `The replica of ${key.orgId} (opening ${key.opening}) is no longer open`,
363
+ }),
364
+ ),
365
+ ),
366
+ )
367
+
368
+ // ---------------------------------------------------------------------------------------------------------------
369
+ // Live queries
370
+
371
+ /** Where a query's result stands, as Zero reports it. */
372
+ export const ResultStatus = Schema.Literals(["unknown", "cached", "complete", "error"])
373
+ export type ResultStatus = typeof ResultStatus.Type
374
+
375
+ /** One result of a live query: the rows (copied out of Zero's view), from which replica, and how settled. */
376
+ export interface Snapshot<Row> {
377
+ readonly key: ReplicaKey
378
+ readonly rows: ReadonlyArray<Row>
379
+ readonly status: ResultStatus
380
+ readonly error: Option.Option<string>
381
+ }
382
+
383
+ /**
384
+ * The schema of a snapshot of rows of type `Row`, checked by `row`: the entity's row schema (`entity.row`) checks
385
+ * each row as it arrives, and `Row` (the generated sync table's row type, `Row<typeof greetingTable>`) types it,
386
+ * both derived from the module's one Drizzle table.
387
+ */
388
+ export const Snapshot = <Row>(row: Schema.Top): Schema.Codec<Snapshot<Row>, unknown> =>
389
+ Schema.Struct({
390
+ key: ReplicaKey,
391
+ rows: Schema.Array(row),
392
+ status: ResultStatus,
393
+ error: Schema.Option(Schema.String),
394
+ }) as unknown as Schema.Codec<Snapshot<Row>, unknown>
395
+
396
+ /**
397
+ * A query's place in the Model: waiting for the replica's first result, or the latest result of the replica the
398
+ * Model holds. Interaction state only: the rows are what the replica delivered, as delivered.
399
+ */
400
+ export const QueryState = <Row>(row: Schema.Top): Schema.Codec<QueryState<Row>, unknown> =>
401
+ Schema.Union([Schema.TaggedStruct("Waiting", {}), Schema.TaggedStruct("Received", { snapshot: Snapshot<Row>(row) })])
402
+ export type QueryState<Row> =
403
+ | { readonly _tag: "Waiting" }
404
+ | { readonly _tag: "Received"; readonly snapshot: Snapshot<Row> }
405
+
406
+ export const QueryWaiting: QueryState<never> = { _tag: "Waiting" }
407
+
408
+ /**
409
+ * The query state after a snapshot arrives: kept only when it comes from the replica the Model holds open, so a
410
+ * snapshot that left a closed replica before it closed is never shown.
411
+ */
412
+ export const receive = <Row>(state: QueryState<Row>, replica: ReplicaState, snapshot: Snapshot<Row>): QueryState<Row> =>
413
+ replica._tag === "Open" && sameReplica(replica.key, snapshot.key) ? { _tag: "Received", snapshot } : state
414
+
415
+ /**
416
+ * A snapshot's rows when it comes from `replica` (the replica a screen was made for: its user, organisation and
417
+ * opening), none otherwise: a snapshot that left another replica (the previous organisation's, a closed one's)
418
+ * before its view was destroyed is never taken. For a handler that keeps rows rather than a `QueryState`.
419
+ */
420
+ export const rowsFrom = <Row>(replica: ReplicaKey, snapshot: Snapshot<Row>): Option.Option<ReadonlyArray<Row>> =>
421
+ sameReplica(replica, snapshot.key) ? Option.some(snapshot.rows) : Option.none()
422
+
423
+ /**
424
+ * `rowsFrom`, once the server has answered: none for a snapshot of another replica, and none while the replica has
425
+ * only what it held before asking (`unknown`), which a screen must not show as the query's answer (an empty list on
426
+ * a slow first sync reads as "nothing there"). For a handler that keeps rows and says it is ready once it has some.
427
+ */
428
+ export const settledRowsFrom = <Row>(replica: ReplicaKey, snapshot: Snapshot<Row>): Option.Option<ReadonlyArray<Row>> =>
429
+ snapshot.status === "unknown" ? Option.none() : rowsFrom(replica, snapshot)
430
+
431
+ /** The rows to render: the received snapshot's, or none while waiting. */
432
+ export const rowsOf = <Row>(state: QueryState<Row>): ReadonlyArray<Row> =>
433
+ state._tag === "Received" ? state.snapshot.rows : []
434
+
435
+ /** Whether the server has confirmed the result (this session or a cached earlier one). */
436
+ export const isSettled = (state: QueryState<unknown>): boolean =>
437
+ state._tag === "Received" && (state.snapshot.status === "complete" || state.snapshot.status === "cached")
438
+
439
+ /** A named query to run: what `queries.<module>.<name>(args)` from `eloxiv.sync.ts` returns. */
440
+ type NamedQuery = Pick<QueryRequest<any, any, any, any, any, any>, "args" | "~"> & { readonly query: unknown }
441
+
442
+ /**
443
+ * A live query as a Foldkit Subscription entry, for a `Subscription.make` record. While `replica(model)` names an
444
+ * open replica, the query runs there and every change arrives as `toMessage(snapshot, scope)`; when the Model's
445
+ * replica changes or closes, the view is destroyed and a new one opens on the next replica.
446
+ *
447
+ * A record-scoped query (one thread, one person) takes `scope(model)`, the argument it is run with
448
+ * (`query(scope)`): when it changes, the view on the old one is destroyed and one on the new one opens, and each
449
+ * snapshot names the scope it is of.
450
+ */
451
+ export const liveQuery = <Model, Message, Row>(options: {
452
+ readonly replica: (model: Model) => Option.Option<ReplicaKey>
453
+ readonly scope?: (model: Model) => string
454
+ readonly query: (scope: string) => NamedQuery
455
+ readonly toMessage: (snapshot: Snapshot<Row>, scope: string) => Message
456
+ }) => ({
457
+ dependenciesSchema: Schema.Struct({ replica: Schema.Option(ReplicaKey), scope: Schema.String }),
458
+ modelToDependencies: (model: Model) => ({ replica: options.replica(model), scope: options.scope?.(model) ?? "" }),
459
+ dependenciesToStream: ({
460
+ replica,
461
+ scope = "",
462
+ }: {
463
+ readonly replica: Option.Option<ReplicaKey>
464
+ readonly scope?: string
465
+ }): Stream.Stream<Message, never, ReplicaService> =>
466
+ replicaStream<Message>(replica, (key, offer, end) => ({
467
+ runtime: (replica) =>
468
+ runtimeQuery(replica, options.query(scope), (rows, status, error) =>
469
+ offer(options.toMessage({ key, rows: rows as ReadonlyArray<Row>, status, error }, scope)),
470
+ ).pipe(Effect.catch(() => Effect.sync(end))),
471
+ zero: (replica) =>
472
+ Effect.acquireRelease(
473
+ Effect.sync(() => {
474
+ const view = replica.zero.materialize(options.query(scope) as QueryRequest<any, any, any, any, any, any>)
475
+ view.addListener((data, status, error) => {
476
+ offer(
477
+ options.toMessage(
478
+ {
479
+ key,
480
+ rows: copyRows(data) as ReadonlyArray<Row>,
481
+ status,
482
+ error: error === undefined ? Option.none() : Option.some(errorText(error)),
483
+ },
484
+ scope,
485
+ ),
486
+ )
487
+ })
488
+ return view
489
+ }),
490
+ (view) =>
491
+ Effect.sync(() => {
492
+ try {
493
+ view.destroy()
494
+ } catch {
495
+ // The replica closed first: its views went with it.
496
+ }
497
+ }),
498
+ ).pipe(Effect.asVoid),
499
+ })),
500
+ })
501
+
502
+ /**
503
+ * A replica's Subscription stream: nothing without a key; with one, `work` on that replica (`offer` sends a Message,
504
+ * `end` ends the stream), through `onOpenReplica`.
505
+ */
506
+ const replicaStream = <Message>(
507
+ replica: Option.Option<ReplicaKey>,
508
+ work: (key: ReplicaKey, offer: (message: Message) => void, end: () => void) => Parameters<typeof onOpenReplica>[2],
509
+ ): Stream.Stream<Message, never, ReplicaService> =>
510
+ Option.match(replica, {
511
+ onNone: () => Stream.empty,
512
+ onSome: (key) =>
513
+ Stream.callback<Message, never, ReplicaService>((queue) => {
514
+ const end = () => Queue.endUnsafe(queue)
515
+ return onOpenReplica(
516
+ key,
517
+ end,
518
+ work(key, (message) => Queue.offerUnsafe(queue, message), end),
519
+ )
520
+ }),
521
+ })
522
+
523
+ /**
524
+ * A Subscription's work on the replica `key` names, while the scope lasts: `runtime`'s on the client core's replica,
525
+ * `zero`'s on one this adapter opened; when it is not the replica the Model holds open (it closed, or another
526
+ * opened), nothing (`end`: the stream has nothing to say).
527
+ */
528
+ const onOpenReplica = (
529
+ key: ReplicaKey,
530
+ end: () => void,
531
+ work: {
532
+ readonly runtime: (replica: RuntimeReplica) => Effect.Effect<void, never, Scope.Scope>
533
+ readonly zero: (replica: OpenReplica) => Effect.Effect<void, never, Scope.Scope>
534
+ },
535
+ ): Effect.Effect<void, never, Scope.Scope | ReplicaService> =>
536
+ Effect.gen(function* () {
537
+ const open = yield* replicaFor(key).pipe(Effect.option)
538
+ if (Option.isNone(open)) return end()
539
+ yield* isRuntimeReplica(open.value) ? work.runtime(open.value) : work.zero(open.value)
540
+ yield* Effect.never
541
+ })
542
+
543
+ const errorText = (error: unknown): string => {
544
+ const e = error as { readonly message?: unknown; readonly details?: unknown; readonly error?: unknown }
545
+ if (typeof e.message === "string") return e.message
546
+ return JSON.stringify(error)
547
+ }
548
+
549
+ /** Web Crypto, read from `globalThis` (the SDK declares no DOM types). */
550
+ const webCrypto = (globalThis as { readonly crypto?: { randomUUID?: () => string } }).crypto
551
+ const randomId = (): string =>
552
+ typeof webCrypto?.randomUUID === "function"
553
+ ? webCrypto.randomUUID()
554
+ : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
555
+
556
+ /**
557
+ * A named query run live by the runtime, in the replica's generation (refused for another), for as long as the scope
558
+ * lasts: each `rows` event of it reaches `onRows`. Fails when the runtime refuses it (another generation, signed out).
559
+ */
560
+ const runtimeQuery = (
561
+ replica: RuntimeReplica,
562
+ request: NamedQuery,
563
+ onRows: (rows: ReadonlyArray<unknown>, status: ResultStatus, error: Option.Option<string>) => void,
564
+ ): Effect.Effect<void, unknown, Scope.Scope> => {
565
+ const id = randomId()
566
+ const name = (request.query as { readonly queryName?: unknown }).queryName
567
+ return Effect.acquireRelease(
568
+ Effect.tryPromise({
569
+ try: async () => {
570
+ if (typeof name !== "string") throw new Error("Not a named query")
571
+ const stop = replica.runtime.onEvent((event) => {
572
+ if (event.type !== "rows" || event.subscription !== id || event.generation !== replica.key.opening) return
573
+ onRows(
574
+ event.rows,
575
+ event.status,
576
+ event.error === undefined ? Option.none() : Option.some(errorText(event.error)),
577
+ )
578
+ })
579
+ try {
580
+ await replica.runtime.subscribe(
581
+ { query: name, args: request.args, id, generation: replica.key.opening },
582
+ replica.owner,
583
+ )
584
+ } catch (error) {
585
+ stop()
586
+ throw error
587
+ }
588
+ return stop
589
+ },
590
+ catch: (error) => error,
591
+ }),
592
+ (stop) =>
593
+ Effect.sync(() => {
594
+ stop()
595
+ try {
596
+ replica.runtime.unsubscribe(id, replica.owner)
597
+ } catch {
598
+ // The context changed first: the runtime destroyed the view with it.
599
+ }
600
+ }),
601
+ )
602
+ }
603
+
604
+ // ---------------------------------------------------------------------------------------------------------------
605
+ // Connection state
606
+
607
+ /** Zero's connection state, as Messages carry it. */
608
+ export const ConnectionState = Schema.Struct({
609
+ key: ReplicaKey,
610
+ state: Schema.Literals(["initializing", "connecting", "disconnected", "connected", "needs-auth", "error", "closed"]),
611
+ reason: Schema.Option(Schema.String),
612
+ })
613
+ export type ConnectionState = typeof ConnectionState.Type
614
+
615
+ /** The runtime's connection states (the LocalClient contract's), as Zero names them. */
616
+ const RUNTIME_CONNECTION: Record<"connecting" | "connected" | "disconnected" | "needsAuth", ConnectionState["state"]> =
617
+ { connecting: "connecting", connected: "connected", disconnected: "disconnected", needsAuth: "needs-auth" }
618
+
619
+ /** The open replica's connection state as a Subscription entry: every change (and the current state) as a Message. */
620
+ export const connectionState = <Model, Message>(options: {
621
+ readonly replica: (model: Model) => Option.Option<ReplicaKey>
622
+ readonly toMessage: (state: ConnectionState) => Message
623
+ }) => ({
624
+ dependenciesSchema: Schema.Struct({ replica: Schema.Option(ReplicaKey) }),
625
+ modelToDependencies: (model: Model) => ({ replica: options.replica(model) }),
626
+ dependenciesToStream: ({
627
+ replica,
628
+ }: {
629
+ readonly replica: Option.Option<ReplicaKey>
630
+ }): Stream.Stream<Message, never, ReplicaService> =>
631
+ replicaStream<Message>(replica, (key, offer) => ({
632
+ // The runtime's own connection events, while its context is this generation.
633
+ runtime: (replica) =>
634
+ Effect.acquireRelease(
635
+ Effect.sync(() =>
636
+ replica.runtime.onEvent((event) => {
637
+ if (event.type !== "connection" || replica.runtime.generation() !== key.opening) return
638
+ offer(options.toMessage({ key, state: RUNTIME_CONNECTION[event.state], reason: Option.none() }))
639
+ }),
640
+ ),
641
+ (stop) => Effect.sync(stop),
642
+ ).pipe(Effect.asVoid),
643
+ zero: (replica) => {
644
+ const source = replica.zero.connection.state
645
+ const emit = (state: { readonly name: ConnectionState["state"]; readonly reason?: unknown }) =>
646
+ offer(
647
+ options.toMessage({
648
+ key,
649
+ state: state.name,
650
+ reason:
651
+ state.reason === undefined
652
+ ? Option.none()
653
+ : Option.some(typeof state.reason === "string" ? state.reason : JSON.stringify(state.reason)),
654
+ }),
655
+ )
656
+ return Effect.acquireRelease(
657
+ Effect.sync(() => {
658
+ emit(source.current)
659
+ return source.subscribe(emit)
660
+ }),
661
+ (unsubscribe) => Effect.sync(unsubscribe),
662
+ ).pipe(Effect.asVoid)
663
+ },
664
+ })),
665
+ })
666
+
667
+ // ---------------------------------------------------------------------------------------------------------------
668
+ // Writes
669
+
670
+ /** The server did not confirm a write: the replica closed or went offline before it answered. It may still run. */
671
+ export class WriteNotConfirmed extends Schema.TaggedError<WriteNotConfirmed>()("WriteNotConfirmed", {
672
+ message: Schema.String,
673
+ }) {}
674
+
675
+ /** Why a write did not land, as a Message carries it: the invocation's typed error, or no confirmation. */
676
+ export const WriteError = Schema.Union([InvocationError, WriteNotConfirmed, ReplicaUnavailable])
677
+ export type WriteError = typeof WriteError.Type
678
+
679
+ const isInvocationError = Schema.is(InvocationError)
680
+
681
+ /**
682
+ * Write optimistically on the replica `key` names: `writeOptimistic(key, mutators.hello.greet({ message }))`. The
683
+ * prediction is applied at once (the live queries show it); the Effect succeeds once the server ran the action and
684
+ * the replica holds its rows, and fails with the invocation's typed error once the replica has dropped the
685
+ * prediction, `WriteNotConfirmed` if the replica closes first, or `ReplicaUnavailable` if `key` is not the open
686
+ * replica (nothing is written then). Interrupting it stops the wait, not the write.
687
+ */
688
+ export const writeOptimistic = (
689
+ key: ReplicaKey,
690
+ request: MutateRequest<any, any, any, any>,
691
+ ): Effect.Effect<void, WriteError, ReplicaService> =>
692
+ Effect.gen(function* () {
693
+ const replica = yield* replicaFor(key)
694
+ if (isRuntimeReplica(replica)) return yield* runtimeWrite(replica, request)
695
+ const pending = write(replica.zero, request)
696
+ const server = Effect.tryPromise({
697
+ try: () => pending.server,
698
+ catch: (error): WriteError =>
699
+ isInvocationError(error)
700
+ ? error
701
+ : error instanceof WriteNotConfirmedError
702
+ ? new WriteNotConfirmed({ message: error.message })
703
+ : new WriteNotConfirmed({ message: messageOf(error) }),
704
+ })
705
+ const closed = closedFirst(replica.closed)
706
+ yield* Effect.raceFirst(server, closed)
707
+ })
708
+
709
+ const decodeInvocationError = Schema.decodeUnknownOption(InvocationError)
710
+
711
+ /** Fails with `WriteNotConfirmed` once the replica is let go of: what a write's wait races. */
712
+ const closedFirst = (closed: Deferred.Deferred<void>) =>
713
+ Deferred.await(closed).pipe(
714
+ Effect.andThen(Effect.fail(new WriteNotConfirmed({ message: "The replica closed before the server answered" }))),
715
+ )
716
+
717
+ /**
718
+ * An optimistic write through the runtime, in the replica's generation (nothing predicted or sent for another): it
719
+ * succeeds once confirmed, fails with the kernel's typed error once rejected (after the rollback), or
720
+ * `WriteNotConfirmed` when the replica goes offline, the context changes or the Model lets go of it first.
721
+ */
722
+ const runtimeWrite = (
723
+ replica: RuntimeReplica,
724
+ request: MutateRequest<any, any, any, any>,
725
+ ): Effect.Effect<void, WriteError> =>
726
+ Effect.gen(function* () {
727
+ const id = randomId()
728
+ const outcome = yield* Deferred.make<void, WriteError>()
729
+ const settle = (exit: WriteError | undefined) =>
730
+ Effect.runSync(exit === undefined ? Deferred.succeed(outcome, undefined) : Deferred.fail(outcome, exit))
731
+ const stop = replica.runtime.onEvent((event) => {
732
+ if (event.type === "context") {
733
+ settle(new WriteNotConfirmed({ message: "The context changed before the server answered" }))
734
+ return
735
+ }
736
+ if (event.type !== "write" || event.id !== id) return
737
+ if (event.phase === "confirmed") settle(undefined)
738
+ else if (event.phase === "rejected")
739
+ settle(
740
+ Option.getOrElse(
741
+ decodeInvocationError(event.error),
742
+ () => new WriteNotConfirmed({ message: errorText(event.error) }),
743
+ ),
744
+ )
745
+ else if (event.phase === "notConfirmed")
746
+ settle(new WriteNotConfirmed({ message: event.message ?? "The server did not confirm the write" }))
747
+ })
748
+ const mutator = (request as unknown as { readonly mutator?: { readonly mutatorName?: unknown } }).mutator
749
+ ?.mutatorName
750
+ const started = Effect.tryPromise({
751
+ try: async () => {
752
+ if (typeof mutator !== "string") throw new Error("Not a named mutator")
753
+ await replica.runtime.write(
754
+ {
755
+ mutator,
756
+ input: (request as unknown as { readonly args?: unknown }).args,
757
+ id,
758
+ generation: replica.key.opening,
759
+ },
760
+ replica.owner,
761
+ )
762
+ },
763
+ catch: (error): WriteError =>
764
+ // The kernel's typed refusal (`InvalidInput`, ...) as it is; anything else (another generation, signed out,
765
+ // closed) means this replica is no longer the one to write to.
766
+ isInvocationError(error) ? error : new ReplicaUnavailable({ message: messageOf(error) }),
767
+ })
768
+ const closed = closedFirst(replica.closed)
769
+ yield* started.pipe(
770
+ Effect.andThen(Deferred.await(outcome)),
771
+ (wait) => Effect.raceFirst(wait, closed),
772
+ Effect.ensuring(Effect.sync(stop)),
773
+ )
774
+ })
775
+
776
+ /** The session and organisation an action call acts in, given by the Command (update decides them, not a closure). */
777
+ export interface ActingAs {
778
+ readonly token: string
779
+ readonly orgId: string
780
+ readonly idempotencyKey?: string | undefined
781
+ }
782
+
783
+ /** A call that did not reach a typed answer (the network, the protocol). */
784
+ export class ActionCallFailed extends Schema.TaggedError<ActionCallFailed>()("ActionCallFailed", {
785
+ action: Schema.String,
786
+ message: Schema.String,
787
+ }) {}
788
+
789
+ /**
790
+ * Call an action through the typed client, in the calling fiber: the Command that runs it owns the request, so
791
+ * interrupting the Command aborts it (a call that already reached the kernel may still run, once with an
792
+ * idempotency key). Fails with the action's typed error, or `ActionCallFailed`.
793
+ */
794
+ export const callAction = <
795
+ const Modules extends ReadonlyArray<AnyModuleContract>,
796
+ const Tag extends ActionName<Modules>,
797
+ >(
798
+ client: EloxivClient<Modules>,
799
+ action: Tag,
800
+ input: ActionInput<Modules, Tag>,
801
+ acting: ActingAs,
802
+ ): Effect.Effect<ActionOutput<Modules, Tag>, InvocationError | ActionCallFailed> =>
803
+ client
804
+ .callEffect(action, input, acting)
805
+ .pipe(
806
+ Effect.mapError((error) =>
807
+ isInvocationError(error) ? error : new ActionCallFailed({ action, message: messageOf(error) }),
808
+ ),
809
+ )
810
+
811
+ // ---------------------------------------------------------------------------------------------------------------
812
+ // Collaborative documents
813
+
814
+ /** Which record's collaborative document the Model wants open, under which session (its handle, never its token). */
815
+ export const CollabTarget = Schema.Struct({
816
+ entity: Schema.String,
817
+ id: Schema.String,
818
+ orgId: Schema.String,
819
+ session: Schema.String,
820
+ })
821
+ export type CollabTarget = typeof CollabTarget.Type
822
+
823
+ /** A peer's presence, as Messages carry it. */
824
+ export const CollabPeerState = Schema.Struct({ clientId: Schema.Number, userId: Schema.String, state: Schema.Unknown })
825
+
826
+ /**
827
+ * One state of an open collaborative document, as a Message carries it: the text root's text (a copy), whether the
828
+ * caller may change it, the connection's status, others' presence, and why the kernel closed it, if it did.
829
+ */
830
+ export const CollabSnapshot = Schema.Struct({
831
+ entity: Schema.String,
832
+ id: Schema.String,
833
+ orgId: Schema.String,
834
+ text: Schema.String,
835
+ seq: Schema.Number,
836
+ canWrite: Schema.Boolean,
837
+ status: Schema.Literals(["connecting", "synced", "offline", "closed"]),
838
+ peers: Schema.Array(CollabPeerState),
839
+ closedWith: Schema.Option(Schema.String),
840
+ })
841
+ export type CollabSnapshot = typeof CollabSnapshot.Type
842
+
843
+ /** No collaborative document is open for that record (the Model no longer wants it, or it has not opened yet). */
844
+ export class CollabUnavailable extends Schema.TaggedError<CollabUnavailable>()("CollabUnavailable", {
845
+ message: Schema.String,
846
+ }) {}
847
+
848
+ /** A text edit whose passage is not in the document: nothing was applied. */
849
+ export class CollabEditRefused extends Schema.TaggedError<CollabEditRefused>()("CollabEditRefused", {
850
+ message: Schema.String,
851
+ }) {}
852
+
853
+ /** A record whose document a Command addresses. */
854
+ export interface CollabRecord {
855
+ readonly entity: string
856
+ readonly id: string
857
+ readonly orgId: string
858
+ }
859
+
860
+ const collabKey = (target: CollabRecord) => `${target.orgId}\u0000${target.entity}\u0000${target.id}`
861
+
862
+ /** The documents the `collabDocument` Subscriptions hold open, by record: what Commands edit. */
863
+ const openDocuments = new Map<string, { readonly connection: CollabConnection; readonly text: string }>()
864
+
865
+ /**
866
+ * A record's collaborative document as a Foldkit Subscription entry. While `document(model)` names a record and a
867
+ * session, the document is open (its WebSocket included) and every change (a local or remote edit, presence, the
868
+ * connection's status) arrives as `toMessage(snapshot)`; when the Model names another record, organisation or
869
+ * session, or none, the connection closes and its presence is withdrawn. The Y.Doc stays inside the runtime: the
870
+ * Model holds snapshots, never the document. Edit it with `editCollabText` and `setCollabPresence` Commands.
871
+ */
872
+ export const collabDocument = <Model, Message>(options: {
873
+ /** The kernel's base URL. */
874
+ readonly baseUrl: string
875
+ readonly credentials: Credentials
876
+ readonly document: (model: Model) => Option.Option<CollabTarget>
877
+ /** The text root the snapshots carry (default `content`). */
878
+ readonly text?: string | undefined
879
+ readonly toMessage: (snapshot: CollabSnapshot) => Message
880
+ /** A WebSocket constructor (default the global one). */
881
+ readonly WebSocket?: typeof WebSocket | undefined
882
+ }) => ({
883
+ dependenciesSchema: Schema.Struct({ document: Schema.Option(CollabTarget) }),
884
+ modelToDependencies: (model: Model) => ({ document: options.document(model) }),
885
+ dependenciesToStream: ({ document }: { readonly document: Option.Option<CollabTarget> }): Stream.Stream<Message> =>
886
+ Option.match(document, {
887
+ onNone: () => Stream.empty,
888
+ onSome: (target) =>
889
+ Stream.callback<Message>((queue) =>
890
+ Effect.acquireRelease(
891
+ Effect.sync(() => {
892
+ const name = options.text ?? "content"
893
+ const connection = connectCollab({
894
+ baseUrl: options.baseUrl,
895
+ entity: target.entity,
896
+ id: target.id,
897
+ orgId: target.orgId,
898
+ token: () => options.credentials.token(target.session),
899
+ WebSocket: options.WebSocket,
900
+ })
901
+ const key = collabKey(target)
902
+ openDocuments.set(key, { connection, text: name })
903
+ const snapshot = (): CollabSnapshot => ({
904
+ entity: target.entity,
905
+ id: target.id,
906
+ orgId: target.orgId,
907
+ text: connection.doc.getText(name).toJSON(),
908
+ seq: connection.seq,
909
+ canWrite: connection.canWrite,
910
+ status: connection.status,
911
+ peers: connection.peers.map((p) => ({ clientId: p.clientId, userId: p.userId, state: p.state })),
912
+ closedWith:
913
+ connection.closedWith === undefined ? Option.none() : Option.some(connection.closedWith._tag),
914
+ })
915
+ const emit = () => Queue.offerUnsafe(queue, options.toMessage(snapshot()))
916
+ const stop = connection.subscribe(emit)
917
+ connection.doc.on("update", emit)
918
+ emit()
919
+ return { key, connection, stop, emit }
920
+ }),
921
+ ({ key, connection, stop, emit }) =>
922
+ Effect.sync(() => {
923
+ stop()
924
+ connection.doc.off("update", emit)
925
+ if (openDocuments.get(key)?.connection === connection) openDocuments.delete(key)
926
+ connection.close()
927
+ }),
928
+ ).pipe(Effect.andThen(Effect.never)),
929
+ ),
930
+ }),
931
+ })
932
+
933
+ const openDocument = (target: CollabRecord) => {
934
+ const open = openDocuments.get(collabKey(target))
935
+ return open === undefined || open.connection.status === "closed"
936
+ ? Effect.fail(
937
+ new CollabUnavailable({ message: `No collaborative document of ${target.entity} ${target.id} is open` }),
938
+ )
939
+ : Effect.succeed(open)
940
+ }
941
+
942
+ /**
943
+ * Edit the open document's text root (the kinds `collab.editText` takes), as one Yjs transaction that the document
944
+ * sends to the kernel: for Commands. Succeeds with the text after the edits; nothing is applied when a passage is
945
+ * not there (`CollabEditRefused`) or the document is not open (`CollabUnavailable`).
946
+ */
947
+ export const editCollabText = (
948
+ target: CollabRecord,
949
+ edits: ReadonlyArray<CollabTextEdit>,
950
+ ): Effect.Effect<string, CollabUnavailable | CollabEditRefused> =>
951
+ Effect.flatMap(openDocument(target), (open) =>
952
+ Effect.try({
953
+ try: () => applyTextEdits(open.connection.doc, open.text, edits),
954
+ catch: (error) => new CollabEditRefused({ message: messageOf(error) }),
955
+ }),
956
+ )
957
+
958
+ /** Publish (or withdraw, with null) this client's presence on the open document: for Commands. */
959
+ export const setCollabPresence = (target: CollabRecord, state: unknown): Effect.Effect<void, CollabUnavailable> =>
960
+ Effect.map(openDocument(target), (open) => open.connection.setPresence(state))