backant-cli 0.0.0-stage → 0.1.0
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 +292 -2
- package/bin/backant.js +3 -0
- package/dist/commands/application-auth.js +315 -0
- package/dist/commands/data-exploration.js +334 -0
- package/dist/commands/format.js +78 -0
- package/dist/commands/init.js +97 -0
- package/dist/commands/login.js +154 -0
- package/dist/commands/logs.js +103 -0
- package/dist/commands/pull.js +186 -0
- package/dist/commands/push.js +678 -0
- package/dist/commands/secrets.js +48 -0
- package/dist/commands/skill.js +57 -0
- package/dist/commands/snapshot.js +312 -0
- package/dist/commands/validate.js +1429 -0
- package/dist/index.js +49 -0
- package/dist/utils/assets-scanner.js +20 -0
- package/dist/utils/connection.js +115 -0
- package/dist/utils/flow-scanner.js +92 -0
- package/dist/utils/format-utils.js +266 -0
- package/dist/utils/hash-utils.js +227 -0
- package/dist/utils/job-scanner.js +35 -0
- package/dist/utils/live-models-generator.js +189 -0
- package/dist/utils/model-scanner.js +43 -0
- package/dist/utils/package-info.js +31 -0
- package/dist/utils/services-scanner.js +46 -0
- package/dist/utils/skill-installer.js +135 -0
- package/dist/utils/snapshot-writer.js +216 -0
- package/package.json +34 -4
- package/skills/bestudio/SKILL.md +36 -0
- package/skills/bestudio/project-entrypoint.md +12 -0
- package/skills/bestudio/references/project-definitions.md +24 -0
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { resolveConnection } from "../utils/connection.js";
|
|
5
|
+
const environments = ["dev", "staging", "prod"];
|
|
6
|
+
const sensitiveName = /(password|passwd|secret|token|api.?key|authorization|cookie|email|phone|address|ssn|first.?name|last.?name)/i;
|
|
7
|
+
function isSensitiveField(name) {
|
|
8
|
+
const normalized = name.replace(/[^a-z0-9]/gi, "").toLowerCase();
|
|
9
|
+
return sensitiveName.test(name) || ["name", "fullname", "firstname", "lastname"].includes(normalized);
|
|
10
|
+
}
|
|
11
|
+
function projectServerId() {
|
|
12
|
+
try {
|
|
13
|
+
const snapshot = JSON.parse(fs.readFileSync(path.join(process.cwd(), ".bestudio", "snapshot.json"), "utf8"));
|
|
14
|
+
return typeof snapshot.serverId === "string" ? snapshot.serverId : undefined;
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export function context(options) {
|
|
21
|
+
const env = options.env || process.env.BESTUDIO_ENV || "dev";
|
|
22
|
+
if (!environments.includes(env)) {
|
|
23
|
+
throw new Error(`Invalid environment "${env}". Choose dev, staging, or prod.`);
|
|
24
|
+
}
|
|
25
|
+
const connection = resolveConnection(options);
|
|
26
|
+
let serverId = options.server || projectServerId();
|
|
27
|
+
if (!serverId)
|
|
28
|
+
throw new Error("No server selected. Pass --server <id-or-name> or run from a project with .bestudio/snapshot.json.");
|
|
29
|
+
return { env: env, apiUrl: connection.apiUrl, token: connection.accessToken, serverId };
|
|
30
|
+
}
|
|
31
|
+
export async function request(ctx, pathname, init) {
|
|
32
|
+
const url = new URL(`${ctx.apiUrl}${pathname}`);
|
|
33
|
+
let response;
|
|
34
|
+
try {
|
|
35
|
+
response = await fetch(url, {
|
|
36
|
+
...init,
|
|
37
|
+
headers: {
|
|
38
|
+
Authorization: `Bearer ${ctx.token}`,
|
|
39
|
+
"Content-Type": "application/json",
|
|
40
|
+
...init?.headers,
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
throw new Error(`Network error: ${error?.message || "Failed to connect to BE Studio"}`);
|
|
46
|
+
}
|
|
47
|
+
let body;
|
|
48
|
+
try {
|
|
49
|
+
body = await response.json();
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
throw new Error(`BE Studio returned a non-JSON response (HTTP ${response.status}).`);
|
|
53
|
+
}
|
|
54
|
+
if (!response.ok || body.success === false) {
|
|
55
|
+
throw new Error(body.error || `BE Studio request failed (HTTP ${response.status}).`);
|
|
56
|
+
}
|
|
57
|
+
return body;
|
|
58
|
+
}
|
|
59
|
+
async function resolveServer(ctx) {
|
|
60
|
+
// Server IDs in BE Studio are opaque strings; resolve a name via the existing authenticated server list.
|
|
61
|
+
const looksLikeId = /^(server-|[0-9a-f]{8}-[0-9a-f-]{27,})/i.test(ctx.serverId);
|
|
62
|
+
if (looksLikeId)
|
|
63
|
+
return ctx.serverId;
|
|
64
|
+
const response = await request(ctx, "/system/servers");
|
|
65
|
+
const servers = Array.isArray(response.data) ? response.data : response.data?.servers;
|
|
66
|
+
const found = Array.isArray(servers) ? servers.find((item) => item?.name === ctx.serverId || item?.id === ctx.serverId || item?._id === ctx.serverId) : undefined;
|
|
67
|
+
if (!found)
|
|
68
|
+
throw new Error(`Server "${ctx.serverId}" was not found in your accessible server list.`);
|
|
69
|
+
const id = found.id || found._id;
|
|
70
|
+
if (typeof id !== "string")
|
|
71
|
+
throw new Error(`Server "${ctx.serverId}" did not include a usable ID.`);
|
|
72
|
+
return id;
|
|
73
|
+
}
|
|
74
|
+
export async function withServer(options) {
|
|
75
|
+
const ctx = context(options);
|
|
76
|
+
ctx.serverId = await resolveServer(ctx);
|
|
77
|
+
return ctx;
|
|
78
|
+
}
|
|
79
|
+
export function queryString(ctx) {
|
|
80
|
+
return `serverId=${encodeURIComponent(ctx.serverId)}&env=${encodeURIComponent(ctx.env)}`;
|
|
81
|
+
}
|
|
82
|
+
function safeSchema(schema) {
|
|
83
|
+
const fields = Array.isArray(schema?.fields) ? schema.fields : [];
|
|
84
|
+
return {
|
|
85
|
+
modelName: schema?.modelName,
|
|
86
|
+
fields: fields.map((field) => ({
|
|
87
|
+
name: field.name,
|
|
88
|
+
type: field.type,
|
|
89
|
+
required: field.required === true || field.rules?.some((rule) => rule.type === "required") === true,
|
|
90
|
+
...(field.sensitive || field.private || field.writeOnly ? { sensitive: true } : {}),
|
|
91
|
+
})),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
async function getSchema(ctx, model) {
|
|
95
|
+
const result = await request(ctx, `/api/database-explorer/models/${encodeURIComponent(model)}/schema?${queryString(ctx)}`);
|
|
96
|
+
if (!result.data)
|
|
97
|
+
throw new Error(`Schema not found for model "${model}".`);
|
|
98
|
+
return result.data;
|
|
99
|
+
}
|
|
100
|
+
function schemaSensitiveFields(schema) {
|
|
101
|
+
const fields = Array.isArray(schema?.fields) ? schema.fields : [];
|
|
102
|
+
return new Set(fields.filter((f) => f.sensitive || f.private || f.writeOnly || isSensitiveField(String(f.name || ""))).map((f) => f.name));
|
|
103
|
+
}
|
|
104
|
+
export function redactDocument(value, schema) {
|
|
105
|
+
const protectedFields = schemaSensitiveFields(schema);
|
|
106
|
+
const visit = (item) => {
|
|
107
|
+
if (Array.isArray(item))
|
|
108
|
+
return item.map(visit);
|
|
109
|
+
if (!item || typeof item !== "object")
|
|
110
|
+
return item;
|
|
111
|
+
const result = {};
|
|
112
|
+
for (const [key, child] of Object.entries(item)) {
|
|
113
|
+
result[key] = isSensitiveField(key) || protectedFields.has(key) ? "[REDACTED]" : visit(child);
|
|
114
|
+
}
|
|
115
|
+
return result;
|
|
116
|
+
};
|
|
117
|
+
return visit(value);
|
|
118
|
+
}
|
|
119
|
+
export function parseJsonOption(value, name) {
|
|
120
|
+
if (!value)
|
|
121
|
+
return undefined;
|
|
122
|
+
try {
|
|
123
|
+
const parsed = JSON.parse(value);
|
|
124
|
+
if (!parsed || Array.isArray(parsed) || typeof parsed !== "object")
|
|
125
|
+
throw new Error();
|
|
126
|
+
return parsed;
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
throw new Error(`--${name} must be a valid JSON object.`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
export function parseSort(value) {
|
|
133
|
+
if (!value)
|
|
134
|
+
return undefined;
|
|
135
|
+
return value.split(",").map((part) => {
|
|
136
|
+
const [field, rawDirection = "asc"] = part.trim().split(":");
|
|
137
|
+
const direction = rawDirection.toLowerCase();
|
|
138
|
+
if (!field || (direction !== "asc" && direction !== "desc"))
|
|
139
|
+
throw new Error("--sort syntax: field:asc,otherField:desc");
|
|
140
|
+
return { field, direction };
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
function scopedField(field) {
|
|
144
|
+
if (field === "_id" || field.startsWith("data."))
|
|
145
|
+
return field;
|
|
146
|
+
return `data.${field}`;
|
|
147
|
+
}
|
|
148
|
+
export function scopedSort(sort) {
|
|
149
|
+
return sort?.map((item) => ({ ...item, field: scopedField(item.field) }));
|
|
150
|
+
}
|
|
151
|
+
export function scopedFilter(filter) {
|
|
152
|
+
const result = {};
|
|
153
|
+
for (const [key, value] of Object.entries(filter)) {
|
|
154
|
+
if (key.startsWith("$")) {
|
|
155
|
+
result[key] = Array.isArray(value) ? value.map((v) => v && typeof v === "object" ? scopedFilter(v) : v) : (value && typeof value === "object" ? scopedFilter(value) : value);
|
|
156
|
+
}
|
|
157
|
+
else {
|
|
158
|
+
if (["serverId", "env", "modelName"].includes(key) || ["data.serverId", "data.env", "data.modelName"].includes(key)) {
|
|
159
|
+
throw new Error(`--filter cannot target reserved field "${key}".`);
|
|
160
|
+
}
|
|
161
|
+
result[scopedField(key)] = value && typeof value === "object" && !Array.isArray(value) ? scopedFilter(value) : value;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return result;
|
|
165
|
+
}
|
|
166
|
+
async function queryDocuments(ctx, model, query) {
|
|
167
|
+
const result = await request(ctx, "/api/database-explorer/collections/modelData/query", {
|
|
168
|
+
method: "POST",
|
|
169
|
+
body: JSON.stringify({ serverId: ctx.serverId, env: ctx.env, modelName: model, query }),
|
|
170
|
+
});
|
|
171
|
+
if (!result.data)
|
|
172
|
+
throw new Error("DB Explorer query returned no data.");
|
|
173
|
+
return result.data;
|
|
174
|
+
}
|
|
175
|
+
function output(value, json) {
|
|
176
|
+
if (json)
|
|
177
|
+
console.log(JSON.stringify(value, null, 2));
|
|
178
|
+
else
|
|
179
|
+
console.log(value);
|
|
180
|
+
}
|
|
181
|
+
function printError(error) {
|
|
182
|
+
console.error(`✖ ${error?.message || "Data exploration failed"}`);
|
|
183
|
+
process.exitCode = 1;
|
|
184
|
+
}
|
|
185
|
+
async function inspectModels(options) {
|
|
186
|
+
try {
|
|
187
|
+
const ctx = await withServer(options);
|
|
188
|
+
const result = await request(ctx, `/api/database-explorer/models?${queryString(ctx)}`);
|
|
189
|
+
const models = result.data?.models || [];
|
|
190
|
+
if (options.json)
|
|
191
|
+
output({ serverId: ctx.serverId, env: ctx.env, models }, true);
|
|
192
|
+
else
|
|
193
|
+
output(models.length ? `Models (${ctx.env}):\n${models.map((name) => ` ${name}`).join("\n")}` : `No models found in ${ctx.env}.`);
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
printError(error);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
async function inspectSchema(model, options) {
|
|
200
|
+
try {
|
|
201
|
+
const ctx = await withServer(options);
|
|
202
|
+
const schema = safeSchema(await getSchema(ctx, model));
|
|
203
|
+
if (options.json)
|
|
204
|
+
output(schema, true);
|
|
205
|
+
else
|
|
206
|
+
output(`${schema.modelName || model} schema (${ctx.env}):\n${schema.fields.map((field) => ` ${field.name}: ${field.type}${field.required ? " (required)" : ""}${field.sensitive ? " (sensitive)" : ""}`).join("\n")}`);
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
printError(error);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
async function dataList(model, options) {
|
|
213
|
+
try {
|
|
214
|
+
const ctx = await withServer(options);
|
|
215
|
+
const page = Number(options.page || 1);
|
|
216
|
+
const pageSize = Number(options.pageSize || 20);
|
|
217
|
+
if (!Number.isInteger(page) || page < 1 || !Number.isInteger(pageSize) || pageSize < 1 || pageSize > 1000)
|
|
218
|
+
throw new Error("--page must be >= 1 and --page-size must be between 1 and 1000.");
|
|
219
|
+
const schema = await getSchema(ctx, model);
|
|
220
|
+
const projection = options.projection?.split(",").map((field) => scopedField(field.trim())).filter(Boolean);
|
|
221
|
+
const data = await queryDocuments(ctx, model, { page, pageSize, sort: scopedSort(parseSort(options.sort)), projection });
|
|
222
|
+
const docs = (data.documents || []).map((doc) => redactDocument(doc, schema));
|
|
223
|
+
const result = { model, env: ctx.env, documents: docs, pagination: data.pagination };
|
|
224
|
+
if (options.json)
|
|
225
|
+
output(result, true);
|
|
226
|
+
else
|
|
227
|
+
output(`${model} (${ctx.env}) — ${data.pagination?.total ?? docs.length} record(s), page ${page}/${data.pagination?.totalPages ?? 1}\n${docs.map((doc) => ` Mongo _id: ${doc._id ?? "—"} | BE data.id: ${doc.data?.id ?? "—"}\n ${JSON.stringify(doc.data ?? doc)}`).join("\n") || " No records found."}`);
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
printError(error);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
async function dataGet(model, id, options) {
|
|
234
|
+
try {
|
|
235
|
+
const ctx = await withServer(options);
|
|
236
|
+
const schema = await getSchema(ctx, model);
|
|
237
|
+
const isMongoId = /^[a-f\d]{24}$/i.test(id);
|
|
238
|
+
const idType = options.idType || (isMongoId ? "auto" : "data");
|
|
239
|
+
if (!["auto", "mongo", "data"].includes(idType))
|
|
240
|
+
throw new Error("--id-type must be auto, mongo, or data.");
|
|
241
|
+
let mongoDoc;
|
|
242
|
+
if (idType === "mongo" || (idType === "auto" && isMongoId)) {
|
|
243
|
+
try {
|
|
244
|
+
const response = await request(ctx, `/api/database-explorer/collections/modelData/${encodeURIComponent(id)}?${queryString(ctx)}`);
|
|
245
|
+
const doc = response.data?.document;
|
|
246
|
+
// The backend detail endpoint looks up by _id without applying server/env/model filters; never display an out-of-scope result.
|
|
247
|
+
if (doc && doc._id && String(doc._id) === id && doc.modelName === model && doc.serverId === ctx.serverId && doc.env === ctx.env)
|
|
248
|
+
mongoDoc = doc;
|
|
249
|
+
else if (idType === "mongo")
|
|
250
|
+
throw new Error(`MongoDB _id was not found for ${model} in the selected server/environment.`);
|
|
251
|
+
}
|
|
252
|
+
catch (error) {
|
|
253
|
+
if (idType === "mongo" || !/not found/i.test(error?.message || ""))
|
|
254
|
+
throw error;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
let logicalDoc;
|
|
258
|
+
if (idType === "data" || idType === "auto") {
|
|
259
|
+
const data = await queryDocuments(ctx, model, { filter: { "data.id": id }, page: 1, pageSize: 2 });
|
|
260
|
+
const matches = data.documents || [];
|
|
261
|
+
if (matches.length > 1)
|
|
262
|
+
throw new Error("More than one record matched BE Studio data.id.");
|
|
263
|
+
logicalDoc = matches[0];
|
|
264
|
+
}
|
|
265
|
+
if (mongoDoc && logicalDoc && String(mongoDoc._id) !== String(logicalDoc._id))
|
|
266
|
+
throw new Error("This value matches both MongoDB _id and BE Studio data.id. Specify --id-type mongo or --id-type data.");
|
|
267
|
+
const doc = mongoDoc || logicalDoc;
|
|
268
|
+
if (!doc)
|
|
269
|
+
throw new Error(`No ${model} record matched that ID in ${ctx.env}.`);
|
|
270
|
+
const safe = redactDocument(doc, schema);
|
|
271
|
+
if (options.json)
|
|
272
|
+
output({ model, env: ctx.env, idType: mongoDoc ? "mongo" : "data", document: safe }, true);
|
|
273
|
+
else
|
|
274
|
+
output(`${model} record (${ctx.env})\n Mongo _id: ${safe._id ?? "—"}\n BE data.id: ${safe.data?.id ?? "—"}\n${JSON.stringify(safe.data ?? safe, null, 2)}`);
|
|
275
|
+
}
|
|
276
|
+
catch (error) {
|
|
277
|
+
printError(error);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
async function dataQuery(model, options) {
|
|
281
|
+
try {
|
|
282
|
+
const ctx = await withServer(options);
|
|
283
|
+
const schema = await getSchema(ctx, model);
|
|
284
|
+
const page = Number(options.page || 1);
|
|
285
|
+
const pageSize = Number(options.pageSize || 20);
|
|
286
|
+
if (!Number.isInteger(page) || page < 1 || !Number.isInteger(pageSize) || pageSize < 1 || pageSize > 1000)
|
|
287
|
+
throw new Error("--page must be >= 1 and --page-size must be between 1 and 1000.");
|
|
288
|
+
const filter = parseJsonOption(options.filter, "filter");
|
|
289
|
+
const projection = options.projection?.split(",").map((field) => scopedField(field.trim())).filter(Boolean);
|
|
290
|
+
const data = await queryDocuments(ctx, model, { filter: filter ? scopedFilter(filter) : undefined, sort: scopedSort(parseSort(options.sort)), projection, page, pageSize });
|
|
291
|
+
const result = { model, env: ctx.env, documents: (data.documents || []).map((doc) => redactDocument(doc, schema)), pagination: data.pagination };
|
|
292
|
+
if (options.json)
|
|
293
|
+
output(result, true);
|
|
294
|
+
else
|
|
295
|
+
output(`${model} query (${ctx.env}) — ${data.pagination?.total ?? result.documents.length} record(s)\n${result.documents.map((doc) => ` Mongo _id: ${doc._id ?? "—"} | BE data.id: ${doc.data?.id ?? "—"}\n ${JSON.stringify(doc.data ?? doc)}`).join("\n") || " No records found."}`);
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
printError(error);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
function sharedOptions(command) {
|
|
302
|
+
return command.option("--server <id-or-name>", "Target server ID or accessible server name")
|
|
303
|
+
.option("--env <environment>", "Environment on the selected target: dev, staging, or prod (default: BESTUDIO_ENV or dev)")
|
|
304
|
+
.option("--local", "Target local BE Studio at http://localhost:3000")
|
|
305
|
+
.option("--url <apiUrl>", "API URL for a custom BE Studio instance; cannot be combined with --local")
|
|
306
|
+
.option("--token <token>", "Access token for this command; otherwise use saved target credentials")
|
|
307
|
+
.option("--json", "Print structured JSON output");
|
|
308
|
+
}
|
|
309
|
+
export const dataExplorationCommand = new Command("inspect")
|
|
310
|
+
.description("Inspect live models and data (read-only)")
|
|
311
|
+
.addHelpText("after", `
|
|
312
|
+
Examples:
|
|
313
|
+
backant inspect models --server my-server
|
|
314
|
+
backant inspect schema User --server my-server --env dev
|
|
315
|
+
`);
|
|
316
|
+
sharedOptions(dataExplorationCommand.command("models").description("List live models"))
|
|
317
|
+
.action(inspectModels);
|
|
318
|
+
sharedOptions(dataExplorationCommand.command("schema <model>").description("Show a live model schema"))
|
|
319
|
+
.action(inspectSchema);
|
|
320
|
+
const dataCommand = new Command("data")
|
|
321
|
+
.description("Read live model records (read-only)")
|
|
322
|
+
.addHelpText("after", `
|
|
323
|
+
Examples:
|
|
324
|
+
backant data list User --server my-server --env dev
|
|
325
|
+
backant data query User --filter '{"active":true}' --server my-server
|
|
326
|
+
`);
|
|
327
|
+
const listCommand = sharedOptions(dataCommand.command("list <model>").description("List model records"));
|
|
328
|
+
listCommand.option("--page <number>", "Page number", "1").option("--page-size <number>", "Records per page (max 1000)", "20").option("--sort <field:direction,...>", "Sort fields, for example createdAt:desc").option("--projection <fields>", "Comma-separated fields to include").action(dataList);
|
|
329
|
+
const getCommand = sharedOptions(dataCommand.command("get <model> <id>").description("Get a record by MongoDB _id or BE Studio data.id"));
|
|
330
|
+
getCommand.option("--id-type <type>", "ID interpretation: auto, mongo, or data", "auto").action(dataGet);
|
|
331
|
+
const queryCommand = sharedOptions(dataCommand.command("query <model>").description("Query model records"));
|
|
332
|
+
queryCommand.option("--filter <json>", "Mongo-style JSON filter").option("--sort <field:direction,...>", "Sort fields, for example createdAt:desc").option("--projection <fields>", "Comma-separated fields to include").option("--page <number>", "Page number", "1").option("--page-size <number>", "Records per page (max 1000)", "20").action(dataQuery);
|
|
333
|
+
// Register as a sibling command: `backant data ...`.
|
|
334
|
+
export const liveDataCommand = dataCommand;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
import { isCanonical, canonicalizeWorkspace, canonicalizeSnapshot, } from "../utils/format-utils.js";
|
|
5
|
+
/**
|
|
6
|
+
* Format command
|
|
7
|
+
*
|
|
8
|
+
* Canonicalizes workspace files for better diff readability.
|
|
9
|
+
* Does NOT touch snapshot, does NOT change hash.
|
|
10
|
+
*/
|
|
11
|
+
async function formatCommand(domain) {
|
|
12
|
+
const projectRoot = process.cwd();
|
|
13
|
+
if (domain) {
|
|
14
|
+
// Format specific domain
|
|
15
|
+
if (domain !== "routes" &&
|
|
16
|
+
domain !== "actions" &&
|
|
17
|
+
domain !== "jobs" &&
|
|
18
|
+
domain !== "models") {
|
|
19
|
+
console.error("✖ Domain must be one of: routes, actions, jobs, models");
|
|
20
|
+
process.exit(1);
|
|
21
|
+
}
|
|
22
|
+
const canonical = isCanonical(domain, projectRoot);
|
|
23
|
+
if (canonical) {
|
|
24
|
+
console.log(`✔ ${domain}: Already canonical`);
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
// Format workspace files
|
|
28
|
+
canonicalizeWorkspace(domain, projectRoot);
|
|
29
|
+
// Format snapshot
|
|
30
|
+
const snapshotPath = path.join(projectRoot, ".bestudio", "snapshot.json");
|
|
31
|
+
if (fs.existsSync(snapshotPath)) {
|
|
32
|
+
const snapshotContent = fs.readFileSync(snapshotPath, "utf-8");
|
|
33
|
+
const snapshot = JSON.parse(snapshotContent);
|
|
34
|
+
const formattedSnapshot = canonicalizeSnapshot(snapshot, domain);
|
|
35
|
+
fs.writeFileSync(snapshotPath, JSON.stringify(formattedSnapshot, null, 2) + "\n", "utf-8");
|
|
36
|
+
}
|
|
37
|
+
console.log(`✔ ${domain}: Formatted`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
// Format all domains
|
|
42
|
+
console.log("📝 Formatting workspace...");
|
|
43
|
+
const routesCanonical = isCanonical("routes", projectRoot);
|
|
44
|
+
const actionsCanonical = isCanonical("actions", projectRoot);
|
|
45
|
+
const jobsCanonical = isCanonical("jobs", projectRoot);
|
|
46
|
+
const modelsCanonical = isCanonical("models", projectRoot);
|
|
47
|
+
if (routesCanonical &&
|
|
48
|
+
actionsCanonical &&
|
|
49
|
+
jobsCanonical &&
|
|
50
|
+
modelsCanonical) {
|
|
51
|
+
console.log("✔ Workspace is already canonical");
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
// Format all domains
|
|
55
|
+
for (const domainToFormat of ["routes", "actions", "jobs", "models"]) {
|
|
56
|
+
canonicalizeWorkspace(domainToFormat, projectRoot);
|
|
57
|
+
}
|
|
58
|
+
// Format snapshot
|
|
59
|
+
const snapshotPath = path.join(projectRoot, ".bestudio", "snapshot.json");
|
|
60
|
+
if (fs.existsSync(snapshotPath)) {
|
|
61
|
+
const snapshotContent = fs.readFileSync(snapshotPath, "utf-8");
|
|
62
|
+
const snapshot = JSON.parse(snapshotContent);
|
|
63
|
+
const formattedSnapshot = canonicalizeSnapshot(snapshot);
|
|
64
|
+
fs.writeFileSync(snapshotPath, JSON.stringify(formattedSnapshot, null, 2) + "\n", "utf-8");
|
|
65
|
+
}
|
|
66
|
+
console.log("✔ Workspace formatted");
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
export const formatCommandDefinition = new Command("format")
|
|
71
|
+
.description("Format workspace files to canonical structure")
|
|
72
|
+
.argument("[domain]", "Domain to format: routes, actions, jobs, or models (optional)")
|
|
73
|
+
.addHelpText("after", `
|
|
74
|
+
Examples:
|
|
75
|
+
backant format
|
|
76
|
+
backant format models
|
|
77
|
+
`)
|
|
78
|
+
.action(formatCommand);
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
import { installProjectSkills } from "../utils/skill-installer.js";
|
|
5
|
+
export const BACKANT_AGENTS_START = "<!-- BEGIN BACKANT INSTRUCTIONS -->";
|
|
6
|
+
export const BACKANT_AGENTS_END = "<!-- END BACKANT INSTRUCTIONS -->";
|
|
7
|
+
const BACKANT_AGENTS_SECTION = `${BACKANT_AGENTS_START}
|
|
8
|
+
## Backant project guidance
|
|
9
|
+
|
|
10
|
+
- Inspect bestudio.config.json and the existing project files before making changes.
|
|
11
|
+
- Use the installed Backant skill in .agents/skills/bestudio/ or .claude/skills/bestudio/ when available; rely on CLI help and validate for the installed version's actual behavior.
|
|
12
|
+
- Follow the project's existing Backant file structure and supported definitions.
|
|
13
|
+
- Run backant validate after changing project definitions.
|
|
14
|
+
- Check the target before pushing: Cloud is the default; use --local only for a local Backant instance. --env selects the environment on that target.
|
|
15
|
+
- Use backant <command> --help to check current CLI commands and options.
|
|
16
|
+
${BACKANT_AGENTS_END}\n`;
|
|
17
|
+
function writeFileIfMissing(filePath, contents) {
|
|
18
|
+
if (!fs.existsSync(filePath)) {
|
|
19
|
+
fs.writeFileSync(filePath, contents, { flag: "wx" });
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function ensureBackantAgentsSection(agentsPath) {
|
|
23
|
+
if (!fs.existsSync(agentsPath)) {
|
|
24
|
+
fs.writeFileSync(agentsPath, BACKANT_AGENTS_SECTION, { flag: "wx" });
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
27
|
+
const stat = fs.lstatSync(agentsPath);
|
|
28
|
+
if (!stat.isFile()) {
|
|
29
|
+
throw new Error("AGENTS.md exists but is not a regular file; refusing to modify it.");
|
|
30
|
+
}
|
|
31
|
+
const existing = fs.readFileSync(agentsPath, "utf8");
|
|
32
|
+
const hasStart = existing.includes(BACKANT_AGENTS_START);
|
|
33
|
+
const hasEnd = existing.includes(BACKANT_AGENTS_END);
|
|
34
|
+
if (hasStart && hasEnd)
|
|
35
|
+
return false;
|
|
36
|
+
if (hasStart || hasEnd) {
|
|
37
|
+
throw new Error("AGENTS.md contains an incomplete Backant instruction section; refusing to modify it.");
|
|
38
|
+
}
|
|
39
|
+
const newline = existing.includes("\r\n") ? "\r\n" : "\n";
|
|
40
|
+
const separator = existing.length === 0 ? "" : existing.endsWith("\n") ? newline : `${newline}${newline}`;
|
|
41
|
+
const section = BACKANT_AGENTS_SECTION.replace(/\n/g, newline);
|
|
42
|
+
fs.writeFileSync(agentsPath, `${existing}${separator}${section}`);
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
export function initializeProject(name, workingDirectory = process.cwd()) {
|
|
46
|
+
const target = path.resolve(workingDirectory, name);
|
|
47
|
+
if (fs.existsSync(target) && !fs.statSync(target).isDirectory()) {
|
|
48
|
+
throw new Error(`Project path exists and is not a directory: ${target}`);
|
|
49
|
+
}
|
|
50
|
+
fs.mkdirSync(target, { recursive: true });
|
|
51
|
+
writeFileIfMissing(path.join(target, "bestudio.config.json"), JSON.stringify({
|
|
52
|
+
name,
|
|
53
|
+
version: "0.1.0",
|
|
54
|
+
schemaVersion: 1,
|
|
55
|
+
autoFormat: true,
|
|
56
|
+
}, null, 2));
|
|
57
|
+
// Create default route scaffold without replacing files in an existing project.
|
|
58
|
+
const helloRouteDir = path.join(target, "routes", "hello");
|
|
59
|
+
fs.mkdirSync(helloRouteDir, { recursive: true });
|
|
60
|
+
writeFileIfMissing(path.join(helloRouteDir, "route.json"), JSON.stringify({
|
|
61
|
+
method: "GET",
|
|
62
|
+
path: "/hello",
|
|
63
|
+
action: "./action.ts",
|
|
64
|
+
}, null, 2));
|
|
65
|
+
writeFileIfMissing(path.join(helloRouteDir, "action.ts"), `export default async function (req, res) {
|
|
66
|
+
res.json({ hello: "world" });
|
|
67
|
+
}
|
|
68
|
+
`);
|
|
69
|
+
// Create optional directories when they do not already exist.
|
|
70
|
+
const optionalDirs = ["jobs", "services", "assets", "models"];
|
|
71
|
+
for (const dir of optionalDirs) {
|
|
72
|
+
fs.mkdirSync(path.join(target, dir), { recursive: true });
|
|
73
|
+
}
|
|
74
|
+
ensureBackantAgentsSection(path.join(target, "AGENTS.md"));
|
|
75
|
+
installProjectSkills(target, { onlyCreateMissing: true });
|
|
76
|
+
return target;
|
|
77
|
+
}
|
|
78
|
+
export const initCommand = new Command("init")
|
|
79
|
+
.description("Create a new BE Studio project scaffold")
|
|
80
|
+
.argument("<name>", "project name")
|
|
81
|
+
.addHelpText("after", `
|
|
82
|
+
Example:
|
|
83
|
+
backant init my-backend
|
|
84
|
+
`)
|
|
85
|
+
.action((name) => {
|
|
86
|
+
try {
|
|
87
|
+
initializeProject(name);
|
|
88
|
+
console.log(`✔ BE Studio project initialized`);
|
|
89
|
+
console.log(`✔ Default route ensured: GET /hello`);
|
|
90
|
+
console.log(`✔ Backant agent instructions ensured: AGENTS.md`);
|
|
91
|
+
console.log(`✔ Backant agent skill ensured: .agents/skills/bestudio and .claude/skills/bestudio`);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
console.error(`✖ ${error.message || "Project initialization failed"}`);
|
|
95
|
+
process.exitCode = 1;
|
|
96
|
+
}
|
|
97
|
+
});
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import readline from "readline";
|
|
3
|
+
import { getConnectionTarget, getTargetApiUrl, saveAuthProfile } from "../utils/connection.js";
|
|
4
|
+
function question(rl, prompt) {
|
|
5
|
+
return new Promise((resolve) => {
|
|
6
|
+
rl.question(prompt, (answer) => {
|
|
7
|
+
resolve(answer);
|
|
8
|
+
});
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
function questionMasked(prompt) {
|
|
12
|
+
return new Promise((resolve) => {
|
|
13
|
+
process.stdout.write(prompt);
|
|
14
|
+
const stdin = process.stdin;
|
|
15
|
+
stdin.setRawMode(true);
|
|
16
|
+
stdin.resume();
|
|
17
|
+
stdin.setEncoding("utf8");
|
|
18
|
+
let password = "";
|
|
19
|
+
const onData = (char) => {
|
|
20
|
+
// Handle special characters
|
|
21
|
+
if (char === "\u0003") {
|
|
22
|
+
// Ctrl+C
|
|
23
|
+
stdin.setRawMode(false);
|
|
24
|
+
stdin.pause();
|
|
25
|
+
stdin.removeListener("data", onData);
|
|
26
|
+
process.exit(0);
|
|
27
|
+
}
|
|
28
|
+
else if (char === "\r" || char === "\n") {
|
|
29
|
+
// Enter
|
|
30
|
+
stdin.setRawMode(false);
|
|
31
|
+
stdin.pause();
|
|
32
|
+
stdin.removeListener("data", onData);
|
|
33
|
+
process.stdout.write("\n");
|
|
34
|
+
resolve(password);
|
|
35
|
+
}
|
|
36
|
+
else if (char === "\u007f" || char === "\b") {
|
|
37
|
+
// Backspace
|
|
38
|
+
if (password.length > 0) {
|
|
39
|
+
password = password.slice(0, -1);
|
|
40
|
+
process.stdout.write("\b \b");
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
// Regular character
|
|
45
|
+
password += char;
|
|
46
|
+
process.stdout.write("*");
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
stdin.on("data", onData);
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
async function promptCredentials() {
|
|
53
|
+
const rl = readline.createInterface({
|
|
54
|
+
input: process.stdin,
|
|
55
|
+
output: process.stdout,
|
|
56
|
+
});
|
|
57
|
+
try {
|
|
58
|
+
const email = await question(rl, "Email: ");
|
|
59
|
+
rl.close();
|
|
60
|
+
const password = await questionMasked("Password: ");
|
|
61
|
+
return { email, password };
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
rl.close();
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
async function loginRequest(apiUrl, email, password) {
|
|
69
|
+
const url = `${apiUrl}/auth/login`;
|
|
70
|
+
let response;
|
|
71
|
+
try {
|
|
72
|
+
response = await fetch(url, {
|
|
73
|
+
method: "POST",
|
|
74
|
+
headers: {
|
|
75
|
+
"Content-Type": "application/json",
|
|
76
|
+
},
|
|
77
|
+
body: JSON.stringify({
|
|
78
|
+
email,
|
|
79
|
+
password,
|
|
80
|
+
}),
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
throw new Error(`Network error: ${error.message || "Failed to connect to server"}`);
|
|
85
|
+
}
|
|
86
|
+
let apiResponse;
|
|
87
|
+
try {
|
|
88
|
+
apiResponse = await response.json();
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
throw new Error("Failed to parse response as JSON");
|
|
92
|
+
}
|
|
93
|
+
// Backend returns { success: false, error: "..." } on failure
|
|
94
|
+
if (!response.ok || !apiResponse.success) {
|
|
95
|
+
const errorMessage = apiResponse.error || response.statusText || "Login failed";
|
|
96
|
+
throw new Error(errorMessage);
|
|
97
|
+
}
|
|
98
|
+
// Validate response structure
|
|
99
|
+
if (!apiResponse.data) {
|
|
100
|
+
throw new Error("Response missing data field");
|
|
101
|
+
}
|
|
102
|
+
const data = apiResponse.data;
|
|
103
|
+
if (!data.token) {
|
|
104
|
+
throw new Error("Response missing token field");
|
|
105
|
+
}
|
|
106
|
+
if (!data.userId) {
|
|
107
|
+
throw new Error("Response missing userId field");
|
|
108
|
+
}
|
|
109
|
+
if (!data.tenantId) {
|
|
110
|
+
throw new Error("Response missing tenantId field");
|
|
111
|
+
}
|
|
112
|
+
return data;
|
|
113
|
+
}
|
|
114
|
+
function saveAuth(target, apiUrl, loginResponse) {
|
|
115
|
+
saveAuthProfile(target, apiUrl, {
|
|
116
|
+
accessToken: loginResponse.token,
|
|
117
|
+
userId: loginResponse.userId,
|
|
118
|
+
tenantId: loginResponse.tenantId,
|
|
119
|
+
loggedInAt: new Date().toISOString(),
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
async function loginCommand(options) {
|
|
123
|
+
try {
|
|
124
|
+
const apiUrl = getTargetApiUrl(options);
|
|
125
|
+
const target = getConnectionTarget(options);
|
|
126
|
+
// Prompt for credentials
|
|
127
|
+
const { email, password } = await promptCredentials();
|
|
128
|
+
// Make login request
|
|
129
|
+
const loginResponse = await loginRequest(apiUrl, email, password);
|
|
130
|
+
// Save auth data
|
|
131
|
+
saveAuth(target, apiUrl, loginResponse);
|
|
132
|
+
console.log(`✔ Logged in to ${options.local ? "local BE Studio" : options.url ? apiUrl : "BE Studio Cloud"} as ${email}`);
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
console.error("✖ Login failed");
|
|
136
|
+
if (error.message) {
|
|
137
|
+
console.error(` ${error.message}`);
|
|
138
|
+
}
|
|
139
|
+
process.exit(1);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
export const loginCommandDefinition = new Command("login")
|
|
143
|
+
.description("Authenticate with BE Studio Cloud or a local instance")
|
|
144
|
+
.option("--local", "Login to local BE Studio at http://localhost:3000")
|
|
145
|
+
.option("--url <url>", "API URL for a custom BE Studio instance")
|
|
146
|
+
.addHelpText("after", `
|
|
147
|
+
Examples:
|
|
148
|
+
backant login
|
|
149
|
+
backant login --local
|
|
150
|
+
|
|
151
|
+
Cloud and local credentials are saved separately. Each target requires a
|
|
152
|
+
one-time login. Use --local on later commands to select the local target.
|
|
153
|
+
`)
|
|
154
|
+
.action(loginCommand);
|