Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions backend/src/build-system/node/frontend-file-structure/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { BuildHandler, BuildResult } from 'src/build-system/types';
import { BuilderContext } from 'src/build-system/context';
import { ModelProvider } from 'src/common/model-provider';
import { prompts } from './prompt';

export class FileStructureHandler implements BuildHandler {
readonly id = 'op:File_Structure::STATE:GENERATE';
Comment on lines +1 to +7
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Operation ID format needs standardization

The operation IDs in the codebase show inconsistencies in their format:

  • Some use uppercase OP: prefix while others use lowercase op:
  • Some use underscores in operation names (File_Structure, UX_Structure) while others use plain uppercase (PRD, UXSMD)
  • Some use double colons :: as separators while others use single colon :
  • The STATE: segment is present in some IDs but missing in others

Examples of inconsistencies:

  • OP:DATABASE:SCHEMAS vs op:File_Structure::STATE:GENERATE
  • op:UX_Structure::STATE:GENERATE vs op:UXSMD::STATE:GENERATE
  • op:PROJECT::STATE:SETUP vs OP:DATABASE:SCHEMAS
🔗 Analysis chain

Verify the operation ID format consistency

The operation ID op:File_Structure::STATE:GENERATE follows a specific format. Let's verify this format is consistent with other handlers in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other operation IDs to verify format consistency
rg -g '*.ts' 'readonly id = .*' --no-filename | sort -u

Length of output: 479


async run(context: BuilderContext, args: unknown): Promise<BuildResult> {
console.log('Generating File Structure Document...');

// extract relevant data from the context
const projectName =
context.getData('projectName') || 'Default Project Name';

const prompt = prompts.generateFileStructurePrompt(
projectName,
args as string,
// TODO: change later
args as string,
'FrameWork Holder',
);
Comment on lines +16 to +22
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Improve type safety and remove hardcoded values

Several issues in this code segment need attention:

  1. Unsafe type casting of args
  2. Hardcoded framework value
  3. TODO comment needs addressing

Consider this safer implementation:

+    interface FileStructureArgs {
+      sitemapDoc: string;
+      dataAnalysisDoc: string;
+      framework: string;
+    }
+    
+    if (!args || typeof args !== 'object') {
+      throw new Error('Invalid arguments provided to FileStructureHandler');
+    }
+
+    const typedArgs = args as FileStructureArgs;
+
     const prompt = prompts.generateFileStructurePrompt(
       projectName,
-      args as string,
-      // TODO: change later
-      args as string,
-      'FrameWork Holder',
+      typedArgs.sitemapDoc,
+      typedArgs.dataAnalysisDoc,
+      typedArgs.framework,
     );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const prompt = prompts.generateFileStructurePrompt(
projectName,
args as string,
// TODO: change later
args as string,
'FrameWork Holder',
);
interface FileStructureArgs {
sitemapDoc: string;
dataAnalysisDoc: string;
framework: string;
}
if (!args || typeof args !== 'object') {
throw new Error('Invalid arguments provided to FileStructureHandler');
}
const typedArgs = args as FileStructureArgs;
const prompt = prompts.generateFileStructurePrompt(
projectName,
typedArgs.sitemapDoc,
typedArgs.dataAnalysisDoc,
typedArgs.framework,
);


const fileStructureContent = await context.model.chatSync(
{
content: prompt,
},
'gpt-4o-mini',
);
return {
success: true,
data: fileStructureContent,
};
}
Comment on lines +24 to +34
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling and input validation

The model interaction lacks error handling and the response isn't validated before returning.

Consider this improved implementation:

+    if (!prompt) {
+      throw new Error('Failed to generate prompt for file structure');
+    }
+
+    try {
       const fileStructureContent = await context.model.chatSync(
         {
           content: prompt,
         },
         'gpt-4o-mini',
       );
+
+      if (!fileStructureContent) {
+        throw new Error('No content generated by the model');
+      }
+
       return {
         success: true,
         data: fileStructureContent,
       };
+    } catch (error) {
+      context.logger.error('Failed to generate file structure', { error });
+      return {
+        success: false,
+        error: error instanceof Error ? error.message : 'Unknown error occurred',
+      };
+    }

Committable suggestion skipped: line range outside the PR's diff.

}
64 changes: 64 additions & 0 deletions backend/src/build-system/node/frontend-file-structure/prompt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
export const prompts = {
generateFileStructurePrompt: (
projectName: string,
sitemapDoc: string,
DataAnalysisDoc: string,
framework: string,
): string => {
return `You are an expert frontend developer. Your task is to generate a complete folder and file structure for the src directory of a frontend project. Include all necessary files and folders to cover UI, API calls, and local state management while ensuring scalability and maintainability.
Based on following input

- Project name: ${projectName}
- Sitemap Documentation: ${sitemapDoc}
- Data Analysis Doc ${DataAnalysisDoc}

Comment on lines +8 to +14
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add parameter validation and utilize the framework parameter.

  1. The framework parameter is not being used in the template, which could lead to incorrect file extensions.
  2. Consider adding validation for empty or undefined parameters.
   ): string => {
+    if (!projectName || !sitemapDoc || !dataAnalysisDoc || !framework) {
+      throw new Error('All parameters are required for generating file structure prompt');
+    }
+    const fileExtension = framework.toLowerCase().includes('react') ? 'tsx' : 'js';
     return `You are an expert frontend developer. Your task is to generate a complete folder and file structure for the src directory of a frontend project. Include all necessary files and folders to cover UI, API calls, and local state management while ensuring scalability and maintainability. 
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return `You are an expert frontend developer. Your task is to generate a complete folder and file structure for the src directory of a frontend project. Include all necessary files and folders to cover UI, API calls, and local state management while ensuring scalability and maintainability.
Based on following input
- Project name: ${projectName}
- Sitemap Documentation: ${sitemapDoc}
- Data Analysis Doc ${DataAnalysisDoc}
if (!projectName || !sitemapDoc || !dataAnalysisDoc || !framework) {
throw new Error('All parameters are required for generating file structure prompt');
}
const fileExtension = framework.toLowerCase().includes('react') ? 'tsx' : 'js';
return `You are an expert frontend developer. Your task is to generate a complete folder and file structure for the src directory of a frontend project. Include all necessary files and folders to cover UI, API calls, and local state management while ensuring scalability and maintainability.
Based on following input
- Project name: ${projectName}
- Sitemap Documentation: ${sitemapDoc}
- Data Analysis Doc ${DataAnalysisDoc}

### Instructions and Rules:

Include:
Folder Structure:
components: Reusable UI elements grouped by category (e.g., common, layout, specific).
contexts: Global state management (e.g., auth, theme, player).
hooks: Custom hooks for data fetching and state management.
pages: Route-specific views (e.g., Home, Search, Playlist).
utils: Utility functions (e.g., constants, helpers, validators).
api: Organized API logic (e.g., auth, music, user).
router.ts: Central routing configuration.
index.ts: Application entry point.

Files:
Include placeholder files in each folder to illustrate their purpose.
Add example filenames for components, hooks, APIs, etc.

Do Not Include:

Asset folders (e.g., images, icons, fonts).
Test folders or files.
Service folders unrelated to API logic.

File Naming Guidelines:

Use meaningful and descriptive file names.
For components, include an index.tsx file in each folder to simplify imports.
Each component should have its own folder named after the component (e.g., Button/).
Use index.tsx as the main file inside the component folder.
Component-specific styles must be in index.css within the same folder as the component.
Comment on lines +40 to +44
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Make file extensions framework-agnostic.

The file naming guidelines assume React with TypeScript (.tsx), but this should be dynamic based on the framework parameter.

     Use meaningful and descriptive file names.
-    For components, include an index.tsx file in each folder to simplify imports.
+    For components, include an index.${fileExtension} file in each folder to simplify imports.
     Each component should have its own folder named after the component (e.g., Button/).
-    Use index.tsx as the main file inside the component folder.
+    Use index.${fileExtension} as the main file inside the component folder.

Committable suggestion skipped: line range outside the PR's diff.


File Comments:

Include comments describing the purpose of each file or folder to improve readability.

Self check:
1, Are you consider all the cases based on the sitemap doc? If not add new folder or file

This final result must be 100% complete. Will be directly use in the production

Output Format:

Start with: "\`\`\`FolderStructure"
Tree format:
Include folder names with placeholder/example files inside.
Add comments to describe the purpose of each file/folder.
End with: "\`\`\`"
`;
},
};
Loading