import fs from "fs-extra"; import path from "path"; import inquirer from "inquirer"; import { logger } from "../utils/logger"; /** * CI/CD configuration generator */ export class CICDConfigGenerator { /** * Generate CI/CD configuration * @param interactive Whether to use interactive mode * @param platform CI/CD platform * @param deployPlatform Deployment platform * @returns Generated configuration */ async generate( interactive: boolean = false, platform: string = "github", deployPlatform: string = "vercel" ): Promise { try { // Default configuration let config: Record = { platform, deployPlatform, }; // If interactive mode is enabled, prompt for configuration if (interactive) { config = await this.promptForConfiguration(config); } // Generate configuration files await this.generateConfigurationFiles(config); logger.success("CI/CD configuration generated successfully!"); } catch (error) { logger.error( `Failed to generate CI/CD configuration: ${(error as Error).message}` ); throw error; } } /** * Prompt for configuration * @param defaultConfig Default configuration * @returns User configuration */ private async promptForConfiguration( defaultConfig: Record ): Promise> { try { // Prompt for CI/CD platform const { platform } = await inquirer.prompt([ { type: "list", name: "platform", message: "Select a CI/CD platform:", choices: ["github", "gitlab", "circleci", "jenkins"], default: defaultConfig.platform, }, ]); // Prompt for deployment platform const { deployPlatform } = await inquirer.prompt([ { type: "list", name: "deployPlatform", message: "Select a deployment platform:", choices: ["vercel", "netlify", "aws"], default: defaultConfig.deployPlatform, }, ]); // Prompt for Node.js version const { nodeVersion } = await inquirer.prompt([ { type: "list", name: "nodeVersion", message: "Select a Node.js version:", choices: ["18.x", "20.x", "16.x"], default: "20.x", }, ]); // Prompt for test command const { testCommand } = await inquirer.prompt([ { type: "input", name: "testCommand", message: "Enter the test command:", default: "npm run test", }, ]); // Prompt for build command const { buildCommand } = await inquirer.prompt([ { type: "input", name: "buildCommand", message: "Enter the build command:", default: "npm run build", }, ]); // Return configuration return { platform, deployPlatform, nodeVersion, testCommand, buildCommand, }; } catch (error) { logger.error( `Failed to prompt for configuration: ${(error as Error).message}` ); throw error; } } /** * Generate configuration files * @param config Configuration */ private async generateConfigurationFiles( config: Record ): Promise { try { // Create configuration files based on platform switch (config.platform) { case "github": await this.generateGitHubWorkflow(config); break; case "gitlab": await this.generateGitLabCI(config); break; case "circleci": await this.generateCircleCI(config); break; case "jenkins": await this.generateJenkinsfile(config); break; default: throw new Error( `Unsupported CI/CD platform: ${config.platform}` ); } } catch (error) { logger.error( `Failed to generate configuration files: ${(error as Error).message}` ); throw error; } } /** * Generate GitHub workflow configuration * @param config Configuration */ private async generateGitHubWorkflow( config: Record ): Promise { try { // Create .github/workflows directory const workflowsDir = path.join( process.cwd(), ".github", "workflows" ); await fs.ensureDir(workflowsDir); // Generate workflow file const workflowPath = path.join(workflowsDir, "ci-cd.yml"); // Generate workflow content based on deployment platform let workflowContent = ""; switch (config.deployPlatform) { case "vercel": workflowContent = this.generateGitHubVercelWorkflow(config); break; case "netlify": workflowContent = this.generateGitHubNetlifyWorkflow(config); break; case "aws": workflowContent = this.generateGitHubAWSWorkflow(config); break; default: throw new Error( `Unsupported deployment platform: ${config.deployPlatform}` ); } // Write workflow file await fs.writeFile(workflowPath, workflowContent, "utf8"); logger.success( `GitHub workflow configuration generated at ${workflowPath}` ); } catch (error) { logger.error( `Failed to generate GitHub workflow: ${(error as Error).message}` ); throw error; } } /** * Generate GitHub workflow for Vercel * @param config Configuration * @returns Workflow content */ private generateGitHubVercelWorkflow(config: Record): string { return `name: CI/CD on: push: branches: [ main ] pull_request: branches: [ main ] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node.js ${config.nodeVersion} uses: actions/setup-node@v3 with: node-version: ${config.nodeVersion} cache: 'npm' - name: Install dependencies run: npm ci - name: Run tests run: ${config.testCommand} deploy: needs: test if: github.event_name == 'push' && github.ref == 'refs/heads/main' runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node.js ${config.nodeVersion} uses: actions/setup-node@v3 with: node-version: ${config.nodeVersion} cache: 'npm' - name: Install dependencies run: npm ci - name: Build run: ${config.buildCommand} - name: Deploy to Vercel uses: amondnet/vercel-action@v20 with: vercel-token: \${{ secrets.VERCEL_TOKEN }} vercel-org-id: \${{ secrets.VERCEL_ORG_ID }} vercel-project-id: \${{ secrets.VERCEL_PROJECT_ID }} vercel-args: '--prod' `; } /** * Generate GitHub workflow for Netlify * @param config Configuration * @returns Workflow content */ private generateGitHubNetlifyWorkflow(config: Record): string { return `name: CI/CD on: push: branches: [ main ] pull_request: branches: [ main ] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node.js ${config.nodeVersion} uses: actions/setup-node@v3 with: node-version: ${config.nodeVersion} cache: 'npm' - name: Install dependencies run: npm ci - name: Run tests run: ${config.testCommand} deploy: needs: test if: github.event_name == 'push' && github.ref == 'refs/heads/main' runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node.js ${config.nodeVersion} uses: actions/setup-node@v3 with: node-version: ${config.nodeVersion} cache: 'npm' - name: Install dependencies run: npm ci - name: Build run: ${config.buildCommand} - name: Deploy to Netlify uses: nwtgck/actions-netlify@v1.2 with: publish-dir: './out' production-branch: main github-token: \${{ secrets.GITHUB_TOKEN }} deploy-message: "Deploy from GitHub Actions" env: NETLIFY_AUTH_TOKEN: \${{ secrets.NETLIFY_AUTH_TOKEN }} NETLIFY_SITE_ID: \${{ secrets.NETLIFY_SITE_ID }} `; } /** * Generate GitHub workflow for AWS * @param config Configuration * @returns Workflow content */ private generateGitHubAWSWorkflow(config: Record): string { return `name: CI/CD on: push: branches: [ main ] pull_request: branches: [ main ] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node.js ${config.nodeVersion} uses: actions/setup-node@v3 with: node-version: ${config.nodeVersion} cache: 'npm' - name: Install dependencies run: npm ci - name: Run tests run: ${config.testCommand} deploy: needs: test if: github.event_name == 'push' && github.ref == 'refs/heads/main' runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node.js ${config.nodeVersion} uses: actions/setup-node@v3 with: node-version: ${config.nodeVersion} cache: 'npm' - name: Install dependencies run: npm ci - name: Build run: ${config.buildCommand} - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v1 with: aws-access-key-id: \${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: \${{ secrets.AWS_SECRET_ACCESS_KEY }} aws-region: \${{ secrets.AWS_REGION }} - name: Deploy to S3 run: | aws s3 sync ./out s3://\${{ secrets.AWS_S3_BUCKET }} --delete - name: Invalidate CloudFront cache run: | aws cloudfront create-invalidation --distribution-id \${{ secrets.AWS_CLOUDFRONT_DISTRIBUTION_ID }} --paths "/*" `; } /** * Generate GitLab CI configuration * @param config Configuration */ private async generateGitLabCI(config: Record): Promise { try { // Generate GitLab CI file const gitlabCIPath = path.join(process.cwd(), ".gitlab-ci.yml"); // Generate GitLab CI content based on deployment platform let gitlabCIContent = ""; switch (config.deployPlatform) { case "vercel": gitlabCIContent = this.generateGitLabVercelCI(config); break; case "netlify": gitlabCIContent = this.generateGitLabNetlifyCI(config); break; case "aws": gitlabCIContent = this.generateGitLabAWSCI(config); break; default: throw new Error( `Unsupported deployment platform: ${config.deployPlatform}` ); } // Write GitLab CI file await fs.writeFile(gitlabCIPath, gitlabCIContent, "utf8"); logger.success( `GitLab CI configuration generated at ${gitlabCIPath}` ); } catch (error) { logger.error( `Failed to generate GitLab CI: ${(error as Error).message}` ); throw error; } } /** * Generate GitLab CI for Vercel * @param config Configuration * @returns GitLab CI content */ private generateGitLabVercelCI(config: Record): string { return `image: node:${config.nodeVersion} stages: - test - deploy cache: paths: - node_modules/ test: stage: test script: - npm ci - ${config.testCommand} deploy: stage: deploy script: - npm ci - ${config.buildCommand} - npm install -g vercel - vercel --token $VERCEL_TOKEN --prod only: - main environment: name: production url: https://$CI_PROJECT_NAME.vercel.app `; } /** * Generate GitLab CI for Netlify * @param config Configuration * @returns GitLab CI content */ private generateGitLabNetlifyCI(config: Record): string { return `image: node:${config.nodeVersion} stages: - test - deploy cache: paths: - node_modules/ test: stage: test script: - npm ci - ${config.testCommand} deploy: stage: deploy script: - npm ci - ${config.buildCommand} - npm install -g netlify-cli - netlify deploy --site $NETLIFY_SITE_ID --auth $NETLIFY_AUTH_TOKEN --prod only: - main environment: name: production url: https://$CI_PROJECT_NAME.netlify.app `; } /** * Generate GitLab CI for AWS * @param config Configuration * @returns GitLab CI content */ private generateGitLabAWSCI(config: Record): string { return `image: node:${config.nodeVersion} stages: - test - deploy cache: paths: - node_modules/ test: stage: test script: - npm ci - ${config.testCommand} deploy: stage: deploy image: name: amazon/aws-cli entrypoint: [""] script: - npm ci - ${config.buildCommand} - aws s3 sync ./out s3://$AWS_S3_BUCKET --delete - aws cloudfront create-invalidation --distribution-id $AWS_CLOUDFRONT_DISTRIBUTION_ID --paths "/*" only: - main environment: name: production url: https://$AWS_S3_BUCKET.s3-website-$AWS_REGION.amazonaws.com `; } /** * Generate CircleCI configuration * @param config Configuration */ private async generateCircleCI(config: Record): Promise { try { // Create .circleci directory const circleCIDir = path.join(process.cwd(), ".circleci"); await fs.ensureDir(circleCIDir); // Generate CircleCI config file const circleCIPath = path.join(circleCIDir, "config.yml"); // Generate CircleCI content based on deployment platform let circleCIContent = ""; switch (config.deployPlatform) { case "vercel": circleCIContent = this.generateCircleCIVercel(config); break; case "netlify": circleCIContent = this.generateCircleCINetlify(config); break; case "aws": circleCIContent = this.generateCircleCIAWS(config); break; default: throw new Error( `Unsupported deployment platform: ${config.deployPlatform}` ); } // Write CircleCI config file await fs.writeFile(circleCIPath, circleCIContent, "utf8"); logger.success( `CircleCI configuration generated at ${circleCIPath}` ); } catch (error) { logger.error( `Failed to generate CircleCI config: ${(error as Error).message}` ); throw error; } } /** * Generate CircleCI config for Vercel * @param config Configuration * @returns CircleCI config content */ private generateCircleCIVercel(config: Record): string { return `version: 2.1 orbs: node: circleci/node@5.0.0 jobs: test: docker: - image: cimg/node:${config.nodeVersion} steps: - checkout - node/install-packages: pkg-manager: npm - run: name: Run tests command: ${config.testCommand} deploy: docker: - image: cimg/node:${config.nodeVersion} steps: - checkout - node/install-packages: pkg-manager: npm - run: name: Build command: ${config.buildCommand} - run: name: Install Vercel CLI command: npm install -g vercel - run: name: Deploy to Vercel command: vercel --token $VERCEL_TOKEN --prod workflows: version: 2 test-and-deploy: jobs: - test - deploy: requires: - test filters: branches: only: main `; } /** * Generate CircleCI config for Netlify * @param config Configuration * @returns CircleCI config content */ private generateCircleCINetlify(config: Record): string { return `version: 2.1 orbs: node: circleci/node@5.0.0 jobs: test: docker: - image: cimg/node:${config.nodeVersion} steps: - checkout - node/install-packages: pkg-manager: npm - run: name: Run tests command: ${config.testCommand} deploy: docker: - image: cimg/node:${config.nodeVersion} steps: - checkout - node/install-packages: pkg-manager: npm - run: name: Build command: ${config.buildCommand} - run: name: Install Netlify CLI command: npm install -g netlify-cli - run: name: Deploy to Netlify command: netlify deploy --site $NETLIFY_SITE_ID --auth $NETLIFY_AUTH_TOKEN --prod workflows: version: 2 test-and-deploy: jobs: - test - deploy: requires: - test filters: branches: only: main `; } /** * Generate CircleCI config for AWS * @param config Configuration * @returns CircleCI config content */ private generateCircleCIAWS(config: Record): string { return `version: 2.1 orbs: node: circleci/node@5.0.0 aws-cli: circleci/aws-cli@3.1.1 jobs: test: docker: - image: cimg/node:${config.nodeVersion} steps: - checkout - node/install-packages: pkg-manager: npm - run: name: Run tests command: ${config.testCommand} deploy: docker: - image: cimg/node:${config.nodeVersion} steps: - checkout - node/install-packages: pkg-manager: npm - run: name: Build command: ${config.buildCommand} - aws-cli/setup: profile-name: default - run: name: Deploy to S3 command: aws s3 sync ./out s3://$AWS_S3_BUCKET --delete - run: name: Invalidate CloudFront cache command: aws cloudfront create-invalidation --distribution-id $AWS_CLOUDFRONT_DISTRIBUTION_ID --paths "/*" workflows: version: 2 test-and-deploy: jobs: - test - deploy: requires: - test filters: branches: only: main `; } /** * Generate Jenkinsfile * @param config Configuration */ private async generateJenkinsfile( config: Record ): Promise { try { // Generate Jenkinsfile const jenkinsfilePath = path.join(process.cwd(), "Jenkinsfile"); // Generate Jenkinsfile content based on deployment platform let jenkinsfileContent = ""; switch (config.deployPlatform) { case "vercel": jenkinsfileContent = this.generateJenkinsfileVercel(config); break; case "netlify": jenkinsfileContent = this.generateJenkinsfileNetlify(config); break; case "aws": jenkinsfileContent = this.generateJenkinsfileAWS(config); break; default: throw new Error( `Unsupported deployment platform: ${config.deployPlatform}` ); } // Write Jenkinsfile await fs.writeFile(jenkinsfilePath, jenkinsfileContent, "utf8"); logger.success(`Jenkinsfile generated at ${jenkinsfilePath}`); } catch (error) { logger.error( `Failed to generate Jenkinsfile: ${(error as Error).message}` ); throw error; } } /** * Generate Jenkinsfile for Vercel * @param config Configuration * @returns Jenkinsfile content */ private generateJenkinsfileVercel(config: Record): string { return `pipeline { agent { docker { image 'node:${config.nodeVersion}' } } stages { stage('Install') { steps { sh 'npm ci' } } stage('Test') { steps { sh '${config.testCommand}' } } stage('Build') { steps { sh '${config.buildCommand}' } } stage('Deploy') { when { branch 'main' } steps { sh 'pnpm install -g vercel' sh 'vercel --token $VERCEL_TOKEN --prod' } } } }`; } /** * Generate Jenkinsfile for Netlify * @param config Configuration * @returns Jenkinsfile content */ private generateJenkinsfileNetlify(config: Record): string { return `pipeline { agent { docker { image 'node:${config.nodeVersion}' } } stages { stage('Install') { steps { sh 'npm ci' } } stage('Test') { steps { sh '${config.testCommand}' } } stage('Build') { steps { sh '${config.buildCommand}' } } stage('Deploy') { when { branch 'main' } steps { sh 'npm install -g netlify-cli' sh 'netlify deploy --site $NETLIFY_SITE_ID --auth $NETLIFY_AUTH_TOKEN --prod' } } } }`; } /** * Generate Jenkinsfile for AWS * @param config Configuration * @returns Jenkinsfile content */ private generateJenkinsfileAWS(config: Record): string { return `pipeline { agent { docker { image 'node:${config.nodeVersion}' } } stages { stage('Install') { steps { sh 'npm ci' } } stage('Test') { steps { sh '${config.testCommand}' } } stage('Build') { steps { sh '${config.buildCommand}' } } stage('Deploy') { when { branch 'main' } steps { sh 'apt-get update && apt-get install -y awscli' sh 'aws s3 sync ./out s3://$AWS_S3_BUCKET --delete' sh 'aws cloudfront create-invalidation --distribution-id $AWS_CLOUDFRONT_DISTRIBUTION_ID --paths "/*"' } } } }`; } }