@sixb/cli 0.1.21 → 0.1.22

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 (129) hide show
  1. package/README.md +18 -3
  2. package/dist/commands/api.d.ts.map +1 -1
  3. package/dist/commands/app.d.ts.map +1 -1
  4. package/dist/commands/build.d.ts.map +1 -1
  5. package/dist/commands/check.d.ts.map +1 -1
  6. package/dist/commands/db-migrate.d.ts.map +1 -1
  7. package/dist/commands/deploy.d.ts.map +1 -1
  8. package/dist/commands/desktop.d.ts +15 -0
  9. package/dist/commands/desktop.d.ts.map +1 -0
  10. package/dist/commands/dev-runner.d.ts +4 -0
  11. package/dist/commands/dev-runner.d.ts.map +1 -1
  12. package/dist/commands/dev.d.ts.map +1 -1
  13. package/dist/commands/init.d.ts.map +1 -1
  14. package/dist/commands/lake-check.d.ts.map +1 -1
  15. package/dist/commands/lake-cleanup.d.ts.map +1 -1
  16. package/dist/commands/login.d.ts.map +1 -1
  17. package/dist/commands/logout.d.ts.map +1 -1
  18. package/dist/commands/orchestrator.d.ts.map +1 -1
  19. package/dist/commands/profile.d.ts.map +1 -1
  20. package/dist/commands/rules.d.ts.map +1 -1
  21. package/dist/commands/scheduler.d.ts.map +1 -1
  22. package/dist/commands/service-account.d.ts.map +1 -1
  23. package/dist/commands/status.d.ts.map +1 -1
  24. package/dist/commands/token.d.ts.map +1 -1
  25. package/dist/commands/typegen.d.ts.map +1 -1
  26. package/dist/commands/worker-group.d.ts +2 -0
  27. package/dist/commands/worker-group.d.ts.map +1 -1
  28. package/dist/commands/worker.d.ts +2 -0
  29. package/dist/commands/worker.d.ts.map +1 -1
  30. package/dist/lib/command-line.d.ts +22 -2
  31. package/dist/lib/command-line.d.ts.map +1 -1
  32. package/dist/lib/deploy-release.d.ts +3 -1
  33. package/dist/lib/deploy-release.d.ts.map +1 -1
  34. package/dist/lib/desktop.d.ts +26 -0
  35. package/dist/lib/desktop.d.ts.map +1 -0
  36. package/dist/lib/dev-messages.d.ts +43 -0
  37. package/dist/lib/dev-messages.d.ts.map +1 -0
  38. package/dist/lib/dev-supervisor.d.ts +27 -0
  39. package/dist/lib/dev-supervisor.d.ts.map +1 -1
  40. package/dist/lib/open-url.d.ts +3 -0
  41. package/dist/lib/open-url.d.ts.map +1 -0
  42. package/dist/lib/role-lifecycle.d.ts.map +1 -1
  43. package/dist/lib/runtime.d.ts +2 -0
  44. package/dist/lib/runtime.d.ts.map +1 -1
  45. package/dist/lib/worker-concurrency.d.ts +11 -0
  46. package/dist/lib/worker-concurrency.d.ts.map +1 -1
  47. package/dist/lib/worker-registry.d.ts +2 -0
  48. package/dist/lib/worker-registry.d.ts.map +1 -1
  49. package/dist/ui/deploy-screens.d.ts +48 -0
  50. package/dist/ui/deploy-screens.d.ts.map +1 -0
  51. package/dist/ui/index.d.ts +28 -244
  52. package/dist/ui/index.d.ts.map +1 -1
  53. package/dist/ui/layout.d.ts +65 -0
  54. package/dist/ui/layout.d.ts.map +1 -0
  55. package/dist/ui/live/ansi.d.ts +8 -0
  56. package/dist/ui/live/ansi.d.ts.map +1 -0
  57. package/dist/ui/live/can-run-live.d.ts +6 -0
  58. package/dist/ui/live/can-run-live.d.ts.map +1 -0
  59. package/dist/ui/live/components.d.ts +17 -0
  60. package/dist/ui/live/components.d.ts.map +1 -0
  61. package/dist/ui/live/deploy.d.ts +22 -0
  62. package/dist/ui/live/deploy.d.ts.map +1 -0
  63. package/dist/ui/live/dev.d.ts +47 -0
  64. package/dist/ui/live/dev.d.ts.map +1 -0
  65. package/dist/ui/live/prompt.d.ts +30 -0
  66. package/dist/ui/live/prompt.d.ts.map +1 -0
  67. package/dist/ui/live/session.d.ts +27 -0
  68. package/dist/ui/live/session.d.ts.map +1 -0
  69. package/dist/ui/screens.d.ts +136 -0
  70. package/dist/ui/screens.d.ts.map +1 -0
  71. package/dist/ui/theme.d.ts +58 -0
  72. package/dist/ui/theme.d.ts.map +1 -0
  73. package/package.json +19 -18
  74. package/src/commands/{api.tsx → api.ts} +18 -27
  75. package/src/commands/{app.tsx → app.ts} +14 -18
  76. package/src/commands/build.ts +70 -0
  77. package/src/commands/{check.tsx → check.ts} +27 -18
  78. package/src/commands/db-migrate.ts +32 -0
  79. package/src/commands/{deploy.tsx → deploy.ts} +109 -102
  80. package/src/commands/desktop.ts +71 -0
  81. package/src/commands/{dev-runner.tsx → dev-runner.ts} +67 -33
  82. package/src/commands/{init.tsx → init.ts} +19 -8
  83. package/src/commands/lake-check.ts +36 -0
  84. package/src/commands/{lake-cleanup.tsx → lake-cleanup.ts} +17 -12
  85. package/src/commands/{login.tsx → login.ts} +36 -30
  86. package/src/commands/{logout.tsx → logout.ts} +5 -5
  87. package/src/commands/{orchestrator.tsx → orchestrator.ts} +15 -28
  88. package/src/commands/{profile.tsx → profile.ts} +38 -19
  89. package/src/commands/{rules.tsx → rules.ts} +15 -24
  90. package/src/commands/{scheduler.tsx → scheduler.ts} +14 -27
  91. package/src/commands/{service-account.tsx → service-account.ts} +37 -39
  92. package/src/commands/{status.tsx → status.ts} +8 -8
  93. package/src/commands/{token.tsx → token.ts} +19 -20
  94. package/src/commands/typegen.ts +18 -0
  95. package/src/commands/{worker-group.tsx → worker-group.ts} +40 -29
  96. package/src/commands/{worker.tsx → worker.ts} +30 -22
  97. package/src/index.tsx +22 -1
  98. package/src/lib/command-line.ts +108 -57
  99. package/src/lib/deploy-release.ts +17 -1
  100. package/src/lib/desktop.ts +52 -0
  101. package/src/lib/dev-messages.ts +44 -0
  102. package/src/lib/dev-supervisor.ts +132 -12
  103. package/src/lib/open-url.ts +15 -0
  104. package/src/lib/role-lifecycle.ts +2 -3
  105. package/src/lib/runtime.ts +4 -0
  106. package/src/lib/worker-concurrency.ts +31 -0
  107. package/src/lib/worker-registry.ts +4 -0
  108. package/src/ui/README.md +54 -0
  109. package/src/ui/deploy-screens.ts +360 -0
  110. package/src/ui/index.ts +158 -0
  111. package/src/ui/layout.ts +245 -0
  112. package/src/ui/live/ansi.ts +103 -0
  113. package/src/ui/live/can-run-live.ts +9 -0
  114. package/src/ui/live/components.tsx +81 -0
  115. package/src/ui/live/deploy.tsx +170 -0
  116. package/src/ui/live/dev.tsx +522 -0
  117. package/src/ui/live/prompt.tsx +205 -0
  118. package/src/ui/live/session.ts +103 -0
  119. package/src/ui/screens.ts +490 -0
  120. package/src/ui/theme.ts +122 -0
  121. package/dist/lib/role-view.d.ts +0 -21
  122. package/dist/lib/role-view.d.ts.map +0 -1
  123. package/src/commands/build.tsx +0 -65
  124. package/src/commands/db-migrate.tsx +0 -30
  125. package/src/commands/lake-check.tsx +0 -33
  126. package/src/commands/typegen.tsx +0 -18
  127. package/src/lib/role-view.ts +0 -49
  128. package/src/ui/index.tsx +0 -1398
  129. /package/src/commands/{dev.tsx → dev.ts} +0 -0
@@ -0,0 +1,360 @@
1
+ import type {
2
+ DeployAccessKey,
3
+ DeployCheck,
4
+ DeployCommand,
5
+ DeployRelease,
6
+ DeployStatus,
7
+ } from "@sixb/core/deploy"
8
+ import {
9
+ commands,
10
+ header,
11
+ headline,
12
+ marked,
13
+ pad,
14
+ plural,
15
+ type Row,
16
+ remedy,
17
+ rows,
18
+ type Status,
19
+ screen,
20
+ section,
21
+ stack,
22
+ table,
23
+ } from "./layout"
24
+ import { glyph, tone } from "./theme"
25
+
26
+ export function deployReleaseView({
27
+ release,
28
+ configPath,
29
+ }: {
30
+ release: DeployRelease
31
+ configPath: string
32
+ }): string {
33
+ const steps = [
34
+ { label: "build", commands: release.steps.build },
35
+ { label: "before start", commands: release.steps.beforeStart },
36
+ ]
37
+ const labelWidth =
38
+ Math.max(
39
+ ...release.services.map((service) => service.name.length),
40
+ ...steps.map((step) => step.label.length)
41
+ ) + 2
42
+ const originWidth = Math.max(
43
+ 0,
44
+ ...release.services.map((service) => service.http?.publicOrigin.length ?? 0)
45
+ )
46
+ const origins = new Set(
47
+ release.services.flatMap((service) => (service.http ? [service.http.publicOrigin] : []))
48
+ )
49
+ // The public origins already show beside their services; list only what the config set.
50
+ const env = Object.entries(release.env).filter(
51
+ ([key, value]) => !(key.endsWith("_PUBLIC_ORIGIN") && origins.has(value))
52
+ )
53
+ const continuation = " ".repeat(labelWidth)
54
+
55
+ const services = release.services.map((service) => {
56
+ const first = service.http
57
+ ? `${tone.url(service.http.publicOrigin)}${" ".repeat(originWidth - service.http.publicOrigin.length + 2)}${tone.muted(`${glyph.arrow} ${service.http.host}:${service.http.port}`)}`
58
+ : tone.muted(describeDeployProcess(service))
59
+ const extra = [
60
+ tone.faint(`$ ${formatDeployCommand(service.command)}`),
61
+ ...Object.entries(service.env)
62
+ .filter(([key, value]) => release.env[key] !== value)
63
+ .map(([key, value]) => tone.muted(`${key}=${value}`)),
64
+ ]
65
+ return [
66
+ `${pad(service.name, labelWidth)}${first}`,
67
+ ...extra.map((line) => `${continuation}${line}`),
68
+ ].join("\n")
69
+ })
70
+
71
+ return screen(
72
+ stack(
73
+ header("deploy --dry-run", release.name),
74
+ tone.muted(`${release.target.kind} ${release.target.location} ${glyph.dot} ${configPath}`)
75
+ ),
76
+ section("Services", services.join("\n")),
77
+ section(
78
+ "Steps",
79
+ steps
80
+ .map(
81
+ (step) =>
82
+ `${pad(step.label, labelWidth)}${step.commands
83
+ .map(formatDeployCommand)
84
+ .join(tone.faint(` ${glyph.arrow} `))}`
85
+ )
86
+ .join("\n")
87
+ ),
88
+ section(
89
+ "Environment",
90
+ stack(
91
+ ...env.map(([key, value]) => `${key}${tone.faint("=")}${value}`),
92
+ origins.size > 0 ? tone.muted("plus the public origins above") : null
93
+ )
94
+ ),
95
+ headline("idle", "Nothing was deployed", "--json prints the full release")
96
+ )
97
+ }
98
+
99
+ /** The plain line a finished step prints where there is no live view, and in CI logs. */
100
+ export function deployStepLine(label: string, seconds: string): string {
101
+ return `${tone.ok(glyph.ok)} ${label} ${tone.faint(`(${seconds}s)`)}`
102
+ }
103
+
104
+ /** How a deploy ended. What was deployed, and where, opened the deploy's output already. */
105
+ export function deployCompleteView({
106
+ release,
107
+ seconds,
108
+ }: {
109
+ release: DeployRelease
110
+ seconds?: number
111
+ }): string {
112
+ const urls = release.services.flatMap((service) =>
113
+ service.http ? [{ label: service.name, value: service.http.publicOrigin }] : []
114
+ )
115
+ return screen(
116
+ headline(
117
+ "ok",
118
+ `${release.name} deployed`,
119
+ seconds === undefined ? undefined : `${seconds.toFixed(1)}s`
120
+ ),
121
+ urls.length > 0 ? rows(urls) : null
122
+ )
123
+ }
124
+
125
+ export function deployStatusView({
126
+ name,
127
+ location,
128
+ status,
129
+ }: {
130
+ name: string
131
+ location: string
132
+ status: DeployStatus
133
+ }): string {
134
+ if (!status.release) {
135
+ return screen(
136
+ header("deploy status", name),
137
+ headline("idle", `Nothing is deployed on ${location} yet.`),
138
+ `${tone.faint("$")} ${tone.blue("sixb deploy")}`
139
+ )
140
+ }
141
+ const healthy =
142
+ status.running && status.processes.every((process) => process.status === "running")
143
+ const release = status.release
144
+ return screen(
145
+ header("deploy status", location),
146
+ status.processes.length > 0
147
+ ? table(
148
+ ["", "service", "pid", "cpu", "memory", "restarts", "up"],
149
+ status.processes.map((process) => [
150
+ process.status === "running" ? tone.blue(glyph.live) : tone.warn(glyph.idle),
151
+ process.instance === 0 ? process.service : `${process.service}#${process.instance}`,
152
+ process.pid === undefined ? "-" : String(process.pid),
153
+ process.cpuPercent === undefined ? "-" : `${process.cpuPercent.toFixed(1)}%`,
154
+ process.memoryBytes === undefined ? "-" : formatBytes(process.memoryBytes),
155
+ process.restarts > 0 ? tone.warn(String(process.restarts)) : String(process.restarts),
156
+ process.status === "running" && process.startedAt
157
+ ? formatAge(process.startedAt, "")
158
+ : tone.warn(process.status),
159
+ ])
160
+ )
161
+ : tone.muted("The supervisor is not running."),
162
+ stack(
163
+ ...status.processes
164
+ .filter((process) => process.lastError)
165
+ .map((process) =>
166
+ marked(tone.warn(glyph.warn), `${process.service}: ${process.lastError}`, tone.muted)
167
+ )
168
+ ) || null,
169
+ stack(
170
+ headline(
171
+ healthy ? "live" : "warn",
172
+ `${name} ${healthy ? "is running" : status.running ? "needs attention" : "is stopped"}`
173
+ ),
174
+ ` ${tone.muted(`${release.commit.slice(0, 12)} ${glyph.dot} ${release.ref} ${glyph.dot} deployed ${formatAge(release.deployedAt)} by ${release.deployedBy}`)}`
175
+ )
176
+ )
177
+ }
178
+
179
+ const CHECK_STATUS = {
180
+ ok: "ok",
181
+ fixable: "warn",
182
+ manual: "idle",
183
+ warning: "warn",
184
+ } as const satisfies Record<DeployCheck["status"], Status>
185
+
186
+ export function deployChecksView({
187
+ name,
188
+ location,
189
+ checks,
190
+ }: {
191
+ name: string
192
+ location: string
193
+ checks: readonly DeployCheck[]
194
+ }): string {
195
+ const blocking = checks.filter((check) => check.status === "fixable" || check.status === "manual")
196
+ const warnings = checks.filter((check) => check.status === "warning")
197
+ const next = blocking.some((check) => check.status === "fixable")
198
+ ? "sixb deploy setup"
199
+ : blocking.length > 0
200
+ ? "the steps above, then sixb deploy check"
201
+ : "sixb deploy"
202
+
203
+ return screen(
204
+ header("deploy check", location),
205
+ rows(
206
+ checks.map(
207
+ (check): Row => ({
208
+ label: check.label,
209
+ value: check.detail,
210
+ status: CHECK_STATUS[check.status],
211
+ ...(check.remedy ? { remedy: check.remedy } : {}),
212
+ })
213
+ )
214
+ ),
215
+ blocking.length > 0
216
+ ? headline("warn", `${name} · ${blocking.length} to fix before deploying`)
217
+ : headline(
218
+ "ok",
219
+ `${name} is ready to deploy`,
220
+ warnings.length > 0 ? `${warnings.length} to look at` : undefined
221
+ ),
222
+ nextStep(next)
223
+ )
224
+ }
225
+
226
+ export function deployCiView({
227
+ name,
228
+ repo,
229
+ environment,
230
+ branch,
231
+ credential,
232
+ secrets,
233
+ retired,
234
+ workflow,
235
+ token,
236
+ }: {
237
+ name: string
238
+ repo: string
239
+ environment: string
240
+ branch: string
241
+ credential: string
242
+ secrets: readonly string[]
243
+ retired: readonly DeployAccessKey[]
244
+ workflow: { readonly path: string; readonly state: "written" | "unchanged" | "kept" }
245
+ token: {
246
+ readonly name: string
247
+ readonly submodules: readonly {
248
+ readonly path: string
249
+ readonly url: string
250
+ readonly repo: string | null
251
+ }[]
252
+ } | null
253
+ }): string {
254
+ const items: Row[] = [
255
+ { label: "Key", status: "ok", value: credential },
256
+ { label: "Secrets", status: "ok", value: secrets.join(", ") },
257
+ {
258
+ label: "Older keys",
259
+ status: "ok",
260
+ value:
261
+ retired.length === 0
262
+ ? "none to revoke"
263
+ : `revoked ${retired.map((key) => key.fingerprint).join(", ")}`,
264
+ },
265
+ {
266
+ label: "Workflow",
267
+ status: "ok",
268
+ value: {
269
+ written: workflow.path,
270
+ unchanged: `${workflow.path} (unchanged)`,
271
+ kept: `${workflow.path} (yours, kept: it differs from what this command writes; delete it and run again to start over)`,
272
+ }[workflow.state],
273
+ },
274
+ ...(token
275
+ ? [
276
+ {
277
+ label: "Token",
278
+ status: "idle" as const,
279
+ value: `${token.submodules.map((submodule) => submodule.path).join(", ")} ${token.submodules.length === 1 ? "is" : "are"} private, and CI cannot read ${token.submodules.length === 1 ? "it" : "them"} with its own token.`,
280
+ remedy: `Create a fine-grained token with Contents: read on ${token.submodules.map((submodule) => submodule.repo ?? submodule.url).join(", ")}, then run \`gh secret set ${token.name} --env ${environment} --repo ${repo}\`.`,
281
+ },
282
+ ]
283
+ : []),
284
+ ]
285
+ const next =
286
+ workflow.state === "written"
287
+ ? `commit ${workflow.path} and push to ${branch}.`
288
+ : `push to ${branch} to deploy.`
289
+
290
+ return screen(
291
+ stack(header("deploy ci", repo), tone.muted(`environment ${environment}`)),
292
+ rows(items),
293
+ headline(
294
+ token ? "warn" : "ok",
295
+ `${name} deploys from GitHub Actions on every push to ${branch}`
296
+ ),
297
+ nextStep(next)
298
+ )
299
+ }
300
+
301
+ export function deployAccessView({
302
+ title,
303
+ keys,
304
+ }: {
305
+ title: string
306
+ keys: readonly DeployAccessKey[]
307
+ }): string {
308
+ // Two lines a key: a fingerprint and a long comment do not fit side by side in 80 columns.
309
+ const list =
310
+ keys.length === 0
311
+ ? tone.muted("No keys.")
312
+ : keys
313
+ .map((key) =>
314
+ stack(
315
+ `${key.comment || "(no comment)"}${key.restricted ? tone.warn(" restricted") : ""}`,
316
+ tone.muted(`${key.type} ${key.fingerprint}`)
317
+ )
318
+ )
319
+ .join("\n")
320
+ return screen(header(), list, headline("ok", title))
321
+ }
322
+
323
+ /** The one thing to do next: a command to run, or what to do in words. */
324
+ function nextStep(next: string): string {
325
+ return section("Next steps", next.startsWith("sixb ") ? commands([next]) : remedy(next))
326
+ }
327
+
328
+ function formatAge(iso: string, suffix = " ago"): string {
329
+ const seconds = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 1000))
330
+ const age =
331
+ seconds < 60
332
+ ? `${seconds}s`
333
+ : seconds < 3600
334
+ ? `${Math.floor(seconds / 60)}m`
335
+ : seconds < 86_400
336
+ ? `${Math.floor(seconds / 3600)}h`
337
+ : `${Math.floor(seconds / 86_400)}d`
338
+ return `${age}${suffix}`
339
+ }
340
+
341
+ function formatBytes(bytes: number): string {
342
+ if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)}G`
343
+ if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)}M`
344
+ return `${Math.round(bytes / 1024)}K`
345
+ }
346
+
347
+ function describeDeployProcess(service: DeployRelease["services"][number]): string {
348
+ const count = plural(service.instances, "process", "processes")
349
+ if (service.kind === "script") return `project script · ${count}`
350
+ // `worker-group` without worker types runs every type the project registers work for.
351
+ const namesWorkerTypes = service.command.args[1] && !service.command.args[1].startsWith("-")
352
+ if (service.kind === "workers" && !namesWorkerTypes) {
353
+ return `${count} · every worker type the project registers`
354
+ }
355
+ return count
356
+ }
357
+
358
+ function formatDeployCommand(command: DeployCommand): string {
359
+ return [command.program, ...command.args].join(" ")
360
+ }
@@ -0,0 +1,158 @@
1
+ import type { CliHelp } from "../lib/command-line"
2
+ import { errorMessage, errorRemediation } from "../lib/errors"
3
+ import { commandHelpView, errorView, helpView, versionView } from "./screens"
4
+ import { glyph, SPINNER_FRAMES, tone } from "./theme"
5
+
6
+ export * from "./deploy-screens"
7
+ export * from "./screens"
8
+
9
+ /**
10
+ * Writes a finished screen. Screens are plain strings, so nothing here loads a renderer: the
11
+ * live screens (`sixb dev`, a deploy in progress, prompts) live in `./live` and load on demand.
12
+ */
13
+ export async function renderStatic(view: string): Promise<void> {
14
+ process.stdout.write(view)
15
+ }
16
+
17
+ /**
18
+ * Renders a caught failure the one way the CLI renders failures, so a remediation carried on
19
+ * the error reaches the terminal without each caller remembering to pass it through.
20
+ */
21
+ export async function renderCliError(
22
+ error: unknown,
23
+ options: { readonly title?: string; readonly details?: readonly string[] } = {}
24
+ ): Promise<void> {
25
+ await renderStatic(cliErrorView(error, options))
26
+ }
27
+
28
+ /** The screen `renderCliError` prints, for a live view that ends with it. */
29
+ export function cliErrorView(
30
+ error: unknown,
31
+ options: { readonly title?: string; readonly details?: readonly string[] } = {}
32
+ ): string {
33
+ const remediation = errorRemediation(error)
34
+ return errorView({
35
+ ...(options.title ? { title: options.title } : {}),
36
+ message: errorMessage(error),
37
+ ...(remediation ? { remediation } : {}),
38
+ ...(options.details ? { details: options.details } : {}),
39
+ })
40
+ }
41
+
42
+ export async function renderVersion(version: string): Promise<void> {
43
+ await renderStatic(versionView(version))
44
+ }
45
+
46
+ /** Root or command help, after the usage error that led to it when there is one. */
47
+ export async function renderHelp(help: CliHelp, usageError?: string): Promise<void> {
48
+ await renderStatic(
49
+ help.path.length === 0
50
+ ? helpView({ errorMessage: usageError })
51
+ : commandHelpView({ help, errorMessage: usageError })
52
+ )
53
+ }
54
+
55
+ // ─── Tasks ───────────────────────────────────────────────────────────────────
56
+
57
+ export interface Task {
58
+ /** Says what the work is doing now. */
59
+ step(label: string): void
60
+ /** Clears the spinner. What was printed while it spun stays. */
61
+ stop(): void
62
+ }
63
+
64
+ /**
65
+ * A one-line spinner for work that takes a moment: `⠋ sixb check · Loading runtime`. Only a
66
+ * terminal sees it; a pipe or a CI log gets nothing, and the result screen that follows says what
67
+ * happened. Lines the work prints meanwhile land above the spinner, not inside it.
68
+ */
69
+ export function startTask(command: string, label: string): Task {
70
+ if (!process.stdout.isTTY || process.env.CI) return { step() {}, stop() {} }
71
+
72
+ let frame = 0
73
+ let current = label
74
+ let drawn = false
75
+ const line = () =>
76
+ ` ${tone.blue(SPINNER_FRAMES[frame % SPINNER_FRAMES.length] ?? glyph.mark)} ${tone.strong(`sixb ${command}`)} ${tone.muted(`${glyph.dot} ${current}`)}`
77
+ const write = process.stdout.write.bind(process.stdout)
78
+ const clear = () => {
79
+ if (drawn) write("\r\x1b[2K")
80
+ drawn = false
81
+ }
82
+ const draw = () => {
83
+ write(`\r\x1b[2K${line()}`)
84
+ drawn = true
85
+ }
86
+
87
+ // Output written while the spinner shows goes above it.
88
+ const consoleMethods = ["log", "info", "warn", "error", "debug"] as const
89
+ const originals = consoleMethods.map((method) => console[method])
90
+ consoleMethods.forEach((method, index) => {
91
+ const original = originals[index] as (...args: unknown[]) => void
92
+ console[method] = (...args: unknown[]) => {
93
+ clear()
94
+ original.apply(console, args)
95
+ draw()
96
+ }
97
+ })
98
+ const stderrWrite = process.stderr.write.bind(process.stderr)
99
+ const wrapWrite =
100
+ (target: typeof write) =>
101
+ (...args: Parameters<typeof write>): boolean => {
102
+ clear()
103
+ const result = target(...args)
104
+ draw()
105
+ return result
106
+ }
107
+ process.stdout.write = wrapWrite(write) as typeof process.stdout.write
108
+ process.stderr.write = wrapWrite(stderrWrite) as typeof process.stderr.write
109
+
110
+ write("\x1b[?25l")
111
+ const restoreCursor = () => write("\x1b[?25h")
112
+ process.once("exit", restoreCursor)
113
+ draw()
114
+ const timer = setInterval(() => {
115
+ frame += 1
116
+ draw()
117
+ }, 80)
118
+
119
+ let stopped = false
120
+ return {
121
+ step(next) {
122
+ current = next
123
+ if (!stopped) draw()
124
+ },
125
+ stop() {
126
+ if (stopped) return
127
+ stopped = true
128
+ clearInterval(timer)
129
+ clear()
130
+ process.stdout.write = write as typeof process.stdout.write
131
+ process.stderr.write = stderrWrite as typeof process.stderr.write
132
+ consoleMethods.forEach((method, index) => {
133
+ console[method] = originals[index] as (typeof console)[typeof method]
134
+ })
135
+ restoreCursor()
136
+ process.off("exit", restoreCursor)
137
+ },
138
+ }
139
+ }
140
+
141
+ /** Runs work behind a spinner, and clears it whether the work succeeds or throws. */
142
+ export async function withTask<T>(
143
+ command: string,
144
+ label: string,
145
+ work: (task: Task) => Promise<T>
146
+ ): Promise<T> {
147
+ const task = startTask(command, label)
148
+ try {
149
+ return await work(task)
150
+ } finally {
151
+ task.stop()
152
+ }
153
+ }
154
+
155
+ /** The line a long-running role prints as it begins to shut down. */
156
+ export function printStopping(command: string): void {
157
+ process.stdout.write(`\n ${tone.faint(glyph.idle)} ${tone.muted(`Stopping sixb ${command}…`)}\n`)
158
+ }