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.
@@ -0,0 +1,135 @@
1
+ import { createHash } from "crypto";
2
+ import fs from "fs";
3
+ import path from "path";
4
+ import { fileURLToPath } from "url";
5
+ import { getCliVersion } from "./package-info.js";
6
+ const moduleDirectory = path.dirname(fileURLToPath(import.meta.url));
7
+ const packageRoot = findCliPackageRoot(moduleDirectory);
8
+ const skillDirectory = path.join(packageRoot, "skills", "bestudio");
9
+ const entrypointPath = path.join(skillDirectory, "project-entrypoint.md");
10
+ const markerPattern = /^(---\r?\n[\s\S]*?\r?\n---\r?\n)<!-- managed-by: backant \| version: ([^ |]+) \| sha256: ([a-f0-9]{64}) -->\r?\n/;
11
+ function findCliPackageRoot(startDirectory) {
12
+ let directory = startDirectory;
13
+ while (true) {
14
+ const packageJsonPath = path.join(directory, "package.json");
15
+ try {
16
+ const metadata = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
17
+ if (metadata.name === "backant-cli")
18
+ return directory;
19
+ }
20
+ catch {
21
+ // Keep walking until the CLI package root is found.
22
+ }
23
+ const parent = path.dirname(directory);
24
+ if (parent === directory) {
25
+ throw new Error("Could not locate the BE Studio CLI package root");
26
+ }
27
+ directory = parent;
28
+ }
29
+ }
30
+ function sha256(value) {
31
+ return createHash("sha256").update(value, "utf8").digest("hex");
32
+ }
33
+ function renderEntrypoint() {
34
+ const template = fs.readFileSync(entrypointPath, "utf8");
35
+ const frontmatterMatch = /^(---\r?\n[\s\S]*?\r?\n---\r?\n)([\s\S]*)$/.exec(template);
36
+ if (!frontmatterMatch) {
37
+ throw new Error("The Backant project skill entrypoint must start with YAML frontmatter");
38
+ }
39
+ const [, frontmatter, body] = frontmatterMatch;
40
+ const marker = `<!-- managed-by: backant | version: ${getCliVersion()} | sha256: ${sha256(`${frontmatter}${body}`)} -->`;
41
+ return `${frontmatter}${marker}\n${body}`;
42
+ }
43
+ function isUnmodifiedManagedEntrypoint(contents) {
44
+ const match = markerPattern.exec(contents);
45
+ if (!match)
46
+ return false;
47
+ const body = contents.slice(match[0].length);
48
+ return sha256(`${match[1]}${body}`) === match[3];
49
+ }
50
+ function readStat(filePath) {
51
+ try {
52
+ return fs.lstatSync(filePath);
53
+ }
54
+ catch (error) {
55
+ if (error.code === "ENOENT")
56
+ return null;
57
+ throw error;
58
+ }
59
+ }
60
+ function ensureSafeSkillDirectory(projectDirectory, skillRoot) {
61
+ let currentDirectory = projectDirectory;
62
+ for (const segment of [...skillRoot, "bestudio"]) {
63
+ currentDirectory = path.join(currentDirectory, segment);
64
+ const stat = readStat(currentDirectory);
65
+ if (stat?.isSymbolicLink())
66
+ return `Refusing to follow symbolic link: ${currentDirectory}`;
67
+ if (stat && !stat.isDirectory())
68
+ return `Expected a directory at ${currentDirectory}`;
69
+ if (!stat)
70
+ fs.mkdirSync(currentDirectory);
71
+ }
72
+ return null;
73
+ }
74
+ export function installProjectSkills(projectDirectory, options = {}) {
75
+ if (!fs.existsSync(entrypointPath)) {
76
+ throw new Error(`Bundled Backant project skill entrypoint was not found at ${entrypointPath}`);
77
+ }
78
+ const nextEntrypoint = renderEntrypoint();
79
+ const result = { created: [], updated: [], unchanged: [], skipped: [] };
80
+ for (const skillRoot of [[".agents", "skills"], [".claude", "skills"]]) {
81
+ const relativePath = path.join(...skillRoot, "bestudio", "SKILL.md");
82
+ const directoryError = ensureSafeSkillDirectory(projectDirectory, skillRoot);
83
+ if (directoryError) {
84
+ result.skipped.push(`${relativePath}: ${directoryError}`);
85
+ continue;
86
+ }
87
+ const destination = path.join(projectDirectory, relativePath);
88
+ const stat = readStat(destination);
89
+ if (stat?.isSymbolicLink() || (stat && !stat.isFile())) {
90
+ result.skipped.push(`${relativePath}: existing path is not a regular file`);
91
+ continue;
92
+ }
93
+ if (!stat) {
94
+ fs.writeFileSync(destination, nextEntrypoint, { flag: "wx" });
95
+ result.created.push(relativePath);
96
+ continue;
97
+ }
98
+ const currentEntrypoint = fs.readFileSync(destination, "utf8");
99
+ if (currentEntrypoint === nextEntrypoint) {
100
+ result.unchanged.push(relativePath);
101
+ continue;
102
+ }
103
+ if (options.onlyCreateMissing) {
104
+ result.skipped.push(`${relativePath}: already exists`);
105
+ continue;
106
+ }
107
+ if (options.force || isUnmodifiedManagedEntrypoint(currentEntrypoint)) {
108
+ fs.writeFileSync(destination, nextEntrypoint);
109
+ result.updated.push(relativePath);
110
+ continue;
111
+ }
112
+ result.skipped.push(`${relativePath}: user-modified or unrecognized content`);
113
+ }
114
+ return result;
115
+ }
116
+ export function getProjectSkillVersionInfo(projectDirectory) {
117
+ const currentVersion = getCliVersion();
118
+ const installedVersions = new Set();
119
+ for (const skillRoot of [[".agents", "skills"], [".claude", "skills"]]) {
120
+ const relativePath = path.join(...skillRoot, "bestudio", "SKILL.md");
121
+ const skillPath = path.join(projectDirectory, relativePath);
122
+ const stat = readStat(skillPath);
123
+ if (!stat?.isFile() || stat.isSymbolicLink())
124
+ continue;
125
+ const contents = fs.readFileSync(skillPath, "utf8");
126
+ const match = markerPattern.exec(contents);
127
+ if (!match)
128
+ continue;
129
+ const body = contents.slice(match[0].length);
130
+ if (sha256(`${match[1]}${body}`) !== match[3] || match[2] === currentVersion)
131
+ continue;
132
+ installedVersions.add(match[2]);
133
+ }
134
+ return [...installedVersions].map((version) => `Local skill version (${version}) differs from CLI (${currentVersion}). Run 'backant skill sync' to update.`);
135
+ }
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Snapshot Writer Utilities
3
+ *
4
+ * Writes snapshot data to workspace files.
5
+ * Used by pull command to sync backend state to local workspace.
6
+ */
7
+ import fs from "fs";
8
+ import path from "path";
9
+ import { canonicalizeJson } from "./format-utils.js";
10
+ function resolveSafeWorkspacePath(projectRoot, relativePath) {
11
+ const resolvedRoot = path.resolve(projectRoot);
12
+ const resolvedTarget = path.resolve(resolvedRoot, relativePath);
13
+ if (resolvedTarget !== resolvedRoot &&
14
+ !resolvedTarget.startsWith(resolvedRoot + path.sep)) {
15
+ return null;
16
+ }
17
+ return resolvedTarget;
18
+ }
19
+ /**
20
+ * Write routes from snapshot to workspace
21
+ * Each route uses its own file.entry path
22
+ */
23
+ export function writeRoutesFromSnapshot(snapshot, projectRoot) {
24
+ if (!snapshot.routes || !Array.isArray(snapshot.routes)) {
25
+ return;
26
+ }
27
+ for (const route of snapshot.routes) {
28
+ if (!route.file?.entry) {
29
+ console.warn(`⚠ Route ${route.id} missing file.entry, skipping write to workspace.`);
30
+ continue;
31
+ }
32
+ // Use route's file.entry path
33
+ const routeJsonPath = resolveSafeWorkspacePath(projectRoot, route.file.entry);
34
+ if (!routeJsonPath) {
35
+ console.warn(`⚠ Route ${route.id} has unsafe file.entry path, skipping.`);
36
+ continue;
37
+ }
38
+ const routeDir = path.dirname(routeJsonPath);
39
+ // Create directory if it doesn't exist
40
+ if (!fs.existsSync(routeDir)) {
41
+ fs.mkdirSync(routeDir, { recursive: true });
42
+ }
43
+ let resolvedFlow = route.flowId || route.flow;
44
+ if (!resolvedFlow && !route.actionId && fs.existsSync(routeJsonPath)) {
45
+ try {
46
+ const existing = JSON.parse(fs.readFileSync(routeJsonPath, "utf-8"));
47
+ if (typeof existing?.flow === "string" && existing.flow.trim() !== "") {
48
+ resolvedFlow = existing.flow;
49
+ }
50
+ }
51
+ catch {
52
+ // Ignore parse error on existing file
53
+ }
54
+ }
55
+ // Write route.json preserving flow routes
56
+ const routeJson = resolvedFlow
57
+ ? {
58
+ method: route.method,
59
+ path: route.path,
60
+ flow: resolvedFlow,
61
+ }
62
+ : {
63
+ method: route.method,
64
+ path: route.path,
65
+ action: "./action.ts",
66
+ };
67
+ fs.writeFileSync(routeJsonPath, canonicalizeJson(routeJson, ["method", "path", "action", "flow"]), "utf-8");
68
+ }
69
+ }
70
+ /**
71
+ * Write actions from snapshot to workspace
72
+ * Each action uses its own file.entry path
73
+ */
74
+ export function writeActionsFromSnapshot(snapshot, projectRoot) {
75
+ if (!snapshot.actions || !Array.isArray(snapshot.actions)) {
76
+ return;
77
+ }
78
+ for (const action of snapshot.actions) {
79
+ if (!action.file?.entry) {
80
+ console.warn(`⚠ Action ${action.id} missing file.entry, skipping write to workspace.`);
81
+ continue;
82
+ }
83
+ // Use action's file.entry path
84
+ const actionPath = path.join(projectRoot, action.file.entry);
85
+ const actionDir = path.dirname(actionPath);
86
+ // Create directory if it doesn't exist
87
+ if (!fs.existsSync(actionDir)) {
88
+ fs.mkdirSync(actionDir, { recursive: true });
89
+ }
90
+ // Normalize line endings to LF
91
+ const actionCode = action.code.replace(/\r\n/g, "\n");
92
+ fs.writeFileSync(actionPath, actionCode, "utf-8");
93
+ // Write config.ts if configCode exists (in same directory as action)
94
+ if (action.configCode) {
95
+ const configPath = path.join(actionDir, "config.ts");
96
+ const configCode = action.configCode.replace(/\r\n/g, "\n");
97
+ fs.writeFileSync(configPath, configCode, "utf-8");
98
+ }
99
+ }
100
+ }
101
+ /**
102
+ * Write jobs from snapshot to workspace
103
+ * Each job uses its own file.entry path
104
+ */
105
+ export function writeJobsFromSnapshot(snapshot, projectRoot) {
106
+ if (!snapshot.jobs || !Array.isArray(snapshot.jobs)) {
107
+ return;
108
+ }
109
+ for (const job of snapshot.jobs) {
110
+ if (!job.file?.entry) {
111
+ console.warn(`⚠ Job ${job.id} missing file.entry, skipping write to workspace.`);
112
+ continue;
113
+ }
114
+ // Use job's file.entry path
115
+ const jobPath = path.join(projectRoot, job.file.entry);
116
+ const jobDir = path.dirname(jobPath);
117
+ // Create directory if it doesn't exist
118
+ if (!fs.existsSync(jobDir)) {
119
+ fs.mkdirSync(jobDir, { recursive: true });
120
+ }
121
+ // Normalize line endings to LF
122
+ const jobCode = job.code.replace(/\r\n/g, "\n");
123
+ fs.writeFileSync(jobPath, jobCode, "utf-8");
124
+ }
125
+ }
126
+ /**
127
+ * Write models from snapshot to workspace
128
+ * Each model uses its own file.entry path
129
+ */
130
+ export function writeModelsFromSnapshot(snapshot, projectRoot) {
131
+ if (!snapshot.models || !Array.isArray(snapshot.models)) {
132
+ return;
133
+ }
134
+ for (const model of snapshot.models) {
135
+ if (!model.file?.entry) {
136
+ console.warn(`⚠ Model ${model.modelName} missing file.entry, skipping write to workspace.`);
137
+ continue;
138
+ }
139
+ // Use model's file.entry path
140
+ const modelPath = path.join(projectRoot, model.file.entry);
141
+ const modelDir = path.dirname(modelPath);
142
+ // Create directory if it doesn't exist
143
+ if (!fs.existsSync(modelDir)) {
144
+ fs.mkdirSync(modelDir, { recursive: true });
145
+ }
146
+ // Write model.json (canonicalized)
147
+ const modelJson = {
148
+ modelName: model.modelName,
149
+ fields: model.fields,
150
+ indexes: model.indexes || [],
151
+ uniqueConstraints: model.uniqueConstraints || [],
152
+ };
153
+ // Only include optional fields if they exist and are not null
154
+ if (model.options) {
155
+ modelJson.options = model.options;
156
+ }
157
+ if (model.hooks) {
158
+ modelJson.hooks = model.hooks;
159
+ }
160
+ if (model.metadata) {
161
+ modelJson.metadata = model.metadata;
162
+ }
163
+ fs.writeFileSync(modelPath, canonicalizeJson(modelJson), "utf-8");
164
+ }
165
+ }
166
+ /**
167
+ * Write flows from snapshot to workspace
168
+ * Each flow uses its own file.entry path (or flows/<id>/flow.json)
169
+ */
170
+ export function writeFlowsFromSnapshot(snapshot, projectRoot) {
171
+ if (!snapshot.flows || !Array.isArray(snapshot.flows)) {
172
+ return;
173
+ }
174
+ for (const flowItem of snapshot.flows) {
175
+ const entryRelative = flowItem.file?.entry ||
176
+ (flowItem.id ? path.join("flows", flowItem.id, "flow.json") : null);
177
+ if (!entryRelative || !flowItem.flow) {
178
+ console.warn(`⚠ Flow ${flowItem.id || "unknown"} missing file.entry or flow body, skipping write to workspace.`);
179
+ continue;
180
+ }
181
+ const flowPath = resolveSafeWorkspacePath(projectRoot, entryRelative);
182
+ if (!flowPath) {
183
+ console.warn(`⚠ Flow ${flowItem.id || "unknown"} has unsafe file.entry path, skipping.`);
184
+ continue;
185
+ }
186
+ const flowDir = path.dirname(flowPath);
187
+ if (!fs.existsSync(flowDir)) {
188
+ fs.mkdirSync(flowDir, { recursive: true });
189
+ }
190
+ fs.writeFileSync(flowPath, JSON.stringify(flowItem.flow, null, 2) + "\n", "utf-8");
191
+ }
192
+ }
193
+ /**
194
+ * Write snapshot to workspace for a specific domain
195
+ */
196
+ export function writeSnapshotToWorkspace(snapshot, projectRoot, domain) {
197
+ switch (domain) {
198
+ case "routes":
199
+ writeRoutesFromSnapshot(snapshot, projectRoot);
200
+ break;
201
+ case "actions":
202
+ writeActionsFromSnapshot(snapshot, projectRoot);
203
+ break;
204
+ case "jobs":
205
+ writeJobsFromSnapshot(snapshot, projectRoot);
206
+ break;
207
+ case "models":
208
+ writeModelsFromSnapshot(snapshot, projectRoot);
209
+ break;
210
+ case "flows":
211
+ writeFlowsFromSnapshot(snapshot, projectRoot);
212
+ break;
213
+ default:
214
+ throw new Error(`Unknown domain: ${domain}`);
215
+ }
216
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "backant-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Command-line tooling for developing and deploying BE Studio projects.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/frknrhn/backant-cli.git"
8
+ },
9
+ "homepage": "https://github.com/frknrhn/backant-cli#readme",
10
+ "keywords": ["backant", "be-studio", "backend", "cli"],
11
+ "type": "module",
12
+ "engines": {
13
+ "node": ">=20"
14
+ },
15
+ "files": ["dist", "bin", "skills"],
16
+ "bin": {
17
+ "backant": "bin/backant.js"
18
+ },
19
+ "scripts": {
20
+ "build": "tsc",
21
+ "dev": "ts-node src/index.ts",
22
+ "link": "npm run build && npm link",
23
+ "check:golden": "node scripts/check-golden-projects.mjs",
24
+ "check:package": "node scripts/check-package-contents.mjs",
25
+ "test": "npm run build && tsc -p tsconfig.test.json && node --test dist-test/tests/*.test.js"
26
+ },
27
+ "dependencies": {
28
+ "commander": "^12.0.0"
29
+ },
30
+ "devDependencies": {
31
+ "typescript": "^5.4.0",
32
+ "ts-node": "^10.9.2",
33
+ "@types/node": "^20.0.0"
34
+ }
35
+ }
36
+
@@ -0,0 +1,36 @@
1
+ ---
2
+ name: bestudio
3
+ description: Use when creating, inspecting, validating, or deploying a BE Studio (Backant) project with the backant CLI.
4
+ ---
5
+
6
+ # Work with Backant projects
7
+
8
+ Backant is a backend platform whose project definitions can be managed as files and deployed with the `backant` CLI. Follow the project’s existing structure and let the CLI validate changes before reporting them complete.
9
+
10
+ ## Discover before changing
11
+
12
+ - Read the project’s `AGENTS.md` and `bestudio.config.json`, then inspect the files related to the requested change.
13
+ - Start with `backant --help`; use `backant <command> --help` before relying on unfamiliar arguments or options.
14
+ - The installed CLI is authoritative for available commands. Do not assume a command exists because another platform has it.
15
+ - Reuse valid project examples where available. If the project has no relevant example, consult `references/project-definitions.md` for the supported model and flow basics.
16
+
17
+ ## Make focused changes
18
+
19
+ - Keep edits within the requested project area and preserve unrelated files and user instructions.
20
+ - Do not invent schemas, fields, node types, or runtime APIs. Use existing definitions, the reference file, and validation errors as evidence.
21
+ - For Flow action code, follow the `(ctx, input)` interface described in the project definitions reference.
22
+ - Do not expose credentials, tokens, or secret values in files, command output, or the final response.
23
+
24
+ ## Validate in a closed loop
25
+
26
+ 1. Run `backant validate` after making project definition changes.
27
+ 2. If it reports errors, inspect the named file and message, fix the cause, and run validation again.
28
+ 3. Continue until validation succeeds. Report any remaining warning or limitation accurately.
29
+ 4. Do not claim the project is valid based only on successfully writing files.
30
+
31
+ ## Push only when requested
32
+
33
+ - Confirm the requested target environment before deployment. `--env` selects the environment; it does not select the server.
34
+ - Do not push unless the user asks to deploy or push. Never target production unless the user explicitly requests it.
35
+ - The CLI defaults to BE Studio Cloud. Check `backant push --help` for the current options before pushing.
36
+ - After an explicitly requested push, report the selected environment and the CLI result.
@@ -0,0 +1,12 @@
1
+ ---
2
+ name: bestudio
3
+ description: Use when creating, inspecting, validating, or deploying a BE Studio (Backant) project with the backant CLI.
4
+ ---
5
+
6
+ # Backant project entrypoint
7
+
8
+ This project-local skill is intentionally small. Before changing Backant definitions, run `backant skill show` and follow the current workflow and safety instructions printed by the installed CLI.
9
+
10
+ When changing models or Flows, also run `backant skill show --ref project-definitions` and follow the supported structures there. The CLI output is the current source of truth; do not rely on remembered or invented commands and schemas.
11
+
12
+ Run `backant validate` after changing project definitions. Fix reported issues and validate again before saying the work is complete. Do not push or deploy unless the user explicitly requests it.
@@ -0,0 +1,24 @@
1
+ # Model and Flow definitions
2
+
3
+ Use this reference only when the task changes a model or Flow. Prefer valid examples already present in the project; `backant validate` is the final structural check.
4
+
5
+ ## Models
6
+
7
+ - Store each model in `models/<model-folder>/model.json`.
8
+ - `modelName` is required, starts with an uppercase letter, and contains only letters and numbers.
9
+ - The folder name must match `modelName` case-insensitively. For example, `ShortsProject` belongs in `models/shortsproject/` under the current validator.
10
+ - `fields` must be a non-empty array. Each field needs `name`, `type`, and a `rules` array (which can be empty).
11
+ - Supported field types are `string`, `number`, `boolean`, `date`, `object`, `array`, and `objectId`.
12
+ - Indexes are optional; each index needs a non-empty `fields` array.
13
+
14
+ ## Flows
15
+
16
+ - Store each Flow in `flows/<flow-id>/flow.json`.
17
+ - The root object needs a non-empty `entry` node ID and a `nodes` object. The entry value must be a key in `nodes`.
18
+ - Each node’s `id` must match its key. `nodeName` must be unique within the Flow and match `/^[a-zA-Z][a-zA-Z0-9_]*$/`.
19
+ - Supported node types are `trigger`, `action`, `if`, `switch`, `loop`, `parallel`, `retry`, `delay`, `subflow`, and `human`.
20
+ - A node transition uses an object such as `"next": { "nodeId": "saveProject" }`; the referenced node must exist.
21
+ - An `action` needs non-empty code using the `(ctx, input)` signature. The Flow runtime exposes model operations through `ctx.models`.
22
+ - An `if` node needs a non-empty `condition` and a valid `then` reference; `else` is optional.
23
+
24
+ For less common node types, inspect a working project example and the detailed errors from `backant validate`. Do not infer runtime behavior from structural validity alone.