import fs from "fs-extra"; import path from "path"; import ejs from "ejs"; import execa from "execa"; import { logger } from "../utils/logger"; /** * Project generator options */ export interface ProjectGeneratorOptions { template: string; directory?: string; skipInstall?: boolean; skipGit?: boolean; features?: string[]; deploymentPlatform?: string; } /** * Project generator for creating new projects */ export class ProjectGenerator { /** * List of Shadcn components to install */ private readonly shadcnComponents = [ "accordion", "alert", "alert-dialog", "aspect-ratio", "avatar", "badge", "button", "calendar", "card", "carousel", "checkbox", "collapsible", "command", "context-menu", "dialog", "dropdown-menu", "form", "hover-card", "input", "label", "menubar", "navigation-menu", "popover", "progress", "radio-group", "scroll-area", "select", "separator", "sheet", "skeleton", "slider", "switch", "table", "tabs", "textarea", "toast", "toggle", "tooltip", ]; /** * Generate a new project * @param name Project name * @param options Project generator options */ async generate( name: string, options: ProjectGeneratorOptions ): Promise { try { logger.info("Starting project generation..."); // Set default options const directory = options.directory || name; const template = options.template || "saas"; const features = options.features || [ "auth", "database", "api", "testing", ]; const deploymentPlatform = options.deploymentPlatform || "vercel"; logger.info(`Project name: ${name}`); logger.info(`Template: ${template}`); logger.info(`Features: ${features.join(", ")}`); logger.info(`Deployment platform: ${deploymentPlatform}`); // Create project directory const projectDir = path.resolve(directory); logger.info(`Creating project directory: ${projectDir}`); if (fs.existsSync(projectDir)) { throw new Error( `Directory with name '${template}' is already exists` ); } await fs.mkdir(projectDir); logger.info("Project directory created successfully"); // Load template const templateDir = path.join( __dirname, "..", "..", "templates", template ); logger.info(`Loading template from: ${templateDir}`); if (!fs.existsSync(templateDir)) { throw new Error(`Template '${template}' not found`); } // Copy template files logger.info("Copying template files..."); await fs.copy(templateDir, projectDir, { filter: (src) => { const relPath = src.replace(templateDir, ""); logger.debug(`Processing file: ${relPath}`); // Skip node_modules and .git return ( !relPath.includes("node_modules") && !relPath.includes(".git") ); }, }); logger.info("Template files copied successfully"); // Process template files logger.info("Processing template files..."); await this.processTemplateFiles(projectDir, { name, features, deploymentPlatform, }); logger.info("Template files processed successfully"); // Install dependencies if (!options.skipInstall) { logger.info("Installing dependencies..."); await this.installDependencies(projectDir); logger.info("Dependencies installed successfully"); } else { logger.info("Skipping dependency installation"); } // Install and configure Shadcn components logger.info("Installing Shadcn components..."); await this.installShadcnComponents(projectDir); logger.info("Shadcn components installed successfully"); // Initialize git repository if (!options.skipGit) { logger.info("Initializing git repository..."); await this.initGitRepository(projectDir); logger.info("Git repository initialized successfully"); } else { logger.info("Skipping git initialization"); } // Create deployment configuration logger.info("Creating deployment configuration..."); await this.createDeploymentConfig(projectDir, deploymentPlatform); logger.info("Deployment configuration created successfully"); logger.success(`Project '${name}' created successfully`); } catch (error) { logger.error( `Failed to generate project: ${(error as Error).message}` ); throw error; } } /** * Process template files * @param projectDir Project directory * @param data Template data */ private async processTemplateFiles( projectDir: string, data: Record ): Promise { try { logger.info("Getting list of files to process..."); // Get all files in the project directory const files = await this.getFiles(projectDir); logger.info(`Found ${files.length} files to process`); // Process each file for (const file of files) { logger.debug(`Processing file: ${file}`); // Skip binary files if (this.isBinaryFile(file)) { logger.debug(`Skipping binary file: ${file}`); continue; } // Read file content const content = await fs.readFile(file, "utf8"); // Process file content with EJS const processedContent = ejs.render(content, data); // Write processed content back to file await fs.writeFile(file, processedContent, "utf8"); logger.debug(`Processed file: ${file}`); } // Rename files if needed logger.info("Renaming special files..."); await this.renameFiles(projectDir, data); logger.info("Special files renamed successfully"); } catch (error) { logger.error( `Failed to process template files: ${(error as Error).message}` ); throw error; } } /** * Get all files in a directory recursively * @param dir Directory * @returns Array of file paths */ private async getFiles(dir: string): Promise { logger.debug(`Scanning directory: ${dir}`); const dirents = await fs.readdir(dir, { withFileTypes: true }); const files = await Promise.all( dirents.map((dirent) => { const res = path.resolve(dir, dirent.name); return dirent.isDirectory() ? this.getFiles(res) : res; }) ); return Array.prototype.concat(...files); } /** * Check if a file is binary * @param file File path * @returns True if the file is binary */ private isBinaryFile(file: string): boolean { const ext = path.extname(file).toLowerCase(); const binaryExtensions = [ ".png", ".jpg", ".jpeg", ".gif", ".ico", ".pdf", ".zip", ".tar", ".gz", ".7z", ".mp3", ".mp4", ".avi", ".mov", ".wmv", ".woff", ".woff2", ".eot", ".ttf", ]; return binaryExtensions.includes(ext); } /** * Rename files if needed * @param projectDir Project directory * @param data Template data */ private async renameFiles( projectDir: string, data: Record ): Promise { const toRename = ["gitignore", "cursorrules", "env.example"]; for (const file of toRename) { const filePath = path.join(projectDir, file); if (fs.existsSync(filePath)) { logger.debug(`Renaming ${file} to .${file}`); await fs.rename(filePath, path.join(projectDir, "." + file)); } } } /** * Install dependencies * @param projectDir Project directory */ private async installDependencies(projectDir: string): Promise { try { logger.info("Installing dependencies..."); const { stdout, stderr } = await execa("pnpm", ["install"], { cwd: projectDir, stdio: "pipe", }); if (stderr) { logger.warn(`Dependency installation warnings: ${stderr}`); } logger.debug(`Dependency installation output: ${stdout}`); } catch (error) { logger.error( `Failed to install dependencies: ${(error as Error).message}` ); throw error; } } /** * Initialize git repository * @param projectDir Project directory */ private async initGitRepository(projectDir: string): Promise { try { logger.info("Initializing git repository..."); await execa("git", ["init"], { cwd: projectDir }); logger.debug("Git repository initialized"); await execa("git", ["add", "."], { cwd: projectDir }); logger.debug("Files added to git"); await execa("git", ["commit", "-m", "Initial commit"], { cwd: projectDir, }); logger.debug("Initial commit created"); } catch (error) { logger.error( `Failed to initialize git repository: ${(error as Error).message}` ); throw error; } } /** * Create deployment configuration * @param projectDir Project directory * @param deploymentPlatform Deployment platform */ private async createDeploymentConfig( projectDir: string, deploymentPlatform: string ): Promise { try { logger.info("Creating deployment configuration..."); const configPath = path.join(projectDir, "rsdt.config.js"); const config = `module.exports = { deployment: { platform: '${deploymentPlatform}', environment: 'development', optimization: { optimizeImages: true, optimizeFonts: true, generateServiceWorker: true }, hooks: { preDeploy: 'pnpm run test', postDeploy: 'pnpm run notify' } } };`; await fs.writeFile(configPath, config, "utf8"); logger.debug(`Deployment configuration written to ${configPath}`); } catch (error) { logger.error( `Failed to create deployment configuration: ${(error as Error).message}` ); throw error; } } /** * Install and configure Shadcn components * @param projectDir Project directory */ private async installShadcnComponents(projectDir: string): Promise { try { // Initialize Shadcn logger.info("Initializing Shadcn..."); await execa("pnpm", ["dlx", "shadcn-ui@latest", "init"], { cwd: projectDir, stdio: "pipe", }); // Install each component for (const component of this.shadcnComponents) { logger.info(`Installing Shadcn component: ${component}`); try { const { stdout, stderr } = await execa( "pnpm", ["dlx", "shadcn-ui@latest", "add", component], { cwd: projectDir, stdio: "pipe", } ); if (stderr) { logger.warn( `Warning while installing ${component}: ${stderr}` ); } logger.debug(`Component ${component} installed: ${stdout}`); } catch (error) { logger.warn( `Failed to install component ${component}: ${(error as Error).message}` ); // Continue with other components even if one fails continue; } } } catch (error) { logger.error( `Failed to install Shadcn components: ${(error as Error).message}` ); throw error; } } }