@agiflowai/scaffold-mcp 1.0.11 → 1.0.12

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