@rocket.chat/houston 0.27.0-next.3 → 2.1.9

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 (294) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +109 -15
  3. package/bin/houston +62 -0
  4. package/data/docs/ARCHITECTURE.md +387 -0
  5. package/data/docs/automation.md +107 -0
  6. package/data/docs/e2ee.md +76 -0
  7. package/data/docs/eks.md +258 -0
  8. package/data/docs/gui.md +282 -0
  9. package/data/docs/guide.md +642 -0
  10. package/data/docs/kubernetes.md +138 -0
  11. package/data/docs/loadtest.md +264 -0
  12. package/data/docs/troubleshooting.md +203 -0
  13. package/data/docs/upgrading.md +84 -0
  14. package/data/docs/voice.md +253 -0
  15. package/data/iam/engineer-policy.json +11 -0
  16. package/data/iam/engineer-rbac.yaml +42 -0
  17. package/data/iam/operator-policy.json +211 -0
  18. package/data/loadtest/badbot.js +22 -0
  19. package/data/loadtest/common.js +170 -0
  20. package/data/loadtest/custom.js +20 -0
  21. package/data/loadtest/journey.js +58 -0
  22. package/data/loadtest/login.js +18 -0
  23. package/data/loadtest/messages.js +13 -0
  24. package/data/loadtest/mixed.js +57 -0
  25. package/data/loadtest/read.js +12 -0
  26. package/data/loadtest/webhook.js +20 -0
  27. package/data/monitoring/houston-logs.json +98 -0
  28. package/data/monitoring/k6-loadtest.json +610 -0
  29. package/data/monitoring/mongodb-exporter.json +3007 -0
  30. package/data/monitoring/node-exporter-full.json +16114 -0
  31. package/data/monitoring/rocketchat-metrics.json +6471 -0
  32. package/data/presets/airgapped.yaml +16 -0
  33. package/data/presets/default.yaml +9 -0
  34. package/data/seed/avatar-0.png +0 -0
  35. package/data/seed/avatar-1.png +0 -0
  36. package/data/seed/avatar-2.png +0 -0
  37. package/data/seed/avatar-3.png +0 -0
  38. package/data/seed/avatar-4.png +0 -0
  39. package/data/seed/avatar-5.png +0 -0
  40. package/data/seed/avatar-6.png +0 -0
  41. package/data/seed/avatar-7.png +0 -0
  42. package/data/seed/seed-metrics.csv +3 -0
  43. package/data/seed/seed-preview.png +0 -0
  44. package/data/seed/seed-report.pdf +32 -0
  45. package/data/seed/seed-runbook.txt +3 -0
  46. package/data/skill/SKILL.md +399 -0
  47. package/data/versions.yaml +55 -0
  48. package/data/voice/freeswitch/drachtio.xml +52 -0
  49. package/data/voice/freeswitch/public.xml +87 -0
  50. package/data/webui/app.css +2003 -0
  51. package/data/webui/index.html +678 -0
  52. package/data/webui/js/api.js +561 -0
  53. package/data/webui/js/boot.js +44 -0
  54. package/data/webui/js/clusters-tail.js +1377 -0
  55. package/data/webui/js/clusters.js +896 -0
  56. package/data/webui/js/create.js +276 -0
  57. package/data/webui/js/detail.js +507 -0
  58. package/data/webui/js/jobs.js +636 -0
  59. package/data/webui/js/logs.js +634 -0
  60. package/data/webui/js/main.js +14 -0
  61. package/data/webui/js/options.js +408 -0
  62. package/data/webui/js/people.js +438 -0
  63. package/data/webui/js/perf.js +303 -0
  64. package/data/webui/js/render.js +438 -0
  65. package/data/webui/js/shared.js +3 -0
  66. package/data/webui/js/state.js +583 -0
  67. package/data/webui/js/theme.js +123 -0
  68. package/data/webui/js/util.js +584 -0
  69. package/dist/cli/app.js +593 -0
  70. package/dist/cli/capabilities.js +76 -0
  71. package/dist/cli/cell-widths.js +495 -0
  72. package/dist/cli/entry.js +10 -0
  73. package/dist/cli/error-panel.js +492 -0
  74. package/dist/cli/handlers/actor.js +84 -0
  75. package/dist/cli/handlers/https.js +614 -0
  76. package/dist/cli/handlers/prompt.js +299 -0
  77. package/dist/cli/handlers/users.js +226 -0
  78. package/dist/cli/handlers.js +3694 -0
  79. package/dist/cli/help.js +183 -0
  80. package/dist/cli/index.js +15 -0
  81. package/dist/cli/perf.js +814 -0
  82. package/dist/cli/render.js +254 -0
  83. package/dist/cli/serve.js +858 -0
  84. package/dist/cli/spec-data.js +2599 -0
  85. package/dist/cli/spec-types.js +8 -0
  86. package/dist/cli/usage-error.js +520 -0
  87. package/dist/cli/wire.js +70 -0
  88. package/dist/core/audit.js +346 -0
  89. package/dist/core/backup-compat.js +85 -0
  90. package/dist/core/backup.js +1639 -0
  91. package/dist/core/cluster.js +1398 -0
  92. package/dist/core/configimport.js +345 -0
  93. package/dist/core/data.js +267 -0
  94. package/dist/core/database-of.js +82 -0
  95. package/dist/core/diagnose.js +159 -0
  96. package/dist/core/doctor.js +1518 -0
  97. package/dist/core/edge/acme.js +338 -0
  98. package/dist/core/edge/engine.js +500 -0
  99. package/dist/core/edge/networks.js +174 -0
  100. package/dist/core/edge/paths.js +107 -0
  101. package/dist/core/edge/routes.js +251 -0
  102. package/dist/core/edge/routeyml.js +195 -0
  103. package/dist/core/edge/runtime.js +493 -0
  104. package/dist/core/edge/spec.js +305 -0
  105. package/dist/core/edge/types.js +202 -0
  106. package/dist/core/eks-docs.js +135 -0
  107. package/dist/core/eks.js +2240 -0
  108. package/dist/core/envvars.js +562 -0
  109. package/dist/core/eventlog.js +541 -0
  110. package/dist/core/firstrun.js +153 -0
  111. package/dist/core/journal.js +694 -0
  112. package/dist/core/kube/ask.js +231 -0
  113. package/dist/core/kube/capabilities.js +269 -0
  114. package/dist/core/kube/certmanager.js +452 -0
  115. package/dist/core/kube/chart.js +413 -0
  116. package/dist/core/kube/cluster.js +196 -0
  117. package/dist/core/kube/context.js +545 -0
  118. package/dist/core/kube/endpoints.js +448 -0
  119. package/dist/core/kube/exec.js +195 -0
  120. package/dist/core/kube/forward.js +732 -0
  121. package/dist/core/kube/grafana-ingress.js +110 -0
  122. package/dist/core/kube/ingress.js +218 -0
  123. package/dist/core/kube/manifests.js +361 -0
  124. package/dist/core/kube/monitoring.js +768 -0
  125. package/dist/core/kube/names.js +237 -0
  126. package/dist/core/kube/namespace.js +678 -0
  127. package/dist/core/kube/operator.js +941 -0
  128. package/dist/core/kube/probe.js +202 -0
  129. package/dist/core/kube/reachability.js +163 -0
  130. package/dist/core/kube/release.js +439 -0
  131. package/dist/core/kube/replicaset.js +180 -0
  132. package/dist/core/kube/scale.js +398 -0
  133. package/dist/core/kube/status.js +633 -0
  134. package/dist/core/kube/tools.js +238 -0
  135. package/dist/core/kube/transfer.js +173 -0
  136. package/dist/core/kube/workspace.js +423 -0
  137. package/dist/core/lifecycle/admin.js +64 -0
  138. package/dist/core/lifecycle/create-docker.js +1549 -0
  139. package/dist/core/lifecycle/create-k8s.js +960 -0
  140. package/dist/core/lifecycle/destroy.js +339 -0
  141. package/dist/core/lifecycle/inspect.js +636 -0
  142. package/dist/core/lifecycle/naming.js +298 -0
  143. package/dist/core/lifecycle/notes.js +862 -0
  144. package/dist/core/lifecycle/ownership.js +313 -0
  145. package/dist/core/lifecycle/payload.js +401 -0
  146. package/dist/core/lifecycle/ports.js +388 -0
  147. package/dist/core/lifecycle/preconditions.js +367 -0
  148. package/dist/core/lifecycle/pruning.js +551 -0
  149. package/dist/core/lifecycle/ready.js +818 -0
  150. package/dist/core/lifecycle/request.js +510 -0
  151. package/dist/core/lifecycle/seeding.js +281 -0
  152. package/dist/core/lifecycle/sizing.js +392 -0
  153. package/dist/core/lifecycle/state.js +286 -0
  154. package/dist/core/lifecycle/tlsplan.js +704 -0
  155. package/dist/core/lifecycle/types.js +232 -0
  156. package/dist/core/loadtest.js +1051 -0
  157. package/dist/core/migrate.js +612 -0
  158. package/dist/core/monitor.js +494 -0
  159. package/dist/core/postready.js +976 -0
  160. package/dist/core/promote.js +804 -0
  161. package/dist/core/rcapi.js +1336 -0
  162. package/dist/core/recovery.js +75 -0
  163. package/dist/core/runner/engine.js +394 -0
  164. package/dist/core/runner/host.js +298 -0
  165. package/dist/core/runner/locks.js +129 -0
  166. package/dist/core/runner/paths.js +173 -0
  167. package/dist/core/runner/ports.js +172 -0
  168. package/dist/core/runner/queries.js +612 -0
  169. package/dist/core/runner/record.js +563 -0
  170. package/dist/core/scaleseed.js +271 -0
  171. package/dist/core/seed-db.js +208 -0
  172. package/dist/core/sessions.js +472 -0
  173. package/dist/core/skill.js +326 -0
  174. package/dist/core/sso-identities.js +172 -0
  175. package/dist/core/sso.js +703 -0
  176. package/dist/core/tls-local.js +311 -0
  177. package/dist/core/tls.js +878 -0
  178. package/dist/core/topology.js +482 -0
  179. package/dist/core/upgrade.js +877 -0
  180. package/dist/core/users.js +739 -0
  181. package/dist/lib/audit.js +100 -0
  182. package/dist/lib/close-matches.js +238 -0
  183. package/dist/lib/compose.js +672 -0
  184. package/dist/lib/config.js +1398 -0
  185. package/dist/lib/context.js +18 -0
  186. package/dist/lib/errors.js +305 -0
  187. package/dist/lib/events.js +208 -0
  188. package/dist/lib/float-text.js +126 -0
  189. package/dist/lib/format.js +1320 -0
  190. package/dist/lib/home.js +325 -0
  191. package/dist/lib/journal.js +122 -0
  192. package/dist/lib/json-text.js +733 -0
  193. package/dist/lib/jsonout.js +382 -0
  194. package/dist/lib/lock.js +516 -0
  195. package/dist/lib/login-name.js +202 -0
  196. package/dist/lib/map-limit.js +29 -0
  197. package/dist/lib/mkdir-parents.js +90 -0
  198. package/dist/lib/mongo-kernel.js +67 -0
  199. package/dist/lib/monitoring.js +492 -0
  200. package/dist/lib/platform-name.js +59 -0
  201. package/dist/lib/presets/common.js +390 -0
  202. package/dist/lib/presets/composite.js +326 -0
  203. package/dist/lib/presets/e2ee.js +143 -0
  204. package/dist/lib/presets/email.js +172 -0
  205. package/dist/lib/presets/guides.js +27 -0
  206. package/dist/lib/presets/index.js +490 -0
  207. package/dist/lib/presets/keycloak.js +371 -0
  208. package/dist/lib/presets/ldap.js +1285 -0
  209. package/dist/lib/presets/livechat.js +220 -0
  210. package/dist/lib/presets/multi-instance.js +124 -0
  211. package/dist/lib/presets/oidc.js +161 -0
  212. package/dist/lib/presets/public.js +496 -0
  213. package/dist/lib/presets/registry.js +64 -0
  214. package/dist/lib/presets/s3-minio.js +300 -0
  215. package/dist/lib/presets/saml.js +149 -0
  216. package/dist/lib/presets/scenario.js +51 -0
  217. package/dist/lib/presets/types.js +86 -0
  218. package/dist/lib/presets/voice-pbx.js +320 -0
  219. package/dist/lib/presets/voice.js +345 -0
  220. package/dist/lib/presets/webhooks.js +182 -0
  221. package/dist/lib/redact.js +106 -0
  222. package/dist/lib/seed-options.js +68 -0
  223. package/dist/lib/seed-profiles.js +59 -0
  224. package/dist/lib/targz.js +1383 -0
  225. package/dist/lib/teammode.js +25 -0
  226. package/dist/lib/tempdir.js +162 -0
  227. package/dist/lib/unicode-tables.js +2335 -0
  228. package/dist/lib/version-spec.js +357 -0
  229. package/dist/lib/versions.js +463 -0
  230. package/dist/lib/yaml-dump.js +1361 -0
  231. package/dist/perf/baseline.js +168 -0
  232. package/dist/perf/constrain.js +299 -0
  233. package/dist/perf/k6.js +235 -0
  234. package/dist/perf/mongoprof.js +171 -0
  235. package/dist/perf/rcmetrics.js +191 -0
  236. package/dist/perf/report.js +386 -0
  237. package/dist/perf/resources.js +236 -0
  238. package/dist/perf/slo.js +111 -0
  239. package/dist/perf/timeline.js +187 -0
  240. package/dist/perf/timings.js +85 -0
  241. package/dist/perf/verdict.js +201 -0
  242. package/dist/seams/aws-cli.js +126 -0
  243. package/dist/seams/docker-cli.js +280 -0
  244. package/dist/seams/exec.js +861 -0
  245. package/dist/seams/fs/lock.js +528 -0
  246. package/dist/seams/kubectl.js +83 -0
  247. package/dist/seams/rc-http.js +921 -0
  248. package/dist/seed/apply.js +190 -0
  249. package/dist/seed/assets.js +76 -0
  250. package/dist/seed/check.js +391 -0
  251. package/dist/seed/client.js +172 -0
  252. package/dist/seed/executor.js +726 -0
  253. package/dist/seed/history.js +281 -0
  254. package/dist/seed/kinds.js +91 -0
  255. package/dist/seed/plan.js +432 -0
  256. package/dist/seed/receipt.js +339 -0
  257. package/dist/seed/repairs.js +75 -0
  258. package/dist/seed/verification.js +363 -0
  259. package/dist/seed/wording.js +248 -0
  260. package/dist/web/app.js +326 -0
  261. package/dist/web/jobs.js +510 -0
  262. package/dist/web/route-deps.js +211 -0
  263. package/dist/web/route-table.js +213 -0
  264. package/dist/web/routes/backup.js +244 -0
  265. package/dist/web/routes/clusters.js +303 -0
  266. package/dist/web/routes/data.js +187 -0
  267. package/dist/web/routes/edge.js +82 -0
  268. package/dist/web/routes/index.js +63 -0
  269. package/dist/web/routes/jobs.js +95 -0
  270. package/dist/web/routes/logs.js +297 -0
  271. package/dist/web/routes/meta.js +191 -0
  272. package/dist/web/routes/people.js +151 -0
  273. package/dist/web/routes/perf.js +95 -0
  274. package/dist/web/routes/repros.js +550 -0
  275. package/dist/web/routes/session.js +361 -0
  276. package/dist/web/routes/spa.js +198 -0
  277. package/dist/web/security.js +475 -0
  278. package/dist/web/signin.js +246 -0
  279. package/package.json +70 -32
  280. package/.eslintrc +0 -94
  281. package/.swcrc +0 -18
  282. package/dist/bin.js +0 -3
  283. package/dist/cli.js +0 -184
  284. package/dist/commands/createBranch.js +0 -194
  285. package/dist/outputCI.js +0 -59
  286. package/src/bin.js +0 -4
  287. package/src/cli.ts +0 -25
  288. package/src/commands/createBranch.ts +0 -28
  289. package/src/outputCI.ts +0 -12
  290. package/src-old/logs.js +0 -323
  291. package/src-old/md.js +0 -191
  292. package/src-old/release-table.js +0 -60
  293. package/src-old/set-version.js +0 -614
  294. package/src-old/utils.js +0 -15
@@ -0,0 +1,1377 @@
1
+ import { ctx } from "./shared.js";
2
+
3
+ // ---- clusters: where workspaces run, and what that is costing ----------------
4
+ // Two halves, as the edge has: a chip that is always visible when something in AWS is
5
+ // billing, so a forgotten cluster cannot stay forgotten, and a page with room for it.
6
+ // The page is Amazon EKS's: Docker and a Kubernetes on this machine only ever change
7
+ // state (installed or not, running or not), so they get one slim card at the top.
8
+ let CLUSTERS = null; // the cheap list: what contexts exist
9
+ const CLSTATE = { // per-context status, filled in from the overview
10
+ status: {}, // context -> the status document, or null while loading
11
+ deleting: "", // which cluster the delete dialog is about
12
+ deletingRow: null, // its row, for the region
13
+ overview: null, // the one answer the page renders: /api/clusters/overview
14
+ overviewAt: 0, // when it was read, so Home and the page share one read
15
+ overviewError: "", // why the last read failed, so nothing waits on it forever
16
+ selected: "", // the place whose own view is open
17
+ jobs: [], // running cluster jobs, for the building/deleting cards
18
+ jobsRead: false, // whether /api/jobs has been read since the page loaded
19
+ full: {}, // context -> the full read of a cluster not in AWS, once opened
20
+ connection: null, // server AWS identity; never browser credentials
21
+ connectionAt: 0,
22
+ };
23
+
24
+ const clCost = (st) => (st && st.cost && st.cost.usd_hr) || 0;
25
+
26
+ function clAttention(st) {
27
+ // What makes a cluster want you, in the sense the colour rule means. NOT cost.
28
+ if (!st) return "";
29
+ if (st.gone) return "AWS says this cluster no longer exists — its kubeconfig entry "
30
+ + "is left over";
31
+ if (!st.reachable) return st.reach_why || "it could not be read";
32
+ if (st.expires_in_days !== undefined && st.expires_in_days !== null
33
+ && st.expires_in_days < 0) return `expired ${-st.expires_in_days} day(s) ago`;
34
+ if ((st.unreadable || []).length) return `${st.unreadable.join(", ")} could not be read`;
35
+ return "";
36
+ }
37
+
38
+ // SERVICE MESSAGES ARE WRITTEN FOR A TERMINAL, where `like this` is a command. One
39
+ // helper renders them, rather than a second set of messages written for the browser.
40
+ function codeText(text) {
41
+ const out = [];
42
+ String(text ?? "").split("`").forEach((part, i) => {
43
+ if (part === "") return;
44
+ out.push(i % 2 ? ctx.el("code", {}, part) : part);
45
+ });
46
+ return out;
47
+ }
48
+
49
+ const clShort = (row) => row.short || String(row.context).split("/").pop();
50
+ const clRegion = (row, st) => (st && st.region) || row.region || "local";
51
+ // WHERE A CLUSTER LIVES decides which part of the page shows it. Only AWS bills.
52
+ const clWhere = (row, st) => (st && st.where) || (row && row.where) || "aws";
53
+ // Whether a cluster-create job is running for this row's cluster: its "Building" card speaks
54
+ // for it. The name AND the region: a name is unique per region, so another cluster of the
55
+ // same name elsewhere -- billing -- must stay on the page.
56
+ const clBuilding = (row) => CLSTATE.jobs.some((j) => j.kind === "cluster-create" && j.label === clShort(row)
57
+ && (!j.region || !row.region || j.region === row.region));
58
+ const clRows = (where) => ((CLUSTERS && CLUSTERS.contexts) || []).filter((r) => clWhere(r, CLSTATE.status[r.context]) === where && !clBuilding(r));
59
+
60
+ // The words both front-ends use for a state.
61
+ function clStateOf(st) {
62
+ if (!st) return ["reading", "reading…"];
63
+ if (st.gone) return ["gone", "gone in AWS"];
64
+ if (st.reachable) return ["running", "running"];
65
+ if (st.reach_status === "denied") return ["refusing", "refusing"];
66
+ if (st.reach_status === "no-context") return ["unreachable", "no credentials"];
67
+ return ["unreachable", "not answering"];
68
+ }
69
+
70
+ function clNodes(st) {
71
+ const shapes = (st && st.instance_types) ? Object.entries(st.instance_types) : [];
72
+ if (shapes.length) return shapes.map(([t, c]) => `${c} × ${t || "unlabelled"}`).join(", ");
73
+ return st && st.nodes !== null && st.nodes !== undefined ? `${st.nodes} node${st.nodes === 1 ? "" : "s"}` : "";
74
+ }
75
+
76
+ function clBuiltBy(row, st) {
77
+ if ((st && st.made_by_houston === true) || row.ours || row.made_by_houston) return "houston";
78
+ if (st && st.made_by_houston === false) return "you";
79
+ return "?";
80
+ }
81
+
82
+ // A command, set so a line never breaks inside one of its words.
83
+ function cmdCode(text) {
84
+ const code = ctx.el("code", {});
85
+ String(text).split(" ").forEach((word, i) => {
86
+ if (i) code.append(" ");
87
+ code.append(ctx.el("span", { class: "tok" }, word));
88
+ });
89
+ return code;
90
+ }
91
+
92
+ // ---- the server's AWS identity ---------------------------------------------------
93
+ // One answer for every place that says it: the page, Home, the chip and the setup.
94
+ // From /api/clusters/connection when it has been read, else from the overview's
95
+ // preflight -- which carries the same `whoami` error -- so Home never needs a call
96
+ // of its own.
97
+ function awsSignIn() {
98
+ const c = CLSTATE.connection;
99
+ const pre = CLSTATE.overview && CLSTATE.overview.preflight;
100
+ const principal = (c && c.principal) || (pre && pre.identity) || "";
101
+ const account = (c && c.account) || (pre && pre.account) || "";
102
+ const blocker = ((pre && pre.blockers) || []).find((b) => /^not signed in to AWS/u.test(b)) || "";
103
+ const error = (c && c.error) || blocker;
104
+ if (account && !(c && c.error)) {
105
+ const tail = principal.split(":").pop() || "";
106
+ const parts = tail.split("/");
107
+ const kind = parts[0] === "user" ? "user" : parts[0] === "assumed-role" ? "role" : parts[0] === "role" ? "role" : "";
108
+ const name = parts[0] === "assumed-role" ? (parts[2] || parts[1] || tail) : (parts[parts.length - 1] || tail);
109
+ return { state: "signed", name, kind, account, principal,
110
+ region: (c && c.region) || (pre && pre.region) || "", profile: (c && c.profile) || "" };
111
+ }
112
+ if (!c && !pre) return { state: "unknown" };
113
+ const expired = /expired/iu.test(error);
114
+ return { state: expired ? "expired" : "none", error, profile: (c && c.profile) || "", profiles: (c && c.profiles) || [] };
115
+ }
116
+
117
+ async function clReadConnection(force = false) {
118
+ if (!force && CLSTATE.connection && Date.now() - CLSTATE.connectionAt < 120000) return CLSTATE.connection;
119
+ try { CLSTATE.connection = await ctx.api("/api/clusters/connection"); }
120
+ catch (error) { CLSTATE.connection = { error: error.message }; }
121
+ CLSTATE.connectionAt = Date.now();
122
+ return CLSTATE.connection;
123
+ }
124
+
125
+ // ---- the chip ------------------------------------------------------------------
126
+ // Only when something is in AWS: a free cluster on this machine has nothing to remind
127
+ // anybody about. Amber when one wants you; never red -- red is for destroying something.
128
+ async function refreshClusterBadge() {
129
+ const badge = ctx.$("#cluster-badge");
130
+ if (!badge) return;
131
+ try { CLUSTERS = await ctx.api("/api/clusters"); CLSTATE.listError = ""; }
132
+ catch (e) { CLSTATE.listError = e.message; badge.hidden = true; return; } // no gui extra / no permission
133
+ // The rows every view draws from follow the list now, not only when a build starts or ends:
134
+ // the Clusters page opened after this read drew "no cluster on this machine" for a running
135
+ // k3s until its own read came back.
136
+ clSyncRows();
137
+ // ALSO ONCE AFTER A PAGE LOAD. Read only while a job was already known, a build running
138
+ // when the page was refreshed was invisible on Home and in this chip until someone opened
139
+ // Clusters -- and its cluster's own warning arrived a minute later in its place.
140
+ if (CLSTATE.jobs.length || !CLSTATE.jobsRead) {
141
+ try {
142
+ const jobs = await ctx.api("/api/jobs");
143
+ const before = CLSTATE.jobs.map((j) => j.id).join();
144
+ CLSTATE.jobs = (jobs.jobs || []).filter((j) => (j.kind === "cluster-create" || j.kind === "cluster-delete") && ctx.jobActive(j.status));
145
+ CLSTATE.jobsRead = true;
146
+ if (CLSTATE.jobs.map((j) => j.id).join() !== before) {
147
+ clSyncRows();
148
+ if (ctx.VIEW === "home" && !ctx.SELECTED) ctx.renderHome();
149
+ }
150
+ } catch (_) { /* keep what is known */ }
151
+ }
152
+ const aws = clRows("aws");
153
+ const building = CLSTATE.jobs.filter((j) => j.kind === "cluster-create");
154
+ if (!aws.length && !building.length) { badge.hidden = true; return; }
155
+ badge.hidden = false;
156
+ const sts = aws.map((r) => CLSTATE.status[r.context]).filter(Boolean);
157
+ const sign = awsSignIn();
158
+ const t = CLSTATE.overview ? CLSTATE.overview.totals : null;
159
+ const wants = sign.state === "expired" || building.length
160
+ || sts.some((st) => clAttention(st) || ctx.placeWarn(st));
161
+ let text = "EKS";
162
+ if (sign.state === "expired") text = "EKS · AWS sign-in expired";
163
+ else if (building.length) text = "EKS · building";
164
+ else if (t && t.usd_day !== null && t.usd_day !== undefined) {
165
+ text = `EKS ~$${Number(t.usd_day).toFixed(2)}/day${t.unpriced ? "+" : ""}`;
166
+ } else if (sts.length) {
167
+ const perHr = sts.reduce((sum, st) => sum + clCost(st), 0);
168
+ if (perHr) text = `EKS ~$${(perHr * 24).toFixed(2)}/day`;
169
+ }
170
+ badge.textContent = text;
171
+ badge.className = "chip" + (wants ? " warn" : " up");
172
+ }
173
+
174
+ // ---- the page --------------------------------------------------------------------
175
+ let pageReads = 0; // the newest open wins; an older read never repaints over it
176
+
177
+ function pvWrap(anim) {
178
+ const panel = ctx.$("#detail");
179
+ panel.innerHTML = "";
180
+ const box = ctx.el("div", { class: "pv" + (anim ? " anim" : "") });
181
+ panel.append(box);
182
+ return box;
183
+ }
184
+
185
+ async function openClusters() {
186
+ // THE ROLE BEFORE THE PAGE: every control here is role-aware, and MY_ROLE is filled
187
+ // in by the poll rather than at load.
188
+ if (!ctx.MY_ROLE) {
189
+ try {
190
+ const me = await ctx.api("/api/session");
191
+ ctx.ACCOUNTS = !!me.accounts; ctx.ME = me.user || ""; ctx.MY_ROLE = me.role || "";
192
+ } catch (_) { /* signed out; api() has already redirected */ }
193
+ }
194
+ const fresh = ctx.VIEW !== "clusters";
195
+ ctx.setView("clusters");
196
+ ctx.$(".panes").classList.add("no-detail");
197
+ ctx.$("#actpane").innerHTML = "";
198
+ const read = ++pageReads;
199
+ if (CLUSTERS) clSyncRows(); // the first draw shows the clusters already known
200
+ clRenderPage(fresh);
201
+ try {
202
+ CLUSTERS = await ctx.api("/api/clusters");
203
+ CLSTATE.listError = "";
204
+ } catch (e) { CLSTATE.listError = e.message; }
205
+ clSyncRows();
206
+ if (read !== pageReads || ctx.VIEW !== "clusters") return;
207
+ clRenderPage(false);
208
+ const jobs = ctx.api("/api/jobs").catch(() => ({ jobs: [] }));
209
+ const [ov] = await Promise.all([
210
+ loadClusterOverview(true, { evenWithoutClusters: true }).catch((e) => { CLSTATE.overviewError = e.message; return null; }),
211
+ clReadConnection(),
212
+ clReadPolicy(),
213
+ ctx.KUBE ? Promise.resolve() : ctx.refreshKube(),
214
+ ]);
215
+ if (ov) CLSTATE.overviewError = "";
216
+ CLSTATE.jobs = ((await jobs).jobs || []).filter((j) => (j.kind === "cluster-create" || j.kind === "cluster-delete") && ctx.jobActive(j.status));
217
+ CLSTATE.jobsRead = true;
218
+ clSyncRows();
219
+ if (read !== pageReads || ctx.VIEW !== "clusters") return;
220
+ clRenderPage(false);
221
+ refreshClusterBadge();
222
+ }
223
+
224
+ // The places read their rows from the same lists the Create dialog uses. A cluster being
225
+ // built is left out: eksctl writes its kubeconfig context part-way through the build, and
226
+ // from then the page drew its "Building" card AND a card of its own for the same cluster.
227
+ function clSyncRows() {
228
+ const rows = (CLUSTERS && CLUSTERS.contexts) || [];
229
+ ctx.ALL_KUBE_CLUSTERS = rows;
230
+ ctx.KUBE_CLUSTERS = rows.filter((r) => clWhere(r, CLSTATE.status[r.context]) !== "elsewhere" && !clBuilding(r));
231
+ }
232
+
233
+ function clRenderPage(anim) {
234
+ const box = pvWrap(anim);
235
+ box.append(ctx.el("h1", {}, "Clusters"), ctx.el("p", { class: "sub" }, "Where your workspaces can run."));
236
+ const { here, aws } = ctx.places({ inventory: true });
237
+ // This machine: one slim card, a row each.
238
+ const list = ctx.el("div", { class: "pcard mlist" });
239
+ for (const p of here) list.append(machineRow(p));
240
+ box.append(ctx.el("section", { class: "mstrip", id: "cl-local" },
241
+ ctx.el("div", { class: "zone-h" }, ctx.el("h2", { class: "small" }, "This server"), ctx.el("span", { class: "tag" }, "Free")), list));
242
+ // Amazon EKS: the page.
243
+ const zone = ctx.el("section", { class: "zone eks", id: "cl-aws" });
244
+ const head = ctx.el("div", { class: "zone-h" }, ctx.el("h2", {}, "Amazon EKS"),
245
+ ctx.el("span", { class: "tag money" }, "Costs money"), ctx.el("span", { class: "sp" }));
246
+ const jobs = CLSTATE.jobs;
247
+ const failed = (CLSTATE.overview && CLSTATE.overview.failed) || [];
248
+ const any = aws.length || jobs.length || failed.length;
249
+ if (ctx.canAdmin() && any) head.append(ctx.el("button", { class: "btn sm", type: "button", onclick: () => openEksSetup() }, "+ Add a cluster"));
250
+ zone.append(head, ctx.el("p", { class: "zone-p" }, "A Kubernetes cluster in your AWS account. Everyone on this server "
251
+ + "shares it, and AWS bills it by the hour until it is deleted, whether or not a workspace runs on it."));
252
+ const ident = identLine(any);
253
+ if (ident) zone.append(ident);
254
+ if (CLSTATE.listError || CLSTATE.overviewError) {
255
+ zone.append(ctx.el("div", { class: "zerr", role: "alert" },
256
+ ctx.el("span", {}, `Couldn't read the clusters: ${CLSTATE.listError || CLSTATE.overviewError}`),
257
+ ctx.el("button", { class: "btn sm", type: "button", onclick: () => { CLSTATE.overviewError = ""; openClusters(); } }, "Try again")));
258
+ }
259
+ if (any) {
260
+ const grid = ctx.el("div", { class: "places eks", id: "cl-eks" });
261
+ for (const p of aws) grid.append(eksCard(p));
262
+ for (const j of jobs) grid.append(jobCard(j));
263
+ for (const b of failed) grid.append(failedCard(b));
264
+ zone.append(grid);
265
+ const t = CLSTATE.overview ? CLSTATE.overview.totals : null;
266
+ if (t && t.clusters > 1 && t.usd_day !== null && t.usd_day !== undefined) {
267
+ zone.append(ctx.el("div", { class: "ident" }, `${t.clusters} clusters · `, ctx.el("b", {}, `~$${Number(t.usd_day).toFixed(2)} a day`),
268
+ ` together${t.unpriced ? ` (+ ${t.unpriced} not priced)` : ""}`
269
+ + (t.spend_usd !== null && t.spend_usd !== undefined ? ` · ~$${Number(t.spend_usd).toFixed(2)} so far` : "") + " · estimates"));
270
+ }
271
+ } else if (!CLSTATE.listError && !CLSTATE.overviewError) {
272
+ zone.append(ctx.canAdmin() ? eksHero()
273
+ : ctx.el("div", { class: "pcard place muted" }, ctx.el("div", { class: "nm" }, "Amazon EKS isn't set up on this server"),
274
+ ctx.el("p", { class: "ds" }, "An admin sets it up. Until then, workspaces run on this server.")));
275
+ }
276
+ box.append(zone);
277
+ }
278
+
279
+ function identLine(any) {
280
+ const s = awsSignIn();
281
+ if (s.state === "signed") {
282
+ const line = ctx.el("div", { class: "ident top", id: "cl-connection" }, "Signed in to AWS on the server as ",
283
+ ctx.el("b", {}, s.name), s.kind ? ` (${s.kind})` : "", ` · account ${s.account}`, s.region ? ` · ${s.region}` : "");
284
+ line.title = s.principal;
285
+ if (ctx.canAdmin()) line.append(" · ", ctx.el("button", { class: "linkbtn", type: "button", onclick: () => openEksSetup() }, "Details"));
286
+ return line;
287
+ }
288
+ if (s.state === "expired") {
289
+ return ctx.el("div", { class: "ident top bad", id: "cl-connection" }, "▲ ", ctx.el("b", {}, "The server's AWS sign-in has expired."),
290
+ " Houston can't check these clusters or their cost. ",
291
+ ctx.canAdmin() ? ctx.el("button", { class: "linkbtn", type: "button", onclick: () => openEksSetup() }, "Sign in again")
292
+ : "An admin signs in again on the server.");
293
+ }
294
+ if (s.state === "none" && any) {
295
+ return ctx.el("div", { class: "ident top", id: "cl-connection" }, "AWS isn't connected on the server. ",
296
+ ctx.canAdmin() ? ctx.el("button", { class: "linkbtn", type: "button", onclick: () => openEksSetup() }, "How to connect") : "");
297
+ }
298
+ return null;
299
+ }
300
+
301
+ function machineRow(p) {
302
+ const opens = p.key === "docker" || p.key.startsWith("k8s:");
303
+ const note = p.key === "k8s-new" ? "Set up automatically the first time you use it"
304
+ : p.key === "k8s-none" ? (p.ds || "") : p.facts[0] || "";
305
+ const sub = p.wh.replace(/^On this server( · )?/u, "");
306
+ const row = ctx.el("div", { class: "mrow" + (opens ? " click" : ""), "data-place": p.key },
307
+ ctx.placeIcon(p.ico),
308
+ ctx.el("div", { class: "mname" }, ctx.el("b", {}, p.nm), sub ? ctx.el("span", { class: "wh" }, ` · ${sub}`) : ""),
309
+ ctx.el("span", {}, ctx.el("span", { class: `pill ${p.pill[0]}` }, p.pill[1])),
310
+ ctx.el("span", { class: "wh mnote" }, note),
311
+ ctx.el("span", { class: "mact" }, createDestOf(p)
312
+ ? ctx.el("button", { class: "btn sm", type: "button", onclick: (ev) => { ev.stopPropagation(); ctx.openCreate(undefined, { dest: createDestOf(p) }); } }, "Create here") : ""));
313
+ if (opens) row.addEventListener("click", () => openPlace(p.key));
314
+ return row;
315
+ }
316
+
317
+ // Where "Create here" can actually go. Under `gui.create_policy admin` the form cannot send
318
+ // a cluster for a member, so a named one is offered only when it is the server's default
319
+ // -- the dialog's "default" card -- and otherwise not at all: it opened Create, toasted,
320
+ // and dropped the member back on step 1 (the deferred M5 of the EKS redesign).
321
+ function createDestOf(p) {
322
+ if (!ctx.canWrite() || !p.usable) return "";
323
+ if (!p.context || ctx.MAY_SET_PRIVILEGED === true) return p.key;
324
+ const lands = ctx.emptyContextRow();
325
+ return p.row && lands && p.row.context === lands.context ? "k8s-default" : "";
326
+ }
327
+
328
+ // The policy that decides it, read with the page: Create reads it when it opens, and the
329
+ // page draws its buttons before that.
330
+ async function clReadPolicy() {
331
+ try { ctx.MAY_SET_PRIVILEGED = !!(await ctx.api("/api/settings")).may_set_privileged; }
332
+ catch (_) { /* the buttons stay as the last read left them */ }
333
+ }
334
+
335
+ function eksCard(p) {
336
+ const card = ctx.el("div", { class: "pcard place click", "data-place": p.key, "data-context": p.context, tabindex: "0", role: "button",
337
+ "aria-label": `${p.nm}, ${p.wh}` }, ...ctx.placeBody(p));
338
+ const acts = [];
339
+ // The DNS record is the step a new cluster is waiting on, so it gets a button where the
340
+ // card says so -- not only an entry in the cluster's own pane.
341
+ if (/^Public names under/u.test(p.warn || "") && p.row) {
342
+ acts.push(ctx.el("button", { class: "btn sm", type: "button",
343
+ onclick: (ev) => { ev.stopPropagation(); clOpenDns(p.row); } }, "Set up DNS"));
344
+ }
345
+ if (createDestOf(p)) {
346
+ acts.push(ctx.el("button", { class: "btn sm", type: "button",
347
+ onclick: (ev) => { ev.stopPropagation(); ctx.openCreate(undefined, { dest: createDestOf(p) }); } }, "Create here"));
348
+ }
349
+ if (acts.length) card.append(ctx.el("div", { class: "acts" }, ...acts));
350
+ card.addEventListener("click", () => openPlace(p.key));
351
+ card.addEventListener("keydown", (ev) => { if (ev.key === "Enter" && ev.target === card) openPlace(p.key); });
352
+ return card;
353
+ }
354
+
355
+ function jobCard(job) {
356
+ const deleting = job.kind === "cluster-delete";
357
+ const min = Math.max(0, Math.floor((Date.now() / 1000 - job.started_at) / 60));
358
+ const p = { ico: "aws", nm: job.label || "?", wh: "Amazon EKS", pill: ["busy warn", `${deleting ? "Deleting" : "Building"} · ${min} min`],
359
+ ds: deleting ? "Releasing its load balancers, then the cluster and everything in it."
360
+ : "About 20 minutes in all. It started billing when the build began.",
361
+ progress: deleting ? null : Math.min(95, Math.round((min / 20) * 100)), facts: [] };
362
+ const card = ctx.el("div", { class: "pcard place click", "data-job": job.id, role: "button", tabindex: "0" }, ...ctx.placeBody(p));
363
+ card.addEventListener("click", () => ctx.reopenJob(job));
364
+ return card;
365
+ }
366
+
367
+ function failedCard(build) {
368
+ const gone = build.present === false;
369
+ const cmd = `houston cluster delete ${build.name}${build.region ? ` --region ${build.region}` : ""}`;
370
+ const p = { ico: "aws", nm: build.name, wh: `Amazon EKS · ${build.region || "?"}`,
371
+ pill: ["warn", gone ? "Build failed, nothing left" : "Build failed"],
372
+ ds: gone ? "The build failed and AWS holds nothing of it." : "The build failed part-way and may still be billing. An admin deletes what it left, in a shell on the server:",
373
+ facts: [] };
374
+ const card = ctx.el("div", { class: "pcard place", "data-failed": build.name }, ...ctx.placeBody(p));
375
+ if (!gone) {
376
+ card.append(ctx.el("div", { class: "acts" }, cmdCode(cmd),
377
+ ctx.el("button", { class: "btn sm", type: "button", onclick: () => clCopy(cmd, "the command") }, "Copy")));
378
+ }
379
+ return card;
380
+ }
381
+
382
+ function eksHero() {
383
+ const s = awsSignIn();
384
+ const signed = s.state === "signed";
385
+ return ctx.el("div", { class: "pcard hero", id: "cl-hero" },
386
+ ctx.el("div", { class: "ph" }, ctx.placeIcon("aws"), ctx.el("div", {}, ctx.el("div", { class: "nm" }, "Run workspaces on Amazon EKS"),
387
+ ctx.el("div", { class: "wh" }, "For when what you test needs a real cloud cluster: AWS load balancers, EBS storage, several nodes."))),
388
+ ctx.el("ol", { class: "hsteps" },
389
+ ctx.el("li", {}, ctx.el("i", {}, signed ? "✓" : "1"), ctx.el("b", {}, "Connect AWS on the server"),
390
+ ctx.el("span", {}, signed ? `Done: signed in as ${s.name}${s.kind ? ` (${s.kind})` : ""}.`
391
+ : "Company SSO or a server role. Houston never asks for AWS keys here.")),
392
+ ctx.el("li", {}, ctx.el("i", {}, "2"), ctx.el("b", {}, "Choose a cluster"),
393
+ ctx.el("span", {}, "Build a new one (about 20 minutes), or connect one houston already built.")),
394
+ ctx.el("li", {}, ctx.el("i", {}, "3"), ctx.el("b", {}, "Create workspaces on it"),
395
+ ctx.el("span", {}, "It appears as a place to run, next to Docker, when you create a workspace."))),
396
+ ctx.el("div", { class: "hero-f" }, ctx.el("button", { class: "btn solid", type: "button", onclick: () => openEksSetup() }, "Set up Amazon EKS"),
397
+ ctx.el("span", { class: "wh" }, `A cluster costs about $${heroDay()} a day while it exists, whether or not anything runs on it.`)));
398
+ }
399
+
400
+ let HERO_DAY = null;
401
+ function heroDay() {
402
+ if (HERO_DAY === null) {
403
+ HERO_DAY = "…";
404
+ ctx.api("/api/clusters/estimate?nodes=3").then((r) => {
405
+ HERO_DAY = Number(r.usd_day).toFixed(2);
406
+ const hero = ctx.$("#cl-hero .hero-f .wh");
407
+ if (hero) hero.textContent = `A cluster costs about $${HERO_DAY} a day while it exists, whether or not anything runs on it.`;
408
+ }).catch(() => { HERO_DAY = "?"; });
409
+ }
410
+ return HERO_DAY;
411
+ }
412
+
413
+ // ---- one place's own view: facts in the stage, actions in the pane ---------------
414
+ function placeOf(key) {
415
+ const { here, aws } = ctx.places({ inventory: true });
416
+ return [...here, ...aws].find((p) => p.key === key) || null;
417
+ }
418
+
419
+ async function openPlace(key) {
420
+ ctx.SELECTED = null;
421
+ ctx.closeLogs();
422
+ if (ctx.dstate.statsTimer) { clearInterval(ctx.dstate.statsTimer); ctx.dstate.statsTimer = null; }
423
+ ctx.dstate.detail = null;
424
+ CLSTATE.selected = key;
425
+ const fresh = ctx.VIEW !== "cluster";
426
+ ctx.setView("cluster");
427
+ ctx.$(".panes").classList.remove("no-detail");
428
+ if (CLUSTERS) clSyncRows();
429
+ clRenderPlace(fresh);
430
+ if (!CLUSTERS) { try { CLUSTERS = await ctx.api("/api/clusters"); } catch (_) { /* the view says what it has */ } }
431
+ clSyncRows();
432
+ const p = placeOf(key);
433
+ const reads = [p && p.row && p.row.where === "local" ? clReadFull(p.row) : null, clReadPolicy()];
434
+ if (!CLSTATE.overview) reads.push(loadClusterOverview(false, { evenWithoutClusters: true }).catch(() => null));
435
+ await Promise.all(reads);
436
+ if (ctx.VIEW === "cluster" && CLSTATE.selected === key) clRenderPlace(false);
437
+ }
438
+
439
+ // Refresh, on either Clusters view: every read again, the AWS side past the server's
440
+ // ten-minute cache, because whoever presses it has usually just changed something there.
441
+ async function clRefresh() {
442
+ CLUSTERS = null;
443
+ await Promise.all([clReadConnection(true),
444
+ loadClusterOverview(true, { evenWithoutClusters: true, fresh: true }).catch(() => null)]);
445
+ if (ctx.VIEW === "cluster") await openPlace(CLSTATE.selected);
446
+ else if (ctx.VIEW === "clusters") await openClusters();
447
+ }
448
+
449
+ // A cluster named by its context -- a workspace's "Runs on" -- opened as its own view.
450
+ function openContext(context) {
451
+ const row = ((CLUSTERS && CLUSTERS.contexts) || []).find((r) => r.context === context);
452
+ const where = row ? clWhere(row, CLSTATE.status[context]) : String(context).startsWith("arn:aws:eks:") ? "aws" : "local";
453
+ if (where === "elsewhere") { openClusters(); return; }
454
+ openPlace(`${where === "aws" ? "eks" : "k8s"}:${context}`);
455
+ }
456
+
457
+ function kvGrid(rows) {
458
+ const grid = ctx.el("div", { class: "pkv" });
459
+ for (const [k, ...v] of rows) grid.append(ctx.el("div", { class: "k" }, k), ctx.el("div", {}, ...v));
460
+ return ctx.el("div", { class: "hcard dash" }, grid);
461
+ }
462
+
463
+ const okT = (t) => ctx.el("span", {}, ctx.el("span", { class: "ok-t" }, "✓"), ` ${t}`);
464
+ const noT = (t) => ctx.el("span", {}, ctx.el("span", { class: "no-t" }, "✗"), ` ${t}`);
465
+ function joinDots(items) { const out = []; items.forEach((it, i) => { if (i) out.push(" · "); out.push(it); }); return out; }
466
+
467
+ function heldList(held) {
468
+ if (held === null || held === undefined) return [ctx.el("span", { class: "m" }, "could not be read — not the same as none")];
469
+ if (!held.length) return ["None yet"];
470
+ const out = [];
471
+ held.forEach((w, i) => {
472
+ if (i) out.push(ctx.el("br"));
473
+ out.push(w.name || String(w), ctx.el("span", { class: "m" },
474
+ w.name ? ` (${w.owner_readable === false ? "owner unreadable" : (w.owner || "unowned")}${typeof w.pvcs === "number" ? `, ${w.pvcs} volume${w.pvcs === 1 ? "" : "s"}` : ""})` : ""));
475
+ });
476
+ return out;
477
+ }
478
+
479
+ function clRenderPlace(anim) {
480
+ const key = CLSTATE.selected;
481
+ const p = placeOf(key);
482
+ const box = pvWrap(anim);
483
+ box.append(ctx.el("div", { class: "crumb" }, ctx.el("button", { class: "linkbtn", type: "button", onclick: () => openClusters() }, "Clusters"),
484
+ ` › ${p ? p.nm : key.replace(/^[a-z0-9-]+:/u, "")}`));
485
+ if (!p) { box.append(ctx.el("p", { class: "sub" }, "This cluster is no longer listed on this server.")); clPlacePane(null); return; }
486
+ const head = ctx.el("div", { class: "dhead" }, ctx.placeIcon(p.ico),
487
+ ctx.el("div", {}, ctx.el("h1", {}, p.nm), ctx.el("div", { class: "wh" }, p.wh)),
488
+ ctx.el("span", { class: `pill ${p.pill[0]}` }, p.pill[1]));
489
+ if (p.cost !== null && p.cost !== undefined) head.append(ctx.el("span", { class: "dcost" }, `~$${p.cost.toFixed(2)}`, ctx.el("small", {}, " a day")));
490
+ box.append(head);
491
+ const st = p.context ? CLSTATE.status[p.context] : null;
492
+ if (p.key === "docker") {
493
+ const ws = (ctx.ALL_REPROS || []).filter((r) => (r.runtime || "docker") === "docker");
494
+ const cap = ctx.MACHINE_ROOM || ctx.HOME.cap;
495
+ box.append(kvGrid([
496
+ ["Workspaces", ...heldList(ws.map((r) => ({ name: r.name, owner: `${r.rc_version} · ${r.state}` })))],
497
+ ["Memory", cap && cap.known ? `Room for about ${cap.room} more workspaces` : "Not read on this server"],
498
+ ["Engine", ctx.DOCKER_OK === false ? "Docker is not answering" : "Docker, with Compose"],
499
+ ]));
500
+ } else if (p.ico === "k8s") {
501
+ const full = CLSTATE.full[p.context];
502
+ const r = full && full.ready;
503
+ // FACTS, NOT A CHECKLIST: a k3s ships its storage class and its ingress, and
504
+ // "✓ ingress traefik" read as houston having installed it.
505
+ const uses = full === undefined ? [ctx.el("span", { class: "m" }, "reading…")]
506
+ : !r ? [ctx.el("span", { class: "m" }, "could not be read — not the same as nothing")]
507
+ : joinDots([r.storage_class ? `storage class ${r.storage_class}` : noT("no default storage class"),
508
+ r.ingress_class ? `ingress ${r.ingress_class}` : "no ingress",
509
+ ...(r.cert_manager ? ["cert-manager"] : [])]);
510
+ const nodes = full && typeof full.nodes === "number" ? `${full.nodes} node${full.nodes === 1 ? "" : "s"}` : "";
511
+ const up = full && typeof full.age_hours === "number" ? `up ${Math.floor(full.age_hours / 24)}d ${Math.floor(full.age_hours % 24)}h` : "";
512
+ if (st && !st.reachable) box.append(ctx.el("div", { class: "callout money", style: "margin:0 0 1rem" }, "▲ ", ...codeText(`${st.reach_why || "it could not be read"}. ${st.reach_advice || ""}`), ctx.el("b", {}, " These are unknown, not zero.")));
513
+ box.append(kvGrid([
514
+ ["Workspaces", ...heldList((full && full.workspaces) || (st && st.workspaces))],
515
+ ["Uses", ...uses],
516
+ ["Details", [(st && st.distribution) || (p.row && p.row.ours ? "kind" : "kubernetes"), nodes, `context ${p.context}`, up].filter(Boolean).join(" · ")],
517
+ ["Cost", "Free: it runs on this server"],
518
+ ]));
519
+ } else {
520
+ if (p.warn) box.append(ctx.el("div", { class: "callout money", style: "margin:0 0 1rem" }, `▲ ${p.warn}`));
521
+ if (st && st.gone) box.append(ctx.el("div", { class: "callout", style: "margin:0 0 1rem" }, ...codeText(st.reach_advice || "AWS says this cluster no longer exists, so it is not costing anything.")));
522
+ else if (st && !st.reachable) box.append(ctx.el("div", { class: "callout money", style: "margin:0 0 1rem" }, ctx.el("b", {}, "These are unknown, not zero. "), ...codeText(st.reach_advice || "")));
523
+ if (st && st.manageable === false && st.unmanageable_why) box.append(ctx.el("div", { class: "callout money", style: "margin:0 0 1rem" }, ...codeText(st.unmanageable_why)));
524
+ const rows = [["Workspaces", ...heldList(st ? st.workspaces : undefined)]];
525
+ if (st && st.cost) {
526
+ const c = st.cost;
527
+ rows.push(["Cost", `~$${Number(c.usd_hr).toFixed(2)} an hour · ~$${(c.usd_hr * 24).toFixed(2)} a day`
528
+ + (typeof st.spend_usd === "number" ? ` · ~$${st.spend_usd.toFixed(2)} so far` : ""),
529
+ ctx.el("div", { class: "m", style: "margin-top:.2rem" }, `Estimate: ${c.basis || "on-demand prices"}. Traffic and storage are extra.`)]);
530
+ } else rows.push(["Cost", st ? ctx.el("span", { class: "m" }, "could not be priced — not the same as free") : ctx.el("span", { class: "m" }, "reading…")]);
531
+ if (st && st.ready) {
532
+ const r = st.ready;
533
+ const facts = [];
534
+ if (r.storage_class !== null) facts.push(r.storage_class ? okT(`storage ${r.storage_class}`) : noT("no default storage class"));
535
+ if (r.ingress_class !== null) facts.push(r.ingress_class ? okT(`ingress ${r.ingress_class}`) : noT("no ingress"));
536
+ if (r.cert_manager !== null) facts.push(r.cert_manager ? okT("cert-manager") : noT("no cert-manager"));
537
+ if (st.zone && r.dns_answers === false) facts.push(noT(`public names under ${st.zone} do not answer yet`));
538
+ else if (st.zone) facts.push(`public names under ${st.zone}`);
539
+ else facts.push("no public names yet: workspaces open only in a browser on the server, through a port-forward");
540
+ // Saying so was not enough: the record lived only behind the pane's "Public names
541
+ // (DNS)…", which nobody new to EKS knew to open.
542
+ const dnsBtn = (st.zone && r.dns_answers === false) || !st.zone
543
+ ? ctx.el("button", { class: "btn sm", type: "button", style: "margin-left:.6rem", onclick: () => clOpenDns(p.row) }, "Set up DNS")
544
+ : "";
545
+ rows.push(["Ready", ctx.el("span", {}, ...joinDots(facts), dnsBtn)]);
546
+ }
547
+ if (st) {
548
+ const details = [clNodes(st), st.kubernetes_version ? `Kubernetes ${st.kubernetes_version}` : "",
549
+ st.created_at ? `created ${String(st.created_at).slice(0, 10)}` : "",
550
+ st.expires ? `reminder date ${st.expires} (nothing deletes on it)` : "",
551
+ clBuiltBy(p.row, st) === "houston" ? "built by houston" : clBuiltBy(p.row, st) === "you" ? "not built by houston" : ""].filter(Boolean);
552
+ rows.push(["Details", details.join(" · ") || "—"]);
553
+ }
554
+ box.append(kvGrid(rows));
555
+ }
556
+ clPlacePane(p);
557
+ }
558
+
559
+ function clPlacePane(p) {
560
+ const pane = ctx.$("#actpane");
561
+ pane.innerHTML = "";
562
+ if (!p) return;
563
+ const box = ctx.el("div", { class: "ppane" }, ctx.el("h4", {}, p.nm));
564
+ if (createDestOf(p)) {
565
+ box.append(ctx.el("button", { class: "btn solid", type: "button", onclick: () => ctx.openCreate(undefined, { dest: createDestOf(p) }) }, "Create a workspace here"));
566
+ }
567
+ const link = (label, fn, cls = "") => ctx.el("button", { class: "plink " + cls, type: "button", onclick: fn }, label);
568
+ const st = p.context ? CLSTATE.status[p.context] : null;
569
+ if (p.row) {
570
+ const row = p.row;
571
+ const gone = !!(st && st.gone);
572
+ if (p.ico === "aws") {
573
+ if (st && st.reachable) box.append(link("Public names (DNS)…", () => clOpenDns(row)));
574
+ if (ctx.canAdmin() && !gone) box.append(link("Prepare again", () => clPrepare(row.context)));
575
+ box.append(link("Copy kubeconfig command", () => clCopy(clKubeconfigCommand(row), "the kubeconfig command")));
576
+ }
577
+ box.append(link("Copy context name", () => clCopy(row.context, "the context name")));
578
+ if (ctx.canAdmin() && (gone || (st && !st.reachable))) {
579
+ box.append(link("Forget this cluster", () => clForget(row)),
580
+ ctx.el("p", { class: "note" }, p.ico === "aws"
581
+ ? "Only stops listing it here. It does not delete it in AWS, which bills it while it exists."
582
+ : "Only stops listing it here. The cluster itself is not touched."));
583
+ }
584
+ if (p.ico === "aws") {
585
+ box.append(ctx.el("hr"));
586
+ if (ctx.canAdmin() && row.billable && !gone && !(st && st.made_by_houston === false)) {
587
+ box.append(link("Delete cluster…", () => clAskDelete(row, st), "danger"),
588
+ ctx.el("p", { class: "note" }, "Deleting stops the charge. Removing workspaces does not."));
589
+ } else if (ctx.canAdmin() && st && st.made_by_houston === false) {
590
+ box.append(ctx.el("p", { class: "note" }, "houston did not build this cluster, so it will not delete it."));
591
+ } else if (!ctx.canAdmin()) {
592
+ box.append(ctx.el("p", { class: "note" }, "Deleting a cluster is an admin action."));
593
+ }
594
+ }
595
+ }
596
+ if (!ctx.canWrite()) box.append(ctx.el("p", { class: "note" }, "Your role is readonly: you can look, not change."));
597
+ pane.append(box);
598
+ }
599
+
600
+ // The overview, read at most once every two minutes whoever asks (Home, the page): one
601
+ // EKS status is measured at ~18 s. ONE READ IN FLIGHT: a second caller shares it, and a
602
+ // read that failed is not retried for a minute.
603
+ let overviewInFlight = null;
604
+ let overviewFailedAt = 0;
605
+ // `fresh` asks the server to re-read the AWS tools and identity too (`?fresh=1`): a Re-check
606
+ // after `aws sso login` or an approval must not be answered from a ten-minute-old read.
607
+ async function loadClusterOverview(force = false, { evenWithoutClusters = false, fresh = false } = {}) {
608
+ if (!force && CLSTATE.overview && Date.now() - CLSTATE.overviewAt < 120000) return CLSTATE.overview;
609
+ if (overviewInFlight && fresh) {
610
+ return overviewInFlight.catch(() => null).then(() => loadClusterOverview(true, { evenWithoutClusters, fresh }));
611
+ }
612
+ if (overviewInFlight) return overviewInFlight;
613
+ if (!force && Date.now() - overviewFailedAt < 60000) return CLSTATE.overview;
614
+ if (!CLUSTERS) {
615
+ try { CLUSTERS = await ctx.api("/api/clusters"); } catch (_) { return null; }
616
+ }
617
+ if (!evenWithoutClusters && !(CLUSTERS.contexts || []).length) return null;
618
+ overviewInFlight = ctx.api(`/api/clusters/overview${fresh ? "?fresh=1" : ""}`).then((ov) => {
619
+ CLSTATE.overview = ov;
620
+ CLSTATE.overviewAt = Date.now();
621
+ CLSTATE.overviewError = "";
622
+ for (const st of ov.clusters || []) CLSTATE.status[st.context] = st;
623
+ refreshClusterBadge();
624
+ return ov;
625
+ }, (error) => { overviewFailedAt = Date.now(); CLSTATE.overviewError = error.message; throw error; })
626
+ .finally(() => { overviewInFlight = null; });
627
+ return overviewInFlight;
628
+ }
629
+
630
+ // One cluster re-read, into the same store.
631
+ async function clProbe(row) {
632
+ try {
633
+ CLSTATE.status[row.context] = await ctx.api(`/api/clusters/status?context=${encodeURIComponent(row.context)}`);
634
+ } catch (e) {
635
+ CLSTATE.status[row.context] = { context: row.context, reachable: false, gone: false,
636
+ reach_why: e.message, reach_advice: "", unreadable: ["cluster"],
637
+ nodes: null, workspaces: null, pvcs: null, loadbalancers: null, cost: null };
638
+ }
639
+ clRepaint();
640
+ }
641
+
642
+ // Whichever cluster view is on screen, drawn again from what is now known.
643
+ function clRepaint() {
644
+ if (ctx.VIEW === "clusters") openClusters();
645
+ else if (ctx.VIEW === "cluster") clRenderPlace(false);
646
+ else refreshClusterBadge();
647
+ }
648
+
649
+ // The rest of a cluster on this machine, read when it is opened rather than on every look.
650
+ async function clReadFull(row) {
651
+ if (!row || clWhere(row, CLSTATE.status[row.context]) === "aws") return;
652
+ const st = CLSTATE.status[row.context];
653
+ if (st && !st.reachable) return;
654
+ try {
655
+ CLSTATE.full[row.context] = await ctx.api(`/api/clusters/status?context=${encodeURIComponent(row.context)}`);
656
+ } catch (_) { CLSTATE.full[row.context] = null; }
657
+ }
658
+
659
+ function clKubeconfigCommand(row) {
660
+ const short = clShort(row);
661
+ return String(row.context).startsWith("arn:aws:eks:")
662
+ ? `aws eks update-kubeconfig --name ${short} --region ${row.region}`
663
+ : `kubectl config use-context ${row.context}`;
664
+ }
665
+
666
+ async function clForget(row) {
667
+ // NOT a destroy, so no confirmation dialog: the cluster is already gone and this
668
+ // removes a name from a local file. Red is reserved for "about to destroy something".
669
+ try {
670
+ await ctx.api("/api/clusters/forget",
671
+ { method: "POST", body: JSON.stringify({ context: row.context }) });
672
+ ctx.toast(`forgot ${row.context} — the cluster itself was not touched`, "ok");
673
+ openClusters();
674
+ } catch (e) { ctx.toast(e.message); }
675
+ }
676
+
677
+ async function clPrepare(context) {
678
+ try {
679
+ const { job_id } = await ctx.api("/api/clusters/prepare",
680
+ { method: "POST", body: JSON.stringify({ context }) });
681
+ ctx.streamJob(job_id, `Preparing ${context}`, (res) => {
682
+ ctx.toast(`${context} is ready to serve a workspace`, "ok");
683
+ if (res && res.cname_target) {
684
+ ctx.toast(`point your name at ${res.cname_target}`, "ok");
685
+ } else if (res && res.cname_pending) {
686
+ ctx.toast("the load balancer has no address yet — prepare again in a minute");
687
+ } else if (res) {
688
+ ctx.toast("no load balancer is waiting for an address — this cluster has no "
689
+ + "load-balancing ingress, so workspaces here reach you by port-forward");
690
+ }
691
+ CLSTATE.overview = null;
692
+ loadClusterOverview(true, { evenWithoutClusters: true }).catch(() => {}).then(clRepaint);
693
+ });
694
+ } catch (e) { ctx.toast(e.message); }
695
+ }
696
+
697
+ async function clCopy(text, what) {
698
+ try { await navigator.clipboard.writeText(text); ctx.toast(`${what} copied`, "ok"); }
699
+ catch (_) { ctx.toast("could not reach the clipboard"); }
700
+ }
701
+
702
+ async function clCopyDoc(name) {
703
+ try {
704
+ const r = await ctx.api(`/api/clusters/iam-policy?name=${encodeURIComponent(name)}`);
705
+ await clCopy(r.documents[0].body, `${name} document`);
706
+ } catch (e) { ctx.toast(e.message); }
707
+ }
708
+
709
+ // ---- Set up Amazon EKS: one guided path ----------------------------------------
710
+ // ① AWS on the server -- the tools and the identity the AWS CLI finds there; keys are
711
+ // never typed into this page -- ② build a cluster, or check the account for one houston
712
+ // built, ③ ready. Every call is the one the CLI makes: connection, sweep, connect, approve,
713
+ // estimate, create.
714
+ const SETUP = { step: 1, back: false, branch: "build", sweeping: false, sweep: null, sweepError: "",
715
+ connected: null, connectedStatus: undefined, building: "", estimate: null, checking: false, checkedAt: 0,
716
+ f: { name: "", region: "", nodes: 3, expires: "7", zone: "", email: "" } };
717
+
718
+ async function openEksSetup() {
719
+ Object.assign(SETUP, { step: 1, back: false, branch: "build", sweeping: false, sweep: null, sweepError: "",
720
+ connected: null, connectedStatus: undefined, building: "", estimate: null, checking: false, checkedAt: 0,
721
+ f: { name: "", region: "", nodes: 3, expires: "7", zone: "", email: "" } });
722
+ const dialog = ctx.$("#eks-setup");
723
+ renderSetup(true);
724
+ if (!dialog.open) dialog.showModal();
725
+ await setupRecheck(false);
726
+ }
727
+
728
+ // Seen to happen: an answer that has not changed redrew the same screen, so a Re-check
729
+ // looked like a button that did nothing.
730
+ async function setupRecheck(force = true) {
731
+ SETUP.checking = true;
732
+ if (SETUP.step === 1 && ctx.$("#eks-setup").open) renderSetup(false);
733
+ try {
734
+ await Promise.all([clReadConnection(force),
735
+ loadClusterOverview(force, { evenWithoutClusters: true, fresh: force }).catch(() => null)]);
736
+ } finally {
737
+ SETUP.checking = false;
738
+ SETUP.checkedAt = Date.now();
739
+ }
740
+ if (ctx.$("#eks-setup").open) renderSetup(false);
741
+ }
742
+
743
+ function setupGo(step, back = false) {
744
+ SETUP.step = step;
745
+ SETUP.back = back;
746
+ renderSetup(true);
747
+ if (step === 2 && !SETUP.estimate) setupPrice();
748
+ }
749
+
750
+ function setupPre() {
751
+ return (CLSTATE.overview && CLSTATE.overview.preflight) || null;
752
+ }
753
+
754
+ function renderSetup(anim) {
755
+ const steps = ctx.$("#eks-steps");
756
+ steps.innerHTML = "";
757
+ ["Connect AWS", "Choose a cluster", "Ready"].forEach((label, i) => {
758
+ const at = i + 1;
759
+ const cls = at < SETUP.step ? "done" : at === SETUP.step ? "on" : "";
760
+ if (i) steps.append(ctx.el("span", { class: "ln" }));
761
+ steps.append(ctx.el("span", { class: cls }, ctx.el("i", {}, cls === "done" ? "✓" : String(at)), label));
762
+ });
763
+ const body = ctx.$("#eks-body");
764
+ const keep = anim ? 0 : body.scrollTop;
765
+ body.innerHTML = "";
766
+ const step = ctx.el("section", { class: "wzd-step" + (anim ? " anim" : "") + (anim && SETUP.back ? " back" : "") });
767
+ body.append(step);
768
+ const foot = ctx.$("#eks-foot");
769
+ foot.innerHTML = "";
770
+ if (SETUP.step === 1) setupStepOne(step, foot);
771
+ else if (SETUP.step === 2) setupStepTwo(step, foot);
772
+ else setupStepThree(step, foot);
773
+ body.scrollTop = keep;
774
+ if (anim) { const q = step.querySelector(".wzd-q"); if (q) q.focus({ preventScroll: true }); }
775
+ }
776
+
777
+ const sq = (cls, mark) => ctx.el("span", { class: `s ${cls}` }, mark);
778
+ const fbtn = (label, onclick, cls = "btn", disabled = false) => {
779
+ const b = ctx.el("button", { type: "button", class: cls, onclick }, label);
780
+ b.disabled = disabled;
781
+ return b;
782
+ };
783
+ const fhint = (text) => ctx.el("span", { class: "hint wzd-hint" }, text);
784
+
785
+ function setupStepOne(step, foot) {
786
+ const pre = setupPre();
787
+ const s = awsSignIn();
788
+ step.append(ctx.el("p", { class: "wzd-q", tabindex: "-1" }, "Connect AWS on the server"),
789
+ ctx.el("p", { class: "hint", style: "margin:-.4rem 0 1rem;font-size:14px" },
790
+ "Houston uses the AWS identity of the machine it runs on. Everyone using this page acts as that one identity, "
791
+ + "and the audit log records who clicked. Houston never asks for AWS keys here."));
792
+ const list = ctx.el("ul", { class: "checklist" });
793
+ if (!pre && CLSTATE.overviewError) {
794
+ list.append(ctx.el("li", {}, sq("n", "!"), ctx.el("span", {}, "Couldn't check the server's tools: ",
795
+ ctx.el("span", { class: "m" }, CLSTATE.overviewError))));
796
+ } else if (!pre) list.append(ctx.el("li", {}, sq("run", "·"), ctx.el("span", {}, "Checking the server…")));
797
+ else {
798
+ const blockers = pre.blockers || [];
799
+ const toolMissing = ["aws", "kubectl", "helm"].filter((t) => blockers.some((b) => b.startsWith(`${t} `)));
800
+ list.append(ctx.el("li", {}, toolMissing.length ? sq("n", "!") : sq("y", "✓"),
801
+ ctx.el("span", {}, "Tools on the server: aws, kubectl, helm",
802
+ toolMissing.length ? ctx.el("span", { class: "warn" }, ` (missing: ${toolMissing.join(", ")}; houston doctor names what to install)`) : "")));
803
+ const eksctl = !blockers.some((b) => b.startsWith("eksctl "));
804
+ list.append(ctx.el("li", {}, eksctl ? sq("y", "✓") : sq("w", "–"),
805
+ ctx.el("span", {}, "eksctl", eksctl ? "" : ctx.el("span", { class: "m" }, " not installed; only needed to build a new cluster"))));
806
+ }
807
+ if (s.state === "unknown") list.append(ctx.el("li", {}, sq("run", "·"), ctx.el("span", {}, "Asking AWS who this server is…")));
808
+ else if (s.state === "signed") {
809
+ list.append(ctx.el("li", {}, sq("y", "✓"), ctx.el("span", {}, "Signed in as ", ctx.el("b", {}, s.name),
810
+ s.kind ? ` (${s.kind})` : "", ` · account ${s.account}`, s.region ? ` · ${s.region}` : "")));
811
+ } else {
812
+ list.append(ctx.el("li", {}, sq("n", "!"), ctx.el("span", {},
813
+ s.state === "expired" ? "The server's AWS SSO sign-in has expired." : "The server isn't signed in to AWS.",
814
+ s.error ? ctx.el("span", { class: "m" }, ` ${s.error.replace(/^not signed in to AWS \(|\)$/gu, "")}`) : "")));
815
+ }
816
+ step.append(list);
817
+ const cmdBox = (text) => ctx.el("div", { class: "cmd" }, ctx.el("pre", {}, text),
818
+ ctx.el("button", { type: "button", class: "btn sm", onclick: () => clCopy(text, "the commands") }, "Copy"));
819
+ if (s.state === "expired") {
820
+ const profile = s.profile || "<profile>";
821
+ step.append(ctx.el("div", { class: "way" }, ctx.el("h4", {}, "Sign in again on the server"),
822
+ ctx.el("p", {}, "Run this as the user that runs Houston, then Re-check."), cmdBox(`aws sso login --profile ${profile}`)));
823
+ } else if (s.state === "none") {
824
+ // The commonest cause: `aws` works in a shell that has AWS_PROFILE and the server was
825
+ // started from one that did not. Re-checking cannot fix that; a restart can.
826
+ if (!s.profile && s.profiles.length) {
827
+ const profile = s.profiles.length === 1 ? s.profiles[0] : "<profile>";
828
+ step.append(ctx.el("div", { class: "way", id: "eks-profiles", style: "margin-bottom:.7rem" },
829
+ ctx.el("h4", {}, "This server was started without AWS_PROFILE"),
830
+ ctx.el("p", {}, "Its AWS config has ", ctx.el("b", {}, s.profiles.join(", ")),
831
+ ". Restart houston serve with AWS_PROFILE set to the one that can use EKS. Running it as a service? "
832
+ + "Print the unit again with houston serve --print-service from a shell that has it set."),
833
+ cmdBox(`AWS_PROFILE=${profile} houston serve`)));
834
+ }
835
+ step.append(ctx.el("p", { style: "margin:.2rem 0 .7rem" }, "On the server, use one of these, then Re-check:"),
836
+ ctx.el("div", { class: "ways" },
837
+ ctx.el("div", { class: "way" }, ctx.el("h4", {}, "Company SSO ", ctx.el("span", { class: "tag" }, "Recommended")),
838
+ ctx.el("p", {}, "Set up a profile once; sign in again when it expires."),
839
+ cmdBox("aws configure sso --profile support-eks\naws sso login --profile support-eks\nAWS_PROFILE=support-eks houston serve")),
840
+ ctx.el("div", { class: "way" }, ctx.el("h4", {}, "Server role"),
841
+ ctx.el("p", {}, "For a shared server: attach an instance, container or workload role with the EKS permissions. Nothing to sign in to.")),
842
+ ctx.el("details", { class: "way" }, ctx.el("summary", {}, "Access keys"),
843
+ ctx.el("p", { style: "margin-top:.4rem" }, "Only if SSO or a role isn't available: set AWS_ACCESS_KEY_ID and "
844
+ + "AWS_SECRET_ACCESS_KEY (plus AWS_SESSION_TOKEN for temporary keys) in the server's environment. "
845
+ + "Don't paste keys into this page."))));
846
+ } else if (s.state === "signed" && ctx.canAdmin()) {
847
+ step.append(ctx.el("details", { class: "way", style: "margin-top:.6rem" }, ctx.el("summary", {}, "Permissions for colleagues"),
848
+ ctx.el("p", { style: "margin:.4rem 0 .6rem" }, "IAM decides who may build. Each person who runs workspaces also needs an EKS access entry on the cluster."),
849
+ ctx.el("div", { style: "display:flex;gap:.5rem;flex-wrap:wrap" },
850
+ ...[["operator", "Copy operator policy"], ["engineer", "Copy engineer policy"], ["rbac", "Copy engineer RBAC"]]
851
+ .map(([key, label]) => fbtn(label, () => clCopyDoc(key), "btn sm")))));
852
+ }
853
+ const signed = s.state === "signed";
854
+ const checked = SETUP.checkedAt ? ` Checked at ${new Date(SETUP.checkedAt).toLocaleTimeString()}.` : "";
855
+ foot.append(fbtn("Cancel", () => ctx.$("#eks-setup").close()),
856
+ fhint(signed ? "" : `Re-check after signing in on the server.${checked}`));
857
+ if (!signed || !pre) foot.append(fbtn(SETUP.checking ? "Checking…" : "Re-check", () => setupRecheck(true), "btn", SETUP.checking));
858
+ foot.append(fbtn("Next →", () => setupGo(2), "btn solid", !signed));
859
+ }
860
+
861
+ function setupStepTwo(step, foot) {
862
+ const read = setupPre();
863
+ const pre = read || { approved: false, account: "", region: "", blockers: [] };
864
+ const s = awsSignIn();
865
+ const account = s.account || pre.account || "";
866
+ const existing = SETUP.branch === "existing";
867
+ step.append(ctx.el("p", { class: "wzd-q", tabindex: "-1" }, "Choose a cluster"));
868
+ const choice = (value, title, why) => {
869
+ const input = ctx.el("input", { type: "radio", name: "eks_branch", value });
870
+ input.checked = SETUP.branch === value;
871
+ input.addEventListener("change", () => { SETUP.branch = value; renderSetup(false); if (value === "build" && !SETUP.estimate) setupPrice(); });
872
+ return ctx.el("label", { class: "choice" }, input, ctx.el("div", {}, ctx.el("b", {}, title), ctx.el("span", {}, why)));
873
+ };
874
+ const day = SETUP.estimate ? `About $${Number(SETUP.estimate.usd_day).toFixed(2)} a day` : "It bills by the hour";
875
+ step.append(choice("build", "Build a new cluster", `About 20 minutes. ${day} from the first minute until someone deletes it.`));
876
+ if (!existing) {
877
+ const sub = ctx.el("div", { style: "margin:0 0 1rem 2rem" });
878
+ if (!read) {
879
+ sub.append(ctx.el("div", { class: "callout money", style: "margin-top:0" },
880
+ `Couldn't read whether account ${account} is approved for spending here${CLSTATE.overviewError ? `: ${CLSTATE.overviewError}` : ""}. Re-check on step 1.`));
881
+ } else if (!pre.approved) {
882
+ // The certificate contact goes with the approval, so it is asked for here.
883
+ const email = ctx.el("input", { name: "eks_email", type: "email", placeholder: "you@example.com", value: SETUP.f.email, autocomplete: "off" });
884
+ email.addEventListener("input", () => { SETUP.f.email = email.value.trim(); });
885
+ sub.append(ctx.el("div", { class: "callout money", style: "margin-top:0" },
886
+ `Account ${account} isn't approved for spending on this server. Approving lets anyone with the admin role build clusters here; it is recorded in the audit log.`,
887
+ ctx.el("label", { class: "f", style: "margin-top:.6rem" }, "Contact email for certificates (optional)", email),
888
+ ctx.el("div", { style: "margin-top:.5rem" }, fbtn(`Approve account ${account}`, () => setupApprove(account), "btn sm", !account || !ctx.canAdmin()))));
889
+ }
890
+ const eksctl = !(pre.blockers || []).some((b) => b.startsWith("eksctl "));
891
+ if (!eksctl) sub.append(ctx.el("div", { class: "callout money" }, "eksctl isn't installed on the server, and a build needs it. Install it, then Re-check on step 1."));
892
+ if (!SETUP.f.region) SETUP.f.region = s.region || pre.region || "";
893
+ const field = (label, key, attrs = {}, hint = "") => {
894
+ const input = ctx.el("input", { name: `eks_${key}`, value: String(SETUP.f[key] ?? ""), autocomplete: "off", ...attrs });
895
+ input.addEventListener("input", () => {
896
+ SETUP.f[key] = input.value.trim();
897
+ if (key === "nodes") setupPrice();
898
+ const go = ctx.$("#eks-build-go");
899
+ if (go) go.disabled = !setupCanBuild();
900
+ });
901
+ return ctx.el("div", {}, ctx.el("label", { class: "f" }, label, input), hint ? ctx.el("p", { class: "hint" }, hint) : "");
902
+ };
903
+ sub.append(ctx.el("div", { class: "two", style: "margin-top:.9rem" },
904
+ field("Name", "name", { placeholder: "team-eks" }), field("Region", "region", { placeholder: "us-east-1" }),
905
+ field("Nodes", "nodes", { type: "number", min: "1", max: "20" }),
906
+ field("Reminder to delete, in days", "expires", { placeholder: "7" }, "A reminder only: nothing deletes on it."),
907
+ field("Public names (optional)", "zone", { placeholder: "eks.example.com" },
908
+ "A DNS zone you control: workspaces become <name>.<zone>. Without one they open only in a "
909
+ + "browser on the server, and adding one later takes a shell on the server.")));
910
+ const est = SETUP.estimate;
911
+ const estBox = ctx.el("div", { class: "callout info", id: "eks-estimate" });
912
+ if (est) {
913
+ estBox.append("Estimate: ", ctx.el("b", {}, `~$${Number(est.usd_hr).toFixed(2)} an hour · ~$${Number(est.usd_day).toFixed(2)} a day · ~$${Math.round(est.usd_day * 30.4)} a month`),
914
+ `. ${est.basis || "On-demand prices"}; traffic and storage are extra.`);
915
+ } else estBox.append("Pricing…");
916
+ sub.append(estBox);
917
+ step.append(sub);
918
+ }
919
+ // SECOND, and only what houston built up front: an AWS account is usually the company's,
920
+ // and most EKS clusters a search finds there are somebody's production, not a place for
921
+ // a test workspace. "Use a cluster your team already runs" read as an invitation to them.
922
+ step.append(choice("existing", "Check for a cluster houston already built",
923
+ `Looks through account ${account || "on the server"} for EKS clusters built with houston. Connecting one is free.`));
924
+ if (existing) {
925
+ const sub = ctx.el("div", { style: "margin:0 0 0 2rem" });
926
+ if (SETUP.sweeping) sub.append(ctx.el("ul", { class: "checklist" }, ctx.el("li", {}, sq("run", "·"),
927
+ ctx.el("span", {}, `Searching the enabled AWS regions of account ${account}… about twenty seconds.`))));
928
+ else if (SETUP.sweepError) sub.append(ctx.el("div", { class: "zerr" }, ctx.el("span", {}, SETUP.sweepError),
929
+ fbtn("Try again", () => setupSweep(), "btn sm")));
930
+ else if (SETUP.sweep) {
931
+ const known = new Set(((CLUSTERS && CLUSTERS.contexts) || []).map((r) => r.context));
932
+ const row = (c) => {
933
+ const have = known.has(c.arn);
934
+ return ctx.el("div", { class: "drow", "data-swept": c.name },
935
+ ctx.el("div", { class: "grow" }, ctx.el("div", { class: "t" }, c.name),
936
+ ctx.el("div", { class: "m" }, [c.region, (c.status || "?").replace(/^ACTIVE$/u, "Active"),
937
+ c.ours ? "built with houston" : "not built with houston"].join(" · "))),
938
+ have ? ctx.el("span", { class: "m" }, "Connected")
939
+ : fbtn("Connect", () => setupConnect(c), "btn sm", !c.arn || (c.status && c.status !== "ACTIVE")));
940
+ };
941
+ const all = SETUP.sweep.clusters || [];
942
+ const ours = all.filter((c) => c.ours);
943
+ const others = all.filter((c) => !c.ours);
944
+ if (ours.length) sub.append(ctx.el("div", { class: "found" }, ...ours.map(row)));
945
+ else sub.append(ctx.el("p", { class: "hint", style: "font-size:13px" },
946
+ `No cluster built with houston in account ${account}. Build one above.`));
947
+ if (others.length) {
948
+ sub.append(ctx.el("details", { class: "adv", id: "eks-others", style: "margin-top:.6rem" },
949
+ ctx.el("summary", {}, `${ctx.plural(others.length, "other EKS cluster")} in this account, not built with houston`),
950
+ ctx.el("p", { class: "m", style: "margin:.4rem 0" },
951
+ "These belong to someone else in the account, often the company's own systems. Connect one only if it is meant for testing."),
952
+ ctx.el("div", { class: "found" }, ...others.map(row))));
953
+ }
954
+ const bad = (SETUP.sweep.unreadable || []).length;
955
+ sub.append(ctx.el("p", { class: "m", style: "margin-top:.4rem" },
956
+ `Searched ${(SETUP.sweep.regions || []).length} regions in account ${account}.`
957
+ + (bad ? ` ${bad} region${bad === 1 ? "" : "s"} could not be read, so this list may be missing a cluster.` : "")));
958
+ } else sub.append(fbtn(`Check account ${account}`, () => setupSweep()));
959
+ step.append(sub);
960
+ }
961
+ foot.append(fbtn("← Back", () => setupGo(1, true)),
962
+ fhint(existing ? "Connect a cluster from the list." : "It starts billing as soon as the build starts."));
963
+ if (!existing) {
964
+ const go = fbtn("Build it: starts billing", () => setupBuild(), "btn solid", !setupCanBuild());
965
+ go.id = "eks-build-go";
966
+ foot.append(go);
967
+ }
968
+ }
969
+
970
+ function setupCanBuild() {
971
+ const pre = setupPre() || {};
972
+ const eksctl = !(pre.blockers || []).some((b) => b.startsWith("eksctl "));
973
+ return !!(setupPre() && pre.approved && eksctl && SETUP.f.name && ctx.canAdmin());
974
+ }
975
+
976
+ async function setupPrice() {
977
+ const nodes = Number(SETUP.f.nodes) || 3;
978
+ try {
979
+ const r = await ctx.api(`/api/clusters/estimate?nodes=${encodeURIComponent(nodes)}`);
980
+ if ((Number(SETUP.f.nodes) || 3) !== nodes) return; // a newer value is on its way
981
+ SETUP.estimate = r;
982
+ } catch (e) { SETUP.estimate = null; const box = ctx.$("#eks-estimate"); if (box) box.textContent = e.message; return; }
983
+ if (ctx.$("#eks-setup").open && SETUP.step === 2) {
984
+ const focus = document.activeElement && document.activeElement.name;
985
+ renderSetup(false);
986
+ if (focus) { const el = ctx.$(`#eks-body [name="${focus}"]`); if (el) { el.focus(); const v = el.value; el.value = ""; el.value = v; } }
987
+ }
988
+ }
989
+
990
+ async function setupSweep() {
991
+ SETUP.sweeping = true; SETUP.sweepError = ""; SETUP.sweep = null;
992
+ renderSetup(false);
993
+ try {
994
+ const { job_id } = await ctx.api("/api/clusters/sweep", { method: "POST", body: JSON.stringify({ all: true }) });
995
+ for (;;) {
996
+ await new Promise((r) => setTimeout(r, 1000));
997
+ const state = await ctx.api(`/api/jobs/${job_id}`);
998
+ if (ctx.jobActive(state.status)) continue;
999
+ if (state.status === "error") throw new Error(state.error || "the search failed");
1000
+ SETUP.sweep = state.result || { clusters: [], regions: [] };
1001
+ break;
1002
+ }
1003
+ } catch (e) { SETUP.sweepError = e.message; }
1004
+ SETUP.sweeping = false;
1005
+ if (ctx.$("#eks-setup").open) renderSetup(false);
1006
+ }
1007
+
1008
+ async function setupConnect(cluster) {
1009
+ if (!ctx.canAdmin()) { ctx.toast("An administrator connects clusters on the Houston server."); return; }
1010
+ try {
1011
+ const result = await ctx.api("/api/clusters/connect", { method: "POST", body: JSON.stringify({ context: cluster.arn }) });
1012
+ SETUP.connected = { name: cluster.name, region: cluster.region, context: result.context,
1013
+ reachable: !!result.reachable, access_reason: result.access_reason || "" };
1014
+ SETUP.connectedStatus = undefined;
1015
+ setupGo(3);
1016
+ CLSTATE.overview = null;
1017
+ try { CLUSTERS = await ctx.api("/api/clusters"); clSyncRows(); } catch (_) { /* the page re-reads on open */ }
1018
+ try { SETUP.connectedStatus = await ctx.api(`/api/clusters/status?context=${encodeURIComponent(result.context)}`); }
1019
+ catch (_) { SETUP.connectedStatus = null; }
1020
+ if (SETUP.connectedStatus) CLSTATE.status[result.context] = SETUP.connectedStatus;
1021
+ if (ctx.$("#eks-setup").open && SETUP.step === 3) renderSetup(false);
1022
+ if (ctx.VIEW === "clusters") openClusters();
1023
+ } catch (e) { ctx.toast(e.message); }
1024
+ }
1025
+
1026
+ async function setupApprove(account) {
1027
+ try {
1028
+ await ctx.api("/api/clusters/approve", { method: "POST", body: JSON.stringify({ account, acme_email: SETUP.f.email || "" }) });
1029
+ ctx.toast(`Account ${account} approved for spending on this server. Recorded in the audit log.`, "ok");
1030
+ await setupRecheck(true);
1031
+ } catch (e) { ctx.toast(e.message); }
1032
+ }
1033
+
1034
+ async function setupBuild() {
1035
+ const name = (SETUP.f.name || "").trim();
1036
+ if (!name) { ctx.toast("The cluster needs a name, e.g. team-eks"); return; }
1037
+ // `|| 3`, as setupPrice prices it: a cleared field sent 0, which the server now refuses.
1038
+ const body = { name, region: SETUP.f.region, nodes: Number(SETUP.f.nodes) || 3, expires: SETUP.f.expires, zone: SETUP.f.zone };
1039
+ try {
1040
+ const { job_id } = await ctx.api("/api/clusters/create", { method: "POST", body: JSON.stringify(body) });
1041
+ SETUP.building = name;
1042
+ CLSTATE.jobs = [...CLSTATE.jobs, { id: job_id, kind: "cluster-create", label: name, status: "running", started_at: Date.now() / 1000 }];
1043
+ setupGo(3);
1044
+ // It runs on without this dialog: the Clusters page shows it as a building card,
1045
+ // and the toast says how it ended.
1046
+ const zone = SETUP.f.zone;
1047
+ ctx.watchDetachedJob({ id: job_id, title: `Building ${name}` }).then((state) => {
1048
+ CLSTATE.overview = null;
1049
+ if (ctx.VIEW === "clusters") openClusters();
1050
+ if (state && state.status !== "error" && zone) {
1051
+ ctx.toast(`${name} is ready. One step left: its DNS record — Set up DNS on its card.`, "info");
1052
+ }
1053
+ });
1054
+ if (ctx.VIEW === "clusters") openClusters();
1055
+ } catch (e) { ctx.toast(e.message); }
1056
+ }
1057
+
1058
+ function setupStepThree(step, foot) {
1059
+ if (SETUP.building) {
1060
+ step.append(ctx.el("p", { class: "wzd-q", tabindex: "-1" }, `${SETUP.building} is being built`),
1061
+ ctx.el("div", { class: "progress", style: "margin:.4rem 0 1rem" }, ctx.el("i", { style: "width:6%" })),
1062
+ ctx.el("p", { class: "hint", style: "font-size:14px" }, "About 20 minutes. You can close this: the Clusters page shows its progress, "
1063
+ + "and it appears as a place to run workspaces when it is ready."),
1064
+ // Said BEFORE it is needed: nothing told a first-time user a built cluster wants a DNS record.
1065
+ ctx.el("p", { class: "hint", style: "font-size:14px" }, SETUP.f.zone
1066
+ ? `Then one step is left: one DNS record, so its workspaces get public names under ${SETUP.f.zone}. `
1067
+ + "Home and the cluster's card show it, with a Set up button."
1068
+ : "Without a DNS zone its workspaces open only in a browser on the server, through a port-forward; the cluster's page says how to add one."));
1069
+ foot.append(fhint(""), fbtn("Close", () => ctx.$("#eks-setup").close(), "btn solid"));
1070
+ return;
1071
+ }
1072
+ const c = SETUP.connected || {};
1073
+ const st = SETUP.connectedStatus;
1074
+ step.append(ctx.el("p", { class: "wzd-q", tabindex: "-1" }, `${c.name || "The cluster"} is connected`));
1075
+ const list = ctx.el("ul", { class: "checklist" });
1076
+ list.append(ctx.el("li", {}, c.reachable ? sq("y", "✓") : sq("n", "!"),
1077
+ ctx.el("span", {}, c.reachable ? `${c.name} answers from this server` : `${c.name} does not let this server in yet: ${c.access_reason || "access denied"}`)));
1078
+ if (st === undefined) list.append(ctx.el("li", {}, sq("run", "·"), ctx.el("span", {}, "Checking what it has…")));
1079
+ else if (st && st.ready) {
1080
+ const r = st.ready;
1081
+ const ready = r.storage_class && r.ingress_class && r.cert_manager;
1082
+ list.append(ctx.el("li", {}, ready ? sq("y", "✓") : sq("n", "!"),
1083
+ ctx.el("span", {}, ready ? "Storage, ingress and certificates are ready"
1084
+ : "Not prepared yet: Prepare installs the ingress and certificates workspaces need",
1085
+ !ready && ctx.canAdmin() ? ctx.el("span", {}, " ", fbtn("Prepare it", () => clPrepare(c.context), "btn sm")) : "")));
1086
+ }
1087
+ step.append(list);
1088
+ const target = st && st.ready && st.ready.cname_target;
1089
+ if (target || (st && st.zone)) {
1090
+ const record = `*.${(st && st.zone) || "<your zone>"} CNAME ${target || "<the load balancer's address, once it has one>"}`;
1091
+ step.append(ctx.el("div", { class: "way" }, ctx.el("h4", {}, "Public names ", ctx.el("span", { class: "pill off" }, "Needed from other computers")),
1092
+ ctx.el("p", {}, `Without them, workspaces on ${c.name} open only in a browser on the server itself, through a port-forward. Add one DNS record:`),
1093
+ ctx.el("div", { class: "cmd" }, ctx.el("pre", {}, record), fbtn("Copy", () => clCopy(record, "the record"), "btn sm"))));
1094
+ }
1095
+ foot.append(fhint(""), fbtn("Close", () => ctx.$("#eks-setup").close()));
1096
+ if (ctx.canWrite() && c.context) {
1097
+ foot.append(fbtn(`Create a workspace on ${c.name}`, () => {
1098
+ ctx.$("#eks-setup").close();
1099
+ ctx.openCreate(undefined, { dest: `eks:${c.context}` });
1100
+ }, "btn solid", !c.reachable));
1101
+ }
1102
+ }
1103
+
1104
+ // ---- a cluster's public names ---------------------------------------------------
1105
+ // Its DNS zone and the load balancer to point it at, from the cluster's own view.
1106
+ const BUILD = { name: "", zone: "", target: "", region4: "" };
1107
+
1108
+ const chk = (ok, ...text) => ctx.el("div", { class: "chk" },
1109
+ ctx.el("span", { class: ok ? "ok" : "no" }, ok ? "✓" : "✗"), ctx.el("span", {}, ...text));
1110
+
1111
+ function sameIn(command) {
1112
+ return ctx.el("div", { class: "same" }, ctx.el("span", {}, "In a shell on the server:"),
1113
+ cmdCode(command),
1114
+ ctx.el("button", { type: "button", class: "cp", onclick: () => clCopy(command, "the command") }, "copy"));
1115
+ }
1116
+
1117
+ function btn(label, onclick, { primary = false, disabled = false } = {}) {
1118
+ const b = ctx.el("button", { type: "button", class: "btn" + (primary ? " solid" : ""), onclick }, label);
1119
+ if (disabled) b.disabled = true;
1120
+ return b;
1121
+ }
1122
+
1123
+ // One record, laid out the way a DNS provider's form asks for it. The one-line
1124
+ // "*.zone CNAME target" left a first-time user to work out that Cloudflare wants only the
1125
+ // part before the domain (typing "*" made *.example.com, every name on the domain), that
1126
+ // its proxy must be off (it defaults on, and warns when turned off), and that
1127
+ // houston-probe is a test name, not a record to create -- all three happened.
1128
+ function clDnsNames(zone) {
1129
+ // The registered domain: the last two labels, or three under a two-part suffix such as
1130
+ // co.uk or com.au. ponytail: a heuristic, not the public suffix list; it only words a hint.
1131
+ const labels = zone.split(".");
1132
+ const twoPart = labels.length > 2 && /^[a-z]{2}$/u.test(labels.at(-1)) && /^(co|com|net|org|gov|ac|edu)$/u.test(labels.at(-2));
1133
+ const apex = labels.slice(twoPart ? -3 : -2).join(".");
1134
+ return { apex, rel: zone === apex ? "*" : `*.${zone.slice(0, -apex.length - 1)}` };
1135
+ }
1136
+
1137
+ function clRenderDns() {
1138
+ const body = ctx.$("#cluster-build-body");
1139
+ const menu = ctx.$("#cluster-build-menu");
1140
+ ctx.$("#cluster-build-title").textContent = `Public names for ${BUILD.name}`;
1141
+ ctx.$("#cluster-build-steps").innerHTML = "";
1142
+ body.innerHTML = ""; menu.innerHTML = "";
1143
+ const zone = BUILD.zone;
1144
+ menu.append(btn("Close", () => ctx.$("#cluster-build").close()));
1145
+ if (!zone) {
1146
+ body.append(ctx.el("p", { class: "hint" }, "This cluster has no DNS zone, so a workspace on it opens only in a "
1147
+ + "browser on the server that made it, through a port-forward. Give it a zone, a domain you control such as "
1148
+ + "rc.example.com, and every workspace is named <name>.<zone>; then add the one record this shows."),
1149
+ sameIn(`houston cluster prepare ${BUILD.name} --zone <zone>`));
1150
+ return;
1151
+ }
1152
+ const { apex, rel } = clDnsNames(zone);
1153
+ const target = BUILD.target || "<the load balancer's address, once it has one>";
1154
+ body.append(ctx.el("p", { class: "hint" }, `Workspaces on this cluster are named <name>.${zone}. Add this one record `
1155
+ + "at your DNS provider, once:"));
1156
+ body.append(kvGrid([
1157
+ ["Type", ctx.el("b", {}, "CNAME"), ctx.el("span", { class: "m" }, " — not an A record: the load balancer's addresses change")],
1158
+ ["Name", ctx.el("code", {}, `*.${zone}`), ctx.el("div", { class: "m" }, "Cloudflare and most providers want only the part "
1159
+ + `before your domain: if your domain is ${apex}, type `, ctx.el("code", {}, rel), ".")],
1160
+ ["Target", ctx.el("code", {}, target), " ", ctx.el("button", { type: "button", class: "cp", onclick: () => clCopy(target, "the target") }, "copy")],
1161
+ ["Proxy", ctx.el("b", {}, "DNS only"), ctx.el("div", { class: "m" }, "At Cloudflare, the grey cloud. Ignore its warning that this "
1162
+ + "exposes your origin: the target is a public AWS load balancer, and the proxy would take over HTTPS, so the "
1163
+ + "workspaces' certificates fail.")],
1164
+ ]));
1165
+ body.append(ctx.el("p", { class: "hint" }, "houston checks it by looking up ", ctx.el("code", {}, `houston-probe.${zone}`),
1166
+ ", a name you do not create: the record above answers for it."));
1167
+ body.append(ctx.el("div", { id: "cluster-build-dns", class: "chk-slot" }));
1168
+ body.append(sameIn(`dig +short houston-probe.${zone} CNAME @1.1.1.1`));
1169
+ menu.append(btn("Check DNS", () => clBuildCheckDns()));
1170
+ }
1171
+
1172
+ async function clBuildCheckDns() {
1173
+ const slot = ctx.$("#cluster-build-dns");
1174
+ if (!slot || !BUILD.zone) return;
1175
+ const host = `houston-probe.${BUILD.zone}`;
1176
+ slot.innerHTML = "";
1177
+ slot.append(ctx.el("span", { class: "muted" }, `asking for ${host}…`));
1178
+ try {
1179
+ const r = await ctx.api(`/api/clusters/dns-check?host=${encodeURIComponent(host)}&target=${encodeURIComponent(BUILD.target)}`);
1180
+ slot.innerHTML = "";
1181
+ if (r.matches) slot.append(chk(true, `${host} answers — it reaches the cluster`));
1182
+ else if (r.answers && r.answers.length) slot.append(chk(false, `${host} points at ${r.answers.join(", ")}, not at the cluster`));
1183
+ else if (r.addresses && r.addresses.length) {
1184
+ slot.append(chk(false, `${host} answers with addresses (${r.addresses.join(", ")}) but not the CNAME: the record is `
1185
+ + "proxied (at Cloudflare, set it to DNS only, the grey cloud) or it is an A record (make it a CNAME)."));
1186
+ } else {
1187
+ slot.append(chk(false, `${host} does not answer yet. Check the record's name is *.${BUILD.zone} `
1188
+ + `(${clDnsNames(BUILD.zone).rel} at Cloudflare); a new record takes a few minutes.`));
1189
+ }
1190
+ } catch (e) { slot.innerHTML = ""; slot.append(chk(false, e.message)); }
1191
+ }
1192
+
1193
+ function clOpenDns(row) {
1194
+ const st = CLSTATE.status[row.context] || {};
1195
+ Object.assign(BUILD, { name: clShort(row), region4: st.region || row.region || "",
1196
+ zone: st.zone || "", target: (st.ready && st.ready.cname_target) || "" });
1197
+ clRenderDns();
1198
+ ctx.$("#cluster-build").showModal();
1199
+ }
1200
+
1201
+ function clJobResultBox(lines) {
1202
+ const pre = ctx.$("#job-log");
1203
+ if (!pre) return;
1204
+ const box = ctx.el("div", { class: "result" }, ctx.el("div", { html: "<hr>" }));
1205
+ for (const [text, cls] of lines) box.append(ctx.el("div", { class: cls || "" }, ...codeText(text)));
1206
+ pre.append(box);
1207
+ pre.scrollTop = pre.scrollHeight;
1208
+ }
1209
+
1210
+ function renderClusterDeleteResult(r) {
1211
+ if (!r || typeof r !== "object") return;
1212
+ const left = r.leftovers || { found: [], unreadable: [] };
1213
+ const region = r.region || "the region";
1214
+ const lines = [];
1215
+ if (!(left.found || []).length && !(left.unreadable || []).length) {
1216
+ lines.push([`nothing in ${region} is billing — AWS holds no volume, load balancer, NAT gateway, address or stack of it`, "ok"]);
1217
+ } else {
1218
+ // Tied to this cluster by a tag: with the command. Not tied: to check, without one.
1219
+ const tied = (left.found || []).filter((row) => row.certain !== false);
1220
+ const loose = (left.found || []).filter((row) => row.certain === false);
1221
+ if (tied.length) lines.push([`left behind in ${region} — each one bills until it is removed:`, "warn"]);
1222
+ for (const row of tied) {
1223
+ lines.push([` ${row.kind} ${row.id} ${row.detail || ""}`]);
1224
+ lines.push([` \`${row.fix}\``]);
1225
+ }
1226
+ if (loose.length) lines.push([`in ${region}, not tied to this cluster by any tag — check before deleting:`, "warn"]);
1227
+ for (const row of loose) lines.push([` ${row.kind} ${row.id} ${row.detail || ""}`]);
1228
+ for (const row of left.unreadable || []) {
1229
+ lines.push([` ${row.kind}: could not be read (${row.why}) — check it in AWS`, "warn"]);
1230
+ }
1231
+ }
1232
+ lines.push(["next: `houston cluster list` checks every region, so nothing is missed"]);
1233
+ clJobResultBox(lines);
1234
+ }
1235
+
1236
+ function renderClusterCreateResult(r) {
1237
+ if (!r || typeof r !== "object") return;
1238
+ const prepared = r.prepared || {};
1239
+ const lines = [[`cluster ${r.name || ""} is up in ${r.region || ""}`, "ok"]];
1240
+ if (prepared.cname_target) {
1241
+ lines.push([`next: point *.${prepared.zone || "<your zone>"} at ${prepared.cname_target} (a CNAME, once, at your DNS provider)`]);
1242
+ }
1243
+ lines.push([`then click New workspace and pick ${r.name || "the cluster"} under Where it runs`]);
1244
+ clJobResultBox(lines);
1245
+ }
1246
+
1247
+ function renderClusterSweepResult(r) {
1248
+ if (!r || typeof r !== "object") return;
1249
+ const lines = [[`${(r.regions || []).length} region(s) swept, ${(r.clusters || []).length} cluster(s) found`]];
1250
+ for (const c of r.clusters || []) {
1251
+ lines.push([` ${c.region} ${c.name} ${c.status || "?"}${c.expires ? ` · expires ${c.expires}` : ""}${c.ours ? "" : " · not houston's"}`]);
1252
+ }
1253
+ for (const bad of r.unreadable || []) {
1254
+ lines.push([` ${bad.region} could NOT be read (${bad.why}) — this report does not cover it`, "warn"]);
1255
+ }
1256
+ clJobResultBox(lines);
1257
+ }
1258
+
1259
+ function clAskDelete(row, st) {
1260
+ const name = row.context.split("/").pop();
1261
+ CLSTATE.deleting = name;
1262
+ // The ROW, for its region: the request carried only the name, the server looked in the
1263
+ // AWS CLI's default region, found nothing, and the dialog said "Done" over a cluster
1264
+ // that billed on in eu-west-1.
1265
+ CLSTATE.deletingRow = row;
1266
+ ctx.$("#cluster-delete-what").textContent =
1267
+ `${name} — this destroys the cluster, its VPC and everything in it. It cannot be undone.`;
1268
+ const holds = ctx.$("#cluster-delete-holds");
1269
+ holds.innerHTML = "";
1270
+ if (st && st.workspaces && st.workspaces.length) {
1271
+ holds.append(ctx.el("p", { class: "cl-warn" },
1272
+ `It is holding ${st.workspaces.length} workspace(s): `
1273
+ + st.workspaces.map((w) => `${w.name} (${w.owner || "unowned"})`).join(", ")
1274
+ + ". The delete will refuse unless you force it — and on a shared cluster those "
1275
+ + "owners may be colleagues on other machines."));
1276
+ } else if (!st || !st.reachable) {
1277
+ holds.append(ctx.el("p", { class: "cl-warn" },
1278
+ "What it holds could not be read, which is not the same as it being empty."));
1279
+ }
1280
+ const form = ctx.$("#cluster-delete-form");
1281
+ form.reset();
1282
+ ctx.$("#cluster-delete-go").disabled = true;
1283
+ form.confirm.oninput = () => {
1284
+ ctx.$("#cluster-delete-go").disabled = form.confirm.value.trim() !== name;
1285
+ };
1286
+ ctx.$("#cluster-delete-dialog").showModal();
1287
+ }
1288
+
1289
+ async function clSubmitDelete(ev) {
1290
+ ev.preventDefault();
1291
+ const form = ctx.$("#cluster-delete-form");
1292
+ const name = CLSTATE.deleting;
1293
+ if (!name || form.confirm.value.trim() !== name) return;
1294
+ const force = !!form.force.checked;
1295
+ ctx.$("#cluster-delete-dialog").close();
1296
+ try {
1297
+ const { job_id } = await ctx.api("/api/clusters/delete",
1298
+ { method: "POST", body: JSON.stringify({ name, force,
1299
+ region: (CLSTATE.deletingRow && CLSTATE.deletingRow.region) || "" }) });
1300
+ ctx.streamJob(job_id, `Deleting ${name}`, (res) => {
1301
+ renderClusterDeleteResult(res);
1302
+ ctx.toast(`cluster ${name} is gone`, "ok");
1303
+ delete CLSTATE.status[name];
1304
+ openClusters();
1305
+ });
1306
+ } catch (e) { ctx.toast(e.message); }
1307
+ }
1308
+
1309
+ ctx.$("#edge-close").addEventListener("click", () => ctx.$("#edge-dialog").close());
1310
+ // The Access note follows BOTH things it talks about: which cluster, and whether a
1311
+ // name has been given.
1312
+ ctx.$("#context-select").addEventListener("change", ctx.syncClusterNote);
1313
+ ctx.$("#create-form").domain.addEventListener("input", ctx.syncClusterNote);
1314
+ ctx.$("#cluster-badge").addEventListener("click", () => openClusters());
1315
+ // Enter in a field must not close a flow: every step moves by its own buttons.
1316
+ ctx.$("#cluster-build-form").addEventListener("submit", (ev) => ev.preventDefault());
1317
+ ctx.$("#eks-form").addEventListener("submit", (ev) => ev.preventDefault());
1318
+ ctx.$("#eks-x").addEventListener("click", () => ctx.$("#eks-setup").close());
1319
+ ctx.$("#cluster-delete-cancel").addEventListener("click",
1320
+ () => ctx.$("#cluster-delete-dialog").close());
1321
+ ctx.$("#cluster-delete-form").addEventListener("submit", clSubmitDelete);
1322
+ ctx.$("#doctor-recheck").addEventListener("click", ctx.openDoctor);
1323
+ ctx.$("#doctor-close").addEventListener("click", () => ctx.$("#doctor-dialog").close());
1324
+ ctx.$("#cap-cancel").addEventListener("click", () => ctx.$("#cap-dialog").close());
1325
+ ctx.$("#cap-submit").addEventListener("click", ctx.submitCap);
1326
+
1327
+ const POLL_MS = 4000;
1328
+ let pollTimer = null;
1329
+ function startPolling() { if (!pollTimer) pollTimer = setInterval(ctx.loadRepros, POLL_MS); }
1330
+ function stopPolling() { if (pollTimer) { clearInterval(pollTimer); pollTimer = null; } }
1331
+ // Each poll costs several docker CLI invocations; a hidden tab kept paying for them.
1332
+ document.addEventListener("visibilitychange", () => {
1333
+ if (document.hidden) stopPolling();
1334
+ else { ctx.loadRepros(); startPolling(); }
1335
+ });
1336
+
1337
+ ctx.loadRepros().then(ctx.restoreLocation);
1338
+ ctx.adoptRunningJobs();
1339
+ ctx.refreshKube();
1340
+ startPolling();
1341
+
1342
+ Object.defineProperties(ctx, {
1343
+ "CLUSTERS": { enumerable: true, get: () => CLUSTERS, set: value => { CLUSTERS = value; } },
1344
+ "CLSTATE": { enumerable: true, get: () => CLSTATE },
1345
+ "clCost": { enumerable: true, get: () => clCost },
1346
+ "clAttention": { enumerable: true, get: () => clAttention },
1347
+ "refreshClusterBadge": { enumerable: true, get: () => refreshClusterBadge },
1348
+ "codeText": { enumerable: true, get: () => codeText },
1349
+ "awsSignIn": { enumerable: true, get: () => awsSignIn },
1350
+ "loadClusterOverview": { enumerable: true, get: () => loadClusterOverview },
1351
+ "clReadConnection": { enumerable: true, get: () => clReadConnection },
1352
+ "clStateOf": { enumerable: true, get: () => clStateOf },
1353
+ "clWhere": { enumerable: true, get: () => clWhere },
1354
+ "clRows": { enumerable: true, get: () => clRows },
1355
+ "clBuilding": { enumerable: true, get: () => clBuilding },
1356
+ "clForget": { enumerable: true, get: () => clForget },
1357
+ "clProbe": { enumerable: true, get: () => clProbe },
1358
+ "openClusters": { enumerable: true, get: () => openClusters },
1359
+ "clRefresh": { enumerable: true, get: () => clRefresh },
1360
+ "openPlace": { enumerable: true, get: () => openPlace },
1361
+ "openContext": { enumerable: true, get: () => openContext },
1362
+ "openEksSetup": { enumerable: true, get: () => openEksSetup },
1363
+ "clPrepare": { enumerable: true, get: () => clPrepare },
1364
+ "clCopy": { enumerable: true, get: () => clCopy },
1365
+ "clCopyDoc": { enumerable: true, get: () => clCopyDoc },
1366
+ "clOpenDns": { enumerable: true, get: () => clOpenDns },
1367
+ "renderClusterDeleteResult": { enumerable: true, get: () => renderClusterDeleteResult },
1368
+ "renderClusterCreateResult": { enumerable: true, get: () => renderClusterCreateResult },
1369
+ "renderClusterSweepResult": { enumerable: true, get: () => renderClusterSweepResult },
1370
+ "clAskDelete": { enumerable: true, get: () => clAskDelete },
1371
+ "clSubmitDelete": { enumerable: true, get: () => clSubmitDelete },
1372
+ "POLL_MS": { enumerable: true, get: () => POLL_MS },
1373
+ "pollTimer": { enumerable: true, get: () => pollTimer, set: value => { pollTimer = value; } },
1374
+ "startPolling": { enumerable: true, get: () => startPolling },
1375
+ "stopPolling": { enumerable: true, get: () => stopPolling },
1376
+ });
1377
+ export { CLUSTERS, CLSTATE, clCost, clAttention, refreshClusterBadge, codeText, awsSignIn, loadClusterOverview, clReadConnection, clStateOf, clWhere, clRows, clBuilding, clForget, clProbe, openClusters, clRefresh, openPlace, openContext, openEksSetup, clPrepare, clCopy, clCopyDoc, clOpenDns, renderClusterDeleteResult, renderClusterCreateResult, renderClusterSweepResult, clAskDelete, clSubmitDelete, POLL_MS, pollTimer, startPolling, stopPolling };