@eloxiv/client 0.0.0-stage → 0.1.0

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 +1249 -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 +226 -0
  164. package/dist/Session.d.ts.map +1 -0
  165. package/dist/Session.js +763 -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 +1409 -0
  254. package/src/RuntimeRuns.ts +180 -0
  255. package/src/ServicesSync.ts +58 -0
  256. package/src/Session.ts +814 -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/Skew.ts ADDED
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Recovering from version skew (the Release contract's `ClientOutdated`) without losing what the person was doing.
3
+ * A write refused because this build is older than the kernel's minimum is kept, and the person is offered a reload
4
+ * (`reload-offered`). Reloading is the host's (`reload`, typically `location.reload()`); declining keeps the kept
5
+ * writes (`reload-declined`) and leaves an explicit retry: `retry()` reads the kernel's release afresh (past any
6
+ * cache) and, when this build is accepted again (the deployment was rolled back, or the minimum lowered), sends the
7
+ * kept writes again, each under its own idempotency key, so a retry runs it once; otherwise the reload is offered
8
+ * again. Reads never stop: only writes are refused to an old build.
9
+ */
10
+ import type { ReleaseInfo } from "@eloxiv/contracts"
11
+ import { satisfiesRange } from "@eloxiv/contracts"
12
+ import { isClientOutdated } from "./Client.ts"
13
+
14
+ export type SkewState =
15
+ | { readonly kind: "current" }
16
+ | { readonly kind: "reload-offered"; readonly minClientVersion: string; readonly kept: number }
17
+ | { readonly kind: "reload-declined"; readonly minClientVersion: string; readonly kept: number }
18
+
19
+ export interface SkewRecoveryOptions {
20
+ /** This build's version (what the client sends as `x-eloxiv-client-version`). */
21
+ readonly clientVersion: string
22
+ /** Reload the app onto the current build (the host's: `location.reload()`, a desktop host's update). */
23
+ readonly reload: () => void
24
+ /** The kernel's release, read afresh (default: `GET <baseUrl>/release` past any cache). */
25
+ readonly release: () => Promise<ReleaseInfo>
26
+ }
27
+
28
+ /** The kernel's release, past any HTTP cache (a query no cache has seen, and `no-store`). */
29
+ export const fetchFreshRelease = async (baseUrl: string): Promise<ReleaseInfo> => {
30
+ const response = await fetch(`${baseUrl}/release?fresh=${Date.now().toString(36)}`, {
31
+ headers: { "cache-control": "no-store" },
32
+ })
33
+ if (!response.ok) throw new Error(`/release answered ${response.status}`)
34
+ return (await response.json()) as ReleaseInfo
35
+ }
36
+
37
+ export const skewRecovery = (options: SkewRecoveryOptions) => {
38
+ let state: SkewState = { kind: "current" }
39
+ const kept: Array<() => Promise<unknown>> = []
40
+ const listeners = new Set<(state: SkewState) => void>()
41
+ const set = (next: SkewState) => {
42
+ state = next
43
+ for (const listener of listeners) listener(state)
44
+ }
45
+ return {
46
+ state: () => state,
47
+ subscribe: (listener: (state: SkewState) => void) => {
48
+ listeners.add(listener)
49
+ return () => {
50
+ listeners.delete(listener)
51
+ }
52
+ },
53
+ /**
54
+ * Run a write; if the kernel refuses it as from an outdated build, keep it (`again` sends it again, with the
55
+ * same idempotency key) and offer the reload. Resolves with the write's result, or `undefined` when it was
56
+ * kept; any other failure is the write's own.
57
+ */
58
+ write: async <A>(again: () => Promise<A>): Promise<A | undefined> => {
59
+ try {
60
+ return await again()
61
+ } catch (error) {
62
+ if (!isClientOutdated(error)) throw error
63
+ kept.push(again)
64
+ // A typed call's error carries the minimum itself; a `send` or a batch read's, in its `error`.
65
+ const failure = error as { minClientVersion?: unknown; error?: { minClientVersion?: unknown } }
66
+ const stated = failure.minClientVersion ?? failure.error?.minClientVersion
67
+ const minimum = typeof stated === "string" ? stated : ""
68
+ set({ kind: "reload-offered", minClientVersion: minimum, kept: kept.length })
69
+ return undefined
70
+ }
71
+ },
72
+ /** The person chose to reload. The kept writes go with the page; the new build's screens are theirs to redo. */
73
+ reload: () => options.reload(),
74
+ /** The person declined the reload: the kept writes stay, for an explicit retry. */
75
+ decline: () => {
76
+ if (state.kind === "reload-offered") set({ ...state, kind: "reload-declined" })
77
+ },
78
+ /**
79
+ * Read the release afresh: if this build is accepted, send the kept writes again (in order) and return to
80
+ * `current`; if not, offer the reload again. Resolves with how many kept writes were sent.
81
+ */
82
+ retry: async (): Promise<number> => {
83
+ const release = await options.release()
84
+ const minimum = release.minClientVersion
85
+ const accepted = minimum === null || satisfiesRange(options.clientVersion, `>=${minimum}`) === true
86
+ if (!accepted) {
87
+ set({ kind: "reload-offered", minClientVersion: minimum ?? "", kept: kept.length })
88
+ return 0
89
+ }
90
+ const sending = kept.splice(0)
91
+ set({ kind: "current" })
92
+ for (const again of sending) await again()
93
+ return sending.length
94
+ },
95
+ }
96
+ }
97
+ export type SkewRecovery = ReturnType<typeof skewRecovery>
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Spaces in each person's replica (the Space contract): the kernel-provided `spaces` module's synced tables
3
+ * (generated from its Drizzle tables, `KernelTables.gen.ts`) and named queries. An app that installs
4
+ * `spacesModule` adds `spacesTables`, `spacesRelationships` and `spacesQueries` to its sync schema;
5
+ * `@eloxiv/shell-core`'s `resolveSpaces` turns the rows into the person's spaces.
6
+ *
7
+ * The kernel filters every query by the entity's read policy, in the organisation the replica acts in:
8
+ * - grants (`spaceGrant`): one row per space and audience, synced only where the audience is everyone or a role
9
+ * the person holds (live: losing the role takes the row off the replica), never once withdrawn;
10
+ * - preferences (`spacePreference`): the person's own, one per grant they were set through, synced only while that
11
+ * grant reaches them; never anyone else's.
12
+ */
13
+ import { createBuilder, createSchema, defineQueryWithType } from "@rocicorp/zero"
14
+ import {
15
+ spaceGrantRelationships,
16
+ spaceGrantTable,
17
+ spacePreferenceRelationships,
18
+ spacePreferenceTable,
19
+ } from "./KernelTables.gen.ts"
20
+
21
+ export { spaceGrantTable, spacePreferenceTable }
22
+
23
+ export const spacesTables = [spaceGrantTable, spacePreferenceTable] as const
24
+ export const spacesRelationships = [spaceGrantRelationships, spacePreferenceRelationships] as const
25
+
26
+ const localSchema = createSchema({ tables: [spaceGrantTable, spacePreferenceTable] })
27
+ const zql = createBuilder(localSchema)
28
+ const defineQuery = defineQueryWithType<typeof localSchema>()
29
+
30
+ /** Named queries, namespaced like a module's (`spaces.granted`, `spaces.preferences`). */
31
+ export const spacesQueries = {
32
+ spaces: {
33
+ /** Every space granted to you in the organisation you act in (the kernel adds the filter). */
34
+ granted: defineQuery(() => zql.spaceGrant),
35
+ /** Your own preferences for your spaces. */
36
+ preferences: defineQuery(() => zql.spacePreference),
37
+ },
38
+ }
39
+
40
+ /** A grant row as the replica holds it (the columns `resolveSpaces` reads). */
41
+ export interface SpaceGrantRow {
42
+ readonly spaceId: string
43
+ readonly title: string
44
+ readonly description?: string | null | undefined
45
+ readonly icon?: string | null | undefined
46
+ readonly entries: ReadonlyArray<{ readonly view: string }>
47
+ readonly position: number
48
+ readonly updatedAt: number
49
+ }
50
+
51
+ /** A preference row as the replica holds it. */
52
+ export interface SpacePreferenceRow {
53
+ readonly spaceId: string
54
+ /** When set (the newest of a space's rows wins when it was set through several grants). */
55
+ readonly updatedAt?: number | undefined
56
+ readonly pinned?: boolean | null | undefined
57
+ readonly hidden?: boolean | null | undefined
58
+ readonly position?: number | null | undefined
59
+ readonly entryOrder?: ReadonlyArray<string> | null | undefined
60
+ readonly hiddenEntries?: ReadonlyArray<string> | null | undefined
61
+ }
package/src/Storage.ts ADDED
@@ -0,0 +1,167 @@
1
+ /**
2
+ * The StorageAdapter contract (decision 7; docs/contracts/storage-adapter.md): where the local replica lives.
3
+ * Each adapter is what `connectSync({ storage })` takes, with what it is:
4
+ *
5
+ * - `indexedDbStorage()`: IndexedDB, in browsers and webviews (Tauri's included). Durable.
6
+ * - `sqliteStorage(open)`: SQLite through any synchronous SQLite database (Bun's `bun:sqlite`, Node's
7
+ * `node:sqlite`, or another binding with the same shape), on desktop, servers and the daemon. Durable. On
8
+ * React Native, `expoSQLiteStoreProvider` from `@eloxiv/client/expo-sqlite` is the SQLite adapter.
9
+ * - `memoryStorage()`: memory only; nothing is kept (tests, short-lived processes).
10
+ *
11
+ * The SDK imports no SQLite binding itself (it runs everywhere); the caller passes one:
12
+ * ```ts
13
+ * import { Database } from "bun:sqlite"
14
+ * connectSync({ ..., storage: sqliteStorage((file) => new Database(file), { directory }).storage })
15
+ * ```
16
+ */
17
+ import type { StorageAdapterInfo } from "@eloxiv/contracts"
18
+ import {
19
+ dropStore,
20
+ SQLiteStore,
21
+ type PreparedStatement,
22
+ type SQLiteDatabase,
23
+ type SQLiteStoreOptions,
24
+ type StoreProvider,
25
+ } from "@rocicorp/zero/sqlite"
26
+ import type { SyncStorage } from "./Sync.ts"
27
+
28
+ export interface StorageAdapter {
29
+ readonly info: StorageAdapterInfo
30
+ /** What `connectSync` takes as `storage`. */
31
+ readonly storage: SyncStorage
32
+ }
33
+
34
+ export const memoryStorage = (): StorageAdapter => ({
35
+ info: { kind: "memory", durable: false, platforms: ["web", "desktop", "mobile", "server"] },
36
+ storage: "mem",
37
+ })
38
+
39
+ export const indexedDbStorage = (): StorageAdapter => ({
40
+ info: { kind: "indexeddb", durable: true, platforms: ["web", "desktop"] },
41
+ storage: "idb",
42
+ })
43
+
44
+ /** A prepared statement of a synchronous SQLite binding (`bun:sqlite`'s and `node:sqlite`'s have this shape). */
45
+ export interface SyncSqliteStatement {
46
+ run(...params: ReadonlyArray<string>): unknown
47
+ all(...params: ReadonlyArray<string>): ReadonlyArray<unknown>
48
+ }
49
+
50
+ /** A synchronous SQLite database (`new Database(file)` in Bun, `new DatabaseSync(file)` in Node). */
51
+ export interface SyncSqliteDatabase {
52
+ exec(sql: string): unknown
53
+ prepare(sql: string): SyncSqliteStatement
54
+ close(): unknown
55
+ }
56
+
57
+ export interface SqliteStorageOptions {
58
+ /** The directory the replica files live in (one file per person and organisation). */
59
+ readonly directory?: string | undefined
60
+ readonly busyTimeout?: number | undefined
61
+ /**
62
+ * Also delete a dropped replica's files (the database and its WAL and shared-memory files). Without it, `drop`
63
+ * still wipes the replica in place (its table dropped and the file vacuumed), so nothing of it can be read back.
64
+ */
65
+ readonly remove?: ((path: string) => void) | undefined
66
+ }
67
+
68
+ /** A row as an array in column order (the store reads positions; bindings return objects or arrays). */
69
+ const asArray = (row: unknown): Array<unknown> =>
70
+ Array.isArray(row) ? row : row !== null && typeof row === "object" ? Object.values(row) : [row]
71
+
72
+ class SyncStatement implements PreparedStatement {
73
+ readonly #statement: SyncSqliteStatement
74
+ constructor(statement: SyncSqliteStatement) {
75
+ this.#statement = statement
76
+ }
77
+ // A synchronous binding runs each call to completion, so no other caller can rebind the statement between
78
+ // executing it and reading its rows (the atomicity SQLiteStore requires of a shared statement).
79
+ exec(params: Array<string>): Promise<void> {
80
+ this.#statement.run(...params)
81
+ return Promise.resolve()
82
+ }
83
+ all(params: Array<string>): Promise<Array<Array<unknown>>> {
84
+ return Promise.resolve(this.#statement.all(...params).map(asArray))
85
+ }
86
+ }
87
+
88
+ /** The replica's table (Zero's SQLite store keeps every key in it). */
89
+ const ENTRY_TABLE = "entry"
90
+
91
+ /** Wipe a replica's file in place: its table dropped, the file vacuumed (freed pages gone), the WAL truncated. */
92
+ const wipe = (open: (path: string) => SyncSqliteDatabase, path: string) => {
93
+ const db = open(path)
94
+ try {
95
+ db.exec(`DROP TABLE IF EXISTS ${ENTRY_TABLE}`)
96
+ db.exec("VACUUM")
97
+ db.exec("PRAGMA wal_checkpoint(TRUNCATE)")
98
+ } finally {
99
+ db.close()
100
+ }
101
+ }
102
+
103
+ class SyncDatabase implements SQLiteDatabase {
104
+ readonly #db: SyncSqliteDatabase
105
+ readonly #open: (path: string) => SyncSqliteDatabase
106
+ readonly #path: string
107
+ readonly #remove: ((path: string) => void) | undefined
108
+ constructor(open: (path: string) => SyncSqliteDatabase, path: string, remove: ((path: string) => void) | undefined) {
109
+ this.#db = open(path)
110
+ this.#open = open
111
+ this.#path = path
112
+ this.#remove = remove
113
+ }
114
+ #closed = false
115
+ close(): void {
116
+ if (this.#closed) return
117
+ this.#closed = true
118
+ this.#db.close()
119
+ }
120
+ destroy(): void {
121
+ this.close()
122
+ wipe(this.#open, this.#path)
123
+ for (const suffix of ["", "-wal", "-shm"]) this.#remove?.(`${this.#path}${suffix}`)
124
+ }
125
+ prepare(sql: string): PreparedStatement {
126
+ return new SyncStatement(this.#db.prepare(sql))
127
+ }
128
+ execSync(sql: string): void {
129
+ this.#db.exec(sql)
130
+ }
131
+ }
132
+
133
+ export const sqliteStorage = (
134
+ open: (path: string) => SyncSqliteDatabase,
135
+ options: SqliteStorageOptions = {},
136
+ ): StorageAdapter & { readonly provider: StoreProvider } => {
137
+ const storeOptions: SQLiteStoreOptions = {
138
+ ...(options.directory === undefined ? {} : { directory: options.directory }),
139
+ ...(options.busyTimeout === undefined ? {} : { busyTimeout: options.busyTimeout }),
140
+ }
141
+ const create = (path: string) => new SyncDatabase(open, path, options.remove)
142
+ const pathOf = (name: string) => {
143
+ const file = name.replace(/[^a-zA-Z0-9]/g, "_")
144
+ return options.directory === undefined ? file : `${options.directory}/${file}`
145
+ }
146
+ const provider: StoreProvider = {
147
+ create: (name) => new SQLiteStore(name, create, storeOptions, "sqlite"),
148
+ drop: async (name) => {
149
+ // Zero's dropStore closes the shared connection, then destroys the file, but ignores a failure to: check.
150
+ await dropStore(name, create, storeOptions)
151
+ const db = open(pathOf(name))
152
+ try {
153
+ const left = db.prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?`).all(ENTRY_TABLE)
154
+ if (left.length > 0) throw new Error(`The replica ${name} could not be dropped`)
155
+ } finally {
156
+ db.close()
157
+ if (options.remove !== undefined)
158
+ for (const suffix of ["", "-wal", "-shm"]) options.remove(`${pathOf(name)}${suffix}`)
159
+ }
160
+ },
161
+ }
162
+ return {
163
+ info: { kind: "sqlite", durable: true, platforms: ["desktop", "mobile", "server"] },
164
+ storage: provider,
165
+ provider,
166
+ }
167
+ }
package/src/Sync.ts ADDED
@@ -0,0 +1,125 @@
1
+ /**
2
+ * The client's local replica and the sync API modules and UI use (decision 9: sync only through
3
+ * `@eloxiv/client`). Queries keep ZQL's shape: this re-exports Zero's query builder, named-query definitions,
4
+ * schema builders (for the generated sync tables) and row types, and `connectSync` opens a replica typed by the
5
+ * app's generated schema (`eloxiv.sync.ts`). React bindings are in `@eloxiv/client/react`.
6
+ */
7
+ import { CLIENT_VERSION_HEADER } from "@eloxiv/contracts"
8
+ import { Zero, type AnyMutatorRegistry, type Schema } from "@rocicorp/zero"
9
+
10
+ export {
11
+ boolean,
12
+ createBuilder,
13
+ createSchema,
14
+ defineQueries,
15
+ defineQueriesWithType,
16
+ defineQuery,
17
+ defineQueryWithType,
18
+ enumeration,
19
+ escapeLike,
20
+ json,
21
+ number,
22
+ relationships,
23
+ string,
24
+ table,
25
+ } from "@rocicorp/zero"
26
+ export type {
27
+ AnyQueryRegistry,
28
+ HumanReadable,
29
+ PullRow,
30
+ Query,
31
+ QueryRequest,
32
+ QueryResultType,
33
+ QueryRowType,
34
+ ReadonlyJSONObject,
35
+ ReadonlyJSONValue,
36
+ Row,
37
+ RunOptions,
38
+ TTL,
39
+ TableSchema,
40
+ } from "@rocicorp/zero"
41
+
42
+ /** An app's sync schema: what `eloxiv.sync.ts` generates (`typeof schema`). */
43
+ export type SyncSchema = Schema
44
+
45
+ /** A replica over the app's sync schema `S`: queries, results and rows are typed by it. */
46
+ export type SyncClient<S extends SyncSchema = SyncSchema> = Zero<S>
47
+
48
+ /**
49
+ * Where the replica lives: `"idb"` (IndexedDB, browsers and webviews), `"mem"` (memory only), or a Zero store
50
+ * provider, such as SQLite on React Native (`expoSQLiteStoreProvider` from `@eloxiv/client/expo-sqlite`).
51
+ */
52
+ export type SyncStorage = NonNullable<ConstructorParameters<typeof Zero>[0]["kvStore"]>
53
+
54
+ export interface SyncOptions<S extends SyncSchema = SyncSchema> {
55
+ /** zero-cache URL, e.g. `http://localhost:4848`. */
56
+ readonly server: string
57
+ /** The app's generated sync schema (`schema` from `eloxiv.sync.ts`). */
58
+ readonly schema: S
59
+ readonly userId: string
60
+ /** Bearer token forwarded by zero-cache to the kernel's query endpoint. */
61
+ readonly token: string
62
+ /**
63
+ * Organisation to sync, as for action calls (`x-eloxiv-org`). The kernel checks
64
+ * membership; each (user, organisation) pair gets its own replica storage.
65
+ */
66
+ readonly orgId?: string | undefined
67
+ /** Replica storage (default memory). Browsers use IndexedDB; React Native uses SQLite (decision 7). */
68
+ readonly storage?: SyncStorage | undefined
69
+ /**
70
+ * The app's mutators (`mutators` from `eloxiv.sync.ts`), for optimistic writes (`write`). A replica that writes
71
+ * names its organisation (`orgId`): its predictions are made for it.
72
+ */
73
+ readonly mutators?: AnyMutatorRegistry | undefined
74
+ /**
75
+ * This client's version (the app build), sent with each pushed write as `x-eloxiv-client-version`, as the typed
76
+ * client sends it: the kernel refuses writes from versions older than its minimum (`ClientOutdated`).
77
+ */
78
+ readonly clientVersion?: string | undefined
79
+ /**
80
+ * Diagnostics: every line the sync engine logs, debug level included, instead of the console's warnings (a test
81
+ * keeps them for its failure report). Off by default.
82
+ */
83
+ readonly log?: ((level: string, ...args: ReadonlyArray<unknown>) => void) | undefined
84
+ }
85
+
86
+ /** Header naming the organisation, forwarded by zero-cache to the kernel's query endpoint. */
87
+ export const ORG_HEADER = "x-eloxiv-org"
88
+
89
+ /** Open the replica of one user in one organisation, typed by the app's schema. */
90
+ export const connectSync = <const S extends SyncSchema>(options: SyncOptions<S>): SyncClient<S> => {
91
+ const orgId = options.orgId
92
+ if (options.mutators !== undefined && orgId === undefined) {
93
+ throw new Error("A replica that writes optimistically names its organisation (connectSync({ orgId }))")
94
+ }
95
+ const headers: Record<string, string> = orgId === undefined ? {} : { [ORG_HEADER]: orgId }
96
+ const mutateHeaders: Record<string, string> =
97
+ options.clientVersion === undefined ? headers : { ...headers, [CLIENT_VERSION_HEADER]: options.clientVersion }
98
+ const zero = new Zero<S>({
99
+ server: options.server,
100
+ schema: options.schema,
101
+ userID: options.userId,
102
+ auth: options.token,
103
+ kvStore: options.storage ?? "mem",
104
+ ...(options.log === undefined
105
+ ? {}
106
+ : {
107
+ logLevel: "debug" as const,
108
+ logSink: { log: (level: string, _context: unknown, ...args: Array<unknown>) => options.log!(level, ...args) },
109
+ }),
110
+ ...(orgId === undefined ? {} : { queryHeaders: headers, storageKey: `org:${orgId}` }),
111
+ // The replica pushes only the person's writes, never anything of its own: a push zero-cache forwards after the
112
+ // session ended is refused for its credential, and zero-cache then drops the connection, before the sign-out's
113
+ // withdrawal of the rows the replica holds could reach it (docs/contracts/sync.md, guarantee 8). Its client group
114
+ // is recorded from its queries' transforms instead (docs/contracts/privacy.md).
115
+ ...(options.mutators === undefined || orgId === undefined
116
+ ? {}
117
+ : {
118
+ mutators: options.mutators,
119
+ mutateHeaders,
120
+ // What each prediction is made for (OptimisticContext): the kernel acts as this user, in this organisation.
121
+ context: { userId: options.userId, orgId },
122
+ }),
123
+ })
124
+ return zero
125
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Kernel-owned sync tables shared by the client and the kernel's query endpoint (`@eloxiv/client/sync`):
3
+ * the sharing grants per-record policies read, and the unified inbox's tables and queries.
4
+ */
5
+ export { shareGrant } from "./ShareGrant.ts"
6
+ export * from "./InboxSync.ts"
7
+ export * from "./PlatformSync.ts"
8
+ export * from "./AgentSync.ts"
9
+ export * from "./SpacesSync.ts"
10
+ export * from "./FileSync.ts"
11
+ export * from "./ServicesSync.ts"
12
+ export * from "./AppStateSync.ts"
package/src/Tab.ts ADDED
@@ -0,0 +1,59 @@
1
+ /**
2
+ * A browser tab's identity (the ClientSDK's `tabIdentity`): one id per tab and app, kept across a reload and a
3
+ * back or forward navigation, new for a new navigation or a new tab. State a tab publishes (app state, its screen)
4
+ * carries it, so the tab can tell its own publications from another tab's and from its agent's commands for it.
5
+ *
6
+ * Runtime-neutral: the host gives the per-tab storage and how the page was reached (`@eloxiv/shell-core/web`'s
7
+ * `webTabEnvironment()` passes `sessionStorage` and the Navigation Timing entry's type in a browser).
8
+ */
9
+
10
+ /** Storage that lives as long as the tab (a browser's `sessionStorage`). */
11
+ export interface TabStorage {
12
+ readonly getItem: (key: string) => string | null
13
+ readonly setItem: (key: string, value: string) => void
14
+ }
15
+
16
+ /** How the page was reached (Navigation Timing's `type`). */
17
+ export type NavigationKind = "navigate" | "reload" | "back_forward" | "prerender"
18
+
19
+ export interface TabEnvironment {
20
+ readonly storage: TabStorage | undefined
21
+ readonly navigation: NavigationKind | undefined
22
+ }
23
+
24
+ /**
25
+ * `length` random bytes as hex: Web Crypto's where the runtime has it (read off `globalThis`: React Native's types do
26
+ * not declare it, though Hermes may provide it), else `Math.random`'s. Ids, never secrets.
27
+ */
28
+ export const randomHex = (length: number) => {
29
+ const bytes = new Uint8Array(length)
30
+ const source = (globalThis as { readonly crypto?: { getRandomValues(array: Uint8Array): Uint8Array } }).crypto
31
+ if (source !== undefined) source.getRandomValues(bytes)
32
+ else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256)
33
+ let id = ""
34
+ for (const byte of bytes) id += byte.toString(16).padStart(2, "0")
35
+ return id
36
+ }
37
+
38
+ const randomId = () => randomHex(16)
39
+
40
+ /**
41
+ * The tab's id for `app`: the one this tab stored, when the page was reloaded or reached by back or forward; a new
42
+ * one, stored, for any other navigation (a link, a typed URL, a new tab). Each
43
+ * app in the same tab has its own. Without storage every call is a new id (the host keeps none). Decide it once per
44
+ * page load and keep it: asked again in the same load after a plain navigation, it would be new.
45
+ */
46
+ export const tabIdentity = (app: string, environment: TabEnvironment): string => {
47
+ const key = `eloxiv.tab.${app}`
48
+ const kept = environment.storage?.getItem(key) ?? null
49
+ const id =
50
+ kept !== null && (environment.navigation === "reload" || environment.navigation === "back_forward")
51
+ ? kept
52
+ : randomId()
53
+ environment.storage?.setItem(key, id)
54
+ return id
55
+ }
56
+
57
+ /** Was this publication made by the tab `tabId` (so the tab ignores its own echo)? */
58
+ export const isOwnPublication = (publication: { readonly tabId?: string | null | undefined }, tabId: string) =>
59
+ publication.tabId === tabId