@cavelon/cli 0.0.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +713 -3
- package/dist/LICENSE +201 -0
- package/dist/agents.js +107 -0
- package/dist/branches.js +61 -0
- package/dist/capacity.js +162 -0
- package/dist/cli.js +4 -0
- package/dist/command.js +62 -0
- package/dist/commands/api.js +313 -0
- package/dist/commands/async.js +207 -0
- package/dist/commands/docs.js +158 -0
- package/dist/commands/index.js +112 -0
- package/dist/commands/init.js +481 -0
- package/dist/commands/inventory.js +56 -0
- package/dist/commands/limits-set.js +633 -0
- package/dist/commands/limits.js +156 -0
- package/dist/commands/loops.js +798 -0
- package/dist/commands/models.js +197 -0
- package/dist/commands/sandboxes.js +674 -0
- package/dist/commands/session.js +480 -0
- package/dist/commands/solution.js +830 -0
- package/dist/commands/tenants.js +266 -0
- package/dist/commands/values.js +386 -0
- package/dist/commands/work.js +761 -0
- package/dist/context.js +60 -0
- package/dist/contracts.js +234 -0
- package/dist/credentials.js +134 -0
- package/dist/errors.js +64 -0
- package/dist/features.js +52 -0
- package/dist/format.js +36 -0
- package/dist/fsutil.js +43 -0
- package/dist/git.js +41 -0
- package/dist/http.js +304 -0
- package/dist/invoke.js +165 -0
- package/dist/io.js +49 -0
- package/dist/limits.js +307 -0
- package/dist/local-state.js +78 -0
- package/dist/main.js +227 -0
- package/dist/markers.js +113 -0
- package/dist/mcp.js +137 -0
- package/dist/openapi.js +233 -0
- package/dist/operations.js +107 -0
- package/dist/package-check.js +342 -0
- package/dist/package-files.js +394 -0
- package/dist/pair-order.js +39 -0
- package/dist/paths.js +77 -0
- package/dist/principal.js +33 -0
- package/dist/project.js +157 -0
- package/dist/prompt.js +34 -0
- package/dist/results.js +104 -0
- package/dist/session.js +190 -0
- package/dist/shell.js +41 -0
- package/dist/skills/cavelon-authoring/SKILL.md +224 -0
- package/dist/skills/cavelon-long-running/SKILL.md +185 -0
- package/dist/skills/cavelon-loop/SKILL.md +159 -0
- package/dist/skills/cavelon-testing/SKILL.md +97 -0
- package/dist/sse.js +44 -0
- package/dist/tar.js +172 -0
- package/dist/user-config.js +36 -0
- package/dist/version.js +17 -0
- package/dist/zip.js +132 -0
- package/package.json +40 -4
package/dist/limits.js
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { CavelonError, ExitCode } from "./errors.js";
|
|
2
|
+
import { cavelonCommand } from "./shell.js";
|
|
3
|
+
const NEAR = 0.8;
|
|
4
|
+
export function changedBy(limit) {
|
|
5
|
+
if (limit.changeable_by === "tenant_admin")
|
|
6
|
+
return "a tenant admin";
|
|
7
|
+
if (limit.changeable_by === "tenant_owner")
|
|
8
|
+
return "a Tenant Owner";
|
|
9
|
+
if (limit.changeable_by === "operator")
|
|
10
|
+
return limit.source === "licence" ? "the operator (licence)" : "the instance operator";
|
|
11
|
+
return limit.changeable_by;
|
|
12
|
+
}
|
|
13
|
+
export function docsPage(docs) {
|
|
14
|
+
const page = docs.split("#")[0];
|
|
15
|
+
return page.startsWith("/docs/") ? page.slice("/docs/".length) : page.replace(/^\//, "");
|
|
16
|
+
}
|
|
17
|
+
export function formatValue(limit) {
|
|
18
|
+
if (typeof limit.value === "boolean")
|
|
19
|
+
return limit.value ? "on" : "off";
|
|
20
|
+
if (Array.isArray(limit.value)) {
|
|
21
|
+
if (limit.value.length === 0)
|
|
22
|
+
return "none";
|
|
23
|
+
const shown = limit.value.slice(0, 4).join(", ");
|
|
24
|
+
return `${limit.value.length} file types (${shown}${limit.value.length > 4 ? ", …" : ""})`;
|
|
25
|
+
}
|
|
26
|
+
const units = {
|
|
27
|
+
megabytes: "MB",
|
|
28
|
+
bytes: "bytes",
|
|
29
|
+
characters: "characters",
|
|
30
|
+
seconds: "s",
|
|
31
|
+
count: "",
|
|
32
|
+
requests_per_minute: "requests/min",
|
|
33
|
+
processing_steps: "Processing Steps",
|
|
34
|
+
};
|
|
35
|
+
const unit = units[limit.unit] ?? limit.unit;
|
|
36
|
+
return unit ? `${limit.value} ${unit}` : String(limit.value);
|
|
37
|
+
}
|
|
38
|
+
const GATE_TEXT = {
|
|
39
|
+
kb_upload_archive_enabled: "archive uploads are on",
|
|
40
|
+
};
|
|
41
|
+
export function bindsWhenText(limit) {
|
|
42
|
+
if (!limit.binds_when)
|
|
43
|
+
return undefined;
|
|
44
|
+
const gate = GATE_TEXT[limit.binds_when];
|
|
45
|
+
return gate ? `applies while ${gate} (${limit.binds_when})` : `applies while ${limit.binds_when} is on`;
|
|
46
|
+
}
|
|
47
|
+
export function bindsNow(limit, published) {
|
|
48
|
+
if (!limit.binds_when)
|
|
49
|
+
return true;
|
|
50
|
+
return published.byKey.get(limit.binds_when)?.value !== false;
|
|
51
|
+
}
|
|
52
|
+
export function describeLimit(limit) {
|
|
53
|
+
const value = Array.isArray(limit.value) && limit.value.length ? `${limit.value.length} file types` : formatValue(limit);
|
|
54
|
+
const binds = bindsWhenText(limit);
|
|
55
|
+
return (`${limit.key} is ${value} (source: ${limit.source}${limit.origin ? `, origin: ${limit.origin}` : ""}); ${changedBy(limit)} changes it with ${limit.setting}. ` +
|
|
56
|
+
(binds ? `It ${binds}. ` : "") +
|
|
57
|
+
`Docs: ${cavelonCommand("docs", "get", docsPage(limit.docs))}`);
|
|
58
|
+
}
|
|
59
|
+
export function limitRef(limit) {
|
|
60
|
+
const { key, value, unit, source, changeable_by, setting, docs, scope, origin, binds_when } = limit;
|
|
61
|
+
return { key, value, unit, source, changeable_by, setting, docs, scope, ...(origin ? { origin } : {}), ...(binds_when ? { binds_when } : {}) };
|
|
62
|
+
}
|
|
63
|
+
export const LIMIT_ABOVE_CEILING = "limit_above_platform_ceiling";
|
|
64
|
+
export function ceilingRefusal(body) {
|
|
65
|
+
if (!body || typeof body !== "object" || Array.isArray(body))
|
|
66
|
+
return undefined;
|
|
67
|
+
const fields = body;
|
|
68
|
+
const text = (v) => (typeof v === "string" && v !== "" ? v : undefined);
|
|
69
|
+
const number = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
|
|
70
|
+
const setting = text(fields.setting);
|
|
71
|
+
const value = number(fields.value);
|
|
72
|
+
const maximum = number(fields.maximum);
|
|
73
|
+
const ceiling = text(fields.maximum_setting);
|
|
74
|
+
const details = {
|
|
75
|
+
...(setting ? { setting } : {}),
|
|
76
|
+
...(value === undefined ? {} : { value }),
|
|
77
|
+
...(maximum === undefined ? {} : { maximum }),
|
|
78
|
+
...(ceiling ? { maximum_setting: ceiling } : {}),
|
|
79
|
+
};
|
|
80
|
+
const what = setting ?? "This limit";
|
|
81
|
+
const most = maximum === undefined ? "a value up to the platform's ceiling" : `at most ${maximum}`;
|
|
82
|
+
const raise = ceiling ? `Only the instance operator raises the ceiling, with ${ceiling}; ask them.` : "Only the instance operator raises the ceiling; ask them.";
|
|
83
|
+
return { hint: `${what} may only be lowered: send ${most}. ${raise}`, details };
|
|
84
|
+
}
|
|
85
|
+
export function ceilingHint(published) {
|
|
86
|
+
const lower = "A tenant admin sets a value up to the ceiling with `cavelon limits set <key> <value>`; only the instance operator raises a ceiling, with the setting named.";
|
|
87
|
+
const capped = (published?.values ?? []).filter((l) => l.change?.maximum_setting && l.change.maximum !== undefined);
|
|
88
|
+
if (!capped.length)
|
|
89
|
+
return lower;
|
|
90
|
+
const each = capped.map((l) => `${l.key} up to ${formatValue({ value: l.change.maximum, unit: l.unit })} (${l.change.maximum_setting})`);
|
|
91
|
+
return `The ceilings here: ${each.join(", ")}. ${lower}`;
|
|
92
|
+
}
|
|
93
|
+
export function parseChange(raw) {
|
|
94
|
+
if (!raw || typeof raw !== "object")
|
|
95
|
+
return undefined;
|
|
96
|
+
const entry = raw;
|
|
97
|
+
const text = (v) => (typeof v === "string" && v !== "" ? v : undefined);
|
|
98
|
+
const operation = text(entry.operation);
|
|
99
|
+
const method = text(entry.method)?.toUpperCase();
|
|
100
|
+
const path = text(entry.path);
|
|
101
|
+
const field = text(entry.field);
|
|
102
|
+
if (!operation || !method || !path?.startsWith("/api/") || !field)
|
|
103
|
+
return undefined;
|
|
104
|
+
const permissions = Array.isArray(entry.permissions) ? entry.permissions.filter((p) => typeof p === "string" && p !== "") : [];
|
|
105
|
+
const bound = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
|
|
106
|
+
const minimum = bound(entry.minimum);
|
|
107
|
+
const maximum = bound(entry.maximum);
|
|
108
|
+
const maximumSetting = text(entry.maximum_setting);
|
|
109
|
+
const roles = Array.isArray(entry.requires_role) ? entry.requires_role.filter((r) => typeof r === "string" && r !== "") : [];
|
|
110
|
+
const mode = text(entry.mode);
|
|
111
|
+
return {
|
|
112
|
+
operation,
|
|
113
|
+
method,
|
|
114
|
+
path,
|
|
115
|
+
field,
|
|
116
|
+
permissions,
|
|
117
|
+
...(minimum === undefined ? {} : { minimum }),
|
|
118
|
+
...(maximum === undefined ? {} : { maximum }),
|
|
119
|
+
...(maximumSetting ? { maximum_setting: maximumSetting } : {}),
|
|
120
|
+
...(roles.length ? { requires_role: roles } : {}),
|
|
121
|
+
...(mode ? { mode } : {}),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
export function isOperatorChange(change) {
|
|
125
|
+
return Boolean(change.requires_role?.length) || change.mode === "platform";
|
|
126
|
+
}
|
|
127
|
+
function parseSwitches(raw) {
|
|
128
|
+
if (!Array.isArray(raw))
|
|
129
|
+
return undefined;
|
|
130
|
+
return raw.flatMap((entry) => {
|
|
131
|
+
if (!entry || typeof entry !== "object")
|
|
132
|
+
return [];
|
|
133
|
+
const item = entry;
|
|
134
|
+
if (typeof item.setting !== "string" || typeof item.enabled !== "boolean")
|
|
135
|
+
return [];
|
|
136
|
+
return [{ setting: item.setting, source: String(item.source ?? ""), enabled: item.enabled }];
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
function isLimit(raw) {
|
|
140
|
+
if (!raw || typeof raw !== "object")
|
|
141
|
+
return false;
|
|
142
|
+
const entry = raw;
|
|
143
|
+
const valueOk = typeof entry.value === "number" || typeof entry.value === "boolean" || (Array.isArray(entry.value) && entry.value.every((v) => typeof v === "string"));
|
|
144
|
+
return typeof entry.key === "string" && valueOk && typeof entry.unit === "string" && typeof entry.source === "string";
|
|
145
|
+
}
|
|
146
|
+
export function parseLimits(caps) {
|
|
147
|
+
const section = caps?.limits;
|
|
148
|
+
if (!section || typeof section !== "object" || !Array.isArray(section.values)) {
|
|
149
|
+
return { published: false, values: [], byKey: new Map() };
|
|
150
|
+
}
|
|
151
|
+
const values = section.values.filter(isLimit).map(({ origin, change: rawChange, tenant_change: rawTenantChange, switches: rawSwitches, binds_when: bindsWhen, ...entry }) => {
|
|
152
|
+
const change = parseChange(rawChange);
|
|
153
|
+
const tenantChange = parseChange(rawTenantChange);
|
|
154
|
+
const switches = parseSwitches(rawSwitches);
|
|
155
|
+
return {
|
|
156
|
+
...entry,
|
|
157
|
+
...(typeof origin === "string" && origin ? { origin } : {}),
|
|
158
|
+
...(typeof bindsWhen === "string" && bindsWhen ? { binds_when: bindsWhen } : {}),
|
|
159
|
+
...(change ? { change } : {}),
|
|
160
|
+
...(tenantChange ? { tenant_change: tenantChange } : {}),
|
|
161
|
+
...(switches ? { switches } : {}),
|
|
162
|
+
changeable_by: String(entry.changeable_by ?? ""),
|
|
163
|
+
setting: String(entry.setting ?? ""),
|
|
164
|
+
docs: String(entry.docs ?? ""),
|
|
165
|
+
scope: String(entry.scope ?? "tenant"),
|
|
166
|
+
description: String(entry.description ?? ""),
|
|
167
|
+
};
|
|
168
|
+
});
|
|
169
|
+
const link = section.tenant_quotas;
|
|
170
|
+
const tenantQuotas = link && typeof link.path === "string" && link.path.startsWith("/api/")
|
|
171
|
+
? { path: link.path, docs: typeof link.docs === "string" ? link.docs : undefined, changes: quotaChanges(link.changes), values: quotaValues(link.values) }
|
|
172
|
+
: undefined;
|
|
173
|
+
return { published: true, values, byKey: new Map(values.map((v) => [v.key, v])), tenantQuotas };
|
|
174
|
+
}
|
|
175
|
+
function quotaValues(raw) {
|
|
176
|
+
if (!Array.isArray(raw))
|
|
177
|
+
return [];
|
|
178
|
+
return raw.flatMap((entry) => {
|
|
179
|
+
if (!entry || typeof entry !== "object")
|
|
180
|
+
return [];
|
|
181
|
+
const item = entry;
|
|
182
|
+
if (typeof item.key !== "string" || !item.key)
|
|
183
|
+
return [];
|
|
184
|
+
const number = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
|
|
185
|
+
const value = number(item.value);
|
|
186
|
+
const used = number(item.used);
|
|
187
|
+
const period = item.period && typeof item.period === "object" ? item.period : null;
|
|
188
|
+
const ratio = value !== null && value > 0 && used !== null ? used / value : null;
|
|
189
|
+
const change = parseChange(item.change);
|
|
190
|
+
return [
|
|
191
|
+
{
|
|
192
|
+
key: item.key,
|
|
193
|
+
value,
|
|
194
|
+
unit: String(item.unit ?? "count"),
|
|
195
|
+
used,
|
|
196
|
+
state: String(item.state ?? ""),
|
|
197
|
+
period,
|
|
198
|
+
source: String(item.source ?? "tenant"),
|
|
199
|
+
changeable_by: String(item.changeable_by ?? ""),
|
|
200
|
+
setting: String(item.setting ?? item.key),
|
|
201
|
+
docs: String(item.docs ?? ""),
|
|
202
|
+
description: String(item.description ?? ""),
|
|
203
|
+
...(change ? { change } : {}),
|
|
204
|
+
ratio,
|
|
205
|
+
near: ratio !== null && ratio >= NEAR,
|
|
206
|
+
},
|
|
207
|
+
];
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
function quotaChanges(raw) {
|
|
211
|
+
if (!Array.isArray(raw))
|
|
212
|
+
return [];
|
|
213
|
+
return raw.flatMap((entry) => {
|
|
214
|
+
const change = parseChange(entry);
|
|
215
|
+
const key = entry?.key;
|
|
216
|
+
return change && typeof key === "string" && key ? [{ key, ...change }] : [];
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
export async function readLimits(ctx) {
|
|
220
|
+
const contracts = await ctx.contracts();
|
|
221
|
+
return parseLimits(await contracts.liveCapabilities());
|
|
222
|
+
}
|
|
223
|
+
export async function limitsOrWarn(ctx) {
|
|
224
|
+
try {
|
|
225
|
+
return await readLimits(ctx);
|
|
226
|
+
}
|
|
227
|
+
catch (error) {
|
|
228
|
+
ctx.warn(`Could not read the instance's limits, so they were not checked: ${error instanceof Error ? error.message : String(error)}`);
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
function quotaOf(key, raw) {
|
|
233
|
+
const current = typeof raw.current === "number" ? raw.current : null;
|
|
234
|
+
const limit = typeof raw.limit === "number" ? raw.limit : null;
|
|
235
|
+
const ratio = current !== null && limit !== null && limit > 0 ? current / limit : null;
|
|
236
|
+
const warning = typeof raw.warning_ratio === "number" && raw.warning_ratio > 0 ? raw.warning_ratio : NEAR;
|
|
237
|
+
const link = raw.change;
|
|
238
|
+
const change = link && typeof link.key === "string" && typeof link.field === "string" ? { key: link.key, field: link.field } : undefined;
|
|
239
|
+
return { key, current, limit, ratio, warning_ratio: warning, near: ratio !== null && ratio >= warning, details: raw, ...(change ? { change } : {}) };
|
|
240
|
+
}
|
|
241
|
+
export async function readQuotas(ctx, limits) {
|
|
242
|
+
const link = limits.tenantQuotas;
|
|
243
|
+
if (!link)
|
|
244
|
+
return undefined;
|
|
245
|
+
const client = await ctx.client();
|
|
246
|
+
const base = { path: link.path, docs: link.docs ?? null };
|
|
247
|
+
let response;
|
|
248
|
+
try {
|
|
249
|
+
response = await client.get(link.path, { allow: [400, 403, 404] });
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
if (!(error instanceof CavelonError))
|
|
253
|
+
throw error;
|
|
254
|
+
return { ...base, items: [], unavailable: `${link.path}: ${error.message}` };
|
|
255
|
+
}
|
|
256
|
+
if (response.status !== 200 || !response.data || typeof response.data !== "object") {
|
|
257
|
+
return { ...base, items: [], unavailable: `${link.path} answered ${response.status}.` };
|
|
258
|
+
}
|
|
259
|
+
const items = Object.entries(response.data)
|
|
260
|
+
.filter((entry) => Boolean(entry[1]) && typeof entry[1] === "object" && !Array.isArray(entry[1]))
|
|
261
|
+
.map(([key, raw]) => quotaOf(key, raw))
|
|
262
|
+
.filter((q) => !(q.change && link.values.some((v) => v.key === q.change.key)));
|
|
263
|
+
return { ...base, items };
|
|
264
|
+
}
|
|
265
|
+
export async function quotaSetting(ctx, limits, key) {
|
|
266
|
+
const link = limits.tenantQuotas;
|
|
267
|
+
if (!link)
|
|
268
|
+
return undefined;
|
|
269
|
+
const client = await ctx.client();
|
|
270
|
+
const response = await client.get(link.path, { allow: [400, 403, 404] });
|
|
271
|
+
if (response.status !== 200 || !response.data || typeof response.data !== "object")
|
|
272
|
+
return undefined;
|
|
273
|
+
for (const raw of Object.values(response.data)) {
|
|
274
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
275
|
+
continue;
|
|
276
|
+
const row = raw;
|
|
277
|
+
const change = row.change;
|
|
278
|
+
if (change?.key === key && typeof change.field === "string" && change.field in row)
|
|
279
|
+
return { value: row[change.field] };
|
|
280
|
+
}
|
|
281
|
+
return undefined;
|
|
282
|
+
}
|
|
283
|
+
export function formatQuotaValue(quota) {
|
|
284
|
+
const used = quota.used === null ? "?" : String(quota.used);
|
|
285
|
+
if (quota.value === null || quota.value <= 0)
|
|
286
|
+
return `${used} (no cap)`;
|
|
287
|
+
return `${used} of ${quota.value}${quota.ratio === null ? "" : ` (${Math.round(quota.ratio * 100)}%)`}`;
|
|
288
|
+
}
|
|
289
|
+
export function formatQuota(quota) {
|
|
290
|
+
if (quota.current === null && quota.limit === null)
|
|
291
|
+
return "-";
|
|
292
|
+
const used = quota.current === null ? "?" : String(quota.current);
|
|
293
|
+
if (quota.limit === null || quota.limit <= 0)
|
|
294
|
+
return `${used} (no limit)`;
|
|
295
|
+
return `${used} of ${quota.limit}${quota.ratio === null ? "" : ` (${Math.round(quota.ratio * 100)}%)`}`;
|
|
296
|
+
}
|
|
297
|
+
export function limitError(options) {
|
|
298
|
+
const { code, message, limits, details } = options;
|
|
299
|
+
const described = limits.map(describeLimit).join(" ");
|
|
300
|
+
return new CavelonError(options.exitCode ?? ExitCode.validation, {
|
|
301
|
+
code,
|
|
302
|
+
message,
|
|
303
|
+
hint: [options.hint, described].filter(Boolean).join(" ") || undefined,
|
|
304
|
+
docs: limits[0]?.docs || undefined,
|
|
305
|
+
details: { ...details, limits: limits.map(limitRef), sent: false },
|
|
306
|
+
});
|
|
307
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { promises as fs } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { readJsonFile, readTextFile, writeFileAtomic } from "./fsutil.js";
|
|
5
|
+
export const STATE_DIR = ".cavelon";
|
|
6
|
+
export function stateDir(root) {
|
|
7
|
+
return path.join(root, STATE_DIR);
|
|
8
|
+
}
|
|
9
|
+
export async function ensureStateDir(root) {
|
|
10
|
+
const dir = stateDir(root);
|
|
11
|
+
const ignore = path.join(dir, ".gitignore");
|
|
12
|
+
if ((await readTextFile(ignore)) !== undefined)
|
|
13
|
+
return false;
|
|
14
|
+
await writeFileAtomic(ignore, "# Local cavelon state; never committed.\n*\n");
|
|
15
|
+
return true;
|
|
16
|
+
}
|
|
17
|
+
export async function writeState(root, name, content) {
|
|
18
|
+
await ensureStateDir(root);
|
|
19
|
+
await writeFileAtomic(path.join(stateDir(root), name), content);
|
|
20
|
+
}
|
|
21
|
+
export async function readPull(root) {
|
|
22
|
+
return readJsonFile(path.join(stateDir(root), "pull.json"));
|
|
23
|
+
}
|
|
24
|
+
const PULLED_FILES = "pulled-files.json";
|
|
25
|
+
export async function fileDigest(file) {
|
|
26
|
+
const bytes = await fs.readFile(file).catch(() => undefined);
|
|
27
|
+
return bytes && createHash("sha256").update(bytes).digest("hex");
|
|
28
|
+
}
|
|
29
|
+
export async function writePulledFiles(root, files) {
|
|
30
|
+
const digests = {};
|
|
31
|
+
for (const file of files) {
|
|
32
|
+
const value = await fileDigest(path.join(root, file));
|
|
33
|
+
if (value)
|
|
34
|
+
digests[file] = value;
|
|
35
|
+
}
|
|
36
|
+
await writeState(root, PULLED_FILES, JSON.stringify({ digests }, null, 2));
|
|
37
|
+
}
|
|
38
|
+
export async function readPulledFiles(root) {
|
|
39
|
+
const stored = await readJsonFile(path.join(stateDir(root), PULLED_FILES));
|
|
40
|
+
return stored?.digests && typeof stored.digests === "object" ? stored.digests : {};
|
|
41
|
+
}
|
|
42
|
+
export function digest(value) {
|
|
43
|
+
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
44
|
+
}
|
|
45
|
+
function previewFile(root, previewId) {
|
|
46
|
+
const safe = /^[A-Za-z0-9._-]{1,100}$/.test(previewId) ? previewId : createHash("sha256").update(previewId).digest("hex").slice(0, 32);
|
|
47
|
+
return path.join(stateDir(root), "previews", `${safe}.json`);
|
|
48
|
+
}
|
|
49
|
+
export async function savePreview(root, preview) {
|
|
50
|
+
await ensureStateDir(root);
|
|
51
|
+
const file = previewFile(root, preview.preview_id);
|
|
52
|
+
await writeFileAtomic(file, JSON.stringify(preview, null, 2));
|
|
53
|
+
return file;
|
|
54
|
+
}
|
|
55
|
+
export async function loadPreview(root, previewId) {
|
|
56
|
+
const stored = await readJsonFile(previewFile(root, previewId));
|
|
57
|
+
return stored?.preview_id === previewId ? stored : undefined;
|
|
58
|
+
}
|
|
59
|
+
export async function deletePreview(root, previewId) {
|
|
60
|
+
await fs.rm(previewFile(root, previewId), { force: true });
|
|
61
|
+
}
|
|
62
|
+
export async function listPreviews(root) {
|
|
63
|
+
const dir = path.join(stateDir(root), "previews");
|
|
64
|
+
let names;
|
|
65
|
+
try {
|
|
66
|
+
names = await fs.readdir(dir);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return [];
|
|
70
|
+
}
|
|
71
|
+
const out = [];
|
|
72
|
+
for (const name of names.filter((n) => n.endsWith(".json"))) {
|
|
73
|
+
const stored = await readJsonFile(path.join(dir, name));
|
|
74
|
+
if (stored?.preview_id)
|
|
75
|
+
out.push({ preview_id: stored.preview_id, created_at: stored.created_at, env: stored.env, harness: stored.harness });
|
|
76
|
+
}
|
|
77
|
+
return out.sort((a, b) => (a.created_at < b.created_at ? 1 : -1));
|
|
78
|
+
}
|
package/dist/main.js
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import { parseArgs } from "node:util";
|
|
2
|
+
import { GLOBAL_OPTIONS } from "./command.js";
|
|
3
|
+
import { createContext, withWarnings } from "./context.js";
|
|
4
|
+
import { asCavelonError, ExitCode, usageError } from "./errors.js";
|
|
5
|
+
import { blockerLines } from "./format.js";
|
|
6
|
+
import { KIT_VERSION } from "./version.js";
|
|
7
|
+
import { COMMANDS } from "./commands/index.js";
|
|
8
|
+
export async function run(argv, io, commands = COMMANDS) {
|
|
9
|
+
const json = argv.includes("--json");
|
|
10
|
+
let ctx;
|
|
11
|
+
try {
|
|
12
|
+
if (argv.length === 0) {
|
|
13
|
+
io.stderr.write(rootHelp(commands));
|
|
14
|
+
return ExitCode.usage;
|
|
15
|
+
}
|
|
16
|
+
if (argv[0] === "--version" || argv[0] === "-v" || argv[0] === "version") {
|
|
17
|
+
io.stdout.write(json ? `${JSON.stringify({ version: KIT_VERSION })}\n` : `${KIT_VERSION}\n`);
|
|
18
|
+
return ExitCode.ok;
|
|
19
|
+
}
|
|
20
|
+
const found = findCommand(argv, commands);
|
|
21
|
+
if (!found) {
|
|
22
|
+
if (argv.includes("--help") || argv.includes("-h") || argv[0] === "help") {
|
|
23
|
+
const topic = argv.filter((a) => !a.startsWith("-") && a !== "help");
|
|
24
|
+
const group = commands.filter((c) => c.name.startsWith(`${topic.join(" ")} `) || c.name === topic.join(" "));
|
|
25
|
+
io.stdout.write(topic.length && group.length ? groupHelp(topic.join(" "), group) : rootHelp(commands));
|
|
26
|
+
return ExitCode.ok;
|
|
27
|
+
}
|
|
28
|
+
const words = argv.filter((a) => !a.startsWith("-"));
|
|
29
|
+
const group = commands.filter((c) => c.name.startsWith(`${words[0]} `));
|
|
30
|
+
throw usageError(`Unknown command "${words.slice(0, 2).join(" ") || argv[0]}".`, group.length ? `Try: ${group.map((c) => `cavelon ${c.name}`).join(", ")}` : "Run `cavelon --help` for the commands.");
|
|
31
|
+
}
|
|
32
|
+
const { spec, rest } = found;
|
|
33
|
+
const args = spec.preprocess ? spec.preprocess(rest) : rest;
|
|
34
|
+
const parsed = parse(spec, args);
|
|
35
|
+
if (parsed.options.help === true) {
|
|
36
|
+
io.stdout.write(commandHelp(spec));
|
|
37
|
+
return ExitCode.ok;
|
|
38
|
+
}
|
|
39
|
+
ctx = createContext(io, {
|
|
40
|
+
json: parsed.options.json === true,
|
|
41
|
+
instance: typeof parsed.options.instance === "string" ? parsed.options.instance : undefined,
|
|
42
|
+
tenant: typeof parsed.options.tenant === "string" ? parsed.options.tenant : undefined,
|
|
43
|
+
solutionEnv: spec.options?.env && typeof parsed.options.env === "string" ? parsed.options.env : undefined,
|
|
44
|
+
});
|
|
45
|
+
const result = await spec.run(ctx, parsed);
|
|
46
|
+
printResult(ctx, result);
|
|
47
|
+
return result.exitCode ?? ExitCode.ok;
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
const err = asCavelonError(error);
|
|
51
|
+
printError(io, ctx?.json ?? json, err, ctx?.warnings ?? []);
|
|
52
|
+
return err.exitCode;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function findCommand(argv, commands) {
|
|
56
|
+
const words = [];
|
|
57
|
+
for (let i = 0; i < argv.length; i++) {
|
|
58
|
+
const arg = argv[i];
|
|
59
|
+
if (arg === "--instance" || arg === "--tenant") {
|
|
60
|
+
i++;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (arg.startsWith("-"))
|
|
64
|
+
continue;
|
|
65
|
+
words.push({ word: arg, index: i });
|
|
66
|
+
if (words.length === 3)
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
for (let n = Math.min(words.length, 3); n > 0; n--) {
|
|
70
|
+
const name = words.slice(0, n).map((w) => w.word).join(" ");
|
|
71
|
+
const spec = commands.find((c) => c.name === name);
|
|
72
|
+
if (spec) {
|
|
73
|
+
const drop = new Set(words.slice(0, n).map((w) => w.index));
|
|
74
|
+
return { spec, rest: argv.filter((_, i) => !drop.has(i)) };
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
function parse(spec, args) {
|
|
80
|
+
for (const arg of args) {
|
|
81
|
+
if (arg === "--token" || arg.startsWith("--token=")) {
|
|
82
|
+
throw usageError("cavelon never takes a token as an argument; it would end up in the shell history.", "Run `cavelon login` and paste it when asked, or pipe it: `cavelon login --token-stdin`.");
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const options = { ...GLOBAL_OPTIONS, ...spec.options };
|
|
86
|
+
const config = {
|
|
87
|
+
args,
|
|
88
|
+
allowPositionals: true,
|
|
89
|
+
strict: true,
|
|
90
|
+
options: Object.fromEntries(Object.entries(options).map(([name, o]) => [
|
|
91
|
+
name,
|
|
92
|
+
{ type: o.type, ...(o.multiple ? { multiple: true } : {}), ...(o.short ? { short: o.short } : {}) },
|
|
93
|
+
])),
|
|
94
|
+
};
|
|
95
|
+
let values;
|
|
96
|
+
let positionals;
|
|
97
|
+
try {
|
|
98
|
+
({ values, positionals } = parseArgs(config));
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
throw usageError(error instanceof Error ? error.message : String(error), `Run \`cavelon ${spec.name} --help\`.`);
|
|
102
|
+
}
|
|
103
|
+
if (values.help === true)
|
|
104
|
+
return { positionals: {}, options: { help: true } };
|
|
105
|
+
const named = {};
|
|
106
|
+
const specs = spec.positionals ?? [];
|
|
107
|
+
let index = 0;
|
|
108
|
+
for (const p of specs) {
|
|
109
|
+
if (p.variadic) {
|
|
110
|
+
named[p.name] = positionals.slice(index);
|
|
111
|
+
if (p.required && positionals.length <= index)
|
|
112
|
+
throw missing(spec, p.name);
|
|
113
|
+
index = positionals.length;
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
const value = positionals[index++];
|
|
117
|
+
if (value === undefined && p.required)
|
|
118
|
+
throw missing(spec, p.name);
|
|
119
|
+
named[p.name] = value;
|
|
120
|
+
}
|
|
121
|
+
if (positionals.length > index) {
|
|
122
|
+
throw usageError(`Unexpected argument "${positionals[index]}".`, `Run \`cavelon ${spec.name} --help\`.`);
|
|
123
|
+
}
|
|
124
|
+
return { positionals: named, options: values };
|
|
125
|
+
}
|
|
126
|
+
function missing(spec, name) {
|
|
127
|
+
return usageError(`Missing <${name}>.`, `Usage: ${usageLine(spec)}`);
|
|
128
|
+
}
|
|
129
|
+
function printResult(ctx, result) {
|
|
130
|
+
const { io } = ctx;
|
|
131
|
+
for (const warning of ctx.warnings)
|
|
132
|
+
io.stderr.write(`${ctx.style.yellow("warning:")} ${warning}\n`);
|
|
133
|
+
if (ctx.json) {
|
|
134
|
+
let data = result.data;
|
|
135
|
+
if (ctx.warnings.length && data && typeof data === "object" && !Array.isArray(data)) {
|
|
136
|
+
data = withWarnings(data, ctx.warnings);
|
|
137
|
+
}
|
|
138
|
+
if (data !== undefined)
|
|
139
|
+
io.stdout.write(`${JSON.stringify(data)}\n`);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
const text = result.text ?? (result.data === undefined ? "" : JSON.stringify(result.data, null, 2));
|
|
143
|
+
if (text)
|
|
144
|
+
io.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
|
|
145
|
+
}
|
|
146
|
+
function printError(io, json, err, warnings) {
|
|
147
|
+
for (const warning of warnings)
|
|
148
|
+
io.stderr.write(`warning: ${warning}\n`);
|
|
149
|
+
if (json) {
|
|
150
|
+
io.stdout.write(`${JSON.stringify({ error: err.toJSON() })}\n`);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
const lines = [`error: ${err.message}`];
|
|
154
|
+
if (err.blockers?.length)
|
|
155
|
+
lines.push(blockerLines(err.blockers));
|
|
156
|
+
if (err.hint)
|
|
157
|
+
lines.push(`hint: ${err.hint}`);
|
|
158
|
+
if (err.docs)
|
|
159
|
+
lines.push(`docs: ${err.docs}`);
|
|
160
|
+
io.stderr.write(`${lines.join("\n")}\n`);
|
|
161
|
+
}
|
|
162
|
+
export function usageLine(spec) {
|
|
163
|
+
const parts = [`cavelon ${spec.name}`];
|
|
164
|
+
for (const p of spec.positionals ?? []) {
|
|
165
|
+
const name = p.variadic ? `${p.name}...` : p.name;
|
|
166
|
+
parts.push(p.required ? `<${name}>` : `[${name}]`);
|
|
167
|
+
}
|
|
168
|
+
if (Object.keys(spec.options ?? {}).length)
|
|
169
|
+
parts.push("[options]");
|
|
170
|
+
return parts.join(" ");
|
|
171
|
+
}
|
|
172
|
+
function optionLines(options) {
|
|
173
|
+
const rows = Object.entries(options).map(([name, o]) => {
|
|
174
|
+
const flag = `${o.short ? `-${o.short}, ` : ""}--${name}${o.type === "string" ? ` ${o.value ?? "<value>"}` : ""}`;
|
|
175
|
+
return [flag, o.description + (o.multiple ? " Repeatable." : "")];
|
|
176
|
+
});
|
|
177
|
+
const width = Math.max(...rows.map(([f]) => f.length));
|
|
178
|
+
return rows.map(([f, d]) => ` ${f.padEnd(width)} ${d}`);
|
|
179
|
+
}
|
|
180
|
+
export function commandHelp(spec) {
|
|
181
|
+
const lines = [
|
|
182
|
+
`Usage: ${usageLine(spec)}`,
|
|
183
|
+
"",
|
|
184
|
+
spec.summary,
|
|
185
|
+
`Marked: ${spec.readOnly ? "read-only" : spec.destructive ? "changing (destructive)" : "changing"}`,
|
|
186
|
+
];
|
|
187
|
+
if (spec.description)
|
|
188
|
+
lines.push("", spec.description);
|
|
189
|
+
if (spec.positionals?.length) {
|
|
190
|
+
lines.push("", "Arguments:");
|
|
191
|
+
const width = Math.max(...spec.positionals.map((p) => p.name.length));
|
|
192
|
+
for (const p of spec.positionals)
|
|
193
|
+
lines.push(` ${p.name.padEnd(width)} ${p.description}`);
|
|
194
|
+
}
|
|
195
|
+
if (spec.options && Object.keys(spec.options).length)
|
|
196
|
+
lines.push("", "Options:", ...optionLines(spec.options));
|
|
197
|
+
lines.push("", "Global options:", ...optionLines(GLOBAL_OPTIONS));
|
|
198
|
+
if (spec.examples?.length)
|
|
199
|
+
lines.push("", "Examples:", ...spec.examples.map((e) => ` ${e}`));
|
|
200
|
+
return `${lines.join("\n")}\n`;
|
|
201
|
+
}
|
|
202
|
+
function groupHelp(group, commands) {
|
|
203
|
+
const width = Math.max(...commands.map((c) => c.name.length));
|
|
204
|
+
return `${[
|
|
205
|
+
`cavelon ${group}`,
|
|
206
|
+
"",
|
|
207
|
+
...commands.map((c) => ` ${c.name.padEnd(width)} ${c.readOnly ? "[read-only]" : "[changing] "} ${c.summary}`),
|
|
208
|
+
"",
|
|
209
|
+
`Run \`cavelon <command> --help\` for its options.`,
|
|
210
|
+
].join("\n")}\n`;
|
|
211
|
+
}
|
|
212
|
+
export function rootHelp(commands) {
|
|
213
|
+
const width = Math.max(...commands.map((c) => c.name.length));
|
|
214
|
+
return `${[
|
|
215
|
+
`cavelon ${KIT_VERSION}: build, seed and test Cavelon solutions from a repository.`,
|
|
216
|
+
"",
|
|
217
|
+
"Usage: cavelon <command> [arguments] [options]",
|
|
218
|
+
"",
|
|
219
|
+
"Commands:",
|
|
220
|
+
...commands.map((c) => ` ${c.name.padEnd(width)} ${c.readOnly ? "[read-only]" : "[changing] "} ${c.summary}`),
|
|
221
|
+
"",
|
|
222
|
+
"Every command takes --json, --instance <url> and --tenant <tenant>.",
|
|
223
|
+
"Environment: CAVELON_URL, CAVELON_TOKEN, CAVELON_TENANT.",
|
|
224
|
+
"Exit codes: 0 ok, 1 other error, 2 usage, 3 validation failed, 4 conflict or stale preview,",
|
|
225
|
+
" 5 needs a person, 6 timed out, 7 not authorised, 8 server or network error.",
|
|
226
|
+
].join("\n")}\n`;
|
|
227
|
+
}
|