mycontext-cli 0.2.0 → 0.2.2

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 (136) hide show
  1. package/README.md +17 -16
  2. package/dist/cli.js +6 -2
  3. package/dist/cli.js.map +1 -1
  4. package/dist/commands/init.d.ts +3 -0
  5. package/dist/commands/init.d.ts.map +1 -1
  6. package/dist/commands/init.js +118 -11
  7. package/dist/commands/init.js.map +1 -1
  8. package/dist/commands/setup.d.ts.map +1 -1
  9. package/dist/commands/setup.js +8 -0
  10. package/dist/commands/setup.js.map +1 -1
  11. package/dist/config/dependencies.json +180 -0
  12. package/package.json +9 -8
  13. package/dist/cli/src/agents/implementations/CodeGenSubAgent.d.ts +0 -44
  14. package/dist/cli/src/agents/implementations/CodeGenSubAgent.d.ts.map +0 -1
  15. package/dist/cli/src/agents/implementations/CodeGenSubAgent.js +0 -1374
  16. package/dist/cli/src/agents/implementations/CodeGenSubAgent.js.map +0 -1
  17. package/dist/cli/src/agents/implementations/DocsSubAgent.d.ts +0 -35
  18. package/dist/cli/src/agents/implementations/DocsSubAgent.d.ts.map +0 -1
  19. package/dist/cli/src/agents/implementations/DocsSubAgent.js +0 -351
  20. package/dist/cli/src/agents/implementations/DocsSubAgent.js.map +0 -1
  21. package/dist/cli/src/agents/implementations/EnhancementAgent.d.ts +0 -120
  22. package/dist/cli/src/agents/implementations/EnhancementAgent.d.ts.map +0 -1
  23. package/dist/cli/src/agents/implementations/EnhancementAgent.js +0 -606
  24. package/dist/cli/src/agents/implementations/EnhancementAgent.js.map +0 -1
  25. package/dist/cli/src/agents/implementations/QASubAgent.d.ts +0 -31
  26. package/dist/cli/src/agents/implementations/QASubAgent.d.ts.map +0 -1
  27. package/dist/cli/src/agents/implementations/QASubAgent.js +0 -190
  28. package/dist/cli/src/agents/implementations/QASubAgent.js.map +0 -1
  29. package/dist/cli/src/agents/interfaces/SubAgent.d.ts +0 -287
  30. package/dist/cli/src/agents/interfaces/SubAgent.d.ts.map +0 -1
  31. package/dist/cli/src/agents/interfaces/SubAgent.js +0 -7
  32. package/dist/cli/src/agents/interfaces/SubAgent.js.map +0 -1
  33. package/dist/cli/src/agents/orchestrator/SubAgentOrchestrator.d.ts +0 -59
  34. package/dist/cli/src/agents/orchestrator/SubAgentOrchestrator.d.ts.map +0 -1
  35. package/dist/cli/src/agents/orchestrator/SubAgentOrchestrator.js +0 -305
  36. package/dist/cli/src/agents/orchestrator/SubAgentOrchestrator.js.map +0 -1
  37. package/dist/cli/src/agents/personalities/definitions.d.ts +0 -34
  38. package/dist/cli/src/agents/personalities/definitions.d.ts.map +0 -1
  39. package/dist/cli/src/agents/personalities/definitions.js +0 -389
  40. package/dist/cli/src/agents/personalities/definitions.js.map +0 -1
  41. package/dist/cli/src/cli.d.ts +0 -3
  42. package/dist/cli/src/cli.d.ts.map +0 -1
  43. package/dist/cli/src/cli.js +0 -298
  44. package/dist/cli/src/cli.js.map +0 -1
  45. package/dist/cli/src/commands/auth.d.ts +0 -23
  46. package/dist/cli/src/commands/auth.d.ts.map +0 -1
  47. package/dist/cli/src/commands/auth.js +0 -212
  48. package/dist/cli/src/commands/auth.js.map +0 -1
  49. package/dist/cli/src/commands/enhance.d.ts +0 -28
  50. package/dist/cli/src/commands/enhance.d.ts.map +0 -1
  51. package/dist/cli/src/commands/enhance.js +0 -246
  52. package/dist/cli/src/commands/enhance.js.map +0 -1
  53. package/dist/cli/src/commands/generate-components.d.ts +0 -27
  54. package/dist/cli/src/commands/generate-components.d.ts.map +0 -1
  55. package/dist/cli/src/commands/generate-components.js +0 -680
  56. package/dist/cli/src/commands/generate-components.js.map +0 -1
  57. package/dist/cli/src/commands/generate.d.ts +0 -108
  58. package/dist/cli/src/commands/generate.d.ts.map +0 -1
  59. package/dist/cli/src/commands/generate.js +0 -1970
  60. package/dist/cli/src/commands/generate.js.map +0 -1
  61. package/dist/cli/src/commands/init.d.ts +0 -13
  62. package/dist/cli/src/commands/init.d.ts.map +0 -1
  63. package/dist/cli/src/commands/init.js +0 -91
  64. package/dist/cli/src/commands/init.js.map +0 -1
  65. package/dist/cli/src/commands/list.d.ts +0 -17
  66. package/dist/cli/src/commands/list.d.ts.map +0 -1
  67. package/dist/cli/src/commands/list.js +0 -210
  68. package/dist/cli/src/commands/list.js.map +0 -1
  69. package/dist/cli/src/commands/model.d.ts +0 -25
  70. package/dist/cli/src/commands/model.d.ts.map +0 -1
  71. package/dist/cli/src/commands/model.js +0 -317
  72. package/dist/cli/src/commands/model.js.map +0 -1
  73. package/dist/cli/src/commands/preview.d.ts +0 -23
  74. package/dist/cli/src/commands/preview.d.ts.map +0 -1
  75. package/dist/cli/src/commands/preview.js +0 -1200
  76. package/dist/cli/src/commands/preview.js.map +0 -1
  77. package/dist/cli/src/commands/setup.d.ts +0 -35
  78. package/dist/cli/src/commands/setup.d.ts.map +0 -1
  79. package/dist/cli/src/commands/setup.js +0 -412
  80. package/dist/cli/src/commands/setup.js.map +0 -1
  81. package/dist/cli/src/commands/status.d.ts +0 -21
  82. package/dist/cli/src/commands/status.d.ts.map +0 -1
  83. package/dist/cli/src/commands/status.js +0 -287
  84. package/dist/cli/src/commands/status.js.map +0 -1
  85. package/dist/cli/src/commands/validate.d.ts +0 -22
  86. package/dist/cli/src/commands/validate.d.ts.map +0 -1
  87. package/dist/cli/src/commands/validate.js +0 -259
  88. package/dist/cli/src/commands/validate.js.map +0 -1
  89. package/dist/cli/src/types/index.d.ts +0 -152
  90. package/dist/cli/src/types/index.d.ts.map +0 -1
  91. package/dist/cli/src/types/index.js +0 -3
  92. package/dist/cli/src/types/index.js.map +0 -1
  93. package/dist/cli/src/utils/apiKeyManager.d.ts +0 -137
  94. package/dist/cli/src/utils/apiKeyManager.d.ts.map +0 -1
  95. package/dist/cli/src/utils/apiKeyManager.js +0 -471
  96. package/dist/cli/src/utils/apiKeyManager.js.map +0 -1
  97. package/dist/cli/src/utils/componentValidator.d.ts +0 -60
  98. package/dist/cli/src/utils/componentValidator.d.ts.map +0 -1
  99. package/dist/cli/src/utils/componentValidator.js +0 -191
  100. package/dist/cli/src/utils/componentValidator.js.map +0 -1
  101. package/dist/cli/src/utils/designTokenExtractor.d.ts +0 -94
  102. package/dist/cli/src/utils/designTokenExtractor.d.ts.map +0 -1
  103. package/dist/cli/src/utils/designTokenExtractor.js +0 -231
  104. package/dist/cli/src/utils/designTokenExtractor.js.map +0 -1
  105. package/dist/cli/src/utils/errorHandler.d.ts +0 -105
  106. package/dist/cli/src/utils/errorHandler.d.ts.map +0 -1
  107. package/dist/cli/src/utils/errorHandler.js +0 -332
  108. package/dist/cli/src/utils/errorHandler.js.map +0 -1
  109. package/dist/cli/src/utils/fileSystem.d.ts +0 -58
  110. package/dist/cli/src/utils/fileSystem.d.ts.map +0 -1
  111. package/dist/cli/src/utils/fileSystem.js +0 -230
  112. package/dist/cli/src/utils/fileSystem.js.map +0 -1
  113. package/dist/cli/src/utils/githubModels.d.ts +0 -53
  114. package/dist/cli/src/utils/githubModels.d.ts.map +0 -1
  115. package/dist/cli/src/utils/githubModels.js +0 -239
  116. package/dist/cli/src/utils/githubModels.js.map +0 -1
  117. package/dist/cli/src/utils/ollamaClient.d.ts +0 -37
  118. package/dist/cli/src/utils/ollamaClient.d.ts.map +0 -1
  119. package/dist/cli/src/utils/ollamaClient.js +0 -213
  120. package/dist/cli/src/utils/ollamaClient.js.map +0 -1
  121. package/dist/cli/src/utils/spinner.d.ts +0 -30
  122. package/dist/cli/src/utils/spinner.d.ts.map +0 -1
  123. package/dist/cli/src/utils/spinner.js +0 -119
  124. package/dist/cli/src/utils/spinner.js.map +0 -1
  125. package/dist/cli/src/utils/xaiClient.d.ts +0 -59
  126. package/dist/cli/src/utils/xaiClient.d.ts.map +0 -1
  127. package/dist/cli/src/utils/xaiClient.js +0 -244
  128. package/dist/cli/src/utils/xaiClient.js.map +0 -1
  129. package/dist/lib/analytics/usage-tracker.d.ts +0 -125
  130. package/dist/lib/analytics/usage-tracker.d.ts.map +0 -1
  131. package/dist/lib/analytics/usage-tracker.js +0 -429
  132. package/dist/lib/analytics/usage-tracker.js.map +0 -1
  133. package/dist/utils/githubModels.d.ts +0 -53
  134. package/dist/utils/githubModels.d.ts.map +0 -1
  135. package/dist/utils/githubModels.js +0 -239
  136. package/dist/utils/githubModels.js.map +0 -1
@@ -1,1970 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.GenerateCommand = void 0;
40
- const chalk_1 = __importDefault(require("chalk"));
41
- const prompts_1 = __importDefault(require("prompts"));
42
- const path_1 = __importDefault(require("path"));
43
- const spinner_1 = require("../utils/spinner");
44
- const fileSystem_1 = require("../utils/fileSystem");
45
- class GenerateCommand {
46
- constructor() {
47
- this.fs = new fileSystem_1.FileSystemManager();
48
- }
49
- /**
50
- * Sanitizes a group name for use as a directory or route segment.
51
- * - Lowercase
52
- * - Replace spaces and & with dashes
53
- * - Remove all other special characters
54
- * - Collapse multiple dashes
55
- * - Trim leading/trailing dashes
56
- */
57
- sanitizeGroupName(name) {
58
- return name
59
- .toLowerCase()
60
- .replace(/\s+/g, "-") // Replace spaces with dash
61
- .replace(/\s*&\s*/g, "-") // Replace spaces and & with dash
62
- .replace(/[^a-z0-9-]/g, "") // Remove all non-alphanumeric/dash
63
- .replace(/-+/g, "-") // Collapse multiple dashes
64
- .replace(/^-+|-+$/g, ""); // Trim leading/trailing dashes
65
- }
66
- async execute(target, options) {
67
- const spinner = new spinner_1.EnhancedSpinner("Generating content...");
68
- const startTime = Date.now();
69
- let success = false;
70
- let error;
71
- try {
72
- console.log(chalk_1.default.blue.bold("🚀 MyContext Generation\n"));
73
- // Determine generation type
74
- const generationType = options.type || target;
75
- switch (generationType) {
76
- case "context":
77
- await this.generateContext(options, spinner);
78
- break;
79
- case "types":
80
- await this.generateTypes(options, spinner);
81
- break;
82
- case "brand":
83
- await this.generateBrand(options, spinner);
84
- break;
85
- case "components-list":
86
- await this.generateComponentsList(options, spinner);
87
- break;
88
- case "components":
89
- await this.generateComponents(options, spinner);
90
- break;
91
- case "app-structure":
92
- await this.generateAppStructure(options, spinner);
93
- break;
94
- default:
95
- throw new Error(`Unknown generation type: ${generationType}`);
96
- }
97
- success = true;
98
- }
99
- catch (err) {
100
- error = err instanceof Error ? err.message : "Unknown error";
101
- spinner.error({ text: "Generation failed" });
102
- throw err;
103
- }
104
- finally {
105
- // Track CLI generation event
106
- const executionTime = Date.now() - startTime;
107
- const userId = process.env.DEFAULT_USER_ID || "cli-user";
108
- try {
109
- // Import usage tracker dynamically to avoid CLI dependency issues
110
- const { usageTracker } = await Promise.resolve().then(() => __importStar(require("../../../lib/analytics/usage-tracker")));
111
- await usageTracker.trackCLIGeneration(userId, target, "cli", success, executionTime, error);
112
- }
113
- catch (trackingError) {
114
- console.log(chalk_1.default.yellow("⚠️ Analytics tracking failed:", trackingError));
115
- }
116
- }
117
- }
118
- async generateContext(options, spinner) {
119
- spinner.updateText("Generating project context...");
120
- // Get project description
121
- let description = "";
122
- if (!options.yes) {
123
- const response = await (0, prompts_1.default)({
124
- type: "text",
125
- name: "description",
126
- message: "Project description:",
127
- validate: (value) => value.length > 10 || "Description must be at least 10 characters",
128
- });
129
- description = response.description;
130
- }
131
- else {
132
- // For non-interactive mode, use a default description or read from project config
133
- try {
134
- // Try to read from project config first
135
- const configPath = ".mycontext/config.json";
136
- const configContent = await this.fs.readFile(configPath);
137
- const config = JSON.parse(configContent);
138
- description =
139
- config.description ||
140
- "A simple application for testing AI generation flow";
141
- }
142
- catch {
143
- // Fallback to a generic description
144
- description = "A simple application for testing AI generation flow";
145
- }
146
- }
147
- // Generate context files using API
148
- const contextFiles = await this.callGenerationAPI("context", description, options);
149
- // Write files to filesystem
150
- await this.writeContextFiles(contextFiles);
151
- spinner.success({ text: "Context files generated successfully!" });
152
- console.log(chalk_1.default.green("\n✅ Generated Files:"));
153
- Object.keys(contextFiles).forEach((filename) => {
154
- console.log(chalk_1.default.gray(` • ${filename}`));
155
- });
156
- }
157
- async generateTypes(options, spinner) {
158
- spinner.updateText("Generating TypeScript types...");
159
- // Read PRD for context
160
- const prdPath = await this.findPRDFile();
161
- if (!prdPath) {
162
- throw new Error('No PRD found. Run "mycontext generate context" first.');
163
- }
164
- const prdContent = await this.fs.readFile(prdPath);
165
- // Generate types using API
166
- const typesContent = await this.callGenerationAPI("types", prdContent, options);
167
- // Write types file
168
- await this.fs.writeFile("context/types.ts", typesContent);
169
- spinner.success({ text: "TypeScript types generated successfully!" });
170
- }
171
- async generateBrand(options, spinner) {
172
- spinner.updateText("Generating branding guidelines...");
173
- // Read PRD for context
174
- const prdPath = await this.findPRDFile();
175
- if (!prdPath) {
176
- throw new Error('No PRD found. Run "mycontext generate context" first.');
177
- }
178
- const prdContent = await this.fs.readFile(prdPath);
179
- // Generate branding using API (returns { markdown, json })
180
- const branding = await this.callGenerationAPI("brand", prdContent, options);
181
- // Write branding files
182
- await this.fs.writeFile("context/branding.md", branding.markdown);
183
- await this.fs.writeFile("context/branding.json", JSON.stringify(branding.json, null, 2));
184
- spinner.success({ text: "Branding guidelines generated successfully!" });
185
- console.log(chalk_1.default.green("\n✅ Generated Files:"));
186
- console.log(chalk_1.default.gray(" • branding.md"));
187
- console.log(chalk_1.default.gray(" • branding.json"));
188
- }
189
- async generateComponentsList(options, spinner) {
190
- spinner.updateText("Generating comprehensive component list...");
191
- // Read context files for comprehensive analysis
192
- const contextFiles = await this.readContextFiles();
193
- const prdContent = contextFiles["context/01_PRD.md"] || "";
194
- const userStoriesContent = contextFiles["context/02_user_stories.md"] || "";
195
- const typesContent = contextFiles["context/types.ts"] || "";
196
- // Combine context for analysis
197
- const fullContext = `
198
- PRD: ${prdContent}
199
- User Stories: ${userStoriesContent}
200
- Types: ${typesContent}
201
- `.trim();
202
- // Use local generation for component list (more reliable than API workflow)
203
- const componentListData = await this.generateLocalComponentsList(fullContext);
204
- // Write both JSON and Markdown versions
205
- await this.fs.writeFile("context/component-list.json", JSON.stringify(componentListData, null, 2));
206
- // Generate Markdown version for human review
207
- const markdownContent = this.generateComponentListMarkdown(componentListData);
208
- await this.fs.writeFile("context/component-list.md", markdownContent);
209
- spinner.success({ text: "Component list generated successfully!" });
210
- console.log(chalk_1.default.green("\n✅ Generated Files:"));
211
- console.log(chalk_1.default.gray(" • component-list.json"));
212
- console.log(chalk_1.default.gray(" • component-list.md"));
213
- // Show summary
214
- if (componentListData.groups) {
215
- console.log(chalk_1.default.blue("\n📋 Component Groups:"));
216
- componentListData.groups.forEach((group) => {
217
- console.log(chalk_1.default.gray(` • ${group.name} (${group.components?.length || 0} components)`));
218
- });
219
- }
220
- }
221
- async generateComponents(options, spinner) {
222
- spinner.updateText("Generating components...");
223
- // Read component list for context
224
- const componentListPath = "context/component-list.json";
225
- let componentList;
226
- try {
227
- const componentListContent = await this.fs.readFile(componentListPath);
228
- componentList = JSON.parse(componentListContent);
229
- }
230
- catch {
231
- throw new Error('No component list found. Run "mycontext generate components-list" first.');
232
- }
233
- // Create components directory
234
- const componentsDir = "components/generated";
235
- await this.fs.ensureDir(componentsDir);
236
- // Generate each component using the sub-agent system
237
- const generatedComponents = [];
238
- for (const group of componentList.groups || []) {
239
- const groupDir = path_1.default.join(componentsDir, this.sanitizeGroupName(group.name));
240
- await this.fs.ensureDir(groupDir);
241
- for (const component of group.components || []) {
242
- try {
243
- // Generate component using CodeGenSubAgent
244
- const componentResult = await this.callGenerationAPI("component", JSON.stringify({ component, group, options }), options);
245
- // Extract the component code from the result
246
- let componentCode;
247
- if (Array.isArray(componentResult) && componentResult.length > 0) {
248
- // Result is an array from generateLocalComponents
249
- componentCode = componentResult[0].code || componentResult[0];
250
- }
251
- else if (typeof componentResult === "object" &&
252
- componentResult.code) {
253
- // Result is an object with code property
254
- componentCode = componentResult.code;
255
- }
256
- else if (typeof componentResult === "string") {
257
- // Result is a string
258
- componentCode = componentResult;
259
- }
260
- else {
261
- throw new Error(`Invalid component result format for ${component.name}`);
262
- }
263
- // Write component file
264
- const componentPath = path_1.default.join(groupDir, `${component.name}.tsx`);
265
- await this.fs.writeFile(componentPath, componentCode);
266
- generatedComponents.push({
267
- name: component.name,
268
- type: component.type,
269
- path: componentPath,
270
- });
271
- console.log(chalk_1.default.gray(` • ${component.name} (${component.type})`));
272
- }
273
- catch (error) {
274
- console.log(chalk_1.default.red(` ❌ Failed to generate ${component.name}: ${error}`));
275
- }
276
- }
277
- // Generate group index file
278
- const indexContent = this.generateGroupIndex(group);
279
- const indexPath = path_1.default.join(groupDir, "index.ts");
280
- await this.fs.writeFile(indexPath, indexContent);
281
- }
282
- spinner.success({ text: "Components generated successfully!" });
283
- console.log(chalk_1.default.green("\n✅ Generated Components:"));
284
- generatedComponents.forEach((component) => {
285
- console.log(chalk_1.default.gray(` • ${component.name} (${component.type})`));
286
- });
287
- }
288
- generateGroupIndex(group) {
289
- const components = group.components || [];
290
- const imports = components
291
- .map((comp) => `export { ${comp.name} } from './${comp.name}';`)
292
- .join("\n");
293
- return `// ${group.name} Components
294
- ${imports}
295
-
296
- // Group metadata
297
- export const groupMetadata = {
298
- name: "${group.name}",
299
- description: "${group.description || ""}",
300
- priority: "${group.priority || "medium"}",
301
- componentCount: ${components.length},
302
- };
303
- `;
304
- }
305
- async generateAppStructure(options, spinner) {
306
- spinner.updateText("Generating app structure...");
307
- // Read context files
308
- const contextFiles = await this.readContextFiles();
309
- // Generate app structure using API
310
- const appStructure = await this.callGenerationAPI("app-structure", JSON.stringify(contextFiles), options);
311
- // Write app structure file
312
- await this.fs.writeFile("context/app-structure.json", JSON.stringify(appStructure, null, 2));
313
- spinner.success({ text: "App structure generated successfully!" });
314
- }
315
- async callGenerationAPI(type, context, options) {
316
- // For component generation, only use Ollama (local AI)
317
- if (type === "component") {
318
- throw new Error("Component generation requires Ollama (local AI). " +
319
- "Please run 'mycontext setup' to configure your local AI environment.");
320
- }
321
- // For other types (context, types, branding), try external APIs
322
- const xaiApiKey = process.env.XAI_API_KEY;
323
- const githubToken = process.env.GITHUB_TOKEN;
324
- // X.AI Priority (if explicitly requested or available)
325
- if (options.useXAI && xaiApiKey) {
326
- try {
327
- const { XAIClient } = await Promise.resolve().then(() => __importStar(require("../utils/xaiClient")));
328
- const xaiClient = new XAIClient({
329
- apiKey: xaiApiKey,
330
- temperature: options.temperature || 0.7,
331
- maxTokens: options.maxTokens || 4000,
332
- });
333
- // Test connection first
334
- const isConnected = await xaiClient.testConnection();
335
- if (!isConnected) {
336
- throw new Error("X.AI connection failed");
337
- }
338
- console.log(chalk_1.default.blue("🤖 Using X.AI (Grok) for generation..."));
339
- switch (type) {
340
- case "context":
341
- return await xaiClient.generateContext(context);
342
- case "components-list":
343
- return await xaiClient.generateComponentList(context);
344
- default:
345
- // For other types, use the general generate method
346
- return await xaiClient.generate({
347
- prompt: context,
348
- temperature: options.temperature || 0.7,
349
- maxTokens: options.maxTokens || 4000,
350
- });
351
- }
352
- }
353
- catch (error) {
354
- console.log(chalk_1.default.yellow("X.AI unavailable, trying GitHub Models..."));
355
- }
356
- }
357
- // GitHub Models fallback
358
- if (githubToken) {
359
- try {
360
- const { GitHubModelsClient } = await Promise.resolve().then(() => __importStar(require("../utils/githubModels")));
361
- const githubClient = new GitHubModelsClient({
362
- token: githubToken,
363
- temperature: options.temperature || 0.7,
364
- maxTokens: options.maxTokens || 4000,
365
- });
366
- // Test connection first
367
- const isConnected = await githubClient.testConnection();
368
- if (!isConnected) {
369
- throw new Error("GitHub Models connection failed");
370
- }
371
- console.log(chalk_1.default.blue("🤖 Using GitHub Models for generation..."));
372
- switch (type) {
373
- case "context":
374
- return await githubClient.generateComponentList(context);
375
- default:
376
- // For other types, use the general generate method
377
- return await githubClient.generate({
378
- prompt: context,
379
- temperature: options.temperature || 0.7,
380
- maxTokens: options.maxTokens || 4000,
381
- });
382
- }
383
- }
384
- catch (error) {
385
- console.log(chalk_1.default.yellow("GitHub Models unavailable, trying local API..."));
386
- }
387
- }
388
- // Fallback to local API
389
- const apiUrl = process.env.MYCONTEXT_API_URL || "http://localhost:3000/api/generate";
390
- try {
391
- const response = await fetch(apiUrl, {
392
- method: "POST",
393
- headers: {
394
- "Content-Type": "application/json",
395
- ...(process.env.MYCONTEXT_API_KEY && {
396
- Authorization: `Bearer ${process.env.MYCONTEXT_API_KEY}`,
397
- }),
398
- },
399
- body: JSON.stringify({
400
- type,
401
- context,
402
- options: {
403
- useClaudeCodeSDK: options.useClaudeCodeSDK,
404
- useGemini: options.useGemini,
405
- temperature: options.temperature || 0.7,
406
- maxTokens: options.maxTokens || 4000,
407
- },
408
- }),
409
- });
410
- if (!response.ok) {
411
- throw new Error(`API request failed: ${response.status} ${response.statusText}`);
412
- }
413
- const result = (await response.json());
414
- // Handle API response structure
415
- if (result.success && result.result) {
416
- // Check if result has a data property (nested structure)
417
- if (result.result.data) {
418
- return result.result.data;
419
- }
420
- return result.result;
421
- }
422
- else if (result.content) {
423
- return result.content;
424
- }
425
- else {
426
- return result;
427
- }
428
- }
429
- catch (error) {
430
- // Fallback to local generation if API fails
431
- console.log(chalk_1.default.yellow("API unavailable, using local generation..."));
432
- return this.generateLocally(type, context, options);
433
- }
434
- }
435
- async generateLocally(type, context, options) {
436
- // Local generation fallback
437
- switch (type) {
438
- case "context":
439
- return this.generateLocalContext(context);
440
- case "types":
441
- return this.generateLocalTypes(context);
442
- case "brand":
443
- return this.generateLocalBrand(context);
444
- case "components-list":
445
- case "workflow":
446
- return this.generateLocalComponentsList(context);
447
- case "components":
448
- throw new Error("Component generation requires Ollama (local AI). " +
449
- "Please run 'mycontext setup' to configure your local AI environment.");
450
- case "app-structure":
451
- return this.generateLocalAppStructure(context);
452
- default:
453
- throw new Error(`Unknown generation type: ${type}`);
454
- }
455
- }
456
- async generateLocalContext(description) {
457
- // Detect app type based on description
458
- const isTodoApp = description.toLowerCase().includes("todo") ||
459
- description.toLowerCase().includes("task") ||
460
- description.toLowerCase().includes("checklist");
461
- const isEcommerceApp = description.toLowerCase().includes("ecommerce") ||
462
- description.toLowerCase().includes("shop") ||
463
- description.toLowerCase().includes("store") ||
464
- description.toLowerCase().includes("cart") ||
465
- description.toLowerCase().includes("checkout") ||
466
- description.toLowerCase().includes("payment");
467
- if (isTodoApp) {
468
- return {
469
- "01_PRD.md": `# Product Requirements Document
470
-
471
- ## Project Overview
472
- **Project Name:** Todo Application
473
- **Description:** ${description}
474
-
475
- ## Core Features
476
- - **Task Management**: Create, read, update, and delete todo items
477
- - **Task Status**: Mark tasks as complete/incomplete with visual indicators
478
- - **Task Categories**: Organize tasks by categories or priorities
479
- - **Search & Filter**: Find specific tasks quickly
480
- - **Responsive Design**: Works seamlessly on desktop and mobile devices
481
-
482
- ## User Stories
483
- - As a user, I want to create new todo items so that I can track my tasks
484
- - As a user, I want to mark tasks as complete so that I can track my progress
485
- - As a user, I want to edit existing tasks so that I can update details
486
- - As a user, I want to delete tasks so that I can remove completed or irrelevant items
487
- - As a user, I want to filter tasks by status so that I can focus on pending work
488
- - As a user, I want to search for specific tasks so that I can find them quickly
489
-
490
- ## Technical Requirements
491
- - **Frontend**: Next.js 14 with App Router, TypeScript, Tailwind CSS
492
- - **UI Components**: shadcn/ui component library
493
- - **State Management**: React hooks with local storage persistence
494
- - **Styling**: Responsive design with mobile-first approach
495
- - **Accessibility**: WCAG 2.1 AA compliance
496
-
497
- ## Acceptance Criteria
498
- - [ ] Users can create new todo items with title and optional description
499
- - [ ] Users can mark tasks as complete/incomplete with visual feedback
500
- - [ ] Users can edit task details inline
501
- - [ ] Users can delete tasks with confirmation
502
- - [ ] Users can filter tasks by status (all, active, completed)
503
- - [ ] Users can search tasks by title or description
504
- - [ ] Tasks persist across browser sessions using local storage
505
- - [ ] Interface is fully responsive and accessible`,
506
- "02_user_stories.md": `# User Stories
507
-
508
- ## Primary User Stories
509
-
510
- ### 1. Task Creation
511
- **As a** user
512
- **I want to** create new todo items
513
- **So that** I can track my tasks and responsibilities
514
-
515
- **Acceptance Criteria:**
516
- - [ ] I can click an "Add Task" button or press Enter in an input field
517
- - [ ] I can enter a task title (required)
518
- - [ ] I can optionally add a description
519
- - [ ] The task appears in my todo list immediately
520
- - [ ] The input field clears after adding a task
521
-
522
- ### 2. Task Completion
523
- **As a** user
524
- **I want to** mark tasks as complete
525
- **So that** I can track my progress and focus on remaining work
526
-
527
- **Acceptance Criteria:**
528
- - [ ] I can click a checkbox next to each task
529
- - [ ] Completed tasks show visual indicators (strikethrough, different color)
530
- - [ ] I can uncheck completed tasks to mark them as incomplete
531
- - [ ] The completion status persists across sessions
532
-
533
- ### 3. Task Editing
534
- **As a** user
535
- **I want to** edit existing tasks
536
- **So that** I can update details or correct mistakes
537
-
538
- **Acceptance Criteria:**
539
- - [ ] I can click on a task title to edit it inline
540
- - [ ] I can also edit the task description
541
- - [ ] Changes are saved automatically or with a save button
542
- - [ ] I can cancel editing by pressing Escape
543
-
544
- ### 4. Task Deletion
545
- **As a** user
546
- **I want to** delete tasks
547
- **So that** I can remove completed or irrelevant items
548
-
549
- **Acceptance Criteria:**
550
- - [ ] I can click a delete button (trash icon) next to each task
551
- - [ ] A confirmation dialog appears before deletion
552
- - [ ] Deleted tasks are removed from the list permanently
553
- - [ ] I can undo deletion within a short time window
554
-
555
- ### 5. Task Filtering
556
- **As a** user
557
- **I want to** filter tasks by status
558
- **So that** I can focus on specific types of tasks
559
-
560
- **Acceptance Criteria:**
561
- - [ ] I can filter by "All", "Active", or "Completed" tasks
562
- - [ ] The filter selection is visually indicated
563
- - [ ] The task count updates based on the current filter
564
- - [ ] I can clear filters to show all tasks
565
-
566
- ### 6. Task Search
567
- **As a** user
568
- **I want to** search for specific tasks
569
- **So that** I can find them quickly in a long list
570
-
571
- **Acceptance Criteria:**
572
- - [ ] I can type in a search box to filter tasks
573
- - [ ] Search works on both task titles and descriptions
574
- - [ ] Search results update in real-time as I type
575
- - [ ] No results message appears when no matches are found`,
576
- "03_technical_specs.md": `# Technical Specifications
577
-
578
- ## Architecture Overview
579
- - **Frontend Framework**: Next.js 14 with App Router
580
- - **Language**: TypeScript for type safety
581
- - **Styling**: Tailwind CSS with shadcn/ui components
582
- - **State Management**: React hooks with localStorage persistence
583
- - **Build Tool**: Vite for fast development and building
584
-
585
- ## Component Architecture
586
-
587
- ### Core Components
588
- 1. **TodoApp** - Main application container
589
- 2. **TodoList** - Displays the list of todo items
590
- 3. **TodoItem** - Individual todo item with actions
591
- 4. **TodoForm** - Form for creating new todos
592
- 5. **TodoFilter** - Filter and search controls
593
- 6. **TodoStats** - Shows completion statistics
594
-
595
- ### Layout Components
596
- - **Header** - App title and navigation
597
- - **Main** - Primary content area
598
- - **Footer** - Additional information and links
599
-
600
- ## Data Model
601
-
602
- ### Todo Item Structure
603
- \`\`\`typescript
604
- interface Todo {
605
- id: string;
606
- title: string;
607
- description?: string;
608
- completed: boolean;
609
- createdAt: Date;
610
- updatedAt: Date;
611
- priority?: 'low' | 'medium' | 'high';
612
- category?: string;
613
- }
614
- \`\`\`
615
-
616
- ### Local Storage Schema
617
- \`\`\`json
618
- {
619
- "todos": [
620
- {
621
- "id": "uuid",
622
- "title": "Task title",
623
- "description": "Optional description",
624
- "completed": false,
625
- "createdAt": "2024-01-01T00:00:00.000Z",
626
- "updatedAt": "2024-01-01T00:00:00.000Z"
627
- }
628
- ],
629
- "filters": {
630
- "status": "all",
631
- "search": ""
632
- }
633
- }
634
- \`\`\`
635
-
636
- ## UI/UX Design
637
-
638
- ### Design System
639
- - **Color Palette**: Tailwind CSS default with custom accent colors
640
- - **Typography**: Inter font family for readability
641
- - **Spacing**: Consistent 4px grid system
642
- - **Components**: shadcn/ui primitives for consistency
643
-
644
- ### Responsive Design
645
- - **Mobile First**: Design for mobile devices first
646
- - **Breakpoints**: sm (640px), md (768px), lg (1024px), xl (1280px)
647
- - **Touch Targets**: Minimum 44px for interactive elements
648
-
649
- ### Accessibility
650
- - **WCAG 2.1 AA**: Full compliance with accessibility standards
651
- - **Keyboard Navigation**: All features accessible via keyboard
652
- - **Screen Readers**: Proper ARIA labels and semantic HTML
653
- - **Color Contrast**: Minimum 4.5:1 ratio for text
654
-
655
- ## Performance Considerations
656
- - **Lazy Loading**: Components load only when needed
657
- - **Debounced Search**: Search input debounced to prevent excessive filtering
658
- - **Optimistic Updates**: UI updates immediately, then syncs with storage
659
- - **Virtual Scrolling**: For large lists (future enhancement)
660
-
661
- ## Security & Data
662
- - **Client-Side Only**: No server-side storage required
663
- - **Input Sanitization**: All user inputs are sanitized
664
- - **XSS Prevention**: React's built-in XSS protection
665
- - **Local Storage**: Data persists in browser localStorage`,
666
- };
667
- }
668
- else if (isEcommerceApp) {
669
- return {
670
- "01_PRD.md": `# Product Requirements Document
671
-
672
- ## Project Overview
673
- **Project Name:** Ecommerce Platform
674
- **Description:** ${description}
675
-
676
- ## Core Features
677
- - **Product Catalog**: Browse and search products with filtering and sorting
678
- - **Shopping Cart**: Add, remove, and manage items in cart
679
- - **Checkout Process**: Multi-step checkout with payment processing
680
- - **User Accounts**: Registration, login, and order history
681
- - **Payment Integration**: Secure payment processing with multiple options
682
- - **Order Management**: Track orders and receive notifications
683
-
684
- ## User Stories
685
- - As a customer, I want to browse products so that I can find items to purchase
686
- - As a customer, I want to add items to cart so that I can purchase multiple items
687
- - As a customer, I want to complete checkout so that I can receive my order
688
- - As a customer, I want to track my orders so that I know when they'll arrive
689
- - As a customer, I want to save payment methods so that checkout is faster
690
- - As an admin, I want to manage products so that inventory is accurate
691
-
692
- ## Technical Requirements
693
- - **Frontend**: Next.js 14 with App Router, TypeScript, Tailwind CSS
694
- - **UI Components**: shadcn/ui component library
695
- - **State Management**: React hooks with cart persistence
696
- - **Payment**: Stripe integration for secure payments
697
- - **Authentication**: NextAuth.js for user management
698
- - **Database**: PostgreSQL for product and order data
699
-
700
- ## Acceptance Criteria
701
- - [ ] Users can browse products with search and filtering
702
- - [ ] Users can add/remove items from shopping cart
703
- - [ ] Users can complete checkout with payment processing
704
- - [ ] Users can track order status and history
705
- - [ ] Admin can manage product inventory
706
- - [ ] Payment processing is secure and reliable`,
707
- "02_user_stories.md": `# User Stories
708
-
709
- ## Primary User Stories
710
-
711
- ### 1. Product Browsing
712
- **As a** customer
713
- **I want to** browse products
714
- **So that** I can find items to purchase
715
-
716
- **Acceptance Criteria:**
717
- - [ ] I can view a grid/list of products with images and prices
718
- - [ ] I can search for specific products by name or category
719
- - [ ] I can filter products by price, category, or rating
720
- - [ ] I can sort products by price, popularity, or newest
721
- - [ ] I can view detailed product information
722
-
723
- ### 2. Shopping Cart Management
724
- **As a** customer
725
- **I want to** manage my shopping cart
726
- **So that** I can purchase multiple items efficiently
727
-
728
- **Acceptance Criteria:**
729
- - [ ] I can add products to my cart from product pages
730
- - [ ] I can view my cart contents and total
731
- - [ ] I can update quantities or remove items
732
- - [ ] My cart persists across browser sessions
733
- - [ ] I can save items for later purchase
734
-
735
- ### 3. Checkout Process
736
- **As a** customer
737
- **I want to** complete my purchase
738
- **So that** I can receive my order
739
-
740
- **Acceptance Criteria:**
741
- - [ ] I can enter shipping and billing information
742
- - [ ] I can select from multiple payment options
743
- - [ ] I can review my order before confirmation
744
- - [ ] I receive confirmation of my purchase
745
- - [ ] I can track my order status
746
-
747
- ### 4. Order Tracking
748
- **As a** customer
749
- **I want to** track my orders
750
- **So that** I know when they'll arrive
751
-
752
- **Acceptance Criteria:**
753
- - [ ] I can view my order history
754
- - [ ] I can see current order status
755
- - [ ] I receive email notifications for updates
756
- - [ ] I can cancel orders within allowed timeframe
757
- - [ ] I can request refunds or returns`,
758
- "03_technical_specs.md": `# Technical Specifications
759
-
760
- ## Architecture Overview
761
- - **Frontend Framework**: Next.js 14 with App Router
762
- - **Language**: TypeScript for type safety
763
- - **Styling**: Tailwind CSS with shadcn/ui components
764
- - **State Management**: React hooks with cart persistence
765
- - **Payment Processing**: Stripe integration
766
- - **Authentication**: NextAuth.js
767
- - **Database**: PostgreSQL with Prisma ORM
768
-
769
- ## Component Architecture
770
-
771
- ### Core Components
772
- 1. **ProductCatalog** - Product browsing and search
773
- 2. **ProductCard** - Individual product display
774
- 3. **ShoppingCart** - Cart management and display
775
- 4. **CheckoutForm** - Multi-step checkout process
776
- 5. **PaymentForm** - Payment method selection
777
- 6. **OrderTracking** - Order status and history
778
-
779
- ### Layout Components
780
- - **Header** - Navigation and cart icon
781
- - **ProductGrid** - Product listing layout
782
- - **CheckoutWizard** - Multi-step checkout flow
783
- - **Footer** - Additional information and links
784
-
785
- ## Data Model
786
-
787
- ### Product Structure
788
- \`\`\`typescript
789
- interface Product {
790
- id: string;
791
- name: string;
792
- description: string;
793
- price: number;
794
- images: string[];
795
- category: string;
796
- inventory: number;
797
- rating: number;
798
- reviews: Review[];
799
- }
800
- \`\`\`
801
-
802
- ### Cart Structure
803
- \`\`\`typescript
804
- interface CartItem {
805
- productId: string;
806
- quantity: number;
807
- price: number;
808
- }
809
-
810
- interface Cart {
811
- items: CartItem[];
812
- total: number;
813
- itemCount: number;
814
- }
815
- \`\`\`
816
-
817
- ## UI/UX Design
818
-
819
- ### Design System
820
- - **Color Palette**: Professional ecommerce colors
821
- - **Typography**: Clear, readable fonts for product information
822
- - **Spacing**: Consistent spacing for product grids
823
- - **Components**: shadcn/ui primitives with ecommerce patterns
824
-
825
- ### Responsive Design
826
- - **Mobile First**: Optimized for mobile shopping
827
- - **Product Grid**: Responsive grid layout
828
- - **Checkout**: Mobile-friendly form design
829
- - **Touch Targets**: Large enough for mobile interaction
830
-
831
- ### Accessibility
832
- - **WCAG 2.1 AA**: Full compliance for all users
833
- - **Screen Readers**: Proper product descriptions
834
- - **Keyboard Navigation**: Full keyboard accessibility
835
- - **Color Contrast**: High contrast for product information
836
-
837
- ## Performance Considerations
838
- - **Image Optimization**: Lazy loading and WebP format
839
- - **Product Search**: Fast search with debouncing
840
- - **Cart Updates**: Optimistic updates for better UX
841
- - **Payment Processing**: Secure and fast payment flow
842
-
843
- ## Security & Data
844
- - **Payment Security**: PCI compliance with Stripe
845
- - **User Data**: Secure storage and transmission
846
- - **Input Validation**: All user inputs validated
847
- - **CSRF Protection**: Protection against cross-site attacks`,
848
- };
849
- }
850
- else {
851
- // Fallback: generic context with instructions
852
- const instructions = `<!--\nThis is a generic context file.\nTo regenerate with your project details, run:\n\n mycontext generate context --yes\n\nEdit your PRD or provide a detailed description for better results.\n-->\n`;
853
- return {
854
- "01_PRD.md": `${instructions}
855
- # Product Requirements Document
856
-
857
- ## Project Overview
858
- Describe your project here.
859
-
860
- ## Core Features
861
- - Feature 1: Description
862
- - Feature 2: Description
863
- - Feature 3: Description
864
-
865
- ## Technical Requirements
866
- - Technology Stack: [List technologies]
867
- - Database: [Database choice]
868
- - Authentication: [Auth method]
869
-
870
- ## User Stories
871
- - As a user, I want to [action] so that [benefit]
872
- - As an admin, I need to [action] so that [benefit]
873
-
874
- ## Acceptance Criteria
875
- - [ ] Feature 1 works correctly
876
- - [ ] Feature 2 is responsive
877
- - [ ] Feature 3 is accessible
878
- `,
879
- "02_user_stories.md": `${instructions}
880
- # User Stories
881
-
882
- Add user stories for your project here.
883
-
884
- ## Example User Stories
885
- - As a user, I want to [do something] so that [benefit].
886
- - As an admin, I want to [manage something] so that [benefit].
887
-
888
- ## Acceptance Criteria
889
- - [ ] User can complete the primary action
890
- - [ ] System provides appropriate feedback
891
- - [ ] Error handling is implemented
892
- `,
893
- "03_technical_specs.md": `${instructions}
894
- # Technical Specifications
895
-
896
- ## Architecture
897
- - Frontend: [Framework, e.g., Next.js, React]
898
- - Styling: [CSS framework, e.g., Tailwind CSS]
899
- - State Management: [e.g., Zustand, Redux]
900
- - Database: [e.g., PostgreSQL, MongoDB]
901
- - Authentication: [e.g., NextAuth.js, Auth0]
902
-
903
- ## Component Structure
904
- - Layout components
905
- - Form components
906
- - Display components
907
- - Interactive components
908
-
909
- ## API Design
910
- - RESTful endpoints
911
- - TypeScript interfaces
912
- - Error handling
913
- - Rate limiting
914
- `,
915
- };
916
- }
917
- }
918
- async generateLocalTypes(context) {
919
- return `// Generated TypeScript types based on: ${context}
920
-
921
- export interface User {
922
- id: string;
923
- email: string;
924
- name: string;
925
- role: 'user' | 'admin';
926
- createdAt: Date;
927
- updatedAt: Date;
928
- }
929
-
930
- export interface Project {
931
- id: string;
932
- name: string;
933
- description: string;
934
- userId: string;
935
- status: 'active' | 'inactive' | 'archived';
936
- createdAt: Date;
937
- updatedAt: Date;
938
- }
939
-
940
- export interface ApiResponse<T = any> {
941
- success: boolean;
942
- data?: T;
943
- error?: string;
944
- message?: string;
945
- }
946
-
947
- // Add more types based on your project requirements
948
- `;
949
- }
950
- // Update local brand generation to return both markdown and JSON
951
- async generateLocalBrand(context) {
952
- // Extract project name from context
953
- const projectName = context.includes("Project Name:")
954
- ? context.split("Project Name:")[1]?.split("\n")[0]?.trim() ||
955
- "MyContext Project"
956
- : "MyContext Project";
957
- const theme = "rose";
958
- const colors = {
959
- primary: "oklch(0.645 0.246 16.439)",
960
- secondary: "oklch(0.967 0.001 286.375)",
961
- accent: "oklch(0.967 0.001 286.375)",
962
- background: "oklch(1 0 0)",
963
- foreground: "oklch(0.141 0.005 285.823)",
964
- border: "oklch(0.92 0.004 286.32)",
965
- card: "oklch(1 0 0)",
966
- cardForeground: "oklch(0.141 0.005 285.823)",
967
- // ... add more as needed
968
- };
969
- const cssVariables = {
970
- "--radius": "0.65rem",
971
- "--background": colors.background,
972
- "--foreground": colors.foreground,
973
- "--primary": colors.primary,
974
- "--secondary": colors.secondary,
975
- "--accent": colors.accent,
976
- "--border": colors.border,
977
- "--card": colors.card,
978
- "--card-foreground": colors.cardForeground,
979
- // ... add more as needed
980
- };
981
- const typography = {
982
- fontFamily: "Inter, system-ui, sans-serif",
983
- fontSizes: {
984
- xs: "0.75rem",
985
- sm: "0.875rem",
986
- base: "1rem",
987
- lg: "1.125rem",
988
- xl: "1.25rem",
989
- "2xl": "1.5rem",
990
- "3xl": "1.875rem",
991
- "4xl": "2.25rem",
992
- "5xl": "3rem",
993
- },
994
- fontWeights: {
995
- light: 300,
996
- regular: 400,
997
- medium: 500,
998
- semibold: 600,
999
- bold: 700,
1000
- extrabold: 800,
1001
- },
1002
- lineHeights: {
1003
- tight: 1.25,
1004
- normal: 1.5,
1005
- relaxed: 1.75,
1006
- },
1007
- };
1008
- const spacing = {
1009
- base: "4px",
1010
- scale: [0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 80, 96],
1011
- };
1012
- const markdown = `# Branding Guidelines
1013
-
1014
- ## Project Overview
1015
- **Project Name:** ${projectName}
1016
- **Theme:** ${theme} (shadcn/ui)
1017
- **Generated:** ${new Date().toISOString().split("T")[0]}
1018
-
1019
- ### Color Palette
1020
- - Primary: ${colors.primary}
1021
- - Secondary: ${colors.secondary}
1022
- - Accent: ${colors.accent}
1023
- - Background: ${colors.background}
1024
- - Foreground: ${colors.foreground}
1025
- - Border: ${colors.border}
1026
-
1027
- ### CSS Variables
1028
- \`\`\`css
1029
- :root {
1030
- ${Object.entries(cssVariables)
1031
- .map(([k, v]) => ` ${k}: ${v};`)
1032
- .join("\n")}
1033
- }
1034
- \`\`\`
1035
-
1036
- ### Typography
1037
- - Font Family: ${typography.fontFamily}
1038
- - Font Sizes: ${Object.entries(typography.fontSizes)
1039
- .map(([k, v]) => `${k}: ${v}`)
1040
- .join(", ")}
1041
- - Font Weights: ${Object.entries(typography.fontWeights)
1042
- .map(([k, v]) => `${k}: ${v}`)
1043
- .join(", ")}
1044
- - Line Heights: ${Object.entries(typography.lineHeights)
1045
- .map(([k, v]) => `${k}: ${v}`)
1046
- .join(", ")}
1047
-
1048
- ### Spacing System
1049
- - Base: ${spacing.base}
1050
- - Scale: ${spacing.scale.join(", ")}
1051
-
1052
- ---
1053
-
1054
- *This branding guide ensures consistency across all components and maintains the professional, accessible, and user-friendly design principles of the ${projectName} project.*
1055
- `;
1056
- const json = {
1057
- projectName,
1058
- theme,
1059
- colors,
1060
- cssVariables,
1061
- typography,
1062
- spacing,
1063
- generated: new Date().toISOString(),
1064
- };
1065
- return { markdown, json };
1066
- }
1067
- async generateLocalComponents(context) {
1068
- // Parse the context to extract component information
1069
- let componentData;
1070
- try {
1071
- componentData = JSON.parse(context);
1072
- }
1073
- catch {
1074
- // If context is not JSON, return empty array
1075
- return [];
1076
- }
1077
- const { component, group, options } = componentData;
1078
- // Use the CodeGenSubAgent to generate actual component code
1079
- const { CodeGenSubAgent } = await Promise.resolve().then(() => __importStar(require("../agents/implementations/CodeGenSubAgent")));
1080
- const codeGenAgent = new CodeGenSubAgent();
1081
- const result = await codeGenAgent.run({
1082
- component,
1083
- group,
1084
- options,
1085
- context,
1086
- });
1087
- return [result];
1088
- }
1089
- async generateLocalComponentsList(context) {
1090
- // Dynamic AI-driven component list generation
1091
- // Instead of hardcoded patterns, we use intelligent analysis
1092
- // Step 1: Analyze the context to determine app type and intent
1093
- const appAnalysis = this.analyzeAppContext(context);
1094
- // Step 2: Generate component list based on analysis
1095
- return this.generateComponentListFromAnalysis(appAnalysis, context);
1096
- }
1097
- /**
1098
- * Analyzes app context to determine type, intent, and requirements
1099
- */
1100
- analyzeAppContext(context) {
1101
- const analysis = {
1102
- appType: this.detectAppType(context),
1103
- primaryIntent: this.detectPrimaryIntent(context),
1104
- complexity: this.assessComplexity(context),
1105
- keyFeatures: this.extractKeyFeatures(context),
1106
- userTypes: this.identifyUserTypes(context),
1107
- dataEntities: this.identifyDataEntities(context),
1108
- technicalRequirements: this.extractTechnicalRequirements(context),
1109
- uiPatterns: this.suggestUIPatterns(context),
1110
- componentGroups: [],
1111
- priorityMatrix: this.createPriorityMatrix(context),
1112
- };
1113
- // Generate component groups based on analysis
1114
- analysis.componentGroups = this.suggestComponentGroups(analysis);
1115
- return analysis;
1116
- }
1117
- /**
1118
- * Detects the type of application based on context
1119
- */
1120
- detectAppType(context) {
1121
- const lowerContext = context.toLowerCase();
1122
- // Define app type patterns with confidence scores
1123
- const typePatterns = [
1124
- {
1125
- type: "ecommerce",
1126
- patterns: [
1127
- "shop",
1128
- "store",
1129
- "cart",
1130
- "checkout",
1131
- "product",
1132
- "order",
1133
- "payment",
1134
- ],
1135
- score: 0.9,
1136
- },
1137
- {
1138
- type: "dashboard",
1139
- patterns: [
1140
- "dashboard",
1141
- "analytics",
1142
- "metrics",
1143
- "report",
1144
- "chart",
1145
- "graph",
1146
- ],
1147
- score: 0.85,
1148
- },
1149
- {
1150
- type: "social",
1151
- patterns: [
1152
- "social",
1153
- "network",
1154
- "profile",
1155
- "friend",
1156
- "post",
1157
- "comment",
1158
- "share",
1159
- ],
1160
- score: 0.8,
1161
- },
1162
- {
1163
- type: "productivity",
1164
- patterns: ["todo", "task", "project", "calendar", "note", "document"],
1165
- score: 0.85,
1166
- },
1167
- {
1168
- type: "communication",
1169
- patterns: ["chat", "message", "email", "notification", "contact"],
1170
- score: 0.8,
1171
- },
1172
- {
1173
- type: "content",
1174
- patterns: ["blog", "article", "news", "media", "gallery", "video"],
1175
- score: 0.75,
1176
- },
1177
- {
1178
- type: "utility",
1179
- patterns: ["tool", "calculator", "converter", "generator", "utility"],
1180
- score: 0.7,
1181
- },
1182
- {
1183
- type: "game",
1184
- patterns: ["game", "play", "score", "level", "player", "board"],
1185
- score: 0.9,
1186
- },
1187
- {
1188
- type: "weather",
1189
- patterns: ["weather", "forecast", "temperature", "climate"],
1190
- score: 0.85,
1191
- },
1192
- {
1193
- type: "finance",
1194
- patterns: ["finance", "banking", "budget", "expense", "investment"],
1195
- score: 0.8,
1196
- },
1197
- ];
1198
- let bestMatch = "general";
1199
- let highestScore = 0;
1200
- for (const pattern of typePatterns) {
1201
- const matchCount = pattern.patterns.filter((p) => lowerContext.includes(p)).length;
1202
- const score = (matchCount / pattern.patterns.length) * pattern.score;
1203
- if (score > highestScore) {
1204
- highestScore = score;
1205
- bestMatch = pattern.type;
1206
- }
1207
- }
1208
- return bestMatch;
1209
- }
1210
- /**
1211
- * Detects the primary intent of the application
1212
- */
1213
- detectPrimaryIntent(context) {
1214
- const lowerContext = context.toLowerCase();
1215
- const intentPatterns = [
1216
- {
1217
- intent: "create",
1218
- patterns: ["create", "add", "new", "generate", "build"],
1219
- score: 0.8,
1220
- },
1221
- {
1222
- intent: "view",
1223
- patterns: ["view", "display", "show", "browse", "list"],
1224
- score: 0.8,
1225
- },
1226
- {
1227
- intent: "manage",
1228
- patterns: ["manage", "organize", "control", "admin", "dashboard"],
1229
- score: 0.8,
1230
- },
1231
- {
1232
- intent: "connect",
1233
- patterns: ["connect", "social", "network", "share", "collaborate"],
1234
- score: 0.8,
1235
- },
1236
- {
1237
- intent: "analyze",
1238
- patterns: ["analyze", "track", "monitor", "report", "insights"],
1239
- score: 0.8,
1240
- },
1241
- {
1242
- intent: "entertain",
1243
- patterns: ["game", "play", "entertain", "fun", "leisure"],
1244
- score: 0.8,
1245
- },
1246
- ];
1247
- let bestIntent = "view";
1248
- let highestScore = 0;
1249
- for (const pattern of intentPatterns) {
1250
- const matchCount = pattern.patterns.filter((p) => lowerContext.includes(p)).length;
1251
- const score = (matchCount / pattern.patterns.length) * pattern.score;
1252
- if (score > highestScore) {
1253
- highestScore = score;
1254
- bestIntent = pattern.intent;
1255
- }
1256
- }
1257
- return bestIntent;
1258
- }
1259
- /**
1260
- * Assesses the complexity of the application
1261
- */
1262
- assessComplexity(context) {
1263
- const wordCount = context.split(" ").length;
1264
- const featureKeywords = [
1265
- "authentication",
1266
- "payment",
1267
- "real-time",
1268
- "api",
1269
- "database",
1270
- "search",
1271
- "filter",
1272
- "chart",
1273
- "notification",
1274
- ];
1275
- const featureCount = featureKeywords.filter((keyword) => context.toLowerCase().includes(keyword)).length;
1276
- if (wordCount > 100 || featureCount > 5)
1277
- return "high";
1278
- if (wordCount > 50 || featureCount > 3)
1279
- return "medium";
1280
- return "low";
1281
- }
1282
- /**
1283
- * Extracts key features from the context
1284
- */
1285
- extractKeyFeatures(context) {
1286
- const featurePatterns = [
1287
- /authentication|login|signup|auth/gi,
1288
- /payment|checkout|billing|subscription/gi,
1289
- /search|filter|sort/gi,
1290
- /real.?time|live|instant/gi,
1291
- /notification|alert|reminder/gi,
1292
- /chart|graph|analytics|metrics/gi,
1293
- /upload|file|media/gi,
1294
- /location|map|geolocation/gi,
1295
- /chat|message|communication/gi,
1296
- /calendar|schedule|booking/gi,
1297
- ];
1298
- const features = [];
1299
- featurePatterns.forEach((pattern) => {
1300
- const matches = context.match(pattern);
1301
- if (matches) {
1302
- features.push(...matches.map((m) => m.toLowerCase()));
1303
- }
1304
- });
1305
- return [...new Set(features)]; // Remove duplicates
1306
- }
1307
- /**
1308
- * Identifies user types from context
1309
- */
1310
- identifyUserTypes(context) {
1311
- const userTypes = [];
1312
- const lowerContext = context.toLowerCase();
1313
- if (lowerContext.includes("admin") || lowerContext.includes("management"))
1314
- userTypes.push("admin");
1315
- if (lowerContext.includes("user") || lowerContext.includes("customer"))
1316
- userTypes.push("user");
1317
- if (lowerContext.includes("guest") || lowerContext.includes("public"))
1318
- userTypes.push("guest");
1319
- if (lowerContext.includes("moderator") || lowerContext.includes("editor"))
1320
- userTypes.push("moderator");
1321
- return userTypes.length > 0 ? userTypes : ["user"];
1322
- }
1323
- /**
1324
- * Identifies data entities from context
1325
- */
1326
- identifyDataEntities(context) {
1327
- const entityPatterns = [
1328
- /user|profile|account/gi,
1329
- /product|item|goods/gi,
1330
- /order|transaction|purchase/gi,
1331
- /post|article|content/gi,
1332
- /comment|review|feedback/gi,
1333
- /category|tag|label/gi,
1334
- /file|document|media/gi,
1335
- /event|activity|log/gi,
1336
- ];
1337
- const entities = [];
1338
- entityPatterns.forEach((pattern) => {
1339
- const matches = context.match(pattern);
1340
- if (matches) {
1341
- entities.push(...matches.map((m) => m.toLowerCase()));
1342
- }
1343
- });
1344
- return [...new Set(entities)];
1345
- }
1346
- /**
1347
- * Extracts technical requirements
1348
- */
1349
- extractTechnicalRequirements(context) {
1350
- const requirements = [];
1351
- const lowerContext = context.toLowerCase();
1352
- if (lowerContext.includes("mobile") || lowerContext.includes("responsive"))
1353
- requirements.push("responsive");
1354
- if (lowerContext.includes("real-time") || lowerContext.includes("live"))
1355
- requirements.push("realtime");
1356
- if (lowerContext.includes("offline") || lowerContext.includes("pwa"))
1357
- requirements.push("offline");
1358
- if (lowerContext.includes("accessibility") || lowerContext.includes("a11y"))
1359
- requirements.push("accessible");
1360
- if (lowerContext.includes("performance") || lowerContext.includes("fast"))
1361
- requirements.push("performant");
1362
- return requirements;
1363
- }
1364
- /**
1365
- * Suggests UI patterns based on app type and intent
1366
- */
1367
- suggestUIPatterns(context) {
1368
- const appType = this.detectAppType(context);
1369
- const patterns = [];
1370
- switch (appType) {
1371
- case "ecommerce":
1372
- patterns.push("product-grid", "shopping-cart", "checkout-flow", "product-detail");
1373
- break;
1374
- case "dashboard":
1375
- patterns.push("data-table", "chart-dashboard", "metric-cards", "sidebar-navigation");
1376
- break;
1377
- case "social":
1378
- patterns.push("feed", "profile-card", "comment-thread", "social-actions");
1379
- break;
1380
- case "productivity":
1381
- patterns.push("list-view", "form-wizard", "calendar-view", "kanban-board");
1382
- break;
1383
- case "weather":
1384
- patterns.push("dashboard", "card-layout", "metric-cards", "chart-dashboard");
1385
- break;
1386
- default:
1387
- patterns.push("list-view", "form", "card-layout", "navigation");
1388
- }
1389
- return patterns;
1390
- }
1391
- /**
1392
- * Suggests component groups based on analysis
1393
- */
1394
- suggestComponentGroups(analysis) {
1395
- const groups = [];
1396
- // Core functionality group
1397
- groups.push({
1398
- name: "Core Functionality",
1399
- description: "Primary application features and main user workflows",
1400
- priority: "high",
1401
- components: this.generateCoreComponents(analysis),
1402
- });
1403
- // Data management group
1404
- if (analysis.complexity !== "low") {
1405
- groups.push({
1406
- name: "Data Management",
1407
- description: "Data input, display, and manipulation components",
1408
- priority: "high",
1409
- components: this.generateDataComponents(analysis),
1410
- });
1411
- }
1412
- // Navigation and layout group
1413
- groups.push({
1414
- name: "Navigation & Layout",
1415
- description: "Layout components and navigation elements",
1416
- priority: "medium",
1417
- components: this.generateLayoutComponents(analysis),
1418
- });
1419
- // User interaction group
1420
- if (analysis.primaryIntent === "create" ||
1421
- analysis.primaryIntent === "manage") {
1422
- groups.push({
1423
- name: "User Interaction",
1424
- description: "Forms, controls, and interactive elements",
1425
- priority: "medium",
1426
- components: this.generateInteractionComponents(analysis),
1427
- });
1428
- }
1429
- // Analytics and feedback group
1430
- if (analysis.appType === "dashboard" ||
1431
- analysis.primaryIntent === "analyze") {
1432
- groups.push({
1433
- name: "Analytics & Feedback",
1434
- description: "Charts, metrics, and user feedback components",
1435
- priority: "medium",
1436
- components: this.generateAnalyticsComponents(analysis),
1437
- });
1438
- }
1439
- return groups;
1440
- }
1441
- /**
1442
- * Creates a priority matrix for components
1443
- */
1444
- createPriorityMatrix(context) {
1445
- const complexity = this.assessComplexity(context);
1446
- return {
1447
- critical: complexity === "high" ? 0.3 : 0.2,
1448
- high: 0.4,
1449
- medium: 0.2,
1450
- low: 0.1,
1451
- };
1452
- }
1453
- /**
1454
- * Generates component list from analysis
1455
- */
1456
- generateComponentListFromAnalysis(analysis, context) {
1457
- const projectName = this.extractProjectName(context);
1458
- return {
1459
- project: {
1460
- name: projectName,
1461
- description: context,
1462
- version: "0.1.0",
1463
- generated: new Date().toISOString(),
1464
- analysis: {
1465
- appType: analysis.appType,
1466
- primaryIntent: analysis.primaryIntent,
1467
- complexity: analysis.complexity,
1468
- keyFeatures: analysis.keyFeatures,
1469
- userTypes: analysis.userTypes,
1470
- dataEntities: analysis.dataEntities,
1471
- technicalRequirements: analysis.technicalRequirements,
1472
- uiPatterns: analysis.uiPatterns,
1473
- },
1474
- },
1475
- groups: analysis.componentGroups,
1476
- metadata: {
1477
- totalComponents: analysis.componentGroups.reduce((acc, group) => acc + group.components.length, 0),
1478
- totalGroups: analysis.componentGroups.length,
1479
- generatedAt: new Date().toISOString(),
1480
- version: "1.0.0",
1481
- analysisScore: this.calculateAnalysisScore(analysis),
1482
- },
1483
- };
1484
- }
1485
- /**
1486
- * Extracts project description from context
1487
- */
1488
- extractProjectDescription(context) {
1489
- // Try to extract from PRD content
1490
- const prdMatch = context.match(/## Project Overview[\s\S]*?\*\*Description:\*\*\s*([^\n]+)/i);
1491
- if (prdMatch && prdMatch[1]) {
1492
- return prdMatch[1].trim();
1493
- }
1494
- // Try to extract from common patterns
1495
- const patterns = [
1496
- /(?:project|app|application)\s+(?:name|called|titled?)\s+["']?([^"'\n]+)["']?/i,
1497
- /(?:create|build|develop)\s+(?:a|an)\s+([a-z\s]+?)\s+(?:app|application)/i,
1498
- /^([A-Z][a-z\s]+?)\s+(?:app|application|platform|system)/i,
1499
- ];
1500
- for (const pattern of patterns) {
1501
- const match = context.match(pattern);
1502
- if (match && match[1]) {
1503
- return match[1].trim();
1504
- }
1505
- }
1506
- // Fallback: use first meaningful phrase
1507
- const words = context.split(" ").slice(0, 3);
1508
- return (words
1509
- .join(" ")
1510
- .replace(/[^\w\s]/g, "")
1511
- .trim() || "MyContext Project");
1512
- }
1513
- /**
1514
- * Extracts project name from context
1515
- */
1516
- extractProjectName(context) {
1517
- // First try to get from the config file
1518
- try {
1519
- const configPath = ".mycontext/config.json";
1520
- // Note: This is a synchronous context, so we'll use a fallback approach
1521
- // The config reading will be handled in the calling method
1522
- }
1523
- catch {
1524
- // Config file doesn't exist or can't be read, continue with other methods
1525
- }
1526
- // Try to extract from PRD content
1527
- const prdMatch = context.match(/## Project Overview[\s\S]*?\*\*Project Name:\*\*\s*([^\n]+)/i);
1528
- if (prdMatch && prdMatch[1]) {
1529
- return prdMatch[1].trim();
1530
- }
1531
- // Try to extract from common patterns
1532
- const patterns = [
1533
- /(?:project|app|application)\s+(?:name|called|titled?)\s+["']?([^"'\n]+)["']?/i,
1534
- /(?:create|build|develop)\s+(?:a|an)\s+([a-z\s]+?)\s+(?:app|application)/i,
1535
- /^([A-Z][a-z\s]+?)\s+(?:app|application|platform|system)/i,
1536
- ];
1537
- for (const pattern of patterns) {
1538
- const match = context.match(pattern);
1539
- if (match && match[1]) {
1540
- return match[1].trim();
1541
- }
1542
- }
1543
- // Fallback: use first meaningful phrase
1544
- const words = context.split(" ").slice(0, 3);
1545
- return (words
1546
- .join(" ")
1547
- .replace(/[^\w\s]/g, "")
1548
- .trim() || "MyContext Project");
1549
- }
1550
- /**
1551
- * Calculates analysis confidence score
1552
- */
1553
- calculateAnalysisScore(analysis) {
1554
- let score = 0;
1555
- // App type detection score
1556
- score += analysis.appType !== "general" ? 20 : 10;
1557
- // Intent detection score
1558
- score += analysis.primaryIntent !== "view" ? 15 : 10;
1559
- // Feature extraction score
1560
- score += Math.min(analysis.keyFeatures.length * 5, 25);
1561
- // User types score
1562
- score += analysis.userTypes.length * 5;
1563
- // Data entities score
1564
- score += Math.min(analysis.dataEntities.length * 3, 15);
1565
- // Technical requirements score
1566
- score += analysis.technicalRequirements.length * 5;
1567
- return Math.min(score, 100);
1568
- }
1569
- // Helper methods for generating specific component types
1570
- generateCoreComponents(analysis) {
1571
- // This would generate components based on app type and intent
1572
- // For now, return a basic set
1573
- return [
1574
- {
1575
- name: `${analysis.appType.charAt(0).toUpperCase() + analysis.appType.slice(1)}App`,
1576
- description: `Main application container for ${analysis.appType} functionality`,
1577
- type: "layout",
1578
- priority: "high",
1579
- userStories: [
1580
- `As a user, I want to access ${analysis.appType} features in a single application`,
1581
- ],
1582
- actionFunctions: ["initializeApp", "handleNavigation", "manageState"],
1583
- dependencies: ["layout", "state", "navigation"],
1584
- tags: [analysis.appType, "app", "container"],
1585
- },
1586
- ];
1587
- }
1588
- generateDataComponents(analysis) {
1589
- const appType = analysis.appType;
1590
- const dataEntities = analysis.dataEntities;
1591
- const components = [];
1592
- if (appType === "ecommerce") {
1593
- components.push({
1594
- name: "ProductList",
1595
- description: "Display and manage product catalog",
1596
- type: "display",
1597
- priority: "high",
1598
- userStories: [
1599
- "As a user, I want to browse products to find items to purchase",
1600
- ],
1601
- actionFunctions: ["loadProducts", "filterProducts", "sortProducts"],
1602
- dependencies: ["list", "card", "button"],
1603
- tags: ["product", "list", "catalog"],
1604
- });
1605
- components.push({
1606
- name: "ProductDetail",
1607
- description: "Show detailed information about a specific product",
1608
- type: "display",
1609
- priority: "medium",
1610
- userStories: ["As a user, I want to view detailed product information"],
1611
- actionFunctions: ["loadProductDetails", "addToCart"],
1612
- dependencies: ["card", "button", "image"],
1613
- tags: ["product", "detail", "information"],
1614
- });
1615
- components.push({
1616
- name: "ShoppingCart",
1617
- description: "Manage items added to the shopping cart",
1618
- type: "interactive",
1619
- priority: "high",
1620
- userStories: [
1621
- "As a user, I want to add items to my cart so that I can purchase multiple items",
1622
- ],
1623
- actionFunctions: [
1624
- "addItemToCart",
1625
- "removeItemFromCart",
1626
- "updateQuantity",
1627
- ],
1628
- dependencies: ["cart", "button", "input"],
1629
- tags: ["cart", "shopping", "checkout"],
1630
- });
1631
- components.push({
1632
- name: "CheckoutForm",
1633
- description: "Multi-step checkout process with payment",
1634
- type: "form",
1635
- priority: "high",
1636
- userStories: ["As a user, I want to complete my purchase securely"],
1637
- actionFunctions: ["validateCheckout", "processPayment", "confirmOrder"],
1638
- dependencies: ["form", "payment-gateway", "validation"],
1639
- tags: ["checkout", "payment", "form"],
1640
- });
1641
- components.push({
1642
- name: "OrderHistory",
1643
- description: "Display user's order history and status",
1644
- type: "display",
1645
- priority: "medium",
1646
- userStories: [
1647
- "As a user, I want to view my order history and track orders",
1648
- ],
1649
- actionFunctions: ["loadOrderHistory", "trackOrder", "cancelOrder"],
1650
- dependencies: ["list", "order-item", "status-indicator"],
1651
- tags: ["order", "history", "tracking"],
1652
- });
1653
- components.push({
1654
- name: "UserProfile",
1655
- description: "Manage user account and preferences",
1656
- type: "form",
1657
- priority: "medium",
1658
- userStories: ["As a user, I want to manage my account and preferences"],
1659
- actionFunctions: ["loadUserProfile", "updateProfile", "changePassword"],
1660
- dependencies: ["form", "avatar", "settings"],
1661
- tags: ["user", "profile", "account"],
1662
- });
1663
- }
1664
- else if (appType === "dashboard") {
1665
- components.push({
1666
- name: "DashboardOverview",
1667
- description: "Display key metrics and quick actions",
1668
- type: "display",
1669
- priority: "high",
1670
- userStories: [
1671
- "As a user, I want to see analytics and performance metrics",
1672
- ],
1673
- actionFunctions: ["loadOverviewData", "updateCharts"],
1674
- dependencies: ["card", "chart", "metric-cards"],
1675
- tags: ["dashboard", "overview", "metrics"],
1676
- });
1677
- components.push({
1678
- name: "DataGrid",
1679
- description: "Display and manage tabular data",
1680
- type: "display",
1681
- priority: "medium",
1682
- userStories: [
1683
- "As a user, I want to view and manage data in a table format",
1684
- ],
1685
- actionFunctions: ["loadData", "filterData", "sortData"],
1686
- dependencies: ["table", "input", "button"],
1687
- tags: ["data", "grid", "table"],
1688
- });
1689
- }
1690
- else if (appType === "productivity") {
1691
- components.push({
1692
- name: "TodoList",
1693
- description: "Display and manage todo items",
1694
- type: "display",
1695
- priority: "high",
1696
- userStories: ["As a user, I want to view and manage todo items"],
1697
- actionFunctions: ["loadTodos", "addTodo", "completeTodo", "deleteTodo"],
1698
- dependencies: ["list", "item", "button"],
1699
- tags: ["todo", "list", "task"],
1700
- });
1701
- components.push({
1702
- name: "TaskDetail",
1703
- description: "Show detailed information about a specific task",
1704
- type: "display",
1705
- priority: "medium",
1706
- userStories: ["As a user, I want to view detailed task information"],
1707
- actionFunctions: ["loadTaskDetails", "updateTaskStatus"],
1708
- dependencies: ["card", "button", "checkbox"],
1709
- tags: ["task", "detail", "information"],
1710
- });
1711
- }
1712
- else if (appType === "weather") {
1713
- components.push({
1714
- name: "WeatherForecast",
1715
- description: "Display weather forecast for a specific location",
1716
- type: "display",
1717
- priority: "high",
1718
- userStories: ["As a user, I want to see weather forecast"],
1719
- actionFunctions: ["loadWeatherForecast", "changeLocation"],
1720
- dependencies: ["card", "chart", "location-picker"],
1721
- tags: ["weather", "forecast", "temperature"],
1722
- });
1723
- components.push({
1724
- name: "WeatherHistory",
1725
- description: "Display historical weather data",
1726
- type: "display",
1727
- priority: "medium",
1728
- userStories: ["As a user, I want to view historical weather data"],
1729
- actionFunctions: ["loadWeatherHistory", "selectDateRange"],
1730
- dependencies: ["chart", "date-picker"],
1731
- tags: ["weather", "history", "temperature"],
1732
- });
1733
- }
1734
- else if (appType === "finance") {
1735
- components.push({
1736
- name: "TransactionList",
1737
- description: "Display and manage financial transactions",
1738
- type: "display",
1739
- priority: "high",
1740
- userStories: [
1741
- "As a user, I want to view and manage financial transactions",
1742
- ],
1743
- actionFunctions: [
1744
- "loadTransactions",
1745
- "filterTransactions",
1746
- "sortTransactions",
1747
- ],
1748
- dependencies: ["list", "transaction-item", "button"],
1749
- tags: ["transaction", "list", "finance"],
1750
- });
1751
- components.push({
1752
- name: "BudgetOverview",
1753
- description: "Display budget overview and spending trends",
1754
- type: "display",
1755
- priority: "medium",
1756
- userStories: [
1757
- "As a user, I want to see budget overview and spending trends",
1758
- ],
1759
- actionFunctions: ["loadBudgetOverview", "updateBudget"],
1760
- dependencies: ["card", "chart", "budget-form"],
1761
- tags: ["budget", "overview", "spending"],
1762
- });
1763
- }
1764
- // Add more specific components for other app types if needed
1765
- return components;
1766
- }
1767
- generateLayoutComponents(analysis) {
1768
- return [
1769
- {
1770
- name: "AppLayout",
1771
- description: "Main application layout with navigation",
1772
- type: "layout",
1773
- priority: "high",
1774
- userStories: [
1775
- "As a user, I want to navigate between different sections easily",
1776
- ],
1777
- actionFunctions: [
1778
- "handleNavigation",
1779
- "toggleSidebar",
1780
- "updateBreadcrumbs",
1781
- ],
1782
- dependencies: ["header", "sidebar", "main"],
1783
- tags: ["layout", "navigation", "structure"],
1784
- },
1785
- ];
1786
- }
1787
- generateInteractionComponents(analysis) {
1788
- return [
1789
- {
1790
- name: "ActionForm",
1791
- description: "Form for user interactions and data input",
1792
- type: "form",
1793
- priority: "medium",
1794
- userStories: ["As a user, I want to input data and perform actions"],
1795
- actionFunctions: ["handleSubmit", "validateInput", "clearForm"],
1796
- dependencies: ["input", "button", "form"],
1797
- tags: ["form", "interaction", "input"],
1798
- },
1799
- ];
1800
- }
1801
- generateAnalyticsComponents(analysis) {
1802
- return [
1803
- {
1804
- name: "AnalyticsDashboard",
1805
- description: "Display analytics and metrics",
1806
- type: "display",
1807
- priority: "medium",
1808
- userStories: [
1809
- "As a user, I want to see analytics and performance metrics",
1810
- ],
1811
- actionFunctions: ["loadMetrics", "updateCharts", "exportData"],
1812
- dependencies: ["chart", "card", "table"],
1813
- tags: ["analytics", "metrics", "dashboard"],
1814
- },
1815
- ];
1816
- }
1817
- generateComponentListMarkdown(data) {
1818
- const { project, groups, metadata } = data;
1819
- let markdown = `# Component List
1820
-
1821
- ## Project Overview
1822
- **Project Name:** ${project?.name || "MyContext Project"}
1823
- **Description:** ${project?.description || "AI-powered component generation platform"}
1824
- **Generated:** ${project?.generated || new Date().toISOString().split("T")[0]}
1825
-
1826
- ## Summary
1827
- - **Total Components:** ${metadata?.totalComponents ||
1828
- groups?.reduce((acc, g) => acc + (g.components?.length || 0), 0) ||
1829
- 0}
1830
- - **Total Groups:** ${metadata?.totalGroups || groups?.length || 0}
1831
- - **Version:** ${metadata?.version || "1.0.0"}
1832
-
1833
- ---
1834
-
1835
- `;
1836
- if (groups && Array.isArray(groups)) {
1837
- groups.forEach((group) => {
1838
- markdown += `## ${group.name}
1839
-
1840
- **Description:** ${group.description}
1841
- **Priority:** ${group.priority}
1842
- **Components:** ${group.components?.length || 0}
1843
-
1844
- `;
1845
- if (group.components && Array.isArray(group.components)) {
1846
- group.components.forEach((component) => {
1847
- markdown += `### ${component.name}
1848
-
1849
- **Type:** ${component.type}
1850
- **Priority:** ${component.priority}
1851
- **Description:** ${component.description}
1852
-
1853
- **User Stories:**
1854
- ${component.userStories?.map((story) => `- ${story}`).join("\n") ||
1855
- "- No user stories defined"}
1856
-
1857
- **Action Functions:**
1858
- ${component.actionFunctions
1859
- ?.map((func) => `- \`${func}\``)
1860
- .join("\n") || "- No action functions defined"}
1861
-
1862
- **Dependencies:** ${component.dependencies?.join(", ") || "None"}
1863
- **Tags:** ${component.tags?.join(", ") || "None"}
1864
-
1865
- ---
1866
- `;
1867
- });
1868
- }
1869
- });
1870
- }
1871
- markdown += `
1872
- ## Implementation Notes
1873
-
1874
- ### Building Blocks Philosophy
1875
- Each component is designed as a reusable building block that can:
1876
- - Work across different projects
1877
- - Include specific action functions for user workflows
1878
- - Be easily customized and extended
1879
- - Follow consistent design patterns
1880
-
1881
- ### User Story Integration
1882
- Components are mapped to specific user stories to ensure they serve real user needs and provide actionable functionality.
1883
-
1884
- ### Action Functions
1885
- Every component includes action functions that handle the business logic and user interactions, making them truly useful rather than just visual elements.
1886
-
1887
- ---
1888
-
1889
- *This component list serves as the blueprint for generating production-ready UI components that fulfill specific user workflows and can be reused across projects.*
1890
- `;
1891
- return markdown;
1892
- }
1893
- async generateLocalAppStructure(context) {
1894
- return {
1895
- directoryStructure: `
1896
- app/
1897
- ├── layout.tsx
1898
- ├── page.tsx
1899
- ├── globals.css
1900
- ├── (auth)/
1901
- │ ├── login/
1902
- │ └── register/
1903
- ├── (dashboard)/
1904
- │ ├── projects/
1905
- │ └── settings/
1906
- components/
1907
- ├── ui/
1908
- └── custom/
1909
- lib/
1910
- ├── utils.ts
1911
- └── types.ts
1912
- `,
1913
- fileTemplates: {
1914
- "app/layout.tsx": "// Root layout component",
1915
- "app/page.tsx": "// Home page component",
1916
- "components/ui/button.tsx": "// Button component",
1917
- },
1918
- componentUsage: {
1919
- UserProfile: "Display user information with avatar and settings",
1920
- ProjectCard: "Show project details in a card format",
1921
- },
1922
- };
1923
- }
1924
- async writeContextFiles(files) {
1925
- for (const [filename, content] of Object.entries(files)) {
1926
- await this.fs.writeFile(`context/${filename}`, content);
1927
- }
1928
- }
1929
- async findPRDFile() {
1930
- const possiblePaths = [
1931
- "context/prd.md",
1932
- "context/PRD.md",
1933
- "context/01_PRD.md",
1934
- ".mycontext/context/prd.md",
1935
- "prd.md",
1936
- "PRD.md",
1937
- ];
1938
- for (const path of possiblePaths) {
1939
- try {
1940
- await this.fs.readFile(path);
1941
- return path;
1942
- }
1943
- catch {
1944
- continue;
1945
- }
1946
- }
1947
- return null;
1948
- }
1949
- async readContextFiles() {
1950
- const files = {};
1951
- const filePaths = [
1952
- "context/01_PRD.md",
1953
- "context/02_user_stories.md",
1954
- "context/03_technical_specs.md",
1955
- "context/types.ts",
1956
- "context/branding.md",
1957
- ];
1958
- for (const filePath of filePaths) {
1959
- try {
1960
- files[filePath] = await this.fs.readFile(filePath);
1961
- }
1962
- catch {
1963
- // File doesn't exist, skip
1964
- }
1965
- }
1966
- return files;
1967
- }
1968
- }
1969
- exports.GenerateCommand = GenerateCommand;
1970
- //# sourceMappingURL=generate.js.map