@agiflowai/scaffold-mcp 1.0.14 → 1.0.16

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.
Files changed (32) hide show
  1. package/dist/ListScaffoldingMethodsTool-RfVCiYIl.mjs +1016 -0
  2. package/dist/ListScaffoldingMethodsTool-dP6UGYi-.cjs +1104 -0
  3. package/dist/cli.cjs +11 -16
  4. package/dist/cli.mjs +5 -9
  5. package/dist/index.cjs +7 -11
  6. package/dist/index.mjs +2 -6
  7. package/dist/{stdio-AbTm52SJ.mjs → stdio-C0MGNdE2.mjs} +15 -18
  8. package/dist/{stdio-baUp7xGL.cjs → stdio-CMrGIHf9.cjs} +24 -28
  9. package/dist/{useScaffoldMethod-CcrpFEPv.cjs → useScaffoldMethod-CYcSFnmq.cjs} +1 -3
  10. package/dist/{useScaffoldMethod-DOvwnNOJ.cjs → useScaffoldMethod-CazDraH-.cjs} +10 -9
  11. package/dist/{useScaffoldMethod-CPgJIBHx.mjs → useScaffoldMethod-D5xkoGJE.mjs} +1 -2
  12. package/dist/{useScaffoldMethod-BMWhFebp.mjs → useScaffoldMethod-D_Bu4nj2.mjs} +7 -5
  13. package/package.json +4 -4
  14. package/dist/ListScaffoldingMethodsTool-B49G_iLj.mjs +0 -350
  15. package/dist/ListScaffoldingMethodsTool-DuYGFDwJ.cjs +0 -376
  16. package/dist/ScaffoldConfigLoader-8YI7v2GJ.mjs +0 -142
  17. package/dist/ScaffoldConfigLoader-BWpNpMx-.cjs +0 -150
  18. package/dist/ScaffoldConfigLoader-DKJtnrWT.mjs +0 -3
  19. package/dist/ScaffoldConfigLoader-HutEtfaH.cjs +0 -3
  20. package/dist/ScaffoldService-DSQBnAHm.cjs +0 -308
  21. package/dist/ScaffoldService-DcsGLMuD.mjs +0 -295
  22. package/dist/ScaffoldService-DfXjmrNT.cjs +0 -3
  23. package/dist/ScaffoldService-dL74anIv.mjs +0 -3
  24. package/dist/TemplateService-7QcWREot.cjs +0 -85
  25. package/dist/TemplateService-B1bd6iHw.mjs +0 -3
  26. package/dist/TemplateService-CVDL2uqt.mjs +0 -79
  27. package/dist/TemplateService-DUbdBOFs.cjs +0 -3
  28. package/dist/VariableReplacementService-B9RA8D0a.mjs +0 -66
  29. package/dist/VariableReplacementService-BO-UYgcf.mjs +0 -3
  30. package/dist/VariableReplacementService-DNYx0Dym.cjs +0 -73
  31. package/dist/VariableReplacementService-wuYKgeui.cjs +0 -3
  32. package/dist/chunk-CbDLau6x.cjs +0 -34
@@ -0,0 +1,1016 @@
1
+ import path from "node:path";
2
+ import { ProjectConfigResolver, TemplatesManagerService, copy, ensureDir, log, pathExists, readFile, readJson, readdir, stat, writeFile } from "@agiflowai/aicode-utils";
3
+ import yaml from "js-yaml";
4
+ import { jsonSchemaToZod } from "@composio/json-schema-to-zod";
5
+ import { z } from "zod";
6
+ import { fileURLToPath } from "node:url";
7
+ import { Liquid } from "liquidjs";
8
+
9
+ //#region src/utils/pagination.ts
10
+ var PaginationHelper = class PaginationHelper {
11
+ /**
12
+ * Default page size for pagination
13
+ */
14
+ static DEFAULT_PAGE_SIZE = 10;
15
+ /**
16
+ * Decodes a cursor string to extract the start index
17
+ * @param cursor - String representing the start index (e.g., "10")
18
+ * @returns Start index or 0 if invalid/undefined
19
+ */
20
+ static decodeCursor(cursor) {
21
+ if (!cursor) return 0;
22
+ const index = Number.parseInt(cursor, 10);
23
+ if (Number.isNaN(index) || index < 0) return 0;
24
+ return index;
25
+ }
26
+ /**
27
+ * Encodes an index into a cursor string
28
+ * @param index - Start index to encode
29
+ * @returns Cursor string (e.g., "10")
30
+ */
31
+ static encodeCursor(index) {
32
+ return index.toString();
33
+ }
34
+ /**
35
+ * Paginates an array of items
36
+ * @param items - All items to paginate
37
+ * @param cursor - Optional cursor representing the start index
38
+ * @param pageSize - Number of items per page (default: 10)
39
+ * @param includeMeta - Whether to include metadata in response (default: true)
40
+ * @returns Paginated result with items and optional nextCursor
41
+ */
42
+ static paginate(items, cursor, pageSize = PaginationHelper.DEFAULT_PAGE_SIZE, includeMeta = true) {
43
+ const startIndex = PaginationHelper.decodeCursor(cursor);
44
+ const endIndex = startIndex + pageSize;
45
+ const result = {
46
+ items: items.slice(startIndex, endIndex),
47
+ nextCursor: endIndex < items.length ? PaginationHelper.encodeCursor(endIndex) : void 0
48
+ };
49
+ if (includeMeta) result._meta = {
50
+ total: items.length,
51
+ offset: startIndex,
52
+ limit: pageSize
53
+ };
54
+ return result;
55
+ }
56
+ };
57
+
58
+ //#endregion
59
+ //#region src/services/FileSystemService.ts
60
+ var FileSystemService = class {
61
+ async pathExists(path$1) {
62
+ return pathExists(path$1);
63
+ }
64
+ async readFile(path$1, encoding = "utf8") {
65
+ return readFile(path$1, encoding);
66
+ }
67
+ async readJson(path$1) {
68
+ return readJson(path$1);
69
+ }
70
+ async writeFile(path$1, content, encoding = "utf8") {
71
+ return writeFile(path$1, content, encoding);
72
+ }
73
+ async ensureDir(path$1) {
74
+ return ensureDir(path$1);
75
+ }
76
+ async copy(src, dest) {
77
+ return copy(src, dest);
78
+ }
79
+ async readdir(path$1) {
80
+ return readdir(path$1);
81
+ }
82
+ async stat(path$1) {
83
+ return stat(path$1);
84
+ }
85
+ };
86
+
87
+ //#endregion
88
+ //#region src/services/ScaffoldConfigLoader.ts
89
+ const VariablesSchemaSchema = z.object({
90
+ type: z.literal("object"),
91
+ properties: z.record(z.any()),
92
+ required: z.array(z.string()),
93
+ additionalProperties: z.boolean()
94
+ });
95
+ const ScaffoldConfigEntrySchema = z.object({
96
+ name: z.string(),
97
+ description: z.string().optional(),
98
+ instruction: z.string().optional(),
99
+ targetFolder: z.string().optional(),
100
+ variables_schema: VariablesSchemaSchema,
101
+ includes: z.array(z.string()),
102
+ generator: z.string().optional(),
103
+ patterns: z.array(z.string()).optional()
104
+ });
105
+ const ScaffoldYamlSchema = z.object({
106
+ boilerplate: z.union([ScaffoldConfigEntrySchema, z.array(ScaffoldConfigEntrySchema)]).optional(),
107
+ features: z.union([ScaffoldConfigEntrySchema, z.array(ScaffoldConfigEntrySchema)]).optional()
108
+ }).catchall(z.union([ScaffoldConfigEntrySchema, z.array(ScaffoldConfigEntrySchema)]));
109
+ var ScaffoldConfigLoader = class {
110
+ constructor(fileSystem, templateService) {
111
+ this.fileSystem = fileSystem;
112
+ this.templateService = templateService;
113
+ }
114
+ async parseArchitectConfig(templatePath) {
115
+ const architectPath = path.join(templatePath, "scaffold.yaml");
116
+ if (!await this.fileSystem.pathExists(architectPath)) return null;
117
+ try {
118
+ const content = await this.fileSystem.readFile(architectPath, "utf8");
119
+ const rawConfig = yaml.load(content);
120
+ return ScaffoldYamlSchema.parse(rawConfig);
121
+ } catch (error) {
122
+ if (error instanceof z.ZodError) {
123
+ const errorMessages = error.errors.map((err) => `${err.path.join(".")}: ${err.message}`).join("; ");
124
+ throw new Error(`scaffold.yaml validation failed: ${errorMessages}`);
125
+ }
126
+ throw new Error(`Failed to parse scaffold.yaml: ${error instanceof Error ? error.message : String(error)}`);
127
+ }
128
+ }
129
+ parseIncludeEntry(includeEntry, variables) {
130
+ const [pathPart, conditionsPart] = includeEntry.split("?");
131
+ const conditions = {};
132
+ if (conditionsPart) {
133
+ const conditionPairs = conditionsPart.split("&");
134
+ for (const pair of conditionPairs) {
135
+ const [key, value] = pair.split("=");
136
+ if (key && value) conditions[key.trim()] = value.trim();
137
+ }
138
+ }
139
+ if (pathPart.includes("->")) {
140
+ const [sourcePath, targetPath] = pathPart.split("->").map((p) => p.trim());
141
+ return {
142
+ sourcePath,
143
+ targetPath: this.replaceVariablesInPath(targetPath, variables),
144
+ conditions
145
+ };
146
+ }
147
+ const processedPath = this.replaceVariablesInPath(pathPart.trim(), variables);
148
+ return {
149
+ sourcePath: pathPart.trim(),
150
+ targetPath: processedPath,
151
+ conditions
152
+ };
153
+ }
154
+ replaceVariablesInPath(pathStr, variables) {
155
+ return this.templateService.renderString(pathStr, variables);
156
+ }
157
+ shouldIncludeFile(conditions, variables) {
158
+ if (!conditions || Object.keys(conditions).length === 0) return true;
159
+ for (const [conditionKey, conditionValue] of Object.entries(conditions)) {
160
+ const variableValue = variables[conditionKey];
161
+ if (conditionValue === "true" || conditionValue === "false") {
162
+ const expectedBoolean = conditionValue === "true";
163
+ let actualBoolean;
164
+ if (typeof variableValue === "string") actualBoolean = variableValue.toLowerCase() === "true";
165
+ else actualBoolean = Boolean(variableValue);
166
+ if (actualBoolean !== expectedBoolean) return false;
167
+ } else if (String(variableValue) !== conditionValue) return false;
168
+ }
169
+ return true;
170
+ }
171
+ async validateTemplate(templatePath, scaffoldType) {
172
+ const errors = [];
173
+ const missingFiles = [];
174
+ if (!await this.fileSystem.pathExists(templatePath)) {
175
+ errors.push(`Template directory ${templatePath} does not exist`);
176
+ return {
177
+ isValid: false,
178
+ errors,
179
+ missingFiles
180
+ };
181
+ }
182
+ let architectConfig;
183
+ try {
184
+ architectConfig = await this.parseArchitectConfig(templatePath);
185
+ } catch (error) {
186
+ errors.push(`Failed to parse scaffold.yaml: ${error instanceof Error ? error.message : String(error)}`);
187
+ return {
188
+ isValid: false,
189
+ errors,
190
+ missingFiles
191
+ };
192
+ }
193
+ if (!architectConfig) {
194
+ errors.push("scaffold.yaml not found in template directory");
195
+ return {
196
+ isValid: false,
197
+ errors,
198
+ missingFiles
199
+ };
200
+ }
201
+ if (!architectConfig[scaffoldType]) {
202
+ const availableTypes = Object.keys(architectConfig).join(", ");
203
+ errors.push(`Scaffold type '${scaffoldType}' not found in scaffold.yaml. Available types: ${availableTypes}`);
204
+ return {
205
+ isValid: false,
206
+ errors,
207
+ missingFiles
208
+ };
209
+ }
210
+ const config = architectConfig[scaffoldType];
211
+ if (config.includes && Array.isArray(config.includes)) for (const includeFile of config.includes) {
212
+ const parsed = this.parseIncludeEntry(includeFile, {});
213
+ const sourcePath = path.join(templatePath, parsed.sourcePath);
214
+ const liquidSourcePath = `${sourcePath}.liquid`;
215
+ const sourceExists = await this.fileSystem.pathExists(sourcePath);
216
+ const liquidExists = await this.fileSystem.pathExists(liquidSourcePath);
217
+ if (!sourceExists && !liquidExists) missingFiles.push(includeFile);
218
+ }
219
+ return {
220
+ isValid: errors.length === 0 && missingFiles.length === 0,
221
+ errors,
222
+ missingFiles
223
+ };
224
+ }
225
+ };
226
+
227
+ //#endregion
228
+ //#region src/utils/schemaDefaults.ts
229
+ /**
230
+ * Applies schema defaults to variables without strict validation.
231
+ * This is useful when you want to fill in defaults but not fail on extra properties.
232
+ *
233
+ * @param schema - JSON Schema with properties and defaults
234
+ * @param variables - User-provided variables
235
+ * @returns Variables with defaults applied for missing properties
236
+ */
237
+ function applySchemaDefaults(schema, variables) {
238
+ const result = { ...variables };
239
+ if (!schema.properties) return result;
240
+ for (const [key, propSchema] of Object.entries(schema.properties)) if (result[key] === void 0 && propSchema.default !== void 0) result[key] = propSchema.default;
241
+ return result;
242
+ }
243
+
244
+ //#endregion
245
+ //#region src/services/ScaffoldProcessingService.ts
246
+ /**
247
+ * Shared service for common scaffolding operations like processing templates and tracking files
248
+ */
249
+ var ScaffoldProcessingService = class {
250
+ constructor(fileSystem, variableReplacer) {
251
+ this.fileSystem = fileSystem;
252
+ this.variableReplacer = variableReplacer;
253
+ }
254
+ /**
255
+ * Process a target path for variable replacement, handling both files and directories
256
+ */
257
+ async processTargetForVariableReplacement(targetPath, variables) {
258
+ if ((await this.fileSystem.stat(targetPath)).isDirectory()) await this.variableReplacer.processFilesForVariableReplacement(targetPath, variables);
259
+ else await this.variableReplacer.replaceVariablesInFile(targetPath, variables);
260
+ }
261
+ /**
262
+ * Track all created files, handling both single files and directories
263
+ */
264
+ async trackCreatedFiles(targetPath, createdFiles) {
265
+ if ((await this.fileSystem.stat(targetPath)).isDirectory()) await this.trackCreatedFilesRecursive(targetPath, createdFiles);
266
+ else createdFiles.push(targetPath);
267
+ }
268
+ /**
269
+ * Track all existing files, handling both single files and directories
270
+ */
271
+ async trackExistingFiles(targetPath, existingFiles) {
272
+ if ((await this.fileSystem.stat(targetPath)).isDirectory()) await this.trackExistingFilesRecursive(targetPath, existingFiles);
273
+ else existingFiles.push(targetPath);
274
+ }
275
+ /**
276
+ * Copy source to target, then process templates and track files
277
+ * Now supports tracking existing files separately from created files
278
+ * Automatically handles .liquid template files by stripping the extension
279
+ */
280
+ async copyAndProcess(sourcePath, targetPath, variables, createdFiles, existingFiles) {
281
+ await this.fileSystem.ensureDir(path.dirname(targetPath));
282
+ if (await this.fileSystem.pathExists(targetPath) && existingFiles) {
283
+ await this.trackExistingFiles(targetPath, existingFiles);
284
+ return;
285
+ }
286
+ let actualSourcePath = sourcePath;
287
+ if (!await this.fileSystem.pathExists(sourcePath)) {
288
+ const liquidSourcePath = `${sourcePath}.liquid`;
289
+ if (await this.fileSystem.pathExists(liquidSourcePath)) actualSourcePath = liquidSourcePath;
290
+ else throw new Error(`Source file not found: ${sourcePath} (also tried ${liquidSourcePath})`);
291
+ }
292
+ await this.fileSystem.copy(actualSourcePath, targetPath);
293
+ await this.processTargetForVariableReplacement(targetPath, variables);
294
+ await this.trackCreatedFiles(targetPath, createdFiles);
295
+ }
296
+ /**
297
+ * Recursively collect all file paths in a directory for created files
298
+ */
299
+ async trackCreatedFilesRecursive(dirPath, createdFiles) {
300
+ let items = [];
301
+ try {
302
+ items = await this.fileSystem.readdir(dirPath);
303
+ } catch (error) {
304
+ log.warn(`Cannot read directory ${dirPath}: ${error}`);
305
+ return;
306
+ }
307
+ const itemPaths = items.filter((item) => item).map((item) => path.join(dirPath, item));
308
+ const statResults = await Promise.all(itemPaths.map(async (itemPath) => {
309
+ try {
310
+ return {
311
+ itemPath,
312
+ stat: await this.fileSystem.stat(itemPath),
313
+ error: null
314
+ };
315
+ } catch (error) {
316
+ log.warn(`Cannot stat ${itemPath}: ${error}`);
317
+ return {
318
+ itemPath,
319
+ stat: null,
320
+ error
321
+ };
322
+ }
323
+ }));
324
+ const directories = [];
325
+ for (const { itemPath, stat: stat$1 } of statResults) {
326
+ if (!stat$1) continue;
327
+ if (stat$1.isDirectory()) directories.push(itemPath);
328
+ else if (stat$1.isFile()) createdFiles.push(itemPath);
329
+ }
330
+ await Promise.all(directories.map((dir) => this.trackCreatedFilesRecursive(dir, createdFiles)));
331
+ }
332
+ /**
333
+ * Recursively collect all file paths in a directory for existing files
334
+ */
335
+ async trackExistingFilesRecursive(dirPath, existingFiles) {
336
+ let items = [];
337
+ try {
338
+ items = await this.fileSystem.readdir(dirPath);
339
+ } catch (error) {
340
+ log.warn(`Cannot read directory ${dirPath}: ${error}`);
341
+ return;
342
+ }
343
+ const itemPaths = items.filter((item) => item).map((item) => path.join(dirPath, item));
344
+ const statResults = await Promise.all(itemPaths.map(async (itemPath) => {
345
+ try {
346
+ return {
347
+ itemPath,
348
+ stat: await this.fileSystem.stat(itemPath),
349
+ error: null
350
+ };
351
+ } catch (error) {
352
+ log.warn(`Cannot stat ${itemPath}: ${error}`);
353
+ return {
354
+ itemPath,
355
+ stat: null,
356
+ error
357
+ };
358
+ }
359
+ }));
360
+ const directories = [];
361
+ for (const { itemPath, stat: stat$1 } of statResults) {
362
+ if (!stat$1) continue;
363
+ if (stat$1.isDirectory()) directories.push(itemPath);
364
+ else if (stat$1.isFile()) existingFiles.push(itemPath);
365
+ }
366
+ await Promise.all(directories.map((dir) => this.trackExistingFilesRecursive(dir, existingFiles)));
367
+ }
368
+ };
369
+
370
+ //#endregion
371
+ //#region src/services/ScaffoldService.ts
372
+ var ScaffoldService = class {
373
+ templatesRootPath;
374
+ processingService;
375
+ constructor(fileSystem, scaffoldConfigLoader, variableReplacer, templatesRootPath) {
376
+ this.fileSystem = fileSystem;
377
+ this.scaffoldConfigLoader = scaffoldConfigLoader;
378
+ this.variableReplacer = variableReplacer;
379
+ const resolvedPath = templatesRootPath || TemplatesManagerService.findTemplatesPathSync();
380
+ if (!resolvedPath) throw new Error("Templates folder not found. Please create a \"templates\" folder in your workspace root, or specify \"templatesPath\" in toolkit.yaml to point to your templates directory.");
381
+ this.templatesRootPath = resolvedPath;
382
+ this.processingService = new ScaffoldProcessingService(fileSystem, variableReplacer);
383
+ }
384
+ /**
385
+ * Scaffold a new project from a boilerplate template
386
+ */
387
+ async useBoilerplate(options) {
388
+ try {
389
+ const { projectName, packageName, targetFolder, templateFolder, boilerplateName, variables = {} } = options;
390
+ const targetPath = path.isAbsolute(targetFolder) ? projectName ? path.join(targetFolder, projectName) : targetFolder : projectName ? path.join(process.cwd(), targetFolder, projectName) : path.join(process.cwd(), targetFolder);
391
+ const templatePath = path.join(this.templatesRootPath, templateFolder);
392
+ const validationResult = await this.scaffoldConfigLoader.validateTemplate(templatePath, "boilerplate");
393
+ if (!validationResult.isValid) return {
394
+ success: false,
395
+ message: `Template validation failed: ${[...validationResult.errors, ...validationResult.missingFiles.map((f) => `Template file not found: ${f}`)].join("; ")}`
396
+ };
397
+ if (projectName) {
398
+ if (await this.fileSystem.pathExists(targetPath)) return {
399
+ success: false,
400
+ message: `Directory ${targetPath} already exists`
401
+ };
402
+ }
403
+ const architectConfig = await this.scaffoldConfigLoader.parseArchitectConfig(templatePath);
404
+ if (!architectConfig || !architectConfig.boilerplate) return {
405
+ success: false,
406
+ message: `Invalid architect configuration: missing 'boilerplate' section in scaffold.yaml`
407
+ };
408
+ const boilerplateArray = architectConfig.boilerplate;
409
+ let config;
410
+ if (Array.isArray(boilerplateArray)) {
411
+ config = boilerplateArray.find((b) => b.name === boilerplateName);
412
+ if (!config) return {
413
+ success: false,
414
+ message: `Boilerplate '${boilerplateName}' not found in scaffold configuration`
415
+ };
416
+ } else config = architectConfig.boilerplate;
417
+ const effectiveProjectName = projectName || (packageName.includes("/") ? packageName.split("/")[1] : packageName);
418
+ const allVariables = {
419
+ ...variables,
420
+ projectName: effectiveProjectName,
421
+ packageName
422
+ };
423
+ return await this.processScaffold({
424
+ config,
425
+ targetPath,
426
+ templatePath,
427
+ allVariables,
428
+ scaffoldType: "boilerplate"
429
+ });
430
+ } catch (error) {
431
+ return {
432
+ success: false,
433
+ message: `Error scaffolding boilerplate: ${error instanceof Error ? error.message : String(error)}`
434
+ };
435
+ }
436
+ }
437
+ /**
438
+ * Scaffold a new feature into an existing project
439
+ */
440
+ async useFeature(options) {
441
+ try {
442
+ const { projectPath, templateFolder, featureName, variables = {} } = options;
443
+ const targetPath = path.resolve(projectPath);
444
+ const templatePath = path.join(this.templatesRootPath, templateFolder);
445
+ const projectName = path.basename(targetPath);
446
+ const validationResult = await this.scaffoldConfigLoader.validateTemplate(templatePath, "features");
447
+ if (!validationResult.isValid) return {
448
+ success: false,
449
+ message: `Template validation failed: ${[...validationResult.errors, ...validationResult.missingFiles.map((f) => `Template file not found: ${f}`)].join("; ")}`
450
+ };
451
+ if (!await this.fileSystem.pathExists(targetPath)) return {
452
+ success: false,
453
+ message: `Target directory ${targetPath} does not exist. Please create the parent directory first.`
454
+ };
455
+ const architectConfig = await this.scaffoldConfigLoader.parseArchitectConfig(templatePath);
456
+ if (!architectConfig || !architectConfig.features) return {
457
+ success: false,
458
+ message: `Invalid architect configuration: missing 'features' section in scaffold.yaml`
459
+ };
460
+ const featureArray = architectConfig.features;
461
+ let config;
462
+ if (Array.isArray(featureArray)) {
463
+ config = featureArray.find((f) => f.name === featureName);
464
+ if (!config) return {
465
+ success: false,
466
+ message: `Feature '${featureName}' not found in scaffold configuration`
467
+ };
468
+ } else config = architectConfig.features;
469
+ const allVariables = {
470
+ ...variables,
471
+ projectName,
472
+ appPath: targetPath,
473
+ appName: projectName
474
+ };
475
+ return await this.processScaffold({
476
+ config,
477
+ targetPath,
478
+ templatePath,
479
+ allVariables,
480
+ scaffoldType: "feature"
481
+ });
482
+ } catch (error) {
483
+ return {
484
+ success: false,
485
+ message: `Error scaffolding feature: ${error instanceof Error ? error.message : String(error)}`
486
+ };
487
+ }
488
+ }
489
+ /**
490
+ * Common scaffolding processing logic shared by both useBoilerplate and useFeature
491
+ */
492
+ async processScaffold(params) {
493
+ const { config, targetPath, templatePath, allVariables, scaffoldType } = params;
494
+ log.debug("Config generator:", config.generator);
495
+ log.debug("Config:", JSON.stringify(config, null, 2));
496
+ if (config.generator) {
497
+ log.info("Using custom generator:", config.generator);
498
+ try {
499
+ const generator = (await import(path.join(templatePath, "generators", config.generator))).default;
500
+ if (typeof generator !== "function") return {
501
+ success: false,
502
+ message: `Invalid generator: ${config.generator} does not export a default function`
503
+ };
504
+ return await generator({
505
+ variables: allVariables,
506
+ config,
507
+ targetPath,
508
+ templatePath,
509
+ fileSystem: this.fileSystem,
510
+ scaffoldConfigLoader: this.scaffoldConfigLoader,
511
+ variableReplacer: this.variableReplacer,
512
+ ScaffoldProcessingService: this.processingService.constructor,
513
+ getRootPath: () => {
514
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
515
+ return path.join(__dirname, "../../../../..");
516
+ },
517
+ getProjectPath: (projectPath) => {
518
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
519
+ const rootPath = path.join(__dirname, "../../../../..");
520
+ return projectPath.replace(rootPath, "").replace("/", "");
521
+ }
522
+ });
523
+ } catch (error) {
524
+ return {
525
+ success: false,
526
+ message: `Error loading or executing generator ${config.generator}: ${error instanceof Error ? error.message : String(error)}`
527
+ };
528
+ }
529
+ }
530
+ const parsedIncludes = [];
531
+ const warnings = [];
532
+ const variablesWithDefaults = config.variables_schema ? applySchemaDefaults(config.variables_schema, allVariables) : allVariables;
533
+ if (config.includes && Array.isArray(config.includes)) {
534
+ const filteredIncludes = config.includes.map((includeEntry) => this.scaffoldConfigLoader.parseIncludeEntry(includeEntry, variablesWithDefaults)).filter((parsed) => this.scaffoldConfigLoader.shouldIncludeFile(parsed.conditions, variablesWithDefaults));
535
+ const existsResults = await Promise.all(filteredIncludes.map(async (parsed) => {
536
+ const targetFilePath = path.join(targetPath, parsed.targetPath);
537
+ return {
538
+ parsed,
539
+ exists: await this.fileSystem.pathExists(targetFilePath)
540
+ };
541
+ }));
542
+ for (const { parsed, exists } of existsResults) {
543
+ parsedIncludes.push(parsed);
544
+ if (exists) warnings.push(`File/folder ${parsed.targetPath} already exists and will be preserved`);
545
+ }
546
+ }
547
+ await this.fileSystem.ensureDir(targetPath);
548
+ const createdFiles = [];
549
+ const existingFiles = [];
550
+ await Promise.all(parsedIncludes.map(async (parsed) => {
551
+ const sourcePath = path.join(templatePath, parsed.sourcePath);
552
+ const targetFilePath = path.join(targetPath, parsed.targetPath);
553
+ await this.processingService.copyAndProcess(sourcePath, targetFilePath, variablesWithDefaults, createdFiles, existingFiles);
554
+ }));
555
+ let message = `Successfully scaffolded ${scaffoldType} at ${targetPath}`;
556
+ if (existingFiles.length > 0) message += `. ${existingFiles.length} existing file(s) were preserved`;
557
+ message += ". Run 'pnpm install' to install dependencies.";
558
+ return {
559
+ success: true,
560
+ message,
561
+ warnings: warnings.length > 0 ? warnings : void 0,
562
+ createdFiles: createdFiles.length > 0 ? createdFiles : void 0,
563
+ existingFiles: existingFiles.length > 0 ? existingFiles : void 0
564
+ };
565
+ }
566
+ };
567
+
568
+ //#endregion
569
+ //#region src/services/TemplateService.ts
570
+ var TemplateService = class {
571
+ liquid;
572
+ constructor() {
573
+ this.liquid = new Liquid({
574
+ strictFilters: false,
575
+ strictVariables: false
576
+ });
577
+ this.setupCustomFilters();
578
+ log.info("TemplateService initialized");
579
+ }
580
+ toPascalCase(str) {
581
+ const camelCase = str.replace(/[-_\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : "");
582
+ return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);
583
+ }
584
+ setupCustomFilters() {
585
+ this.liquid.registerFilter("camelCase", (str) => {
586
+ return str.replace(/[-_\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : "");
587
+ });
588
+ this.liquid.registerFilter("pascalCase", (str) => {
589
+ return this.toPascalCase(str);
590
+ });
591
+ this.liquid.registerFilter("titleCase", (str) => {
592
+ return this.toPascalCase(str);
593
+ });
594
+ this.liquid.registerFilter("kebabCase", (str) => {
595
+ return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
596
+ });
597
+ this.liquid.registerFilter("snakeCase", (str) => {
598
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[\s-]+/g, "_").toLowerCase();
599
+ });
600
+ this.liquid.registerFilter("upperCase", (str) => {
601
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[\s-]+/g, "_").toUpperCase();
602
+ });
603
+ this.liquid.registerFilter("lower", (str) => str.toLowerCase());
604
+ this.liquid.registerFilter("upper", (str) => str.toUpperCase());
605
+ this.liquid.registerFilter("pluralize", (str) => {
606
+ if (str.endsWith("y")) return `${str.slice(0, -1)}ies`;
607
+ else if (str.endsWith("s") || str.endsWith("sh") || str.endsWith("ch") || str.endsWith("x") || str.endsWith("z")) return `${str}es`;
608
+ else return `${str}s`;
609
+ });
610
+ this.liquid.registerFilter("singularize", (str) => {
611
+ if (str.endsWith("ies")) return `${str.slice(0, -3)}y`;
612
+ else if (str.endsWith("es")) return str.slice(0, -2);
613
+ else if (str.endsWith("s") && !str.endsWith("ss")) return str.slice(0, -1);
614
+ else return str;
615
+ });
616
+ this.liquid.registerFilter("strip", (str) => {
617
+ return str.trim();
618
+ });
619
+ }
620
+ renderString(template, variables) {
621
+ try {
622
+ log.debug("Rendering template", {
623
+ variables,
624
+ templatePreview: template.substring(0, 100)
625
+ });
626
+ const result = this.liquid.parseAndRenderSync(template, variables);
627
+ log.debug("Rendered template", { resultPreview: result.substring(0, 100) });
628
+ return result;
629
+ } catch (error) {
630
+ log.error("LiquidJS rendering error", {
631
+ error: error instanceof Error ? error.message : String(error),
632
+ templatePreview: template.substring(0, 200),
633
+ variables
634
+ });
635
+ return template;
636
+ }
637
+ }
638
+ containsTemplateVariables(content) {
639
+ return [/\{\{.*?\}\}/, /\{%.*?%\}/].some((pattern) => pattern.test(content));
640
+ }
641
+ };
642
+
643
+ //#endregion
644
+ //#region src/services/VariableReplacementService.ts
645
+ var VariableReplacementService = class {
646
+ binaryExtensions = [
647
+ ".png",
648
+ ".jpg",
649
+ ".jpeg",
650
+ ".gif",
651
+ ".ico",
652
+ ".woff",
653
+ ".woff2",
654
+ ".ttf",
655
+ ".eot",
656
+ ".pdf",
657
+ ".zip",
658
+ ".tar",
659
+ ".gz",
660
+ ".exe",
661
+ ".dll",
662
+ ".so",
663
+ ".dylib"
664
+ ];
665
+ constructor(fileSystem, templateService) {
666
+ this.fileSystem = fileSystem;
667
+ this.templateService = templateService;
668
+ }
669
+ async processFilesForVariableReplacement(dirPath, variables) {
670
+ let items = [];
671
+ try {
672
+ items = await this.fileSystem.readdir(dirPath);
673
+ } catch (error) {
674
+ log.warn(`Skipping directory ${dirPath}: ${error}`);
675
+ return;
676
+ }
677
+ const itemPaths = items.filter((item) => item).map((item) => path.join(dirPath, item));
678
+ const statResults = await Promise.all(itemPaths.map(async (itemPath) => {
679
+ try {
680
+ return {
681
+ itemPath,
682
+ stat: await this.fileSystem.stat(itemPath),
683
+ error: null
684
+ };
685
+ } catch (error) {
686
+ log.warn(`Skipping item ${itemPath}: ${error}`);
687
+ return {
688
+ itemPath,
689
+ stat: null,
690
+ error
691
+ };
692
+ }
693
+ }));
694
+ const directories = [];
695
+ const files = [];
696
+ for (const { itemPath, stat: stat$1 } of statResults) {
697
+ if (!stat$1) continue;
698
+ if (stat$1.isDirectory()) directories.push(itemPath);
699
+ else if (stat$1.isFile()) files.push(itemPath);
700
+ }
701
+ await Promise.all([...files.map((file) => this.replaceVariablesInFile(file, variables)), ...directories.map((dir) => this.processFilesForVariableReplacement(dir, variables))]);
702
+ }
703
+ async replaceVariablesInFile(filePath, variables) {
704
+ try {
705
+ if (this.isBinaryFile(filePath)) return;
706
+ const content = await this.fileSystem.readFile(filePath, "utf8");
707
+ const renderedContent = this.templateService.renderString(content, variables);
708
+ await this.fileSystem.writeFile(filePath, renderedContent, "utf8");
709
+ } catch (error) {
710
+ log.warn(`Skipping file ${filePath}: ${error}`);
711
+ }
712
+ }
713
+ isBinaryFile(filePath) {
714
+ const ext = path.extname(filePath).toLowerCase();
715
+ return this.binaryExtensions.includes(ext);
716
+ }
717
+ };
718
+
719
+ //#endregion
720
+ //#region src/services/ScaffoldingMethodsService.ts
721
+ var ScaffoldingMethodsService = class {
722
+ templateService;
723
+ constructor(fileSystem, templatesRootPath) {
724
+ this.fileSystem = fileSystem;
725
+ this.templatesRootPath = templatesRootPath;
726
+ this.templateService = new TemplateService();
727
+ }
728
+ async listScaffoldingMethods(projectPath, cursor) {
729
+ const absoluteProjectPath = path.resolve(projectPath);
730
+ const sourceTemplate = (await ProjectConfigResolver.resolveProjectConfig(absoluteProjectPath)).sourceTemplate;
731
+ return this.listScaffoldingMethodsByTemplate(sourceTemplate, cursor);
732
+ }
733
+ async listScaffoldingMethodsByTemplate(templateName, cursor) {
734
+ const templatePath = await this.findTemplatePath(templateName);
735
+ if (!templatePath) throw new Error(`Template not found for sourceTemplate: ${templateName}`);
736
+ const fullTemplatePath = path.join(this.templatesRootPath, templatePath);
737
+ const scaffoldYamlPath = path.join(fullTemplatePath, "scaffold.yaml");
738
+ if (!await this.fileSystem.pathExists(scaffoldYamlPath)) throw new Error(`scaffold.yaml not found at ${scaffoldYamlPath}`);
739
+ const scaffoldContent = await this.fileSystem.readFile(scaffoldYamlPath, "utf8");
740
+ const architectConfig = yaml.load(scaffoldContent);
741
+ const methods = [];
742
+ if (architectConfig.features && Array.isArray(architectConfig.features)) architectConfig.features.forEach((feature) => {
743
+ const featureName = feature.name || `scaffold-${templateName}`;
744
+ methods.push({
745
+ name: featureName,
746
+ description: feature.description || "",
747
+ instruction: feature.instruction || "",
748
+ variables_schema: feature.variables_schema || {
749
+ type: "object",
750
+ properties: {},
751
+ required: [],
752
+ additionalProperties: false
753
+ },
754
+ generator: feature.generator
755
+ });
756
+ });
757
+ const paginatedResult = PaginationHelper.paginate(methods, cursor);
758
+ return {
759
+ sourceTemplate: templateName,
760
+ templatePath,
761
+ methods: paginatedResult.items,
762
+ nextCursor: paginatedResult.nextCursor,
763
+ _meta: paginatedResult._meta
764
+ };
765
+ }
766
+ /**
767
+ * Gets scaffolding methods with instructions rendered using provided variables
768
+ */
769
+ async listScaffoldingMethodsWithVariables(projectPath, variables, cursor) {
770
+ const result = await this.listScaffoldingMethods(projectPath, cursor);
771
+ const processedMethods = result.methods.map((method) => ({
772
+ ...method,
773
+ instruction: method.instruction ? this.processScaffoldInstruction(method.instruction, variables) : void 0
774
+ }));
775
+ return {
776
+ ...result,
777
+ methods: processedMethods
778
+ };
779
+ }
780
+ /**
781
+ * Processes scaffold instruction with template service
782
+ */
783
+ processScaffoldInstruction(instruction, variables) {
784
+ if (this.templateService.containsTemplateVariables(instruction)) return this.templateService.renderString(instruction, variables);
785
+ return instruction;
786
+ }
787
+ async findTemplatePath(sourceTemplate) {
788
+ const templateDirs = await this.discoverTemplateDirs();
789
+ if (templateDirs.includes(sourceTemplate)) return sourceTemplate;
790
+ for (const templateDir of templateDirs) {
791
+ const templatePath = path.join(this.templatesRootPath, templateDir);
792
+ const scaffoldYamlPath = path.join(templatePath, "scaffold.yaml");
793
+ if (await this.fileSystem.pathExists(scaffoldYamlPath)) try {
794
+ const scaffoldContent = await this.fileSystem.readFile(scaffoldYamlPath, "utf8");
795
+ const architectConfig = yaml.load(scaffoldContent);
796
+ if (architectConfig.boilerplate && Array.isArray(architectConfig.boilerplate)) {
797
+ for (const boilerplate of architectConfig.boilerplate) if (boilerplate.name?.includes(sourceTemplate)) return templateDir;
798
+ }
799
+ } catch (error) {
800
+ log.warn(`Failed to read scaffold.yaml at ${scaffoldYamlPath}:`, error);
801
+ }
802
+ }
803
+ return null;
804
+ }
805
+ /**
806
+ * Resolves the project path, handling both monorepo and monolith cases
807
+ * Uses ProjectConfigResolver to find the correct workspace/project root
808
+ */
809
+ async resolveProjectPath(projectPath) {
810
+ const absolutePath = path.resolve(projectPath);
811
+ return (await ProjectConfigResolver.resolveProjectConfig(absolutePath)).workspaceRoot || absolutePath;
812
+ }
813
+ /**
814
+ * Dynamically discovers all template directories
815
+ * Supports both flat structure (templates/nextjs-15) and nested structure (templates/apps/nextjs-15)
816
+ **/
817
+ async discoverTemplateDirs() {
818
+ const templateDirs = [];
819
+ try {
820
+ const itemPaths = (await this.fileSystem.readdir(this.templatesRootPath)).map((item) => ({
821
+ item,
822
+ itemPath: path.join(this.templatesRootPath, item)
823
+ }));
824
+ const itemResults = await Promise.all(itemPaths.map(async ({ item, itemPath }) => {
825
+ try {
826
+ if (!(await this.fileSystem.stat(itemPath)).isDirectory()) return {
827
+ item,
828
+ itemPath,
829
+ isDir: false,
830
+ hasScaffold: false
831
+ };
832
+ const scaffoldYamlPath = path.join(itemPath, "scaffold.yaml");
833
+ return {
834
+ item,
835
+ itemPath,
836
+ isDir: true,
837
+ hasScaffold: await this.fileSystem.pathExists(scaffoldYamlPath)
838
+ };
839
+ } catch {
840
+ return {
841
+ item,
842
+ itemPath,
843
+ isDir: false,
844
+ hasScaffold: false
845
+ };
846
+ }
847
+ }));
848
+ const categoryDirs = [];
849
+ for (const result of itemResults) {
850
+ if (!result.isDir) continue;
851
+ if (result.hasScaffold) templateDirs.push(result.item);
852
+ else categoryDirs.push({
853
+ item: result.item,
854
+ itemPath: result.itemPath
855
+ });
856
+ }
857
+ const nestedResults = await Promise.all(categoryDirs.map(async ({ item, itemPath }) => {
858
+ const found = [];
859
+ try {
860
+ const subItems = await this.fileSystem.readdir(itemPath);
861
+ const subResults = await Promise.all(subItems.map(async (subItem) => {
862
+ const subItemPath = path.join(itemPath, subItem);
863
+ try {
864
+ if (!(await this.fileSystem.stat(subItemPath)).isDirectory()) return null;
865
+ const subScaffoldYamlPath = path.join(subItemPath, "scaffold.yaml");
866
+ if (await this.fileSystem.pathExists(subScaffoldYamlPath)) return path.join(item, subItem);
867
+ } catch {
868
+ return null;
869
+ }
870
+ return null;
871
+ }));
872
+ for (const relativePath of subResults) if (relativePath) found.push(relativePath);
873
+ } catch (error) {
874
+ log.warn(`Failed to read subdirectories in ${itemPath}:`, error);
875
+ }
876
+ return found;
877
+ }));
878
+ for (const dirs of nestedResults) templateDirs.push(...dirs);
879
+ } catch (error) {
880
+ log.warn(`Failed to read templates root directory ${this.templatesRootPath}:`, error);
881
+ }
882
+ return templateDirs;
883
+ }
884
+ async useScaffoldMethod(request) {
885
+ const { projectPath, scaffold_feature_name, variables, sessionId } = request;
886
+ const absoluteProjectPath = await this.resolveProjectPath(projectPath);
887
+ const scaffoldingMethods = await this.listScaffoldingMethods(absoluteProjectPath);
888
+ const method = scaffoldingMethods.methods.find((m) => m.name === scaffold_feature_name);
889
+ if (!method) {
890
+ const availableMethods = scaffoldingMethods.methods.map((m) => m.name).join(", ");
891
+ throw new Error(`Scaffold method '${scaffold_feature_name}' not found. Available methods: ${availableMethods}`);
892
+ }
893
+ const templateService = new TemplateService();
894
+ const scaffoldConfigLoader = new ScaffoldConfigLoader(this.fileSystem, templateService);
895
+ const variableReplacer = new VariableReplacementService(this.fileSystem, templateService);
896
+ const scaffoldService = new ScaffoldService(this.fileSystem, scaffoldConfigLoader, variableReplacer, this.templatesRootPath);
897
+ const projectName = path.basename(absoluteProjectPath);
898
+ const result = await scaffoldService.useFeature({
899
+ projectPath: absoluteProjectPath,
900
+ templateFolder: scaffoldingMethods.templatePath,
901
+ featureName: scaffold_feature_name,
902
+ variables: {
903
+ ...variables,
904
+ appPath: absoluteProjectPath,
905
+ appName: projectName
906
+ }
907
+ });
908
+ if (!result.success) throw new Error(result.message);
909
+ if (sessionId && result.createdFiles && result.createdFiles.length > 0) try {
910
+ const { ExecutionLogService, DECISION_ALLOW } = await import("@agiflowai/hooks-adapter");
911
+ await new ExecutionLogService(sessionId).logExecution({
912
+ filePath: absoluteProjectPath,
913
+ operation: "scaffold",
914
+ decision: DECISION_ALLOW,
915
+ generatedFiles: result.createdFiles
916
+ });
917
+ } catch (error) {
918
+ log.warn("Failed to log scaffold execution:", error);
919
+ }
920
+ return {
921
+ success: true,
922
+ message: `
923
+ Successfully scaffolded ${scaffold_feature_name} in ${projectPath}.
924
+ Please follow this **instruction**: \n ${method.instruction ? this.processScaffoldInstruction(method.instruction, variables) : ""}.
925
+ -> Create or update the plan based on the instruction.
926
+ `,
927
+ warnings: result.warnings,
928
+ createdFiles: result.createdFiles,
929
+ existingFiles: result.existingFiles
930
+ };
931
+ }
932
+ };
933
+
934
+ //#endregion
935
+ //#region src/instructions/tools/list-scaffolding-methods/description.md?raw
936
+ var description_default = "Lists all available scaffolding methods (features) that can be added to an existing project{% if not isMonolith %} or for a specific template{% endif %}.\n\nThis tool:\n{% if isMonolith %}\n- Reads your project's sourceTemplate from toolkit.yaml at workspace root\n{% else %}\n- Reads the project's sourceTemplate from project.json (monorepo) or toolkit.yaml (monolith), OR\n- Directly uses the provided templateName to list available features\n{% endif %}\n- Returns available features for that template type\n- Provides variable schemas for each scaffolding method\n- Shows descriptions of what each method creates\n\nUse this FIRST when adding features to understand:\n- What scaffolding methods are available\n- What variables each method requires\n- What files/features will be generated\n\nExample methods might include:\n- Adding new React routes (for React apps)\n- Creating API endpoints (for backend projects)\n- Adding new components (for frontend projects)\n- Setting up database models (for API projects)\n";
937
+
938
+ //#endregion
939
+ //#region src/tools/ListScaffoldingMethodsTool.ts
940
+ var ListScaffoldingMethodsTool = class ListScaffoldingMethodsTool {
941
+ static TOOL_NAME = "list-scaffolding-methods";
942
+ fileSystemService;
943
+ scaffoldingMethodsService;
944
+ templateService;
945
+ isMonolith;
946
+ constructor(templatesPath, isMonolith = false) {
947
+ this.fileSystemService = new FileSystemService();
948
+ this.scaffoldingMethodsService = new ScaffoldingMethodsService(this.fileSystemService, templatesPath);
949
+ this.templateService = new TemplateService();
950
+ this.isMonolith = isMonolith;
951
+ }
952
+ /**
953
+ * Get the tool definition for MCP
954
+ */
955
+ getDefinition() {
956
+ const description = this.templateService.renderString(description_default, { isMonolith: this.isMonolith });
957
+ const properties = { cursor: {
958
+ type: "string",
959
+ description: "Optional pagination cursor to fetch the next page of results. Omit to fetch the first page."
960
+ } };
961
+ if (!this.isMonolith) {
962
+ properties.projectPath = {
963
+ type: "string",
964
+ description: "Absolute path to the project directory (for monorepo: containing project.json; for monolith: workspace root with toolkit.yaml). Either projectPath or templateName is required."
965
+ };
966
+ properties.templateName = {
967
+ type: "string",
968
+ description: "Name of the template to list scaffolding methods for (e.g., \"nextjs-15\", \"typescript-mcp-package\"). Either projectPath or templateName is required."
969
+ };
970
+ }
971
+ return {
972
+ name: ListScaffoldingMethodsTool.TOOL_NAME,
973
+ description: description.trim(),
974
+ inputSchema: {
975
+ type: "object",
976
+ properties,
977
+ additionalProperties: false
978
+ }
979
+ };
980
+ }
981
+ /**
982
+ * Execute the tool
983
+ */
984
+ async execute(args) {
985
+ try {
986
+ const { projectPath, templateName, cursor } = args;
987
+ let result;
988
+ if (this.isMonolith) try {
989
+ const resolvedTemplateName = (await ProjectConfigResolver.resolveProjectConfig(process.cwd())).sourceTemplate;
990
+ result = await this.scaffoldingMethodsService.listScaffoldingMethodsByTemplate(resolvedTemplateName, cursor);
991
+ } catch (error) {
992
+ throw new Error(`Failed to read template name from configuration: ${error instanceof Error ? error.message : String(error)}`);
993
+ }
994
+ else {
995
+ if (!projectPath && !templateName) throw new Error("Either projectPath or templateName must be provided");
996
+ if (projectPath) result = await this.scaffoldingMethodsService.listScaffoldingMethods(projectPath, cursor);
997
+ else result = await this.scaffoldingMethodsService.listScaffoldingMethodsByTemplate(templateName, cursor);
998
+ }
999
+ return { content: [{
1000
+ type: "text",
1001
+ text: JSON.stringify(result, null, 2)
1002
+ }] };
1003
+ } catch (error) {
1004
+ return {
1005
+ content: [{
1006
+ type: "text",
1007
+ text: `Error listing scaffolding methods: ${error instanceof Error ? error.message : String(error)}`
1008
+ }],
1009
+ isError: true
1010
+ };
1011
+ }
1012
+ }
1013
+ };
1014
+
1015
+ //#endregion
1016
+ export { ScaffoldService as a, FileSystemService as c, TemplateService as i, PaginationHelper as l, ScaffoldingMethodsService as n, ScaffoldProcessingService as o, VariableReplacementService as r, ScaffoldConfigLoader as s, ListScaffoldingMethodsTool as t };