@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
@@ -0,0 +1,75 @@
1
+ import { active, bad, ok as fine, link, muted, pointing, strong, warn } from "../../core/text/spans.js";
2
+ import { fit, table } from "./text.js";
3
+ import { authUrl } from "../../core/status/look.js";
4
+ import { typed } from "../../lib/typed.js";
5
+ /** A spinner as wide as most answers, so the columns hardly move when they come. */
6
+ const waiting = (frame, width) => typed([active(frame), " ".repeat(width - 1)]);
7
+ const machineCell = (machine, frame) => {
8
+ switch (machine.kind) {
9
+ case "pending":
10
+ return waiting(frame, "255.255.255.255".length);
11
+ case "found":
12
+ return typed([machine.address ?? muted("unknown")]);
13
+ case "not-provisioned":
14
+ return typed([muted("not provisioned")]);
15
+ case "no-machine":
16
+ return typed([muted("no machine")]);
17
+ case "unreadable":
18
+ return typed([bad("state unreadable")]);
19
+ }
20
+ };
21
+ const took = (ms) => muted(` ${String(ms)}ms`);
22
+ /** An answer, said the same way for both probes. */
23
+ const said = (reach, frame) => {
24
+ switch (reach.kind) {
25
+ case "pending":
26
+ return waiting(frame, "open 99ms".length);
27
+ case "skipped":
28
+ return typed([muted("–")]);
29
+ case "no-answer":
30
+ return typed([bad("no answer")]);
31
+ case "unreachable":
32
+ return typed([bad("unreachable")]);
33
+ case "unknown-host":
34
+ return typed([bad("unknown host")]);
35
+ case "bad-certificate":
36
+ return typed([bad(reach.code === "CERT_HAS_EXPIRED" ? "cert expired" : reach.code === "ERR_TLS_CERT_ALTNAME_INVALID" ? "wrong cert" : "untrusted cert")]);
37
+ case "failed":
38
+ return typed([bad(reach.code.toLowerCase())]);
39
+ case "refused":
40
+ return typed([bad("refused")]);
41
+ case "open":
42
+ return typed([fine("open"), took(reach.ms)]);
43
+ case "answered":
44
+ return typed([(reach.status < 400 ? fine : reach.status < 500 ? warn : bad)(String(reach.status)), took(reach.ms)]);
45
+ }
46
+ };
47
+ const sshCell = (reach, frame) => (reach.kind === "refused" ? typed([warn("off")]) : said(reach, frame));
48
+ const httpsCell = (reach, frame, url) => Object.freeze(said(reach, frame).map((span, index) => (index === 0 && typeof span !== "string" ? link(span.text, url, span.tone) : span)));
49
+ const headings = ["SERVER", "KIND", "TARGET", "DOMAIN", "ADDRESS", "SSH", "HTTPS", "APPS"];
50
+ const probed = ["SSH", "HTTPS"];
51
+ const row = (look, frame) => {
52
+ const { server } = look;
53
+ return typed([
54
+ [strong(server.name)],
55
+ [server.kind],
56
+ [server.target],
57
+ [link(server.domain, `https://${server.domain}/`)],
58
+ machineCell(look.machine, frame),
59
+ sshCell(look.ssh, frame),
60
+ look.https === undefined ? [] : httpsCell(look.https, frame, authUrl(server)),
61
+ [server.apps.map((app) => app.name).join(", ")],
62
+ ]);
63
+ };
64
+ /** Every server in a table, then what could not be read; --offline drops the probes' columns. */
65
+ export const statusView = (looks, drawing) => {
66
+ const shown = headings.flatMap((heading, index) => (drawing.offline && probed.includes(heading) ? Object.freeze([]) : Object.freeze([index])));
67
+ const rows = [headings.map((heading) => Object.freeze([muted(heading)])), ...looks.map((look) => row(look, drawing.frame))].map((cells) => Object.freeze(shown.map((index) => cells[index] ?? [])));
68
+ const notes = looks.flatMap((look) => typed(look.machine.kind === "unreadable" ? [
69
+ [" ", bad("✗"), " ", strong(look.server.name), `: OpenTofu's state could not be read: ${look.machine.reason}`],
70
+ ...(look.machine.reason === "tofu init needed"
71
+ ? [pointing(" ", `tofu -chdir=servers/${look.server.name}/terraform init`)]
72
+ : []),
73
+ ] : []));
74
+ return typed([...table(fit(rows, drawing.room, [shown.length - 1, shown.indexOf(3)])), ...(notes.length === 0 ? [] : [[], ...notes])]);
75
+ };
@@ -16,7 +16,7 @@ export const screen = (stream, env) => {
16
16
  const program = env["TERM_PROGRAM"] ?? "";
17
17
  // tmux and screen swallow what they do not know, or pass it to the wrong pane.
18
18
  const direct = live && env["TMUX"] === undefined && env["STY"] === undefined;
19
- return {
19
+ return typed({
20
20
  colors: colors(tty, env),
21
21
  live,
22
22
  // A pseudo-terminal may report 0.
@@ -25,7 +25,7 @@ export const screen = (stream, env) => {
25
25
  notifications: direct && notifying.includes(program),
26
26
  progressBar: direct && (showingProgress.includes(program) || env["WT_SESSION"] !== undefined),
27
27
  links: direct && linking.includes(program),
28
- };
28
+ });
29
29
  };
30
30
  const printable = (text) => text.replace(/\p{Cc}/gu, " ");
31
31
  const osc = (body) => `\u001b]${body}\u0007`;
@@ -43,6 +43,7 @@ export const escapes = {
43
43
  up: (count) => (count > 0 ? `\u001b[${String(count)}F` : ""),
44
44
  clearDown: "\u001b[J",
45
45
  };
46
+ import { typed } from "../../lib/typed.js";
46
47
  const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
47
48
  const frameOf = (ms) => frames[Math.floor(ms / 80) % frames.length] ?? "";
48
49
  /** Draws a line in place, again every frame, until stopped; stopping clears it. */
@@ -77,6 +78,7 @@ export const watch = async (write, initial, updates, draw) => {
77
78
  write(`${escapes.up(drawn)}${lines.map((line) => `${escapes.clearLine}${line}\n`).join("")}${escapes.clearDown}`);
78
79
  return lines.length;
79
80
  };
81
+ // Recursive: TypeScript cannot infer what it returns.
80
82
  const go = async (state, waiting, drawn) => {
81
83
  const shown = redraw(state, drawn);
82
84
  if (waiting.length === 0) {
@@ -1,22 +1,11 @@
1
- import { characters, width } from "./line.js";
2
- /** 0.4s, 12s, 2m03s, 1h04m: never more precise than it is worth reading. */
3
- export const duration = (ms) => {
4
- const seconds = Math.max(0, ms) / 1000;
5
- if (seconds < 10)
6
- return `${(Math.floor(seconds * 10) / 10).toFixed(1)}s`;
7
- if (seconds < 60)
8
- return `${String(Math.floor(seconds))}s`;
9
- const minutes = Math.floor(seconds / 60);
10
- if (minutes < 60)
11
- return `${String(minutes)}m${String(Math.floor(seconds % 60)).padStart(2, "0")}s`;
12
- return `${String(Math.floor(minutes / 60))}h${String(minutes % 60).padStart(2, "0")}m`;
13
- };
1
+ import { characters, width } from "../../core/text/spans.js";
2
+ import { typed } from "../../lib/typed.js";
14
3
  /** `left`, then `right` flush with the last column, at least two spaces apart. */
15
- export const spread = (left, right, columns) => [
4
+ export const spread = (left, right, columns) => typed([
16
5
  ...left,
17
6
  " ".repeat(Math.max(2, columns - width(left) - width(right))),
18
7
  ...right,
19
- ];
8
+ ]);
20
9
  /** At most `columns` wide, cut with an ellipsis: a line redrawn in place must not wrap. */
21
10
  export const truncate = (line, columns) => {
22
11
  if (width(line) <= columns)
@@ -28,14 +17,14 @@ export const truncate = (line, columns) => {
28
17
  const piece = typeof span === "string" ? kept : { ...span, text: kept };
29
18
  return { kept: kept === "" ? so.kept : [...so.kept, piece], room: so.room - chars.length };
30
19
  }, { kept: [], room: columns - 1 });
31
- return [...cut.kept, "…"];
20
+ return typed([...cut.kept, "…"]);
32
21
  };
33
22
  /** Words in lines of at most `columns`; a word longer than that gets a line of its own. */
34
23
  export const wrap = (words, columns) => words.reduce((lines, word) => {
35
24
  const last = lines.at(-1);
36
25
  if (last === undefined)
37
- return [word];
38
- return characters(last).length + 1 + characters(word).length <= columns ? [...lines.slice(0, -1), `${last} ${word}`] : [...lines, word];
26
+ return Object.freeze([word]);
27
+ return characters(last).length + 1 + characters(word).length <= columns ? Object.freeze([...lines.slice(0, -1), `${last} ${word}`]) : Object.freeze([...lines, word]);
39
28
  }, []);
40
29
  /** How long ago, as a reader rounds it: 45s ago, 12m ago, 30h ago, 3d ago. */
41
30
  export const ago = (ms) => {
@@ -49,10 +38,12 @@ export const ago = (ms) => {
49
38
  return hours < 48 ? `${String(hours)}h ago` : `${String(Math.floor(hours / 24))}d ago`;
50
39
  };
51
40
  /** Rows of cells in columns as wide as their widest cell, two spaces apart; nothing trails a row's last cell. */
41
+ /** Each column as wide as its widest cell. */
42
+ const columnWidths = (rows) => rows.reduce((most, row) => Object.freeze(Array.from({ length: Math.max(most.length, row.length) }, (_, at) => Math.max(most[at] ?? 0, width(row[at] ?? [])))), []);
52
43
  export const table = (rows) => {
53
- const filled = rows.map((row) => row.slice(0, row.findLastIndex((cell) => width(cell) > 0) + 1));
54
- const widths = filled.reduce((most, row) => Array.from({ length: Math.max(most.length, row.length) }, (_, at) => Math.max(most[at] ?? 0, width(row[at] ?? []))), []);
55
- return filled.map((row) => row.flatMap((cell, at) => (at === row.length - 1 ? cell : [...cell, " ".repeat((widths[at] ?? 0) - width(cell) + 2)])));
44
+ const filled = rows.map((row) => Object.freeze(row.slice(0, row.findLastIndex((cell) => width(cell) > 0) + 1)));
45
+ const widths = columnWidths(filled);
46
+ return Object.freeze(filled.map((row) => Object.freeze(row.flatMap((cell, at) => (at === row.length - 1 ? cell : typed([...cell, " ".repeat((widths[at] ?? 0) - width(cell) + 2)]))))));
56
47
  };
57
48
  /**
58
49
  * Rows for table() that fit `room` columns: the cells of the columns in
@@ -60,14 +51,14 @@ export const table = (rows) => {
60
51
  * heading's) width.
61
52
  */
62
53
  export const fit = (rows, room, shrink) => {
63
- const widths = rows.reduce((most, row) => Array.from({ length: Math.max(most.length, row.length) }, (_, at) => Math.max(most[at] ?? 0, width(row[at] ?? []))), []);
54
+ const widths = columnWidths(rows);
64
55
  const over = widths.reduce((sum, each) => sum + each, 0) + 2 * Math.max(0, widths.length - 1) - room;
65
56
  const cut = shrink.reduce((so, at) => {
66
57
  const now = so.widths[at] ?? 0;
67
58
  const less = Math.min(Math.max(0, so.over), Math.max(0, now - width(rows[0]?.[at] ?? [])));
68
- return { widths: so.widths.with(at, now - less), over: so.over - less };
59
+ return { widths: Object.freeze(so.widths.with(at, now - less)), over: so.over - less };
69
60
  }, { widths, over }).widths;
70
- return rows.map((row) => row.map((cell, at) => truncate(cell, cut[at] ?? width(cell))));
61
+ return Object.freeze(rows.map((row) => Object.freeze(row.map((cell, at) => truncate(cell, cut[at] ?? width(cell))))));
71
62
  };
72
63
  /** Paths by the root they are under, the longest first: the engine may live inside the fleet. */
73
64
  export const shortener = (roots) => (text) => roots.toSorted(([a], [b]) => b.length - a.length).reduce((short, [path, name]) => short.replaceAll(path, name), text);
@@ -0,0 +1,32 @@
1
+ import { bad, muted, ok, pointing, strong } from "../../core/text/spans.js";
2
+ import { count } from "../../core/text/plural.js";
3
+ import { overall, tally } from "../../core/validation/findings.js";
4
+ import { typed } from "../../lib/typed.js";
5
+ const marks = { problem: bad("✗"), unchecked: muted("·"), passed: ok("✓") };
6
+ /** "✗ 3 servers · 1 problem · 2 not checked" */
7
+ export const summary = (reports) => {
8
+ const { problems, unchecked: notChecked } = tally(reports);
9
+ return typed([
10
+ marks[overall(reports.flatMap((report) => report.findings))],
11
+ " ",
12
+ count(reports.length, "server"),
13
+ muted(" · "),
14
+ problems === 0 ? ok("no problems") : bad(count(problems, "problem")),
15
+ ...(notChecked === 0 ? [] : [muted(" · "), `${String(notChecked)} not checked`]),
16
+ ]);
17
+ };
18
+ /** Each server with its mark, its findings under it with what to do about them, then the summary. */
19
+ export const validateView = (reports) => {
20
+ const names = Math.max(0, ...reports.map((report) => report.server.name.length));
21
+ return typed([
22
+ ...reports.flatMap((report) => typed([
23
+ [marks[overall(report.findings)], " ", strong(report.server.name.padEnd(names)), muted(` ${report.server.kind} on ${report.server.target}`)],
24
+ ...report.findings.flatMap((each) => typed([
25
+ [" ", marks[each.result], " ", each.result === "passed" ? muted(each.text) : each.text],
26
+ ...(each.hint === undefined ? [] : [pointing(" ", each.hint)]),
27
+ ])),
28
+ [],
29
+ ])),
30
+ summary(reports),
31
+ ]);
32
+ };
@@ -0,0 +1,19 @@
1
+ import { text } from "@optique/core/message";
2
+ import { appName, domain, examples, serverName, subdomain } from "../../core/fleet/brand.js";
3
+ import { typed } from "../../lib/typed.js";
4
+ /** An Optique value parser that mints a brand: arguments arrive already validated. */
5
+ const minting = (metavar, mint, placeholder) => typed({
6
+ mode: "sync",
7
+ metavar,
8
+ placeholder,
9
+ // eslint-disable-next-line functional/prefer-immutable-types -- Optique's Message: readonly by contract, but a type the rule cannot see into
10
+ parse: (input) => {
11
+ const minted = mint(input);
12
+ return minted.ok ? { success: true, value: minted.value } : { success: false, error: [text(minted.error)] };
13
+ },
14
+ format: (value) => value,
15
+ });
16
+ export const appNameParser = minting("APP", appName, examples.app);
17
+ export const serverNameParser = minting("SERVER", serverName, examples.server);
18
+ export const domainParser = minting("DOMAIN", domain, examples.domain);
19
+ export const subdomainParser = minting("SUBDOMAIN", subdomain, examples.subdomain);
@@ -1,94 +1,62 @@
1
- import { z } from "zod";
2
- import { accent, active, bad, muted, ok, strong, warn } from "./line.js";
3
- import { ago, duration, table } from "./text.js";
4
- const deployed = z.object({ sha: z.string(), time: z.iso.datetime() });
5
- /** `ctl runs <app> --json`, as this kayra reads it. */
6
- export const runsSchema = z.object({
7
- app: z.string(),
8
- live: deployed.exactOptional(),
9
- runs: z.array(z.object({
10
- id: z.string(),
11
- state: z.enum(["running", "success", "failure"]),
12
- why: z.string(),
13
- what: z.string(),
14
- sha: z.string().exactOptional(),
15
- started: z.iso.datetime(),
16
- finished: z.iso.datetime().exactOptional(),
17
- })),
18
- });
19
- /** `ctl rollback <app> --json`, as this kayra reads it. */
20
- export const releasesSchema = z.object({
21
- app: z.string(),
22
- releases: z.array(deployed.extend({ live: z.boolean() })),
23
- });
24
- /** The answer as the schema has it, or nothing: then it is not the answer this kayra expects. */
25
- export const parsed = (schema, answer) => {
26
- try {
27
- const json = JSON.parse(answer);
28
- const result = schema.safeParse(json);
29
- return result.success ? result.data : undefined;
30
- }
31
- catch {
32
- return undefined;
33
- }
34
- };
1
+ import { accent, active, bad, muted, ok, pointing, strong, warn } from "../../core/text/spans.js";
2
+ import { ago, table } from "./text.js";
3
+ import { duration } from "../../core/text/time.js";
4
+ import { parsed, releasesSchema, runsSchema } from "../../core/ctl/answers.js";
5
+ import { count } from "../../core/text/plural.js";
6
+ import { milliseconds } from "../../core/fleet/brand.js";
7
+ import { typed } from "../../lib/typed.js";
35
8
  /** Lines as printing them one by one gives the text back: newline-ended, as a ctl writes. */
36
- const linesOf = (text) => (text === "" ? [] : text.replace(/\n$/, "").split("\n"));
9
+ const linesOf = (text) => (text === "" ? typed([]) : text.replace(/\n$/, "").split("\n"));
37
10
  const short = (sha) => sha.slice(0, 7);
38
- const since = (time, now) => ago(now - Date.parse(time));
39
- const heading = (view, ...more) => [strong(view.app), muted(` on ${view.server}`), ...more];
40
- const live = (release, now) => release === undefined
41
- ? [muted(" · not deployed yet")]
42
- : [muted(" · live "), accent(short(release.sha)), muted(` since ${since(release.time, now)}`)];
43
- const hint = (command, what) => [" ", active("→"), " ", strong(command), muted(` ${what}`)];
11
+ const since = (time, now) => ago(milliseconds(now - Date.parse(time)));
12
+ const heading = (view, ...more) => typed([strong(view.app), muted(` on ${view.server}`), ...more]);
13
+ const live = (release, now) => typed(release === undefined ? [muted(" · not deployed yet")] : [muted(" · live "), accent(short(release.sha)), muted(` since ${since(release.time, now)}`)]);
14
+ const hint = (command, what) => pointing(" ", strong(command), muted(` ${what}`));
44
15
  const states = {
45
16
  success: [ok("✓ success")],
46
17
  failure: [bad("✗ failure")],
47
18
  running: [active("◆ running")],
48
19
  };
49
- const took = (run, now) => run.finished === undefined
50
- ? [active(`${duration(now - Date.parse(run.started))}…`)]
51
- : [duration(Date.parse(run.finished) - Date.parse(run.started))];
20
+ const took = (run, now) => typed(run.finished === undefined ? [active(`${duration(milliseconds(now - Date.parse(run.started)))}…`)] : [duration(milliseconds(Date.parse(run.finished) - Date.parse(run.started)))]);
52
21
  const commit = (run, release) => {
53
22
  if (run.sha === undefined)
54
- return [muted("—")];
55
- return run.sha === release?.sha ? [accent(short(run.sha))] : [short(run.sha)];
23
+ return typed([muted("—")]);
24
+ return typed(run.sha === release?.sha ? [accent(short(run.sha))] : [short(run.sha)]);
56
25
  };
57
26
  /** `kayra app runs`: what runs now, then a table of the newest runs. */
58
27
  export const runsView = (view, answer, now) => {
59
28
  const rows = table([
60
- ["STATE", "COMMIT", "WHY", "WHEN", "TOOK", "RUN"].map((title) => [muted(title)]),
61
- ...answer.runs.map((run) => [states[run.state], commit(run, answer.live), [run.why], [since(run.started, now)], took(run, now), [muted(run.id)]]),
29
+ ["STATE", "COMMIT", "WHY", "WHEN", "TOOK", "RUN"].map((title) => Object.freeze([muted(title)])),
30
+ ...answer.runs.map((run) => Object.freeze([states[run.state], commit(run, answer.live), [run.why], [since(run.started, now)], took(run, now), [muted(run.id)]])),
62
31
  ]);
63
- return [
32
+ return typed([
64
33
  heading(view, ...live(answer.live, now)),
65
34
  [],
66
35
  ...(answer.runs.length === 0
67
36
  ? [[" ", muted("no runs yet")]]
68
- : [...rows.map((row) => [" ", ...row]), [], hint(`kayra app logs ${view.server} ${view.app} [RUN]`, "shows a run's log, the newest by default")]),
69
- ];
37
+ : [...rows.map((row) => typed([" ", ...row])), [], hint(`kayra app logs ${view.server} ${view.app} [RUN]`, "shows a run's log, the newest by default")]),
38
+ ]);
70
39
  };
71
40
  /** `kayra app rollback` without a commit: every release, the live one marked, and how to go back to one. */
72
41
  export const releasesView = (view, answer, now) => {
73
42
  const earlier = answer.releases.find((release) => !release.live);
74
43
  const rows = table([
75
44
  [[muted(" COMMIT")], [muted("DEPLOYED")]],
76
- ...answer.releases.map((release) => [
45
+ ...answer.releases.map((release) => Object.freeze([
77
46
  release.live ? [ok("●"), " ", accent(short(release.sha))] : [" ", short(release.sha)],
78
47
  [since(release.time, now)],
79
48
  release.live ? [ok("live")] : [],
80
- ]),
49
+ ])),
81
50
  ]);
82
- const count = answer.releases.length;
83
- return [
84
- heading(view, muted(` · ${String(count)} release${count === 1 ? "" : "s"}`)),
51
+ return typed([
52
+ heading(view, muted(` · ${count(answer.releases.length, "release")}`)),
85
53
  [],
86
- ...rows.map((row) => [" ", ...row]),
54
+ ...rows.map((row) => typed([" ", ...row])),
87
55
  [],
88
56
  earlier === undefined
89
57
  ? [" ", muted("nothing earlier to roll back to")]
90
58
  : hint(`kayra app rollback ${view.server} ${view.app} ${short(earlier.sha)}`, "deploys that one again"),
91
- ];
59
+ ]);
92
60
  };
93
61
  const errors = /\b(error|fatal|failed|failure|panic|refused|denied|unhealthy)\b/i;
94
62
  const warnings = /\b(warn|warning|deprecated)\b/i;
@@ -97,10 +65,10 @@ const stamped = /^(\d{2}:\d{2}:\d{2} )(.*)$/s;
97
65
  const logLine = (line) => {
98
66
  const [, time = "", text = line] = stamped.exec(line) ?? [];
99
67
  const tone = errors.test(text) ? bad : warnings.test(text) ? warn : text.startsWith("── ") ? strong : text.startsWith("Deployed ") ? ok : undefined;
100
- return [...(time === "" ? [] : [muted(time)]), tone === undefined ? text : tone(text)];
68
+ return typed([...(time === "" ? [] : [muted(time)]), tone === undefined ? text : tone(text)]);
101
69
  };
102
70
  /** `kayra app logs`: the log as it is, its errors and warnings marked; uncoloured, the same bytes. */
103
- export const logView = (log) => linesOf(log).map(logLine);
71
+ export const logView = (log) => Object.freeze(linesOf(log).map(logLine));
104
72
  /** A deployer's answer as its view draws it, or as it came if it is not what the view reads (an older ctl). */
105
73
  export const draw = (view, answer, now) => {
106
74
  switch (view.view) {
@@ -0,0 +1,18 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { typed } from "../../lib/typed.js";
3
+ /** A file's text; undefined where there is none. */
4
+ export const textAt = (path) => (existsSync(path) ? readFileSync(path, "utf8") : undefined);
5
+ /** The folders in a directory, by name; none where it is missing. */
6
+ export const foldersIn = (path) => existsSync(path)
7
+ ? readdirSync(path, { withFileTypes: true })
8
+ .filter((entry) => entry.isDirectory())
9
+ .map((entry) => entry.name)
10
+ .toSorted()
11
+ : typed([]);
12
+ /** The files in a directory ending in `suffix`, by name; none where it is missing. */
13
+ export const filesIn = (path, suffix) => existsSync(path)
14
+ ? readdirSync(path, { withFileTypes: true })
15
+ .filter((entry) => entry.isFile() && entry.name.endsWith(suffix))
16
+ .map((entry) => entry.name)
17
+ .toSorted()
18
+ : typed([]);
@@ -1,9 +1,24 @@
1
1
  import { Agent, request } from "node:https";
2
2
  import { connect } from "node:net";
3
3
  import { getCACertificates } from "node:tls";
4
- import { failure } from "./commands/status.js";
4
+ import { milliseconds } from "../fleet/brand.js";
5
+ import { typed } from "../../lib/typed.js";
6
+ /** Why a connection failed, by Node's error code. */
7
+ export const failure = (code) => {
8
+ if (code === "ECONNREFUSED")
9
+ return typed({ kind: "refused" });
10
+ if (code === "ETIMEDOUT")
11
+ return typed({ kind: "no-answer" });
12
+ if (["EHOSTUNREACH", "ENETUNREACH", "EHOSTDOWN", "EADDRNOTAVAIL"].includes(code))
13
+ return typed({ kind: "unreachable" });
14
+ if (["ENOTFOUND", "EAI_AGAIN", "EAI_NONAME", "EAI_NODATA"].includes(code))
15
+ return typed({ kind: "unknown-host" });
16
+ if (/CERT|SELF_SIGNED|UNABLE_TO_(GET|VERIFY)/.test(code))
17
+ return typed({ kind: "bad-certificate", code });
18
+ return typed({ kind: "failed", code });
19
+ };
5
20
  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);
21
+ const since = (started) => milliseconds(Math.round(performance.now() - started));
7
22
  /** 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
23
  export const network = (ms) => {
9
24
  // A multipass server's certificates are mkcert's, whose root is in the system's store, not Node's.
@@ -13,10 +28,10 @@ export const network = (ms) => {
13
28
  resolve(new Agent({ ca: [...new Set([...getCACertificates("default"), ...getCACertificates("system")])] }));
14
29
  });
15
30
  });
16
- return {
31
+ return typed({
17
32
  connect: (host, port) => new Promise((resolve) => {
18
33
  const started = performance.now();
19
- const socket = connect({ host, port, timeout: ms });
34
+ const socket = connect({ host, port: Number(port), timeout: ms });
20
35
  socket.once("connect", () => {
21
36
  socket.destroy();
22
37
  resolve({ kind: "open", ms: since(started) });
@@ -48,5 +63,5 @@ export const network = (ms) => {
48
63
  asked.end();
49
64
  });
50
65
  },
51
- };
66
+ });
52
67
  };
@@ -0,0 +1,24 @@
1
+ import { capture } from "../interpreter/process.js";
2
+ import { err, ok } from "../../lib/result.js";
3
+ /** Why tofu could not read the state, in a few words: the first line of its error. */
4
+ export const unreadable = (stderr) => {
5
+ if (stderr.includes("tofu init"))
6
+ return "tofu init needed";
7
+ const line = stderr
8
+ .split("\n")
9
+ .map((each) => each.replace(/^[│╷╵\s]+/, "").replace(/^Error:\s*/, "").trim())
10
+ .find((each) => each !== "");
11
+ return line ?? "tofu failed";
12
+ };
13
+ /** OpenTofu, read and never changed. */
14
+ export const opentofu = {
15
+ state: async (dir) => {
16
+ const listed = await capture(["tofu", `-chdir=${dir}`, "state", "list", "-no-color"], "capture");
17
+ return listed.code === 0 ? ok(listed.stdout.split("\n").filter((line) => line.trim() !== "")) : err(unreadable(listed.stderr));
18
+ },
19
+ output: async (dir, name) => {
20
+ const value = await capture(["tofu", `-chdir=${dir}`, "output", "-raw", name], "capture");
21
+ const text = value.stdout.trim();
22
+ return value.code === 0 && text !== "" ? text : undefined;
23
+ },
24
+ };
@@ -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,54 @@
1
+ import { homedir } from "node:os";
2
+ import { isAbsolute, join, normalize } from "node:path";
3
+ import { z } from "zod";
4
+ import { branded } from "../../lib/brand.js";
5
+ import { err, ok } from "../../lib/result.js";
6
+ import { minting } from "../../lib/schema.js";
7
+ /** A string matching `regex`: brand it, and it is the schema the fleet's files are parsed with and the constructor everything else mints with. */
8
+ // eslint-disable-next-line functional/prefer-immutable-types -- a RegExp, and a Zod schema: immutable once built, but classes the rule cannot see into
9
+ const pattern = (regex, what) => z.string().regex(regex, { error: (issue) => `'${String(issue.input)}' is not ${what}` });
10
+ export const serverNameSchema = pattern(/^[a-z0-9][a-z0-9-]*$/, "a server name (lowercase letters, digits, dashes)").transform(branded());
11
+ export const appNameSchema = pattern(/^[a-z][a-z0-9-]*$/, "an app name (lowercase letters, digits, dashes)").transform(branded());
12
+ export const subdomainSchema = pattern(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/, "a subdomain").transform(branded());
13
+ export const domainSchema = pattern(/^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z][a-z0-9-]*$/, "a domain").transform(branded());
14
+ /** A path inside a repository, never above it. */
15
+ export const repoPathSchema = z
16
+ .string()
17
+ .refine((value) => !`/${value}/`.includes("/../"), { error: "path must stay inside its repo" })
18
+ .transform(branded());
19
+ /** Where an app's repository is cloned from: which schemes, the server's target says. */
20
+ export const repoUrlSchema = z.string().transform(branded());
21
+ export const serverName = minting(serverNameSchema);
22
+ export const appName = minting(appNameSchema);
23
+ export const subdomain = minting(subdomainSchema);
24
+ export const domain = minting(domainSchema);
25
+ export const repoPath = minting(repoPathSchema);
26
+ /** `~/…` is the operator's home, as Ansible reads it in vault_password_file. */
27
+ export const absolutePath = (value) => {
28
+ const expanded = value === "~" || value.startsWith("~/") ? join(homedir(), value.slice(1)) : value;
29
+ return isAbsolute(expanded) ? ok(normalize(expanded)) : err(`'${value}' is not an absolute path`);
30
+ };
31
+ export const kayraRoot = (path) => path;
32
+ export const fleetRoot = (path) => path;
33
+ export const serverDir = (root, name) => join(root, "servers", name);
34
+ export const vaultPasswordFile = (path) => path;
35
+ export const within = (base, ...segments) => join(base, ...segments);
36
+ /** One of each, as help shows a value: what a command-line parser offers before the operator types one. */
37
+ export const examples = {
38
+ app: "app",
39
+ server: "server",
40
+ domain: "example.com",
41
+ subdomain: "www",
42
+ };
43
+ /** A word without whitespace: what an inventory gives for a host, a user or a key. */
44
+ const word = (what, mint) => (value) => /^\S+$/.test(value) ? ok(mint(value)) : err(`'${value}' is not ${what}`);
45
+ export const host = word("a host", (value) => value);
46
+ export const sshUser = word("an ssh user", (value) => value);
47
+ export const keyFile = word("a key file", (value) => value);
48
+ /** Where ssh listens unless the inventory says otherwise. */
49
+ export const sshDefaultPort = "22";
50
+ export const port = (value) => /^\d+$/.test(value) && Number(value) >= 1 && Number(value) <= 65535 ? ok(value) : err(`'${value}' is not a port`);
51
+ export const remotePath = (value) => value.startsWith("/") ? ok(value) : err(`'${value}' is not an absolute path`);
52
+ export const milliseconds = (value) => Math.max(0, value);
53
+ export const exitCode = (value) => value;
54
+ 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 "../../lib/typed.js";
3
4
  const version = "https://json-schema.org/draft/2020-12/schema";
4
- const jsonSchema = (title, schema) => ({
5
- ...z.toJSONSchema(schema, { target: "draft-2020-12", unrepresentable: "any" }),
5
+ const jsonSchema = (title, schema) => typed({
6
+ ...z.toJSONSchema(schema, { target: "draft-2020-12", unrepresentable: "any", io: "input" }),
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/core/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,45 @@
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 { parseServer } from "./parse.js";
6
+ import { fields } from "../../lib/yaml.js";
7
+ import { all, attempt, err, flatMap, map, ok } from "../../lib/result.js";
8
+ import { defaultsSchema } from "./settings.js";
9
+ import { checkSettings, knownSettings } from "./shape.js";
10
+ /** The fleet is the nearest directory, from `from` upwards, with a servers/defaults.yml. */
11
+ export const findFleetRoot = (from) => {
12
+ const upwards = Array.from({ length: from.split(sep).length }, (_, up) => within(from, ...Array.from({ length: up }, () => "..")));
13
+ const found = upwards.find((dir) => existsSync(join(dir, "servers", "defaults.yml")));
14
+ return found === undefined ? err("no fleet here: no servers/defaults.yml in this directory or above it") : ok(fleetRoot(found));
15
+ };
16
+ /** Every file of a server, read once: what every command, and validate, works from. */
17
+ const readServer = (root, entry) => {
18
+ const name = serverName(entry);
19
+ if (!name.ok)
20
+ return err(`servers/${entry}: ${name.error}`);
21
+ const dir = serverDir(root, name.value);
22
+ const server = parseServer({
23
+ name: name.value,
24
+ dir,
25
+ descriptor: textAt(join(dir, "server.yml")) ?? "",
26
+ vars: textAt(join(dir, "vars.yml")),
27
+ secrets: textAt(join(dir, "secrets.yml")),
28
+ inventory: textAt(join(dir, "inventory.ini")),
29
+ hasTerraform: existsSync(join(dir, "terraform")),
30
+ stacks: foldersIn(join(dir, "stacks")).map((stack) => ({ name: stack, compose: textAt(join(dir, "stacks", stack, "compose.yaml")) })),
31
+ appValues: filesIn(join(dir, "apps"), ".yml").map((file) => ({ file, text: textAt(join(dir, "apps", file)) ?? "" })),
32
+ });
33
+ return server.ok ? server : err(`servers/${entry}/server.yml: ${server.error}`);
34
+ };
35
+ /** servers/defaults.yml: settings shared by every server, any kind's. */
36
+ const checkDefaults = (root) => {
37
+ const values = fields(textAt(join(root, "servers", "defaults.yml")) ?? "");
38
+ if (!values.ok)
39
+ return err(`servers/defaults.yml ${values.error}`);
40
+ return map(checkSettings("servers/defaults.yml", values.value, defaultsSchema, knownSettings(undefined)), () => true);
41
+ };
42
+ const fleetOf = (root) => map(all(foldersIn(join(root, "servers"))
43
+ .filter((entry) => existsSync(join(root, "servers", entry, "server.yml")))
44
+ .map((entry) => readServer(root, entry))), (servers) => ({ root, servers }));
45
+ 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"];