@yunuseon/kayra 0.16.1 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +4 -0
  2. package/ansible/roles/platform/tasks/main.yml +31 -0
  3. package/cli/dist/browser/assets/{index-3W_NFATj.css → index-Ct0Eudk4.css} +1 -1
  4. package/cli/dist/browser/assets/index-hcyM6f6T.js +7 -0
  5. package/cli/dist/browser/assets/xterm-CerOhKYV.js +16 -0
  6. package/cli/dist/browser/index.html +2 -2
  7. package/cli/dist/clients/api/api.js +189 -0
  8. package/cli/dist/clients/api/auth.js +37 -0
  9. package/cli/dist/clients/api/commands.js +63 -0
  10. package/cli/dist/clients/api/contract.gen.js +1 -0
  11. package/cli/dist/clients/api/contract.js +91 -0
  12. package/cli/dist/clients/api/directories.js +20 -0
  13. package/cli/dist/clients/api/discovery.js +43 -0
  14. package/cli/dist/clients/api/live.js +40 -0
  15. package/cli/dist/clients/api/protocol.js +68 -0
  16. package/cli/dist/clients/api/queries.js +20 -0
  17. package/cli/dist/{web → clients/api}/runs.js +14 -11
  18. package/cli/dist/clients/api/start.js +97 -0
  19. package/cli/dist/clients/api/status.js +29 -0
  20. package/cli/dist/clients/api/validate.js +13 -0
  21. package/cli/dist/{ui → clients/cli}/explain.js +10 -8
  22. package/cli/dist/clients/cli/framed.js +67 -0
  23. package/cli/dist/clients/cli/invocation.js +84 -0
  24. package/cli/dist/clients/cli/paint.js +23 -0
  25. package/cli/dist/{cli.js → clients/cli/parser.js} +38 -32
  26. package/cli/dist/clients/cli/questions.js +89 -0
  27. package/cli/dist/clients/cli/status.js +75 -0
  28. package/cli/dist/{ui → clients/cli}/terminal.js +5 -15
  29. package/cli/dist/{ui → clients/cli}/text.js +15 -24
  30. package/cli/dist/clients/cli/validate.js +32 -0
  31. package/cli/dist/clients/cli/values.js +19 -0
  32. package/cli/dist/{ui → clients/cli}/views.js +28 -60
  33. package/cli/dist/clients/ui/assets.js +36 -0
  34. package/cli/dist/core/adapters/fs.js +18 -0
  35. package/cli/dist/{net.js → core/adapters/network.js} +20 -5
  36. package/cli/dist/core/adapters/opentofu.js +24 -0
  37. package/cli/dist/core/ctl/answers.js +32 -0
  38. package/cli/dist/core/fleet/brand.js +45 -0
  39. package/cli/dist/{schemas.js → core/fleet/docs.js} +4 -3
  40. package/cli/dist/core/fleet/load.js +44 -0
  41. package/cli/dist/core/fleet/model.js +1 -0
  42. package/cli/dist/{fleet.js → core/fleet/parse.js} +61 -41
  43. package/cli/dist/{settings.js → core/fleet/settings.js} +10 -3
  44. package/cli/dist/{validate.js → core/fleet/shape.js} +6 -5
  45. package/cli/dist/core/interpreter/events.js +81 -0
  46. package/cli/dist/core/interpreter/io.js +18 -0
  47. package/cli/dist/core/interpreter/loop.js +101 -0
  48. package/cli/dist/core/interpreter/needs.js +47 -0
  49. package/cli/dist/core/interpreter/process.js +107 -0
  50. package/cli/dist/core/interpreter/progress.js +15 -0
  51. package/cli/dist/core/interpreter/pty.js +8 -0
  52. package/cli/dist/core/operations/catalog.js +169 -0
  53. package/cli/dist/core/operations/dispatch.js +142 -0
  54. package/cli/dist/{plan.js → core/plan/describe.js} +13 -16
  55. package/cli/dist/core/plan/model.js +14 -0
  56. package/cli/dist/{commands → core/recipes}/app-check.js +11 -16
  57. package/cli/dist/core/recipes/apps.js +63 -0
  58. package/cli/dist/core/recipes/backup.js +34 -0
  59. package/cli/dist/core/recipes/certs.js +4 -0
  60. package/cli/dist/{commands → core/recipes}/doctor.js +20 -35
  61. package/cli/dist/core/recipes/host.js +104 -0
  62. package/cli/dist/core/recipes/ssh.js +20 -0
  63. package/cli/dist/core/recipes/steps.js +82 -0
  64. package/cli/dist/core/status/look.js +55 -0
  65. package/cli/dist/core/status/model.js +6 -0
  66. package/cli/dist/core/status/ports.js +1 -0
  67. package/cli/dist/core/status/updates.js +13 -0
  68. package/cli/dist/core/text/plural.js +2 -0
  69. package/cli/dist/core/text/spans.js +22 -0
  70. package/cli/dist/core/text/time.js +12 -0
  71. package/cli/dist/core/validation/facts.js +49 -0
  72. package/cli/dist/{commands/validate.js → core/validation/findings.js} +31 -66
  73. package/cli/dist/deployer/app.js +2 -1
  74. package/cli/dist/deployer/{builder.js → build/builder.js} +14 -13
  75. package/cli/dist/deployer/{bundle.js → build/bundle.js} +8 -7
  76. package/cli/dist/deployer/{compose.js → build/compose.js} +8 -7
  77. package/cli/dist/deployer/cron.js +2 -2
  78. package/cli/dist/deployer/{answers.js → ctl/answers.js} +5 -4
  79. package/cli/dist/deployer/{ctl.js → ctl/ctl.js} +3 -3
  80. package/cli/dist/deployer/deployer.js +23 -22
  81. package/cli/dist/deployer/{forge.js → forges/forge.js} +2 -1
  82. package/cli/dist/deployer/{forgejo.js → forges/forgejo.js} +2 -2
  83. package/cli/dist/deployer/{github.js → forges/github.js} +2 -2
  84. package/cli/dist/deployer/{gitlab.js → forges/gitlab.js} +2 -2
  85. package/cli/dist/deployer/{github-issues.js → forges/issues.js} +5 -4
  86. package/cli/dist/deployer/{notify.js → forges/notify.js} +9 -8
  87. package/cli/dist/deployer/{http.js → http/http.js} +1 -0
  88. package/cli/dist/deployer/{page.js → http/page.js} +1 -1
  89. package/cli/dist/deployer/{webhook.js → http/webhook.js} +2 -1
  90. package/cli/dist/deployer/main.js +2 -2
  91. package/cli/dist/deployer/{queue.js → runs/queue.js} +4 -3
  92. package/cli/dist/deployer/{records.js → runs/records.js} +9 -8
  93. package/cli/dist/deployer/{run.js → runs/run.js} +10 -9
  94. package/cli/dist/deployer/{store.js → runs/store.js} +9 -8
  95. package/cli/dist/main.js +98 -99
  96. package/cli/dist/result.js +11 -1
  97. package/cli/dist/serve.js +77 -0
  98. package/cli/dist/typed.js +2 -0
  99. package/package.json +4 -2
  100. package/scripts/agent/guard.sh +9 -2
  101. package/scripts/local/packed-runs.sh +20 -5
  102. package/scripts/local/setup-hosts.sh +9 -2
  103. package/cli/dist/brand.js +0 -39
  104. package/cli/dist/browser/assets/index-DRFX9Q77.js +0 -2
  105. package/cli/dist/commands/index.js +0 -52
  106. package/cli/dist/commands/server.js +0 -289
  107. package/cli/dist/commands/status.js +0 -194
  108. package/cli/dist/gather.js +0 -61
  109. package/cli/dist/interpret.js +0 -141
  110. package/cli/dist/load.js +0 -64
  111. package/cli/dist/ui/line.js +0 -39
  112. package/cli/dist/ui/progress.js +0 -144
  113. package/cli/dist/web/auth.js +0 -36
  114. package/cli/dist/web/commands.js +0 -102
  115. package/cli/dist/web/contract.js +0 -7
  116. package/cli/dist/web/server.js +0 -336
  117. /package/cli/dist/{web → clients/ui}/opener.js +0 -0
@@ -0,0 +1,32 @@
1
+ import { z } from "zod";
2
+ const deployed = z.object({ sha: z.string(), time: z.iso.datetime() });
3
+ /** `ctl runs <app> --json`, as this kayra reads it. */
4
+ export const runsSchema = z.object({
5
+ app: z.string(),
6
+ live: deployed.exactOptional(),
7
+ runs: z.array(z.object({
8
+ id: z.string(),
9
+ state: z.enum(["running", "success", "failure"]),
10
+ why: z.string(),
11
+ what: z.string(),
12
+ sha: z.string().exactOptional(),
13
+ started: z.iso.datetime(),
14
+ finished: z.iso.datetime().exactOptional(),
15
+ })),
16
+ });
17
+ /** `ctl rollback <app> --json`, as this kayra reads it. */
18
+ export const releasesSchema = z.object({
19
+ app: z.string(),
20
+ releases: z.array(deployed.extend({ live: z.boolean() })),
21
+ });
22
+ /** The answer as the schema has it, or nothing: then it is not the answer this kayra expects. */
23
+ export const parsed = (schema, answer) => {
24
+ try {
25
+ const json = JSON.parse(answer);
26
+ const result = schema.safeParse(json);
27
+ return result.success ? result.data : undefined;
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ };
@@ -0,0 +1,45 @@
1
+ import { homedir } from "node:os";
2
+ import { isAbsolute, join, normalize } from "node:path";
3
+ import { err, ok } from "../../result.js";
4
+ export const serverName = (value) => /^[a-z0-9][a-z0-9-]*$/.test(value)
5
+ ? ok(value)
6
+ : err(`'${value}' is not a server name (lowercase letters, digits, dashes)`);
7
+ export const appName = (value) => /^[a-z][a-z0-9-]*$/.test(value)
8
+ ? ok(value)
9
+ : err(`'${value}' is not an app name (lowercase letters, digits, dashes)`);
10
+ export const subdomain = (value) => /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(value) ? ok(value) : err(`'${value}' is not a subdomain`);
11
+ export const domain = (value) => /^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z][a-z0-9-]*$/.test(value)
12
+ ? ok(value)
13
+ : err(`'${value}' is not a domain`);
14
+ /** `~/…` is the operator's home, as Ansible reads it in vault_password_file. */
15
+ export const absolutePath = (value) => {
16
+ const expanded = value === "~" || value.startsWith("~/") ? join(homedir(), value.slice(1)) : value;
17
+ return isAbsolute(expanded) ? ok(normalize(expanded)) : err(`'${value}' is not an absolute path`);
18
+ };
19
+ export const kayraRoot = (path) => path;
20
+ export const fleetRoot = (path) => path;
21
+ export const serverDir = (root, name) => join(root, "servers", name);
22
+ export const vaultPasswordFile = (path) => path;
23
+ export const within = (base, ...segments) => join(base, ...segments);
24
+ /** One of each, as help shows a value: what a command-line parser offers before the operator types one. */
25
+ export const examples = {
26
+ app: "app",
27
+ server: "server",
28
+ domain: "example.com",
29
+ subdomain: "www",
30
+ };
31
+ /** A word without whitespace: what an inventory gives for a host, a user or a key. */
32
+ const word = (what, mint) => (value) => /^\S+$/.test(value) ? ok(mint(value)) : err(`'${value}' is not ${what}`);
33
+ export const host = word("a host", (value) => value);
34
+ export const sshUser = word("an ssh user", (value) => value);
35
+ export const keyFile = word("a key file", (value) => value);
36
+ /** Where ssh listens unless the inventory says otherwise. */
37
+ export const sshDefaultPort = "22";
38
+ export const port = (value) => /^\d+$/.test(value) && Number(value) >= 1 && Number(value) <= 65535 ? ok(value) : err(`'${value}' is not a port`);
39
+ /** HTTPS, or also plain HTTP where `schemes` allow it (a multipass server, a test machine by definition). */
40
+ export const repoUrl = (value, schemes) => schemes.some((scheme) => value.startsWith(scheme)) ? ok(value) : err(`'${value}' is not a ${schemes.join(" or ")} URL`);
41
+ export const repoPath = (value) => `/${value}/`.includes("/../") ? err(`'${value}' leaves its repository`) : ok(value);
42
+ export const remotePath = (value) => value.startsWith("/") ? ok(value) : err(`'${value}' is not an absolute path`);
43
+ export const milliseconds = (value) => Math.max(0, value);
44
+ export const exitCode = (value) => value;
45
+ export const kayraVersion = (value) => /^\d+\.\d+\.\d+/.test(value) ? ok(value) : err(`'${value}' is not a version`);
@@ -1,13 +1,14 @@
1
1
  import { z } from "zod";
2
2
  import { appManifestSchema, appValuesSchema, defaultsSchema, serverKinds, serverSchema, settings, varsSchema, } from "./settings.js";
3
+ import { typed } from "../../typed.js";
3
4
  const version = "https://json-schema.org/draft/2020-12/schema";
4
- const jsonSchema = (title, schema) => ({
5
+ const jsonSchema = (title, schema) => typed({
5
6
  ...z.toJSONSchema(schema, { target: "draft-2020-12", unrepresentable: "any" }),
6
7
  $schema: version,
7
8
  title,
8
9
  });
9
10
  /** The fleet's files as JSON Schemas, for editors: published in the package under schema/. */
10
- export const jsonSchemas = () => ({
11
+ export const jsonSchemas = () => typed({
11
12
  "server.json": jsonSchema("server.yml", serverSchema),
12
13
  "defaults.json": jsonSchema("defaults.yml", defaultsSchema),
13
14
  ...Object.fromEntries(serverKinds.map((kind) => [`vars-${kind}.json`, jsonSchema(`vars.yml (kind ${kind})`, varsSchema(kind))])),
@@ -27,7 +28,7 @@ export const settingsPage = () => [
27
28
  "description: Every setting a fleet can give its servers, generated from kayra's schemas.",
28
29
  "---",
29
30
  "",
30
- "{/* Generated by `npm run schemas` from cli/src/settings.ts — edit there, not here. */}",
31
+ "{/* Generated by `npm run schemas` from cli/src/core/fleet/settings.ts — edit there, not here. */}",
31
32
  "",
32
33
  "A server's `vars.yml` may set the settings of its kind and nothing else: an unknown key stops every",
33
34
  "kayra command, with a suggestion where it looks like a typo. `servers/defaults.yml` holds settings",
@@ -0,0 +1,44 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join, sep } from "node:path";
3
+ import { filesIn, foldersIn, textAt } from "../adapters/fs.js";
4
+ import { fleetRoot, serverDir, serverName, within } from "./brand.js";
5
+ import { fields, parseServer } from "./parse.js";
6
+ import { all, attempt, err, flatMap, map, ok } from "../../result.js";
7
+ import { defaultsSchema } from "./settings.js";
8
+ import { checkSettings, knownSettings } from "./shape.js";
9
+ /** The fleet is the nearest directory, from `from` upwards, with a servers/defaults.yml. */
10
+ export const findFleetRoot = (from) => {
11
+ const upwards = Array.from({ length: from.split(sep).length }, (_, up) => within(from, ...Array.from({ length: up }, () => "..")));
12
+ const found = upwards.find((dir) => existsSync(join(dir, "servers", "defaults.yml")));
13
+ return found === undefined ? err("no fleet here: no servers/defaults.yml in this directory or above it") : ok(fleetRoot(found));
14
+ };
15
+ /** Every file of a server, read once: what every command, and validate, works from. */
16
+ const readServer = (root, entry) => {
17
+ const name = serverName(entry);
18
+ if (!name.ok)
19
+ return err(`servers/${entry}: ${name.error}`);
20
+ const dir = serverDir(root, name.value);
21
+ const server = parseServer({
22
+ name: name.value,
23
+ dir,
24
+ descriptor: textAt(join(dir, "server.yml")) ?? "",
25
+ vars: textAt(join(dir, "vars.yml")),
26
+ secrets: textAt(join(dir, "secrets.yml")),
27
+ inventory: textAt(join(dir, "inventory.ini")),
28
+ hasTerraform: existsSync(join(dir, "terraform")),
29
+ stacks: foldersIn(join(dir, "stacks")).map((stack) => ({ name: stack, compose: textAt(join(dir, "stacks", stack, "compose.yaml")) })),
30
+ appValues: filesIn(join(dir, "apps"), ".yml").map((file) => ({ file, text: textAt(join(dir, "apps", file)) ?? "" })),
31
+ });
32
+ return server.ok ? server : err(`servers/${entry}/server.yml: ${server.error}`);
33
+ };
34
+ /** servers/defaults.yml: settings shared by every server, any kind's. */
35
+ const checkDefaults = (root) => {
36
+ const values = fields(textAt(join(root, "servers", "defaults.yml")) ?? "");
37
+ if (!values.ok)
38
+ return err(`servers/defaults.yml ${values.error}`);
39
+ return map(checkSettings("servers/defaults.yml", values.value, defaultsSchema, knownSettings(undefined)), () => true);
40
+ };
41
+ const fleetOf = (root) => map(all(foldersIn(join(root, "servers"))
42
+ .filter((entry) => existsSync(join(root, "servers", entry, "server.yml")))
43
+ .map((entry) => readServer(root, entry))), (servers) => ({ root, servers }));
44
+ export const loadFleet = (root) => attempt(() => flatMap(checkDefaults(root), () => fleetOf(root)), (why) => `the fleet could not be read: ${why}`);
@@ -0,0 +1 @@
1
+ export const serverTargets = ["multipass", "hetzner", "home"];
@@ -1,18 +1,19 @@
1
1
  import { parseDocument } from "yaml";
2
- import { absolutePath, appName, domain, vaultPasswordFile, } from "./brand.js";
3
- import { all, err, map, ok } from "./result.js";
2
+ import { absolutePath, appName, domain, host, sshDefaultPort, keyFile, port, remotePath, repoPath, repoUrl, sshUser, vaultPasswordFile } from "./brand.js";
3
+ import { all, err, map, ok } from "../../result.js";
4
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;
5
+ import { checkSettings, checkShape, knownSettings } from "./shape.js";
6
+ import { serverTargets } from "./model.js";
7
+ import { typed } from "../../typed.js";
8
+ export const mapping = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? typed(Object.fromEntries(Object.entries(value))) : undefined;
9
9
  /** YAML text as a value; a syntax error is a value too, not an exception. */
10
10
  export const yamlOf = (text) => {
11
11
  const document = parseDocument(text);
12
12
  const problem = document.errors.at(0);
13
13
  return problem === undefined ? ok(document.toJS()) : err(`is not valid YAML: ${problem.message.split("\n")[0] ?? ""}`);
14
14
  };
15
- const fields = (text) => {
15
+ /** YAML text as a mapping; empty for an empty file. */
16
+ export const fields = (text) => {
16
17
  const parsed = yamlOf(text);
17
18
  if (!parsed.ok)
18
19
  return parsed;
@@ -22,7 +23,7 @@ const fields = (text) => {
22
23
  const result = mapping(value);
23
24
  return result === undefined ? err("is not a YAML mapping") : ok(result);
24
25
  };
25
- const vaulted = (text) => text.startsWith("$ANSIBLE_VAULT");
26
+ export const isVaulted = (text) => text.startsWith("$ANSIBLE_VAULT");
26
27
  const oneOf = (allowed, value, field) => {
27
28
  const match = allowed.find((candidate) => candidate === value);
28
29
  return match === undefined
@@ -36,7 +37,7 @@ const vault = (descriptor) => {
36
37
  if (file === undefined)
37
38
  return ok({ kind: "ask" });
38
39
  return typeof file === "string"
39
- ? map(absolutePath(file), (path) => ({ kind: "file", file: vaultPasswordFile(path) }))
40
+ ? map(absolutePath(file), (path) => typed({ kind: "file", file: vaultPasswordFile(path) }))
40
41
  : err("vault_password_file must be a path");
41
42
  };
42
43
  /**
@@ -51,32 +52,47 @@ const app = (target) => (value) => {
51
52
  const name = typeof entry["name"] === "string" ? appName(entry["name"]) : err("an app needs a name");
52
53
  if (!name.ok)
53
54
  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)))
55
+ const declared = entry["repo"];
56
+ const repo = typeof declared === "string" ? repoUrl(declared, target === "multipass" ? ["https://", "http://"] : ["https://"]) : undefined;
57
+ if (repo?.ok !== true)
57
58
  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("/../"))
59
+ const within = entry["path"] ?? ".";
60
+ const path = typeof within === "string" ? repoPath(within) : undefined;
61
+ if (path?.ok !== true)
60
62
  return err(`app ${name.value}: path must stay inside its repo`);
61
- return ok({ name: name.value, repo, entry: JSON.stringify(value) });
63
+ return ok({ name: name.value, repo: repo.value, path: path.value, entry });
62
64
  };
63
65
  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));
66
+ /** A field the inventory may leave out: undefined where it does. */
67
+ const optional = (value, mint) => value === "" ? ok(undefined) : mint(value);
68
+ const inventoryOf = (text) => {
69
+ const fields = [
70
+ optional(inventoryField(text, "ansible_host"), host),
71
+ port(inventoryField(text, "ansible_port") || sshDefaultPort),
72
+ optional(inventoryField(text, "ansible_user"), sshUser),
73
+ optional(inventoryField(text, "ansible_ssh_private_key_file"), keyFile),
74
+ ];
75
+ const [address, sshPort, user, key] = fields;
76
+ if (!address.ok)
77
+ return err(`inventory.ini: ansible_host ${address.error}`);
78
+ if (!sshPort.ok)
79
+ return err(`inventory.ini: ansible_port ${sshPort.error}`);
80
+ if (!user.ok)
81
+ return err(`inventory.ini: ansible_user ${user.error}`);
82
+ if (!key.ok)
83
+ return err(`inventory.ini: ansible_ssh_private_key_file ${key.error}`);
84
+ return ok({ host: address.value, port: sshPort.value, user: user.value, key: key.value });
85
+ };
86
+ const stackHosts = (stacks, serverDomain) => Object.freeze(stacks
87
+ .flatMap((compose) => Object.freeze([...compose.matchAll(/Host\(`([^`]*)`\)/g)].map((match) => match[1] ?? "")))
88
+ .map((host) => (host.endsWith(`.${serverDomain}`) ? host.slice(0, -serverDomain.length - 1) : host)));
73
89
  /** An app's config is plaintext, to be read and diffed; its secrets are vaulted wherever secrets.yml is. */
74
90
  const appValuesProblem = (appValues, secretsMustBeVaulted) => appValues
75
91
  .map(({ file, text }) => file.endsWith(".secrets.yml")
76
- ? secretsMustBeVaulted && !vaulted(text)
92
+ ? secretsMustBeVaulted && !isVaulted(text)
77
93
  ? `apps/${file} must be vault-encrypted`
78
94
  : undefined
79
- : vaulted(text)
95
+ : isVaulted(text)
80
96
  ? `apps/${file} is vault-encrypted; it holds config only — secrets go in apps/${file.replace(/\.yml$/, ".secrets.yml")}`
81
97
  : undefined)
82
98
  .find((problem) => problem !== undefined);
@@ -111,17 +127,17 @@ export const parseServer = (files) => {
111
127
  return shape;
112
128
  if (target.value === "home" && files.inventory === undefined)
113
129
  return err("target home needs a hand-written inventory.ini next to it");
114
- if (target.value !== "home" && !files.terraform)
130
+ if (target.value !== "home" && !files.hasTerraform)
115
131
  return err("no terraform/ next to it");
116
132
  if (files.vars === undefined)
117
133
  return err("no vars.yml next to it");
118
134
  if (files.secrets === undefined)
119
135
  return err("no secrets.yml next to it");
120
- if (vaulted(files.vars))
136
+ if (isVaulted(files.vars))
121
137
  return err("vars.yml is vault-encrypted; it holds settings only — secrets go in secrets.yml");
122
138
  if (target.value !== "multipass" && serverVault.value.kind === "none")
123
139
  return err(`target ${target.value} requires vault: true`);
124
- if (target.value !== "multipass" && !vaulted(files.secrets))
140
+ if (target.value !== "multipass" && !isVaulted(files.secrets))
125
141
  return err(`target ${target.value} requires a vault-encrypted secrets.yml`);
126
142
  const appValues = appValuesProblem(files.appValues, target.value !== "multipass");
127
143
  if (appValues !== undefined)
@@ -132,7 +148,13 @@ export const parseServer = (files) => {
132
148
  const varsChecked = checkSettings("vars.yml", vars.value, varsSchema(kind.value), knownSettings(kind.value));
133
149
  if (!varsChecked.ok)
134
150
  return varsChecked;
135
- const backupDir = mapping(vars.value["restic_backup"])?.["dir"];
151
+ const backup = mapping(vars.value["restic_backup"])?.["dir"];
152
+ const backupDir = typeof backup === "string" ? remotePath(backup) : ok(undefined);
153
+ if (!backupDir.ok)
154
+ return err(`vars.yml: restic_backup.dir ${backupDir.error}`);
155
+ const inventory = files.inventory === undefined ? ok(undefined) : inventoryOf(files.inventory);
156
+ if (!inventory.ok)
157
+ return inventory;
136
158
  return ok({
137
159
  name: files.name,
138
160
  dir: files.dir,
@@ -140,17 +162,15 @@ export const parseServer = (files) => {
140
162
  target: target.value,
141
163
  domain: serverDomain.value,
142
164
  vault: serverVault.value,
143
- secretsVaulted: vaulted(files.secrets),
165
+ hasVaultedSecrets: isVaulted(files.secrets),
144
166
  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),
167
+ hasTerraform: files.hasTerraform,
168
+ buildsVm: target.value === "home" && vars.value["vm"] !== undefined,
169
+ usesAcmeDns: typeof vars.value["acme_dns"] === "string" && vars.value["acme_dns"] !== "",
170
+ inventory: inventory.value,
171
+ backupDir: backupDir.value,
172
+ stackHosts: stackHosts(files.stacks.flatMap((stack) => Object.freeze(stack.compose ?? [])), serverDomain.value),
173
+ vars: vars.value,
174
+ files: { vars: files.vars, secrets: files.secrets, stacks: files.stacks.map((stack) => stack.name), appValues: files.appValues },
151
175
  });
152
176
  };
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,14 +1,18 @@
1
1
  import { z } from "zod";
2
+ import { typed } from "../../typed.js";
2
3
  /** The server kinds, each with its playbook; settings say which kinds read them. */
3
4
  export const serverKinds = ["platform", "edge", "nas"];
4
- const setting = (name, kinds, schema, description) => ({ name, kinds, secret: false, schema: schema.describe(description), description });
5
- const secret = (name, kinds, schema, description) => ({ name, kinds, secret: true, schema: schema.describe(description), description });
5
+ // eslint-disable-next-line functional/prefer-immutable-types -- holds a Zod schema: immutable once built, but a class the rule cannot see into
6
+ const setting = (name, kinds, schema, description) => typed({ name, kinds, secret: false, schema: schema.describe(description), description });
7
+ // eslint-disable-next-line functional/prefer-immutable-types -- holds a Zod schema: immutable once built, but a class the rule cannot see into
8
+ const secret = (name, kinds, schema, description) => typed({ name, kinds, secret: true, schema: schema.describe(description), description });
6
9
  const text = z.string();
7
10
  const texts = z.array(z.string());
8
11
  const platform = ["platform"];
9
12
  const edge = ["edge"];
10
13
  const nas = ["nas"];
11
14
  /** Nested settings check the fields they know and allow others: a typo is caught at the top. */
15
+ // eslint-disable-next-line functional/prefer-immutable-types -- a Zod schema: immutable once built, but a class the rule cannot see into
12
16
  const record = (fields) => z.looseObject(fields);
13
17
  export const settings = [
14
18
  // Every kind that serves HTTPS
@@ -100,13 +104,16 @@ export const settings = [
100
104
  ];
101
105
  /** Ansible's own variables (connection, privilege escalation) are always allowed. */
102
106
  export const isAnsibleVariable = (key) => key.startsWith("ansible_");
103
- export const settingsFor = (kind, secrets) => settings.filter((each) => each.secret === secrets && each.kinds.includes(kind));
107
+ export const settingsFor = (kind, secrets) => Object.freeze(settings.filter((each) => each.secret === secrets && each.kinds.includes(kind)));
108
+ // eslint-disable-next-line functional/prefer-immutable-types -- Zod schemas: immutable once built, but classes the rule cannot see into
104
109
  const shape = (chosen) => Object.fromEntries(chosen.map((each) => [each.name, each.schema.optional()]));
105
110
  /** vars.yml for a kind: its settings and nothing else (Ansible's own variables apart). */
111
+ // eslint-disable-next-line functional/prefer-immutable-types -- a Zod schema: immutable once built, but a class the rule cannot see into
106
112
  export const varsSchema = (kind) => z.strictObject(shape(settingsFor(kind, false)));
107
113
  /** defaults.yml: settings shared by every server, so any kind's. */
108
114
  export const defaultsSchema = z.strictObject(shape(settings.filter((each) => !each.secret)));
109
115
  /** secrets.yml: the known secrets typed; other keys may be helpers that vars.yml references. */
116
+ // eslint-disable-next-line functional/prefer-immutable-types -- a Zod schema: immutable once built, but a class the rule cannot see into
110
117
  export const secretsSchema = (kind) => z.looseObject(shape(settingsFor(kind, true)));
111
118
  /** server.yml: topology only. */
112
119
  export const serverSchema = z.strictObject({
@@ -1,12 +1,13 @@
1
- import { err, ok } from "./result.js";
1
+ import { err, ok } from "../../result.js";
2
2
  import { isAnsibleVariable, settings } from "./settings.js";
3
+ import { typed } from "../../typed.js";
3
4
  /** Edit distance, for "did you mean". */
4
- const indices = (length) => [...Array(length).keys()];
5
+ const indices = (length) => typed([...Array(length).keys()]);
5
6
  const distance = (a, b) => indices(b.length)
6
- .reduce((row, j) => indices(a.length).reduce((next, i) => [
7
+ .reduce((row, j) => indices(a.length).reduce((next, i) => Object.freeze([
7
8
  ...next,
8
9
  Math.min((row[i + 1] ?? 0) + 1, (next[i] ?? 0) + 1, (row[i] ?? 0) + (a.charAt(i) === b.charAt(j) ? 0 : 1)),
9
- ], [j + 1]), indices(a.length + 1))
10
+ ]), [j + 1]), indices(a.length + 1))
10
11
  .at(-1) ?? 0;
11
12
  /** The known name a key is most likely a typo of, if one is close enough. */
12
13
  export const closest = (key, known) => {
@@ -47,7 +48,7 @@ export const checkSettings = (file, values, schema, known) => {
47
48
  return parsed.success ? ok(values) : err(firstIssue(file, parsed.error, known, "is not a setting"));
48
49
  };
49
50
  /** The names a kind's vars.yml may set. */
50
- export const knownSettings = (kind) => settings.filter((each) => !each.secret && (kind === undefined || each.kinds.includes(kind))).map((each) => each.name);
51
+ export const knownSettings = (kind) => Object.freeze(settings.filter((each) => !each.secret && (kind === undefined || each.kinds.includes(kind))).map((each) => each.name));
51
52
  /** A YAML document against a schema, for files whose keys are not settings (server.yml, app.yml). */
52
53
  export const checkShape = (file, values, schema) => {
53
54
  const parsed = schema.safeParse(values);
@@ -0,0 +1,81 @@
1
+ import { commandOf, kindOf, titleOf } from "../plan/describe.js";
2
+ import { bad, muted, ok, pointing, strong, warn } from "../text/spans.js";
3
+ import { duration } from "../text/time.js";
4
+ import { parts, position } from "./progress.js";
5
+ import { count } from "../text/plural.js";
6
+ import { milliseconds } from "../fleet/brand.js";
7
+ import { typed } from "../../typed.js";
8
+ /** The heading for a command: as typed, what it runs on, which kayra. */
9
+ export const heading = (command, target, version) => typed({
10
+ command,
11
+ ...(target === undefined ? {} : { server: target.name }),
12
+ about: [...(target === undefined ? [] : [`${target.kind} on ${target.target}`, target.domain]), `kayra ${version}`],
13
+ });
14
+ /** "8 steps", or "15 checks" for a plan of nothing else (doctor). */
15
+ export const steps = (plan) => {
16
+ const noun = plan.every((step) => step.kind === "check") ? "check" : "step";
17
+ return count(plan.length, noun);
18
+ };
19
+ /** The footer: how it went, how long it took, and what reruns a failed part alone. */
20
+ export const footer = (invocation, plan, ended, ms) => {
21
+ const took = duration(ms);
22
+ const { command } = invocation;
23
+ const { stop } = ended;
24
+ if (stop === undefined)
25
+ return typed(ended.failures === 0 ? [[ok("✓"), " ", strong(command), muted(` · ${steps(plan)} · ${took}`)]] : [[bad("✗"), " ", strong(command), muted(` · ${String(ended.failures)} of ${steps(plan)} failed · ${took}`)]]);
26
+ const where = `step ${String(stop.index + 1)} of ${String(plan.length)}`;
27
+ if (stop.why === "declined")
28
+ return typed([[warn("■"), " ", strong(command), muted(` stopped at ${where}: not confirmed`)]]);
29
+ if (stop.why === "interrupted")
30
+ return typed([[warn("■"), " ", strong(command), muted(` interrupted at ${where} · ${took}`)]]);
31
+ const { part } = stop.step;
32
+ const alone = part !== undefined && parts(plan).length > 1 && invocation.server !== undefined;
33
+ return typed([
34
+ [bad("✗"), " ", strong(command), " failed at ", strong(titleOf(stop.step)), muted(` · ${where} · ${took}`)],
35
+ ...(alone ? [pointing(" ", strong(`kayra ${part} ${invocation.server ?? ""}`), muted(" runs just this part"))] : []),
36
+ ]);
37
+ };
38
+ /** Every step of a plan, its command's paths named by their root. */
39
+ export const listed = (plan, short) => Object.freeze(plan.map((step, index) => {
40
+ const command = commandOf(step);
41
+ const { opens } = position(plan, index);
42
+ return typed({
43
+ index,
44
+ kind: kindOf(step),
45
+ title: titleOf(step),
46
+ ...(command === undefined ? {} : { command: short(command) }),
47
+ ...(step.part === undefined ? {} : { part: step.part }),
48
+ ...(opens === undefined ? {} : { opens }),
49
+ });
50
+ }));
51
+ /** The plan and each step as events: what framed draws on a terminal, as data. */
52
+ export const reporting = (emit, invocation, short) => typed({
53
+ plan: async (plan, work) => {
54
+ const started = performance.now();
55
+ emit({ kind: "plan", invocation, steps: listed(plan, short) });
56
+ const ended = await work();
57
+ const ms = milliseconds(performance.now() - started);
58
+ emit({
59
+ kind: "ended",
60
+ failures: ended.failures,
61
+ ...(ended.stop === undefined ? {} : { stop: { index: ended.stop.index, why: ended.stop.why } }),
62
+ ms,
63
+ footer: footer(invocation, plan, ended, ms),
64
+ });
65
+ return ended;
66
+ },
67
+ step: async (_step, at, work) => {
68
+ const started = performance.now();
69
+ emit({ kind: "started", index: at.index });
70
+ const done = await work();
71
+ emit({
72
+ kind: "done",
73
+ index: at.index,
74
+ failed: done.failed,
75
+ stopped: done.stopped,
76
+ ...(done.why === undefined ? {} : { why: done.why }),
77
+ ms: milliseconds(performance.now() - started),
78
+ });
79
+ return done;
80
+ },
81
+ });
@@ -0,0 +1,18 @@
1
+ export const isStopped = (signal) => signal?.aborted === true;
2
+ /** Cancellation also ends a question; a late answer cannot restart the plan. */
3
+ export const ask = async (io, question) => {
4
+ if (isStopped(io.signal))
5
+ return undefined;
6
+ return new Promise((resolve, reject) => {
7
+ const done = (answer) => {
8
+ io.signal?.removeEventListener("abort", stopped);
9
+ resolve(answer);
10
+ };
11
+ const stopped = () => { done(undefined); };
12
+ io.signal?.addEventListener("abort", stopped, { once: true });
13
+ void io.ask(question).then(done, (error) => {
14
+ io.signal?.removeEventListener("abort", stopped);
15
+ reject(error instanceof Error ? error : new Error(String(error)));
16
+ });
17
+ });
18
+ };
@@ -0,0 +1,101 @@
1
+ import { bad, ok as fine, muted, pointing, strong } from "../text/spans.js";
2
+ import { position, silent } from "./progress.js";
3
+ import { ask, isStopped } from "./io.js";
4
+ import { answer, resolve, spawned } from "./process.js";
5
+ import { meet, scratch } from "./needs.js";
6
+ import { inPty } from "./pty.js";
7
+ import { typed } from "../../typed.js";
8
+ /** Lines as printing them one by one gives the text back: newline-ended, as a ctl writes. */
9
+ const asItCame = (_answer, said) => (said === "" ? typed([]) : said.replace(/\n$/, "").split("\n"));
10
+ const lines = (text) => Object.freeze(text
11
+ .trimEnd()
12
+ .split("\n")
13
+ .filter((line) => line !== ""));
14
+ /** Under the step's own line. */
15
+ const detail = (line) => typed([" ", line]);
16
+ const aside = (line) => typed([" ", muted(line)]);
17
+ const hint = (text) => (typed(text === undefined ? [] : [pointing(" ", text)]));
18
+ const goOn = { failed: false, stopped: false, out: [], err: [] };
19
+ const check = async (step, plumbing) => {
20
+ const exit = await answer(step.probe, plumbing);
21
+ const said = [...lines(exit.stderr).map(detail), ...hint(step.hint)];
22
+ if (step.onFailure === "stop")
23
+ return exit.code === 0 ? goOn : typed({ failed: true, stopped: true, out: [], err: said });
24
+ return typed(exit.code === 0 ? { ...goOn, out: [[fine("✓"), " ", step.label]] } : { failed: true, stopped: false, out: [[bad("✗"), " ", step.label], ...said], err: [] });
25
+ };
26
+ const runStep = async (step, io, met) => {
27
+ const argv = await resolve(step.argv, io);
28
+ if (!argv.ok)
29
+ return typed({ failed: true, stopped: true, why: "a query failed", out: [], err: [detail(argv.error)] });
30
+ const { stdout } = step;
31
+ const talks = step.kind === "session" && io.output !== undefined;
32
+ if (talks && io.input === undefined)
33
+ return typed({ failed: true, stopped: true, why: "no terminal", out: [], err: [detail("it talks with a person, and this client gives it no keys")] });
34
+ // A quiet step's stderr waits until it is done, so it cannot tear through a spinner.
35
+ const quiet = stdout === "discard";
36
+ const exit = await spawned(talks ? inPty(argv.value, io.size) : argv.value, {
37
+ stdout: typeof stdout === "string" ? stdout : "capture",
38
+ stderr: quiet ? "capture" : "show",
39
+ ...(talks && io.input !== undefined ? { stdin: { kind: "typed", input: io.input } } : met.stdin === undefined ? {} : { stdin: met.stdin }),
40
+ }, { ...step.env, ...met.env }, io);
41
+ if (!exit.started)
42
+ return typed({ failed: true, stopped: true, why: "not started", out: [], err: [detail(`${argv.value[0]}: ${exit.stderr}`)] });
43
+ // Whatever it answered is shown, even when it failed: it may say why.
44
+ const out = typeof stdout === "string" ? [] : (io.draw ?? asItCame)(stdout, exit.stdout);
45
+ if (exit.code === 0)
46
+ return typed({ ...goOn, out, err: lines(exit.stderr).map(aside) });
47
+ return typed({ failed: true, stopped: true, why: `exit ${String(exit.code)}`, out, err: lines(exit.stderr).map(detail) });
48
+ };
49
+ const perform = async (step, io, met) => {
50
+ switch (step.kind) {
51
+ case "session":
52
+ case "run":
53
+ return runStep(step, io, met);
54
+ case "check":
55
+ return check(step, io);
56
+ case "confirm": {
57
+ io.err("");
58
+ io.err([" ", bad("▲"), " ", strong(step.warning)]);
59
+ const answered = await ask(io, { kind: "confirm", text: [" Type ", strong(step.expect), " to confirm: "], expect: step.expect });
60
+ return answered === step.expect ? goOn : typed({ failed: false, stopped: true, out: ["Aborted."], err: [] });
61
+ }
62
+ case "note":
63
+ return typed({ ...goOn, out: [step.text] });
64
+ }
65
+ };
66
+ /**
67
+ * Runs a plan step by step, until it ends or a step stops it, shown by `progress`.
68
+ * True if nothing failed and the operator did not interrupt it.
69
+ */
70
+ export const interpret = async (plan, io, progress = silent, interrupted = () => false) => {
71
+ const made = scratch();
72
+ try {
73
+ const ended = await progress.plan(plan, () => plan.reduce(async (previous, step, index) => {
74
+ const so = await previous;
75
+ if (so.stop !== undefined)
76
+ return so;
77
+ if (interrupted() || isStopped(io.signal))
78
+ return { ...so, stop: { index, step, why: "interrupted" } };
79
+ // What a step needs is asked before its frame opens: a prompt, then the step.
80
+ const met = (step.kind === "run" || step.kind === "session") && step.needs !== undefined ? await meet(step.needs, so.asked, io, made) : { met: { env: {} }, asked: so.asked };
81
+ if (met === undefined) {
82
+ io.err([" ", muted("Nothing given: stopped before it ran.")]);
83
+ return { ...so, stop: { index, step, why: isStopped(io.signal) ? "interrupted" : "declined" } };
84
+ }
85
+ const done = await progress.step(step, position(plan, index), () => perform(step, io, met.met));
86
+ // Ctrl-C reached the step's program too: how it ended says nothing about the server.
87
+ if (interrupted() || isStopped(io.signal))
88
+ return { failures: so.failures, asked: met.asked, stop: { index, step, why: "interrupted" } };
89
+ done.out.forEach(io.out);
90
+ done.err.forEach(io.err);
91
+ const failures = so.failures + (done.failed ? 1 : 0);
92
+ if (done.stopped)
93
+ return { failures, asked: met.asked, stop: { index, step, why: done.failed ? "failed" : "declined" } };
94
+ return { failures, asked: met.asked };
95
+ }, Promise.resolve({ failures: 0, asked: {} })));
96
+ return ended.failures === 0 && ended.stop?.why !== "interrupted";
97
+ }
98
+ finally {
99
+ made.clean();
100
+ }
101
+ };