@tsplc/tmp-agent 0.0.0-stage → 0.6.3

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 (65) hide show
  1. package/README.md +26 -2
  2. package/dist/cli.js +4888 -0
  3. package/dist/cli.js.map +53 -0
  4. package/dist/client.js +514 -0
  5. package/dist/client.js.map +12 -0
  6. package/dist/index.js +3680 -0
  7. package/dist/index.js.map +41 -0
  8. package/package.json +61 -4
  9. package/src/access.ts +260 -0
  10. package/src/agent.ts +461 -0
  11. package/src/audit.ts +74 -0
  12. package/src/cli.ts +290 -0
  13. package/src/client.ts +407 -0
  14. package/src/codesys.ts +195 -0
  15. package/src/dashboard/index.ts +159 -0
  16. package/src/dashboard/ui/access.ts +191 -0
  17. package/src/dashboard/ui/actions.ts +207 -0
  18. package/src/dashboard/ui/api.ts +138 -0
  19. package/src/dashboard/ui/app.ts +41 -0
  20. package/src/dashboard/ui/approval.ts +131 -0
  21. package/src/dashboard/ui/audit.ts +115 -0
  22. package/src/dashboard/ui/contract.ts +19 -0
  23. package/src/dashboard/ui/dashboard.css +1332 -0
  24. package/src/dashboard/ui/deployment.ts +431 -0
  25. package/src/dashboard/ui/deployments.ts +319 -0
  26. package/src/dashboard/ui/details.ts +214 -0
  27. package/src/dashboard/ui/dom.ts +87 -0
  28. package/src/dashboard/ui/environment.ts +345 -0
  29. package/src/dashboard/ui/format.ts +124 -0
  30. package/src/dashboard/ui/logs.ts +126 -0
  31. package/src/dashboard/ui/main.ts +88 -0
  32. package/src/dashboard/ui/overlay.ts +144 -0
  33. package/src/dashboard/ui/shell.ts +185 -0
  34. package/src/dashboard/ui/source.ts +144 -0
  35. package/src/debugging.ts +142 -0
  36. package/src/deploy.ts +203 -0
  37. package/src/deployments/health.ts +98 -0
  38. package/src/deployments/retention.ts +44 -0
  39. package/src/deployments/routes.ts +281 -0
  40. package/src/deployments/runner.ts +900 -0
  41. package/src/deployments/store.ts +209 -0
  42. package/src/deployments/submission.ts +78 -0
  43. package/src/discovery.ts +90 -0
  44. package/src/environment.ts +214 -0
  45. package/src/errors.ts +12 -0
  46. package/src/index.ts +36 -0
  47. package/src/instance.ts +51 -0
  48. package/src/login.ts +267 -0
  49. package/src/logs.ts +115 -0
  50. package/src/maintenance.ts +303 -0
  51. package/src/operations.ts +149 -0
  52. package/src/processes.ts +41 -0
  53. package/src/protocol.ts +557 -0
  54. package/src/releases.ts +414 -0
  55. package/src/restarts.ts +96 -0
  56. package/src/routes.ts +128 -0
  57. package/src/secrets.ts +174 -0
  58. package/src/server-process.ts +264 -0
  59. package/src/service.ts +194 -0
  60. package/src/sessions.ts +58 -0
  61. package/src/state.ts +126 -0
  62. package/src/tailscale.ts +112 -0
  63. package/src/terminal.ts +57 -0
  64. package/src/transfer.ts +94 -0
  65. package/src/upgrade.ts +153 -0
@@ -0,0 +1,345 @@
1
+ import { errorMessage } from "../../errors";
2
+ import type {
3
+ EnvironmentEntry,
4
+ EnvironmentListing,
5
+ EnvironmentValue,
6
+ } from "../../protocol";
7
+ import { api } from "./api";
8
+ import { type App, attempt } from "./app";
9
+ import { contract } from "./contract";
10
+ import {
11
+ badge,
12
+ dot,
13
+ empty,
14
+ fill,
15
+ h,
16
+ pageHeader,
17
+ type Tone,
18
+ type View,
19
+ } from "./dom";
20
+ import { confirm, dialog } from "./overlay";
21
+
22
+ /** A row of the Environment page: a plain variable or a secret, and where it stands. */
23
+ interface Variable {
24
+ name: string;
25
+ secret: boolean;
26
+ /** A plain variable's value on this PC, or the running release's when only it has one. */
27
+ value: string | null;
28
+ /** Whether this PC holds it, so it can be edited and deleted here. */
29
+ stored: boolean;
30
+ status: Status;
31
+ }
32
+
33
+ interface Status {
34
+ tone: Tone;
35
+ text: string;
36
+ }
37
+
38
+ const applied: Status = { tone: "ok", text: "Running" };
39
+ const pending: Status = { tone: "waiting", text: "Deploy to apply" };
40
+
41
+ /** A secret stands applied once the running release reads it; the next deployment picks up a new one. */
42
+ const secretStatus = (entry: EnvironmentEntry): Status => {
43
+ if (!entry.set) {
44
+ return { tone: "error", text: "Not set" };
45
+ }
46
+ return entry.declared ? applied : pending;
47
+ };
48
+
49
+ const editLabel = (variable: Variable) => {
50
+ if (!variable.stored) {
51
+ return "Set";
52
+ }
53
+ return variable.secret ? "Replace" : "Edit";
54
+ };
55
+
56
+ /** The page's rows: this PC's plain variables, what the running release has besides, and the secrets. */
57
+ const variables = ({
58
+ values,
59
+ variables: stored,
60
+ secrets,
61
+ }: EnvironmentListing): Variable[] => {
62
+ const secretNames = new Set(secrets.map(({ name }) => name));
63
+ const plain = [...new Set([...Object.keys(stored), ...Object.keys(values)])]
64
+ .filter((name) => !secretNames.has(name))
65
+ .sort()
66
+ .map((name): Variable => {
67
+ const value = stored[name];
68
+ if (value === undefined) {
69
+ return {
70
+ name,
71
+ secret: false,
72
+ value: values[name] ?? null,
73
+ stored: false,
74
+ status: { tone: "ok", text: "Running, not set on this PC" },
75
+ };
76
+ }
77
+ return {
78
+ name,
79
+ secret: false,
80
+ value,
81
+ stored: true,
82
+ status: values[name] === value ? applied : pending,
83
+ };
84
+ });
85
+ const secret = secrets.map(
86
+ (entry): Variable => ({
87
+ name: entry.name,
88
+ secret: true,
89
+ value: null,
90
+ stored: entry.set,
91
+ status: secretStatus(entry),
92
+ }),
93
+ );
94
+ return [...plain, ...secret];
95
+ };
96
+
97
+ /** Asks for a variable's value, and whether it is a secret, which is never shown again. */
98
+ const askValue = (variable: Variable | null) => {
99
+ const nameInput = h("input", {
100
+ class: "input mono",
101
+ placeholder: "NAME",
102
+ autocomplete: "off",
103
+ spellcheck: "false",
104
+ required: true,
105
+ pattern: contract.envNamePattern,
106
+ });
107
+ const valueInput = h("input", {
108
+ class: "input mono",
109
+ type: variable?.secret ? "password" : "text",
110
+ autocomplete: "off",
111
+ spellcheck: "false",
112
+ placeholder: "Value",
113
+ value: variable && !variable.secret ? (variable.value ?? "") : "",
114
+ });
115
+ const secretInput = h("input", {
116
+ type: "checkbox",
117
+ checked: variable?.secret ?? false,
118
+ });
119
+ const note = h("p", { class: "muted" });
120
+ const describe = () => {
121
+ valueInput.type = secretInput.checked ? "password" : "text";
122
+ note.textContent = secretInput.checked
123
+ ? "Kept on this PC with Bun.secrets and never shown again. The PLC's program gets it at each deployment, the server when it starts."
124
+ : "Shown here. The next tsplc deploy builds the PLC's program with it and starts the server with it.";
125
+ };
126
+ secretInput.addEventListener("change", describe);
127
+ describe();
128
+ return dialog<{ name: string; change: EnvironmentValue }>({
129
+ title: variable ? `Set ${variable.name}` : "Add a variable",
130
+ body: [
131
+ variable
132
+ ? null
133
+ : h("label", { class: "field" }, h("span", {}, "Name"), nameInput),
134
+ h("label", { class: "field" }, h("span", {}, "Value"), valueInput),
135
+ h("label", { class: "check" }, secretInput, "Secret"),
136
+ note,
137
+ ],
138
+ actions: (close) => [
139
+ h(
140
+ "button",
141
+ {
142
+ class: "button primary",
143
+ onclick: () => {
144
+ const name = variable?.name ?? nameInput.value.trim();
145
+ if (!variable && (!name || !nameInput.checkValidity())) {
146
+ nameInput.reportValidity();
147
+ return;
148
+ }
149
+ close({
150
+ name,
151
+ change: { secret: secretInput.checked, value: valueInput.value },
152
+ });
153
+ },
154
+ },
155
+ "Save",
156
+ ),
157
+ ],
158
+ });
159
+ };
160
+
161
+ /** This PC's variables, plain and secret, and whether the running release has them. */
162
+ export const environmentView = (app: App): View => {
163
+ const admin = app.can("admin");
164
+ const body = h("tbody");
165
+ const table = h(
166
+ "table",
167
+ { class: "table" },
168
+ h(
169
+ "thead",
170
+ {},
171
+ h(
172
+ "tr",
173
+ {},
174
+ h("th", {}, "Name"),
175
+ h("th", {}, "Value"),
176
+ h("th", {}, "Status"),
177
+ admin ? h("th", {}, "") : null,
178
+ ),
179
+ ),
180
+ body,
181
+ );
182
+ const holder = h("div", {}, empty("Loading the environment…"));
183
+
184
+ const set = async (variable: Variable | null) => {
185
+ const entered = await askValue(variable);
186
+ if (!entered) {
187
+ return;
188
+ }
189
+ const listing = await attempt(
190
+ () => api.setEnvironment(entered.name, entered.change),
191
+ {
192
+ done: entered.change.secret
193
+ ? `Saved ${entered.name}. The next deployment applies it, and Restart server applies it to the server now.`
194
+ : `Saved ${entered.name}. Deploy to apply it to the PLC's program and the server.`,
195
+ },
196
+ );
197
+ if (listing) {
198
+ render(listing);
199
+ }
200
+ };
201
+
202
+ const remove = async (variable: Variable) => {
203
+ const confirmed = await confirm({
204
+ title: `Delete ${variable.name}?`,
205
+ body: [
206
+ h(
207
+ "p",
208
+ {},
209
+ variable.secret
210
+ ? "A release that reads it can't deploy without it, and the server starts without it after the next restart."
211
+ : "The next deployment is built without it, unless tsplc.config.ts sets it.",
212
+ ),
213
+ ],
214
+ confirm: "Delete",
215
+ tone: "danger",
216
+ });
217
+ if (!confirmed) {
218
+ return;
219
+ }
220
+ const listing = await attempt(() => api.deleteEnvironment(variable.name), {
221
+ done: `Deleted ${variable.name}`,
222
+ });
223
+ if (listing) {
224
+ render(listing);
225
+ }
226
+ };
227
+
228
+ const row = (variable: Variable) =>
229
+ h(
230
+ "tr",
231
+ {},
232
+ h(
233
+ "td",
234
+ {},
235
+ h("span", { class: "mono" }, variable.name),
236
+ variable.secret ? h("span", {}, " ", badge("Secret")) : null,
237
+ ),
238
+ h(
239
+ "td",
240
+ { class: "mono" },
241
+ variable.secret
242
+ ? h(
243
+ "span",
244
+ { class: "muted" },
245
+ variable.stored ? "••••••••" : "Not set",
246
+ )
247
+ : variable.value,
248
+ ),
249
+ h(
250
+ "td",
251
+ {},
252
+ h(
253
+ "span",
254
+ { class: "state" },
255
+ dot(variable.status.tone),
256
+ variable.status.text,
257
+ ),
258
+ ),
259
+ admin
260
+ ? h(
261
+ "td",
262
+ { class: "row-actions" },
263
+ h(
264
+ "button",
265
+ { class: "button small", onclick: () => void set(variable) },
266
+ editLabel(variable),
267
+ ),
268
+ variable.stored
269
+ ? h(
270
+ "button",
271
+ {
272
+ class: "button small danger-text",
273
+ onclick: () => void remove(variable),
274
+ },
275
+ "Delete",
276
+ )
277
+ : null,
278
+ )
279
+ : null,
280
+ );
281
+
282
+ const render = (listing: EnvironmentListing) => {
283
+ const rows = variables(listing);
284
+ fill(body, ...rows.map(row));
285
+ fill(
286
+ holder,
287
+ rows.length
288
+ ? table
289
+ : empty(
290
+ "No variables yet. Add one, and the next deployment builds with it.",
291
+ ),
292
+ );
293
+ };
294
+
295
+ const restart = async () => {
296
+ const confirmed = await confirm({
297
+ title: "Restart the server?",
298
+ body: [
299
+ h(
300
+ "p",
301
+ {},
302
+ "The line's server stops and starts again with the running release's values and the secrets as they are now. The controller keeps running.",
303
+ ),
304
+ ],
305
+ confirm: "Restart",
306
+ tone: "primary",
307
+ });
308
+ if (confirmed) {
309
+ await attempt(() => api.restartServer(), {
310
+ done: "The server restarted",
311
+ });
312
+ }
313
+ };
314
+
315
+ void api
316
+ .environment()
317
+ .then(render, (error: unknown) =>
318
+ fill(holder, h("p", { class: "error-text" }, errorMessage(error))),
319
+ );
320
+ return {
321
+ element: h(
322
+ "div",
323
+ { class: "page" },
324
+ pageHeader(
325
+ "Environment",
326
+ "The variables the PLC's program and the line's server read. tsplc deploy builds with them, over the values in tsplc.config.ts.",
327
+ app.can("deployer")
328
+ ? h(
329
+ "button",
330
+ { class: "button", onclick: () => void restart() },
331
+ "Restart server",
332
+ )
333
+ : null,
334
+ admin
335
+ ? h(
336
+ "button",
337
+ { class: "button primary", onclick: () => void set(null) },
338
+ "Add variable",
339
+ )
340
+ : null,
341
+ ),
342
+ holder,
343
+ ),
344
+ };
345
+ };
@@ -0,0 +1,124 @@
1
+ import { formatAge, formatDuration } from "@tsplc/debug/format";
2
+ import type {
3
+ DeploymentMode,
4
+ DeploymentRecord,
5
+ DeploymentState,
6
+ GitSource,
7
+ } from "../../protocol";
8
+ import { contract } from "./contract";
9
+ import type { Tone } from "./dom";
10
+
11
+ export type Phase = DeploymentRecord["phases"][number];
12
+ export type PhaseName = Phase["name"];
13
+
14
+ export const isFinished = (state: DeploymentState) =>
15
+ contract.finalStates.includes(state);
16
+
17
+ /** A deployment can still be canceled: it hasn't started changing the controller. */
18
+ export const cancelable = (state: DeploymentState) =>
19
+ contract.cancelableStates.includes(state);
20
+
21
+ export const states: Record<DeploymentState, { label: string; tone: Tone }> = {
22
+ queued: { label: "Queued", tone: "idle" },
23
+ building: { label: "Building", tone: "active" },
24
+ awaitingApproval: { label: "Awaiting approval", tone: "waiting" },
25
+ applying: { label: "Applying", tone: "active" },
26
+ starting: { label: "Starting", tone: "active" },
27
+ verifying: { label: "Verifying", tone: "active" },
28
+ ready: { label: "Ready", tone: "ok" },
29
+ error: { label: "Error", tone: "error" },
30
+ canceled: { label: "Canceled", tone: "idle" },
31
+ };
32
+
33
+ export const phaseLabels: Record<PhaseName, string> = {
34
+ queue: "Queue",
35
+ build: "Build",
36
+ review: "Review",
37
+ apply: "Apply",
38
+ server: "Server",
39
+ health: "Health check",
40
+ };
41
+
42
+ export const modeLabels: Record<DeploymentMode, string> = {
43
+ apply: "Apply",
44
+ review: "Review",
45
+ };
46
+
47
+ export const operationLabels: Record<DeploymentRecord["operation"], string> = {
48
+ download: "Full download",
49
+ "online-change": "Online change",
50
+ };
51
+
52
+ const hour = 3_600_000;
53
+ const day = 86_400_000;
54
+
55
+ /** A length of time: the debugger's durations within an hour, then hours and minutes, since approval can wait for days. */
56
+ export const formatSpan = (ms: number) =>
57
+ ms < hour
58
+ ? formatDuration(ms)
59
+ : `${Math.floor(ms / hour)} h ${Math.floor((ms % hour) / 60_000)} min`;
60
+
61
+ /** How long before `now` `iso` was: the debugger's ages within a day, then days. A clock ahead of the browser's reads as now. */
62
+ export const formatAgo = (iso: string, now: number) => {
63
+ const elapsed = Math.max(0, now - Date.parse(iso));
64
+ return elapsed < day
65
+ ? formatAge(elapsed)
66
+ : `${Math.floor(elapsed / day)} d ago`;
67
+ };
68
+
69
+ /** A phase's length so far: to `now` while it runs. */
70
+ export const phaseDuration = (phase: Phase, now: number) =>
71
+ (phase.finishedAt === null ? now : Date.parse(phase.finishedAt)) -
72
+ Date.parse(phase.startedAt);
73
+
74
+ /**
75
+ * How long a deployment took, from its creation, when its queue phase starts, to the end of its
76
+ * last phase, or to `now` while it hasn't finished.
77
+ */
78
+ export const deploymentDuration = (record: DeploymentRecord, now: number) => {
79
+ const end = isFinished(record.state)
80
+ ? Math.max(
81
+ ...record.phases.map((phase) =>
82
+ Date.parse(phase.finishedAt ?? phase.startedAt),
83
+ ),
84
+ )
85
+ : now;
86
+ return Math.max(0, end - Date.parse(record.createdAt));
87
+ };
88
+
89
+ export const formatDeploymentDuration = (
90
+ record: DeploymentRecord,
91
+ now: number,
92
+ ) => formatSpan(deploymentDuration(record, now));
93
+
94
+ export const shortId = (id: string) => id.replace(/^dpl_/, "").slice(0, 9);
95
+
96
+ export const shortRelease = (release: string) => release.slice(0, 12);
97
+
98
+ export const shortCommit = (git: GitSource) => git.commit.slice(0, 7);
99
+
100
+ /** Who ran a command from where: `user@host`, or whichever of them is known. */
101
+ export const userAtHost = (machine: {
102
+ user?: string | null;
103
+ host?: string | null;
104
+ }) => [machine.user, machine.host].filter(Boolean).join("@");
105
+
106
+ /** A path whose segments are each encoded, for a URL. */
107
+ export const encodePath = (path: string) =>
108
+ path.split("/").map(encodeURIComponent).join("/");
109
+
110
+ export const formatTimestamp = (iso: string) =>
111
+ new Date(iso).toLocaleString(undefined, {
112
+ dateStyle: "medium",
113
+ timeStyle: "medium",
114
+ });
115
+
116
+ export const formatSize = (bytes: number) => {
117
+ if (bytes < 1000) {
118
+ return `${bytes} B`;
119
+ }
120
+ if (bytes < 1_000_000) {
121
+ return `${(bytes / 1000).toFixed(1)} kB`;
122
+ }
123
+ return `${(bytes / 1_000_000).toFixed(1)} MB`;
124
+ };
@@ -0,0 +1,126 @@
1
+ import { formatClock } from "@tsplc/debug/format";
2
+ import type { DeploymentLogLine } from "../../protocol";
3
+ import { empty, fill, h } from "./dom";
4
+ import { type PhaseName, phaseLabels } from "./format";
5
+
6
+ const allPhases = "all";
7
+
8
+ /**
9
+ * A deployment's log: lines coloured by level, filtered by phase and text, and kept scrolled to
10
+ * the newest line while following.
11
+ */
12
+ export const logViewer = (lines: readonly DeploymentLogLine[]) => {
13
+ const phase = h("select", { class: "input", "aria-label": "Phase" });
14
+ const search = h("input", {
15
+ class: "input search",
16
+ type: "search",
17
+ placeholder: "Search the log…",
18
+ });
19
+ const follow = h("input", { type: "checkbox", checked: true });
20
+ const count = h("span", { class: "muted mono count" });
21
+ const output = h("div", { class: "log", tabindex: 0 });
22
+ const shown: DeploymentLogLine[] = [];
23
+
24
+ const matches = (line: DeploymentLogLine) => {
25
+ const text = search.value.trim().toLowerCase();
26
+ return (
27
+ (phase.value === allPhases || line.phase === phase.value) &&
28
+ (!text || line.message.toLowerCase().includes(text))
29
+ );
30
+ };
31
+
32
+ const lineElement = (line: DeploymentLogLine) =>
33
+ h(
34
+ "div",
35
+ { class: `log-line l-${line.level}` },
36
+ h("span", { class: "log-seq" }, String(line.seq)),
37
+ h("time", { class: "log-time", title: line.at }, formatClock(line.at)),
38
+ h(
39
+ "span",
40
+ { class: "log-phase" },
41
+ line.phase ? phaseLabels[line.phase] : "",
42
+ ),
43
+ h("span", { class: "log-message" }, line.message),
44
+ );
45
+
46
+ const phasesSeen = () => [
47
+ ...new Set(lines.flatMap((line) => (line.phase ? [line.phase] : []))),
48
+ ];
49
+
50
+ const renderPhases = () => {
51
+ const selected = phase.value || allPhases;
52
+ const seen: PhaseName[] = phasesSeen();
53
+ if (phase.options.length === seen.length + 1) {
54
+ return;
55
+ }
56
+ fill(
57
+ phase,
58
+ h("option", { value: allPhases }, "All phases"),
59
+ ...seen.map((name) => h("option", { value: name }, phaseLabels[name])),
60
+ );
61
+ phase.value = selected;
62
+ };
63
+
64
+ const updateCount = () => {
65
+ count.textContent =
66
+ shown.length === lines.length
67
+ ? `${lines.length} lines`
68
+ : `${shown.length} of ${lines.length} lines`;
69
+ };
70
+
71
+ const scrollToEnd = () => {
72
+ if (follow.checked) {
73
+ output.scrollTop = output.scrollHeight;
74
+ }
75
+ };
76
+
77
+ const render = () => {
78
+ shown.splice(0, shown.length, ...lines.filter(matches));
79
+ fill(
80
+ output,
81
+ ...(shown.length
82
+ ? shown.map(lineElement)
83
+ : [empty(lines.length ? "No line matches." : "No log lines yet.")]),
84
+ );
85
+ updateCount();
86
+ scrollToEnd();
87
+ };
88
+
89
+ output.addEventListener("scroll", () => {
90
+ follow.checked =
91
+ output.scrollHeight - output.scrollTop - output.clientHeight < 24;
92
+ });
93
+ phase.addEventListener("change", render);
94
+ search.addEventListener("input", render);
95
+ follow.addEventListener("change", scrollToEnd);
96
+ renderPhases();
97
+ render();
98
+
99
+ return {
100
+ element: h(
101
+ "div",
102
+ { class: "log-viewer" },
103
+ h(
104
+ "div",
105
+ { class: "toolbar" },
106
+ search,
107
+ phase,
108
+ h("label", { class: "check" }, follow, "Follow"),
109
+ count,
110
+ ),
111
+ output,
112
+ ),
113
+ /** Shows lines added to `lines` since the last call. */
114
+ added: (added: readonly DeploymentLogLine[]) => {
115
+ renderPhases();
116
+ const matching = added.filter(matches);
117
+ if (matching.length && shown.length === 0) {
118
+ output.replaceChildren();
119
+ }
120
+ shown.push(...matching);
121
+ output.append(...matching.map(lineElement));
122
+ updateCount();
123
+ scrollToEnd();
124
+ },
125
+ };
126
+ };
@@ -0,0 +1,88 @@
1
+ import { errorMessage } from "../../errors";
2
+ import { accessView } from "./access";
3
+ import { ApiError, api } from "./api";
4
+ import { type App, createApp } from "./app";
5
+ import { auditView } from "./audit";
6
+ import { contract, type PagePath } from "./contract";
7
+ import { deploymentView } from "./deployment";
8
+ import { deploymentsView } from "./deployments";
9
+ import { h, type View } from "./dom";
10
+ import { environmentView } from "./environment";
11
+ import { shell, signInForm } from "./shell";
12
+
13
+ type Page = View & { navigate?(pathname: string): boolean };
14
+
15
+ const views: Record<PagePath, (app: App) => Page> = {
16
+ "/deployments": deploymentsView,
17
+ "/environment": environmentView,
18
+ "/audit": auditView,
19
+ "/access": accessView,
20
+ };
21
+
22
+ /** The page at `pathname`; the deployments list at `/` and any path the dashboard has no page for. */
23
+ const pageFor = (app: App, pathname: string): Page => {
24
+ if (pathname.startsWith(contract.deploymentPages)) {
25
+ return deploymentView(app, pathname);
26
+ }
27
+ const page =
28
+ contract.pages.find(({ path }) => path === pathname) ?? contract.pages[0];
29
+ return views[page.path](app);
30
+ };
31
+
32
+ const root = () => {
33
+ const element = document.getElementById("app");
34
+ if (!element) {
35
+ throw new Error("The page has no #app element");
36
+ }
37
+ return element;
38
+ };
39
+
40
+ const start = async () => {
41
+ const identity = await api.session().catch((error: unknown) => {
42
+ if (error instanceof ApiError && error.status === 401) {
43
+ return null;
44
+ }
45
+ throw error;
46
+ });
47
+ if (!identity) {
48
+ root().replaceChildren(signInForm(() => void start()));
49
+ return;
50
+ }
51
+ let page: Page | null = null;
52
+ const main = h("div", { class: "content" });
53
+ const show = (pathname: string) => {
54
+ top.setActive(pathname);
55
+ if (page?.navigate?.(pathname)) {
56
+ return;
57
+ }
58
+ page?.dispose?.();
59
+ page = pageFor(app, pathname);
60
+ main.replaceChildren(page.element);
61
+ scrollTo(0, 0);
62
+ };
63
+ const app = createApp(identity, (path) => {
64
+ if (path !== location.pathname) {
65
+ history.pushState(null, "", path);
66
+ }
67
+ show(path);
68
+ });
69
+ const top = shell(app);
70
+ root().replaceChildren(top.element, main);
71
+ addEventListener("popstate", () => show(location.pathname));
72
+ show(location.pathname);
73
+ };
74
+
75
+ start().catch((error: unknown) =>
76
+ root().replaceChildren(
77
+ h(
78
+ "div",
79
+ { class: "sign-in" },
80
+ h(
81
+ "div",
82
+ { class: "card" },
83
+ h("h1", {}, "The dashboard could not start"),
84
+ h("p", { class: "error-text" }, errorMessage(error)),
85
+ ),
86
+ ),
87
+ ),
88
+ );