@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,89 @@
1
+ import { createInterface } from "node:readline/promises";
2
+ import { typed } from "../../typed.js";
3
+ /** The command line's questions: secret typing stays unseen, piped answers keep their order. */
4
+ export const questions = (render) => {
5
+ // eslint-disable-next-line functional/prefer-immutable-types -- resources belong to this reader and close with the plan
6
+ const reading = {};
7
+ const piped = async () => {
8
+ if (reading.lines === undefined) {
9
+ const terminal = createInterface({ input: process.stdin });
10
+ // eslint-disable-next-line functional/immutable-data -- keep buffered lines across questions
11
+ reading.lines = terminal[Symbol.asyncIterator]();
12
+ // eslint-disable-next-line functional/immutable-data -- release stdin when the plan ends
13
+ reading.close = () => { terminal.close(); };
14
+ }
15
+ const next = await reading.lines.next();
16
+ return next.done === true ? "" : next.value;
17
+ };
18
+ const prompted = (prompt, secret) => {
19
+ const { stdin } = process;
20
+ if (!secret) {
21
+ const terminal = createInterface({ input: stdin, output: process.stderr });
22
+ return new Promise((resolve) => {
23
+ const done = (answer) => {
24
+ resolve(answer);
25
+ terminal.close();
26
+ };
27
+ // eslint-disable-next-line functional/immutable-data -- cancellation closes the outstanding question
28
+ reading.close = () => { done(undefined); };
29
+ terminal.once("SIGINT", () => { done(undefined); });
30
+ terminal.once("close", () => { resolve(undefined); });
31
+ void terminal.question(prompt).then(done, () => { done(undefined); });
32
+ });
33
+ }
34
+ const wasRaw = stdin.isRaw;
35
+ stdin.setRawMode(true);
36
+ stdin.setEncoding("utf8");
37
+ stdin.resume();
38
+ return new Promise((resolve) => {
39
+ // eslint-disable-next-line functional/prefer-immutable-types -- typed characters until Enter or cancellation
40
+ const state = { text: "", ended: false };
41
+ const done = (answer) => {
42
+ if (state.ended)
43
+ return;
44
+ // eslint-disable-next-line functional/immutable-data -- finish once, even when a paste includes several lines
45
+ state.ended = true;
46
+ stdin.removeListener("data", key);
47
+ stdin.removeListener("end", ended);
48
+ stdin.setRawMode(wasRaw);
49
+ stdin.pause();
50
+ process.stderr.write("\n");
51
+ resolve(answer);
52
+ };
53
+ const ended = () => { done(undefined); };
54
+ const key = (chunk) => {
55
+ Array.from(chunk).forEach((char) => {
56
+ if (state.ended)
57
+ return;
58
+ if (char === "\r" || char === "\n")
59
+ done(state.text);
60
+ else if (char === "\u0003" || char === "\u0004")
61
+ done(undefined);
62
+ else if (char === "\u007f" || char === "\b") {
63
+ // eslint-disable-next-line functional/immutable-data -- remove one Unicode character
64
+ state.text = Array.from(state.text).slice(0, -1).join("");
65
+ }
66
+ else {
67
+ // eslint-disable-next-line functional/immutable-data -- append a typed character
68
+ state.text += char;
69
+ }
70
+ });
71
+ };
72
+ // eslint-disable-next-line functional/immutable-data -- cancellation restores terminal mode
73
+ reading.close = ended;
74
+ stdin.on("data", key);
75
+ stdin.once("end", ended);
76
+ process.stderr.write(prompt);
77
+ });
78
+ };
79
+ return typed({
80
+ ask: async (question) => {
81
+ const prompt = render(question.text);
82
+ if (process.stdin.isTTY)
83
+ return prompted(prompt, question.kind === "secret");
84
+ process.stderr.write(prompt);
85
+ return piped();
86
+ },
87
+ close: () => { reading.close?.(); },
88
+ });
89
+ };
@@ -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 "../../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 "../../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. */
@@ -59,6 +60,7 @@ export const spinner = (write, draw) => {
59
60
  write(escapes.clearLine);
60
61
  };
61
62
  };
63
+ /** A state change, as an answer brings it. */
62
64
  const tick = (ms) => new Promise((resolve) => {
63
65
  setTimeout(() => {
64
66
  resolve(undefined);
@@ -76,6 +78,7 @@ export const watch = async (write, initial, updates, draw) => {
76
78
  write(`${escapes.up(drawn)}${lines.map((line) => `${escapes.clearLine}${line}\n`).join("")}${escapes.clearDown}`);
77
79
  return lines.length;
78
80
  };
81
+ // Recursive: TypeScript cannot infer what it returns.
79
82
  const go = async (state, waiting, drawn) => {
80
83
  const shown = redraw(state, drawn);
81
84
  if (waiting.length === 0) {
@@ -89,16 +92,3 @@ export const watch = async (write, initial, updates, draw) => {
89
92
  };
90
93
  return go(initial, updates.map((update, id) => ({ id, landed: update.then((done) => ({ id, update: done })) })), 0);
91
94
  };
92
- /** What watch() returns, drawn nowhere: for a stream that is no terminal. */
93
- export const settle = async (initial, updates) => (await Promise.all(updates)).reduce((state, update) => update(state), initial);
94
- /** Each state as the updates land, in the order they land: for a viewer elsewhere (the web interface). */
95
- export const follow = async (initial, updates, each) => {
96
- const go = async (state, waiting) => {
97
- each(state);
98
- if (waiting.length === 0)
99
- return state;
100
- const next = await Promise.race(waiting.map((one) => one.landed));
101
- return go(next.update(state), waiting.filter((one) => one.id !== next.id));
102
- };
103
- return go(initial, updates.map((update, id) => ({ id, landed: update.then((done) => ({ id, update: done })) })));
104
- };
@@ -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 "../../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 "../../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 "../../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 "../../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,36 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { extname, join, normalize, sep } from "node:path";
3
+ const types = {
4
+ ".html": "text/html; charset=utf-8",
5
+ ".js": "text/javascript; charset=utf-8",
6
+ ".css": "text/css; charset=utf-8",
7
+ ".svg": "image/svg+xml",
8
+ ".png": "image/png",
9
+ ".ico": "image/x-icon",
10
+ ".woff2": "font/woff2",
11
+ ".json": "application/json; charset=utf-8",
12
+ };
13
+ const unbuilt = `<!doctype html><meta charset="utf-8"><title>kayra</title>
14
+ <body style="font:15px system-ui;margin:3rem auto;max-width:40rem"><h1>kayra</h1>
15
+ <p>The browser side is not built in this checkout:</p><pre>npm --prefix web ci &amp;&amp; npm --prefix web run build</pre>
16
+ <p>The API is up at <code>/api/fleet</code>.</p></body>`;
17
+ /**
18
+ * The built browser side (web/dist in a checkout, cli/dist/browser in the
19
+ * package); a path that is no file is the app's own route, answered by its
20
+ * index; without a build, a page saying how to make one.
21
+ */
22
+ export const serveAsset = (assets, path, response) => {
23
+ if (assets === undefined) {
24
+ response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
25
+ response.end(unbuilt);
26
+ return;
27
+ }
28
+ const file = normalize(join(assets, decodeURIComponent(path)));
29
+ const inside = file.startsWith(assets + sep) && existsSync(file) && statSync(file).isFile();
30
+ const chosen = inside ? file : join(assets, "index.html");
31
+ response.writeHead(200, {
32
+ "Content-Type": types[extname(chosen)] ?? "application/octet-stream",
33
+ "Cache-Control": chosen.includes(`${sep}assets${sep}`) ? "public, max-age=31536000, immutable" : "no-cache",
34
+ });
35
+ response.end(readFileSync(chosen));
36
+ };
@@ -0,0 +1,18 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { typed } from "../../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 "../../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 "../../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
+ };