@yunuseon/kayra 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/dist/main.js CHANGED
@@ -2,20 +2,28 @@
2
2
  import { run } from "@optique/run";
3
3
  import { createInterface } from "node:readline/promises";
4
4
  import { existsSync, readFileSync } from "node:fs";
5
+ import { homedir } from "node:os";
5
6
  import { join, resolve } from "node:path";
6
7
  import { absolutePath, fleetRoot, kayraRoot, within } from "./brand.js";
7
8
  import { appCheck } from "./commands/app-check.js";
8
- import { parser } from "./cli.js";
9
- import { doctor } from "./commands/doctor.js";
10
- import * as server from "./commands/server.js";
11
- import { status } from "./commands/status.js";
12
- import { findings, report } from "./commands/validate.js";
9
+ import { parser, runOptions } from "./cli.js";
10
+ import { isDeployer, planFor } from "./commands/index.js";
11
+ import { verbose } from "./commands/server.js";
12
+ import { look, opentofu, statusJson, statusView } from "./commands/status.js";
13
+ import { findings, overall, validateJson, validateView } from "./commands/validate.js";
13
14
  import { gather } from "./gather.js";
14
- import { serverNamed } from "./fleet.js";
15
15
  import { interpret } from "./interpret.js";
16
16
  import { findFleetRoot, loadFleet } from "./load.js";
17
+ import { systemBrowser } from "./web/opener.js";
18
+ import { serveUi } from "./web/server.js";
19
+ import { network } from "./net.js";
17
20
  import { render } from "./plan.js";
18
- import { flatMap, ok } from "./result.js";
21
+ import { flatMap, map, ok } from "./result.js";
22
+ import { explain } from "./ui/explain.js";
23
+ import { bad, muted, paint, strong } from "./ui/line.js";
24
+ import { framed, silent } from "./ui/progress.js";
25
+ import { screen, settle, watch } from "./ui/terminal.js";
26
+ import { shortener, truncate } from "./ui/text.js";
19
27
  import { z } from "zod";
20
28
  const here = absolutePath(process.cwd());
21
29
  const engine = absolutePath(import.meta.dirname);
@@ -23,80 +31,75 @@ if (!here.ok || !engine.ok)
23
31
  throw new Error("node reported a relative path");
24
32
  const kayra = kayraRoot(within(engine.value, "..", ".."));
25
33
  const version = z.object({ version: z.string() }).parse(JSON.parse(readFileSync(join(kayra, "package.json"), "utf8"))).version;
26
- const appKinds = { "app runs": "runs", "app logs": "logs", "app deploy": "deploy", "app rollback": "rollback" };
27
- const isDeployer = (command) => command.name === "job" || command.name in appKinds;
28
- const deployerCommand = (command) => command.name === "job"
29
- ? { kind: "job", job: command.job, noPrs: command.noPrs }
30
- : { kind: appKinds[command.name], app: command.app, more: "more" in command ? command.more : undefined };
31
- const onServer = (on, target, command) => {
32
- switch (command.name) {
33
- case "up":
34
- return server.up(on, target);
35
- case "provision":
36
- return server.provision(on, target);
37
- case "deploy":
38
- return server.deploy(on, target);
39
- case "setup":
40
- return server.setup(on, target);
41
- case "plan":
42
- return server.preview(on, target);
43
- case "verify":
44
- return server.verify(on, target);
45
- case "apps":
46
- return server.apps(on, target);
47
- case "hosts":
48
- return server.hosts(on, target);
49
- case "ssh":
50
- return server.ssh(target, command.remote);
51
- case "down":
52
- return server.down(on, target);
53
- case "adopt":
54
- return server.adopt(on, target);
55
- case "backup test":
56
- return server.backupTest(on, target);
57
- }
58
- };
59
- const plan = (fleet, command) => {
60
- const on = { kayra, fleet: fleet.root };
61
- if (command.name === "doctor")
62
- return ok(doctor(fleet, kayra));
63
- if (command.name === "certs")
64
- return server.certsFor(on, command.domain, command.subdomains);
65
- if (command.name === "app purge")
66
- return flatMap(serverNamed(fleet, command.server), (target) => server.appPurge(on, target, command.app));
67
- if (isDeployer(command)) {
68
- const deployerArgs = deployerCommand(command);
69
- return flatMap(serverNamed(fleet, command.server), (target) => server.deployer(target, deployerArgs));
70
- }
71
- return flatMap(serverNamed(fleet, command.server), (target) => onServer(on, target, command));
72
- };
34
+ const screens = { out: screen(process.stdout, process.env), err: screen(process.stderr, process.env) };
73
35
  const io = {
74
- out: (line) => {
75
- console.log(line);
36
+ out: (text) => {
37
+ console.log(paint(text, screens.out.colors, screens.out.links));
76
38
  },
77
- err: (line) => {
78
- console.error(line);
39
+ err: (text) => {
40
+ console.error(paint(text, screens.err.colors, screens.err.links));
79
41
  },
80
42
  ask: async (prompt) => {
81
43
  const terminal = createInterface({ input: process.stdin, output: process.stderr });
82
- const answer = await terminal.question(prompt);
44
+ // Ctrl-C at the prompt, or no more input: no answer, so nothing happens.
45
+ const answer = await new Promise((resolve) => {
46
+ terminal.once("SIGINT", () => {
47
+ resolve("");
48
+ });
49
+ terminal.once("close", () => {
50
+ resolve("");
51
+ });
52
+ void terminal.question(paint(prompt, screens.err.colors)).then(resolve, () => {
53
+ resolve("");
54
+ });
55
+ });
83
56
  terminal.close();
84
57
  return answer;
85
58
  },
86
59
  };
87
60
  const fail = (message) => {
88
- console.error(`kayra: ${message}`);
61
+ io.err(screens.err.live ? [bad("✗"), " ", message] : `kayra: ${message}`);
89
62
  process.exit(1);
90
63
  };
64
+ /** The heading's facts: what the server is, and which kayra runs. */
65
+ const invocation = (target) => ({
66
+ command: ["kayra", ...process.argv.slice(2).filter((word) => word !== "--dry-run")].join(" "),
67
+ ...(target === undefined ? {} : { server: target.name }),
68
+ about: [...(target === undefined ? [] : [`${target.kind} on ${target.target}`, target.domain]), `kayra ${version}`],
69
+ });
70
+ /** --dry-run: the plan as data, styled on a terminal, plain and copyable for a program. */
71
+ const show = (steps, about, short) => {
72
+ (screens.out.live ? explain(about, steps, short, screens.out.columns) : render(steps)).forEach(io.out);
73
+ };
74
+ /** Runs a plan, framed on stderr unless its output is the point; the exit status says how it went. */
75
+ const execute = async (steps, about, framing) => {
76
+ const interrupt = new AbortController();
77
+ // Ctrl-C reaches the step's program too; the plan stops once it gives up. A second one does not wait.
78
+ process.once("SIGINT", () => {
79
+ interrupt.abort();
80
+ process.once("SIGINT", () => process.exit(130));
81
+ });
82
+ const progress = framing
83
+ ? framed(screens.err, (raw) => process.stderr.write(raw), about)
84
+ : silent;
85
+ const passed = await interpret(steps, io, progress, () => interrupt.signal.aborted);
86
+ // eslint-disable-next-line functional/immutable-data -- the exit status; process.exit() could cut piped output short
87
+ process.exitCode = interrupt.signal.aborted ? 130 : passed ? 0 : 1;
88
+ };
91
89
  const found = flatMap(findFleetRoot(here.value), loadFleet);
92
90
  // Outside a fleet only `app check` runs: it works in an app's repository.
93
91
  const fleet = found.ok ? found : ok({ root: fleetRoot(here.value), servers: [] });
94
92
  if (!fleet.ok)
95
93
  fail(fleet.error);
96
94
  else {
97
- const args = run(parser(fleet.value), { programName: "kayra", help: "both", completion: "both", version: { value: version, command: true, option: true } });
95
+ const args = run(parser(fleet.value), runOptions(version));
98
96
  if (!found.ok && args.command.name !== "app check")
99
97
  fail(found.error);
98
+ const short = shortener([
99
+ [kayra, "<kayra>"],
100
+ ...(found.ok ? [[fleet.value.root, "<fleet>"]] : []),
101
+ [homedir(), "~"],
102
+ ]);
100
103
  if (args.command.name === "app check") {
101
104
  const root = absolutePath(resolve(here.value, args.command.dir ?? "."));
102
105
  const manifestPath = root.ok ? join(root.value, "app.yml") : "";
@@ -104,32 +107,54 @@ else {
104
107
  if (!steps.ok)
105
108
  fail(steps.error);
106
109
  else if (args.dryRun)
107
- render(steps.value).forEach(io.out);
108
- // eslint-disable-next-line functional/immutable-data -- the exit status; process.exit() could cut piped output short
110
+ show(steps.value, invocation(undefined), short);
109
111
  else
110
- process.exitCode = (await interpret(steps.value, io)) ? 0 : 1;
112
+ await execute(steps.value, invocation(undefined), true);
111
113
  }
112
114
  else if (args.command.name === "status") {
113
- (await status(fleet.value)).forEach(io.out);
115
+ const { json, offline } = args.command;
116
+ const { initial, updates } = look(fleet.value, opentofu, offline ? undefined : network(2_000));
117
+ // On a terminal the table is there at once, its cells filled in as the answers arrive; the report itself goes to stdout.
118
+ const draw = (looks, frame) => statusView(looks, { frame, room: screens.err.columns - 1, offline }).map((line) => paint(truncate(line, screens.err.columns - 1), screens.err.colors));
119
+ const looks = !json && screens.out.live && screens.err.live
120
+ ? await watch((raw) => process.stderr.write(raw), initial, updates, draw)
121
+ : await settle(initial, updates);
122
+ (json
123
+ ? [JSON.stringify(statusJson(looks), null, 2)]
124
+ : statusView(looks, { frame: "", room: screens.out.live ? screens.out.columns : Infinity, offline })).forEach(io.out);
125
+ }
126
+ else if (args.command.name === "ui") {
127
+ // The browser side: web/dist in a checkout, cli/dist/web in the package.
128
+ const assets = [join(kayra, "web", "dist"), join(kayra, "cli", "dist", "web")].find((dir) => existsSync(join(dir, "index.html")));
129
+ const { port, noOpen } = args.command;
130
+ const listening = await serveUi({ kayra, fleet: fleet.value, version, assets, short, network: network(2_000) }, port);
131
+ io.err([strong("kayra ui"), muted(` · ${fleet.value.servers.length.toString()} servers · kayra ${version} · Ctrl-C stops it`)]);
132
+ io.out(listening.url);
133
+ if (!noOpen)
134
+ systemBrowser.open(listening.url);
135
+ process.once("SIGINT", () => {
136
+ void listening.close().then(() => process.exit(0));
137
+ });
114
138
  }
115
139
  else if (args.command.name === "validate") {
116
- const chosen = args.command.server;
140
+ const { server: chosen, json } = args.command;
117
141
  const servers = fleet.value.servers.filter((each) => chosen === undefined || each.name === chosen);
118
- const reports = await Promise.all(servers.map(async (each) => findings(await gather(fleet.value.root, each))));
119
- reports.forEach((found, index) => {
120
- report(servers[index]?.name ?? "", found).forEach(io.out);
121
- });
142
+ const reports = await Promise.all(servers.map(async (each) => ({ server: each, findings: findings(await gather(fleet.value.root, each)) })));
143
+ (json ? [JSON.stringify(validateJson(reports), null, 2)] : validateView(reports)).forEach(io.out);
122
144
  // eslint-disable-next-line functional/immutable-data -- the exit status; process.exit() could cut piped output short
123
- process.exitCode = reports.some((found) => found.some((each) => each.problem)) ? 1 : 0;
145
+ process.exitCode = reports.some((each) => overall(each.findings) === "problem") ? 1 : 0;
124
146
  }
125
147
  else {
126
- const steps = plan(fleet.value, args.command);
148
+ const { command } = args;
149
+ const steps = map(planFor({ kayra, fleet: fleet.value.root }, fleet.value, command), (each) => (args.verbose ? verbose(each) : each));
150
+ const target = "server" in command ? fleet.value.servers.find((each) => each.name === command.server) : undefined;
151
+ // ssh and the deployer's answers are the output itself: nothing around them.
152
+ const framing = command.name !== "ssh" && !isDeployer(command);
127
153
  if (!steps.ok)
128
154
  fail(steps.error);
129
155
  else if (args.dryRun)
130
- render(steps.value).forEach(io.out);
131
- // eslint-disable-next-line functional/immutable-data -- the exit status; process.exit() could cut piped output short
156
+ show(steps.value, invocation(target), short);
132
157
  else
133
- process.exitCode = (await interpret(steps.value, io)) ? 0 : 1;
158
+ await execute(steps.value, invocation(target), framing);
134
159
  }
135
160
  }
@@ -0,0 +1,52 @@
1
+ import { Agent, request } from "node:https";
2
+ import { connect } from "node:net";
3
+ import { getCACertificates } from "node:tls";
4
+ import { failure } from "./commands/status.js";
5
+ const codeOf = (error) => typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "ERROR";
6
+ const since = (started) => Math.round(performance.now() - started);
7
+ /** The network, as status asks it: a TCP connect, an HTTPS GET, each given up after `ms`; every answer a Reach, never an exception. */
8
+ export const network = (ms) => {
9
+ // A multipass server's certificates are mkcert's, whose root is in the system's store, not Node's.
10
+ // Reading it takes a while: after the first frame, not before.
11
+ const agent = new Promise((resolve) => {
12
+ setImmediate(() => {
13
+ resolve(new Agent({ ca: [...new Set([...getCACertificates("default"), ...getCACertificates("system")])] }));
14
+ });
15
+ });
16
+ return {
17
+ connect: (host, port) => new Promise((resolve) => {
18
+ const started = performance.now();
19
+ const socket = connect({ host, port, timeout: ms });
20
+ socket.once("connect", () => {
21
+ socket.destroy();
22
+ resolve({ kind: "open", ms: since(started) });
23
+ });
24
+ socket.once("timeout", () => {
25
+ socket.destroy();
26
+ resolve({ kind: "no-answer" });
27
+ });
28
+ socket.once("error", (error) => {
29
+ resolve(failure(codeOf(error)));
30
+ });
31
+ }),
32
+ get: async (url) => {
33
+ const via = await agent;
34
+ return new Promise((resolve) => {
35
+ const started = performance.now();
36
+ const asked = request(url, { agent: via, timeout: ms }, (response) => {
37
+ response.resume();
38
+ resolve({ kind: "answered", status: response.statusCode ?? 0, ms: since(started) });
39
+ asked.destroy();
40
+ });
41
+ asked.once("timeout", () => {
42
+ asked.destroy();
43
+ resolve({ kind: "no-answer" });
44
+ });
45
+ asked.once("error", (error) => {
46
+ resolve(failure(codeOf(error)));
47
+ });
48
+ asked.end();
49
+ });
50
+ },
51
+ };
52
+ };
package/cli/dist/plan.js CHANGED
@@ -1,5 +1,6 @@
1
- export const run = (argv, env = {}) => ({
1
+ export const run = (title, argv, env = {}) => ({
2
2
  kind: "run",
3
+ title,
3
4
  argv,
4
5
  env,
5
6
  stdout: "show",
@@ -16,16 +17,48 @@ const arg = (value) => {
16
17
  return value.words === "one" ? `"${command}"` : command;
17
18
  };
18
19
  const describeProbe = (probe) => probe.kind === "on-path" ? `command -v ${quote(probe.program)}` : assignments(probe.env) + shell(probe.argv);
20
+ /** Every step of a plan as part of one kayra command. */
21
+ export const partOf = (part, plan) => plan.map((step) => ({ ...step, part }));
22
+ /** guard, check, run, confirm or note: what kind of step it is, as --dry-run says. */
23
+ export const kindOf = (step) => (step.kind === "check" ? (step.onFailure === "stop" ? "guard" : "check") : step.kind);
24
+ /** What it is called while it runs; a confirmation and a note say what they say. */
25
+ export const titleOf = (step) => {
26
+ switch (step.kind) {
27
+ case "run":
28
+ return step.title;
29
+ case "check":
30
+ return step.label;
31
+ case "confirm":
32
+ return step.warning;
33
+ case "note":
34
+ return step.text;
35
+ }
36
+ };
37
+ /** The shell command a step runs, or undefined if it runs none. */
38
+ export const commandOf = (step) => {
39
+ switch (step.kind) {
40
+ case "run":
41
+ return `${assignments(step.env)}${step.argv.map(arg).join(" ")}${step.stdout === "discard" ? " >/dev/null" : ""}`;
42
+ case "check":
43
+ return describeProbe(step.probe);
44
+ case "confirm":
45
+ case "note":
46
+ return undefined;
47
+ }
48
+ };
19
49
  const describe = (step) => {
20
50
  switch (step.kind) {
21
51
  case "run":
22
- return `run ${assignments(step.env)}${step.argv.map(arg).join(" ")}${step.stdout === "discard" ? " >/dev/null" : ""}`;
52
+ return `run ${commandOf(step) ?? ""}`;
23
53
  case "check":
24
- return `${step.onFailure === "stop" ? "guard " : "check "} ${step.label}: ${describeProbe(step.probe)}`;
54
+ return `${kindOf(step).padEnd(8)} ${step.label}: ${commandOf(step) ?? ""}`;
25
55
  case "confirm":
26
- return `confirm ${step.prompt}(${step.expect})`;
56
+ return `confirm ${step.warning} (${step.expect})`;
27
57
  case "note":
28
58
  return `note ${step.text}`;
29
59
  }
30
60
  };
61
+ /** The plan as plain lines: --dry-run's output where it is read by a program. */
31
62
  export const render = (plan) => plan.map(describe);
63
+ /** A plan with a step that asks on the terminal (the vault password, typed): it cannot run without one. */
64
+ export const needsTerminal = (plan) => plan.some((step) => step.kind === "run" && step.env["ANSIBLE_ASK_VAULT_PASS"] === "True");
@@ -0,0 +1,37 @@
1
+ import { commandOf, kindOf, titleOf } from "../plan.js";
2
+ import { accent, active, bad, muted, strong, warn } from "./line.js";
3
+ import { position, steps as count } from "./progress.js";
4
+ import { wrap } from "./text.js";
5
+ import { drawnAs } from "./views.js";
6
+ const kinds = { guard: warn, check: active, run: active, confirm: bad, note: muted };
7
+ const tag = (step) => {
8
+ const kind = kindOf(step);
9
+ return (kinds[kind] ?? muted)(kind.padEnd(7));
10
+ };
11
+ /**
12
+ * --dry-run on a terminal: each step numbered, with its title and, below it, the
13
+ * command it runs. `short` names paths by their root (<kayra>, <fleet>, ~), so a
14
+ * command fits on a line or two; render() is the plain, copyable form.
15
+ */
16
+ export const explain = (invocation, plan, short, columns) => {
17
+ const digits = String(plan.length).length;
18
+ const indent = " ".repeat(digits + 13);
19
+ const steps = plan.flatMap((step, index) => {
20
+ const { opens } = position(plan, index);
21
+ const command = commandOf(step);
22
+ return [
23
+ ...(opens === undefined ? [] : index === 0 ? [[accent(opens)]] : [[], [accent(opens)]]),
24
+ [" ", muted(String(index + 1).padStart(digits)), " ", tag(step), " ", strong(titleOf(step))],
25
+ ...(step.kind === "confirm" ? [[indent, muted(`asks for '${step.expect}' to be typed, or stops`)]] : []),
26
+ ...(command === undefined
27
+ ? []
28
+ : wrap(short(command).split(" "), Math.max(40, Math.min(columns, 120) - indent.length - 2)).map((line, at) => [indent, muted(at === 0 ? line : ` ${line}`)])),
29
+ ...(step.kind === "run" && typeof step.stdout === "object" ? [[indent, muted(`→ ${drawnAs(step.stdout)}`)]] : []),
30
+ ];
31
+ });
32
+ return [
33
+ [strong(invocation.command), muted([...invocation.about, count(plan), "dry run: nothing runs"].map((each) => ` · ${each}`).join(""))],
34
+ [],
35
+ ...steps,
36
+ ];
37
+ };
@@ -0,0 +1,39 @@
1
+ import { styleText } from "node:util";
2
+ import { escapes } from "./terminal.js";
3
+ const toned = (tone) => (text) => ({ tone, text });
4
+ export const ok = toned("ok");
5
+ export const bad = toned("bad");
6
+ export const warn = toned("warn");
7
+ export const active = toned("active");
8
+ export const muted = toned("muted");
9
+ export const strong = toned("strong");
10
+ export const accent = toned("accent");
11
+ export const link = (text, href, tone) => ({ text, href, ...(tone === undefined ? {} : { tone }) });
12
+ const looks = {
13
+ ok: ["green"],
14
+ bad: ["red"],
15
+ warn: ["yellow"],
16
+ active: ["cyan"],
17
+ muted: ["dim"],
18
+ strong: ["bold"],
19
+ accent: ["magenta", "bold"],
20
+ };
21
+ const spans = (text) => (typeof text === "string" ? [text] : text);
22
+ const textOf = (span) => (typeof span === "string" ? span : span.text);
23
+ export const flat = (text) => spans(text).map(textOf).join("");
24
+ const graphemes = new Intl.Segmenter();
25
+ /** A string's characters as a reader counts them. */
26
+ export const characters = (text) => Array.from(graphemes.segment(text), (each) => each.segment);
27
+ /** Columns it takes: one per character, which holds for everything kayra writes itself. */
28
+ export const width = (text) => characters(flat(text)).length;
29
+ export const paint = (text, colors, links = false) => spans(text)
30
+ .map((span) => {
31
+ if (typeof span === "string")
32
+ return span;
33
+ const { tone, href } = span;
34
+ const styled = colors && tone !== undefined
35
+ ? looks[tone].reduce((so, format) => styleText(format, so, { validateStream: false }), span.text)
36
+ : span.text;
37
+ return links && href !== undefined ? escapes.link(styled, href) : styled;
38
+ })
39
+ .join("");
@@ -0,0 +1,144 @@
1
+ import { commandOf, kindOf, titleOf } from "../plan.js";
2
+ import { accent, active, bad, muted, ok, paint, strong, warn } from "./line.js";
3
+ import { escapes, spinner } from "./terminal.js";
4
+ import { duration, spread, truncate } from "./text.js";
5
+ /** Nothing around the steps: for commands whose output is the point (ssh, logs), and for tests. */
6
+ export const silent = {
7
+ plan: (_plan, work) => work(),
8
+ step: (_step, _at, work) => work(),
9
+ };
10
+ const parts = (plan) => [...new Set(plan.flatMap((step) => (step.part === undefined ? [] : [step.part])))];
11
+ /** Where the step at `index` is, for a plan that may consist of several parts. */
12
+ export const position = (plan, index) => {
13
+ const part = plan[index]?.part;
14
+ const opens = part !== undefined && parts(plan).length > 1 && plan[index - 1]?.part !== part;
15
+ return { index, total: plan.length, ...(opens ? { opens: part } : {}) };
16
+ };
17
+ /** A run of this long earns a notification when it ends: the operator has looked away. */
18
+ const worthNotifying = 30_000;
19
+ /** "8 steps", or "15 checks" for a plan of nothing else (doctor). */
20
+ export const steps = (plan) => {
21
+ const noun = plan.every((step) => step.kind === "check") ? "check" : "step";
22
+ return `${String(plan.length)} ${noun}${plan.length === 1 ? "" : "s"}`;
23
+ };
24
+ /** The footer: how it went, how long it took, and what reruns a failed part alone. */
25
+ export const footer = (invocation, plan, ended, ms) => {
26
+ const took = duration(ms);
27
+ const { command } = invocation;
28
+ const { stop } = ended;
29
+ if (stop === undefined)
30
+ return ended.failures === 0
31
+ ? [[ok("✓"), " ", strong(command), muted(` · ${steps(plan)} · ${took}`)]]
32
+ : [[bad("✗"), " ", strong(command), muted(` · ${String(ended.failures)} of ${steps(plan)} failed · ${took}`)]];
33
+ const where = `step ${String(stop.index + 1)} of ${String(plan.length)}`;
34
+ if (stop.why === "declined")
35
+ return [[warn("■"), " ", strong(command), muted(` stopped at ${where}: not confirmed`)]];
36
+ if (stop.why === "interrupted")
37
+ return [[warn("■"), " ", strong(command), muted(` interrupted at ${where} · ${took}`)]];
38
+ const { part } = stop.step;
39
+ const alone = part !== undefined && parts(plan).length > 1 && invocation.server !== undefined;
40
+ return [
41
+ [bad("✗"), " ", strong(command), " failed at ", strong(titleOf(stop.step)), muted(` · ${where} · ${took}`)],
42
+ ...(alone ? [[" ", active("→"), " ", strong(`kayra ${part} ${invocation.server ?? ""}`), muted(" runs just this part")]] : []),
43
+ ];
44
+ };
45
+ /** Frames on stderr: a heading, each step as it runs and how it went, a footer; on a terminal also spinners, the window title, a notification. */
46
+ export const framed = (screen, write, invocation) => {
47
+ const columns = Math.min(screen.columns, 80);
48
+ const say = (text) => {
49
+ write(`${paint(text, screen.colors)}\n`);
50
+ };
51
+ const tell = (raw, when) => {
52
+ if (when)
53
+ write(raw);
54
+ };
55
+ return {
56
+ plan: async (plan, work) => {
57
+ const started = performance.now();
58
+ tell(escapes.pushTitle + escapes.title(invocation.command), screen.title);
59
+ say([strong(invocation.command), muted([...invocation.about, steps(plan)].map((each) => ` · ${each}`).join(""))]);
60
+ say("");
61
+ const ended = await work();
62
+ const ms = performance.now() - started;
63
+ say("");
64
+ footer(invocation, plan, ended, ms).forEach(say);
65
+ tell(escapes.popTitle, screen.title);
66
+ tell(escapes.progressDone, screen.progressBar);
67
+ const failed = ended.failures > 0 || ended.stop?.why === "failed";
68
+ tell(escapes.notify(`${invocation.command} ${failed ? "failed" : "is done"} after ${duration(ms)}`), screen.notifications && ms >= worthNotifying);
69
+ return ended;
70
+ },
71
+ step: async (step, at, work) => {
72
+ if (step.kind === "confirm" || step.kind === "note")
73
+ return work();
74
+ if (at.opens !== undefined) {
75
+ if (at.index > 0)
76
+ say("");
77
+ say([accent(at.opens)]);
78
+ }
79
+ const title = titleOf(step);
80
+ const counter = `${String(at.index + 1)}/${String(at.total)}`;
81
+ tell(escapes.title(`${invocation.command} · ${counter} ${title}`), screen.title);
82
+ tell(escapes.progress((at.index / at.total) * 100), screen.progressBar);
83
+ const shown = step.kind === "run" && step.stdout === "show";
84
+ if (shown)
85
+ say(spread([" ", active("◆"), " ", strong(title)], [muted(counter)], columns));
86
+ const stop = !shown && screen.live
87
+ ? spinner(write, (frame, ms) => paint(spread(truncate([" ", active(frame), " ", title], columns - 8), [muted(duration(ms))], columns), screen.colors))
88
+ : () => undefined;
89
+ const started = performance.now();
90
+ const done = await work();
91
+ stop();
92
+ // A diagnosis reports itself on stdout: that line is doctor's output.
93
+ if (step.kind === "check" && step.onFailure === "continue")
94
+ return done;
95
+ const took = duration(performance.now() - started);
96
+ say(spread([" ", done.failed ? bad("✗") : ok("✓"), " ", title], [muted(done.why === undefined ? took : `${done.why} · ${took}`)], columns));
97
+ return done;
98
+ },
99
+ };
100
+ };
101
+ /** Every step of a plan, its command's paths named by their root. */
102
+ export const listed = (plan, short) => plan.map((step, index) => {
103
+ const command = commandOf(step);
104
+ const { opens } = position(plan, index);
105
+ return {
106
+ index,
107
+ kind: kindOf(step),
108
+ title: titleOf(step),
109
+ ...(command === undefined ? {} : { command: short(command) }),
110
+ ...(step.part === undefined ? {} : { part: step.part }),
111
+ ...(opens === undefined ? {} : { opens }),
112
+ };
113
+ });
114
+ /** The plan and each step as events: what framed draws on a terminal, as data. */
115
+ export const reporting = (emit, invocation, short) => ({
116
+ plan: async (plan, work) => {
117
+ const started = performance.now();
118
+ emit({ kind: "plan", invocation, steps: listed(plan, short) });
119
+ const ended = await work();
120
+ const ms = performance.now() - started;
121
+ emit({
122
+ kind: "ended",
123
+ failures: ended.failures,
124
+ ...(ended.stop === undefined ? {} : { stop: { index: ended.stop.index, why: ended.stop.why } }),
125
+ ms,
126
+ footer: footer(invocation, plan, ended, ms),
127
+ });
128
+ return ended;
129
+ },
130
+ step: async (_step, at, work) => {
131
+ const started = performance.now();
132
+ emit({ kind: "started", index: at.index });
133
+ const done = await work();
134
+ emit({
135
+ kind: "done",
136
+ index: at.index,
137
+ failed: done.failed,
138
+ stopped: done.stopped,
139
+ ...(done.why === undefined ? {} : { why: done.why }),
140
+ ms: performance.now() - started,
141
+ });
142
+ return done;
143
+ },
144
+ });