@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.
- package/LICENSE +21 -0
- package/README.md +6 -2
- package/dist/Account.d.ts +131 -0
- package/dist/Account.d.ts.map +1 -0
- package/dist/Account.js +169 -0
- package/dist/Account.js.map +1 -0
- package/dist/Agent.d.ts +496 -0
- package/dist/Agent.d.ts.map +1 -0
- package/dist/Agent.js +228 -0
- package/dist/Agent.js.map +1 -0
- package/dist/AgentSync.d.ts +990 -0
- package/dist/AgentSync.d.ts.map +1 -0
- package/dist/AgentSync.js +46 -0
- package/dist/AgentSync.js.map +1 -0
- package/dist/AppState.d.ts +127 -0
- package/dist/AppState.d.ts.map +1 -0
- package/dist/AppState.js +145 -0
- package/dist/AppState.js.map +1 -0
- package/dist/AppStateSync.d.ts +193 -0
- package/dist/AppStateSync.d.ts.map +1 -0
- package/dist/AppStateSync.js +23 -0
- package/dist/AppStateSync.js.map +1 -0
- package/dist/Auth.d.ts +95 -0
- package/dist/Auth.d.ts.map +1 -0
- package/dist/Auth.js +139 -0
- package/dist/Auth.js.map +1 -0
- package/dist/Avatars.d.ts +53 -0
- package/dist/Avatars.d.ts.map +1 -0
- package/dist/Avatars.js +121 -0
- package/dist/Avatars.js.map +1 -0
- package/dist/BrowserAnalytics.d.ts +56 -0
- package/dist/BrowserAnalytics.d.ts.map +1 -0
- package/dist/BrowserAnalytics.js +94 -0
- package/dist/BrowserAnalytics.js.map +1 -0
- package/dist/Chat.d.ts +712 -0
- package/dist/Chat.d.ts.map +1 -0
- package/dist/Chat.js +883 -0
- package/dist/Chat.js.map +1 -0
- package/dist/ChatIntegrity.d.ts +63 -0
- package/dist/ChatIntegrity.d.ts.map +1 -0
- package/dist/ChatIntegrity.js +89 -0
- package/dist/ChatIntegrity.js.map +1 -0
- package/dist/ChatSends.d.ts +103 -0
- package/dist/ChatSends.d.ts.map +1 -0
- package/dist/ChatSends.js +157 -0
- package/dist/ChatSends.js.map +1 -0
- package/dist/Client.d.ts +113 -0
- package/dist/Client.d.ts.map +1 -0
- package/dist/Client.js +189 -0
- package/dist/Client.js.map +1 -0
- package/dist/Collab.d.ts +138 -0
- package/dist/Collab.d.ts.map +1 -0
- package/dist/Collab.js +454 -0
- package/dist/Collab.js.map +1 -0
- package/dist/CollabTools.d.ts +129 -0
- package/dist/CollabTools.d.ts.map +1 -0
- package/dist/CollabTools.js +277 -0
- package/dist/CollabTools.js.map +1 -0
- package/dist/Connections.d.ts +288 -0
- package/dist/Connections.d.ts.map +1 -0
- package/dist/Connections.js +316 -0
- package/dist/Connections.js.map +1 -0
- package/dist/Consent.d.ts +338 -0
- package/dist/Consent.d.ts.map +1 -0
- package/dist/Consent.js +142 -0
- package/dist/Consent.js.map +1 -0
- package/dist/Desktop.d.ts +61 -0
- package/dist/Desktop.d.ts.map +1 -0
- package/dist/Desktop.js +101 -0
- package/dist/Desktop.js.map +1 -0
- package/dist/Directory.d.ts +36 -0
- package/dist/Directory.d.ts.map +1 -0
- package/dist/Directory.js +42 -0
- package/dist/Directory.js.map +1 -0
- package/dist/ErrorReporter.d.ts +48 -0
- package/dist/ErrorReporter.d.ts.map +1 -0
- package/dist/ErrorReporter.js +70 -0
- package/dist/ErrorReporter.js.map +1 -0
- package/dist/ExpoSqlite.d.ts +7 -0
- package/dist/ExpoSqlite.d.ts.map +1 -0
- package/dist/ExpoSqlite.js +7 -0
- package/dist/ExpoSqlite.js.map +1 -0
- package/dist/FileSync.d.ts +265 -0
- package/dist/FileSync.d.ts.map +1 -0
- package/dist/FileSync.js +29 -0
- package/dist/FileSync.js.map +1 -0
- package/dist/FileTables.gen.d.ts +109 -0
- package/dist/FileTables.gen.d.ts.map +1 -0
- package/dist/FileTables.gen.js +23 -0
- package/dist/FileTables.gen.js.map +1 -0
- package/dist/Foldkit.d.ts +487 -0
- package/dist/Foldkit.d.ts.map +1 -0
- package/dist/Foldkit.js +617 -0
- package/dist/Foldkit.js.map +1 -0
- package/dist/History.d.ts +133 -0
- package/dist/History.d.ts.map +1 -0
- package/dist/History.js +210 -0
- package/dist/History.js.map +1 -0
- package/dist/InboxSync.d.ts +428 -0
- package/dist/InboxSync.d.ts.map +1 -0
- package/dist/InboxSync.js +37 -0
- package/dist/InboxSync.js.map +1 -0
- package/dist/KernelTables.gen.d.ts +1522 -0
- package/dist/KernelTables.gen.d.ts.map +1 -0
- package/dist/KernelTables.gen.js +307 -0
- package/dist/KernelTables.gen.js.map +1 -0
- package/dist/Make.d.ts +75 -0
- package/dist/Make.d.ts.map +1 -0
- package/dist/Make.js +70 -0
- package/dist/Make.js.map +1 -0
- package/dist/Models.d.ts +88 -0
- package/dist/Models.d.ts.map +1 -0
- package/dist/Models.js +80 -0
- package/dist/Models.js.map +1 -0
- package/dist/Optimistic.d.ts +120 -0
- package/dist/Optimistic.d.ts.map +1 -0
- package/dist/Optimistic.js +231 -0
- package/dist/Optimistic.js.map +1 -0
- package/dist/PlatformSync.d.ts +273 -0
- package/dist/PlatformSync.d.ts.map +1 -0
- package/dist/PlatformSync.js +92 -0
- package/dist/PlatformSync.js.map +1 -0
- package/dist/Poll.d.ts +113 -0
- package/dist/Poll.d.ts.map +1 -0
- package/dist/Poll.js +179 -0
- package/dist/Poll.js.map +1 -0
- package/dist/Preferences.d.ts +18 -0
- package/dist/Preferences.d.ts.map +1 -0
- package/dist/Preferences.js +22 -0
- package/dist/Preferences.js.map +1 -0
- package/dist/Proposals.d.ts +29 -0
- package/dist/Proposals.d.ts.map +1 -0
- package/dist/Proposals.js +41 -0
- package/dist/Proposals.js.map +1 -0
- package/dist/React.d.ts +17 -0
- package/dist/React.d.ts.map +1 -0
- package/dist/React.js +17 -0
- package/dist/React.js.map +1 -0
- package/dist/Reader.d.ts +35 -0
- package/dist/Reader.d.ts.map +1 -0
- package/dist/Reader.js +136 -0
- package/dist/Reader.js.map +1 -0
- package/dist/Resources.d.ts +98 -0
- package/dist/Resources.d.ts.map +1 -0
- package/dist/Resources.js +161 -0
- package/dist/Resources.js.map +1 -0
- package/dist/Rows.d.ts +4 -0
- package/dist/Rows.d.ts.map +1 -0
- package/dist/Rows.js +16 -0
- package/dist/Rows.js.map +1 -0
- package/dist/Runtime.d.ts +254 -0
- package/dist/Runtime.d.ts.map +1 -0
- package/dist/Runtime.js +1249 -0
- package/dist/Runtime.js.map +1 -0
- package/dist/RuntimeRuns.d.ts +74 -0
- package/dist/RuntimeRuns.d.ts.map +1 -0
- package/dist/RuntimeRuns.js +118 -0
- package/dist/RuntimeRuns.js.map +1 -0
- package/dist/ServicesSync.d.ts +286 -0
- package/dist/ServicesSync.d.ts.map +1 -0
- package/dist/ServicesSync.js +40 -0
- package/dist/ServicesSync.js.map +1 -0
- package/dist/Session.d.ts +226 -0
- package/dist/Session.d.ts.map +1 -0
- package/dist/Session.js +763 -0
- package/dist/Session.js.map +1 -0
- package/dist/ShareGrant.d.ts +47 -0
- package/dist/ShareGrant.d.ts.map +1 -0
- package/dist/ShareGrant.js +20 -0
- package/dist/ShareGrant.js.map +1 -0
- package/dist/Sharing.d.ts +203 -0
- package/dist/Sharing.d.ts.map +1 -0
- package/dist/Sharing.js +520 -0
- package/dist/Sharing.js.map +1 -0
- package/dist/Skew.d.ts +52 -0
- package/dist/Skew.d.ts.map +1 -0
- package/dist/Skew.js +77 -0
- package/dist/Skew.js.map +1 -0
- package/dist/SpacesSync.d.ts +247 -0
- package/dist/SpacesSync.d.ts.map +1 -0
- package/dist/SpacesSync.js +30 -0
- package/dist/SpacesSync.js.map +1 -0
- package/dist/Storage.d.ts +51 -0
- package/dist/Storage.d.ts.map +1 -0
- package/dist/Storage.js +107 -0
- package/dist/Storage.js.map +1 -0
- package/dist/Sync.d.ts +48 -0
- package/dist/Sync.d.ts.map +1 -0
- package/dist/Sync.js +48 -0
- package/dist/Sync.js.map +1 -0
- package/dist/SyncTables.d.ts +13 -0
- package/dist/SyncTables.d.ts.map +1 -0
- package/dist/SyncTables.js +13 -0
- package/dist/SyncTables.js.map +1 -0
- package/dist/Tab.d.ts +36 -0
- package/dist/Tab.d.ts.map +1 -0
- package/dist/Tab.js +44 -0
- package/dist/Tab.js.map +1 -0
- package/dist/Transport.d.ts +139 -0
- package/dist/Transport.d.ts.map +1 -0
- package/dist/Transport.js +232 -0
- package/dist/Transport.js.map +1 -0
- package/dist/Upload.d.ts +41 -0
- package/dist/Upload.d.ts.map +1 -0
- package/dist/Upload.js +93 -0
- package/dist/Upload.js.map +1 -0
- package/dist/WebMcp.d.ts +78 -0
- package/dist/WebMcp.d.ts.map +1 -0
- package/dist/WebMcp.js +204 -0
- package/dist/WebMcp.js.map +1 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -0
- package/package.json +97 -3
- package/src/Account.ts +249 -0
- package/src/Agent.ts +387 -0
- package/src/AgentSync.ts +59 -0
- package/src/AppState.ts +222 -0
- package/src/AppStateSync.ts +26 -0
- package/src/Auth.ts +225 -0
- package/src/Avatars.ts +144 -0
- package/src/BrowserAnalytics.ts +133 -0
- package/src/Chat.ts +1150 -0
- package/src/ChatIntegrity.ts +130 -0
- package/src/ChatSends.ts +209 -0
- package/src/Client.ts +319 -0
- package/src/Collab.ts +524 -0
- package/src/CollabTools.ts +381 -0
- package/src/Connections.ts +517 -0
- package/src/Consent.ts +176 -0
- package/src/Desktop.ts +139 -0
- package/src/Directory.ts +71 -0
- package/src/ErrorReporter.ts +112 -0
- package/src/ExpoSqlite.ts +6 -0
- package/src/FileSync.ts +34 -0
- package/src/FileTables.gen.ts +23 -0
- package/src/Foldkit.ts +960 -0
- package/src/History.ts +337 -0
- package/src/InboxSync.ts +47 -0
- package/src/KernelTables.gen.ts +329 -0
- package/src/Make.ts +120 -0
- package/src/Models.ts +134 -0
- package/src/Optimistic.ts +364 -0
- package/src/PlatformSync.ts +156 -0
- package/src/Poll.ts +227 -0
- package/src/Preferences.ts +42 -0
- package/src/Proposals.ts +57 -0
- package/src/React.ts +26 -0
- package/src/Reader.ts +180 -0
- package/src/Resources.ts +257 -0
- package/src/Rows.ts +16 -0
- package/src/Runtime.ts +1409 -0
- package/src/RuntimeRuns.ts +180 -0
- package/src/ServicesSync.ts +58 -0
- package/src/Session.ts +814 -0
- package/src/ShareGrant.ts +20 -0
- package/src/Sharing.ts +696 -0
- package/src/Skew.ts +97 -0
- package/src/SpacesSync.ts +61 -0
- package/src/Storage.ts +167 -0
- package/src/Sync.ts +125 -0
- package/src/SyncTables.ts +12 -0
- package/src/Tab.ts +59 -0
- package/src/Transport.ts +321 -0
- package/src/Upload.ts +125 -0
- package/src/WebMcp.ts +279 -0
- package/src/index.ts +26 -0
- package/src/web-globals.d.ts +103 -0
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optimistic writes through the replica (decision "Data"; the Sync contract's `mutate`). An action that declares
|
|
3
|
+
* an optimistic effect (`optimistic.insert`, `update` or `delete` in its contract) has a mutator, which
|
|
4
|
+
* `eloxiv generate` writes into its module's `sync.gen.ts` and `eloxiv.sync.ts` composes into the app's
|
|
5
|
+
* `mutators`. `write(replica, mutators.hello.greet(input))` applies the prediction to the replica at once and
|
|
6
|
+
* pushes the call; the kernel runs it as the action, through the one invocation path, and the replica replaces the
|
|
7
|
+
* prediction with the server's rows, or drops it when the call is refused. Modules and UI reach this only here
|
|
8
|
+
* (decision 9): Zero's mutator API is not theirs to import.
|
|
9
|
+
*
|
|
10
|
+
* An action that declares `optimistic.custom()` is predicted by its module's own code (`predictions.ts`, a
|
|
11
|
+
* `Prediction` named like the action), which `eloxiv generate` wires in with `definePredictionWithType`: it runs
|
|
12
|
+
* only on the replica, may write only the tables of the entities the action declares, and a prediction that throws
|
|
13
|
+
* or writes another table predicts nothing and sends nothing (the write rejects with `ActionFailed`).
|
|
14
|
+
*/
|
|
15
|
+
import {
|
|
16
|
+
ApplicationError,
|
|
17
|
+
createBuilder,
|
|
18
|
+
defineMutator,
|
|
19
|
+
defineMutators as defineZeroMutators,
|
|
20
|
+
type AnyMutatorRegistry,
|
|
21
|
+
type MutatorDefinition,
|
|
22
|
+
type MutatorDefinitions,
|
|
23
|
+
type MutatorRegistry,
|
|
24
|
+
type MutateRequest,
|
|
25
|
+
type Schema as ZeroSchema,
|
|
26
|
+
type SchemaQuery,
|
|
27
|
+
type Transaction,
|
|
28
|
+
type Zero,
|
|
29
|
+
} from "@rocicorp/zero"
|
|
30
|
+
import {
|
|
31
|
+
ActionFailed,
|
|
32
|
+
InvalidInput,
|
|
33
|
+
InvocationError,
|
|
34
|
+
isRecordKeyNonce,
|
|
35
|
+
newRecordKeyNonce,
|
|
36
|
+
recordKey,
|
|
37
|
+
type AnyAction,
|
|
38
|
+
} from "@eloxiv/contracts"
|
|
39
|
+
import { Exit, Schema } from "effect"
|
|
40
|
+
|
|
41
|
+
export { recordKey }
|
|
42
|
+
|
|
43
|
+
/** What a prediction knows of the replica it runs on: whose it is and the organisation it acts in. */
|
|
44
|
+
export interface OptimisticContext {
|
|
45
|
+
readonly userId: string
|
|
46
|
+
readonly orgId: string
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The action input a mutator takes: the action's input as it travels (encoded). */
|
|
50
|
+
export type OptimisticInput<A extends AnyAction> = Schema.Codec.Encoded<A["input"]>
|
|
51
|
+
|
|
52
|
+
/** What `write` knows of a mutator: the action it predicts and the input field naming a new record's key. */
|
|
53
|
+
interface OptimisticMeta {
|
|
54
|
+
readonly action: AnyAction
|
|
55
|
+
readonly key: string | undefined
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const META = Symbol.for("@eloxiv/client/optimistic")
|
|
59
|
+
|
|
60
|
+
type Predict<S extends ZeroSchema, A extends AnyAction> = (options: {
|
|
61
|
+
readonly tx: Transaction<S>
|
|
62
|
+
readonly args: OptimisticInput<A>
|
|
63
|
+
readonly ctx: OptimisticContext
|
|
64
|
+
}) => Promise<void>
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* For generated code (`sync.gen.ts`): `defineOptimisticWithType<typeof schema>()(action, predict)` is the mutator of
|
|
68
|
+
* `action`, predicting its effect with `predict` over the module's own sync schema.
|
|
69
|
+
*/
|
|
70
|
+
export const defineOptimisticWithType =
|
|
71
|
+
<S extends ZeroSchema>() =>
|
|
72
|
+
<A extends AnyAction>(
|
|
73
|
+
action: A,
|
|
74
|
+
predict: Predict<S, A>,
|
|
75
|
+
): MutatorDefinition<OptimisticInput<A> & ({} | undefined), OptimisticInput<A> & ({} | undefined), any, any> => {
|
|
76
|
+
const definition = defineMutator(async ({ tx, args, ctx }: { tx: Transaction<S>; args: any; ctx: any }) => {
|
|
77
|
+
await predict({ tx, args, ctx: contextOf(ctx) })
|
|
78
|
+
}) as any
|
|
79
|
+
const meta: OptimisticMeta = {
|
|
80
|
+
action,
|
|
81
|
+
key: action.optimistic?.kind === "insert" ? action.optimistic.key : undefined,
|
|
82
|
+
}
|
|
83
|
+
Object.defineProperty(definition, META, { value: meta })
|
|
84
|
+
return definition
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const contextOf = (ctx: unknown): OptimisticContext => {
|
|
88
|
+
const c = ctx as Partial<OptimisticContext> | undefined
|
|
89
|
+
if (typeof c?.userId !== "string" || typeof c.orgId !== "string") {
|
|
90
|
+
throw new Error("An optimistic write needs a replica that names its user and organisation (connectSync)")
|
|
91
|
+
}
|
|
92
|
+
return { userId: c.userId, orgId: c.orgId }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** For generated code: the primary key a predicted insert gives its record (the kernel derives the same one). */
|
|
96
|
+
export const predictedKey = (ctx: OptimisticContext, cedarType: string, named: unknown): string => {
|
|
97
|
+
if (!isRecordKeyNonce(named)) throw new Error("A predicted insert needs the key write() names for it")
|
|
98
|
+
return recordKey(ctx, cedarType, named)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** For generated code: an action's target ids (its target field holds one id or a list). */
|
|
102
|
+
export const targetIds = <T>(value: T | ReadonlyArray<T>): ReadonlyArray<T> =>
|
|
103
|
+
Array.isArray(value) ? (value as ReadonlyArray<T>) : [value as T]
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* For generated code: the time a prediction records, as sync carries instants (epoch milliseconds). The same for
|
|
107
|
+
* every time Zero applies the prediction in this process (it applies it again, on top of each change from the
|
|
108
|
+
* server, until the server answers), so a predicted record does not move.
|
|
109
|
+
*/
|
|
110
|
+
const predictedTimes = new Map<string, number>()
|
|
111
|
+
export const predictedNow = (tx: { readonly clientID: string; readonly mutationID: number }): number => {
|
|
112
|
+
const key = `${tx.clientID}\u0000${tx.mutationID}`
|
|
113
|
+
const known = predictedTimes.get(key)
|
|
114
|
+
if (known !== undefined) return known
|
|
115
|
+
const now = Date.now()
|
|
116
|
+
if (predictedTimes.size > 1_000) predictedTimes.clear()
|
|
117
|
+
predictedTimes.set(key, now)
|
|
118
|
+
return now
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** What a custom prediction knows of the replica it runs on, with what it needs to predict deterministically. */
|
|
122
|
+
export interface PredictionContext extends OptimisticContext {
|
|
123
|
+
/**
|
|
124
|
+
* Now, in epoch milliseconds, as sync carries instants: the same every time Zero applies this prediction again
|
|
125
|
+
* (it does, on top of each change from the server, until the server answers).
|
|
126
|
+
*/
|
|
127
|
+
readonly now: () => number
|
|
128
|
+
/** The primary key the kernel derives (`recordKey`) for a record of `cedarType` from a key the caller named. */
|
|
129
|
+
readonly recordKey: (cedarType: string, named: unknown) => string
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The replica as a custom prediction sees it: it reads any rows the replica holds (`run`, with `zql`), and writes
|
|
134
|
+
* only the tables `T` of the entities its action declares (`mutate`). Writing any other table refuses the write.
|
|
135
|
+
*/
|
|
136
|
+
export interface PredictionTransaction<S extends ZeroSchema, T extends keyof S["tables"] & string> {
|
|
137
|
+
readonly mutate: Pick<Transaction<S>["mutate"], T>
|
|
138
|
+
readonly run: Transaction<S>["run"]
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* A module's own prediction of an action that declares `optimistic.custom()`, exported from its `predictions.ts`
|
|
143
|
+
* under the action's local name and typed there by the generated `Predictions` (`sync.gen.ts`): the action's
|
|
144
|
+
* encoded input (`args`), the replica's user and organisation (`ctx`), the module's query builder (`zql`), and the
|
|
145
|
+
* tables it may write (`tx.mutate`). It runs only on the client's replica, never on the server, and may run more
|
|
146
|
+
* than once (once when written, again on each rebase): it must derive what it writes from these alone.
|
|
147
|
+
*/
|
|
148
|
+
export type Prediction<S extends ZeroSchema, A extends AnyAction, T extends keyof S["tables"] & string> = (options: {
|
|
149
|
+
readonly tx: PredictionTransaction<S, T>
|
|
150
|
+
readonly args: OptimisticInput<A>
|
|
151
|
+
readonly ctx: PredictionContext
|
|
152
|
+
readonly zql: SchemaQuery<S>
|
|
153
|
+
}) => Promise<void> | void
|
|
154
|
+
|
|
155
|
+
/** A custom prediction was refused: it threw, or wrote a table its action does not declare. */
|
|
156
|
+
class PredictionRefused extends Error {
|
|
157
|
+
override readonly name = "PredictionRefused"
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const encodeActionFailed = Schema.encodeUnknownSync(ActionFailed)
|
|
161
|
+
/** The error Zero reports for a refused prediction: the write's two promises reject with `ActionFailed`. */
|
|
162
|
+
const predictionFailure = (action: AnyAction, error: unknown): ApplicationError => {
|
|
163
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
164
|
+
const message = `Custom prediction for ${action.name} failed; nothing was applied or sent: ${reason}`
|
|
165
|
+
return new ApplicationError(message, {
|
|
166
|
+
cause: error,
|
|
167
|
+
details: encodeActionFailed(new ActionFailed({ action: action.name, message })) as never,
|
|
168
|
+
})
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* For generated code (`sync.gen.ts`): `definePredictionWithType(schema)(action, tables, prediction)` is the mutator
|
|
173
|
+
* of an action that declares `optimistic.custom()`, predicting with the module's own `prediction` over the module's
|
|
174
|
+
* sync `schema`, writing only `tables` (the synced tables of the entities the action declares). Refused at once
|
|
175
|
+
* when the action does not declare a custom prediction, no prediction is given, or a table is not the schema's.
|
|
176
|
+
*/
|
|
177
|
+
export const definePredictionWithType =
|
|
178
|
+
<S extends ZeroSchema>(schema: S) =>
|
|
179
|
+
<A extends AnyAction, const T extends keyof S["tables"] & string>(
|
|
180
|
+
action: A,
|
|
181
|
+
tables: ReadonlyArray<T>,
|
|
182
|
+
prediction: Prediction<S, A, T>,
|
|
183
|
+
): MutatorDefinition<OptimisticInput<A> & ({} | undefined), OptimisticInput<A> & ({} | undefined), any, any> => {
|
|
184
|
+
if (action.optimistic?.kind !== "custom") {
|
|
185
|
+
throw new Error(`${action.name} does not declare a custom prediction (optimistic.custom())`)
|
|
186
|
+
}
|
|
187
|
+
if (typeof prediction !== "function") {
|
|
188
|
+
throw new Error(
|
|
189
|
+
`${action.name} declares a custom prediction (optimistic.custom()), but its module's predictions.ts exports none for it`,
|
|
190
|
+
)
|
|
191
|
+
}
|
|
192
|
+
if (tables.length === 0) throw new Error(`${action.name}'s prediction may write no table`)
|
|
193
|
+
for (const table of tables) {
|
|
194
|
+
if (!Object.hasOwn(schema.tables, table)) throw new Error(`${action.name} predicts ${table}, not a table here`)
|
|
195
|
+
}
|
|
196
|
+
const allowed: ReadonlySet<string> = new Set(tables)
|
|
197
|
+
const zql = createBuilder(schema)
|
|
198
|
+
const definition = defineMutator(async ({ tx, args, ctx }: { tx: Transaction<S>; args: any; ctx: any }) => {
|
|
199
|
+
const context = contextOf(ctx)
|
|
200
|
+
// Only the declared tables; anything else (another table, a symbol, the whole object's keys) refuses the write.
|
|
201
|
+
const mutate = new Proxy(Object.create(null) as object, {
|
|
202
|
+
get: (_, table) => {
|
|
203
|
+
if (typeof table === "string" && allowed.has(table)) return (tx.mutate as Record<string, unknown>)[table]
|
|
204
|
+
throw new PredictionRefused(
|
|
205
|
+
`attempted to write table ${String(table)}, which ${action.name} does not declare (allowed: ${[...allowed].join(", ")})`,
|
|
206
|
+
)
|
|
207
|
+
},
|
|
208
|
+
set: () => false,
|
|
209
|
+
defineProperty: () => false,
|
|
210
|
+
ownKeys: () => [],
|
|
211
|
+
})
|
|
212
|
+
const run: Transaction<S>["run"] = (query, options) => tx.run(query, options)
|
|
213
|
+
const scoped: PredictionTransaction<S, T> = Object.freeze({
|
|
214
|
+
mutate: mutate as PredictionTransaction<S, T>["mutate"],
|
|
215
|
+
run,
|
|
216
|
+
})
|
|
217
|
+
const predicting: PredictionContext = Object.freeze({
|
|
218
|
+
userId: context.userId,
|
|
219
|
+
orgId: context.orgId,
|
|
220
|
+
now: () => predictedNow(tx),
|
|
221
|
+
recordKey: (cedarType: string, named: unknown) => predictedKey(context, cedarType, named),
|
|
222
|
+
})
|
|
223
|
+
try {
|
|
224
|
+
await prediction({ tx: scoped, args, ctx: predicting, zql })
|
|
225
|
+
} catch (error) {
|
|
226
|
+
// Zero rolls the replica's transaction back: nothing of the prediction stays, and a first run sends nothing.
|
|
227
|
+
throw predictionFailure(action, error)
|
|
228
|
+
}
|
|
229
|
+
}) as any
|
|
230
|
+
Object.defineProperty(definition, META, { value: { action, key: undefined } satisfies OptimisticMeta })
|
|
231
|
+
return definition
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** A module's generated sync file (its namespace), which exports `mutators` when it has optimistic writes. */
|
|
235
|
+
type ModuleMutators = object
|
|
236
|
+
type MutatorsOf<M> = M extends { readonly mutators: infer T } ? T : {}
|
|
237
|
+
/** Every module's mutators together (each module's sit under its own name: action names are namespaced). */
|
|
238
|
+
type MergeAll<Ms extends ReadonlyArray<unknown>> = Ms extends readonly [infer First, ...infer Rest]
|
|
239
|
+
? MutatorsOf<First> & MergeAll<Rest>
|
|
240
|
+
: {}
|
|
241
|
+
type Definitions<T> = T extends MutatorDefinitions ? T : never
|
|
242
|
+
|
|
243
|
+
const merge = (into: Record<string, unknown>, from: Readonly<Record<string, unknown>>) => {
|
|
244
|
+
for (const [name, value] of Object.entries(from)) {
|
|
245
|
+
const existing = into[name]
|
|
246
|
+
if (existing === undefined) {
|
|
247
|
+
into[name] = value
|
|
248
|
+
} else if (isPlain(existing) && isPlain(value) && !isDefinition(existing) && !isDefinition(value)) {
|
|
249
|
+
const nested = { ...existing }
|
|
250
|
+
merge(nested, value)
|
|
251
|
+
into[name] = nested
|
|
252
|
+
} else {
|
|
253
|
+
throw new Error(`Two modules define the mutator ${name}`)
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const isPlain = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null
|
|
258
|
+
const isDefinition = (value: unknown) => isPlain(value) && value["~"] === "MutatorDefinition"
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* For the app's composition (`eloxiv.sync.ts`): every installed module's mutators (each `sync.gen.ts`'s
|
|
262
|
+
* `mutators`, named by action) as one registry over the app's schema `S`, for `connectSync({ mutators })` and
|
|
263
|
+
* `write`.
|
|
264
|
+
*/
|
|
265
|
+
export const defineMutators =
|
|
266
|
+
<S extends ZeroSchema>() =>
|
|
267
|
+
<const Ms extends ReadonlyArray<ModuleMutators>>(...modules: Ms) => {
|
|
268
|
+
const definitions: Record<string, unknown> = {}
|
|
269
|
+
for (const module of modules) {
|
|
270
|
+
merge(definitions, (module as { readonly mutators?: Readonly<Record<string, unknown>> }).mutators ?? {})
|
|
271
|
+
}
|
|
272
|
+
const registry = defineZeroMutators(definitions as never) as unknown as Record<string, unknown>
|
|
273
|
+
// Each mutator keeps what `write` needs of its definition.
|
|
274
|
+
const attach = (defs: Readonly<Record<string, unknown>>, mutators: Record<string, unknown>) => {
|
|
275
|
+
for (const [name, value] of Object.entries(defs)) {
|
|
276
|
+
if (isDefinition(value)) {
|
|
277
|
+
const meta = (value as { [META]?: OptimisticMeta })[META]
|
|
278
|
+
if (meta !== undefined) Object.defineProperty(mutators[name] as object, META, { value: meta })
|
|
279
|
+
} else if (isPlain(value)) {
|
|
280
|
+
attach(value, mutators[name] as Record<string, unknown>)
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
attach(definitions, registry)
|
|
285
|
+
return registry as unknown as MutatorRegistry<Definitions<MergeAll<Ms>>, S>
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** The server did not confirm the write: the replica is offline or closed, or Zero failed it. It may still run. */
|
|
289
|
+
export class WriteNotConfirmed extends Error {
|
|
290
|
+
override readonly name = "WriteNotConfirmed"
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** An optimistic write: the prediction applied to the replica, and the server's answer. */
|
|
294
|
+
export interface OptimisticWrite {
|
|
295
|
+
/** Resolves once the prediction is in the replica (rejects if it could not be applied). */
|
|
296
|
+
readonly client: Promise<void>
|
|
297
|
+
/**
|
|
298
|
+
* Resolves once the server ran the action and the replica holds its rows; rejects with the invocation's error
|
|
299
|
+
* (`Forbidden`, `InvalidInput`, `ApprovalRequired` with its `approvalId`, `ConsentRequired` with its `consentId`,
|
|
300
|
+
* `ActionFailed`, ...), when the replica has already dropped the prediction; or with `WriteNotConfirmed`.
|
|
301
|
+
*/
|
|
302
|
+
readonly server: Promise<void>
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
type Details =
|
|
306
|
+
| { readonly type: "success" }
|
|
307
|
+
| {
|
|
308
|
+
readonly type: "error"
|
|
309
|
+
readonly error:
|
|
310
|
+
| { readonly type: "app"; readonly message: string; readonly details: unknown }
|
|
311
|
+
| { readonly type: "zero"; readonly message: string }
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const decodeError = Schema.decodeUnknownExit(InvocationError)
|
|
315
|
+
|
|
316
|
+
const settle = (action: string, result: Promise<Details>): Promise<void> => {
|
|
317
|
+
const settled = result.then((details) => {
|
|
318
|
+
if (details.type === "success") return undefined
|
|
319
|
+
const error = details.error
|
|
320
|
+
if (error.type === "zero") throw new WriteNotConfirmed(error.message)
|
|
321
|
+
const decoded = decodeError(error.details)
|
|
322
|
+
if (Exit.isSuccess(decoded)) throw decoded.value
|
|
323
|
+
throw new ActionFailed({ action, message: error.message })
|
|
324
|
+
})
|
|
325
|
+
// A caller may await only one of the two; the other must not surface as an unhandled rejection.
|
|
326
|
+
settled.catch(() => undefined)
|
|
327
|
+
return settled
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const refusedAt = (refusal: InvocationError): OptimisticWrite => {
|
|
331
|
+
const rejected = Promise.reject(refusal)
|
|
332
|
+
rejected.catch(() => undefined)
|
|
333
|
+
return { client: rejected, server: rejected }
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Write optimistically: `write(replica, mutators.hello.greet({ message }))`. The input is checked against the
|
|
338
|
+
* action's input schema first (an invalid one is refused with `InvalidInput`, and nothing is predicted or sent);
|
|
339
|
+
* an insert's record key is named here when the caller leaves it out, so the prediction and the server's record
|
|
340
|
+
* share their primary key.
|
|
341
|
+
*/
|
|
342
|
+
export const write = (replica: Zero<any, any, any>, request: MutateRequest<any, any, any, any>): OptimisticWrite => {
|
|
343
|
+
const meta = (request.mutator as { [META]?: OptimisticMeta })[META]
|
|
344
|
+
if (meta === undefined) {
|
|
345
|
+
throw new Error(`${request.mutator.mutatorName} is not an optimistic mutator (defineMutators from eloxiv.sync.ts)`)
|
|
346
|
+
}
|
|
347
|
+
const input = request.args as Readonly<Record<string, unknown>> | undefined
|
|
348
|
+
const checked = Schema.decodeUnknownExit(meta.action.input as Schema.Codec<unknown, unknown>)(input)
|
|
349
|
+
if (Exit.isFailure(checked)) {
|
|
350
|
+
return refusedAt(new InvalidInput({ message: `Invalid input for ${meta.action.name}: ${String(checked.cause)}` }))
|
|
351
|
+
}
|
|
352
|
+
const args =
|
|
353
|
+
meta.key !== undefined && input?.[meta.key] === undefined ? { ...input, [meta.key]: newRecordKeyNonce() } : input
|
|
354
|
+
const again = request.mutator as unknown as (args: unknown) => MutateRequest<any, any, any, any>
|
|
355
|
+
const result = replica.mutate(again(args)) as unknown as {
|
|
356
|
+
readonly client: Promise<Details>
|
|
357
|
+
readonly server: Promise<Details>
|
|
358
|
+
}
|
|
359
|
+
return { client: settle(meta.action.name, result.client), server: settle(meta.action.name, result.server) }
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** Whether `registry` is the app's mutators (its leaves carry what `write` needs). */
|
|
363
|
+
export const isOptimisticRegistry = (registry: unknown): registry is AnyMutatorRegistry =>
|
|
364
|
+
isPlain(registry) && registry["~"] === "MutatorRegistry"
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Settings and feature flags in each person's replica (the Settings and Flags contracts): the kernel-provided
|
|
3
|
+
* `settings` and `flags` modules' synced tables (generated from their Drizzle tables, `KernelTables.gen.ts`) and
|
|
4
|
+
* named queries, and the functions that read them locally the way the kernel does. An app that installs those
|
|
5
|
+
* modules adds `platformTables` and `platformQueries` to its sync schema.
|
|
6
|
+
*
|
|
7
|
+
* The kernel filters every query by the entity's read policy, in the organisation the replica acts in:
|
|
8
|
+
* - settings: the person's own user-level values and the organisation's values, one key per query (reads are
|
|
9
|
+
* keyed; nothing lists settings);
|
|
10
|
+
* - flags: the rules that can apply to the person (the organisation's, rollouts, role rules, rules about them
|
|
11
|
+
* and rules of the groups they are in; leaving a group takes its rules off the replica).
|
|
12
|
+
*/
|
|
13
|
+
import {
|
|
14
|
+
ChecklistState,
|
|
15
|
+
evaluateFlag,
|
|
16
|
+
type Checklist,
|
|
17
|
+
resolveSetting,
|
|
18
|
+
type FlagReason,
|
|
19
|
+
type ResolvedSetting,
|
|
20
|
+
type SettingLevel,
|
|
21
|
+
type SettingScope,
|
|
22
|
+
} from "@eloxiv/contracts"
|
|
23
|
+
import { createBuilder, createSchema, defineQueryWithType } from "@rocicorp/zero"
|
|
24
|
+
import { Exit, Schema } from "effect"
|
|
25
|
+
import { flagRuleTable, settingValueTable } from "./KernelTables.gen.ts"
|
|
26
|
+
|
|
27
|
+
export { flagRuleTable, settingValueTable }
|
|
28
|
+
|
|
29
|
+
export const platformTables = [settingValueTable, flagRuleTable] as const
|
|
30
|
+
|
|
31
|
+
const localSchema = createSchema({ tables: [settingValueTable, flagRuleTable] })
|
|
32
|
+
const zql = createBuilder(localSchema)
|
|
33
|
+
const defineQuery = defineQueryWithType<typeof localSchema>()
|
|
34
|
+
|
|
35
|
+
/** Named queries, namespaced like a module's (`settings.value`, `flags.mine`). */
|
|
36
|
+
export const platformQueries = {
|
|
37
|
+
settings: {
|
|
38
|
+
/** One setting's values for you: yours and your organisation's (the kernel adds the filter). */
|
|
39
|
+
value: defineQuery(({ args }: { args: string }) => zql.settingValue.where("key", args).limit(2)),
|
|
40
|
+
},
|
|
41
|
+
flags: {
|
|
42
|
+
/**
|
|
43
|
+
* Every targeting rule that can apply to you, for every flag. Unbounded on purpose: a client that held only
|
|
44
|
+
* some of them would evaluate a flag differently from the kernel without knowing it. The rules are few (per
|
|
45
|
+
* flag: the organisation's, a rollout, role rules, the rule about you and your groups' rules).
|
|
46
|
+
*/
|
|
47
|
+
mine: defineQuery(() => zql.flagRule),
|
|
48
|
+
},
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** A setting's stored value: `{ v: <encoded value> }`, or null once cleared (any other JSON is not a value). */
|
|
52
|
+
type SettingRow = { readonly level: string; readonly value?: unknown }
|
|
53
|
+
const storedValue = (value: unknown): { readonly v: unknown } | undefined =>
|
|
54
|
+
typeof value === "object" && value !== null && !Array.isArray(value) && "v" in value ? value : undefined
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* A setting's value from the replica's rows for its key (`settings.value`), resolved as the kernel resolves
|
|
58
|
+
* it: your own value, your organisation's, then `deployment` (app- and module-level values, which are
|
|
59
|
+
* configuration and not in the replica; read them once with `settings.get` if the app sets any), then the
|
|
60
|
+
* default. As in the kernel, a value that no longer decodes against the setting's schema (a module changed the
|
|
61
|
+
* schema) is skipped and the next level applies.
|
|
62
|
+
*/
|
|
63
|
+
export const settingFromReplica = (
|
|
64
|
+
declaration: { readonly scope: SettingScope; readonly default: unknown; readonly schema: Schema.Top },
|
|
65
|
+
rows: ReadonlyArray<SettingRow>,
|
|
66
|
+
deployment: Partial<Readonly<Record<"app" | "module", unknown>>> = {},
|
|
67
|
+
): ResolvedSetting => {
|
|
68
|
+
const values: Partial<Record<SettingLevel, unknown>> = { ...deployment }
|
|
69
|
+
for (const row of rows) {
|
|
70
|
+
const stored = storedValue(row.value)
|
|
71
|
+
if ((row.level === "user" || row.level === "org") && stored !== undefined) {
|
|
72
|
+
values[row.level] = stored.v
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const decode = Schema.decodeUnknownExit(declaration.schema as Schema.Codec<unknown, unknown>)
|
|
76
|
+
for (const [level, value] of Object.entries(values) as Array<[SettingLevel, unknown]>) {
|
|
77
|
+
if (value === undefined || Exit.isFailure(decode(value))) delete values[level]
|
|
78
|
+
}
|
|
79
|
+
return resolveSetting(declaration, values)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
type RuleRow = {
|
|
83
|
+
readonly flag: string
|
|
84
|
+
readonly kind: string
|
|
85
|
+
readonly subject?: string | null | undefined
|
|
86
|
+
readonly enabled: boolean
|
|
87
|
+
readonly percentage?: number | null | undefined
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* A flag for you from the replica's rules (`flags.mine`), evaluated with the kernel's function: the replica
|
|
92
|
+
* holds only the rules about you and your groups, so group rules apply as given; role rules apply for the
|
|
93
|
+
* roles you hold (`roles`, from `GET /api/me/organizations`).
|
|
94
|
+
*/
|
|
95
|
+
export const flagFromReplica = (
|
|
96
|
+
flag: string,
|
|
97
|
+
declaration: { readonly default: boolean },
|
|
98
|
+
rows: ReadonlyArray<RuleRow>,
|
|
99
|
+
subject: { readonly userId: string; readonly roles: ReadonlyArray<string> },
|
|
100
|
+
): { readonly enabled: boolean; readonly reason: FlagReason } =>
|
|
101
|
+
evaluateFlag(
|
|
102
|
+
flag,
|
|
103
|
+
declaration,
|
|
104
|
+
rows.map((r) => ({
|
|
105
|
+
flag: r.flag,
|
|
106
|
+
kind: r.kind as "user" | "group" | "role" | "org" | "rollout",
|
|
107
|
+
subject: r.subject ?? null,
|
|
108
|
+
enabled: r.enabled,
|
|
109
|
+
percentage: r.percentage ?? null,
|
|
110
|
+
})),
|
|
111
|
+
{ userId: subject.userId, roles: subject.roles, groups: "given" },
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* A setup checklist's state from the replica's rows for its key (`settings.value`, the checklist's setting), resolved
|
|
116
|
+
* as `settingFromReplica` resolves any setting: for a `user` checklist, the person's own progress, else what their
|
|
117
|
+
* organisation set, else nothing done. Feed it to `checklistSummary`; write the next state with `settings.set`
|
|
118
|
+
* (`checklistWrite`).
|
|
119
|
+
*/
|
|
120
|
+
export const checklistFromReplica = (checklist: Checklist, rows: ReadonlyArray<SettingRow>): ChecklistState =>
|
|
121
|
+
Schema.decodeUnknownSync(ChecklistState)(settingFromReplica(checklist.setting, rows).value)
|
|
122
|
+
|
|
123
|
+
/** Where a flag's rules are: still arriving, unreadable (with why), or in the replica. */
|
|
124
|
+
export type FlagRules =
|
|
125
|
+
| { readonly state: "loading" }
|
|
126
|
+
| { readonly state: "unavailable"; readonly reason: string }
|
|
127
|
+
| { readonly state: "settled"; readonly rows: ReadonlyArray<RuleRow> }
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* A flag's state for a UI, each case its own: `loading` (the rules or the person's roles have not arrived),
|
|
131
|
+
* `unavailable` (the rules cannot be read: the replica failed or is closed), `unregistered` (no installed module
|
|
132
|
+
* declares the flag), or `on` / `off` with the kernel's reason. Only `on` is on (`isFlagOn`): every other state
|
|
133
|
+
* fails closed, and a UI can still tell "still loading" from "off" from "broken".
|
|
134
|
+
*/
|
|
135
|
+
export type FlagStatus =
|
|
136
|
+
| { readonly status: "loading" }
|
|
137
|
+
| { readonly status: "unavailable"; readonly reason: string }
|
|
138
|
+
| { readonly status: "unregistered" }
|
|
139
|
+
| { readonly status: "on" | "off"; readonly reason: FlagReason }
|
|
140
|
+
|
|
141
|
+
export const flagStatus = (
|
|
142
|
+
flag: string,
|
|
143
|
+
declarations: Readonly<Record<string, { readonly default: boolean }>>,
|
|
144
|
+
rules: FlagRules,
|
|
145
|
+
subject: { readonly userId: string; readonly roles: ReadonlyArray<string> } | undefined,
|
|
146
|
+
): FlagStatus => {
|
|
147
|
+
const declaration = declarations[flag]
|
|
148
|
+
if (declaration === undefined) return { status: "unregistered" }
|
|
149
|
+
if (rules.state === "unavailable") return { status: "unavailable", reason: rules.reason }
|
|
150
|
+
if (rules.state === "loading" || subject === undefined) return { status: "loading" }
|
|
151
|
+
const evaluated = flagFromReplica(flag, declaration, rules.rows, subject)
|
|
152
|
+
return { status: evaluated.enabled ? "on" : "off", reason: evaluated.reason }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Is the flag on? Only a settled `on` is; loading, unavailable and unregistered are off (fail closed). */
|
|
156
|
+
export const isFlagOn = (status: FlagStatus): boolean => status.status === "on"
|