@yunuseon/kayra 0.17.0 → 0.17.2

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 (113) hide show
  1. package/agent/skills/kayra-release/SKILL.md +6 -1
  2. package/ansible/roles/platform/tasks/main.yml +40 -1
  3. package/cli/dist/browser/assets/index-hcyM6f6T.js +7 -0
  4. package/cli/dist/browser/index.html +1 -1
  5. package/cli/dist/clients/api/api.js +138 -218
  6. package/cli/dist/clients/api/auth.js +8 -7
  7. package/cli/dist/clients/api/commands.js +50 -14
  8. package/cli/dist/clients/api/contract.js +8 -6
  9. package/cli/dist/clients/api/directories.js +1 -1
  10. package/cli/dist/clients/api/discovery.js +8 -3
  11. package/cli/dist/clients/api/live.js +40 -0
  12. package/cli/dist/clients/api/protocol.js +17 -10
  13. package/cli/dist/clients/api/queries.js +4 -4
  14. package/cli/dist/clients/api/runs.js +10 -9
  15. package/cli/dist/clients/api/start.js +97 -0
  16. package/cli/dist/clients/api/status.js +29 -0
  17. package/cli/dist/clients/api/validate.js +13 -0
  18. package/cli/dist/clients/cli/explain.js +12 -10
  19. package/cli/dist/clients/cli/framed.js +12 -9
  20. package/cli/dist/clients/cli/invocation.js +4 -3
  21. package/cli/dist/clients/cli/paint.js +1 -1
  22. package/cli/dist/clients/cli/parser.js +8 -8
  23. package/cli/dist/clients/cli/questions.js +11 -10
  24. package/cli/dist/clients/cli/status.js +75 -0
  25. package/cli/dist/clients/cli/terminal.js +4 -2
  26. package/cli/dist/{core/present → clients/cli}/text.js +15 -24
  27. package/cli/dist/clients/cli/validate.js +32 -0
  28. package/cli/dist/clients/cli/values.js +19 -0
  29. package/cli/dist/{core/present → clients/cli}/views.js +28 -60
  30. package/cli/dist/core/adapters/fs.js +18 -0
  31. package/cli/dist/core/{net.js → adapters/network.js} +20 -5
  32. package/cli/dist/core/adapters/opentofu.js +24 -0
  33. package/cli/dist/core/ctl/answers.js +32 -0
  34. package/cli/dist/core/fleet/brand.js +54 -0
  35. package/cli/dist/core/{schemas.js → fleet/docs.js} +5 -4
  36. package/cli/dist/core/fleet/load.js +45 -0
  37. package/cli/dist/core/fleet/model.js +1 -0
  38. package/cli/dist/core/fleet/parse.js +144 -0
  39. package/cli/dist/core/{settings.js → fleet/settings.js} +47 -15
  40. package/cli/dist/core/{validate.js → fleet/shape.js} +6 -20
  41. package/cli/dist/core/{present/progress.js → interpreter/events.js} +27 -31
  42. package/cli/dist/core/interpreter/io.js +18 -0
  43. package/cli/dist/core/interpreter/loop.js +101 -0
  44. package/cli/dist/core/interpreter/needs.js +47 -0
  45. package/cli/dist/core/interpreter/process.js +107 -0
  46. package/cli/dist/core/interpreter/progress.js +15 -0
  47. package/cli/dist/core/interpreter/pty.js +8 -0
  48. package/cli/dist/core/operations/catalog.js +35 -18
  49. package/cli/dist/core/operations/{run.js → dispatch.js} +50 -47
  50. package/cli/dist/core/{plan.js → plan/describe.js} +4 -14
  51. package/cli/dist/core/plan/model.js +14 -0
  52. package/cli/dist/core/recipes/app-check.js +27 -0
  53. package/cli/dist/core/recipes/apps.js +63 -0
  54. package/cli/dist/core/recipes/backup.js +34 -0
  55. package/cli/dist/core/recipes/certs.js +4 -0
  56. package/cli/dist/core/{commands → recipes}/doctor.js +20 -35
  57. package/cli/dist/core/recipes/host.js +104 -0
  58. package/cli/dist/core/recipes/ssh.js +20 -0
  59. package/cli/dist/core/recipes/steps.js +82 -0
  60. package/cli/dist/core/status/look.js +55 -0
  61. package/cli/dist/core/status/model.js +6 -0
  62. package/cli/dist/core/status/ports.js +1 -0
  63. package/cli/dist/core/text/plural.js +2 -0
  64. package/cli/dist/core/text/spans.js +22 -0
  65. package/cli/dist/core/text/time.js +12 -0
  66. package/cli/dist/core/validation/facts.js +50 -0
  67. package/cli/dist/core/{commands/validate.js → validation/findings.js} +31 -66
  68. package/cli/dist/deployer/app.js +3 -2
  69. package/cli/dist/deployer/brand.js +1 -1
  70. package/cli/dist/deployer/{builder.js → build/builder.js} +14 -13
  71. package/cli/dist/deployer/{bundle.js → build/bundle.js} +8 -7
  72. package/cli/dist/deployer/{compose.js → build/compose.js} +8 -7
  73. package/cli/dist/deployer/cron.js +3 -3
  74. package/cli/dist/deployer/{answers.js → ctl/answers.js} +5 -4
  75. package/cli/dist/deployer/{ctl.js → ctl/ctl.js} +3 -3
  76. package/cli/dist/deployer/deployer.js +24 -23
  77. package/cli/dist/deployer/{forge.js → forges/forge.js} +2 -1
  78. package/cli/dist/deployer/{forgejo.js → forges/forgejo.js} +2 -2
  79. package/cli/dist/deployer/{github.js → forges/github.js} +2 -2
  80. package/cli/dist/deployer/{gitlab.js → forges/gitlab.js} +2 -2
  81. package/cli/dist/deployer/{github-issues.js → forges/issues.js} +5 -4
  82. package/cli/dist/deployer/{notify.js → forges/notify.js} +9 -8
  83. package/cli/dist/deployer/{http.js → http/http.js} +1 -0
  84. package/cli/dist/deployer/{page.js → http/page.js} +1 -1
  85. package/cli/dist/deployer/{webhook.js → http/webhook.js} +2 -1
  86. package/cli/dist/deployer/main.js +2 -2
  87. package/cli/dist/deployer/{queue.js → runs/queue.js} +4 -3
  88. package/cli/dist/deployer/{records.js → runs/records.js} +9 -8
  89. package/cli/dist/deployer/{run.js → runs/run.js} +10 -9
  90. package/cli/dist/deployer/{store.js → runs/store.js} +9 -8
  91. package/cli/dist/lib/brand.js +2 -0
  92. package/cli/dist/lib/closest.js +17 -0
  93. package/cli/dist/lib/result.js +15 -0
  94. package/cli/dist/lib/schema.js +7 -0
  95. package/cli/dist/lib/typed.js +2 -0
  96. package/cli/dist/lib/yaml.js +21 -0
  97. package/cli/dist/main.js +89 -89
  98. package/cli/dist/serve.js +2 -2
  99. package/package.json +3 -2
  100. package/schema/app.json +4 -2
  101. package/schema/server.json +10 -5
  102. package/cli/dist/browser/assets/index-9a-SE2rU.js +0 -7
  103. package/cli/dist/core/brand.js +0 -39
  104. package/cli/dist/core/commands/app-check.js +0 -35
  105. package/cli/dist/core/commands/server.js +0 -298
  106. package/cli/dist/core/commands/status.js +0 -194
  107. package/cli/dist/core/fleet.js +0 -156
  108. package/cli/dist/core/gather.js +0 -61
  109. package/cli/dist/core/interpret.js +0 -276
  110. package/cli/dist/core/load.js +0 -64
  111. package/cli/dist/core/present/line.js +0 -17
  112. package/cli/dist/result.js +0 -5
  113. /package/cli/dist/core/{updates.js → status/updates.js} +0 -0
@@ -1,156 +0,0 @@
1
- import { parseDocument } from "yaml";
2
- import { absolutePath, appName, domain, vaultPasswordFile, } from "./brand.js";
3
- import { all, err, map, ok } from "../result.js";
4
- import { serverKinds, serverSchema, varsSchema } from "./settings.js";
5
- import { checkSettings, checkShape, knownSettings } from "./validate.js";
6
- export { serverKinds };
7
- export const serverTargets = ["multipass", "hetzner", "home"];
8
- const mapping = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : undefined;
9
- /** YAML text as a value; a syntax error is a value too, not an exception. */
10
- export const yamlOf = (text) => {
11
- const document = parseDocument(text);
12
- const problem = document.errors.at(0);
13
- return problem === undefined ? ok(document.toJS()) : err(`is not valid YAML: ${problem.message.split("\n")[0] ?? ""}`);
14
- };
15
- const fields = (text) => {
16
- const parsed = yamlOf(text);
17
- if (!parsed.ok)
18
- return parsed;
19
- const value = parsed.value;
20
- if (value === null || value === undefined)
21
- return ok({});
22
- const result = mapping(value);
23
- return result === undefined ? err("is not a YAML mapping") : ok(result);
24
- };
25
- const vaulted = (text) => text.startsWith("$ANSIBLE_VAULT");
26
- const oneOf = (allowed, value, field) => {
27
- const match = allowed.find((candidate) => candidate === value);
28
- return match === undefined
29
- ? err(`${field} must be ${allowed.join(", ")}, not '${String(value)}'`)
30
- : ok(match);
31
- };
32
- const vault = (descriptor) => {
33
- const file = descriptor["vault_password_file"];
34
- if (descriptor["vault"] !== true)
35
- return ok({ kind: "none" });
36
- if (file === undefined)
37
- return ok({ kind: "ask" });
38
- return typeof file === "string"
39
- ? map(absolutePath(file), (path) => ({ kind: "file", file: vaultPasswordFile(path) }))
40
- : err("vault_password_file must be a path");
41
- };
42
- /**
43
- * Apps live in their own repo: the builder clones it over HTTPS, and the app
44
- * root stays inside it. A multipass server, a test machine by definition, may
45
- * clone over plain HTTP too: the upgrade lab serves its fixture app that way.
46
- */
47
- const app = (target) => (value) => {
48
- const entry = mapping(value);
49
- if (entry === undefined)
50
- return err("an app must be a mapping");
51
- const name = typeof entry["name"] === "string" ? appName(entry["name"]) : err("an app needs a name");
52
- if (!name.ok)
53
- return name;
54
- const repo = entry["repo"];
55
- const schemes = target === "multipass" ? ["https://", "http://"] : ["https://"];
56
- if (typeof repo !== "string" || !schemes.some((scheme) => repo.startsWith(scheme)))
57
- return err(`app ${name.value}: repo must be an https:// URL${target === "multipass" ? " (or http:// on multipass)" : ""}`);
58
- const path = entry["path"] ?? ".";
59
- if (typeof path !== "string" || `/${path}/`.includes("/../"))
60
- return err(`app ${name.value}: path must stay inside its repo`);
61
- return ok({ name: name.value, repo, entry: JSON.stringify(value) });
62
- };
63
- const inventoryField = (inventory, key) => new RegExp(`${key}=([^ \\n]*)`).exec(inventory)?.[1] ?? "";
64
- const inventoryOf = (text) => ({
65
- host: inventoryField(text, "ansible_host"),
66
- port: inventoryField(text, "ansible_port") || "22",
67
- user: inventoryField(text, "ansible_user"),
68
- key: inventoryField(text, "ansible_ssh_private_key_file"),
69
- });
70
- const stackHosts = (stacks, serverDomain) => stacks
71
- .flatMap((compose) => [...compose.matchAll(/Host\(`([^`]*)`\)/g)].map((match) => match[1] ?? ""))
72
- .map((host) => (host.endsWith(`.${serverDomain}`) ? host.slice(0, -serverDomain.length - 1) : host));
73
- /** An app's config is plaintext, to be read and diffed; its secrets are vaulted wherever secrets.yml is. */
74
- const appValuesProblem = (appValues, secretsMustBeVaulted) => appValues
75
- .map(({ file, text }) => file.endsWith(".secrets.yml")
76
- ? secretsMustBeVaulted && !vaulted(text)
77
- ? `apps/${file} must be vault-encrypted`
78
- : undefined
79
- : vaulted(text)
80
- ? `apps/${file} is vault-encrypted; it holds config only — secrets go in apps/${file.replace(/\.yml$/, ".secrets.yml")}`
81
- : undefined)
82
- .find((problem) => problem !== undefined);
83
- /** What every command may rely on, checked for every server whenever the fleet loads. */
84
- export const parseServer = (files) => {
85
- const descriptor = fields(files.descriptor);
86
- if (!descriptor.ok)
87
- return descriptor;
88
- const kind = oneOf(serverKinds, descriptor.value["kind"] ?? "platform", "kind");
89
- if (!kind.ok)
90
- return kind;
91
- const target = oneOf(serverTargets, descriptor.value["target"], "target");
92
- if (!target.ok)
93
- return target;
94
- const declared = descriptor.value["domain"];
95
- const serverDomain = typeof declared === "string" ? domain(declared) : err("domain is required");
96
- if (!serverDomain.ok)
97
- return serverDomain;
98
- const serverVault = vault(descriptor.value);
99
- if (!serverVault.ok)
100
- return serverVault;
101
- const declaredApps = descriptor.value["apps"] ?? [];
102
- if (!Array.isArray(declaredApps))
103
- return err("apps must be a list");
104
- if (kind.value !== "platform" && declaredApps.length > 0)
105
- return err("apps run on platform servers only");
106
- const apps = all(declaredApps.map(app(target.value)));
107
- if (!apps.ok)
108
- return apps;
109
- const shape = checkShape("server.yml", descriptor.value, serverSchema);
110
- if (!shape.ok)
111
- return shape;
112
- if (target.value === "home" && files.inventory === undefined)
113
- return err("target home needs a hand-written inventory.ini next to it");
114
- if (target.value !== "home" && !files.terraform)
115
- return err("no terraform/ next to it");
116
- if (files.vars === undefined)
117
- return err("no vars.yml next to it");
118
- if (files.secrets === undefined)
119
- return err("no secrets.yml next to it");
120
- if (vaulted(files.vars))
121
- return err("vars.yml is vault-encrypted; it holds settings only — secrets go in secrets.yml");
122
- if (target.value !== "multipass" && serverVault.value.kind === "none")
123
- return err(`target ${target.value} requires vault: true`);
124
- if (target.value !== "multipass" && !vaulted(files.secrets))
125
- return err(`target ${target.value} requires a vault-encrypted secrets.yml`);
126
- const appValues = appValuesProblem(files.appValues, target.value !== "multipass");
127
- if (appValues !== undefined)
128
- return err(appValues);
129
- const vars = fields(files.vars);
130
- if (!vars.ok)
131
- return err(`vars.yml ${vars.error}`);
132
- const varsChecked = checkSettings("vars.yml", vars.value, varsSchema(kind.value), knownSettings(kind.value));
133
- if (!varsChecked.ok)
134
- return varsChecked;
135
- const backupDir = mapping(vars.value["restic_backup"])?.["dir"];
136
- return ok({
137
- name: files.name,
138
- dir: files.dir,
139
- kind: kind.value,
140
- target: target.value,
141
- domain: serverDomain.value,
142
- vault: serverVault.value,
143
- secretsVaulted: vaulted(files.secrets),
144
- apps: apps.value,
145
- terraform: files.terraform,
146
- vm: target.value === "home" && vars.value["vm"] !== undefined,
147
- acmeDns: typeof vars.value["acme_dns"] === "string" && vars.value["acme_dns"] !== "",
148
- inventory: files.inventory === undefined ? undefined : inventoryOf(files.inventory),
149
- backupDir: typeof backupDir === "string" ? backupDir : undefined,
150
- stackHosts: stackHosts(files.stacks, serverDomain.value),
151
- });
152
- };
153
- export const serverNamed = (fleet, name) => {
154
- const server = fleet.servers.find((candidate) => candidate.name === name);
155
- return server === undefined ? err(`no server '${name}'`) : ok(server);
156
- };
@@ -1,61 +0,0 @@
1
- import { existsSync, readdirSync, readFileSync } from "node:fs";
2
- import { homedir } from "node:os";
3
- import { join } from "node:path";
4
- import { yamlOf } from "./fleet.js";
5
- import { capture } from "./interpret.js";
6
- const text = (path) => (existsSync(path) ? readFileSync(path, "utf8") : undefined);
7
- const mappingOf = (source) => {
8
- if (source === undefined)
9
- return {};
10
- const parsed = yamlOf(source);
11
- return parsed.ok && typeof parsed.value === "object" && parsed.value !== null && !Array.isArray(parsed.value)
12
- ? Object.fromEntries(Object.entries(parsed.value))
13
- : {};
14
- };
15
- const vaulted = (source) => source.startsWith("$ANSIBLE_VAULT");
16
- /** A secrets file's values: plaintext as is, a vault only with the server's password file; a missing file has none. */
17
- const secretsOf = async (server, path) => {
18
- const source = text(path);
19
- if (source === undefined)
20
- return { kind: "readable", values: {} };
21
- if (!vaulted(source))
22
- return { kind: "readable", values: mappingOf(source) };
23
- if (server.vault.kind !== "file")
24
- return { kind: "locked", reason: "vaulted, and server.yml names no vault_password_file", hint: "vault_password_file in server.yml lets kayra open it" };
25
- const file = server.vault.file.replace(homedir(), "~");
26
- if (!existsSync(server.vault.file))
27
- return { kind: "locked", reason: `vaulted, and there is no ${file} here`, hint: "put the vault's password there" };
28
- const opened = await capture(["ansible-vault", "view", "--vault-password-file", server.vault.file, path], "capture");
29
- return opened.code === 0
30
- ? { kind: "readable", values: mappingOf(opened.stdout) }
31
- : { kind: "locked", reason: `${file} does not open it`, hint: "is it this vault's password?" };
32
- };
33
- const appPath = (entry) => {
34
- const parsed = JSON.parse(entry);
35
- const path = typeof parsed === "object" && parsed !== null && "path" in parsed ? parsed.path : undefined;
36
- return typeof path === "string" ? path : ".";
37
- };
38
- /** What validate needs of a server, read from the fleet (and its clones under .cache/apps). */
39
- export const gather = async (root, server) => {
40
- const varsText = text(join(server.dir, "vars.yml")) ?? "";
41
- const stacks = join(server.dir, "stacks");
42
- const appSecrets = await Promise.all(server.apps.map(async (app) => [app.name, await secretsOf(server, join(server.dir, "apps", `${app.name}.secrets.yml`))]));
43
- return {
44
- server,
45
- vars: mappingOf(varsText),
46
- varsText,
47
- secrets: await secretsOf(server, join(server.dir, "secrets.yml")),
48
- stackDirs: existsSync(stacks)
49
- ? readdirSync(stacks, { withFileTypes: true })
50
- .filter((entry) => entry.isDirectory())
51
- .map((entry) => entry.name)
52
- .toSorted()
53
- : [],
54
- appConfig: Object.fromEntries(server.apps.map((app) => [app.name, mappingOf(text(join(server.dir, "apps", `${app.name}.yml`)))])),
55
- appSecrets: Object.fromEntries(appSecrets),
56
- manifests: Object.fromEntries(server.apps.flatMap((app) => {
57
- const manifest = text(join(root, ".cache", "apps", app.name, appPath(app.entry), "app.yml"));
58
- return manifest === undefined ? [] : [[app.name, mappingOf(manifest)]];
59
- })),
60
- };
61
- };
@@ -1,276 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { text } from "node:stream/consumers";
6
- import { all, err, flatMap, ok } from "../result.js";
7
- import { active, bad, muted, ok as fine, strong } from "./present/line.js";
8
- import { position, silent } from "./present/progress.js";
9
- import { draw } from "./present/views.js";
10
- const terminal = {};
11
- const isStopped = (signal) => signal?.aborted === true;
12
- /** A program that ignores SIGINT this long gets SIGTERM. */
13
- const patience = 10_000;
14
- const spawned = async (argv, streams, env = {}, plumbing = terminal) => {
15
- const [program, ...args] = argv;
16
- const { output, signal } = plumbing;
17
- if (isStopped(signal))
18
- return { code: 130, stdout: "", stderr: "", started: false };
19
- const shown = (stream) => stream === "show" ? (output === undefined ? "inherit" : "pipe") : stream === "capture" ? "pipe" : "ignore";
20
- const stdin = streams.stdin ?? (output === undefined ? { kind: "inherit" } : { kind: "none" });
21
- const child = spawn(program, args, {
22
- env: { ...process.env, ...env },
23
- detached: output !== undefined,
24
- stdio: [stdin.kind === "inherit" ? "inherit" : stdin.kind === "none" ? "ignore" : "pipe", shown(streams.stdout), shown(streams.stderr)],
25
- });
26
- const forward = (from, sink) => {
27
- child[from]?.setEncoding("utf8").on("data", (chunk) => {
28
- sink(chunk, from);
29
- });
30
- };
31
- if (output !== undefined && streams.stdout === "show")
32
- forward("stdout", output);
33
- if (output !== undefined && streams.stderr === "show")
34
- forward("stderr", output);
35
- // A program that exits before reading all it was given must not take kayra down with EPIPE.
36
- child.stdin?.on("error", () => undefined);
37
- if (stdin.kind === "given")
38
- child.stdin?.end(stdin.text);
39
- const unsubscribe = stdin.kind === "typed"
40
- ? stdin.input((chunk) => {
41
- child.stdin?.write(chunk);
42
- })
43
- : () => undefined;
44
- const read = (from, stream) => {
45
- const piped = child[from];
46
- return piped === null || stream !== "capture" ? Promise.resolve("") : text(piped);
47
- };
48
- const stdout = read("stdout", streams.stdout);
49
- const stderr = read("stderr", streams.stderr);
50
- const kill = (withSignal) => {
51
- if (child.pid === undefined)
52
- return;
53
- try {
54
- if (output === undefined)
55
- child.kill(withSignal);
56
- else
57
- process.kill(-child.pid, withSignal);
58
- }
59
- catch (error) {
60
- if (!(error instanceof Error && "code" in error && error.code === "ESRCH"))
61
- throw error;
62
- }
63
- };
64
- // eslint-disable-next-line functional/prefer-immutable-types -- the escalation belongs to this child, cleared when it exits
65
- const stopping = {};
66
- const stop = () => {
67
- if (stopping.timer !== undefined)
68
- return;
69
- if (stdin.kind === "typed")
70
- child.stdin?.write("\u0003");
71
- kill("SIGINT");
72
- // eslint-disable-next-line functional/immutable-data -- see above
73
- stopping.timer = setTimeout(() => { kill("SIGTERM"); }, patience);
74
- stopping.timer.unref();
75
- };
76
- // The process group exists only once Node confirms the child has spawned.
77
- child.once("spawn", () => {
78
- signal?.addEventListener("abort", stop, { once: true });
79
- if (isStopped(signal))
80
- stop();
81
- });
82
- const exit = await new Promise((resolve) => {
83
- child.on("error", resolve);
84
- child.on("close", (code) => {
85
- resolve(code ?? 1);
86
- });
87
- });
88
- signal?.removeEventListener("abort", stop);
89
- clearTimeout(stopping.timer);
90
- unsubscribe();
91
- return exit instanceof Error
92
- ? { code: 127, stdout: "", stderr: exit.message, started: false }
93
- : { code: exit, stdout: await stdout, stderr: await stderr, started: true };
94
- };
95
- /** A command's stdout, for kayra to read; its stderr reaches the operator unless captured too. */
96
- export const capture = (argv, stderr = "show", env = {}, plumbing = terminal) => spawned(argv, { stdout: "capture", stderr }, env, plumbing);
97
- const answer = (probe, plumbing) => spawned(probe.kind === "on-path" ? ["sh", "-c", 'command -v "$1"', "sh", probe.program] : probe.argv, { stdout: "discard", stderr: "capture", stdin: { kind: "none" } }, probe.kind === "exits-zero" ? probe.env : {}, plumbing);
98
- /** Each query's answer in place of it, as `$(…)` would: one word, or split into many. */
99
- const resolve = async (argv, plumbing) => {
100
- const words = await Promise.all(argv.map(async (value) => {
101
- if (typeof value === "string")
102
- return ok([value]);
103
- const exit = await capture(value.argv, "show", value.env, plumbing);
104
- if (exit.code !== 0)
105
- return err(`$(${value.argv.join(" ")}) failed: exit ${String(exit.code)}`);
106
- const output = exit.stdout.replace(/\n+$/, "");
107
- return ok(value.words === "one" ? [output] : output.split(/\s+/).filter((word) => word !== ""));
108
- }));
109
- return flatMap(all(words), (lists) => {
110
- const [program, ...rest] = lists.flat();
111
- return program === undefined ? err("the command is empty") : ok([program, ...rest]);
112
- });
113
- };
114
- const lines = (text) => text
115
- .trimEnd()
116
- .split("\n")
117
- .filter((line) => line !== "");
118
- /** Under the step's own line. */
119
- const detail = (line) => [" ", line];
120
- const aside = (line) => [" ", muted(line)];
121
- const hint = (text) => (text === undefined ? [] : [[" ", active("→"), " ", text]]);
122
- const goOn = { failed: false, stopped: false, out: [], err: [] };
123
- const check = async (step, plumbing) => {
124
- const exit = await answer(step.probe, plumbing);
125
- const said = [...lines(exit.stderr).map(detail), ...hint(step.hint)];
126
- if (step.onFailure === "stop")
127
- return exit.code === 0 ? goOn : { failed: true, stopped: true, out: [], err: said };
128
- return exit.code === 0
129
- ? { ...goOn, out: [[fine("✓"), " ", step.label]] }
130
- : { failed: true, stopped: false, out: [[bad("✗"), " ", step.label], ...said], err: [] };
131
- };
132
- const keyOf = (need) => (need.kind === "vault" ? `vault:${need.server}` : "sudo");
133
- const questionOf = (need) => need.kind === "vault"
134
- ? { kind: "secret", text: [" ", active("?"), " ", strong(`${need.server}'s vault password`), muted(" (asked once, kept for this run): ")] }
135
- : { kind: "secret", text: [" ", active("?"), " ", strong("sudo's password"), muted(" (for this step only): ")] };
136
- /** Whether sudo would run without a password: a cached one, or none needed. */
137
- const sudoReady = async (plumbing) => (await spawned(["sudo", "-n", "true"], { stdout: "discard", stderr: "capture", stdin: { kind: "none" } }, {}, plumbing)).code === 0;
138
- const scratch = () => {
139
- // eslint-disable-next-line functional/prefer-immutable-types -- made on first need, removed when the run ends
140
- const made = {};
141
- const dir = () => {
142
- // eslint-disable-next-line functional/immutable-data -- see above
143
- made.dir ??= mkdtempSync(join(tmpdir(), "kayra-"));
144
- return made.dir;
145
- };
146
- return {
147
- vaultScript: () => {
148
- const script = join(dir(), "vault-password");
149
- writeFileSync(script, '#!/bin/sh\nprintf \'%s\\n\' "$KAYRA_VAULT_PASSWORD"\n', { mode: 0o700 });
150
- chmodSync(script, 0o700);
151
- return script;
152
- },
153
- clean: () => {
154
- if (made.dir !== undefined)
155
- rmSync(made.dir, { recursive: true, force: true });
156
- },
157
- };
158
- };
159
- /** Asks what a step needs and has not been given yet in this run; undefined if the operator gave nothing. */
160
- const meet = async (needs, asked, io, made) => needs.reduce(async (previous, need) => {
161
- const so = await previous;
162
- if (so === undefined)
163
- return undefined;
164
- if (need.kind === "sudo" && (await sudoReady(io)))
165
- return so;
166
- const key = keyOf(need);
167
- const given = so.asked[key] ?? (await ask(io, questionOf(need)));
168
- if (given === "")
169
- return undefined;
170
- const now = need.kind === "vault" ? { ...so.asked, [key]: given } : so.asked;
171
- return need.kind === "vault"
172
- ? { asked: now, met: { ...so.met, env: { ...so.met.env, ANSIBLE_VAULT_PASSWORD_FILE: made.vaultScript(), KAYRA_VAULT_PASSWORD: given } } }
173
- : { asked: now, met: { env: { ...so.met.env, KAYRA_SUDO_STDIN: "1" }, stdin: { kind: "given", text: `${given}\n` } } };
174
- }, Promise.resolve({ met: { env: {} }, asked }));
175
- /** A step that talks with a person, given a pty: macOS's script, util-linux's elsewhere. */
176
- const inPty = (argv, size) => {
177
- const { columns, rows } = size ?? { columns: 120, rows: 32 };
178
- const sized = ["sh", "-c", `stty rows ${String(rows)} cols ${String(columns)} 2>/dev/null; exec "$@"`, "sh", ...argv];
179
- return process.platform === "darwin"
180
- // BSD script accepts a pipe, but rejects Node's socket-backed stdin with ENOTSUP.
181
- ? ["bash", "-c", '"$@" < <(cat); code=$?; kill "$!" 2>/dev/null || :; exit "$code"', "bash", "script", "-q", "/dev/null", ...sized]
182
- : ["script", "-q", "-e", "-c", sized.map((word) => `'${word.replaceAll("'", `'\\''`)}'`).join(" "), "/dev/null"];
183
- };
184
- const runStep = async (step, io, met) => {
185
- const argv = await resolve(step.argv, io);
186
- if (!argv.ok)
187
- return { failed: true, stopped: true, why: "a query failed", out: [], err: [detail(argv.error)] };
188
- const { stdout } = step;
189
- const talks = step.kind === "session" && io.output !== undefined;
190
- if (talks && io.input === undefined)
191
- return { failed: true, stopped: true, why: "no terminal", out: [], err: [detail("it talks with a person, and this client gives it no keys")] };
192
- // A quiet step's stderr waits until it is done, so it cannot tear through a spinner.
193
- const quiet = stdout === "discard";
194
- const exit = await spawned(talks ? inPty(argv.value, io.size) : argv.value, {
195
- stdout: typeof stdout === "string" ? stdout : "capture",
196
- stderr: quiet ? "capture" : "show",
197
- ...(talks && io.input !== undefined ? { stdin: { kind: "typed", input: io.input } } : met.stdin === undefined ? {} : { stdin: met.stdin }),
198
- }, { ...step.env, ...met.env }, io);
199
- if (!exit.started)
200
- return { failed: true, stopped: true, why: "not started", out: [], err: [detail(`${argv.value[0]}: ${exit.stderr}`)] };
201
- // Whatever it answered is shown, even when it failed: it may say why.
202
- const out = typeof stdout === "string" ? [] : draw(stdout, exit.stdout, Date.now());
203
- if (exit.code === 0)
204
- return { ...goOn, out, err: lines(exit.stderr).map(aside) };
205
- return { failed: true, stopped: true, why: `exit ${String(exit.code)}`, out, err: lines(exit.stderr).map(detail) };
206
- };
207
- const perform = async (step, io, met) => {
208
- switch (step.kind) {
209
- case "session":
210
- case "run":
211
- return runStep(step, io, met);
212
- case "check":
213
- return check(step, io);
214
- case "confirm": {
215
- io.err("");
216
- io.err([" ", bad("▲"), " ", strong(step.warning)]);
217
- const typed = await ask(io, { kind: "confirm", text: [" Type ", strong(step.expect), " to confirm: "], expect: step.expect });
218
- return typed === step.expect ? goOn : { failed: false, stopped: true, out: ["Aborted."], err: [] };
219
- }
220
- case "note":
221
- return { ...goOn, out: [step.text] };
222
- }
223
- };
224
- /** Cancellation also ends a question; a late answer cannot restart the plan. */
225
- const ask = async (io, question) => {
226
- if (isStopped(io.signal))
227
- return "";
228
- return new Promise((resolve, reject) => {
229
- const done = (answer) => {
230
- io.signal?.removeEventListener("abort", stopped);
231
- resolve(answer);
232
- };
233
- const stopped = () => { done(""); };
234
- io.signal?.addEventListener("abort", stopped, { once: true });
235
- void io.ask(question).then(done, (error) => {
236
- io.signal?.removeEventListener("abort", stopped);
237
- reject(error instanceof Error ? error : new Error(String(error)));
238
- });
239
- });
240
- };
241
- /**
242
- * Runs a plan step by step, until it ends or a step stops it, shown by `progress`.
243
- * True if nothing failed and the operator did not interrupt it.
244
- */
245
- export const interpret = async (plan, io, progress = silent, interrupted = () => false) => {
246
- const made = scratch();
247
- try {
248
- const ended = await progress.plan(plan, () => plan.reduce(async (previous, step, index) => {
249
- const so = await previous;
250
- if (so.stop !== undefined)
251
- return so;
252
- if (interrupted() || isStopped(io.signal))
253
- return { ...so, stop: { index, step, why: "interrupted" } };
254
- // What a step needs is asked before its frame opens: a prompt, then the step.
255
- const met = (step.kind === "run" || step.kind === "session") && step.needs !== undefined ? await meet(step.needs, so.asked, io, made) : { met: { env: {} }, asked: so.asked };
256
- if (met === undefined) {
257
- io.err([" ", muted("Nothing given: stopped before it ran.")]);
258
- return { ...so, stop: { index, step, why: isStopped(io.signal) ? "interrupted" : "declined" } };
259
- }
260
- const done = await progress.step(step, position(plan, index), () => perform(step, io, met.met));
261
- // Ctrl-C reached the step's program too: how it ended says nothing about the server.
262
- if (interrupted() || isStopped(io.signal))
263
- return { failures: so.failures, asked: met.asked, stop: { index, step, why: "interrupted" } };
264
- done.out.forEach(io.out);
265
- done.err.forEach(io.err);
266
- const failures = so.failures + (done.failed ? 1 : 0);
267
- if (done.stopped)
268
- return { failures, asked: met.asked, stop: { index, step, why: done.failed ? "failed" : "declined" } };
269
- return { failures, asked: met.asked };
270
- }, Promise.resolve({ failures: 0, asked: {} })));
271
- return ended.failures === 0 && ended.stop?.why !== "interrupted";
272
- }
273
- finally {
274
- made.clean();
275
- }
276
- };
@@ -1,64 +0,0 @@
1
- import { existsSync, readdirSync, readFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { fleetRoot, serverDir, serverName, within } from "./brand.js";
4
- import { parseServer, yamlOf } from "./fleet.js";
5
- import { all, err, flatMap, map, ok } from "../result.js";
6
- import { defaultsSchema } from "./settings.js";
7
- import { checkSettings, knownSettings } from "./validate.js";
8
- /** The fleet is the nearest directory, from `from` upwards, with a servers/defaults.yml. */
9
- export const findFleetRoot = (from) => {
10
- if (existsSync(join(from, "servers", "defaults.yml")))
11
- return ok(fleetRoot(from));
12
- const parent = within(from, "..");
13
- return parent === from
14
- ? err("no fleet here: no servers/defaults.yml in this directory or above it")
15
- : findFleetRoot(parent);
16
- };
17
- const text = (path) => (existsSync(path) ? readFileSync(path, "utf8") : undefined);
18
- const stacks = (dir) => existsSync(join(dir, "stacks"))
19
- ? readdirSync(join(dir, "stacks"))
20
- .toSorted()
21
- .flatMap((stack) => text(join(dir, "stacks", stack, "compose.yaml")) ?? [])
22
- : [];
23
- const appValues = (dir) => existsSync(join(dir, "apps"))
24
- ? readdirSync(join(dir, "apps"))
25
- .filter((file) => file.endsWith(".yml"))
26
- .toSorted()
27
- .map((file) => ({ file, text: readFileSync(join(dir, "apps", file), "utf8") }))
28
- : [];
29
- const readServer = (root, entry) => {
30
- const name = serverName(entry);
31
- if (!name.ok)
32
- return err(`servers/${entry}: ${name.error}`);
33
- const dir = serverDir(root, name.value);
34
- const server = parseServer({
35
- name: name.value,
36
- dir,
37
- descriptor: readFileSync(join(dir, "server.yml"), "utf8"),
38
- vars: text(join(dir, "vars.yml")),
39
- secrets: text(join(dir, "secrets.yml")),
40
- inventory: text(join(dir, "inventory.ini")),
41
- terraform: existsSync(join(dir, "terraform")),
42
- stacks: stacks(dir),
43
- appValues: appValues(dir),
44
- });
45
- return server.ok ? server : err(`servers/${entry}/server.yml: ${server.error}`);
46
- };
47
- /** servers/defaults.yml: settings shared by every server, any kind's. */
48
- const checkDefaults = (root) => {
49
- const parsed = yamlOf(readFileSync(join(root, "servers", "defaults.yml"), "utf8"));
50
- if (!parsed.ok)
51
- return err(`servers/defaults.yml ${parsed.error}`);
52
- const values = parsed.value;
53
- if (values === null || values === undefined)
54
- return ok(true);
55
- if (typeof values !== "object" || Array.isArray(values))
56
- return err("servers/defaults.yml is not a YAML mapping");
57
- return map(checkSettings("servers/defaults.yml", Object.fromEntries(Object.entries(values)), defaultsSchema, knownSettings(undefined)), () => true);
58
- };
59
- export const loadFleet = (root) => flatMap(checkDefaults(root), () => fleetOf(root));
60
- const fleetOf = (root) => map(all(readdirSync(join(root, "servers"), { withFileTypes: true })
61
- .filter((entry) => entry.isDirectory() && existsSync(join(root, "servers", entry.name, "server.yml")))
62
- .map((entry) => entry.name)
63
- .toSorted()
64
- .map((entry) => readServer(root, entry))), (servers) => ({ root, servers }));
@@ -1,17 +0,0 @@
1
- const toned = (tone) => (text) => ({ tone, text });
2
- export const ok = toned("ok");
3
- export const bad = toned("bad");
4
- export const warn = toned("warn");
5
- export const active = toned("active");
6
- export const muted = toned("muted");
7
- export const strong = toned("strong");
8
- export const accent = toned("accent");
9
- export const link = (text, href, tone) => ({ text, href, ...(tone === undefined ? {} : { tone }) });
10
- export const spans = (text) => (typeof text === "string" ? [text] : text);
11
- export const textOf = (span) => (typeof span === "string" ? span : span.text);
12
- export const flat = (text) => spans(text).map(textOf).join("");
13
- const graphemes = new Intl.Segmenter();
14
- /** A string's characters as a reader counts them. */
15
- export const characters = (text) => Array.from(graphemes.segment(text), (each) => each.segment);
16
- /** Columns it takes: one per character, which holds for everything kayra writes itself. */
17
- export const width = (text) => characters(flat(text)).length;
@@ -1,5 +0,0 @@
1
- export const ok = (value) => ({ ok: true, value });
2
- export const err = (error) => ({ ok: false, error });
3
- export const map = (result, f) => result.ok ? ok(f(result.value)) : result;
4
- export const flatMap = (result, f) => (result.ok ? f(result.value) : result);
5
- export const all = (results) => results.reduce((acc, result) => flatMap(acc, (values) => map(result, (value) => [...values, value])), ok([]));
File without changes