@yunuseon/kayra 0.16.1 → 0.17.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/ansible/roles/platform/tasks/main.yml +31 -0
- package/cli/dist/browser/assets/{index-3W_NFATj.css → index-Ct0Eudk4.css} +1 -1
- package/cli/dist/browser/assets/index-hcyM6f6T.js +7 -0
- package/cli/dist/browser/assets/xterm-CerOhKYV.js +16 -0
- package/cli/dist/browser/index.html +2 -2
- package/cli/dist/clients/api/api.js +189 -0
- package/cli/dist/clients/api/auth.js +37 -0
- package/cli/dist/clients/api/commands.js +63 -0
- package/cli/dist/clients/api/contract.gen.js +1 -0
- package/cli/dist/clients/api/contract.js +91 -0
- package/cli/dist/clients/api/directories.js +20 -0
- package/cli/dist/clients/api/discovery.js +43 -0
- package/cli/dist/clients/api/live.js +40 -0
- package/cli/dist/clients/api/protocol.js +68 -0
- package/cli/dist/clients/api/queries.js +20 -0
- package/cli/dist/{web → clients/api}/runs.js +14 -11
- package/cli/dist/clients/api/start.js +97 -0
- package/cli/dist/clients/api/status.js +29 -0
- package/cli/dist/clients/api/validate.js +13 -0
- package/cli/dist/{ui → clients/cli}/explain.js +10 -8
- package/cli/dist/clients/cli/framed.js +67 -0
- package/cli/dist/clients/cli/invocation.js +84 -0
- package/cli/dist/clients/cli/paint.js +23 -0
- package/cli/dist/{cli.js → clients/cli/parser.js} +38 -32
- package/cli/dist/clients/cli/questions.js +89 -0
- package/cli/dist/clients/cli/status.js +75 -0
- package/cli/dist/{ui → clients/cli}/terminal.js +5 -15
- package/cli/dist/{ui → clients/cli}/text.js +15 -24
- package/cli/dist/clients/cli/validate.js +32 -0
- package/cli/dist/clients/cli/values.js +19 -0
- package/cli/dist/{ui → clients/cli}/views.js +28 -60
- package/cli/dist/clients/ui/assets.js +36 -0
- package/cli/dist/core/adapters/fs.js +18 -0
- package/cli/dist/{net.js → core/adapters/network.js} +20 -5
- package/cli/dist/core/adapters/opentofu.js +24 -0
- package/cli/dist/core/ctl/answers.js +32 -0
- package/cli/dist/core/fleet/brand.js +45 -0
- package/cli/dist/{schemas.js → core/fleet/docs.js} +4 -3
- package/cli/dist/core/fleet/load.js +44 -0
- package/cli/dist/core/fleet/model.js +1 -0
- package/cli/dist/{fleet.js → core/fleet/parse.js} +61 -41
- package/cli/dist/{settings.js → core/fleet/settings.js} +10 -3
- package/cli/dist/{validate.js → core/fleet/shape.js} +6 -5
- package/cli/dist/core/interpreter/events.js +81 -0
- package/cli/dist/core/interpreter/io.js +18 -0
- package/cli/dist/core/interpreter/loop.js +101 -0
- package/cli/dist/core/interpreter/needs.js +47 -0
- package/cli/dist/core/interpreter/process.js +107 -0
- package/cli/dist/core/interpreter/progress.js +15 -0
- package/cli/dist/core/interpreter/pty.js +8 -0
- package/cli/dist/core/operations/catalog.js +169 -0
- package/cli/dist/core/operations/dispatch.js +142 -0
- package/cli/dist/{plan.js → core/plan/describe.js} +13 -16
- package/cli/dist/core/plan/model.js +14 -0
- package/cli/dist/{commands → core/recipes}/app-check.js +11 -16
- package/cli/dist/core/recipes/apps.js +63 -0
- package/cli/dist/core/recipes/backup.js +34 -0
- package/cli/dist/core/recipes/certs.js +4 -0
- package/cli/dist/{commands → core/recipes}/doctor.js +20 -35
- package/cli/dist/core/recipes/host.js +104 -0
- package/cli/dist/core/recipes/ssh.js +20 -0
- package/cli/dist/core/recipes/steps.js +82 -0
- package/cli/dist/core/status/look.js +55 -0
- package/cli/dist/core/status/model.js +6 -0
- package/cli/dist/core/status/ports.js +1 -0
- package/cli/dist/core/status/updates.js +13 -0
- package/cli/dist/core/text/plural.js +2 -0
- package/cli/dist/core/text/spans.js +22 -0
- package/cli/dist/core/text/time.js +12 -0
- package/cli/dist/core/validation/facts.js +49 -0
- package/cli/dist/{commands/validate.js → core/validation/findings.js} +31 -66
- package/cli/dist/deployer/app.js +2 -1
- package/cli/dist/deployer/{builder.js → build/builder.js} +14 -13
- package/cli/dist/deployer/{bundle.js → build/bundle.js} +8 -7
- package/cli/dist/deployer/{compose.js → build/compose.js} +8 -7
- package/cli/dist/deployer/cron.js +2 -2
- package/cli/dist/deployer/{answers.js → ctl/answers.js} +5 -4
- package/cli/dist/deployer/{ctl.js → ctl/ctl.js} +3 -3
- package/cli/dist/deployer/deployer.js +23 -22
- package/cli/dist/deployer/{forge.js → forges/forge.js} +2 -1
- package/cli/dist/deployer/{forgejo.js → forges/forgejo.js} +2 -2
- package/cli/dist/deployer/{github.js → forges/github.js} +2 -2
- package/cli/dist/deployer/{gitlab.js → forges/gitlab.js} +2 -2
- package/cli/dist/deployer/{github-issues.js → forges/issues.js} +5 -4
- package/cli/dist/deployer/{notify.js → forges/notify.js} +9 -8
- package/cli/dist/deployer/{http.js → http/http.js} +1 -0
- package/cli/dist/deployer/{page.js → http/page.js} +1 -1
- package/cli/dist/deployer/{webhook.js → http/webhook.js} +2 -1
- package/cli/dist/deployer/main.js +2 -2
- package/cli/dist/deployer/{queue.js → runs/queue.js} +4 -3
- package/cli/dist/deployer/{records.js → runs/records.js} +9 -8
- package/cli/dist/deployer/{run.js → runs/run.js} +10 -9
- package/cli/dist/deployer/{store.js → runs/store.js} +9 -8
- package/cli/dist/main.js +98 -99
- package/cli/dist/result.js +11 -1
- package/cli/dist/serve.js +77 -0
- package/cli/dist/typed.js +2 -0
- package/package.json +4 -2
- package/scripts/agent/guard.sh +9 -2
- package/scripts/local/packed-runs.sh +20 -5
- package/scripts/local/setup-hosts.sh +9 -2
- package/cli/dist/brand.js +0 -39
- package/cli/dist/browser/assets/index-DRFX9Q77.js +0 -2
- package/cli/dist/commands/index.js +0 -52
- package/cli/dist/commands/server.js +0 -289
- package/cli/dist/commands/status.js +0 -194
- package/cli/dist/gather.js +0 -61
- package/cli/dist/interpret.js +0 -141
- package/cli/dist/load.js +0 -64
- package/cli/dist/ui/line.js +0 -39
- package/cli/dist/ui/progress.js +0 -144
- package/cli/dist/web/auth.js +0 -36
- package/cli/dist/web/commands.js +0 -102
- package/cli/dist/web/contract.js +0 -7
- package/cli/dist/web/server.js +0 -336
- /package/cli/dist/{web → clients/ui}/opener.js +0 -0
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
<meta name="color-scheme" content="light dark" />
|
|
7
7
|
<title>kayra</title>
|
|
8
8
|
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%235b5bd6'/%3E%3Cpath d='M11 8v16M11 16l9-8M14 13l7 11' stroke='white' stroke-width='3' stroke-linecap='round' fill='none'/%3E%3C/svg%3E" />
|
|
9
|
-
<script type="module" crossorigin src="/assets/index-
|
|
10
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
9
|
+
<script type="module" crossorigin src="/assets/index-hcyM6f6T.js"></script>
|
|
10
|
+
<link rel="stylesheet" crossorigin href="/assets/index-Ct0Eudk4.css">
|
|
11
11
|
</head>
|
|
12
12
|
<body>
|
|
13
13
|
<div id="app"></div>
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { sep } from "node:path";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { within } from "../../core/fleet/brand.js";
|
|
4
|
+
import { opentofu } from "../../core/adapters/opentofu.js";
|
|
5
|
+
import { isOperation, operation } from "../../core/operations/catalog.js";
|
|
6
|
+
import { contextFor, invocation, isQuery, isStream, stream } from "../../core/operations/dispatch.js";
|
|
7
|
+
import { follow } from "../../core/status/updates.js";
|
|
8
|
+
import { json, send } from "../../deployer/http/http.js";
|
|
9
|
+
import { facts } from "./commands.js";
|
|
10
|
+
import { catalog, openapi } from "./contract.js";
|
|
11
|
+
import { directories } from "./directories.js";
|
|
12
|
+
import { inFlight, liveRuns } from "./live.js";
|
|
13
|
+
import { options, requestBody } from "./protocol.js";
|
|
14
|
+
import { answer as queryAnswer } from "./queries.js";
|
|
15
|
+
import { stateOf, summary } from "./runs.js";
|
|
16
|
+
import { allRuns, preview, start } from "./start.js";
|
|
17
|
+
import { statusJson } from "./status.js";
|
|
18
|
+
const answerJson = (response, status, value) => {
|
|
19
|
+
send(response, status, JSON.stringify(value), "application/json; charset=utf-8");
|
|
20
|
+
};
|
|
21
|
+
const events = (response, ndjson = false) => {
|
|
22
|
+
response.writeHead(200, { "Content-Type": ndjson ? "application/x-ndjson" : "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" });
|
|
23
|
+
return {
|
|
24
|
+
say: (value) => { if (!response.destroyed)
|
|
25
|
+
response.write(ndjson ? `${JSON.stringify(value)}\n` : `data: ${JSON.stringify(value)}\n\n`); },
|
|
26
|
+
end: () => { response.end(ndjson ? "" : "event: end\ndata: {}\n\n"); },
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
/** A run's events as they come, after those it has had: until it ends, or the client goes. */
|
|
30
|
+
const watch = (served, id, response, ndjson, session = false) => {
|
|
31
|
+
const live = served.runs.get(id);
|
|
32
|
+
const run = live?.run ?? allRuns(served).find((each) => each.id === id);
|
|
33
|
+
if (run === undefined || (session && !run.session)) {
|
|
34
|
+
send(response, 404, "no run or session\n");
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const { say, end } = events(response, ndjson);
|
|
38
|
+
run.events.forEach(say);
|
|
39
|
+
if (live === undefined || stateOf(run.events) !== "running") {
|
|
40
|
+
end();
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const listener = (event) => { say(event); if (event.kind === "ended")
|
|
44
|
+
end(); };
|
|
45
|
+
served.runs.swap(id, (current) => ({ ...current, listeners: [...current.listeners, listener] }));
|
|
46
|
+
response.on("close", () => { served.runs.swap(id, (current) => ({ ...current, listeners: current.listeners.filter((each) => each !== listener) })); });
|
|
47
|
+
};
|
|
48
|
+
/** POST /api/operations/<name>[/preview]: a plan previewed or started, a session started, a query answered, a stream followed. */
|
|
49
|
+
const operate = async (served, request, response, named, previewing, ndjson) => {
|
|
50
|
+
const name = decodeURIComponent(named);
|
|
51
|
+
if (!isOperation(name)) {
|
|
52
|
+
send(response, 404, "no such operation\n");
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const body = requestBody.safeParse(await json(request));
|
|
56
|
+
if (!body.success) {
|
|
57
|
+
send(response, 400, "expected {input, options?, confirm?}\n");
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const call = invocation(name, body.data.input);
|
|
61
|
+
const settings = options.parse(body.data.options ?? {});
|
|
62
|
+
if (!call.ok) {
|
|
63
|
+
send(response, 400, `${call.error}\n`);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const kind = operation(call.value.name).kind;
|
|
67
|
+
if (previewing || settings.dryRun) {
|
|
68
|
+
const shown = preview(served, call.value, settings);
|
|
69
|
+
if (shown.ok)
|
|
70
|
+
answerJson(response, 200, shown.value);
|
|
71
|
+
else
|
|
72
|
+
send(response, 400, `${shown.error}\n`);
|
|
73
|
+
}
|
|
74
|
+
else if (kind === "plan" || kind === "session") {
|
|
75
|
+
const started = start(served, call.value, settings, body.data.confirm);
|
|
76
|
+
if (!started.ok)
|
|
77
|
+
send(response, started.error[0], `${started.error[1]}\n`);
|
|
78
|
+
else
|
|
79
|
+
answerJson(response, kind === "session" ? 201 : 202, { [kind === "session" ? "session" : "run"]: started.value });
|
|
80
|
+
}
|
|
81
|
+
else if (isStream(call.value)) {
|
|
82
|
+
const { initial, updates } = stream(served.context, call.value.name, call.value.input);
|
|
83
|
+
const sink = events(response, ndjson);
|
|
84
|
+
await follow(initial, updates, (looks) => { const value = statusJson(looks); sink.say(value); });
|
|
85
|
+
sink.end();
|
|
86
|
+
}
|
|
87
|
+
else if (isQuery(call.value)) {
|
|
88
|
+
const result = await queryAnswer(served.context, call.value.name, call.value.input);
|
|
89
|
+
if (result.ok)
|
|
90
|
+
answerJson(response, 200, result.value);
|
|
91
|
+
else
|
|
92
|
+
send(response, call.value.name === "validate" ? 400 : 502, `${result.error}\n`);
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
/** /api/runs/<id>[/events|answers|cancel] and /api/sessions/<id>[/output|input]: follow, answer, stop. */
|
|
96
|
+
const steer = async (served, request, response, id, action, session, ndjson) => {
|
|
97
|
+
const method = request.method ?? "GET";
|
|
98
|
+
const live = served.runs.get(id);
|
|
99
|
+
if (session && live?.run.session !== true && !allRuns(served).some((each) => each.id === id && each.session)) {
|
|
100
|
+
send(response, 404, "no session\n");
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (method === "GET" && (action === "events" || action === "output"))
|
|
104
|
+
watch(served, id, response, ndjson, session);
|
|
105
|
+
else if (method === "GET" && action === undefined && !session) {
|
|
106
|
+
const run = allRuns(served).find((each) => each.id === id);
|
|
107
|
+
if (run === undefined)
|
|
108
|
+
send(response, 404, "no run\n");
|
|
109
|
+
else {
|
|
110
|
+
const value = { ...summary(run), events: run.events };
|
|
111
|
+
answerJson(response, 200, value);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
else if (((method === "POST" && action === "cancel") || (session && method === "DELETE" && action === undefined)) && live !== undefined && stateOf(live.run.events) === "running") {
|
|
115
|
+
live.stop.abort();
|
|
116
|
+
send(response, 204, "");
|
|
117
|
+
}
|
|
118
|
+
else if (method === "POST" && (action === "answers" || action === "input")) {
|
|
119
|
+
const deliver = action === "answers" ? live?.answer : session ? live?.input : undefined;
|
|
120
|
+
if (deliver === undefined || live?.stop.signal.aborted === true) {
|
|
121
|
+
send(response, 404, "nothing waiting for input\n");
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const body = z.strictObject({ text: z.string() }).safeParse(await json(request));
|
|
125
|
+
if (!body.success)
|
|
126
|
+
send(response, 400, "expected {text: string}\n");
|
|
127
|
+
else {
|
|
128
|
+
deliver(body.data.text);
|
|
129
|
+
send(response, 204, "");
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
else
|
|
133
|
+
send(response, 404, "no active resource\n");
|
|
134
|
+
};
|
|
135
|
+
/** The API of one listener: its requests routed, and a stop that waits for runs and requests to end. */
|
|
136
|
+
export const createApi = (api) => {
|
|
137
|
+
const shutdown = new AbortController();
|
|
138
|
+
const served = {
|
|
139
|
+
api,
|
|
140
|
+
context: contextFor({ kayra: api.kayra, fleet: api.fleet, version: api.version, here: api.fleet.root, network: api.network, tofu: api.tofu ?? opentofu, signal: shutdown.signal }),
|
|
141
|
+
runs: liveRuns(),
|
|
142
|
+
dir: within(api.fleet.root, ".cache", "ui", "runs"),
|
|
143
|
+
shutdown,
|
|
144
|
+
};
|
|
145
|
+
const requests = inFlight();
|
|
146
|
+
const route = async (request, response, url) => {
|
|
147
|
+
const method = request.method ?? "GET";
|
|
148
|
+
const path = url.pathname;
|
|
149
|
+
const named = /^\/api\/operations\/([^/]+)(\/preview)?$/.exec(path);
|
|
150
|
+
const runPath = /^\/api\/runs\/([^/]+)(?:\/(events|answers|cancel))?$/.exec(path);
|
|
151
|
+
const sessionPath = /^\/api\/sessions\/([^/]+)(?:\/(output|input))?$/.exec(path);
|
|
152
|
+
const ndjson = request.headers.accept?.includes("application/x-ndjson") === true;
|
|
153
|
+
if (method === "GET" && path === "/api/operations")
|
|
154
|
+
answerJson(response, 200, catalog());
|
|
155
|
+
else if (method === "GET" && path === "/api/openapi.json")
|
|
156
|
+
answerJson(response, 200, openapi(api.version));
|
|
157
|
+
else if (method === "GET" && path === "/api/directories") {
|
|
158
|
+
const result = await directories(url.searchParams.get("path") ?? ".", api.fleet.root);
|
|
159
|
+
if (result.ok)
|
|
160
|
+
answerJson(response, 200, result.value);
|
|
161
|
+
else
|
|
162
|
+
send(response, 400, `${result.error}\n`);
|
|
163
|
+
}
|
|
164
|
+
else if (method === "GET" && path === "/api/fleet") {
|
|
165
|
+
const factsOfFleet = { fleet: api.fleet.root.split(sep).at(-1) ?? "", version: api.version, servers: api.fleet.servers.map(facts) };
|
|
166
|
+
answerJson(response, 200, factsOfFleet);
|
|
167
|
+
}
|
|
168
|
+
else if (method === "POST" && named !== null)
|
|
169
|
+
await operate(served, request, response, named[1] ?? "", named[2] !== undefined, ndjson);
|
|
170
|
+
else if (method === "GET" && path === "/api/runs") {
|
|
171
|
+
const runs = allRuns(served).map(summary);
|
|
172
|
+
answerJson(response, 200, runs);
|
|
173
|
+
}
|
|
174
|
+
else if (runPath !== null || sessionPath !== null) {
|
|
175
|
+
const [, id = "", action] = runPath ?? sessionPath ?? [];
|
|
176
|
+
await steer(served, request, response, id, action, sessionPath !== null, ndjson);
|
|
177
|
+
}
|
|
178
|
+
else
|
|
179
|
+
send(response, 404, "not found\n");
|
|
180
|
+
};
|
|
181
|
+
return {
|
|
182
|
+
handle: (request, response, url) => requests.track(route(request, response, url)),
|
|
183
|
+
stop: async () => {
|
|
184
|
+
shutdown.abort();
|
|
185
|
+
served.runs.all().forEach((live) => { live.stop.abort(); });
|
|
186
|
+
await Promise.allSettled([requests.settled(), ...served.runs.all().map((live) => live.done)]);
|
|
187
|
+
},
|
|
188
|
+
};
|
|
189
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { typed } from "../../typed.js";
|
|
3
|
+
/** Cookies are shared by every port of a host: the name carries the port, so another local server's cookie is not ours. */
|
|
4
|
+
export const cookieName = (port) => `kayra_ui_${String(port)}`;
|
|
5
|
+
const origins = (port) => typed([`127.0.0.1:${String(port)}`, `localhost:${String(port)}`]);
|
|
6
|
+
const same = (a, b) => {
|
|
7
|
+
const left = Buffer.from(a);
|
|
8
|
+
const right = Buffer.from(b);
|
|
9
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
10
|
+
};
|
|
11
|
+
const cookieValue = (header, name) => header
|
|
12
|
+
?.split(";")
|
|
13
|
+
.map((pair) => Object.freeze(pair.trim().split("=")))
|
|
14
|
+
.find(([key]) => key === name)?.[1];
|
|
15
|
+
const refuse = (status, why) => typed({ admitted: false, status, why });
|
|
16
|
+
/** Host always, the launch token on API calls, and the exact Origin on cookie writes. */
|
|
17
|
+
export const admit = (asked, port, token, enabled = { ui: true, api: false }) => {
|
|
18
|
+
if (asked.host === undefined || !origins(port).some((origin) => origin === asked.host))
|
|
19
|
+
return refuse(403, "not this listener's host");
|
|
20
|
+
if (asked.authorization !== undefined) {
|
|
21
|
+
const bearer = asked.authorization.startsWith("Bearer ") ? asked.authorization.slice(7) : "";
|
|
22
|
+
return enabled.api && same(bearer, token) ? typed({ admitted: true }) : refuse(401, "invalid bearer token");
|
|
23
|
+
}
|
|
24
|
+
const writes = asked.method !== "GET" && asked.method !== "HEAD";
|
|
25
|
+
// Cookie credentials are ambient: the request must originate at the host it names.
|
|
26
|
+
if (writes && asked.origin !== `http://${asked.host}`)
|
|
27
|
+
return refuse(403, "not this listener's origin");
|
|
28
|
+
if (!asked.path.startsWith("/api/"))
|
|
29
|
+
return typed({ admitted: true });
|
|
30
|
+
const presented = cookieValue(asked.cookie, cookieName(port));
|
|
31
|
+
return enabled.ui && presented !== undefined && same(presented, token) ? typed({ admitted: true }) : refuse(401, "no token: open the URL kayra serve printed, or use its API token");
|
|
32
|
+
};
|
|
33
|
+
/** The token the opened URL carries, if it is this launch's. */
|
|
34
|
+
export const tokenIn = (query, token) => {
|
|
35
|
+
const given = query.get("token");
|
|
36
|
+
return given !== null && same(given, token);
|
|
37
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { typed } from "../../typed.js";
|
|
2
|
+
export const offered = (server) => typed([
|
|
3
|
+
...(server.kind === "platform" ? ["deploy", "apps", "verify"] : []),
|
|
4
|
+
"setup", "plan",
|
|
5
|
+
...(server.target === "multipass" && server.kind === "platform" ? ["up"] : []),
|
|
6
|
+
...(server.hasTerraform || server.buildsVm ? ["provision"] : []),
|
|
7
|
+
...(server.backupDir === undefined ? [] : ["backup.test"]),
|
|
8
|
+
...(server.kind === "platform" ? ["job"] : []),
|
|
9
|
+
...(server.target === "multipass" ? [] : ["adopt"]),
|
|
10
|
+
...(server.hasTerraform ? ["down"] : []),
|
|
11
|
+
]);
|
|
12
|
+
export const facts = (server) => typed({
|
|
13
|
+
name: server.name, kind: server.kind, target: server.target, domain: server.domain,
|
|
14
|
+
apps: server.apps.map((app) => app.name), commands: offered(server),
|
|
15
|
+
});
|
|
16
|
+
/** What follows the server and the app on the command line, by operation. */
|
|
17
|
+
const extra = (call) => {
|
|
18
|
+
switch (call.name) {
|
|
19
|
+
case "ssh.exec":
|
|
20
|
+
return ["--", ...call.input.command];
|
|
21
|
+
case "job":
|
|
22
|
+
return [call.input.job, ...(call.input.noPrs ? ["--no-prs"] : [])];
|
|
23
|
+
case "app.rollback":
|
|
24
|
+
return [call.input.sha];
|
|
25
|
+
case "app.deploy":
|
|
26
|
+
return call.input.ref === undefined ? [] : [call.input.ref];
|
|
27
|
+
case "app.log":
|
|
28
|
+
return call.input.run === undefined ? [] : [call.input.run];
|
|
29
|
+
case "app.check":
|
|
30
|
+
return [call.input.dir];
|
|
31
|
+
case "certs":
|
|
32
|
+
return [call.input.domain, ...call.input.subdomains];
|
|
33
|
+
case "up":
|
|
34
|
+
case "provision":
|
|
35
|
+
case "deploy":
|
|
36
|
+
case "setup":
|
|
37
|
+
case "plan":
|
|
38
|
+
case "verify":
|
|
39
|
+
case "apps":
|
|
40
|
+
case "hosts":
|
|
41
|
+
case "ssh":
|
|
42
|
+
case "down":
|
|
43
|
+
case "adopt":
|
|
44
|
+
case "backup.test":
|
|
45
|
+
case "app.purge":
|
|
46
|
+
case "app.runs":
|
|
47
|
+
case "app.releases":
|
|
48
|
+
case "status":
|
|
49
|
+
case "validate":
|
|
50
|
+
case "doctor":
|
|
51
|
+
case "version":
|
|
52
|
+
return [];
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
/** How the command line spells an operation where its words are not its name's. */
|
|
56
|
+
const spelled = { "ssh.exec": "ssh", "app.releases": "app rollback", "app.log": "app logs" };
|
|
57
|
+
/** The command's words, as typed on the command line. */
|
|
58
|
+
export const words = (call) => {
|
|
59
|
+
const { input } = call;
|
|
60
|
+
const scope = ["server" in input ? input.server : undefined, "app" in input ? input.app : undefined];
|
|
61
|
+
const name = spelled[call.name] ?? call.name.replaceAll(".", " ");
|
|
62
|
+
return ["kayra", name, ...scope, ...extra(call)].filter((word) => word !== undefined).join(" ");
|
|
63
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { operations, operationNames } from "../../core/operations/catalog.js";
|
|
3
|
+
import { options, schemas, querySchemas } from "./protocol.js";
|
|
4
|
+
import { typed } from "../../typed.js";
|
|
5
|
+
export const catalog = () => Object.freeze(operationNames.map((name) => {
|
|
6
|
+
const { summary, scope, effect, kind, input } = operations[name];
|
|
7
|
+
return { name, summary, scope, effect, kind, input: z.toJSONSchema(input, { io: "input" }) };
|
|
8
|
+
}));
|
|
9
|
+
const isObject = (value) => typeof value === "object" && value !== null;
|
|
10
|
+
const object = (value) => isObject(value) ? value : typed({});
|
|
11
|
+
const list = (value) => typed(Array.isArray(value) ? value : []);
|
|
12
|
+
const literal = (value) => JSON.stringify(value);
|
|
13
|
+
// Recursive: TypeScript cannot infer what it returns.
|
|
14
|
+
const typescript = (value) => {
|
|
15
|
+
const schema = object(value);
|
|
16
|
+
if ("const" in schema)
|
|
17
|
+
return literal(schema["const"]);
|
|
18
|
+
if (Array.isArray(schema["enum"]))
|
|
19
|
+
return schema["enum"].map(literal).join(" | ");
|
|
20
|
+
if (Array.isArray(schema["anyOf"]))
|
|
21
|
+
return schema["anyOf"].map(typescript).join(" | ");
|
|
22
|
+
if (Array.isArray(schema["oneOf"]))
|
|
23
|
+
return schema["oneOf"].map(typescript).join(" | ");
|
|
24
|
+
if (Array.isArray(schema["type"]))
|
|
25
|
+
return schema["type"].map((type) => typescript({ ...schema, type })).join(" | ");
|
|
26
|
+
switch (schema["type"]) {
|
|
27
|
+
case "null": return "null";
|
|
28
|
+
case "string": return "string";
|
|
29
|
+
case "integer":
|
|
30
|
+
case "number": return "number";
|
|
31
|
+
case "boolean": return "boolean";
|
|
32
|
+
case "array": return `readonly (${typescript(schema["items"])})[]`;
|
|
33
|
+
case "object": {
|
|
34
|
+
const properties = Object.entries(object(schema["properties"]));
|
|
35
|
+
const required = list(schema["required"]);
|
|
36
|
+
const fields = properties.map(([key, property]) => `readonly ${literal(key)}${required.includes(key) ? "" : "?"}: ${typescript(property)}`).join("; ");
|
|
37
|
+
if (properties.length === 0 && schema["additionalProperties"] === false)
|
|
38
|
+
return "Readonly<Record<string, never>>";
|
|
39
|
+
return properties.length === 0 ? `Readonly<Record<string, ${typescript(schema["additionalProperties"])}>>` : `{ ${fields} }`;
|
|
40
|
+
}
|
|
41
|
+
default: return "unknown";
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
export const contractTypes = () => [
|
|
45
|
+
"// Generated by npm run contract. The pinned kayra version defines this /api contract.",
|
|
46
|
+
...Object.entries(schemas).map(([name, schema]) => `export type ${name} = ${typescript(z.toJSONSchema(schema))};`),
|
|
47
|
+
`export type OperationInputs = { ${operationNames.map((name) => `readonly ${literal(name)}: ${typescript(z.toJSONSchema(operations[name].input, { io: "input" }))}`).join("; ")} };`,
|
|
48
|
+
'export type OperationName = keyof OperationInputs;',
|
|
49
|
+
'export type InputOf<N extends OperationName> = OperationInputs[N];',
|
|
50
|
+
'export type OperationCall = { readonly [N in OperationName]: { readonly name: N; readonly input: InputOf<N> } }[OperationName];',
|
|
51
|
+
`export type RunOptions = ${typescript(z.toJSONSchema(options, { io: "input" }))};`,
|
|
52
|
+
"",
|
|
53
|
+
].join("\n");
|
|
54
|
+
const response = (description, schema, media = "application/json") => ({ description, content: { [media]: { schema } } });
|
|
55
|
+
const ref = (name) => ({ $ref: `#/components/schemas/${name}` });
|
|
56
|
+
const isQueryName = (name) => Object.hasOwn(querySchemas, name);
|
|
57
|
+
const resultOf = (name) => isQueryName(name) ? z.toJSONSchema(querySchemas[name]) : {};
|
|
58
|
+
const request = (input) => ({ required: true, content: { "application/json": { schema: { type: "object", additionalProperties: false, properties: { input, options: z.toJSONSchema(options, { io: "input" }), confirm: { type: "string", description: "The real server's name, required before a change" } } } } } });
|
|
59
|
+
const id = { name: "id", in: "path", required: true, schema: { type: "string" } };
|
|
60
|
+
const body = (properties, required) => ({ required: true, content: { "application/json": { schema: { type: "object", properties, required, additionalProperties: false } } } });
|
|
61
|
+
const write = (description) => ({ description, responses: { "204": { description: "Accepted" }, "404": { description: "No active resource" } } });
|
|
62
|
+
export const openapi = (version) => ({
|
|
63
|
+
openapi: "3.1.0",
|
|
64
|
+
info: { title: "kayra local API", version, description: "127.0.0.1 only. Compatibility follows the fleet's pinned kayra version." },
|
|
65
|
+
servers: [{ url: "/api" }],
|
|
66
|
+
security: [{ bearer: [] }, { cookie: [] }],
|
|
67
|
+
paths: {
|
|
68
|
+
"/operations": { get: { responses: { "200": response("The operation catalog", { type: "array", items: ref("OperationInfo") }) } } },
|
|
69
|
+
"/openapi.json": { get: { responses: { "200": response("This OpenAPI document", { type: "object" }) } } },
|
|
70
|
+
"/fleet": { get: { responses: { "200": response("The fleet", ref("FleetFacts")) } } },
|
|
71
|
+
"/directories": { get: { summary: "Browse local directories for app.check", parameters: [{ name: "path", in: "query", schema: { type: "string", default: "." } }], responses: { "200": response("Directories only, relative paths resolved from the fleet", ref("DirectoryListing")), "400": { description: "Directory cannot be read" } } } },
|
|
72
|
+
...Object.fromEntries(catalog().flatMap(({ name, summary, kind, input }) => typed([
|
|
73
|
+
[`/operations/${name}`, { post: { summary, operationId: name, requestBody: request(input), responses: kind === "plan" || kind === "session" ? {
|
|
74
|
+
[kind === "session" ? "201" : "202"]: response("Started", { type: "object", properties: { [kind === "session" ? "session" : "run"]: { type: "string" } }, required: [kind === "session" ? "session" : "run"] }),
|
|
75
|
+
"200": response("Dry run", ref("Preview")), "400": { description: "Invalid input" }, "403": { description: "Real server not confirmed" }, "409": { description: "Server busy" },
|
|
76
|
+
} : { "200": response(summary, kind === "stream" ? ref("Status") : resultOf(name), kind === "stream" ? "text/event-stream" : "application/json") } } }],
|
|
77
|
+
...(kind === "plan" || kind === "session" ? [[`/operations/${name}/preview`, { post: { summary: `Preview: ${summary}`, requestBody: request(input), responses: { "200": response("Plan preview", ref("Preview")) } } }]] : []),
|
|
78
|
+
]))),
|
|
79
|
+
"/runs": { get: { responses: { "200": response("Runs from this fleet", { type: "array", items: ref("RunSummary") }) } } },
|
|
80
|
+
"/runs/{id}": { get: { parameters: [id], responses: { "200": response("A recorded run", ref("Run")), "404": { description: "No run" } } } },
|
|
81
|
+
"/runs/{id}/events": { get: { parameters: [id], responses: { "200": { description: "Events replayed from the start, then followed until the run ends", content: { "text/event-stream": { schema: ref("RunEvent") }, "application/x-ndjson": { schema: ref("RunEvent") } } } } } },
|
|
82
|
+
"/runs/{id}/answers": { post: { ...write("Answer the pending question; answers are never recorded"), parameters: [id], requestBody: body({ text: { type: "string" } }, ["text"]) } },
|
|
83
|
+
"/runs/{id}/cancel": { post: { ...write("Cancel a run"), parameters: [id] } },
|
|
84
|
+
"/sessions/{id}/output": { get: { parameters: [id], responses: { "200": response("Session events", ref("RunEvent"), "text/event-stream") } } },
|
|
85
|
+
"/sessions/{id}/input": { post: { ...write("Send terminal input; input is never recorded"), parameters: [id], requestBody: body({ text: { type: "string" } }, ["text"]) } },
|
|
86
|
+
"/sessions/{id}": { delete: { ...write("Close the session"), parameters: [id] } },
|
|
87
|
+
},
|
|
88
|
+
components: { securitySchemes: { bearer: { type: "http", scheme: "bearer" }, cookie: { type: "apiKey", in: "cookie", name: "kayra_ui_<port>", description: "The browser's per-port cookie, set by the launch URL" } }, schemas: Object.fromEntries(Object.entries(schemas).map(([name, schema]) => {
|
|
89
|
+
return [name, Object.fromEntries(Object.entries(z.toJSONSchema(schema)).filter(([key]) => key !== "$schema"))];
|
|
90
|
+
})) },
|
|
91
|
+
});
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { readdir, realpath, stat } from "node:fs/promises";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
import { err, ok } from "../../result.js";
|
|
4
|
+
export const directories = async (path, root) => {
|
|
5
|
+
try {
|
|
6
|
+
const absolute = await realpath(resolve(root, path));
|
|
7
|
+
const entries = await readdir(absolute, { withFileTypes: true });
|
|
8
|
+
const children = await Promise.all(entries.map(async (entry) => {
|
|
9
|
+
const path = resolve(absolute, entry.name);
|
|
10
|
+
const directory = entry.isDirectory() ||
|
|
11
|
+
(entry.isSymbolicLink() &&
|
|
12
|
+
(await stat(path).then((info) => info.isDirectory(), () => false)));
|
|
13
|
+
return directory ? [{ name: entry.name, path }] : [];
|
|
14
|
+
}));
|
|
15
|
+
return ok({ path: absolute, parent: dirname(absolute), directories: children.flat().toSorted((a, b) => a.name.localeCompare(b.name)) });
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return err("Cannot read that directory. Check its path and permissions.");
|
|
19
|
+
}
|
|
20
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { err, ok } from "../../result.js";
|
|
5
|
+
const entry = z.object({ url: z.string(), token: z.string(), pid: z.number().int().positive() });
|
|
6
|
+
const alive = (pid) => {
|
|
7
|
+
try {
|
|
8
|
+
process.kill(pid, 0);
|
|
9
|
+
return true;
|
|
10
|
+
}
|
|
11
|
+
catch (error) {
|
|
12
|
+
return !(error instanceof Error && "code" in error && error.code === "ESRCH");
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
export const discover = (file, url, token) => {
|
|
16
|
+
if (existsSync(file)) {
|
|
17
|
+
if (!lstatSync(file).isFile())
|
|
18
|
+
return err(`${file} is not a regular discovery file`);
|
|
19
|
+
try {
|
|
20
|
+
const previous = entry.safeParse(JSON.parse(readFileSync(file, "utf8")));
|
|
21
|
+
if (!previous.success)
|
|
22
|
+
return err(`${file} is unreadable; remove it before starting kayra serve`);
|
|
23
|
+
if (alive(previous.data.pid))
|
|
24
|
+
return err(`kayra serve is already discoverable for this fleet (pid ${String(previous.data.pid)})`);
|
|
25
|
+
unlinkSync(file);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return err(`${file} is unreadable; remove it before starting kayra serve`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const contents = `${JSON.stringify({ url, token, pid: process.pid })}\n`;
|
|
32
|
+
try {
|
|
33
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
34
|
+
writeFileSync(file, contents, { mode: 0o600, flag: "wx" });
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
return err(`${file} could not be written: ${error instanceof Error ? error.message : String(error)}`);
|
|
38
|
+
}
|
|
39
|
+
return ok({ remove: () => {
|
|
40
|
+
if (existsSync(file) && readFileSync(file, "utf8") === contents)
|
|
41
|
+
unlinkSync(file);
|
|
42
|
+
} });
|
|
43
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The runs of one listener, in one cell replaced whole: no launch shares
|
|
3
|
+
* locks, credentials or sessions with another.
|
|
4
|
+
*/
|
|
5
|
+
export const liveRuns = () => {
|
|
6
|
+
// eslint-disable-next-line functional/prefer-immutable-types -- the one state cell of this listener's runs
|
|
7
|
+
const cell = { runs: {} };
|
|
8
|
+
return {
|
|
9
|
+
get: (id) => cell.runs[id],
|
|
10
|
+
all: () => Object.values(cell.runs),
|
|
11
|
+
/** Installed before any asynchronous work: the run's lock. */
|
|
12
|
+
add: (id, live) => {
|
|
13
|
+
// eslint-disable-next-line functional/immutable-data -- replace the one state cell whole
|
|
14
|
+
cell.runs = { ...cell.runs, [id]: live };
|
|
15
|
+
},
|
|
16
|
+
swap: (id, change) => {
|
|
17
|
+
const current = cell.runs[id];
|
|
18
|
+
// eslint-disable-next-line functional/immutable-data -- replace the one state cell whole
|
|
19
|
+
if (current !== undefined)
|
|
20
|
+
cell.runs = { ...cell.runs, [id]: change(current) };
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
/** The requests in flight: shutdown waits for them as well as for the runs. */
|
|
25
|
+
export const inFlight = () => {
|
|
26
|
+
// eslint-disable-next-line functional/prefer-immutable-types -- the requests not yet answered
|
|
27
|
+
const cell = { pending: [] };
|
|
28
|
+
return {
|
|
29
|
+
track: (work) => {
|
|
30
|
+
const tracked = work.finally(() => {
|
|
31
|
+
// eslint-disable-next-line functional/immutable-data -- release it once its response completes
|
|
32
|
+
cell.pending = cell.pending.filter((pending) => pending !== tracked);
|
|
33
|
+
});
|
|
34
|
+
// eslint-disable-next-line functional/immutable-data -- one more request in flight
|
|
35
|
+
cell.pending = [...cell.pending, tracked];
|
|
36
|
+
return tracked;
|
|
37
|
+
},
|
|
38
|
+
settled: () => Promise.allSettled(cell.pending),
|
|
39
|
+
};
|
|
40
|
+
};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { effects, kinds, operationNames, scopes } from "../../core/operations/catalog.js";
|
|
3
|
+
import { serverKinds } from "../../core/fleet/settings.js";
|
|
4
|
+
import { serverTargets } from "../../core/fleet/model.js";
|
|
5
|
+
import { parts } from "../../core/plan/model.js";
|
|
6
|
+
import { stopReasons } from "../../core/interpreter/progress.js";
|
|
7
|
+
import { machineStates, reachStates } from "../../core/status/model.js";
|
|
8
|
+
import { tones } from "../../core/text/spans.js";
|
|
9
|
+
import { verdicts } from "../../core/validation/findings.js";
|
|
10
|
+
import { releasesSchema, runsSchema } from "../../core/ctl/answers.js";
|
|
11
|
+
const tone = z.enum(tones);
|
|
12
|
+
const span = z.union([z.string(), z.object({ tone: tone.exactOptional(), text: z.string(), href: z.string().exactOptional() })]);
|
|
13
|
+
const line = z.array(span);
|
|
14
|
+
const text = z.union([z.string(), line]);
|
|
15
|
+
const part = z.enum(parts);
|
|
16
|
+
const listed = z.object({ index: z.number().int(), kind: z.string(), title: z.string(), command: z.string().exactOptional(), part: part.exactOptional(), opens: part.exactOptional() });
|
|
17
|
+
const invocation = z.object({ command: z.string(), server: z.string().exactOptional(), about: z.array(z.string()) });
|
|
18
|
+
const stop = z.enum(stopReasons);
|
|
19
|
+
const state = z.enum(["running", "passed", "failed", "interrupted", "declined"]);
|
|
20
|
+
const summary = z.object({ id: z.string(), command: z.string(), server: z.string().exactOptional(), started: z.string(), state, session: z.boolean() });
|
|
21
|
+
const ended = z.object({ kind: z.literal("ended"), failures: z.number(), stop: z.object({ index: z.number(), why: stop }).exactOptional(), ms: z.number(), footer: z.array(line) });
|
|
22
|
+
const event = z.discriminatedUnion("kind", [
|
|
23
|
+
z.object({ kind: z.literal("plan"), invocation, steps: z.array(listed) }),
|
|
24
|
+
z.object({ kind: z.literal("started"), index: z.number() }),
|
|
25
|
+
z.object({ kind: z.literal("done"), index: z.number(), failed: z.boolean(), stopped: z.boolean(), why: z.string().exactOptional(), ms: z.number() }),
|
|
26
|
+
ended,
|
|
27
|
+
z.object({ kind: z.literal("output"), stream: z.enum(["stdout", "stderr"]), chunk: z.string() }),
|
|
28
|
+
z.object({ kind: z.literal("said"), stream: z.enum(["out", "err"]), text }),
|
|
29
|
+
z.object({ kind: z.literal("ask"), prompt: text, secret: z.boolean(), expect: z.string().exactOptional() }),
|
|
30
|
+
z.object({ kind: z.literal("answered") }),
|
|
31
|
+
]);
|
|
32
|
+
const reach = z.enum(reachStates);
|
|
33
|
+
const verdict = z.enum(verdicts);
|
|
34
|
+
const serverCommand = z.enum(["up", "provision", "deploy", "setup", "plan", "verify", "apps", "down", "adopt", "backup.test"]);
|
|
35
|
+
const serverFacts = z.object({
|
|
36
|
+
name: z.string(), kind: z.enum(serverKinds), target: z.enum(serverTargets), domain: z.string(), apps: z.array(z.string()),
|
|
37
|
+
commands: z.array(z.union([serverCommand, z.literal("job")])),
|
|
38
|
+
});
|
|
39
|
+
export const options = z.strictObject({
|
|
40
|
+
verbose: z.boolean().default(false),
|
|
41
|
+
dryRun: z.boolean().default(false),
|
|
42
|
+
columns: z.number().int().min(1).max(1000).default(120),
|
|
43
|
+
rows: z.number().int().min(1).max(1000).default(32),
|
|
44
|
+
});
|
|
45
|
+
export const requestBody = z.strictObject({ input: z.unknown().exactOptional(), options: options.exactOptional(), confirm: z.string().exactOptional() });
|
|
46
|
+
export const schemas = {
|
|
47
|
+
Tone: tone, Span: span, Line: line, Text: text, Part: part, Listed: listed, Invocation: invocation, Stop: stop, RunState: state,
|
|
48
|
+
RunEvent: event, RunSummary: summary,
|
|
49
|
+
Run: summary.extend({ events: z.array(event) }),
|
|
50
|
+
Preview: z.object({ invocation, steps: z.array(listed), changes: z.boolean() }),
|
|
51
|
+
ServerCommand: serverCommand,
|
|
52
|
+
ServerFacts: serverFacts,
|
|
53
|
+
FleetFacts: z.object({ fleet: z.string(), version: z.string(), servers: z.array(serverFacts) }),
|
|
54
|
+
DirectoryListing: z.object({ path: z.string(), parent: z.string(), directories: z.array(z.object({ name: z.string(), path: z.string() })) }),
|
|
55
|
+
ReachState: reach,
|
|
56
|
+
Status: z.object({ servers: z.array(z.object({
|
|
57
|
+
name: z.string(), kind: z.string(), target: z.string(), domain: z.string(), apps: z.array(z.string()),
|
|
58
|
+
machine: z.object({ state: z.enum(machineStates), address: z.string().nullable(), from: z.enum(["inventory", "opentofu"]).nullable(), reason: z.string().nullable() }),
|
|
59
|
+
ssh: z.object({ port: z.number(), state: reach, ms: z.number().nullable(), error: z.string().nullable() }),
|
|
60
|
+
https: z.object({ url: z.string(), state: reach, status: z.number().nullable(), ms: z.number().nullable(), error: z.string().nullable() }).nullable(),
|
|
61
|
+
})) }),
|
|
62
|
+
Validation: z.object({ result: verdict, servers: z.array(z.object({ name: z.string(), kind: z.string(), target: z.string(), result: verdict, findings: z.array(z.object({ result: verdict, text: z.string(), hint: z.string().nullable() })) })) }),
|
|
63
|
+
AppRuns: runsSchema, AppReleases: releasesSchema,
|
|
64
|
+
OperationInfo: z.object({ name: z.enum(operationNames), summary: z.string(), scope: z.enum(scopes), effect: z.enum(effects), kind: z.enum(kinds), input: z.record(z.string(), z.unknown()) }),
|
|
65
|
+
};
|
|
66
|
+
export const querySchemas = {
|
|
67
|
+
validate: schemas.Validation, version: z.string(), "app.runs": schemas.AppRuns, "app.releases": schemas.AppReleases, "app.log": z.string(),
|
|
68
|
+
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { query } from "../../core/operations/dispatch.js";
|
|
3
|
+
import { validateJson } from "./validate.js";
|
|
4
|
+
import { parsed, releasesSchema, runsSchema } from "../../core/ctl/answers.js";
|
|
5
|
+
import { err, map, ok } from "../../result.js";
|
|
6
|
+
// eslint-disable-next-line functional/prefer-immutable-types -- Zod schemas are immutable; each method returns a new schema
|
|
7
|
+
const data = (schema, text) => {
|
|
8
|
+
if (!text.ok)
|
|
9
|
+
return text;
|
|
10
|
+
const value = parsed(schema, text.value);
|
|
11
|
+
return value === undefined ? err("the deployer returned an unreadable answer") : ok(value);
|
|
12
|
+
};
|
|
13
|
+
const queries = {
|
|
14
|
+
validate: async (context, input) => map(await query(context, "validate", input), validateJson),
|
|
15
|
+
version: (context, input) => query(context, "version", input),
|
|
16
|
+
"app.runs": async (context, input) => data(runsSchema, await query(context, "app.runs", input)),
|
|
17
|
+
"app.releases": async (context, input) => data(releasesSchema, await query(context, "app.releases", input)),
|
|
18
|
+
"app.log": (context, input) => query(context, "app.log", input),
|
|
19
|
+
};
|
|
20
|
+
export const answer = (context, name, input) => queries[name](context, input);
|