@eloxiv/cli 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 (294) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/AgentSkills.d.ts +51 -0
  4. package/dist/AgentSkills.d.ts.map +1 -0
  5. package/dist/AgentSkills.js +264 -0
  6. package/dist/AgentSkills.js.map +1 -0
  7. package/dist/AgentWeb.d.ts +83 -0
  8. package/dist/AgentWeb.d.ts.map +1 -0
  9. package/dist/AgentWeb.js +436 -0
  10. package/dist/AgentWeb.js.map +1 -0
  11. package/dist/App.d.ts +213 -0
  12. package/dist/App.d.ts.map +1 -0
  13. package/dist/App.js +357 -0
  14. package/dist/App.js.map +1 -0
  15. package/dist/Blueprint.d.ts +47 -0
  16. package/dist/Blueprint.d.ts.map +1 -0
  17. package/dist/Blueprint.js +241 -0
  18. package/dist/Blueprint.js.map +1 -0
  19. package/dist/Brand.d.ts +42 -0
  20. package/dist/Brand.d.ts.map +1 -0
  21. package/dist/Brand.js +370 -0
  22. package/dist/Brand.js.map +1 -0
  23. package/dist/Changelog.d.ts +22 -0
  24. package/dist/Changelog.d.ts.map +1 -0
  25. package/dist/Changelog.js +117 -0
  26. package/dist/Changelog.js.map +1 -0
  27. package/dist/Cli.d.ts +17 -0
  28. package/dist/Cli.d.ts.map +1 -0
  29. package/dist/Cli.js +810 -0
  30. package/dist/Cli.js.map +1 -0
  31. package/dist/DbAdmin.d.ts +18 -0
  32. package/dist/DbAdmin.d.ts.map +1 -0
  33. package/dist/DbAdmin.js +91 -0
  34. package/dist/DbAdmin.js.map +1 -0
  35. package/dist/Dependencies.d.ts +53 -0
  36. package/dist/Dependencies.d.ts.map +1 -0
  37. package/dist/Dependencies.js +132 -0
  38. package/dist/Dependencies.js.map +1 -0
  39. package/dist/Deploy.d.ts +39 -0
  40. package/dist/Deploy.d.ts.map +1 -0
  41. package/dist/Deploy.js +458 -0
  42. package/dist/Deploy.js.map +1 -0
  43. package/dist/Docs.d.ts +71 -0
  44. package/dist/Docs.d.ts.map +1 -0
  45. package/dist/Docs.js +240 -0
  46. package/dist/Docs.js.map +1 -0
  47. package/dist/Doctor.d.ts +56 -0
  48. package/dist/Doctor.d.ts.map +1 -0
  49. package/dist/Doctor.js +368 -0
  50. package/dist/Doctor.js.map +1 -0
  51. package/dist/Dossier.d.ts +23 -0
  52. package/dist/Dossier.d.ts.map +1 -0
  53. package/dist/Dossier.js +92 -0
  54. package/dist/Dossier.js.map +1 -0
  55. package/dist/Emit.d.ts +26 -0
  56. package/dist/Emit.d.ts.map +1 -0
  57. package/dist/Emit.js +51 -0
  58. package/dist/Emit.js.map +1 -0
  59. package/dist/Errors.d.ts +26 -0
  60. package/dist/Errors.d.ts.map +1 -0
  61. package/dist/Errors.js +17 -0
  62. package/dist/Errors.js.map +1 -0
  63. package/dist/Evals.d.ts +52 -0
  64. package/dist/Evals.d.ts.map +1 -0
  65. package/dist/Evals.js +126 -0
  66. package/dist/Evals.js.map +1 -0
  67. package/dist/Files.d.ts +47 -0
  68. package/dist/Files.d.ts.map +1 -0
  69. package/dist/Files.js +145 -0
  70. package/dist/Files.js.map +1 -0
  71. package/dist/Generate.d.ts +80 -0
  72. package/dist/Generate.d.ts.map +1 -0
  73. package/dist/Generate.js +310 -0
  74. package/dist/Generate.js.map +1 -0
  75. package/dist/Guards.d.ts +45 -0
  76. package/dist/Guards.d.ts.map +1 -0
  77. package/dist/Guards.js +530 -0
  78. package/dist/Guards.js.map +1 -0
  79. package/dist/Inspect.d.ts +125 -0
  80. package/dist/Inspect.d.ts.map +1 -0
  81. package/dist/Inspect.js +270 -0
  82. package/dist/Inspect.js.map +1 -0
  83. package/dist/Keychain.d.ts +57 -0
  84. package/dist/Keychain.d.ts.map +1 -0
  85. package/dist/Keychain.js +73 -0
  86. package/dist/Keychain.js.map +1 -0
  87. package/dist/Lock.d.ts +13 -0
  88. package/dist/Lock.d.ts.map +1 -0
  89. package/dist/Lock.js +145 -0
  90. package/dist/Lock.js.map +1 -0
  91. package/dist/Mcp.d.ts +91 -0
  92. package/dist/Mcp.d.ts.map +1 -0
  93. package/dist/Mcp.js +128 -0
  94. package/dist/Mcp.js.map +1 -0
  95. package/dist/Merge.d.ts +18 -0
  96. package/dist/Merge.d.ts.map +1 -0
  97. package/dist/Merge.js +43 -0
  98. package/dist/Merge.js.map +1 -0
  99. package/dist/Migrate.d.ts +78 -0
  100. package/dist/Migrate.d.ts.map +1 -0
  101. package/dist/Migrate.js +288 -0
  102. package/dist/Migrate.js.map +1 -0
  103. package/dist/Plugins.d.ts +36 -0
  104. package/dist/Plugins.d.ts.map +1 -0
  105. package/dist/Plugins.js +304 -0
  106. package/dist/Plugins.js.map +1 -0
  107. package/dist/Postgres.d.ts +73 -0
  108. package/dist/Postgres.d.ts.map +1 -0
  109. package/dist/Postgres.js +294 -0
  110. package/dist/Postgres.js.map +1 -0
  111. package/dist/Publish.d.ts +23 -0
  112. package/dist/Publish.d.ts.map +1 -0
  113. package/dist/Publish.js +59 -0
  114. package/dist/Publish.js.map +1 -0
  115. package/dist/Registry.d.ts +539 -0
  116. package/dist/Registry.d.ts.map +1 -0
  117. package/dist/Registry.js +340 -0
  118. package/dist/Registry.js.map +1 -0
  119. package/dist/Remote.d.ts +90 -0
  120. package/dist/Remote.d.ts.map +1 -0
  121. package/dist/Remote.js +1006 -0
  122. package/dist/Remote.js.map +1 -0
  123. package/dist/Run.d.ts +120 -0
  124. package/dist/Run.d.ts.map +1 -0
  125. package/dist/Run.js +477 -0
  126. package/dist/Run.js.map +1 -0
  127. package/dist/SyncGen.d.ts +118 -0
  128. package/dist/SyncGen.d.ts.map +1 -0
  129. package/dist/SyncGen.js +392 -0
  130. package/dist/SyncGen.js.map +1 -0
  131. package/dist/Update.d.ts +301 -0
  132. package/dist/Update.d.ts.map +1 -0
  133. package/dist/Update.js +627 -0
  134. package/dist/Update.js.map +1 -0
  135. package/dist/bin.d.ts +3 -0
  136. package/dist/bin.d.ts.map +1 -0
  137. package/dist/bin.js +42 -0
  138. package/dist/bin.js.map +1 -0
  139. package/dist/docs/backlog.md +56 -0
  140. package/dist/docs/ci.md +277 -0
  141. package/dist/docs/cli.md +696 -0
  142. package/dist/docs/connectors/google.md +115 -0
  143. package/dist/docs/connectors/http-openapi.md +7 -0
  144. package/dist/docs/connectors/mcp.md +8 -0
  145. package/dist/docs/connectors/microsoft-graph.md +75 -0
  146. package/dist/docs/connectors/openai.md +25 -0
  147. package/dist/docs/connectors/slack.md +162 -0
  148. package/dist/docs/connectors/workos.md +39 -0
  149. package/dist/docs/contracts/README.md +173 -0
  150. package/dist/docs/contracts/action-consent.md +92 -0
  151. package/dist/docs/contracts/action-registry.md +85 -0
  152. package/dist/docs/contracts/actor.md +100 -0
  153. package/dist/docs/contracts/agent-resources.md +90 -0
  154. package/dist/docs/contracts/agent-runtime.md +257 -0
  155. package/dist/docs/contracts/approvals.md +126 -0
  156. package/dist/docs/contracts/audit.md +75 -0
  157. package/dist/docs/contracts/auth-provider.md +74 -0
  158. package/dist/docs/contracts/calendar-provider.md +46 -0
  159. package/dist/docs/contracts/client-sdk.md +245 -0
  160. package/dist/docs/contracts/collab-document.md +151 -0
  161. package/dist/docs/contracts/command.md +44 -0
  162. package/dist/docs/contracts/connections.md +235 -0
  163. package/dist/docs/contracts/context-accounting.md +50 -0
  164. package/dist/docs/contracts/daemon.md +243 -0
  165. package/dist/docs/contracts/db-tx.md +53 -0
  166. package/dist/docs/contracts/delegation.md +68 -0
  167. package/dist/docs/contracts/device-control.md +103 -0
  168. package/dist/docs/contracts/directory-provider.md +36 -0
  169. package/dist/docs/contracts/directory.md +161 -0
  170. package/dist/docs/contracts/document-source.md +33 -0
  171. package/dist/docs/contracts/files.md +115 -0
  172. package/dist/docs/contracts/flags.md +83 -0
  173. package/dist/docs/contracts/host.md +68 -0
  174. package/dist/docs/contracts/http-api.md +43 -0
  175. package/dist/docs/contracts/ingestion.md +130 -0
  176. package/dist/docs/contracts/ingress.md +141 -0
  177. package/dist/docs/contracts/invocation.md +260 -0
  178. package/dist/docs/contracts/local-client.md +108 -0
  179. package/dist/docs/contracts/locale.md +56 -0
  180. package/dist/docs/contracts/machine-identity.md +117 -0
  181. package/dist/docs/contracts/mail-provider.md +49 -0
  182. package/dist/docs/contracts/memory.md +53 -0
  183. package/dist/docs/contracts/messaging.md +40 -0
  184. package/dist/docs/contracts/metering.md +139 -0
  185. package/dist/docs/contracts/model-provider.md +84 -0
  186. package/dist/docs/contracts/module-manifest.md +213 -0
  187. package/dist/docs/contracts/notification-channel.md +90 -0
  188. package/dist/docs/contracts/notifications.md +123 -0
  189. package/dist/docs/contracts/outbox.md +80 -0
  190. package/dist/docs/contracts/privacy.md +110 -0
  191. package/dist/docs/contracts/progress.md +52 -0
  192. package/dist/docs/contracts/query-surface.md +108 -0
  193. package/dist/docs/contracts/readiness.md +63 -0
  194. package/dist/docs/contracts/release.md +142 -0
  195. package/dist/docs/contracts/result-rendering.md +61 -0
  196. package/dist/docs/contracts/sandbox.md +186 -0
  197. package/dist/docs/contracts/scheduler.md +148 -0
  198. package/dist/docs/contracts/screen-context.md +81 -0
  199. package/dist/docs/contracts/search.md +120 -0
  200. package/dist/docs/contracts/secrets.md +74 -0
  201. package/dist/docs/contracts/settings.md +109 -0
  202. package/dist/docs/contracts/sharing.md +77 -0
  203. package/dist/docs/contracts/slot.md +48 -0
  204. package/dist/docs/contracts/space.md +67 -0
  205. package/dist/docs/contracts/storage-adapter.md +45 -0
  206. package/dist/docs/contracts/storage-backend.md +56 -0
  207. package/dist/docs/contracts/sync.md +213 -0
  208. package/dist/docs/contracts/telemetry.md +80 -0
  209. package/dist/docs/contracts/theme-tokens.md +50 -0
  210. package/dist/docs/contracts/tool-source.md +58 -0
  211. package/dist/docs/contracts/versioning.md +99 -0
  212. package/dist/docs/contracts/view.md +65 -0
  213. package/dist/docs/contracts/work-items.md +99 -0
  214. package/dist/docs/contracts/workflow.md +82 -0
  215. package/dist/docs/decisions.md +163 -0
  216. package/dist/docs/example-app.md +192 -0
  217. package/dist/docs/getting-started.md +927 -0
  218. package/dist/docs/goal.md +54 -0
  219. package/dist/docs/parity.md +29 -0
  220. package/dist/docs/performance.md +129 -0
  221. package/dist/docs/registry/README.md +74 -0
  222. package/dist/docs/registry/app.md +38 -0
  223. package/dist/docs/registry/approvals-ui-foldkit.md +28 -0
  224. package/dist/docs/registry/calendar-ui-foldkit.md +27 -0
  225. package/dist/docs/registry/calendar.md +35 -0
  226. package/dist/docs/registry/chat-ui-foldkit.md +30 -0
  227. package/dist/docs/registry/desktop-rune.md +49 -0
  228. package/dist/docs/registry/desktop.md +32 -0
  229. package/dist/docs/registry/eloxiv-action.md +25 -0
  230. package/dist/docs/registry/eloxiv-connector.md +25 -0
  231. package/dist/docs/registry/eloxiv-module.md +25 -0
  232. package/dist/docs/registry/eloxiv-policy.md +25 -0
  233. package/dist/docs/registry/eloxiv-view.md +25 -0
  234. package/dist/docs/registry/hello-ui-foldkit.md +29 -0
  235. package/dist/docs/registry/hello.md +39 -0
  236. package/dist/docs/registry/home-ui-foldkit.md +27 -0
  237. package/dist/docs/registry/home.md +29 -0
  238. package/dist/docs/registry/inbox-ui-foldkit.md +27 -0
  239. package/dist/docs/registry/mail-ui-foldkit.md +27 -0
  240. package/dist/docs/registry/mail.md +34 -0
  241. package/dist/docs/registry/meeting-prep.md +26 -0
  242. package/dist/docs/registry/members-ui-foldkit.md +28 -0
  243. package/dist/docs/registry/mobile.md +37 -0
  244. package/dist/docs/registry/notes-ui-foldkit.md +27 -0
  245. package/dist/docs/registry/notes.md +26 -0
  246. package/dist/docs/registry/people-ui-foldkit.md +28 -0
  247. package/dist/docs/registry/people.md +38 -0
  248. package/dist/docs/registry/shell-foldkit.md +34 -0
  249. package/dist/docs/registry/theme.md +25 -0
  250. package/dist/docs/registry/ui-conformance.md +30 -0
  251. package/dist/docs/release.md +100 -0
  252. package/dist/docs/scaffold.md +826 -0
  253. package/dist/docs/security/threat-model.md +299 -0
  254. package/dist/docs/upstream/zero-cache-socket-handoff.md +105 -0
  255. package/dist/index.d.ts +8 -0
  256. package/dist/index.d.ts.map +1 -0
  257. package/dist/index.js +8 -0
  258. package/dist/index.js.map +1 -0
  259. package/package.json +48 -3
  260. package/src/AgentSkills.ts +329 -0
  261. package/src/AgentWeb.ts +507 -0
  262. package/src/App.ts +435 -0
  263. package/src/Blueprint.ts +276 -0
  264. package/src/Brand.ts +415 -0
  265. package/src/Changelog.ts +136 -0
  266. package/src/Cli.ts +1458 -0
  267. package/src/DbAdmin.ts +115 -0
  268. package/src/Dependencies.ts +170 -0
  269. package/src/Deploy.ts +563 -0
  270. package/src/Docs.ts +309 -0
  271. package/src/Doctor.ts +424 -0
  272. package/src/Dossier.ts +148 -0
  273. package/src/Emit.ts +68 -0
  274. package/src/Errors.ts +18 -0
  275. package/src/Evals.ts +153 -0
  276. package/src/Files.ts +152 -0
  277. package/src/Generate.ts +402 -0
  278. package/src/Guards.ts +541 -0
  279. package/src/Inspect.ts +358 -0
  280. package/src/Keychain.ts +107 -0
  281. package/src/Lock.ts +174 -0
  282. package/src/Mcp.ts +159 -0
  283. package/src/Merge.ts +70 -0
  284. package/src/Migrate.ts +331 -0
  285. package/src/Plugins.ts +347 -0
  286. package/src/Postgres.ts +353 -0
  287. package/src/Publish.ts +64 -0
  288. package/src/Registry.ts +405 -0
  289. package/src/Remote.ts +1158 -0
  290. package/src/Run.ts +541 -0
  291. package/src/SyncGen.ts +570 -0
  292. package/src/Update.ts +873 -0
  293. package/src/bin.ts +46 -0
  294. package/src/index.ts +7 -0
package/src/SyncGen.ts ADDED
@@ -0,0 +1,570 @@
1
+ /**
2
+ * The sync generator (decision 9): each synced entity's Zero table, generated from its Drizzle table and its
3
+ * entity, emitted as static TypeScript so the app-wide sync schema keeps every table name, column name, type
4
+ * and nullability precise (`Zero<typeof schema>`, never `Zero<any>`).
5
+ *
6
+ * The Drizzle-to-Zero conversion is drizzle-zero's (0.21.0, its programmatic `drizzleZeroConfig`: the table's
7
+ * schema-qualified name for `.from("schema.table")`, each column's database name for column renames, the
8
+ * Postgres-to-Zero type mapping, the primary key, unique keys, and relationships from the Drizzle relations an
9
+ * entity names). Eloxiv owns the rest, because the package does not do it, or does it differently from what
10
+ * sync needs:
11
+ *
12
+ * - **read nullability:** a column is optional exactly when it admits NULL (drizzle-zero also makes every
13
+ * column with a database default optional, which would type a `NOT NULL DEFAULT now()` timestamp nullable);
14
+ * - **completeness:** drizzle-zero skips a column whose type it cannot map, and a relation whose other table
15
+ * is not generated, with at most a warning; here either fails generation, and so does a field whose type or
16
+ * column differs from the entity's own derivation (`@eloxiv/contracts/drizzle`);
17
+ * - **enums:** the column's `enum` values become the Zero column's literal union;
18
+ * - **sharing:** an entity with a sharing attribute gets the `shares` relationship to the kernel's grants
19
+ * (`eloxiv.share_grant`, joined on `resourceId`), from the entity rather than from Drizzle relations (a
20
+ * module's tables never reference the kernel's);
21
+ * - **emission:** static builder code with literal types (the package's programmatic types widen `optional`
22
+ * and `type` to `boolean` and `ValueType`, and its CLI does not run on Bun).
23
+ */
24
+ import type { AnyAction, AnyEntity, AnyModuleContract, OptimisticValue } from "@eloxiv/contracts"
25
+ import { optimisticEntityName, optimisticProblems, predictedEntityNames } from "@eloxiv/contracts"
26
+ import { entityRelations, entityTable } from "@eloxiv/contracts/drizzle"
27
+ import { createTableRelationsHelpers } from "drizzle-orm"
28
+ import { drizzleZeroConfig } from "drizzle-zero"
29
+
30
+ /** One column of a generated Zero table. */
31
+ export interface ZeroColumnSpec {
32
+ readonly field: string
33
+ readonly type: "string" | "number" | "boolean" | "json"
34
+ readonly optional: boolean
35
+ /** The database column, when it differs from the field name. */
36
+ readonly serverName?: string | undefined
37
+ readonly enum?: ReadonlyArray<string> | undefined
38
+ }
39
+
40
+ /** A generated Zero table: what the emitted code builds. */
41
+ export interface ZeroTableSpec {
42
+ /** The Zero (client) table name. */
43
+ readonly name: string
44
+ /** `schema.table`. */
45
+ readonly serverName: string
46
+ readonly columns: ReadonlyArray<ZeroColumnSpec>
47
+ readonly primaryKey: ReadonlyArray<string>
48
+ readonly uniqueKeys: ReadonlyArray<ReadonlyArray<string>>
49
+ readonly relationships: ReadonlyArray<ZeroRelationshipSpec>
50
+ }
51
+
52
+ /** Generation refused: the entity cannot be synced as declared. */
53
+ export class SyncGenerationError extends Error {
54
+ override readonly name = "SyncGenerationError"
55
+ }
56
+
57
+ const ORG_TYPE = "Eloxiv::Org"
58
+ /** The Zero name of the kernel's sharing grants, as `@eloxiv/client/sync` declares them. */
59
+ const SHARE_GRANT = "shareGrant"
60
+ /** Zero table names a module cannot sync as: the grants above and the kernel's live tables. */
61
+ const RESERVED = new Set([SHARE_GRANT, "eloxivSyncOrg", "eloxivSyncFact", "eloxivShareGrant", "eloxivShareRedemption"])
62
+
63
+ interface BuiltColumn {
64
+ readonly type: string
65
+ readonly optional?: boolean
66
+ readonly serverName?: string
67
+ }
68
+ interface BuiltTable {
69
+ readonly name: string
70
+ readonly serverName?: string
71
+ readonly columns: Readonly<Record<string, BuiltColumn>>
72
+ readonly primaryKey: ReadonlyArray<string>
73
+ readonly uniqueKeys?: ReadonlyArray<ReadonlyArray<string>>
74
+ }
75
+
76
+ /** A relationship between two generated tables (one hop, or two through a junction table). */
77
+ export interface ZeroRelationshipSpec {
78
+ readonly name: string
79
+ readonly cardinality: "one" | "many"
80
+ readonly hops: ReadonlyArray<{
81
+ readonly sourceField: ReadonlyArray<string>
82
+ readonly destField: ReadonlyArray<string>
83
+ /** The destination's Zero table name. */
84
+ readonly destSchema: string
85
+ }>
86
+ }
87
+
88
+ interface BuiltRelationship {
89
+ readonly sourceField: ReadonlyArray<string>
90
+ readonly destField: ReadonlyArray<string>
91
+ readonly destSchema: string
92
+ readonly cardinality: "one" | "many"
93
+ }
94
+
95
+ /**
96
+ * The Zero tables of a set of entities (one module's, or the kernel's): drizzle-zero's conversion of their
97
+ * Drizzle tables and of the Drizzle relations they reference, checked and corrected as described above.
98
+ */
99
+ export const zeroSchemaSpec = (entities: ReadonlyArray<AnyEntity>): ReadonlyArray<ZeroTableSpec> => {
100
+ const synced = entities.filter((entity) => entity.sync !== false)
101
+ if (synced.length === 0) return []
102
+ const input: Record<string, unknown> = {}
103
+ const selection: Record<string, Record<string, true>> = {}
104
+ const relationNames = new Map<string, ReadonlyArray<string>>()
105
+ for (const entity of synced) {
106
+ const where = `${entity.cedarType} (${entity.table.schema}.${entity.table.name})`
107
+ const table = entityTable(entity)
108
+ if (table === undefined) {
109
+ throw new SyncGenerationError(
110
+ `${where} was not defined over a Drizzle table (defineEntity from @eloxiv/contracts/drizzle)`,
111
+ )
112
+ }
113
+ const sync = entity.sync as Exclude<AnyEntity["sync"], false>
114
+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(sync.name) || RESERVED.has(sync.name)) {
115
+ throw new SyncGenerationError(
116
+ `${where}: ${JSON.stringify(sync.name)} cannot be a sync name (an identifier the kernel does not reserve)`,
117
+ )
118
+ }
119
+ if (sync.name in input) {
120
+ throw new SyncGenerationError(`Two entities sync as ${sync.name}: name one of them (sync: { name: "..." })`)
121
+ }
122
+ const orgAttribute = Object.values(entity.policyAttributes).some(
123
+ (a) => a.kind === "column" && a.type === "Entity" && a.entityType === ORG_TYPE,
124
+ )
125
+ if (!orgAttribute) {
126
+ throw new SyncGenerationError(
127
+ `${where} has no organisation column (an Eloxiv::Org policy attribute), which every synced entity needs: its read filter's directory tests are evaluated through it. Add one, or set sync: false`,
128
+ )
129
+ }
130
+ input[sync.name] = table
131
+ selection[sync.name] = Object.fromEntries(sync.fields.map((field) => [field, true]))
132
+ const relations = entityRelations(entity)
133
+ if (relations !== undefined) {
134
+ input[`${sync.name}:relations`] = relations
135
+ relationNames.set(sync.name, Object.keys(relations.config(createTableRelationsHelpers(relations.table))))
136
+ }
137
+ }
138
+ const built = drizzleZeroConfig(input, { tables: selection as never, suppressDefaultsWarning: true }) as unknown as {
139
+ readonly tables: Readonly<Record<string, BuiltTable>>
140
+ readonly relationships: Readonly<Record<string, Readonly<Record<string, ReadonlyArray<BuiltRelationship>>>>>
141
+ }
142
+
143
+ return synced.map((entity) => {
144
+ const where = `${entity.cedarType} (${entity.table.schema}.${entity.table.name})`
145
+ const sync = entity.sync as Exclude<AnyEntity["sync"], false>
146
+ const table = built.tables[sync.name]!
147
+ const storage = entity.storage as Readonly<Record<string, AnyEntity["storage"][string]>>
148
+ const serverName = table.serverName ?? table.name
149
+ if (serverName !== `${entity.table.schema}.${entity.table.name}`) {
150
+ throw new SyncGenerationError(`${where}: drizzle-zero mapped the table to ${serverName}`)
151
+ }
152
+ if (table.primaryKey.length !== 1 || table.primaryKey[0] !== entity.primaryKey) {
153
+ throw new SyncGenerationError(
154
+ `${where}: the table's primary key (${table.primaryKey.join(", ")}) is not the entity's (${entity.primaryKey})`,
155
+ )
156
+ }
157
+ const columns: Array<ZeroColumnSpec> = []
158
+ for (const field of sync.fields) {
159
+ const own = storage[field]!
160
+ const column = table.columns[field]
161
+ if (own.type === null || column === undefined) {
162
+ throw new SyncGenerationError(
163
+ `${where}: field ${field} (column ${own.column}) has a type sync cannot represent exactly; leave it out of sync (sync: { omit: [...] })`,
164
+ )
165
+ }
166
+ if (column.type !== own.type || (column.serverName ?? field) !== own.column) {
167
+ throw new SyncGenerationError(
168
+ `${where}: drizzle-zero mapped field ${field} to ${column.type} column ${column.serverName ?? field}, the entity to ${own.type} column ${own.column}`,
169
+ )
170
+ }
171
+ columns.push({
172
+ field,
173
+ type: own.type,
174
+ optional: own.nullable,
175
+ ...(own.column === field ? {} : { serverName: own.column }),
176
+ ...(own.enum === undefined ? {} : { enum: own.enum }),
177
+ })
178
+ }
179
+ // Every Drizzle relation the entity names must have become a relationship: drizzle-zero drops one whose
180
+ // other table is not generated alongside it, which would leave a query that uses it failing at runtime.
181
+ const own = built.relationships[sync.name] ?? {}
182
+ const expected = relationNames.get(sync.name) ?? []
183
+ const missing = expected.filter((name) => !(name in own))
184
+ if (missing.length > 0) {
185
+ throw new SyncGenerationError(
186
+ `${where}: relation ${missing.join(", ")} reaches a table that is not synced with this module's entities`,
187
+ )
188
+ }
189
+ const relationships: Array<ZeroRelationshipSpec> = Object.entries(own).map(([name, hops]) => ({
190
+ name,
191
+ cardinality: hops.at(-1)!.cardinality,
192
+ hops: hops.map((hop) => ({ sourceField: hop.sourceField, destField: hop.destField, destSchema: hop.destSchema })),
193
+ }))
194
+ if (Object.values(entity.policyAttributes).some((a) => a.kind === "sharing")) {
195
+ if ("shares" in own) {
196
+ throw new SyncGenerationError(`${where}: the relation name shares is reserved for the record's sharing grants`)
197
+ }
198
+ relationships.push({
199
+ name: "shares",
200
+ cardinality: "many",
201
+ hops: [{ sourceField: [entity.primaryKey], destField: ["resourceId"], destSchema: SHARE_GRANT }],
202
+ })
203
+ }
204
+ return {
205
+ name: sync.name,
206
+ serverName,
207
+ columns,
208
+ primaryKey: [entity.primaryKey],
209
+ uniqueKeys: table.uniqueKeys ?? [],
210
+ relationships,
211
+ }
212
+ })
213
+ }
214
+
215
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/
216
+ const key = (name: string) => (IDENTIFIER.test(name) ? name : JSON.stringify(name))
217
+ // Sync names are identifiers the kernel does not reserve (checked as the spec is built), so these are valid and
218
+ // distinct per table.
219
+ const tableVariable = (name: string) => `${name}Table`
220
+ const relationshipsVariable = (name: string) => `${name}Relationships`
221
+ const list = (values: ReadonlyArray<string>) => `[${values.map((v) => JSON.stringify(v)).join(", ")}]`
222
+
223
+ const columnCode = (column: ZeroColumnSpec) => {
224
+ const labels = column.enum !== undefined && column.enum.length > 0 ? column.enum.map((v) => JSON.stringify(v)) : []
225
+ // An enum column is its labels; an enum array is JSON, an array of them (its guard refuses NULL elements).
226
+ const base =
227
+ labels.length === 0
228
+ ? `${column.type}()`
229
+ : column.type === "json"
230
+ ? `json<ReadonlyArray<${labels.join(" | ")}>>()`
231
+ : `enumeration<${labels.join(" | ")}>()`
232
+ return `${base}${column.serverName === undefined ? "" : `.from(${JSON.stringify(column.serverName)})`}${column.optional ? ".optional()" : ""}`
233
+ }
234
+
235
+ const tableCode = (spec: ZeroTableSpec) => {
236
+ const lines = [
237
+ `export const ${tableVariable(spec.name)} = table(${JSON.stringify(spec.name)})`,
238
+ ` .from(${JSON.stringify(spec.serverName)})`,
239
+ ` .columns({`,
240
+ ...spec.columns.map((c) => ` ${key(c.field)}: ${columnCode(c)},`),
241
+ ` })`,
242
+ ` .primaryKey(${spec.primaryKey.map((k) => JSON.stringify(k)).join(", ")})`,
243
+ ...spec.uniqueKeys.map((u) => ` .unique(${u.map((k) => JSON.stringify(k)).join(", ")})`),
244
+ ]
245
+ return `${lines.join("\n")}\n`
246
+ }
247
+
248
+ const destination = (name: string) => (name === SHARE_GRANT ? "shareGrant" : tableVariable(name))
249
+
250
+ const relationshipsCode = (spec: ZeroTableSpec) => {
251
+ if (spec.relationships.length === 0) return ""
252
+ const helpers = [...new Set(spec.relationships.map((r) => r.cardinality))].sort().join(", ")
253
+ const entries = spec.relationships.map((r) => {
254
+ const hops = r.hops.map(
255
+ (hop) =>
256
+ `{ sourceField: ${list(hop.sourceField)}, destSchema: ${destination(hop.destSchema)}, destField: ${list(hop.destField)} }`,
257
+ )
258
+ return ` ${key(r.name)}: ${r.cardinality}(${hops.join(", ")}),`
259
+ })
260
+ return `\nexport const ${relationshipsVariable(spec.name)} = relationships(${tableVariable(spec.name)}, ({ ${helpers} }) => ({\n${entries.join("\n")}\n}))\n`
261
+ }
262
+
263
+ export interface SyncSourceOptions {
264
+ /** The first comment line(s), naming what the file was generated from. */
265
+ readonly header: string
266
+ /**
267
+ * `module`: a module's `sync.gen.ts`, importing Eloxiv's client and exporting its tables, relationships, its
268
+ * own schema, `zql` and `defineQuery` for its named queries. `tables`: only the tables and relationships, for a
269
+ * file inside `@eloxiv/client` (which imports Zero directly).
270
+ */
271
+ readonly kind: "module" | "tables"
272
+ /**
273
+ * A module's contract, for its actions' optimistic effects: when any action declares one, the file also exports
274
+ * `mutators`, each action's prediction as a mutator named like the action. `from` is the contract's import
275
+ * specifier relative to the generated file, `exportName` the contract's export there. An action declaring
276
+ * `optimistic.custom()` takes its prediction from the module's own `predictions.ts`, beside the generated file
277
+ * (`PREDICTIONS_FILE`), which exports one per such action, named like it and typed by the generated `Predictions`.
278
+ */
279
+ readonly optimistic?:
280
+ | {
281
+ readonly contract: AnyModuleContract
282
+ readonly from: string
283
+ readonly exportName: string
284
+ /**
285
+ * Whether `mutators` goes in a generated file of its own (`MUTATORS_FILE`, from `mutatorsSource`), the only one
286
+ * importing `predictions.ts`: the module's tables, schema and queries stay importable by a server, which never
287
+ * runs a prediction (a module with a `predictions.ts` has it; `meta.sync.mutators`). Default: with a custom
288
+ * prediction.
289
+ */
290
+ readonly separate?: boolean
291
+ /**
292
+ * The import specifiers of the separate mutators file (`mutatorsSource`), relative to where it is written: the
293
+ * contract, the module's `sync.gen.ts` and its `predictions.ts`. Default: `from`, `./sync.gen.ts` and
294
+ * `./predictions.ts` (the mutators file beside both, `from` relative to it).
295
+ */
296
+ readonly mutatorsImports?:
297
+ | { readonly contract: string; readonly tables: string; readonly predictions: string }
298
+ | undefined
299
+ }
300
+ | undefined
301
+ }
302
+
303
+ const valueCode = (value: OptimisticValue): string => {
304
+ switch (value.from) {
305
+ case "input": {
306
+ const read = `args${IDENTIFIER.test(value.field) ? `.${value.field}` : `[${JSON.stringify(value.field)}]`}`
307
+ return value.default === undefined ? read : `(${read} ?? ${JSON.stringify(value.default)})`
308
+ }
309
+ case "actor":
310
+ return `ctx.${value.field}`
311
+ case "now":
312
+ return "predictedNow(tx)"
313
+ case "value":
314
+ return JSON.stringify(value.value)
315
+ }
316
+ }
317
+
318
+ /** The module's own predictions (`optimistic.custom()`), beside its generated `sync.gen.ts`. */
319
+ export const PREDICTIONS_FILE = "predictions.ts"
320
+
321
+ /** The module's generated mutators, when they import its predictions: the client's entry, beside `sync.gen.ts`. */
322
+ export const MUTATORS_FILE = "mutators.gen.ts"
323
+
324
+ const read = (field: string) => `args${IDENTIFIER.test(field) ? `.${field}` : `[${JSON.stringify(field)}]`}`
325
+
326
+ /** A record literal at `indent` (its fields one deeper). */
327
+ const recordCode = (entries: ReadonlyArray<readonly [string, string]>, indent: string) =>
328
+ `{\n${entries.map(([field, code]) => `${indent} ${key(field)}: ${code},`).join("\n")}\n${indent}}`
329
+
330
+ /**
331
+ * The module's mutators: for each action with an optimistic effect, its prediction over the module's own sync
332
+ * tables, keyed by the action's name (`hello.greet` is `mutators.hello.greet`). Fails generation for an effect
333
+ * the manifest check refuses, so a generated file never predicts what its declaration does not say.
334
+ */
335
+ const mutatorsCode = (
336
+ options: NonNullable<SyncSourceOptions["optimistic"]>,
337
+ specs: ReadonlyArray<ZeroTableSpec>,
338
+ ):
339
+ | {
340
+ /** The `Predictions` interface (empty without a custom prediction): types only, so `sync.gen.ts` keeps it. */
341
+ readonly types: string
342
+ /** `mutators` and the definitions it uses. */
343
+ readonly code: string
344
+ readonly helpers: ReadonlySet<string>
345
+ readonly custom: boolean
346
+ }
347
+ | undefined => {
348
+ const contract = options.contract
349
+ const entities = contract.entities as Readonly<Record<string, AnyEntity>>
350
+ const actions = Object.entries(contract.actions as Readonly<Record<string, AnyAction>>).filter(
351
+ ([, action]) => action.optimistic !== undefined,
352
+ )
353
+ if (actions.length === 0) return undefined
354
+ const helpers = new Set<string>()
355
+ interface Node {
356
+ readonly children: Map<string, Node | string>
357
+ }
358
+ const root: Node = { children: new Map() }
359
+ /** Each custom prediction's entry in `Predictions`: its export name, action reference and the tables it writes. */
360
+ const predictions: Array<string> = []
361
+ const specOf = (action: AnyAction, entity: AnyEntity) => {
362
+ const sync = entity.sync as Exclude<AnyEntity["sync"], false>
363
+ const spec = specs.find((s) => s.name === sync.name)
364
+ if (spec === undefined) {
365
+ throw new SyncGenerationError(`${action.name} predicts ${entity.name}, which is not generated here`)
366
+ }
367
+ return spec
368
+ }
369
+ for (const [local, action] of actions) {
370
+ const problems = optimisticProblems(action, entities)
371
+ if (problems.length > 0) throw new SyncGenerationError(problems.join("; "))
372
+ const effect = action.optimistic!
373
+ const path = action.name.split(".")
374
+ const reference = `${options.exportName}.actions${IDENTIFIER.test(local) ? `.${local}` : `[${JSON.stringify(local)}]`}`
375
+ let code: string
376
+ if (effect.kind === "custom") {
377
+ // The tables of the entities the action declares that sync here: the only ones its prediction may write.
378
+ const tables = predictedEntityNames(action).flatMap((name) => {
379
+ const entity = entities[name]
380
+ if (entity === undefined) throw new SyncGenerationError(`${action.name} declares ${name}, not an entity here`)
381
+ return entity.sync === false ? [] : [specOf(action, entity).name]
382
+ })
383
+ helpers.add("definePredictionWithType")
384
+ const exported = IDENTIFIER.test(local) ? `.${local}` : `[${JSON.stringify(local)}]`
385
+ predictions.push(
386
+ ` readonly ${key(local)}: Prediction<typeof schema, typeof ${reference}, ${tables.map((t) => JSON.stringify(t)).join(" | ")}>`,
387
+ )
388
+ code = `definePrediction(${reference}, ${JSON.stringify(tables)}, predictions${exported})`
389
+ } else {
390
+ helpers.add("defineOptimisticWithType")
391
+ const entity = entities[optimisticEntityName(action)!]!
392
+ code = declarativeCode(action, effect, reference, entity, specOf(action, entity), helpers)
393
+ }
394
+ let node = root
395
+ for (const part of path.slice(0, -1)) {
396
+ let next = node.children.get(part)
397
+ if (next === undefined) {
398
+ next = { children: new Map() }
399
+ node.children.set(part, next)
400
+ }
401
+ if (typeof next === "string") throw new SyncGenerationError(`${action.name} is nested under another action`)
402
+ node = next
403
+ }
404
+ node.children.set(path.at(-1)!, code)
405
+ }
406
+ const emit = (node: Node, depth: number): string => {
407
+ const pad = " ".repeat(depth)
408
+ const lines = [...node.children].map(
409
+ ([name, value]) => `${pad} ${key(name)}: ${typeof value === "string" ? value : emit(value, depth + 1)},`,
410
+ )
411
+ return `{\n${lines.join("\n")}\n${pad}}`
412
+ }
413
+ const declarative = helpers.has("defineOptimisticWithType")
414
+ const custom = predictions.length > 0
415
+ return {
416
+ types: custom
417
+ ? `
418
+ /**
419
+ * The module's own predictions (\`optimistic.custom()\`): its \`${PREDICTIONS_FILE}\` exports one for each action here,
420
+ * named like it, typed by its entry (the action's input; the tables it may write, those of the entities it declares).
421
+ */
422
+ export interface Predictions {
423
+ ${predictions.join("\n")}
424
+ }
425
+ `
426
+ : "",
427
+ code: `
428
+ /** The module's optimistic writes: each action's prediction (its \`optimistic\` declaration), named like the action. */
429
+ ${declarative ? "const defineOptimistic = defineOptimisticWithType<typeof schema>()\n" : ""}${
430
+ custom ? "const definePrediction = definePredictionWithType(schema)\n" : ""
431
+ }export const mutators = ${emit(root, 0)}
432
+ `,
433
+ helpers,
434
+ custom,
435
+ }
436
+ }
437
+
438
+ /** A declarative effect's mutator: its insert, update or delete over the entity's table. */
439
+ const declarativeCode = (
440
+ action: AnyAction,
441
+ effect: Exclude<NonNullable<AnyAction["optimistic"]>, { readonly kind: "custom" }>,
442
+ reference: string,
443
+ entity: AnyEntity,
444
+ spec: ZeroTableSpec,
445
+ helpers: Set<string>,
446
+ ): string => {
447
+ // The mutator's line is as deep as its name has parts; its body two and four spaces deeper.
448
+ const pad = " ".repeat(action.name.split(".").length)
449
+ const table = `tx.mutate${IDENTIFIER.test(spec.name) ? `.${spec.name}` : `[${JSON.stringify(spec.name)}]`}`
450
+ let body: string
451
+ if (effect.kind === "insert") {
452
+ helpers.add("predictedKey")
453
+ const entries: Array<readonly [string, string]> = [
454
+ [entity.primaryKey, `predictedKey(ctx, ${JSON.stringify(entity.cedarType)}, ${read(effect.key)})`],
455
+ ...Object.entries(effect.values).map(([field, value]) => [field, valueCode(value)] as const),
456
+ ]
457
+ body = `${pad} await ${table}.insert(${recordCode(entries, `${pad} `)})\n`
458
+ } else {
459
+ helpers.add("targetIds")
460
+ const entries: Array<readonly [string, string]> = [
461
+ [entity.primaryKey, "id"],
462
+ ...(effect.kind === "update"
463
+ ? Object.entries(effect.set).map(([field, value]) => [field, valueCode(value)] as const)
464
+ : []),
465
+ ]
466
+ body =
467
+ `${pad} for (const id of targetIds(${read(action.target!.field)})) {\n` +
468
+ `${pad} await ${table}.${effect.kind}(${recordCode(entries, `${pad} `)})\n` +
469
+ `${pad} }\n`
470
+ }
471
+ if (body.includes("predictedNow(tx)")) helpers.add("predictedNow")
472
+ const params = ["tx", "args", ...(body.includes("ctx.") || body.includes("(ctx,") ? ["ctx"] : [])].join(", ")
473
+ return `defineOptimistic(${reference}, async ({ ${params} }) => {\n${body}${pad}})`
474
+ }
475
+
476
+ /** The emitted source for a set of entities: their synced Zero tables and relationships, in order. */
477
+ export const syncSource = (entities: ReadonlyArray<AnyEntity>, options: SyncSourceOptions): string => {
478
+ const specs = zeroSchemaSpec(entities)
479
+ const shared = specs.some((s) => s.relationships.some((r) => r.hops.some((h) => h.destSchema === SHARE_GRANT)))
480
+ const related = specs.filter((s) => s.relationships.length > 0)
481
+ const used = new Set<string>(["table"])
482
+ for (const spec of specs) {
483
+ for (const column of spec.columns) {
484
+ used.add(
485
+ column.enum !== undefined && column.enum.length > 0 && column.type !== "json" ? "enumeration" : column.type,
486
+ )
487
+ }
488
+ }
489
+ if (related.length > 0) used.add("relationships")
490
+ const builders = ["boolean", "enumeration", "json", "number", "relationships", "string", "table"].filter((b) =>
491
+ used.has(b),
492
+ )
493
+ const tableNames = specs.map((s) => tableVariable(s.name))
494
+ const relationshipNames = related.map((s) => relationshipsVariable(s.name))
495
+ const parts: Array<string> = [options.header.endsWith("\n") ? options.header : `${options.header}\n`]
496
+ const mutators =
497
+ options.kind === "module" && options.optimistic !== undefined ? mutatorsCode(options.optimistic, specs) : undefined
498
+ // With its mutators in a file of their own, this one keeps only the predictions' types.
499
+ const separate = mutators !== undefined && (options.optimistic!.separate ?? mutators.custom)
500
+ if (options.kind === "module") {
501
+ const imports = [
502
+ "createBuilder",
503
+ "createSchema",
504
+ "defineQueryWithType",
505
+ ...(specs.length === 0 ? [] : builders),
506
+ ...(separate ? [] : (mutators?.helpers ?? [])),
507
+ ...(mutators?.custom ? ["type Prediction"] : []),
508
+ ]
509
+ parts.push(`import { ${imports.sort().join(", ")} } from "@eloxiv/client"\n`)
510
+ if (shared) parts.push(`import { shareGrant } from "@eloxiv/client/sync"\n`)
511
+ if (mutators !== undefined && (!separate || mutators.custom)) {
512
+ parts.push(
513
+ `import ${separate ? "type " : ""}{ ${options.optimistic!.exportName} } from ${JSON.stringify(options.optimistic!.from)}\n`,
514
+ )
515
+ // The module's own predictions: a namespace, so a missing one is a type error here and refused at load.
516
+ if (mutators.custom && !separate) parts.push(`import * as predictions from "./${PREDICTIONS_FILE}"\n`)
517
+ }
518
+ } else {
519
+ if (specs.length > 0) parts.push(`import { ${builders.join(", ")} } from "@rocicorp/zero"\n`)
520
+ if (shared) parts.push(`import { shareGrant } from "./ShareGrant.ts"\n`)
521
+ }
522
+ for (const spec of specs) parts.push(`\n${tableCode(spec)}`)
523
+ for (const spec of related) parts.push(relationshipsCode(spec))
524
+ if (options.kind === "module") {
525
+ const schemaTables = [...tableNames, ...(shared ? ["shareGrant"] : [])]
526
+ parts.push(`
527
+ /** The module's sync tables and relationships, which the app's sync schema (\`eloxiv.sync.ts\`) composes. */
528
+ export const tables = [${tableNames.join(", ")}] as const
529
+ export const relationshipList = [${relationshipNames.join(", ")}] as const
530
+
531
+ /** The module's own schema, the query builder over it, and \`defineQuery\` for its named queries (\`sync.ts\`). */
532
+ export const schema = createSchema({
533
+ tables: [${schemaTables.join(", ")}],
534
+ relationships: [${relationshipNames.join(", ")}],
535
+ })
536
+ export const zql = createBuilder(schema)
537
+ export const defineQuery: ReturnType<typeof defineQueryWithType<typeof schema, unknown>> = defineQueryWithType<typeof schema>()
538
+ `)
539
+ if (mutators !== undefined) parts.push(mutators.types, separate ? "" : mutators.code)
540
+ }
541
+ return parts.join("")
542
+ }
543
+
544
+ /**
545
+ * A module's `mutators.gen.ts` (`MUTATORS_FILE`), when its mutators are kept apart from `sync.gen.ts`
546
+ * (`optimistic.separate`, or a custom prediction): `mutators`, with the module's `predictions.ts` imported here alone,
547
+ * so only a client (which runs predictions) loads it. Undefined when the module's mutators stay in `sync.gen.ts`.
548
+ */
549
+ export const mutatorsSource = (entities: ReadonlyArray<AnyEntity>, options: SyncSourceOptions): string | undefined => {
550
+ if (options.kind !== "module" || options.optimistic === undefined) return undefined
551
+ const mutators = mutatorsCode(options.optimistic, zeroSchemaSpec(entities))
552
+ if (mutators === undefined || !(options.optimistic.separate ?? mutators.custom)) return undefined
553
+ const from = options.optimistic.mutatorsImports ?? {
554
+ contract: options.optimistic.from,
555
+ tables: "./sync.gen.ts",
556
+ predictions: `./${PREDICTIONS_FILE}`,
557
+ }
558
+ return [
559
+ options.header.endsWith("\n") ? options.header : `${options.header}\n`,
560
+ `import { ${[...mutators.helpers].sort().join(", ")} } from "@eloxiv/client"\n`,
561
+ `import { ${options.optimistic.exportName} } from ${JSON.stringify(from.contract)}\n`,
562
+ ...(mutators.custom ? [`import * as predictions from ${JSON.stringify(from.predictions)}\n`] : []),
563
+ `import { schema } from ${JSON.stringify(from.tables)}\n`,
564
+ mutators.code,
565
+ ].join("")
566
+ }
567
+
568
+ /** The header of a module's generated sync tables. */
569
+ export const MODULE_SYNC_HEADER =
570
+ "// Generated by `eloxiv generate` from this module's Drizzle tables and entities (through drizzle-zero 0.21.0).\n// Do not edit: change schema.ts or contract.ts and run `eloxiv generate`."