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,1429 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
import { execSync } from "child_process";
|
|
5
|
+
import { scanJobs } from "../utils/job-scanner.js";
|
|
6
|
+
import { scanServices } from "../utils/services-scanner.js";
|
|
7
|
+
import { scanAssets } from "../utils/assets-scanner.js";
|
|
8
|
+
import { scanModels } from "../utils/model-scanner.js";
|
|
9
|
+
import { scanFlowsDetailed } from "../utils/flow-scanner.js";
|
|
10
|
+
import { isCanonical } from "../utils/format-utils.js";
|
|
11
|
+
import { getProjectSkillVersionInfo } from "../utils/skill-installer.js";
|
|
12
|
+
function createValidationContext() {
|
|
13
|
+
return {
|
|
14
|
+
errors: [],
|
|
15
|
+
warnings: [],
|
|
16
|
+
stats: {
|
|
17
|
+
routes: 0,
|
|
18
|
+
actions: 0,
|
|
19
|
+
jobs: 0,
|
|
20
|
+
models: 0,
|
|
21
|
+
flows: 0,
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function addError(ctx, filePath, message) {
|
|
26
|
+
ctx.errors.push({ path: filePath, message });
|
|
27
|
+
}
|
|
28
|
+
function addWarning(ctx, filePath, message) {
|
|
29
|
+
ctx.warnings.push({ path: filePath, message });
|
|
30
|
+
}
|
|
31
|
+
function validateConfig(configPath, ctx) {
|
|
32
|
+
if (!fs.existsSync(configPath)) {
|
|
33
|
+
addError(ctx, "bestudio.config.json", "config file not found");
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
try {
|
|
37
|
+
const content = fs.readFileSync(configPath, "utf-8");
|
|
38
|
+
const config = JSON.parse(content);
|
|
39
|
+
if (!config.name || !config.version || !config.schemaVersion) {
|
|
40
|
+
addError(ctx, "bestudio.config.json", "missing required fields: name, version, or schemaVersion");
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
const applicationAuth = config.applicationAuth;
|
|
44
|
+
if (applicationAuth !== undefined) {
|
|
45
|
+
if (!applicationAuth || typeof applicationAuth !== "object" || Array.isArray(applicationAuth)) {
|
|
46
|
+
addError(ctx, "bestudio.config.json", "applicationAuth must be an object");
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
if (!["basic-auth", "role-based", "saas", "advanced-access-control"].includes(applicationAuth.template))
|
|
50
|
+
addError(ctx, "bestudio.config.json", "applicationAuth.template must be basic-auth, role-based, saas, or advanced-access-control");
|
|
51
|
+
if (applicationAuth.enabled !== undefined && typeof applicationAuth.enabled !== "boolean")
|
|
52
|
+
addError(ctx, "bestudio.config.json", "applicationAuth.enabled must be boolean");
|
|
53
|
+
if (applicationAuth.profileFields !== undefined && (!Array.isArray(applicationAuth.profileFields) || applicationAuth.profileFields.some((field) => typeof field !== "string" || !/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(field) || /(password|secret|token|credential|hash|authorization|cookie)/i.test(field))))
|
|
54
|
+
addError(ctx, "bestudio.config.json", "applicationAuth.profileFields contains an invalid or reserved field");
|
|
55
|
+
if (applicationAuth.roles !== undefined && (!Array.isArray(applicationAuth.roles) || applicationAuth.roles.some((role) => !role || typeof role.name !== "string" || !Array.isArray(role.permissions) || role.permissions.some((permission) => typeof permission !== "string" || (permission !== "*" && !/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,127}$/.test(permission))))))
|
|
56
|
+
addError(ctx, "bestudio.config.json", "applicationAuth.roles must contain role names and permission arrays");
|
|
57
|
+
if (applicationAuth.defaultRole !== undefined && !applicationAuth.roles?.some((role) => role.name === applicationAuth.defaultRole))
|
|
58
|
+
addError(ctx, "bestudio.config.json", "applicationAuth.defaultRole must refer to a configured role");
|
|
59
|
+
if (applicationAuth.email !== undefined && (!applicationAuth.email || typeof applicationAuth.email !== "object" || typeof applicationAuth.email.publicBaseUrl !== "string" || typeof applicationAuth.email.verificationEnabled !== "boolean" || typeof applicationAuth.email.passwordResetEnabled !== "boolean"))
|
|
60
|
+
addError(ctx, "bestudio.config.json", "applicationAuth.email requires publicBaseUrl, verificationEnabled, and passwordResetEnabled");
|
|
61
|
+
if ((applicationAuth.template === "saas" || applicationAuth.template === "advanced-access-control") && (applicationAuth.organizationsEnabled !== true || applicationAuth.dataAccessMode !== "deny-unconfigured"))
|
|
62
|
+
addError(ctx, "bestudio.config.json", "SaaS and Advanced Access Control require organizationsEnabled and deny-unconfigured data access");
|
|
63
|
+
if (applicationAuth.customPolicies !== undefined && (!applicationAuth.customPolicies || typeof applicationAuth.customPolicies !== "object" || Array.isArray(applicationAuth.customPolicies)))
|
|
64
|
+
addError(ctx, "bestudio.config.json", "applicationAuth.customPolicies must be an object");
|
|
65
|
+
if (applicationAuth.dataPolicies !== undefined && (!applicationAuth.dataPolicies || typeof applicationAuth.dataPolicies !== "object" || Array.isArray(applicationAuth.dataPolicies)))
|
|
66
|
+
addError(ctx, "bestudio.config.json", "applicationAuth.dataPolicies must be an object");
|
|
67
|
+
if (applicationAuth.dataPolicies && typeof applicationAuth.dataPolicies === "object") {
|
|
68
|
+
for (const [modelName, policy] of Object.entries(applicationAuth.dataPolicies)) {
|
|
69
|
+
if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(modelName) || !policy || typeof policy !== "object") {
|
|
70
|
+
addError(ctx, "bestudio.config.json", `Invalid model access policy: ${modelName}`);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
for (const operation of ["read", "create", "update", "delete"]) {
|
|
74
|
+
const rule = policy[operation];
|
|
75
|
+
if (!rule || typeof rule !== "object" || !["deny", "public", "authenticated", "user", "organization"].includes(rule.scope))
|
|
76
|
+
addError(ctx, "bestudio.config.json", `Invalid ${modelName}.${operation} data policy`);
|
|
77
|
+
if (rule?.scope === "user" && typeof rule.ownerField !== "string")
|
|
78
|
+
addError(ctx, "bestudio.config.json", `${modelName}.${operation} user scope requires ownerField`);
|
|
79
|
+
if (rule?.scope === "organization" && (applicationAuth.organizationsEnabled !== true || typeof rule.organizationField !== "string"))
|
|
80
|
+
addError(ctx, "bestudio.config.json", `${modelName}.${operation} organization scope requires organizationsEnabled and organizationField`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return config;
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
addError(ctx, "bestudio.config.json", `JSON parse error: ${error.message}`);
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function validateRouteJson(routeJsonPath, ctx) {
|
|
94
|
+
if (!fs.existsSync(routeJsonPath)) {
|
|
95
|
+
addError(ctx, routeJsonPath, "route.json file not found");
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
const content = fs.readFileSync(routeJsonPath, "utf-8");
|
|
100
|
+
const routeJson = JSON.parse(content);
|
|
101
|
+
const validMethods = ["GET", "POST", "PUT", "DELETE", "PATCH"];
|
|
102
|
+
if (!routeJson.method || !validMethods.includes(routeJson.method)) {
|
|
103
|
+
addError(ctx, routeJsonPath, `invalid method: ${routeJson.method}. Must be one of: ${validMethods.join(", ")}`);
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
if (!routeJson.path ||
|
|
107
|
+
typeof routeJson.path !== "string" ||
|
|
108
|
+
!routeJson.path.startsWith("/")) {
|
|
109
|
+
addError(ctx, routeJsonPath, `invalid path: ${routeJson.path}. Must be a string starting with "/"`);
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
if (!routeJson.action && !routeJson.flow) {
|
|
113
|
+
addError(ctx, routeJsonPath, `invalid route definition: must specify either "action" or "flow"`);
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
if (routeJson.metadata !== undefined) {
|
|
117
|
+
if (!routeJson.metadata || typeof routeJson.metadata !== "object" || Array.isArray(routeJson.metadata)) {
|
|
118
|
+
addError(ctx, routeJsonPath, "metadata must be an object");
|
|
119
|
+
}
|
|
120
|
+
else if (routeJson.metadata.auth !== undefined) {
|
|
121
|
+
const auth = routeJson.metadata.auth;
|
|
122
|
+
if (!auth || typeof auth !== "object" || Array.isArray(auth))
|
|
123
|
+
addError(ctx, routeJsonPath, "metadata.auth must be an object");
|
|
124
|
+
else {
|
|
125
|
+
if (auth.required !== undefined && typeof auth.required !== "boolean")
|
|
126
|
+
addError(ctx, routeJsonPath, "metadata.auth.required must be boolean");
|
|
127
|
+
for (const key of ["roles", "permissions", "scopes", "organizationRoles", "organizationPermissions", "policies"])
|
|
128
|
+
if (auth[key] !== undefined && (!Array.isArray(auth[key]) || auth[key].some((value) => typeof value !== "string")))
|
|
129
|
+
addError(ctx, routeJsonPath, `metadata.auth.${key} must be a string array`);
|
|
130
|
+
if (auth.organizationRequired !== undefined && typeof auth.organizationRequired !== "boolean")
|
|
131
|
+
addError(ctx, routeJsonPath, "metadata.auth.organizationRequired must be boolean");
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return routeJson;
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
addError(ctx, routeJsonPath, `JSON parse error: ${error.message}`);
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
function validateActionFile(actionPath, routeJsonPath, ctx) {
|
|
143
|
+
const fullPath = path.resolve(path.dirname(routeJsonPath), actionPath);
|
|
144
|
+
if (!fs.existsSync(fullPath)) {
|
|
145
|
+
addError(ctx, actionPath, "action file not found");
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
if (!fullPath.endsWith(".ts")) {
|
|
149
|
+
addError(ctx, actionPath, "action file must have .ts extension");
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
const content = fs.readFileSync(fullPath, "utf-8");
|
|
153
|
+
// Check for inline function syntax (basic check)
|
|
154
|
+
if (content.includes("export default (") ||
|
|
155
|
+
content.includes("export default async (") ||
|
|
156
|
+
/export\s+default\s+(async\s+)?\(/.test(content)) {
|
|
157
|
+
addError(ctx, actionPath, "inline function not allowed. Use: export default async function (...) {}");
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
// Check for default export
|
|
161
|
+
const defaultExportRegex = /export\s+default\s+(async\s+)?function/;
|
|
162
|
+
if (!defaultExportRegex.test(content)) {
|
|
163
|
+
addError(ctx, actionPath, "action file must have default export: export default async function (...) {}");
|
|
164
|
+
return false;
|
|
165
|
+
}
|
|
166
|
+
// Reject named exports
|
|
167
|
+
const namedExportRegex = /export\s+(const|let|var|function|async\s+function)\s+\w+\s*=/;
|
|
168
|
+
if (namedExportRegex.test(content) && !defaultExportRegex.test(content)) {
|
|
169
|
+
addError(ctx, actionPath, "action file must use default export, not named export");
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
return true;
|
|
173
|
+
}
|
|
174
|
+
function validateConfigFile(actionPath, routeJsonPath, ctx) {
|
|
175
|
+
// config.ts should be in the same directory as the action file
|
|
176
|
+
const actionDir = path.dirname(path.resolve(path.dirname(routeJsonPath), actionPath));
|
|
177
|
+
const configPath = path.join(actionDir, "config.ts");
|
|
178
|
+
// Config is optional - no error if missing
|
|
179
|
+
if (!fs.existsSync(configPath)) {
|
|
180
|
+
return true;
|
|
181
|
+
}
|
|
182
|
+
const content = fs.readFileSync(configPath, "utf-8");
|
|
183
|
+
// 1. Check for export const pattern
|
|
184
|
+
const exportConstRegex = /export\s+const\s+\w+\s*=/;
|
|
185
|
+
if (!exportConstRegex.test(content)) {
|
|
186
|
+
addError(ctx, configPath, "config.ts must use 'export const' format (e.g., export const total_chars = { value: 3500, options: {...} })");
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
// 2. Check for { value, options } pattern (more flexible regex)
|
|
190
|
+
// Look for object with both value and options properties
|
|
191
|
+
const hasValueAndOptions = /value\s*[:=]/.test(content) && /options\s*[:=]/.test(content);
|
|
192
|
+
if (!hasValueAndOptions) {
|
|
193
|
+
addError(ctx, configPath, "config fields must have { value, options } structure");
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
// 3. Check for options.type
|
|
197
|
+
const typePattern = /options\s*:\s*\{[^}]*type\s*:/;
|
|
198
|
+
if (!typePattern.test(content)) {
|
|
199
|
+
addError(ctx, configPath, "config fields must have options.type");
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
// 4. Check for options.label
|
|
203
|
+
const labelPattern = /options\s*:\s*\{[^}]*label\s*:/;
|
|
204
|
+
if (!labelPattern.test(content)) {
|
|
205
|
+
addError(ctx, configPath, "config fields must have options.label");
|
|
206
|
+
return false;
|
|
207
|
+
}
|
|
208
|
+
// 5. Check for valid type values
|
|
209
|
+
const validTypes = ["number", "string", "boolean", "select"];
|
|
210
|
+
const typeMatches = content.matchAll(/type\s*:\s*["']([^"']+)["']/g);
|
|
211
|
+
for (const match of typeMatches) {
|
|
212
|
+
const typeValue = match[1];
|
|
213
|
+
if (!validTypes.includes(typeValue)) {
|
|
214
|
+
addError(ctx, configPath, `options.type must be one of: ${validTypes.join(", ")}. Found: "${typeValue}"`);
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
// 6. Check for value type consistency (basic check)
|
|
219
|
+
// If type is "number", value should be a number
|
|
220
|
+
// If type is "string", value should be a string
|
|
221
|
+
// If type is "boolean", value should be a boolean
|
|
222
|
+
// If type is "select", value should be in choices array
|
|
223
|
+
const configFields = content.matchAll(/export\s+const\s+(\w+)\s*=\s*\{[^}]*value\s*:\s*([^,}]+)[^}]*options\s*:\s*\{[^}]*type\s*:\s*["']([^"']+)["']/gs);
|
|
224
|
+
for (const match of configFields) {
|
|
225
|
+
const fieldName = match[1];
|
|
226
|
+
const valueStr = match[2].trim();
|
|
227
|
+
const typeValue = match[3];
|
|
228
|
+
// Basic type checking
|
|
229
|
+
if (typeValue === "number") {
|
|
230
|
+
const numValue = parseFloat(valueStr);
|
|
231
|
+
if (isNaN(numValue)) {
|
|
232
|
+
addError(ctx, configPath, `Field "${fieldName}": value must be a number when options.type is "number"`);
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
else if (typeValue === "string") {
|
|
237
|
+
if (!valueStr.startsWith('"') && !valueStr.startsWith("'")) {
|
|
238
|
+
addError(ctx, configPath, `Field "${fieldName}": value must be a string when options.type is "string"`);
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
else if (typeValue === "boolean") {
|
|
243
|
+
if (valueStr !== "true" && valueStr !== "false") {
|
|
244
|
+
addError(ctx, configPath, `Field "${fieldName}": value must be true or false when options.type is "boolean"`);
|
|
245
|
+
return false;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
// select type validation is more complex (needs choices array), skip for now
|
|
249
|
+
}
|
|
250
|
+
return true;
|
|
251
|
+
}
|
|
252
|
+
function validateTypeScript(projectRoot, ctx) {
|
|
253
|
+
if (!fs.existsSync(path.join(projectRoot, "tsconfig.json"))) {
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
try {
|
|
257
|
+
// Try tsc --noEmit for syntax checking
|
|
258
|
+
execSync("tsc --noEmit", {
|
|
259
|
+
cwd: projectRoot,
|
|
260
|
+
stdio: "pipe",
|
|
261
|
+
encoding: "utf-8",
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
const errorMessage = error.message?.toString() || "";
|
|
266
|
+
if (errorMessage.includes("command not found") ||
|
|
267
|
+
errorMessage.includes("ENOENT")) {
|
|
268
|
+
console.warn("ā TypeScript not available, skipping type check");
|
|
269
|
+
}
|
|
270
|
+
else {
|
|
271
|
+
const errorOutput = error.stdout?.toString() || error.stderr?.toString() || error.message;
|
|
272
|
+
addError(ctx, "typescript", `TypeScript compilation error:\n${errorOutput}`);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
function findJobReferences(actionPath, routeJsonPath) {
|
|
277
|
+
const fullPath = path.resolve(path.dirname(routeJsonPath), actionPath);
|
|
278
|
+
if (!fs.existsSync(fullPath)) {
|
|
279
|
+
return [];
|
|
280
|
+
}
|
|
281
|
+
const content = fs.readFileSync(fullPath, "utf-8");
|
|
282
|
+
const jobRunRegex = /job\.run\(["']([^"']+)["']\)/g;
|
|
283
|
+
const jobs = [];
|
|
284
|
+
let match;
|
|
285
|
+
while ((match = jobRunRegex.exec(content)) !== null) {
|
|
286
|
+
jobs.push(match[1]);
|
|
287
|
+
}
|
|
288
|
+
return jobs;
|
|
289
|
+
}
|
|
290
|
+
function validateJob(jobPath, jobId, ctx) {
|
|
291
|
+
if (!fs.existsSync(jobPath)) {
|
|
292
|
+
addError(ctx, `jobs/${jobId}/job.ts`, "job file not found");
|
|
293
|
+
return false;
|
|
294
|
+
}
|
|
295
|
+
const content = fs.readFileSync(jobPath, "utf-8");
|
|
296
|
+
// Check for default export: export default async function
|
|
297
|
+
const defaultExportRegex = /export\s+default\s+async\s+function/;
|
|
298
|
+
if (!defaultExportRegex.test(content)) {
|
|
299
|
+
addError(ctx, `jobs/${jobId}/job.ts`, "Job must export default async function(ctx)");
|
|
300
|
+
return false;
|
|
301
|
+
}
|
|
302
|
+
// Check for parameter count: (ctx) - single parameter
|
|
303
|
+
// Extract function signature
|
|
304
|
+
const functionSignatureMatch = content.match(/export\s+default\s+async\s+function\s*\(([^)]*)\)/);
|
|
305
|
+
if (!functionSignatureMatch) {
|
|
306
|
+
addError(ctx, `jobs/${jobId}/job.ts`, "Job must export default async function(ctx)");
|
|
307
|
+
return false;
|
|
308
|
+
}
|
|
309
|
+
const params = functionSignatureMatch[1]
|
|
310
|
+
.split(",")
|
|
311
|
+
.map((p) => p.trim())
|
|
312
|
+
.filter((p) => p);
|
|
313
|
+
if (params.length !== 1) {
|
|
314
|
+
addError(ctx, `jobs/${jobId}/job.ts`, "Job function must have exactly 1 parameter: (ctx). Use ctx.payload to access payload.");
|
|
315
|
+
return false;
|
|
316
|
+
}
|
|
317
|
+
// Check that parameter name is 'ctx' (recommended, but not enforced - just validate single param)
|
|
318
|
+
// We allow any single parameter name, but recommend 'ctx'
|
|
319
|
+
// Check for forbidden keywords
|
|
320
|
+
const forbiddenKeywords = ["require", "process", "fs", "global"];
|
|
321
|
+
for (const keyword of forbiddenKeywords) {
|
|
322
|
+
// Use word boundary regex to avoid matching in comments or strings
|
|
323
|
+
const regex = new RegExp(`\\b${keyword}\\b`);
|
|
324
|
+
if (regex.test(content)) {
|
|
325
|
+
addError(ctx, `jobs/${jobId}/job.ts`, `Job contains forbidden keyword: ${keyword}`);
|
|
326
|
+
return false;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return true;
|
|
330
|
+
}
|
|
331
|
+
function validateJobs(projectRoot, config, servicesConfig, assetsConfig, ctx) {
|
|
332
|
+
const jobs = scanJobs(projectRoot);
|
|
333
|
+
for (const job of jobs) {
|
|
334
|
+
const jobPath = path.join(projectRoot, "jobs", job.id, "job.ts");
|
|
335
|
+
if (validateJob(jobPath, job.id, ctx)) {
|
|
336
|
+
ctx.stats.jobs++;
|
|
337
|
+
checkCodeServiceUsage(`jobs/${job.id}/job.ts`, job.code, config, servicesConfig, assetsConfig, ctx);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
function validateServices(projectRoot, ctx) {
|
|
342
|
+
try {
|
|
343
|
+
const services = scanServices(projectRoot);
|
|
344
|
+
if (!services) {
|
|
345
|
+
return true; // No services config is valid
|
|
346
|
+
}
|
|
347
|
+
const serviceNames = Object.keys(services);
|
|
348
|
+
for (const serviceName of serviceNames) {
|
|
349
|
+
const service = services[serviceName];
|
|
350
|
+
const servicePath = `services/${serviceName}.json`;
|
|
351
|
+
// Enabled check
|
|
352
|
+
if (service.enabled !== true) {
|
|
353
|
+
addError(ctx, servicePath, "Service must have enabled: true");
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
if (serviceName === "email") {
|
|
357
|
+
if (!["resend", "smtp"].includes(service.defaultProvider))
|
|
358
|
+
addError(ctx, servicePath, "Email defaultProvider must be resend or smtp");
|
|
359
|
+
for (const [providerName, provider] of Object.entries(service.providers || {})) {
|
|
360
|
+
if (!["resend", "smtp"].includes(providerName))
|
|
361
|
+
addError(ctx, servicePath, "Email supports only resend and smtp providers");
|
|
362
|
+
for (const [envName, envConfig] of Object.entries(provider?.configByEnv || {})) {
|
|
363
|
+
if (!["dev", "staging", "prod"].includes(envName))
|
|
364
|
+
addError(ctx, servicePath, `Invalid email environment: ${envName}`);
|
|
365
|
+
const allowed = providerName === "smtp" ? ["from", "host", "port", "secure"] : ["from"];
|
|
366
|
+
if (!envConfig || typeof envConfig !== "object" || Object.keys(envConfig).some((key) => !allowed.includes(key)))
|
|
367
|
+
addError(ctx, servicePath, "Email provider config contains an unsupported or secret field");
|
|
368
|
+
if (typeof envConfig?.from !== "string" || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(envConfig.from))
|
|
369
|
+
addError(ctx, servicePath, "Email sender address must be valid");
|
|
370
|
+
if (providerName === "smtp" && (typeof envConfig?.host !== "string" || !envConfig.host || !Number.isInteger(envConfig.port) || envConfig.port < 1 || envConfig.port > 65535 || typeof envConfig.secure !== "boolean"))
|
|
371
|
+
addError(ctx, servicePath, "SMTP requires host, valid port, and secure boolean");
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
// Providers check
|
|
376
|
+
if (!service.providers || Object.keys(service.providers).length === 0) {
|
|
377
|
+
addError(ctx, servicePath, "Service must have at least one provider");
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
// DefaultProvider check
|
|
381
|
+
if (service.defaultProvider) {
|
|
382
|
+
if (!service.providers[service.defaultProvider]) {
|
|
383
|
+
addError(ctx, servicePath, `defaultProvider "${service.defaultProvider}" not found in providers`);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
// ENV:XYZ format check (pattern only, don't resolve)
|
|
387
|
+
const envPattern = /^ENV:[A-Z_][A-Z0-9_]*$/;
|
|
388
|
+
// Check for raw secrets in config
|
|
389
|
+
const checkForSecrets = (obj, objPath = "") => {
|
|
390
|
+
if (typeof obj === "string") {
|
|
391
|
+
// Check if it looks like a secret but not ENV: format
|
|
392
|
+
const secretPatterns = [
|
|
393
|
+
"apiKey",
|
|
394
|
+
"secret",
|
|
395
|
+
"key",
|
|
396
|
+
"token",
|
|
397
|
+
"password",
|
|
398
|
+
];
|
|
399
|
+
if (secretPatterns.some((pattern) => objPath.toLowerCase().includes(pattern))) {
|
|
400
|
+
if (!envPattern.test(obj) && obj.length > 10) {
|
|
401
|
+
addWarning(ctx, servicePath, `Potential hardcoded secret in ${objPath} (consider using ENV:VAR_NAME)`);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
else if (typeof obj === "object" && obj !== null) {
|
|
406
|
+
for (const key in obj) {
|
|
407
|
+
checkForSecrets(obj[key], objPath ? `${objPath}.${key}` : key);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
// Check all provider configs
|
|
412
|
+
for (const providerName in service.providers) {
|
|
413
|
+
const provider = service.providers[providerName];
|
|
414
|
+
if (provider.configByEnv) {
|
|
415
|
+
for (const env in provider.configByEnv) {
|
|
416
|
+
const envConfig = provider.configByEnv[env];
|
|
417
|
+
if (envConfig) {
|
|
418
|
+
checkForSecrets(envConfig, `${providerName}.configByEnv.${env}`);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return true;
|
|
425
|
+
}
|
|
426
|
+
catch (error) {
|
|
427
|
+
// Handle duplicate service errors with proper file path
|
|
428
|
+
if (error.message.includes("Duplicate service definition")) {
|
|
429
|
+
const match = error.message.match(/Duplicate service definition: (\w+)/);
|
|
430
|
+
if (match) {
|
|
431
|
+
addError(ctx, `services/${match[1]}.json`, error.message);
|
|
432
|
+
}
|
|
433
|
+
else {
|
|
434
|
+
addError(ctx, "services", error.message);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
else {
|
|
438
|
+
addError(ctx, "services", error.message);
|
|
439
|
+
}
|
|
440
|
+
return false;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
function validateAssets(projectRoot, ctx) {
|
|
444
|
+
try {
|
|
445
|
+
const assets = scanAssets(projectRoot);
|
|
446
|
+
if (!assets) {
|
|
447
|
+
return true; // No assets config is valid
|
|
448
|
+
}
|
|
449
|
+
// Enabled check
|
|
450
|
+
if (assets.enabled !== true) {
|
|
451
|
+
addError(ctx, "assets/storage.json", "Assets must have enabled: true");
|
|
452
|
+
return false;
|
|
453
|
+
}
|
|
454
|
+
// Providers check
|
|
455
|
+
if (!assets.providers || Object.keys(assets.providers).length === 0) {
|
|
456
|
+
addError(ctx, "assets/storage.json", "Assets must have at least one provider");
|
|
457
|
+
return false;
|
|
458
|
+
}
|
|
459
|
+
// DefaultProvider check
|
|
460
|
+
if (assets.defaultProvider) {
|
|
461
|
+
if (!assets.providers[assets.defaultProvider]) {
|
|
462
|
+
addError(ctx, "assets/storage.json", `defaultProvider "${assets.defaultProvider}" not found in providers`);
|
|
463
|
+
return false;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
// Provider type check
|
|
467
|
+
for (const providerName in assets.providers) {
|
|
468
|
+
const provider = assets.providers[providerName];
|
|
469
|
+
if (!provider.type ||
|
|
470
|
+
!["internal", "s3", "custom"].includes(provider.type)) {
|
|
471
|
+
addError(ctx, "assets/storage.json", `Provider "${providerName}" must have type: "internal" | "s3" | "custom"`);
|
|
472
|
+
return false;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
return true;
|
|
476
|
+
}
|
|
477
|
+
catch (error) {
|
|
478
|
+
addError(ctx, "assets/storage.json", error.message);
|
|
479
|
+
return false;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
// Known rule types (for warning purposes, not strict validation)
|
|
483
|
+
// Backend may support additional rule types - unknown types will generate warning but not error
|
|
484
|
+
const KNOWN_RULE_TYPES = [
|
|
485
|
+
"required",
|
|
486
|
+
"minLength",
|
|
487
|
+
"maxLength",
|
|
488
|
+
"pattern",
|
|
489
|
+
"enum",
|
|
490
|
+
"min",
|
|
491
|
+
"max",
|
|
492
|
+
"minDate",
|
|
493
|
+
"maxDate",
|
|
494
|
+
"minItems",
|
|
495
|
+
"maxItems",
|
|
496
|
+
"custom",
|
|
497
|
+
];
|
|
498
|
+
// Recursive field validation helper
|
|
499
|
+
function validateFieldRecursive(field, fieldPath, modelName, depth, ctx) {
|
|
500
|
+
const MAX_DEPTH = 10;
|
|
501
|
+
if (depth > MAX_DEPTH) {
|
|
502
|
+
addError(ctx, fieldPath, `Field nesting depth exceeds maximum (${MAX_DEPTH})`);
|
|
503
|
+
return false;
|
|
504
|
+
}
|
|
505
|
+
let isValid = true;
|
|
506
|
+
// Validate field.name
|
|
507
|
+
if (!field.name || typeof field.name !== "string") {
|
|
508
|
+
addError(ctx, fieldPath, "field.name is required and must be a string");
|
|
509
|
+
isValid = false;
|
|
510
|
+
}
|
|
511
|
+
// Validate field.type
|
|
512
|
+
const validFieldTypes = [
|
|
513
|
+
"string",
|
|
514
|
+
"number",
|
|
515
|
+
"boolean",
|
|
516
|
+
"date",
|
|
517
|
+
"object",
|
|
518
|
+
"array",
|
|
519
|
+
"objectId",
|
|
520
|
+
];
|
|
521
|
+
if (!field.type || !validFieldTypes.includes(field.type)) {
|
|
522
|
+
addError(ctx, fieldPath, `field.type is required and must be one of: ${validFieldTypes.join(", ")}`);
|
|
523
|
+
isValid = false;
|
|
524
|
+
}
|
|
525
|
+
// Validate rules (required, but can be empty array)
|
|
526
|
+
if (!field.hasOwnProperty("rules")) {
|
|
527
|
+
addError(ctx, fieldPath, `field.rules is required (can be empty array [])`);
|
|
528
|
+
isValid = false;
|
|
529
|
+
}
|
|
530
|
+
else if (!Array.isArray(field.rules)) {
|
|
531
|
+
addError(ctx, fieldPath, "field.rules must be an array");
|
|
532
|
+
isValid = false;
|
|
533
|
+
}
|
|
534
|
+
else {
|
|
535
|
+
// Validate each rule
|
|
536
|
+
for (let j = 0; j < field.rules.length; j++) {
|
|
537
|
+
const rule = field.rules[j];
|
|
538
|
+
const rulePath = `${fieldPath}.rules[${j}]`;
|
|
539
|
+
// rule.type is REQUIRED
|
|
540
|
+
if (!rule.type || typeof rule.type !== "string") {
|
|
541
|
+
addError(ctx, rulePath, "rule.type is required and must be a string");
|
|
542
|
+
isValid = false;
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
// Warn if unknown rule type (but don't fail - backend may support more)
|
|
546
|
+
if (!KNOWN_RULE_TYPES.includes(rule.type)) {
|
|
547
|
+
addWarning(ctx, rulePath, `Unknown rule type "${rule.type}" (backend may support it, but it's not in known types)`);
|
|
548
|
+
}
|
|
549
|
+
// errorMessage, errorCode, errorStatus are OPTIONAL (backend has defaults)
|
|
550
|
+
if (rule.errorMessage !== undefined &&
|
|
551
|
+
typeof rule.errorMessage !== "string") {
|
|
552
|
+
addError(ctx, rulePath, "rule.errorMessage must be a string if provided");
|
|
553
|
+
isValid = false;
|
|
554
|
+
}
|
|
555
|
+
if (rule.errorCode !== undefined && typeof rule.errorCode !== "string") {
|
|
556
|
+
addError(ctx, rulePath, "rule.errorCode must be a string if provided");
|
|
557
|
+
isValid = false;
|
|
558
|
+
}
|
|
559
|
+
if (rule.errorStatus !== undefined &&
|
|
560
|
+
typeof rule.errorStatus !== "number") {
|
|
561
|
+
addError(ctx, rulePath, "rule.errorStatus must be a number if provided");
|
|
562
|
+
isValid = false;
|
|
563
|
+
}
|
|
564
|
+
// Validate rule.value based on rule type (if present)
|
|
565
|
+
if (rule.value !== undefined) {
|
|
566
|
+
if ([
|
|
567
|
+
"minLength",
|
|
568
|
+
"maxLength",
|
|
569
|
+
"min",
|
|
570
|
+
"max",
|
|
571
|
+
"minItems",
|
|
572
|
+
"maxItems",
|
|
573
|
+
].includes(rule.type) &&
|
|
574
|
+
typeof rule.value !== "number") {
|
|
575
|
+
addError(ctx, rulePath, `rule.value must be a number for rule type '${rule.type}'`);
|
|
576
|
+
isValid = false;
|
|
577
|
+
}
|
|
578
|
+
if (rule.type === "enum" &&
|
|
579
|
+
(!Array.isArray(rule.value) || rule.value.length === 0)) {
|
|
580
|
+
addError(ctx, rulePath, "rule.value must be a non-empty array for rule type 'enum'");
|
|
581
|
+
isValid = false;
|
|
582
|
+
}
|
|
583
|
+
if (rule.type === "pattern" && typeof rule.value !== "string") {
|
|
584
|
+
addError(ctx, rulePath, "rule.value must be a string (regex pattern) for rule type 'pattern'");
|
|
585
|
+
isValid = false;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
// Validate default value (type checking - flexible for dates)
|
|
591
|
+
if (field.default !== undefined) {
|
|
592
|
+
const fieldType = field.type;
|
|
593
|
+
if (fieldType === "string" && typeof field.default !== "string") {
|
|
594
|
+
addError(ctx, fieldPath, "field.default must be a string when field.type is 'string'");
|
|
595
|
+
isValid = false;
|
|
596
|
+
}
|
|
597
|
+
else if (fieldType === "number" && typeof field.default !== "number") {
|
|
598
|
+
addError(ctx, fieldPath, "field.default must be a number when field.type is 'number'");
|
|
599
|
+
isValid = false;
|
|
600
|
+
}
|
|
601
|
+
else if (fieldType === "boolean" && typeof field.default !== "boolean") {
|
|
602
|
+
addError(ctx, fieldPath, "field.default must be a boolean when field.type is 'boolean'");
|
|
603
|
+
isValid = false;
|
|
604
|
+
}
|
|
605
|
+
else if (fieldType === "date") {
|
|
606
|
+
// Date defaults: string (ISO), Date object, or number (timestamp) - all valid
|
|
607
|
+
if (typeof field.default !== "string" &&
|
|
608
|
+
typeof field.default !== "number" &&
|
|
609
|
+
!(field.default instanceof Date)) {
|
|
610
|
+
addError(ctx, fieldPath, "field.default for date type must be a string (ISO date), number (timestamp), or Date object");
|
|
611
|
+
isValid = false;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
else if (fieldType === "array" && !Array.isArray(field.default)) {
|
|
615
|
+
addError(ctx, fieldPath, "field.default must be an array when field.type is 'array'");
|
|
616
|
+
isValid = false;
|
|
617
|
+
}
|
|
618
|
+
else if (fieldType === "object" && typeof field.default !== "object") {
|
|
619
|
+
addError(ctx, fieldPath, "field.default must be an object when field.type is 'object'");
|
|
620
|
+
isValid = false;
|
|
621
|
+
}
|
|
622
|
+
else if (fieldType === "objectId" && typeof field.default !== "string") {
|
|
623
|
+
addError(ctx, fieldPath, "field.default must be a string (ObjectId) when field.type is 'objectId'");
|
|
624
|
+
isValid = false;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
// Validate transformations (optional)
|
|
628
|
+
if (field.transformations !== undefined) {
|
|
629
|
+
if (!Array.isArray(field.transformations)) {
|
|
630
|
+
addError(ctx, fieldPath, "field.transformations must be an array if provided");
|
|
631
|
+
isValid = false;
|
|
632
|
+
}
|
|
633
|
+
else {
|
|
634
|
+
for (let k = 0; k < field.transformations.length; k++) {
|
|
635
|
+
const transformation = field.transformations[k];
|
|
636
|
+
const transPath = `${fieldPath}.transformations[${k}]`;
|
|
637
|
+
if (typeof transformation === "string") {
|
|
638
|
+
// Legacy format: string (e.g., "trim")
|
|
639
|
+
if (!["trim", "lowercase", "uppercase"].includes(transformation)) {
|
|
640
|
+
addError(ctx, transPath, `transformation must be one of: trim, lowercase, uppercase`);
|
|
641
|
+
isValid = false;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
else if (typeof transformation === "object" &&
|
|
645
|
+
transformation !== null) {
|
|
646
|
+
// Canonical format: object with type and apply
|
|
647
|
+
if (!["trim", "lowercase", "uppercase"].includes(transformation.type)) {
|
|
648
|
+
addError(ctx, transPath, `transformation.type must be one of: trim, lowercase, uppercase`);
|
|
649
|
+
isValid = false;
|
|
650
|
+
}
|
|
651
|
+
if (transformation.apply !== "beforeValidation" &&
|
|
652
|
+
transformation.apply !== "afterValidation") {
|
|
653
|
+
addError(ctx, transPath, `transformation.apply must be either "beforeValidation" or "afterValidation"`);
|
|
654
|
+
isValid = false;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
else {
|
|
658
|
+
addError(ctx, transPath, "transformation must be a string or object with type and apply");
|
|
659
|
+
isValid = false;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
// Validate appliesTo (optional)
|
|
665
|
+
if (field.appliesTo !== undefined) {
|
|
666
|
+
if (field.appliesTo !== "all" && field.appliesTo !== "new") {
|
|
667
|
+
addError(ctx, fieldPath, "field.appliesTo must be either 'all' or 'new' if provided");
|
|
668
|
+
isValid = false;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
// Validate uniqueConstraint (optional)
|
|
672
|
+
if (field.uniqueConstraint !== undefined) {
|
|
673
|
+
if (typeof field.uniqueConstraint !== "object" ||
|
|
674
|
+
field.uniqueConstraint === null) {
|
|
675
|
+
addError(ctx, fieldPath, "field.uniqueConstraint must be an object if provided");
|
|
676
|
+
isValid = false;
|
|
677
|
+
}
|
|
678
|
+
else {
|
|
679
|
+
if (!field.uniqueConstraint.fields ||
|
|
680
|
+
!Array.isArray(field.uniqueConstraint.fields)) {
|
|
681
|
+
addError(ctx, fieldPath, "field.uniqueConstraint.fields is required and must be an array");
|
|
682
|
+
isValid = false;
|
|
683
|
+
}
|
|
684
|
+
else if (field.uniqueConstraint.fields.length === 0) {
|
|
685
|
+
addError(ctx, fieldPath, "field.uniqueConstraint.fields must contain at least one field name");
|
|
686
|
+
isValid = false;
|
|
687
|
+
}
|
|
688
|
+
if (field.uniqueConstraint.scopeFields !== undefined &&
|
|
689
|
+
!Array.isArray(field.uniqueConstraint.scopeFields)) {
|
|
690
|
+
addError(ctx, fieldPath, "field.uniqueConstraint.scopeFields must be an array if provided");
|
|
691
|
+
isValid = false;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
// Validate ref (optional, for objectId)
|
|
696
|
+
if (field.ref !== undefined) {
|
|
697
|
+
if (typeof field.ref !== "string") {
|
|
698
|
+
addError(ctx, fieldPath, "field.ref must be a string if provided");
|
|
699
|
+
isValid = false;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
// Recursive validation for nested structures
|
|
703
|
+
if (field.type === "array" && field.items) {
|
|
704
|
+
const itemsPath = `${fieldPath}.items`;
|
|
705
|
+
if (!validateFieldRecursive(field.items, itemsPath, modelName, depth + 1, ctx)) {
|
|
706
|
+
isValid = false;
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
if (field.type === "object" && field.schema) {
|
|
710
|
+
if (!Array.isArray(field.schema)) {
|
|
711
|
+
addError(ctx, fieldPath, "field.schema must be an array when field.type is 'object'");
|
|
712
|
+
isValid = false;
|
|
713
|
+
}
|
|
714
|
+
else {
|
|
715
|
+
for (let k = 0; k < field.schema.length; k++) {
|
|
716
|
+
const nestedField = field.schema[k];
|
|
717
|
+
const nestedPath = `${fieldPath}.schema[${k}]`;
|
|
718
|
+
if (!validateFieldRecursive(nestedField, nestedPath, modelName, depth + 1, ctx)) {
|
|
719
|
+
isValid = false;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
return isValid;
|
|
725
|
+
}
|
|
726
|
+
function validateModel(modelPath, modelName, schema, ctx) {
|
|
727
|
+
// Validate modelName
|
|
728
|
+
if (!schema.modelName || typeof schema.modelName !== "string") {
|
|
729
|
+
addError(ctx, `models/${modelName}/model.json`, "modelName is required and must be a string");
|
|
730
|
+
return false;
|
|
731
|
+
}
|
|
732
|
+
// Validate modelName format (must start with uppercase letter, alphanumeric only)
|
|
733
|
+
const modelNameTrimmed = schema.modelName.trim();
|
|
734
|
+
if (!/^[A-Z][a-zA-Z0-9]*$/.test(modelNameTrimmed)) {
|
|
735
|
+
addError(ctx, `models/${modelName}/model.json`, "modelName must start with uppercase letter and contain only alphanumeric characters");
|
|
736
|
+
return false;
|
|
737
|
+
}
|
|
738
|
+
// Validate that directory name (lowercase) matches modelName (lowercase)
|
|
739
|
+
if (modelName.toLowerCase() !== schema.modelName.toLowerCase()) {
|
|
740
|
+
addError(ctx, `models/${modelName}/model.json`, `modelName mismatch: directory name "${modelName}" (lowercase) must match schema.modelName "${schema.modelName}" (lowercase)`);
|
|
741
|
+
return false;
|
|
742
|
+
}
|
|
743
|
+
// Validate fields (required, must be array)
|
|
744
|
+
if (!schema.fields || !Array.isArray(schema.fields)) {
|
|
745
|
+
addError(ctx, `models/${modelName}/model.json`, "fields is required and must be an array");
|
|
746
|
+
return false;
|
|
747
|
+
}
|
|
748
|
+
// Validate at least one field
|
|
749
|
+
if (schema.fields.length === 0) {
|
|
750
|
+
addError(ctx, `models/${modelName}/model.json`, "fields array must contain at least one field");
|
|
751
|
+
return false;
|
|
752
|
+
}
|
|
753
|
+
// Validate each field (using recursive helper)
|
|
754
|
+
let isValid = true;
|
|
755
|
+
for (let i = 0; i < schema.fields.length; i++) {
|
|
756
|
+
const field = schema.fields[i];
|
|
757
|
+
const fieldPath = `models/${modelName}/model.json (field[${i}] "${field.name || "?"}")`;
|
|
758
|
+
if (!validateFieldRecursive(field, fieldPath, modelName, 0, ctx)) {
|
|
759
|
+
isValid = false;
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
if (!isValid) {
|
|
763
|
+
return false;
|
|
764
|
+
}
|
|
765
|
+
// Validate indexes (optional, but if present must be array)
|
|
766
|
+
if (schema.indexes !== undefined) {
|
|
767
|
+
if (!Array.isArray(schema.indexes)) {
|
|
768
|
+
addError(ctx, `models/${modelName}/model.json`, "indexes must be an array if provided");
|
|
769
|
+
return false;
|
|
770
|
+
}
|
|
771
|
+
for (let i = 0; i < schema.indexes.length; i++) {
|
|
772
|
+
const index = schema.indexes[i];
|
|
773
|
+
const indexPath = `models/${modelName}/model.json (indexes[${i}])`;
|
|
774
|
+
if (!index.fields || !Array.isArray(index.fields)) {
|
|
775
|
+
addError(ctx, indexPath, "index.fields is required and must be an array");
|
|
776
|
+
return false;
|
|
777
|
+
}
|
|
778
|
+
if (index.fields.length === 0) {
|
|
779
|
+
addError(ctx, indexPath, "index.fields must contain at least one field name");
|
|
780
|
+
return false;
|
|
781
|
+
}
|
|
782
|
+
if (index.unique !== undefined && typeof index.unique !== "boolean") {
|
|
783
|
+
addError(ctx, indexPath, "index.unique must be a boolean if provided");
|
|
784
|
+
return false;
|
|
785
|
+
}
|
|
786
|
+
if (index.name !== undefined && typeof index.name !== "string") {
|
|
787
|
+
addError(ctx, indexPath, "index.name must be a string if provided");
|
|
788
|
+
return false;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
// Validate uniqueConstraints (optional, but if present must be array)
|
|
793
|
+
if (schema.uniqueConstraints !== undefined) {
|
|
794
|
+
if (!Array.isArray(schema.uniqueConstraints)) {
|
|
795
|
+
addError(ctx, `models/${modelName}/model.json`, "uniqueConstraints must be an array if provided");
|
|
796
|
+
return false;
|
|
797
|
+
}
|
|
798
|
+
for (let i = 0; i < schema.uniqueConstraints.length; i++) {
|
|
799
|
+
const constraint = schema.uniqueConstraints[i];
|
|
800
|
+
const constraintPath = `models/${modelName}/model.json (uniqueConstraints[${i}])`;
|
|
801
|
+
if (!constraint.fields || !Array.isArray(constraint.fields)) {
|
|
802
|
+
addError(ctx, constraintPath, "uniqueConstraint.fields is required and must be an array");
|
|
803
|
+
return false;
|
|
804
|
+
}
|
|
805
|
+
if (constraint.fields.length === 0) {
|
|
806
|
+
addError(ctx, constraintPath, "uniqueConstraint.fields must contain at least one field name");
|
|
807
|
+
return false;
|
|
808
|
+
}
|
|
809
|
+
if (constraint.scopeFields !== undefined &&
|
|
810
|
+
!Array.isArray(constraint.scopeFields)) {
|
|
811
|
+
addError(ctx, constraintPath, "uniqueConstraint.scopeFields must be an array if provided");
|
|
812
|
+
return false;
|
|
813
|
+
}
|
|
814
|
+
if (constraint.message !== undefined &&
|
|
815
|
+
typeof constraint.message !== "string") {
|
|
816
|
+
addError(ctx, constraintPath, "uniqueConstraint.message must be a string if provided");
|
|
817
|
+
return false;
|
|
818
|
+
}
|
|
819
|
+
if (constraint.code !== undefined &&
|
|
820
|
+
typeof constraint.code !== "string") {
|
|
821
|
+
addError(ctx, constraintPath, "uniqueConstraint.code must be a string if provided");
|
|
822
|
+
return false;
|
|
823
|
+
}
|
|
824
|
+
if (constraint.status !== undefined &&
|
|
825
|
+
(typeof constraint.status !== "number" ||
|
|
826
|
+
constraint.status < 100 ||
|
|
827
|
+
constraint.status > 599)) {
|
|
828
|
+
addError(ctx, constraintPath, "uniqueConstraint.status must be a valid HTTP status code (100-599) if provided");
|
|
829
|
+
return false;
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
// Validate options (optional, but if present must be object)
|
|
834
|
+
if (schema.options !== undefined) {
|
|
835
|
+
if (typeof schema.options !== "object" || schema.options === null) {
|
|
836
|
+
addError(ctx, `models/${modelName}/model.json`, "options must be an object if provided");
|
|
837
|
+
return false;
|
|
838
|
+
}
|
|
839
|
+
if (schema.options.timestamps !== undefined &&
|
|
840
|
+
typeof schema.options.timestamps !== "boolean") {
|
|
841
|
+
addError(ctx, `models/${modelName}/model.json`, "options.timestamps must be a boolean if provided");
|
|
842
|
+
return false;
|
|
843
|
+
}
|
|
844
|
+
if (schema.options.softDelete !== undefined &&
|
|
845
|
+
typeof schema.options.softDelete !== "boolean") {
|
|
846
|
+
addError(ctx, `models/${modelName}/model.json`, "options.softDelete must be a boolean if provided");
|
|
847
|
+
return false;
|
|
848
|
+
}
|
|
849
|
+
if (schema.options.strict !== undefined &&
|
|
850
|
+
typeof schema.options.strict !== "boolean") {
|
|
851
|
+
addError(ctx, `models/${modelName}/model.json`, "options.strict must be a boolean if provided");
|
|
852
|
+
return false;
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
// Validate hooks (optional, but if present must be object)
|
|
856
|
+
if (schema.hooks !== undefined) {
|
|
857
|
+
if (typeof schema.hooks !== "object" || schema.hooks === null) {
|
|
858
|
+
addError(ctx, `models/${modelName}/model.json`, "hooks must be an object if provided");
|
|
859
|
+
return false;
|
|
860
|
+
}
|
|
861
|
+
if (schema.hooks.beforeCreate !== undefined &&
|
|
862
|
+
typeof schema.hooks.beforeCreate !== "string") {
|
|
863
|
+
addError(ctx, `models/${modelName}/model.json`, "hooks.beforeCreate must be a string (action ID) if provided");
|
|
864
|
+
return false;
|
|
865
|
+
}
|
|
866
|
+
if (schema.hooks.beforeUpdate !== undefined &&
|
|
867
|
+
typeof schema.hooks.beforeUpdate !== "string") {
|
|
868
|
+
addError(ctx, `models/${modelName}/model.json`, "hooks.beforeUpdate must be a string (action ID) if provided");
|
|
869
|
+
return false;
|
|
870
|
+
}
|
|
871
|
+
if (schema.hooks.beforeDelete !== undefined &&
|
|
872
|
+
typeof schema.hooks.beforeDelete !== "string") {
|
|
873
|
+
addError(ctx, `models/${modelName}/model.json`, "hooks.beforeDelete must be a string (action ID) if provided");
|
|
874
|
+
return false;
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
// Validate metadata (optional, but if present must be object)
|
|
878
|
+
if (schema.metadata !== undefined) {
|
|
879
|
+
if (typeof schema.metadata !== "object" || schema.metadata === null) {
|
|
880
|
+
addError(ctx, `models/${modelName}/model.json`, "metadata must be an object if provided");
|
|
881
|
+
return false;
|
|
882
|
+
}
|
|
883
|
+
if (schema.metadata.description !== undefined &&
|
|
884
|
+
typeof schema.metadata.description !== "string") {
|
|
885
|
+
addError(ctx, `models/${modelName}/model.json`, "metadata.description must be a string if provided");
|
|
886
|
+
return false;
|
|
887
|
+
}
|
|
888
|
+
if (schema.metadata.icon !== undefined &&
|
|
889
|
+
typeof schema.metadata.icon !== "string") {
|
|
890
|
+
addError(ctx, `models/${modelName}/model.json`, "metadata.icon must be a string if provided");
|
|
891
|
+
return false;
|
|
892
|
+
}
|
|
893
|
+
if (schema.metadata.color !== undefined &&
|
|
894
|
+
typeof schema.metadata.color !== "string") {
|
|
895
|
+
addError(ctx, `models/${modelName}/model.json`, "metadata.color must be a string if provided");
|
|
896
|
+
return false;
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
return true;
|
|
900
|
+
}
|
|
901
|
+
function validateModels(projectRoot, ctx) {
|
|
902
|
+
try {
|
|
903
|
+
const models = scanModels(projectRoot);
|
|
904
|
+
// Check for duplicate modelNames
|
|
905
|
+
const modelNames = new Set();
|
|
906
|
+
for (const model of models) {
|
|
907
|
+
if (modelNames.has(model.modelName)) {
|
|
908
|
+
addError(ctx, `models/${model.modelName}/model.json`, `Duplicate modelName: "${model.modelName}"`);
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
modelNames.add(model.modelName);
|
|
912
|
+
}
|
|
913
|
+
// Validate each model
|
|
914
|
+
for (const model of models) {
|
|
915
|
+
const modelPath = path.join(projectRoot, model.filePath);
|
|
916
|
+
if (!fs.existsSync(modelPath)) {
|
|
917
|
+
addError(ctx, model.filePath, "model.json file not found (scanned but file missing)");
|
|
918
|
+
continue;
|
|
919
|
+
}
|
|
920
|
+
try {
|
|
921
|
+
const content = fs.readFileSync(modelPath, "utf-8");
|
|
922
|
+
const schema = JSON.parse(content);
|
|
923
|
+
const isValid = validateModel(modelPath, model.modelName, schema, ctx);
|
|
924
|
+
if (isValid) {
|
|
925
|
+
ctx.stats.models++;
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
catch (error) {
|
|
929
|
+
if (error instanceof SyntaxError) {
|
|
930
|
+
addError(ctx, model.filePath, `JSON parse error: ${error.message}`);
|
|
931
|
+
}
|
|
932
|
+
else {
|
|
933
|
+
addError(ctx, model.filePath, `Failed to read file: ${error.message}`);
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
catch (error) {
|
|
939
|
+
addError(ctx, "models", error.message);
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
function isServiceOrProviderEnabled(name, config, servicesConfig) {
|
|
943
|
+
if (servicesConfig?.[name]?.enabled === true) {
|
|
944
|
+
return true;
|
|
945
|
+
}
|
|
946
|
+
if (config.services?.[name]?.enabled === true) {
|
|
947
|
+
return true;
|
|
948
|
+
}
|
|
949
|
+
if (servicesConfig) {
|
|
950
|
+
for (const svcKey of Object.keys(servicesConfig)) {
|
|
951
|
+
const svcObj = servicesConfig[svcKey];
|
|
952
|
+
if (svcObj?.enabled === true &&
|
|
953
|
+
svcObj.providers &&
|
|
954
|
+
Object.prototype.hasOwnProperty.call(svcObj.providers, name)) {
|
|
955
|
+
const provider = svcObj.providers[name];
|
|
956
|
+
if (provider && provider.enabled !== false) {
|
|
957
|
+
return true;
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
return false;
|
|
963
|
+
}
|
|
964
|
+
function checkCodeServiceUsage(fileLabel, code, config, servicesConfig, assetsConfig, ctx) {
|
|
965
|
+
const checkedServices = new Set();
|
|
966
|
+
const servicePropRegex = /\bservices\.(tts|llm|image|pdf|csv|json|video|email)\b/g;
|
|
967
|
+
let match;
|
|
968
|
+
while ((match = servicePropRegex.exec(code)) !== null) {
|
|
969
|
+
const svc = match[1];
|
|
970
|
+
if (checkedServices.has(svc))
|
|
971
|
+
continue;
|
|
972
|
+
checkedServices.add(svc);
|
|
973
|
+
const isEnabled = servicesConfig?.[svc]?.enabled === true ||
|
|
974
|
+
config.services?.[svc]?.enabled === true;
|
|
975
|
+
if (!isEnabled) {
|
|
976
|
+
addError(ctx, fileLabel, `uses services.${svc} but ${svc} service is not enabled in config`);
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
const checkedDynamicServices = new Set();
|
|
980
|
+
const serviceGetRegex = /\bservices\.get\(\s*['"]([^'"]+)['"]\s*\)/g;
|
|
981
|
+
while ((match = serviceGetRegex.exec(code)) !== null) {
|
|
982
|
+
const targetName = match[1];
|
|
983
|
+
if (checkedDynamicServices.has(targetName))
|
|
984
|
+
continue;
|
|
985
|
+
checkedDynamicServices.add(targetName);
|
|
986
|
+
if (!isServiceOrProviderEnabled(targetName, config, servicesConfig)) {
|
|
987
|
+
addError(ctx, fileLabel, `uses services.get('${targetName}') but "${targetName}" service/provider is not enabled in config`);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
const assetsMatch = code.match(/\bassets\.(create|get|getUrl|getMetadata|list)\b/);
|
|
991
|
+
if (assetsMatch) {
|
|
992
|
+
const assetsEnabled = assetsConfig?.enabled === true || config.assets?.enabled === true;
|
|
993
|
+
if (!assetsEnabled) {
|
|
994
|
+
addError(ctx, fileLabel, `uses assets.${assetsMatch[1]} but assets service is not enabled in config`);
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
function checkServiceUsage(actionPath, routeJsonPath, config, servicesConfig, assetsConfig, ctx) {
|
|
999
|
+
const fullPath = path.resolve(path.dirname(routeJsonPath), actionPath);
|
|
1000
|
+
if (!fs.existsSync(fullPath)) {
|
|
1001
|
+
return;
|
|
1002
|
+
}
|
|
1003
|
+
const content = fs.readFileSync(fullPath, "utf-8");
|
|
1004
|
+
checkCodeServiceUsage(actionPath, content, config, servicesConfig, assetsConfig, ctx);
|
|
1005
|
+
}
|
|
1006
|
+
function collectRouteJsonFiles(dir) {
|
|
1007
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
1008
|
+
const files = [];
|
|
1009
|
+
for (const entry of entries) {
|
|
1010
|
+
const fullPath = path.join(dir, entry.name);
|
|
1011
|
+
if (entry.isDirectory()) {
|
|
1012
|
+
files.push(...collectRouteJsonFiles(fullPath));
|
|
1013
|
+
}
|
|
1014
|
+
else if (entry.isFile() && entry.name === "route.json") {
|
|
1015
|
+
files.push(fullPath);
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
return files;
|
|
1019
|
+
}
|
|
1020
|
+
function validateRoutes(projectRoot, config, servicesConfig, assetsConfig, ctx) {
|
|
1021
|
+
const routesDir = path.join(projectRoot, "routes");
|
|
1022
|
+
if (!fs.existsSync(routesDir)) {
|
|
1023
|
+
return;
|
|
1024
|
+
}
|
|
1025
|
+
const routeJsonPaths = collectRouteJsonFiles(routesDir);
|
|
1026
|
+
for (const routeJsonPath of routeJsonPaths) {
|
|
1027
|
+
const routeJson = validateRouteJson(routeJsonPath, ctx);
|
|
1028
|
+
if (!routeJson) {
|
|
1029
|
+
continue;
|
|
1030
|
+
}
|
|
1031
|
+
ctx.stats.routes++;
|
|
1032
|
+
// If route points to a flow, validate flow reference
|
|
1033
|
+
if (routeJson.flow) {
|
|
1034
|
+
const flowPath = path.join(projectRoot, "flows", routeJson.flow, "flow.json");
|
|
1035
|
+
if (!fs.existsSync(flowPath)) {
|
|
1036
|
+
addError(ctx, routeJsonPath, `referenced flow "${routeJson.flow}" not found at flows/${routeJson.flow}/flow.json`);
|
|
1037
|
+
}
|
|
1038
|
+
continue;
|
|
1039
|
+
}
|
|
1040
|
+
// Validate action file (resolve relative to route.json location)
|
|
1041
|
+
const actionRelativePath = routeJson.action;
|
|
1042
|
+
const actionValid = validateActionFile(actionRelativePath, routeJsonPath, ctx);
|
|
1043
|
+
if (actionValid) {
|
|
1044
|
+
ctx.stats.actions++;
|
|
1045
|
+
// Validate config.ts if it exists (optional, but must be valid if present)
|
|
1046
|
+
validateConfigFile(actionRelativePath, routeJsonPath, ctx);
|
|
1047
|
+
// Job references are now validated separately via validateJobs()
|
|
1048
|
+
// Check service/asset usage
|
|
1049
|
+
checkServiceUsage(actionRelativePath, routeJsonPath, config, servicesConfig, assetsConfig, ctx);
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
const VALID_FLOW_NODE_TYPES = new Set([
|
|
1054
|
+
"trigger",
|
|
1055
|
+
"action",
|
|
1056
|
+
"if",
|
|
1057
|
+
"switch",
|
|
1058
|
+
"loop",
|
|
1059
|
+
"parallel",
|
|
1060
|
+
"retry",
|
|
1061
|
+
"delay",
|
|
1062
|
+
"subflow",
|
|
1063
|
+
"human",
|
|
1064
|
+
]);
|
|
1065
|
+
const FLOW_ACTION_FORBIDDEN_PATTERNS = [
|
|
1066
|
+
"require(",
|
|
1067
|
+
"import(",
|
|
1068
|
+
"process.",
|
|
1069
|
+
"global.",
|
|
1070
|
+
"__dirname",
|
|
1071
|
+
"__filename",
|
|
1072
|
+
"eval(",
|
|
1073
|
+
"Function(",
|
|
1074
|
+
"child_process",
|
|
1075
|
+
"fs.",
|
|
1076
|
+
];
|
|
1077
|
+
const FLOW_ACTION_HTTP_PATTERNS = [
|
|
1078
|
+
/\(\s*req\s*,\s*res\s*\)/,
|
|
1079
|
+
/\(\s*req\s*:\s*\w+\s*,\s*res\s*:\s*\w+\s*\)/,
|
|
1080
|
+
];
|
|
1081
|
+
const FLOW_ACTION_PURE_FUNCTION_PATTERNS = [
|
|
1082
|
+
/^\s*(async\s+)?\(\s*ctx\s*,\s*input\s*\)\s*=>/,
|
|
1083
|
+
/^\s*(async\s+)?function\s+\w*\s*\(\s*ctx\s*,\s*input\s*\)/,
|
|
1084
|
+
/^\s*(async\s+)?function\s+\w*\s*\(\s*ctx\s*:\s*FlowCtx\s*,\s*input\s*:\s*any\s*\)/,
|
|
1085
|
+
/module\.exports\s*=\s*(async\s+)?\(\s*ctx\s*,\s*input\s*\)/,
|
|
1086
|
+
/module\.exports\s*=\s*(async\s+)?function\s*\(\s*ctx\s*,\s*input\s*\)/,
|
|
1087
|
+
/export\s+default\s+(async\s+)?\(\s*ctx\s*,\s*input\s*\)/,
|
|
1088
|
+
/export\s+default\s+(async\s+)?function\s*\(\s*ctx\s*,\s*input\s*\)/,
|
|
1089
|
+
];
|
|
1090
|
+
function isPlainObject(val) {
|
|
1091
|
+
return Boolean(val) && typeof val === "object" && !Array.isArray(val);
|
|
1092
|
+
}
|
|
1093
|
+
function validateFlowActionCode(code, nodeLabel, ctx) {
|
|
1094
|
+
if (typeof code !== "string" || code.trim() === "") {
|
|
1095
|
+
addError(ctx, nodeLabel, "action node missing non-empty code");
|
|
1096
|
+
return false;
|
|
1097
|
+
}
|
|
1098
|
+
const trimmed = code.trim();
|
|
1099
|
+
for (const pattern of FLOW_ACTION_FORBIDDEN_PATTERNS) {
|
|
1100
|
+
if (trimmed.includes(pattern)) {
|
|
1101
|
+
addError(ctx, nodeLabel, `action code contains forbidden pattern: ${pattern}`);
|
|
1102
|
+
return false;
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
for (const httpPattern of FLOW_ACTION_HTTP_PATTERNS) {
|
|
1106
|
+
if (httpPattern.test(trimmed)) {
|
|
1107
|
+
addError(ctx, nodeLabel, "FlowAction code must use (ctx, input) signature, not (req, res)");
|
|
1108
|
+
return false;
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
const hasPureFunction = FLOW_ACTION_PURE_FUNCTION_PATTERNS.some((pattern) => pattern.test(trimmed));
|
|
1112
|
+
const hasCtxAndInput = trimmed.includes("ctx") && trimmed.includes("input");
|
|
1113
|
+
if (!hasPureFunction && !hasCtxAndInput) {
|
|
1114
|
+
addError(ctx, nodeLabel, "action code must contain a function with (ctx, input) parameters");
|
|
1115
|
+
return false;
|
|
1116
|
+
}
|
|
1117
|
+
return true;
|
|
1118
|
+
}
|
|
1119
|
+
function validateFlowGraph(nodes, contextLabel, knownFlowIds, projectRoot, config, servicesConfig, assetsConfig, ctx) {
|
|
1120
|
+
const seenNodeNames = new Set();
|
|
1121
|
+
const validateNextRef = (nextRef, edgeLabel, nodeLabel) => {
|
|
1122
|
+
if (!isPlainObject(nextRef) ||
|
|
1123
|
+
typeof nextRef.nodeId !== "string" ||
|
|
1124
|
+
nextRef.nodeId.trim() === "") {
|
|
1125
|
+
addError(ctx, nodeLabel, `${edgeLabel} must be an object with a non-empty nodeId`);
|
|
1126
|
+
return;
|
|
1127
|
+
}
|
|
1128
|
+
if (!Object.prototype.hasOwnProperty.call(nodes, nextRef.nodeId)) {
|
|
1129
|
+
addError(ctx, nodeLabel, `${edgeLabel} references missing nodeId "${nextRef.nodeId}"`);
|
|
1130
|
+
}
|
|
1131
|
+
};
|
|
1132
|
+
const validateSubgraph = (subgraph, subgraphLabel) => {
|
|
1133
|
+
if (!isPlainObject(subgraph)) {
|
|
1134
|
+
addError(ctx, subgraphLabel, "subgraph must be an object with entry and nodes");
|
|
1135
|
+
return;
|
|
1136
|
+
}
|
|
1137
|
+
if (typeof subgraph.entry !== "string" || subgraph.entry.trim() === "") {
|
|
1138
|
+
addError(ctx, subgraphLabel, "subgraph missing non-empty entry node id");
|
|
1139
|
+
return;
|
|
1140
|
+
}
|
|
1141
|
+
if (!isPlainObject(subgraph.nodes)) {
|
|
1142
|
+
addError(ctx, subgraphLabel, "subgraph missing nodes object");
|
|
1143
|
+
return;
|
|
1144
|
+
}
|
|
1145
|
+
if (!Object.prototype.hasOwnProperty.call(subgraph.nodes, subgraph.entry)) {
|
|
1146
|
+
addError(ctx, subgraphLabel, `subgraph entry node "${subgraph.entry}" not found in nodes`);
|
|
1147
|
+
}
|
|
1148
|
+
validateFlowGraph(subgraph.nodes, subgraphLabel, knownFlowIds, projectRoot, config, servicesConfig, assetsConfig, ctx);
|
|
1149
|
+
};
|
|
1150
|
+
for (const [nodeId, node] of Object.entries(nodes)) {
|
|
1151
|
+
const nodeLabel = `${contextLabel} (node "${nodeId}")`;
|
|
1152
|
+
if (!isPlainObject(node)) {
|
|
1153
|
+
addError(ctx, nodeLabel, "node must be an object");
|
|
1154
|
+
continue;
|
|
1155
|
+
}
|
|
1156
|
+
if (typeof node.id !== "string" || node.id !== nodeId) {
|
|
1157
|
+
addError(ctx, nodeLabel, `node.id "${node.id}" must match node key "${nodeId}"`);
|
|
1158
|
+
}
|
|
1159
|
+
if (typeof node.type !== "string" ||
|
|
1160
|
+
!VALID_FLOW_NODE_TYPES.has(node.type)) {
|
|
1161
|
+
addError(ctx, nodeLabel, `invalid node.type "${node.type}". Must be one of: ${Array.from(VALID_FLOW_NODE_TYPES).join(", ")}`);
|
|
1162
|
+
}
|
|
1163
|
+
if (typeof node.nodeName !== "string" ||
|
|
1164
|
+
!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(node.nodeName)) {
|
|
1165
|
+
addError(ctx, nodeLabel, `invalid node.nodeName "${node.nodeName}". Must match /^[a-zA-Z][a-zA-Z0-9_]*$/`);
|
|
1166
|
+
}
|
|
1167
|
+
else if (seenNodeNames.has(node.nodeName)) {
|
|
1168
|
+
addError(ctx, nodeLabel, `duplicate node.nodeName "${node.nodeName}"`);
|
|
1169
|
+
}
|
|
1170
|
+
else {
|
|
1171
|
+
seenNodeNames.add(node.nodeName);
|
|
1172
|
+
}
|
|
1173
|
+
if (node.next !== undefined) {
|
|
1174
|
+
if (Array.isArray(node.next)) {
|
|
1175
|
+
node.next.forEach((ref, idx) => {
|
|
1176
|
+
validateNextRef(ref, `next[${idx}]`, nodeLabel);
|
|
1177
|
+
});
|
|
1178
|
+
}
|
|
1179
|
+
else {
|
|
1180
|
+
validateNextRef(node.next, "next", nodeLabel);
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
switch (node.type) {
|
|
1184
|
+
case "action": {
|
|
1185
|
+
if (validateFlowActionCode(node.code, nodeLabel, ctx)) {
|
|
1186
|
+
checkCodeServiceUsage(nodeLabel, node.code, config, servicesConfig, assetsConfig, ctx);
|
|
1187
|
+
}
|
|
1188
|
+
break;
|
|
1189
|
+
}
|
|
1190
|
+
case "if": {
|
|
1191
|
+
if (typeof node.condition !== "string" ||
|
|
1192
|
+
node.condition.trim() === "") {
|
|
1193
|
+
addError(ctx, nodeLabel, "if node missing non-empty condition");
|
|
1194
|
+
}
|
|
1195
|
+
validateNextRef(node.then, "if.then", nodeLabel);
|
|
1196
|
+
if (node.else !== undefined) {
|
|
1197
|
+
validateNextRef(node.else, "if.else", nodeLabel);
|
|
1198
|
+
}
|
|
1199
|
+
break;
|
|
1200
|
+
}
|
|
1201
|
+
case "switch": {
|
|
1202
|
+
if (typeof node.expression !== "string" ||
|
|
1203
|
+
node.expression.trim() === "") {
|
|
1204
|
+
addError(ctx, nodeLabel, "switch node missing non-empty expression");
|
|
1205
|
+
}
|
|
1206
|
+
if (!Array.isArray(node.cases) || node.cases.length === 0) {
|
|
1207
|
+
addError(ctx, nodeLabel, "switch node must have non-empty cases array");
|
|
1208
|
+
}
|
|
1209
|
+
else {
|
|
1210
|
+
node.cases.forEach((switchCase, idx) => {
|
|
1211
|
+
validateNextRef(switchCase?.next, `switch.cases[${idx}].next`, nodeLabel);
|
|
1212
|
+
});
|
|
1213
|
+
}
|
|
1214
|
+
if (node.default !== undefined) {
|
|
1215
|
+
validateNextRef(node.default, "switch.default", nodeLabel);
|
|
1216
|
+
}
|
|
1217
|
+
break;
|
|
1218
|
+
}
|
|
1219
|
+
case "loop": {
|
|
1220
|
+
if (typeof node.over !== "string" || node.over.trim() === "") {
|
|
1221
|
+
addError(ctx, nodeLabel, "loop node missing non-empty over");
|
|
1222
|
+
}
|
|
1223
|
+
validateSubgraph(node.body, `${nodeLabel}.body`);
|
|
1224
|
+
break;
|
|
1225
|
+
}
|
|
1226
|
+
case "retry": {
|
|
1227
|
+
if (typeof node.attempts !== "number" ||
|
|
1228
|
+
!Number.isFinite(node.attempts) ||
|
|
1229
|
+
node.attempts <= 0) {
|
|
1230
|
+
addError(ctx, nodeLabel, "retry node attempts must be a number greater than 0");
|
|
1231
|
+
}
|
|
1232
|
+
if (typeof node.delayMs !== "number" ||
|
|
1233
|
+
!Number.isFinite(node.delayMs) ||
|
|
1234
|
+
node.delayMs < 0) {
|
|
1235
|
+
addError(ctx, nodeLabel, "retry node delayMs must be a non-negative number");
|
|
1236
|
+
}
|
|
1237
|
+
validateSubgraph(node.body, `${nodeLabel}.body`);
|
|
1238
|
+
break;
|
|
1239
|
+
}
|
|
1240
|
+
case "parallel": {
|
|
1241
|
+
if (!isPlainObject(node.branches) ||
|
|
1242
|
+
Object.keys(node.branches).length === 0) {
|
|
1243
|
+
addError(ctx, nodeLabel, "parallel node must have non-empty branches object");
|
|
1244
|
+
}
|
|
1245
|
+
else {
|
|
1246
|
+
for (const [branchName, branchGraph] of Object.entries(node.branches)) {
|
|
1247
|
+
validateSubgraph(branchGraph, `${nodeLabel}.branches.${branchName}`);
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
break;
|
|
1251
|
+
}
|
|
1252
|
+
case "delay": {
|
|
1253
|
+
if (typeof node.delayMs !== "number" ||
|
|
1254
|
+
!Number.isFinite(node.delayMs) ||
|
|
1255
|
+
node.delayMs < 0) {
|
|
1256
|
+
addError(ctx, nodeLabel, "delay node delayMs must be a non-negative number");
|
|
1257
|
+
}
|
|
1258
|
+
break;
|
|
1259
|
+
}
|
|
1260
|
+
case "subflow": {
|
|
1261
|
+
if (typeof node.flowId !== "string" || node.flowId.trim() === "") {
|
|
1262
|
+
addError(ctx, nodeLabel, "subflow node missing non-empty flowId");
|
|
1263
|
+
}
|
|
1264
|
+
else if (!knownFlowIds.has(node.flowId) &&
|
|
1265
|
+
!fs.existsSync(path.join(projectRoot, "flows", node.flowId, "flow.json"))) {
|
|
1266
|
+
addError(ctx, nodeLabel, `subflow node references unknown flowId "${node.flowId}"`);
|
|
1267
|
+
}
|
|
1268
|
+
if (node.ctxPolicy !== undefined &&
|
|
1269
|
+
!["inherit", "clone", "subset"].includes(node.ctxPolicy)) {
|
|
1270
|
+
addError(ctx, nodeLabel, `subflow node ctxPolicy "${node.ctxPolicy}" must be one of: inherit, clone, subset`);
|
|
1271
|
+
}
|
|
1272
|
+
break;
|
|
1273
|
+
}
|
|
1274
|
+
case "human": {
|
|
1275
|
+
if (typeof node.assignee !== "string" ||
|
|
1276
|
+
node.assignee.trim() === "") {
|
|
1277
|
+
addError(ctx, nodeLabel, "human node missing non-empty assignee");
|
|
1278
|
+
}
|
|
1279
|
+
if (typeof node.varName !== "string" || node.varName.trim() === "") {
|
|
1280
|
+
addError(ctx, nodeLabel, "human node missing non-empty varName");
|
|
1281
|
+
}
|
|
1282
|
+
if (node.onTimeout !== undefined) {
|
|
1283
|
+
if (typeof node.onTimeout !== "string" ||
|
|
1284
|
+
!Object.prototype.hasOwnProperty.call(nodes, node.onTimeout)) {
|
|
1285
|
+
addError(ctx, nodeLabel, `human.onTimeout references missing nodeId "${node.onTimeout}"`);
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
break;
|
|
1289
|
+
}
|
|
1290
|
+
case "trigger":
|
|
1291
|
+
default:
|
|
1292
|
+
break;
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
function validateFlows(projectRoot, config, servicesConfig, assetsConfig, ctx) {
|
|
1297
|
+
const scanResult = scanFlowsDetailed(projectRoot);
|
|
1298
|
+
for (const warning of scanResult.warnings) {
|
|
1299
|
+
addWarning(ctx, warning.path, warning.message);
|
|
1300
|
+
}
|
|
1301
|
+
for (const error of scanResult.errors) {
|
|
1302
|
+
addError(ctx, error.path, error.message);
|
|
1303
|
+
}
|
|
1304
|
+
const knownFlowIds = new Set(scanResult.flows.map((f) => f.id));
|
|
1305
|
+
for (const flowDef of scanResult.flows) {
|
|
1306
|
+
const errorsBefore = ctx.errors.length;
|
|
1307
|
+
if (!isPlainObject(flowDef.flow)) {
|
|
1308
|
+
addError(ctx, flowDef.filePath, "invalid flow.json format");
|
|
1309
|
+
continue;
|
|
1310
|
+
}
|
|
1311
|
+
if (typeof flowDef.flow.entry !== "string" ||
|
|
1312
|
+
flowDef.flow.entry.trim() === "") {
|
|
1313
|
+
addError(ctx, flowDef.filePath, "flow.json missing entry node id");
|
|
1314
|
+
continue;
|
|
1315
|
+
}
|
|
1316
|
+
if (!isPlainObject(flowDef.flow.nodes)) {
|
|
1317
|
+
addError(ctx, flowDef.filePath, "flow.json missing nodes object");
|
|
1318
|
+
continue;
|
|
1319
|
+
}
|
|
1320
|
+
if (!Object.prototype.hasOwnProperty.call(flowDef.flow.nodes, flowDef.flow.entry)) {
|
|
1321
|
+
addError(ctx, flowDef.filePath, `entry node "${flowDef.flow.entry}" not found in nodes`);
|
|
1322
|
+
continue;
|
|
1323
|
+
}
|
|
1324
|
+
validateFlowGraph(flowDef.flow.nodes, flowDef.filePath, knownFlowIds, projectRoot, config, servicesConfig, assetsConfig, ctx);
|
|
1325
|
+
if (ctx.errors.length === errorsBefore) {
|
|
1326
|
+
ctx.stats.flows++;
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
export function validateProject(projectRoot = process.cwd(), options) {
|
|
1331
|
+
const ctx = createValidationContext();
|
|
1332
|
+
const configPath = path.join(projectRoot, "bestudio.config.json");
|
|
1333
|
+
// 1. Validate config
|
|
1334
|
+
const config = validateConfig(configPath, ctx);
|
|
1335
|
+
if (!config) {
|
|
1336
|
+
return {
|
|
1337
|
+
valid: false,
|
|
1338
|
+
errors: ctx.errors,
|
|
1339
|
+
warnings: ctx.warnings,
|
|
1340
|
+
stats: ctx.stats,
|
|
1341
|
+
};
|
|
1342
|
+
}
|
|
1343
|
+
let servicesConfig = null;
|
|
1344
|
+
try {
|
|
1345
|
+
servicesConfig = scanServices(projectRoot);
|
|
1346
|
+
}
|
|
1347
|
+
catch {
|
|
1348
|
+
// Handled by validateServices
|
|
1349
|
+
}
|
|
1350
|
+
let assetsConfig = null;
|
|
1351
|
+
try {
|
|
1352
|
+
assetsConfig = scanAssets(projectRoot);
|
|
1353
|
+
}
|
|
1354
|
+
catch {
|
|
1355
|
+
// Handled by validateAssets
|
|
1356
|
+
}
|
|
1357
|
+
// 2. Validate routes and actions
|
|
1358
|
+
validateRoutes(projectRoot, config, servicesConfig, assetsConfig, ctx);
|
|
1359
|
+
// 3. Validate jobs
|
|
1360
|
+
validateJobs(projectRoot, config, servicesConfig, assetsConfig, ctx);
|
|
1361
|
+
// 4. Validate services
|
|
1362
|
+
validateServices(projectRoot, ctx);
|
|
1363
|
+
// 5. Validate assets
|
|
1364
|
+
validateAssets(projectRoot, ctx);
|
|
1365
|
+
// 6. Validate models
|
|
1366
|
+
validateModels(projectRoot, ctx);
|
|
1367
|
+
// 7. Validate flows
|
|
1368
|
+
validateFlows(projectRoot, config, servicesConfig, assetsConfig, ctx);
|
|
1369
|
+
// 8. TypeScript validation (light check - warning if tsc not available)
|
|
1370
|
+
if (!options?.skipTypeScript) {
|
|
1371
|
+
validateTypeScript(projectRoot, ctx);
|
|
1372
|
+
}
|
|
1373
|
+
return {
|
|
1374
|
+
valid: ctx.errors.length === 0,
|
|
1375
|
+
errors: ctx.errors,
|
|
1376
|
+
warnings: ctx.warnings,
|
|
1377
|
+
stats: ctx.stats,
|
|
1378
|
+
};
|
|
1379
|
+
}
|
|
1380
|
+
export const validateCommand = new Command("validate")
|
|
1381
|
+
.description("Validate BE Studio project structure")
|
|
1382
|
+
.action(() => {
|
|
1383
|
+
const projectRoot = process.cwd();
|
|
1384
|
+
console.log("š Validating BE Studio project...\n");
|
|
1385
|
+
const result = validateProject(projectRoot);
|
|
1386
|
+
for (const info of getProjectSkillVersionInfo(projectRoot)) {
|
|
1387
|
+
console.log(`ā¹ ${info}`);
|
|
1388
|
+
}
|
|
1389
|
+
printResults(projectRoot, result);
|
|
1390
|
+
});
|
|
1391
|
+
function printResults(projectRoot, result) {
|
|
1392
|
+
const { warnings, errors, stats } = result;
|
|
1393
|
+
// Print warnings first
|
|
1394
|
+
if (warnings.length > 0) {
|
|
1395
|
+
console.log("\nValidation warnings:\n");
|
|
1396
|
+
for (const warning of warnings) {
|
|
1397
|
+
console.log(`ā ${warning.path}\n ā ${warning.message}`);
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
// Check canonical format (read-only check)
|
|
1401
|
+
const routesCanonical = isCanonical("routes", projectRoot);
|
|
1402
|
+
const jobsCanonical = isCanonical("jobs", projectRoot);
|
|
1403
|
+
const modelsCanonical = isCanonical("models", projectRoot);
|
|
1404
|
+
if (errors.length === 0) {
|
|
1405
|
+
console.log("\nā Project structure valid");
|
|
1406
|
+
console.log(`ā Routes validated: ${stats.routes}`);
|
|
1407
|
+
console.log(`ā Actions resolved: ${stats.actions}`);
|
|
1408
|
+
console.log(`ā Jobs validated: ${stats.jobs}`);
|
|
1409
|
+
console.log(`ā Models validated: ${stats.models}`);
|
|
1410
|
+
console.log(`ā Flows validated: ${stats.flows}`);
|
|
1411
|
+
// Canonical format check
|
|
1412
|
+
if (routesCanonical && jobsCanonical && modelsCanonical) {
|
|
1413
|
+
console.log("ā Canonical format: ok");
|
|
1414
|
+
}
|
|
1415
|
+
else {
|
|
1416
|
+
console.log("ā¹ Canonical format: check not fully implemented");
|
|
1417
|
+
}
|
|
1418
|
+
console.log("ā Validation successful");
|
|
1419
|
+
process.exit(0);
|
|
1420
|
+
}
|
|
1421
|
+
else {
|
|
1422
|
+
console.log("\nValidation errors:\n");
|
|
1423
|
+
for (const error of errors) {
|
|
1424
|
+
console.log(`ā ${error.path}\n ā ${error.message}`);
|
|
1425
|
+
}
|
|
1426
|
+
console.log("\nValidation failed ā");
|
|
1427
|
+
process.exit(1);
|
|
1428
|
+
}
|
|
1429
|
+
}
|