@sixb/cli 0.1.26 → 0.2.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 (76) hide show
  1. package/dist/commands/agent.d.ts.map +1 -1
  2. package/dist/commands/api.d.ts.map +1 -1
  3. package/dist/commands/check.d.ts.map +1 -1
  4. package/dist/commands/deploy.d.ts.map +1 -1
  5. package/dist/commands/dev-runner.d.ts.map +1 -1
  6. package/dist/commands/dev.d.ts.map +1 -1
  7. package/dist/commands/env.d.ts +31 -0
  8. package/dist/commands/env.d.ts.map +1 -0
  9. package/dist/lib/command-line.d.ts +26 -1
  10. package/dist/lib/command-line.d.ts.map +1 -1
  11. package/dist/lib/deploy-release.d.ts +2 -0
  12. package/dist/lib/deploy-release.d.ts.map +1 -1
  13. package/dist/lib/deploy-source.d.ts +2 -0
  14. package/dist/lib/deploy-source.d.ts.map +1 -1
  15. package/dist/lib/env-config.d.ts +17 -0
  16. package/dist/lib/env-config.d.ts.map +1 -0
  17. package/dist/lib/env-file.d.ts +16 -0
  18. package/dist/lib/env-file.d.ts.map +1 -0
  19. package/dist/lib/hidden-prompt.d.ts +19 -0
  20. package/dist/lib/hidden-prompt.d.ts.map +1 -0
  21. package/dist/tui/app.d.ts +8 -0
  22. package/dist/tui/app.d.ts.map +1 -1
  23. package/dist/tui/computer.d.ts +5 -0
  24. package/dist/tui/computer.d.ts.map +1 -1
  25. package/dist/tui/context.d.ts +13 -0
  26. package/dist/tui/context.d.ts.map +1 -0
  27. package/dist/tui/format.d.ts +85 -0
  28. package/dist/tui/format.d.ts.map +1 -1
  29. package/dist/tui/index.d.ts.map +1 -1
  30. package/dist/tui/markdown.d.ts +18 -0
  31. package/dist/tui/markdown.d.ts.map +1 -0
  32. package/dist/tui/parts.d.ts +8 -0
  33. package/dist/tui/parts.d.ts.map +1 -1
  34. package/dist/tui/runner.d.ts +37 -14
  35. package/dist/tui/runner.d.ts.map +1 -1
  36. package/dist/tui/settings.d.ts +13 -1
  37. package/dist/tui/settings.d.ts.map +1 -1
  38. package/dist/tui/transcript.d.ts +1 -1
  39. package/dist/tui/transcript.d.ts.map +1 -1
  40. package/dist/tui/ui.d.ts +7 -0
  41. package/dist/tui/ui.d.ts.map +1 -1
  42. package/dist/ui/deploy-screens.d.ts +3 -1
  43. package/dist/ui/deploy-screens.d.ts.map +1 -1
  44. package/dist/ui/env-screens.d.ts +37 -0
  45. package/dist/ui/env-screens.d.ts.map +1 -0
  46. package/package.json +19 -19
  47. package/src/commands/agent.ts +17 -10
  48. package/src/commands/api.ts +2 -1
  49. package/src/commands/check.ts +5 -1
  50. package/src/commands/deploy.ts +29 -3
  51. package/src/commands/dev-runner.ts +3 -1
  52. package/src/commands/dev.ts +3 -0
  53. package/src/commands/env.ts +422 -0
  54. package/src/index.tsx +39 -1
  55. package/src/lib/command-line.ts +59 -1
  56. package/src/lib/deploy-release.ts +3 -0
  57. package/src/lib/deploy-source.ts +10 -0
  58. package/src/lib/env-config.ts +96 -0
  59. package/src/lib/env-file.ts +104 -0
  60. package/src/lib/hidden-prompt.ts +97 -0
  61. package/src/tui/app.tsx +315 -179
  62. package/src/tui/computer.ts +37 -0
  63. package/src/tui/context.tsx +149 -0
  64. package/src/tui/format.ts +218 -1
  65. package/src/tui/index.tsx +13 -2
  66. package/src/tui/markdown.ts +91 -0
  67. package/src/tui/parts.ts +23 -3
  68. package/src/tui/runner.ts +113 -30
  69. package/src/tui/settings.ts +54 -5
  70. package/src/tui/transcript.tsx +90 -8
  71. package/src/tui/ui.tsx +40 -11
  72. package/src/ui/deploy-screens.ts +12 -1
  73. package/src/ui/env-screens.ts +81 -0
  74. package/dist/tui/folders.d.ts +0 -7
  75. package/dist/tui/folders.d.ts.map +0 -1
  76. package/src/tui/folders.ts +0 -41
@@ -0,0 +1,422 @@
1
+ import { readFile, writeFile } from "node:fs/promises"
2
+ import { join, resolve } from "node:path"
3
+ import { createInterface } from "node:readline/promises"
4
+ import { pathToFileURL } from "node:url"
5
+ import {
6
+ type EnvConfig,
7
+ type EnvName,
8
+ type EnvSource,
9
+ EnvSourceUnreachableError,
10
+ type EnvVarRule,
11
+ } from "@sixb/core/env"
12
+ import {
13
+ ENV_CONFIG_FILE,
14
+ envVarNeeded,
15
+ loadEnvConfig,
16
+ missingEnvError,
17
+ missingEnvSentence,
18
+ missingEnvVars,
19
+ VAR_NAME_PATTERN,
20
+ } from "../lib/env-config"
21
+ import { isGeneratedEnvFile, readEnvFile, writeEnvFile } from "../lib/env-file"
22
+ import { errorMessage, SixbCliError } from "../lib/errors"
23
+ import { promptHidden } from "../lib/hidden-prompt"
24
+ import { renderStatic } from "../ui"
25
+ import {
26
+ type EnvStatusCell,
27
+ envInitView,
28
+ envKeptView,
29
+ envPulledView,
30
+ envSetView,
31
+ envStatusView,
32
+ } from "../ui/env-screens"
33
+ import { canRunLive } from "../ui/live/can-run-live"
34
+
35
+ const ENV_NAMES: readonly EnvName[] = ["dev", "prod"]
36
+ const DOPPLER_PACKAGE = "@sixb/env-doppler"
37
+
38
+ // ─── pull ────────────────────────────────────────────────────────────────────
39
+
40
+ export async function runEnvPull(options: {
41
+ readonly env?: string
42
+ readonly tokenFile?: string
43
+ readonly force?: boolean
44
+ readonly cwd?: string
45
+ }): Promise<void> {
46
+ const cwd = options.cwd ?? process.cwd()
47
+ const env = parseEnvName(options.env ?? "dev")
48
+
49
+ // A server has a token file. Refusing everyone else keeps prod values off laptops by default.
50
+ if (env === "prod" && options.tokenFile === undefined) {
51
+ throw new SixbCliError("[SixbEnv] Prod values stay on servers, so they can't be pulled here.", {
52
+ remediation: "Read a value in your source's dashboard, or change one with `sixb env set`.",
53
+ })
54
+ }
55
+
56
+ // A server deploying a commit whose `sixb.env.ts` has no source, such as a rollback.
57
+ if (options.tokenFile !== undefined) {
58
+ const deployed = await loadEnvConfig(cwd)
59
+ if (deployed && !deployed.source) {
60
+ await renderStatic(envKeptView({ env, reason: "This commit's sixb.env.ts has no source." }))
61
+ return
62
+ }
63
+ }
64
+
65
+ const { config, source } = await requireSource(cwd)
66
+ const token = options.tokenFile === undefined ? undefined : await readToken(options.tokenFile)
67
+ const pulled = await pullEnv({
68
+ cwd,
69
+ config,
70
+ source,
71
+ env,
72
+ ...(token === undefined ? {} : { token }),
73
+ force: options.force === true,
74
+ })
75
+
76
+ await renderStatic(
77
+ pulled.kept
78
+ ? envKeptView({ env, reason: pulled.reason })
79
+ : envPulledView({ env, count: Object.keys(pulled.values).length })
80
+ )
81
+ }
82
+
83
+ type PullResult =
84
+ | { readonly kept: false; readonly values: Readonly<Record<string, string>> }
85
+ | { readonly kept: true; readonly reason: string }
86
+
87
+ async function pullEnv(input: {
88
+ readonly cwd: string
89
+ readonly config: EnvConfig
90
+ readonly source: EnvSource
91
+ readonly env: EnvName
92
+ readonly token?: string
93
+ readonly force?: boolean
94
+ }): Promise<PullResult> {
95
+ const { config, source, env, token } = input
96
+ const path = join(input.cwd, ".env")
97
+
98
+ let values: Readonly<Record<string, string>>
99
+ try {
100
+ values = await source.read(env, token === undefined ? {} : { token })
101
+ } catch (error) {
102
+ // A server riding out an outage, so it can still take a hotfix. A refusal never reaches this:
103
+ // a revoked token must stop the deploy.
104
+ const riding = token !== undefined && error instanceof EnvSourceUnreachableError
105
+ if (riding && (await isCompleteGeneratedEnv(path, config, env))) {
106
+ return { kept: true, reason: errorMessage(error) }
107
+ }
108
+ throw error
109
+ }
110
+
111
+ const missing = missingEnvVars(config, values, env)
112
+ if (missing.length > 0) {
113
+ throw new SixbCliError(`[SixbEnv] ${env} is missing ${missing.join(", ")}.`, {
114
+ remediation: missing.map((name) => `sixb env set ${name} --env ${env}`).join("\n"),
115
+ })
116
+ }
117
+
118
+ if (!input.force) await refuseToLoseValues(path, values)
119
+ await writeEnvFile(path, values, env)
120
+ return { kept: false, values }
121
+ }
122
+
123
+ async function isCompleteGeneratedEnv(
124
+ path: string,
125
+ config: EnvConfig,
126
+ env: EnvName
127
+ ): Promise<boolean> {
128
+ if (!(await isGeneratedEnvFile(path))) return false
129
+ return missingEnvVars(config, await readEnvFile(path), env).length === 0
130
+ }
131
+
132
+ /** A hand-written `.env` may hold the only copy of a value, so it's replaced only on request. */
133
+ async function refuseToLoseValues(
134
+ path: string,
135
+ values: Readonly<Record<string, string>>
136
+ ): Promise<void> {
137
+ if (!(await Bun.file(path).exists()) || (await isGeneratedEnvFile(path))) return
138
+
139
+ const current = await readEnvFile(path)
140
+ const different = Object.keys(current)
141
+ .filter((name) => current[name] !== values[name])
142
+ .sort()
143
+ if (different.length > 0) {
144
+ throw new SixbCliError(
145
+ `[SixbEnv] This .env was written by hand, and the source has something else for ${different.join(", ")}.`,
146
+ {
147
+ remediation:
148
+ "Move what you want to keep to the source or .env.local, then delete the file or pass --force.",
149
+ }
150
+ )
151
+ }
152
+ }
153
+
154
+ async function readToken(path: string): Promise<string> {
155
+ const text = await readFile(path, "utf8").catch(() => {
156
+ throw new SixbCliError(`[SixbEnv] Could not read the token file ${path}.`)
157
+ })
158
+ const token = text.trim()
159
+ if (!token) throw new SixbCliError(`[SixbEnv] The token file ${path} is empty.`)
160
+ return token
161
+ }
162
+
163
+ // ─── dev ─────────────────────────────────────────────────────────────────────
164
+
165
+ /** Before `sixb dev`: stops on a missing variable, offering to pull when there's a source. */
166
+ export async function assertDevEnv(cwd: string): Promise<void> {
167
+ const config = await loadEnvConfig(cwd)
168
+ if (!config) return
169
+
170
+ const missing = missingEnvVars(config, process.env, "dev")
171
+ if (missing.length === 0) return
172
+ if (!config.source || !canRunLive()) throw missingEnvError(config, missing)
173
+
174
+ process.stderr.write(`\n${missingEnvSentence(missing)}\n`)
175
+ const prompt = createInterface({ input: process.stdin, output: process.stderr })
176
+ const answer = await prompt.question("Pull from dev now? (Y/n) ").finally(() => prompt.close())
177
+ if (/^n/i.test(answer.trim())) throw missingEnvError(config, missing)
178
+
179
+ await pullIntoThisProcess(cwd, config, config.source)
180
+ }
181
+
182
+ /**
183
+ * Bun read `.env` when this process started, and the processes `sixb dev` starts inherit what it
184
+ * read. So a pull also has to update this process, or they run on the old values. `.env.local`
185
+ * still wins, as it does when Bun loads the files itself. A variable exported in the shell loses
186
+ * here, which only happens on the rare start that pulls.
187
+ */
188
+ export async function pullIntoThisProcess(
189
+ cwd: string,
190
+ config: EnvConfig,
191
+ source: EnvSource
192
+ ): Promise<void> {
193
+ const pulled = await pullEnv({ cwd, config, source, env: "dev" })
194
+ if (pulled.kept) return
195
+
196
+ const localPath = join(cwd, ".env.local")
197
+ const local = (await Bun.file(localPath).exists()) ? await readEnvFile(localPath) : {}
198
+ Object.assign(process.env, pulled.values, local)
199
+
200
+ await renderStatic(envPulledView({ env: "dev", count: Object.keys(pulled.values).length }))
201
+
202
+ const stillMissing = missingEnvVars(config, process.env, "dev")
203
+ if (stillMissing.length > 0) throw missingEnvError(config, stillMissing)
204
+ }
205
+
206
+ // ─── set ─────────────────────────────────────────────────────────────────────
207
+
208
+ export async function runEnvSet(options: {
209
+ readonly name: string
210
+ readonly env: string | undefined
211
+ readonly cwd?: string
212
+ }): Promise<void> {
213
+ const cwd = options.cwd ?? process.cwd()
214
+ const { name } = options
215
+ // Never quoted: `sixb env set KEY=value` is an easy slip, and this may be a CI log.
216
+ if (!VAR_NAME_PATTERN.test(name)) {
217
+ throw new SixbCliError("[SixbEnv] That is not a variable name.", {
218
+ remediation:
219
+ "Name the variable alone, then give the value at the prompt or on standard input.",
220
+ })
221
+ }
222
+ const env = parseEnvName(options.env)
223
+ const { config, source } = await requireSource(cwd)
224
+
225
+ // Never an argument: arguments land in shell history and in the process list.
226
+ const value = process.stdin.isTTY
227
+ ? await promptHidden("Value:")
228
+ : (await Bun.stdin.text()).replace(/\r?\n$/, "")
229
+ if (value === "") throw new SixbCliError(`[SixbEnv] ${name} needs a value.`)
230
+
231
+ await source.write(env, { [name]: value })
232
+ await renderStatic(envSetView({ name, env, declared: name in config.vars }))
233
+ }
234
+
235
+ // ─── status ──────────────────────────────────────────────────────────────────
236
+
237
+ export async function runEnvStatus(options: { readonly cwd?: string } = {}): Promise<void> {
238
+ const { config, source } = await requireSource(options.cwd ?? process.cwd())
239
+
240
+ const [dev, prod] = await Promise.allSettled(ENV_NAMES.map((env) => source.names(env)))
241
+ // Someone may only have access to dev. With neither, the failure is what to show.
242
+ if (dev?.status === "rejected" && prod?.status === "rejected") throw dev.reason
243
+
244
+ const devNames = dev?.status === "fulfilled" ? new Set(dev.value) : null
245
+ const prodNames = prod?.status === "fulfilled" ? new Set(prod.value) : null
246
+ const names = new Set([...Object.keys(config.vars), ...(devNames ?? []), ...(prodNames ?? [])])
247
+
248
+ const cell = (env: EnvName, found: ReadonlySet<string> | null, name: string): EnvStatusCell => {
249
+ if (!found) return "unknown"
250
+ if (found.has(name)) return "set"
251
+ return envVarNeeded(config.vars[name] ?? "optional", env) ? "missing" : "unneeded"
252
+ }
253
+ const rows = [...names].sort().map((name) => ({
254
+ name,
255
+ dev: cell("dev", devNames, name),
256
+ prod: cell("prod", prodNames, name),
257
+ declared: name in config.vars,
258
+ }))
259
+ const missing = rows.flatMap((row) => [row.dev, row.prod]).filter((c) => c === "missing").length
260
+
261
+ await renderStatic(envStatusView({ rows, missing }))
262
+ if (missing > 0) process.exitCode = 1
263
+ }
264
+
265
+ // ─── init ────────────────────────────────────────────────────────────────────
266
+
267
+ export async function runEnvInit(options: {
268
+ readonly project: string
269
+ readonly dev?: string
270
+ readonly prod?: string
271
+ readonly cwd?: string
272
+ }): Promise<void> {
273
+ const cwd = options.cwd ?? process.cwd()
274
+ const configPath = join(cwd, ENV_CONFIG_FILE)
275
+ if (await Bun.file(configPath).exists()) {
276
+ throw new SixbCliError(`[SixbEnv] ${ENV_CONFIG_FILE} already exists.`)
277
+ }
278
+
279
+ const files = [
280
+ ["dev", options.dev],
281
+ ["prod", options.prod],
282
+ ] as const
283
+ const given = files.flatMap(([env, file]) => (file === undefined ? [] : [{ env, file }]))
284
+ if (given.length === 0) {
285
+ throw new SixbCliError("[SixbEnv] Say where the current values are.", {
286
+ remediation: "sixb env init <project> --dev .env --prod .env.prod",
287
+ })
288
+ }
289
+
290
+ const source = await loadDopplerSource(cwd, options.project)
291
+ const uploads = await Promise.all(
292
+ given.map(async ({ env, file }) => {
293
+ const path = resolve(cwd, file)
294
+ if (!(await Bun.file(path).exists())) {
295
+ throw new SixbCliError(`[SixbEnv] ${file} does not exist.`)
296
+ }
297
+ return { env, values: uploadableValues(await readEnvFile(path), file) }
298
+ })
299
+ )
300
+
301
+ // Check every environment before writing to any, so a conflict changes nothing. Running this
302
+ // again after a failed upload finds the same values, which aren't a conflict.
303
+ for (const { env, values } of uploads) {
304
+ const existing = await source.read(env)
305
+ const conflicts = Object.keys(values).filter(
306
+ (name) => name in existing && existing[name] !== values[name]
307
+ )
308
+ if (conflicts.length > 0) {
309
+ throw new SixbCliError(
310
+ `[SixbEnv] ${options.project} already has other values in ${env} for ${conflicts.sort().join(", ")}.`,
311
+ {
312
+ remediation:
313
+ "Change them in your source's dashboard, or edit the file, and run this again.",
314
+ }
315
+ )
316
+ }
317
+ }
318
+ for (const { env, values } of uploads) await source.write(env, values)
319
+
320
+ const vars = declaredVars(uploads)
321
+ await writeFile(configPath, renderEnvConfig(options.project, vars))
322
+ await renderStatic(
323
+ envInitView({
324
+ uploaded: uploads.map(({ env, values }) => ({ env, count: Object.keys(values).length })),
325
+ names: Object.keys(vars).length,
326
+ })
327
+ )
328
+ }
329
+
330
+ /**
331
+ * The first guess at each rule. A name with a value in dev and in prod, when each was given, is
332
+ * `required`; one with a value in prod alone is `prod`. Anything else, such as a name only dev has,
333
+ * would fail a deploy if it were required, so it starts `optional`.
334
+ */
335
+ function declaredVars(
336
+ uploads: readonly { readonly env: EnvName; readonly values: Record<string, string> }[]
337
+ ): Record<string, EnvVarRule> {
338
+ const names = uploads.flatMap(({ values }) => Object.keys(values))
339
+ const dev = uploads.find(({ env }) => env === "dev")?.values
340
+ const prod = uploads.find(({ env }) => env === "prod")?.values
341
+
342
+ return Object.fromEntries(
343
+ [...new Set(names)].sort().map((name): [string, EnvVarRule] => {
344
+ if (dev?.[name] && (!prod || prod[name])) return [name, "required"]
345
+ return [name, prod?.[name] ? "prod" : "optional"]
346
+ })
347
+ )
348
+ }
349
+
350
+ /**
351
+ * What a file can upload. A name `sixb.env.ts` couldn't declare stops this before anything is sent.
352
+ * `DOPPLER_*` is how this machine reaches Doppler, not a value of the project.
353
+ */
354
+ function uploadableValues(
355
+ values: Readonly<Record<string, string>>,
356
+ file: string
357
+ ): Record<string, string> {
358
+ const invalid = Object.keys(values).filter((name) => !VAR_NAME_PATTERN.test(name))
359
+ if (invalid.length > 0) {
360
+ throw new SixbCliError(
361
+ `[SixbEnv] ${file} has names that aren't variable names: ${invalid.sort().join(", ")}.`,
362
+ { remediation: "Rename them or remove them, and run this again." }
363
+ )
364
+ }
365
+ return Object.fromEntries(Object.entries(values).filter(([name]) => !name.startsWith("DOPPLER_")))
366
+ }
367
+
368
+ function renderEnvConfig(project: string, vars: Readonly<Record<string, EnvVarRule>>): string {
369
+ const lines = Object.entries(vars).map(([name, rule]) => ` ${name}: "${rule}",`)
370
+ return [
371
+ 'import { defineEnv } from "@sixb/core/env"',
372
+ `import { doppler } from "${DOPPLER_PACKAGE}"`,
373
+ "",
374
+ "export default defineEnv({",
375
+ ` source: doppler({ project: ${JSON.stringify(project)} }),`,
376
+ " vars: {",
377
+ ...lines,
378
+ " },",
379
+ "})",
380
+ "",
381
+ ].join("\n")
382
+ }
383
+
384
+ /** `sixb.env.ts` doesn't exist yet to load a source from, so this finds the project's own copy. */
385
+ async function loadDopplerSource(cwd: string, project: string): Promise<EnvSource> {
386
+ let path: string
387
+ try {
388
+ path = Bun.resolveSync(DOPPLER_PACKAGE, cwd)
389
+ } catch {
390
+ throw new SixbCliError(`[SixbEnv] This project doesn't have ${DOPPLER_PACKAGE} yet.`, {
391
+ remediation: `bun add ${DOPPLER_PACKAGE}`,
392
+ })
393
+ }
394
+ const module = (await import(pathToFileURL(path).href)) as {
395
+ readonly doppler: (options: { readonly project: string }) => EnvSource
396
+ }
397
+ return module.doppler({ project })
398
+ }
399
+
400
+ // ─── shared ──────────────────────────────────────────────────────────────────
401
+
402
+ function parseEnvName(value: string | undefined): EnvName {
403
+ if (value === "dev" || value === "prod") return value
404
+ throw new SixbCliError("[SixbEnv] Choose an environment: --env dev or --env prod.")
405
+ }
406
+
407
+ async function requireSource(
408
+ cwd: string
409
+ ): Promise<{ readonly config: EnvConfig; readonly source: EnvSource }> {
410
+ const config = await loadEnvConfig(cwd)
411
+ if (!config) {
412
+ throw new SixbCliError(`[SixbEnv] No ${ENV_CONFIG_FILE} in ${cwd}.`, {
413
+ remediation: "sixb env init <project> --dev .env --prod .env.prod",
414
+ })
415
+ }
416
+ if (!config.source) {
417
+ throw new SixbCliError(`[SixbEnv] ${ENV_CONFIG_FILE} has no \`source\`.`, {
418
+ remediation: `Add one, such as \`source: doppler({ project: "shop" })\` from ${DOPPLER_PACKAGE}.`,
419
+ })
420
+ }
421
+ return { config, source: config.source }
422
+ }
package/src/index.tsx CHANGED
@@ -93,7 +93,9 @@ async function main(): Promise<void> {
93
93
  if (canRunLive()) {
94
94
  const { runTui } = await import("./tui")
95
95
  await runTui({ version: VERSION })
96
- return
96
+ // Its turns ended and its session closed, or their wait ran out: nothing is left to wait for,
97
+ // and whatever the app leaves running would keep the terminal from its prompt.
98
+ process.exit()
97
99
  }
98
100
  }
99
101
  const parsed = parseCliArgs(args)
@@ -372,6 +374,42 @@ async function main(): Promise<void> {
372
374
  break
373
375
  }
374
376
 
377
+ case "env:init": {
378
+ const { runEnvInit } = await import("./commands/env")
379
+ const dev = getFlag("dev")
380
+ const prod = getFlag("prod")
381
+ await runEnvInit({
382
+ project: positionals[0] ?? "",
383
+ ...(dev === undefined ? {} : { dev }),
384
+ ...(prod === undefined ? {} : { prod }),
385
+ })
386
+ break
387
+ }
388
+
389
+ case "env:pull": {
390
+ const { runEnvPull } = await import("./commands/env")
391
+ const env = getFlag("env")
392
+ const tokenFile = getFlag("token-file")
393
+ await runEnvPull({
394
+ ...(env === undefined ? {} : { env }),
395
+ ...(tokenFile === undefined ? {} : { tokenFile }),
396
+ force: hasFlag("force"),
397
+ })
398
+ break
399
+ }
400
+
401
+ case "env:set": {
402
+ const { runEnvSet } = await import("./commands/env")
403
+ await runEnvSet({ name: positionals[0] ?? "", env: getFlag("env") })
404
+ break
405
+ }
406
+
407
+ case "env:status": {
408
+ const { runEnvStatus } = await import("./commands/env")
409
+ await runEnvStatus()
410
+ break
411
+ }
412
+
375
413
  case "deploy": {
376
414
  const { runDeploy } = await import("./commands/deploy")
377
415
  await runDeploy({ dryRun: hasFlag("dry-run"), json: hasFlag("json"), ref: getFlag("ref") })
@@ -126,6 +126,31 @@ export const CLI_OPTION_DEFINITIONS = {
126
126
  kind: "string",
127
127
  },
128
128
  follow: { syntax: "--follow", summary: "Keep printing new log lines", kind: "boolean" },
129
+ env: {
130
+ syntax: "--env <dev|prod>",
131
+ summary: "Environment (default for pull: dev)",
132
+ kind: "string",
133
+ },
134
+ dev: {
135
+ syntax: "--dev <file>",
136
+ summary: "The file holding the current dev values",
137
+ kind: "string",
138
+ },
139
+ prod: {
140
+ syntax: "--prod <file>",
141
+ summary: "The file holding the current prod values",
142
+ kind: "string",
143
+ },
144
+ "token-file": {
145
+ syntax: "--token-file <path>",
146
+ summary: "Read the source's token from this file, as a server does",
147
+ kind: "string",
148
+ },
149
+ force: {
150
+ syntax: "--force",
151
+ summary: "Replace a hand-written .env, losing what the source doesn't have",
152
+ kind: "boolean",
153
+ },
129
154
  admin: {
130
155
  syntax: "--admin <login>",
131
156
  summary: "Login with sudo that prepares the server (default: root)",
@@ -209,6 +234,10 @@ export type LocalCommandId =
209
234
  | "deploy:access:list"
210
235
  | "deploy:access:add"
211
236
  | "deploy:access:remove"
237
+ | "env:init"
238
+ | "env:pull"
239
+ | "env:set"
240
+ | "env:status"
212
241
  | "init"
213
242
 
214
243
  interface CommandNode {
@@ -595,6 +624,35 @@ const commandTree: readonly CommandNode[] = [
595
624
  },
596
625
  ],
597
626
  },
627
+ {
628
+ name: "env",
629
+ summary: "Keep the project's environment variables in one place",
630
+ usage: "sixb env <init|pull|set|status>",
631
+ rootHelpLabel: "env ...",
632
+ children: [
633
+ command("env:init", "Move a project's values to its source and write sixb.env.ts", {
634
+ path: ["env", "init"],
635
+ usage: "sixb env init <project> [--dev <file>] [--prod <file>]",
636
+ options: ["dev", "prod"],
637
+ minimumPositionals: 1,
638
+ maximumPositionals: 1,
639
+ }),
640
+ command("env:pull", "Write .env from the project's source", {
641
+ path: ["env", "pull"],
642
+ options: ["env", "token-file", "force"],
643
+ }),
644
+ command("env:set", "Set one value in the project's source", {
645
+ path: ["env", "set"],
646
+ usage: "sixb env set <name> --env <dev|prod>",
647
+ options: ["env"],
648
+ minimumPositionals: 1,
649
+ maximumPositionals: 1,
650
+ }),
651
+ command("env:status", "Show which variables have values, without showing them", {
652
+ path: ["env", "status"],
653
+ }),
654
+ ],
655
+ },
598
656
  command("init", "Create a Sixb project in a directory", {
599
657
  usage: "sixb init [dir]",
600
658
  maximumPositionals: 1,
@@ -663,7 +721,7 @@ const ROOT_HELP_GROUP_COMMANDS: readonly {
663
721
  readonly compact?: boolean
664
722
  }[] = [
665
723
  { title: "Agent", names: ["agent"] },
666
- { title: "Develop", names: ["init", "dev", "check", "typegen", "build"] },
724
+ { title: "Develop", names: ["init", "dev", "env", "check", "typegen", "build"] },
667
725
  { title: "Deploy", names: ["deploy", "desktop"] },
668
726
  {
669
727
  title: "Run in production",
@@ -74,6 +74,8 @@ const ACTION_HOST_SERVICES: ReadonlySet<DeployServiceName> = new Set(["api", "wo
74
74
  export interface DeployReleaseOptions {
75
75
  /** The Bun version the project runs on, from its `packageManager` or the running Bun. */
76
76
  readonly bunVersion: string
77
+ /** Whether a deploy writes the target's `.env` from the project's source. */
78
+ readonly envFromSource?: boolean
77
79
  }
78
80
 
79
81
  export function buildDeployRelease(
@@ -98,6 +100,7 @@ export function buildDeployRelease(
98
100
  bunVersion: options.bunVersion,
99
101
  env,
100
102
  steps: {
103
+ ...(options.envFromSource ? { env: sixb("env", "pull", "--env", "prod") } : {}),
101
104
  build: [sixb("build")],
102
105
  // The order `docs/deployment` gives. `check` probes every provider, so a broker or queue
103
106
  // the services cannot reach fails the deploy instead of passing for healthy; it needs the
@@ -171,6 +171,16 @@ function archive(repo: string, commit: string): ReadableStream<Uint8Array> {
171
171
  })
172
172
  }
173
173
 
174
+ /** Whether a commit being deployed has this file in the project's directory. */
175
+ export async function commitHasProjectFile(
176
+ projectDir: string,
177
+ source: Pick<DeploySource, "commit" | "projectPath">,
178
+ file: string
179
+ ): Promise<boolean> {
180
+ const root = await git(projectDir, ["rev-parse", "--show-toplevel"])
181
+ return isFile(root, source.commit, posix.join(source.projectPath, file))
182
+ }
183
+
174
184
  async function isFile(root: string, commit: string, path: string): Promise<boolean> {
175
185
  return git(root, ["cat-file", "-e", `${commit}:${path}`])
176
186
  .then(() => true)
@@ -0,0 +1,96 @@
1
+ import { resolve } from "node:path"
2
+ import { pathToFileURL } from "node:url"
3
+ import type { EnvConfig, EnvName, EnvVarRule } from "@sixb/core/env"
4
+ import { SixbCliError } from "./errors"
5
+
6
+ export const ENV_CONFIG_FILE = "sixb.env.ts"
7
+
8
+ export const VAR_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/
9
+ const VAR_RULES: ReadonlySet<unknown> = new Set(["required", "prod", "optional"])
10
+
11
+ /** Loads `sixb.env.ts` from the project directory. A project without one has no declared names. */
12
+ export async function loadEnvConfig(cwd = process.cwd()): Promise<EnvConfig | null> {
13
+ const path = resolve(cwd, ENV_CONFIG_FILE)
14
+ if (!(await Bun.file(path).exists())) return null
15
+
16
+ const module = (await import(pathToFileURL(path).href)) as { readonly default?: unknown }
17
+ if (module.default === undefined) {
18
+ throw new SixbCliError(`[SixbEnv] ${path} has no default export.`, {
19
+ remediation: "Export the variables: `export default defineEnv({ vars: { ... } })`.",
20
+ })
21
+ }
22
+ return validateEnvConfig(module.default)
23
+ }
24
+
25
+ function validateEnvConfig(value: unknown): EnvConfig {
26
+ const { source, vars } = (value ?? {}) as { readonly source?: unknown; readonly vars?: unknown }
27
+ if (typeof vars !== "object" || vars === null || Array.isArray(vars)) {
28
+ throw new SixbCliError(`[SixbEnv] ${ENV_CONFIG_FILE} must set \`vars\`.`, {
29
+ remediation: 'Name each variable with a rule: `vars: { DATABASE_URL: "required" }`.',
30
+ })
31
+ }
32
+
33
+ for (const [name, rule] of Object.entries(vars)) {
34
+ if (!VAR_NAME_PATTERN.test(name)) {
35
+ throw new SixbCliError(`[SixbEnv] "${name}" in ${ENV_CONFIG_FILE} is not a variable name.`)
36
+ }
37
+ if (!VAR_RULES.has(rule)) {
38
+ throw new SixbCliError(
39
+ `[SixbEnv] ${name} in ${ENV_CONFIG_FILE} must be "required", "prod", or "optional".`
40
+ )
41
+ }
42
+ }
43
+ if (source !== undefined && !isEnvSource(source)) {
44
+ throw new SixbCliError(`[SixbEnv] \`source\` in ${ENV_CONFIG_FILE} is not a source.`, {
45
+ remediation: 'Use a source, such as `doppler({ project: "shop" })` from @sixb/env-doppler.',
46
+ })
47
+ }
48
+ return value as EnvConfig
49
+ }
50
+
51
+ function isEnvSource(value: unknown): boolean {
52
+ const candidate = value as Record<string, unknown> | null
53
+ return ["names", "read", "write", "createServerToken"].every(
54
+ (method) => typeof candidate?.[method] === "function"
55
+ )
56
+ }
57
+
58
+ /** The names `env` must have a value for and doesn't. An empty value counts as none. */
59
+ export function missingEnvVars(
60
+ config: EnvConfig,
61
+ values: Readonly<Record<string, string | undefined>>,
62
+ env: EnvName
63
+ ): string[] {
64
+ return Object.entries(config.vars)
65
+ .filter(([name, rule]) => envVarNeeded(rule, env) && !values[name])
66
+ .map(([name]) => name)
67
+ }
68
+
69
+ /** Whether a variable with this rule must have a value in `env`. */
70
+ export function envVarNeeded(rule: EnvVarRule, env: EnvName): boolean {
71
+ return rule === "required" || (rule === "prod" && env === "prod")
72
+ }
73
+
74
+ /** The sentence every command uses to name what is missing. */
75
+ export function missingEnvSentence(names: readonly string[]): string {
76
+ return `Missing ${names.join(", ")}, which ${ENV_CONFIG_FILE} requires.`
77
+ }
78
+
79
+ /** Stops a command that is about to run the project without a variable it declares. */
80
+ export async function assertDeclaredEnv(cwd: string): Promise<void> {
81
+ const config = await loadEnvConfig(cwd)
82
+ if (!config) return
83
+
84
+ const env = process.env.NODE_ENV === "production" ? "prod" : "dev"
85
+ const missing = missingEnvVars(config, process.env, env)
86
+ if (missing.length > 0) throw missingEnvError(config, missing)
87
+ }
88
+
89
+ /** The failure for a project about to run without these variables, and what fixes it. */
90
+ export function missingEnvError(config: EnvConfig, names: readonly string[]): SixbCliError {
91
+ return new SixbCliError(`[SixbEnv] ${missingEnvSentence(names)}`, {
92
+ remediation: config.source
93
+ ? "Run `sixb env pull`. If the source doesn't have the value, set it with `sixb env set`."
94
+ : "Add what's missing to the project's .env.",
95
+ })
96
+ }