@eloxiv/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +110 -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 +50 -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 +35 -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/Run.ts ADDED
@@ -0,0 +1,541 @@
1
+ /**
2
+ * Running an app with its own tools (docs/cli.md, "Running an app"):
3
+ *
4
+ * eloxiv dev the kernel (setup, seed, serve), zero-cache and the shell's dev server, until Ctrl-C
5
+ * eloxiv build the shell's production build (shell-foldkit/dist); a headless app has nothing to build
6
+ * eloxiv start [role] one production process: kernel (default), zero, shell or setup
7
+ * eloxiv typecheck the app's TypeScript, and its shell's
8
+ *
9
+ * Every tool is the app's own (`node_modules/.bin/<tool>`), so its versions are the ones the app pins; a missing
10
+ * tool is reported with what to install. The kernel runs on this process's runtime (Bun or Node); zero-cache always
11
+ * on Node (its SQLite binding needs it).
12
+ */
13
+ import { spawn, type ChildProcess } from "node:child_process"
14
+ import { createReadStream, existsSync, mkdirSync, realpathSync, statSync } from "node:fs"
15
+ import { createServer, type Server } from "node:http"
16
+ import { connect } from "node:net"
17
+ import { basename, delimiter, dirname, extname, join, resolve, sep } from "node:path"
18
+ import { DEV_ZERO_API_KEY } from "@eloxiv/contracts"
19
+ import { CliError } from "./Errors.ts"
20
+
21
+ /** The shell item's directory in an app (shell-foldkit's), or undefined for a headless app. */
22
+ export const shellDir = (dir: string) =>
23
+ existsSync(join(dir, "shell-foldkit", "vite.config.ts")) ? join(dir, "shell-foldkit") : undefined
24
+
25
+ /** An app's own executable `name` (`node_modules/.bin/<name>`), or a CliError saying what to install. */
26
+ export const appTool = (dir: string, name: string): string => {
27
+ const bin = join(dir, "node_modules", ".bin", process.platform === "win32" ? `${name}.cmd` : name)
28
+ if (!existsSync(bin)) {
29
+ throw new CliError({ message: `${dir} has no ${name} (node_modules/.bin/${name}): run pnpm install first` })
30
+ }
31
+ return bin
32
+ }
33
+
34
+ /**
35
+ * Whether `env` describes a production deployment: `ELOXIV_ENV=production` (the kernel's own setting) or
36
+ * `NODE_ENV=production` (what most hosts and images set). Either one is enough: a check that guards production
37
+ * (zero-cache's admin password, db administration) never takes the other's absence as development.
38
+ */
39
+ export const isProduction = (env: NodeJS.ProcessEnv) =>
40
+ env["ELOXIV_ENV"] === "production" || env["NODE_ENV"] === "production"
41
+
42
+ /**
43
+ * The environment `eloxiv start` runs a role in: production only. `ELOXIV_ENV` follows `NODE_ENV=production` when
44
+ * unset (so the kernel applies its production rules too); anything else is refused, pointing at `eloxiv dev`.
45
+ */
46
+ export const productionEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {
47
+ if (env["ELOXIV_ENV"] === "development" && env["NODE_ENV"] === "production") {
48
+ throw new CliError({
49
+ message: "ELOXIV_ENV=development contradicts NODE_ENV=production: eloxiv start runs production only",
50
+ })
51
+ }
52
+ if (!isProduction(env)) {
53
+ throw new CliError({
54
+ message:
55
+ "eloxiv start runs a production process: set ELOXIV_ENV=production (the recipes' image does); for development, use eloxiv dev",
56
+ })
57
+ }
58
+ return { ...env, ELOXIV_ENV: "production", NODE_ENV: "production" }
59
+ }
60
+
61
+ /**
62
+ * How often (seconds) zero-cache asks the kernel whether a connected client's credentials still hold: the bound on
63
+ * how long a signed-out session's replica keeps receiving rows (docs/contracts/sync.md). The development harness
64
+ * uses the same value.
65
+ */
66
+ export const ZERO_REVALIDATE_SECONDS = 10
67
+
68
+ /**
69
+ * zero-cache's settings for a deployment, from the kernel's (`ELOXIV_*`) environment. Every `ZERO_*` variable
70
+ * already set wins; the fixed ones are what Eloxiv's sync requires (writes only through the kernel's actions, the
71
+ * kernel's publication and headers). Returns the problems that keep it from starting (a production deployment
72
+ * without an admin password, no database to replicate).
73
+ */
74
+ export const zeroEnv = (
75
+ env: NodeJS.ProcessEnv,
76
+ dir: string = process.cwd(),
77
+ ): { readonly env: Record<string, string>; readonly problems: ReadonlyArray<string> } => {
78
+ const problems: Array<string> = []
79
+ const kernel =
80
+ env["ELOXIV_KERNEL_INTERNAL_URL"] ?? env["ELOXIV_BASE_URL"] ?? `http://localhost:${env["ELOXIV_PORT"] ?? 4100}`
81
+ let upstream = env["ZERO_UPSTREAM_DB"]
82
+ if (upstream === undefined) {
83
+ // The setup role on the app's database: zero-cache replicates as it (its shard schema must be a trusted owner's,
84
+ // docs/contracts/release.md "Database hosts"), in UTC (it reads its change stream as text).
85
+ const admin = env["ELOXIV_ADMIN_DATABASE_URL"]
86
+ const app = env["ELOXIV_DATABASE_URL"]
87
+ if (admin === undefined || app === undefined) {
88
+ problems.push(
89
+ "ZERO_UPSTREAM_DB is not set, and neither ELOXIV_ADMIN_DATABASE_URL and ELOXIV_DATABASE_URL to derive it",
90
+ )
91
+ } else {
92
+ const url = new URL(admin)
93
+ url.pathname = new URL(app).pathname
94
+ url.searchParams.set("TimeZone", "UTC")
95
+ upstream = url.toString()
96
+ }
97
+ }
98
+ const production = isProduction(env)
99
+ const password = env["ZERO_ADMIN_PASSWORD"] ?? (production ? undefined : "eloxiv-dev")
100
+ if (password === undefined) problems.push("ZERO_ADMIN_PASSWORD is required in production")
101
+ // The key zero-cache sends with each push, the kernel's own (ELOXIV_ZERO_API_KEY): only a push that carries it
102
+ // records its client group as the person's (docs/contracts/privacy.md).
103
+ const apiKey = env["ELOXIV_ZERO_API_KEY"] ?? (production ? undefined : DEV_ZERO_API_KEY)
104
+ if (apiKey === undefined) problems.push("ELOXIV_ZERO_API_KEY is required in production")
105
+ const fixed: Record<string, string> = {
106
+ ...(upstream === undefined ? {} : { ZERO_UPSTREAM_DB: upstream }),
107
+ ...(password === undefined ? {} : { ZERO_ADMIN_PASSWORD: password }),
108
+ ZERO_REPLICA_FILE: env["ZERO_REPLICA_FILE"] ?? join(dir, ".eloxiv", "zero", "replica.db"),
109
+ ZERO_QUERY_URL: `${kernel}/zero/query`,
110
+ ZERO_MUTATE_URL: `${kernel}/zero/mutate`,
111
+ ...(apiKey === undefined ? {} : { ZERO_MUTATE_API_KEY: apiKey, ZERO_QUERY_API_KEY: apiKey }),
112
+ ZERO_APP_ID: env["ELOXIV_ZERO_APP_ID"] ?? "zero",
113
+ ZERO_PORT: env["ELOXIV_ZERO_PORT"] ?? "4848",
114
+ ZERO_APP_PUBLICATIONS: "eloxiv_sync",
115
+ ZERO_QUERY_ALLOWED_CLIENT_HEADERS: "x-eloxiv-org",
116
+ ZERO_MUTATE_ALLOWED_CLIENT_HEADERS: "x-eloxiv-org,x-eloxiv-client-version",
117
+ ZERO_ENABLE_CRUD_MUTATIONS: "false",
118
+ ZERO_AUTH_REVALIDATE_INTERVAL_SECONDS: String(ZERO_REVALIDATE_SECONDS),
119
+ ZERO_ENABLE_QUERY_PLANNER: "false",
120
+ ZERO_ENABLE_TELEMETRY: "false",
121
+ }
122
+ const own = Object.fromEntries(
123
+ Object.entries(env).filter(
124
+ (entry): entry is [string, string] => entry[0].startsWith("ZERO_") && entry[1] !== undefined,
125
+ ),
126
+ )
127
+ // What sync's guarantees rest on is never taken from the environment.
128
+ const enforced = { ZERO_ENABLE_CRUD_MUTATIONS: "false", ZERO_APP_PUBLICATIONS: "eloxiv_sync" }
129
+ return { env: { ...fixed, ...own, ...enforced }, problems }
130
+ }
131
+
132
+ /** The Content-Security-Policy the shell is served with: its own origin, the kernel and sync, MAKE views' frames. */
133
+ export const shellCsp = (kernelUrl: string, syncUrl: string) => {
134
+ const origin = (url: string) => new URL(url).origin
135
+ const ws = (url: string) => origin(url).replace(/^http/, "ws")
136
+ return [
137
+ "default-src 'self'",
138
+ "script-src 'self'",
139
+ // StyleX writes a static stylesheet; Foldkit sets style attributes for a few dynamic values.
140
+ "style-src 'self' 'unsafe-inline'",
141
+ `connect-src 'self' ${origin(kernelUrl)} ${origin(syncUrl)} ${ws(syncUrl)}`,
142
+ `img-src 'self' data: blob: ${origin(kernelUrl)}`,
143
+ // MAKE views render in a sandboxed frame served by the kernel.
144
+ `frame-src ${origin(kernelUrl)}`,
145
+ "font-src 'self' data:",
146
+ "object-src 'none'",
147
+ "base-uri 'self'",
148
+ "form-action 'self'",
149
+ "frame-ancestors 'none'",
150
+ ].join("; ")
151
+ }
152
+
153
+ /** The headers every response of the shell carries; `immutable` for Vite's content-hashed assets. */
154
+ export const shellHeaders = (path: string, csp: string): Record<string, string> => ({
155
+ "content-security-policy": csp,
156
+ "x-content-type-options": "nosniff",
157
+ "referrer-policy": "strict-origin-when-cross-origin",
158
+ "cross-origin-opener-policy": "same-origin",
159
+ "permissions-policy": "camera=(), microphone=(), geolocation=()",
160
+ "strict-transport-security": "max-age=31536000; includeSubDomains",
161
+ "cache-control": path.startsWith("/assets/") ? "public, max-age=31536000, immutable" : "no-cache",
162
+ })
163
+
164
+ const TYPES: Record<string, string> = {
165
+ ".html": "text/html; charset=utf-8",
166
+ ".js": "text/javascript; charset=utf-8",
167
+ ".mjs": "text/javascript; charset=utf-8",
168
+ ".css": "text/css; charset=utf-8",
169
+ ".json": "application/json",
170
+ ".svg": "image/svg+xml",
171
+ ".png": "image/png",
172
+ ".jpg": "image/jpeg",
173
+ ".ico": "image/x-icon",
174
+ ".webp": "image/webp",
175
+ ".woff2": "font/woff2",
176
+ ".txt": "text/plain; charset=utf-8",
177
+ ".md": "text/markdown; charset=utf-8",
178
+ ".xml": "application/xml; charset=utf-8",
179
+ ".wasm": "application/wasm",
180
+ }
181
+
182
+ /**
183
+ * Serve a built shell (`dist`) with its security headers: files under `dist` only (never through a symbolic link
184
+ * out of it, never a dot file), `index.html` for any other path without an extension (the shell routes on the
185
+ * client), 404 for a missing asset. Resolves once it listens.
186
+ */
187
+ export const serveShell = (options: {
188
+ readonly dist: string
189
+ readonly port: number
190
+ readonly host?: string
191
+ readonly kernelUrl: string
192
+ readonly syncUrl: string
193
+ }): Promise<Server> => {
194
+ const root = realpathSync(options.dist)
195
+ const index = join(root, "index.html")
196
+ if (!existsSync(index)) {
197
+ return Promise.reject(new CliError({ message: `${options.dist} has no index.html: run eloxiv build first` }))
198
+ }
199
+ const csp = shellCsp(options.kernelUrl, options.syncUrl)
200
+ const server = createServer((request, response) => {
201
+ if (request.method !== "GET" && request.method !== "HEAD") {
202
+ response.writeHead(405, { allow: "GET, HEAD" }).end()
203
+ return
204
+ }
205
+ let path: string
206
+ try {
207
+ path = decodeURIComponent(new URL(request.url ?? "/", "http://shell").pathname)
208
+ } catch {
209
+ response.writeHead(400).end()
210
+ return
211
+ }
212
+ const found = (() => {
213
+ if (path.split("/").some((part) => part.startsWith(".") || part.includes("\0"))) return undefined
214
+ const file = resolve(root, `.${path}`)
215
+ if (!existsSync(file)) return undefined
216
+ const real = realpathSync(file)
217
+ if (real !== root && !real.startsWith(root + sep)) return undefined
218
+ return statSync(real).isFile() ? real : undefined
219
+ })()
220
+ const file = found ?? (extname(path) === "" ? index : undefined)
221
+ if (file === undefined) {
222
+ response
223
+ .writeHead(404, { ...shellHeaders(path, csp), "content-type": "text/plain; charset=utf-8" })
224
+ .end("Not found")
225
+ return
226
+ }
227
+ const served = file === index ? "/index.html" : path
228
+ response.writeHead(200, {
229
+ ...shellHeaders(served, csp),
230
+ "content-type": TYPES[extname(file)] ?? "application/octet-stream",
231
+ })
232
+ if (request.method === "HEAD") response.end()
233
+ else createReadStream(file).pipe(response)
234
+ })
235
+ return new Promise((done, fail) => {
236
+ server.once("error", fail)
237
+ server.listen(options.port, options.host ?? "0.0.0.0", () => done(server))
238
+ })
239
+ }
240
+
241
+ /** Spawn `command` with its output shown, resolving with its exit code (a signal counts as failure). */
242
+ export const runTool = (
243
+ command: string,
244
+ args: ReadonlyArray<string>,
245
+ options: { cwd: string; env?: NodeJS.ProcessEnv },
246
+ ) =>
247
+ new Promise<number>((done, fail) => {
248
+ const child = spawn(command, args, { cwd: options.cwd, env: options.env ?? process.env, stdio: "inherit" })
249
+ child.once("error", (e) => fail(new CliError({ message: `${command} could not start: ${e.message}` })))
250
+ child.once("exit", (code) => done(code ?? 1))
251
+ })
252
+
253
+ /** `eloxiv typecheck`: the app's own `tsc` over its tsconfig, then over its shell's. */
254
+ export const typecheck = async (dir: string) => {
255
+ const tsc = appTool(dir, "tsc")
256
+ const projects = [
257
+ join(dir, "tsconfig.json"),
258
+ ...(shellDir(dir) === undefined ? [] : [join(dir, "shell-foldkit", "tsconfig.json")]),
259
+ ]
260
+ for (const project of projects.filter((p) => existsSync(p))) {
261
+ const code = await runTool(tsc, ["-p", project, "--noEmit"], { cwd: dir })
262
+ if (code !== 0) return code
263
+ }
264
+ return 0
265
+ }
266
+
267
+ /**
268
+ * `eloxiv build`: the shell's production build with the URLs the deployed shell talks to (`VITE_ELOXIV_URL`,
269
+ * `VITE_ELOXIV_SYNC_URL`), into `shell-foldkit/dist`. The server needs no build (Bun and Node run its TypeScript).
270
+ */
271
+ export const build = async (
272
+ dir: string,
273
+ urls: { readonly kernelUrl?: string | undefined; readonly syncUrl?: string | undefined },
274
+ ) => {
275
+ const shell = shellDir(dir)
276
+ if (shell === undefined) {
277
+ console.log("headless app: nothing to build (the server runs its TypeScript as it is)")
278
+ return 0
279
+ }
280
+ const env = {
281
+ ...process.env,
282
+ ...(urls.kernelUrl === undefined ? {} : { VITE_ELOXIV_URL: urls.kernelUrl }),
283
+ ...(urls.syncUrl === undefined ? {} : { VITE_ELOXIV_SYNC_URL: urls.syncUrl }),
284
+ }
285
+ if (env["VITE_ELOXIV_URL"] === undefined || env["VITE_ELOXIV_SYNC_URL"] === undefined) {
286
+ console.log("note: VITE_ELOXIV_URL or VITE_ELOXIV_SYNC_URL unset; the shell falls back to localhost for it")
287
+ }
288
+ return runTool(appTool(dir, "vite"), ["build"], { cwd: shell, env })
289
+ }
290
+
291
+ export const START_ROLES = ["kernel", "zero", "shell", "setup"] as const
292
+ export type StartRole = (typeof START_ROLES)[number]
293
+
294
+ const serverEntry = (dir: string) => {
295
+ const entry = join(dir, "server", "main.ts")
296
+ if (!existsSync(entry))
297
+ throw new CliError({ message: `${dir} has no server/main.ts: add the app item first (eloxiv add app)` })
298
+ return entry
299
+ }
300
+
301
+ /**
302
+ * Real Node, for zero-cache (Bun cannot load its SQLite binding): this process when it is Node, else the first
303
+ * `node` on PATH that is not Bun's shim (`bun --bun` puts one first).
304
+ */
305
+ export const nodeExecutable = (): string => {
306
+ if (!("Bun" in globalThis)) return process.execPath
307
+ for (const entry of (process.env["PATH"] ?? "").split(delimiter)) {
308
+ const candidate = join(entry, process.platform === "win32" ? "node.exe" : "node")
309
+ if (existsSync(candidate) && !basename(realpathSync(candidate)).startsWith("bun")) return candidate
310
+ }
311
+ throw new CliError({ message: "zero-cache needs Node.js on PATH" })
312
+ }
313
+
314
+ /**
315
+ * zero-cache's entry script (`@rocicorp/zero`'s `out/zero/src/cli.js`) as the app installed it: the app's own
316
+ * dependency, else the one `@eloxiv/kernel` depends on (pnpm keeps a dependency's dependencies beside it).
317
+ */
318
+ export const zeroCacheEntry = (dir: string): string => {
319
+ const candidates = [join(dir, "node_modules", "@rocicorp", "zero")]
320
+ const kernel = join(dir, "node_modules", "@eloxiv", "kernel")
321
+ if (existsSync(kernel)) {
322
+ const real = realpathSync(kernel)
323
+ candidates.push(join(real, "node_modules", "@rocicorp", "zero"), join(real, "..", "..", "@rocicorp", "zero"))
324
+ }
325
+ for (const candidate of candidates) {
326
+ const entry = join(candidate, "out", "zero", "src", "cli.js")
327
+ if (existsSync(entry)) return entry
328
+ }
329
+ throw new CliError({
330
+ message: `${dir} has no zero-cache (@rocicorp/zero, through @eloxiv/kernel): run pnpm install first`,
331
+ })
332
+ }
333
+
334
+ /** Long-running processes the CLI started: `done` once they have all ended (with the first failure's code, else 0). */
335
+ export interface Running {
336
+ readonly done: Promise<number>
337
+ /** Ask every process to stop (SIGTERM) and wait for them. */
338
+ readonly stop: () => Promise<number>
339
+ }
340
+
341
+ /**
342
+ * Supervise `children`: when one exits by itself the others are stopped too, and `done` resolves with its code (0
343
+ * only when every one exited cleanly). The CLI stops them on Ctrl-C or SIGTERM (an interrupted command's cleanup).
344
+ * A child may start later (a promise of it, undefined when it is not started after all); one that starts after the
345
+ * others were stopped is stopped at once.
346
+ */
347
+ export const supervise = (
348
+ children: ReadonlyArray<{
349
+ readonly name: string
350
+ readonly child: ChildProcess | Promise<ChildProcess | undefined>
351
+ }>,
352
+ ): Running => {
353
+ let stopping = false
354
+ let result = 0
355
+ const started: Array<ChildProcess> = []
356
+ const alive = (child: ChildProcess) => child.exitCode === null && child.signalCode === null
357
+ const stopAll = () => {
358
+ stopping = true
359
+ for (const child of started) if (alive(child)) child.kill("SIGTERM")
360
+ }
361
+ const done = Promise.all(
362
+ children.map(({ name, child: starting }) =>
363
+ Promise.resolve(starting).then(
364
+ (child) =>
365
+ new Promise<void>((exited) => {
366
+ if (child === undefined || !alive(child)) return exited()
367
+ started.push(child)
368
+ child.once("error", (e) => {
369
+ console.error(`${name} could not start: ${e.message}`)
370
+ result ||= 1
371
+ stopAll()
372
+ exited()
373
+ })
374
+ child.once("exit", (code, signal) => {
375
+ if (!stopping) {
376
+ console.error(`${name} exited (${code ?? signal}); stopping the others`)
377
+ if (code !== 0) result = code ?? 1
378
+ stopAll()
379
+ }
380
+ exited()
381
+ })
382
+ if (stopping) child.kill("SIGTERM")
383
+ }),
384
+ ),
385
+ ),
386
+ ).then(() => result)
387
+ return {
388
+ done,
389
+ stop: () => {
390
+ stopAll()
391
+ return done
392
+ },
393
+ }
394
+ }
395
+
396
+ /** Whether `child` is accepting connections on `port` (polled), false once it has exited without doing so. */
397
+ const listening = (port: string, child: ChildProcess): Promise<boolean> =>
398
+ new Promise((answer) => {
399
+ const attempt = () => {
400
+ if (child.exitCode !== null || child.signalCode !== null) return answer(false)
401
+ const socket = connect(Number(port), "localhost")
402
+ socket.once("connect", () => {
403
+ socket.destroy()
404
+ answer(true)
405
+ })
406
+ socket.once("error", () => {
407
+ socket.destroy()
408
+ setTimeout(attempt, 200)
409
+ })
410
+ }
411
+ attempt()
412
+ })
413
+
414
+ /** zero-cache's replica file is SQLite, which does not make its directory: a new app has none yet. */
415
+ const replicaDirectory = (zero: Record<string, string>) => {
416
+ const file = zero["ZERO_REPLICA_FILE"]
417
+ if (file !== undefined) mkdirSync(dirname(resolve(file)), { recursive: true })
418
+ }
419
+
420
+ const spawnShown = (
421
+ name: string,
422
+ command: string,
423
+ args: ReadonlyArray<string>,
424
+ options: { cwd: string; env?: NodeJS.ProcessEnv },
425
+ ) => ({
426
+ name,
427
+ child: spawn(command, args, { cwd: options.cwd, env: options.env ?? process.env, stdio: "inherit" }),
428
+ })
429
+
430
+ /** `eloxiv start <role>`: one production process of the app, until it ends or the CLI is stopped. */
431
+ export const start = async (
432
+ dir: string,
433
+ role: StartRole,
434
+ options: { readonly port?: number; readonly kernelUrl?: string; readonly syncUrl?: string } = {},
435
+ ): Promise<Running> => {
436
+ const runtimeArgs = [...process.execArgv]
437
+ const env = productionEnv(process.env)
438
+ switch (role) {
439
+ case "kernel":
440
+ return supervise([spawnShown("kernel", process.execPath, [...runtimeArgs, serverEntry(dir)], { cwd: dir, env })])
441
+ case "setup":
442
+ return supervise([
443
+ spawnShown("setup", process.execPath, [...runtimeArgs, serverEntry(dir), "setup"], { cwd: dir, env }),
444
+ ])
445
+ case "zero": {
446
+ const zero = zeroEnv(env, dir)
447
+ if (zero.problems.length > 0)
448
+ throw new CliError({ message: `zero-cache cannot start: ${zero.problems.join("; ")}` })
449
+ replicaDirectory(zero.env)
450
+ return supervise([
451
+ spawnShown("zero-cache", nodeExecutable(), [zeroCacheEntry(dir)], { cwd: dir, env: { ...env, ...zero.env } }),
452
+ ])
453
+ }
454
+ case "shell": {
455
+ const shell = shellDir(dir)
456
+ if (shell === undefined) throw new CliError({ message: `${dir} has no shell (shell-foldkit) to serve` })
457
+ const kernelUrl = options.kernelUrl ?? process.env["ELOXIV_BASE_URL"]
458
+ const syncUrl = options.syncUrl ?? process.env["ELOXIV_ZERO_URL"]
459
+ if (kernelUrl === undefined || syncUrl === undefined) {
460
+ throw new CliError({
461
+ message:
462
+ "eloxiv start shell needs the kernel's and sync's public URLs: ELOXIV_BASE_URL and ELOXIV_ZERO_URL (or --kernel-url, --sync-url)",
463
+ })
464
+ }
465
+ const port = options.port ?? Number(process.env["PORT"] ?? 8080)
466
+ const server = await serveShell({ dist: join(shell, "dist"), port, kernelUrl, syncUrl })
467
+ console.log(`shell served on port ${port} from ${join(shell, "dist")}`)
468
+ let closed: Promise<number> | undefined
469
+ const done = new Promise<number>((resolveDone) => server.once("close", () => resolveDone(0)))
470
+ return {
471
+ done,
472
+ stop: () =>
473
+ (closed ??= new Promise<number>((resolveStop) => {
474
+ server.close(() => resolveStop(0))
475
+ server.closeAllConnections()
476
+ })),
477
+ }
478
+ }
479
+ }
480
+ }
481
+
482
+ /**
483
+ * `eloxiv dev`: the kernel (`server/main.ts prepare-and-serve`: setup, seed, serve), zero-cache with development
484
+ * settings (started once the kernel serves, so its setup has made the database) and the shell's dev server, each the
485
+ * app's own, until Ctrl-C or one of them exits. PostgreSQL is the app's (`ELOXIV_DATABASE_URL`,
486
+ * `ELOXIV_ADMIN_DATABASE_URL`); it must have `wal_level=logical`.
487
+ */
488
+ export const dev = (dir: string, options: { readonly shell: boolean }): Running => {
489
+ const kernelPort = process.env["ELOXIV_PORT"] ?? "4100"
490
+ const zeroPort = process.env["ELOXIV_ZERO_PORT"] ?? "4848"
491
+ const shellPort = process.env["ELOXIV_SHELL_PORT"] ?? "5173"
492
+ const kernelUrl = `http://localhost:${kernelPort}`
493
+ const syncUrl = `http://localhost:${zeroPort}`
494
+ const shell = options.shell ? shellDir(dir) : undefined
495
+ const base = { ...process.env, ELOXIV_ENV: "development", NODE_ENV: "development" }
496
+ const zero = zeroEnv({ ...base, ELOXIV_KERNEL_INTERNAL_URL: kernelUrl, ELOXIV_ZERO_PORT: zeroPort }, dir)
497
+ if (zero.problems.length > 0) throw new CliError({ message: `zero-cache cannot start: ${zero.problems.join("; ")}` })
498
+ const zeroCache = zeroCacheEntry(dir)
499
+ const vite = shell === undefined ? undefined : appTool(dir, "vite")
500
+ replicaDirectory(zero.env)
501
+ const kernel = spawn(process.execPath, [...process.execArgv, serverEntry(dir), "prepare-and-serve"], {
502
+ cwd: dir,
503
+ stdio: "inherit",
504
+ env: {
505
+ ...base,
506
+ ELOXIV_PORT: kernelPort,
507
+ ELOXIV_TRUSTED_ORIGINS:
508
+ process.env["ELOXIV_TRUSTED_ORIGINS"] ??
509
+ `http://localhost:${shellPort},tauri://localhost,http://tauri.localhost`,
510
+ },
511
+ })
512
+ const children = [
513
+ { name: "kernel", child: kernel },
514
+ {
515
+ // Once the kernel serves, its setup has made the database and the publication zero-cache replicates: on a new
516
+ // database zero-cache started beside it found neither and exited.
517
+ name: "zero-cache",
518
+ child: listening(kernelPort, kernel).then((up) =>
519
+ up
520
+ ? spawn(nodeExecutable(), [zeroCache], { cwd: dir, stdio: "inherit", env: { ...base, ...zero.env } })
521
+ : undefined,
522
+ ),
523
+ },
524
+ ...(shell === undefined || vite === undefined
525
+ ? []
526
+ : [
527
+ {
528
+ name: "shell",
529
+ child: spawn(vite, ["--port", shellPort, "--strictPort"], {
530
+ cwd: shell,
531
+ stdio: "inherit",
532
+ env: { ...base, VITE_ELOXIV_URL: kernelUrl, VITE_ELOXIV_SYNC_URL: syncUrl },
533
+ }),
534
+ },
535
+ ]),
536
+ ]
537
+ console.log(
538
+ `kernel ${kernelUrl} sync ${syncUrl}${shell === undefined ? "" : ` shell http://localhost:${shellPort}`} (Ctrl-C stops them)`,
539
+ )
540
+ return supervise(children)
541
+ }