import execa from "execa"; import fs from "fs-extra"; import path from "path"; import { PlatformAdapter, DeploymentConfig, DeploymentResult, DeploymentStatus, DeploymentHistoryItem, RollbackResult, } from "../platform-adapter"; import { logger } from "../../utils/logger"; /** * AWS platform adapter */ export class AWSAdapter implements PlatformAdapter { /** * Deploy the application to AWS * @param config Deployment configuration * @returns Deployment result */ async deploy(config: DeploymentConfig): Promise { try { // Ensure AWS CLI is installed await this.ensureAWSCLI(); // Set environment variables await this.setEnvironmentVariables(config); // Build the application if needed if (config.buildCommand) { await execa("pnpm", ["run", config.buildCommand], { stdio: "inherit", }); } // Create AWS deployment configuration await this.createAWSConfig(config); // Deploy to AWS const outputDir = config.outputDir || "out"; const bucketName = `${config.environment}-${path.basename(process.cwd())}`; const region = config.region || "us-east-1"; logger.info( `Deploying to AWS S3 bucket: ${bucketName} in region: ${region}` ); // Create S3 bucket if it doesn't exist try { await execa("aws", [ "s3api", "head-bucket", "--bucket", bucketName, "--region", region, ]); } catch (error) { logger.info(`Creating S3 bucket: ${bucketName}`); await execa("aws", [ "s3", "mb", `s3://${bucketName}`, "--region", region, ]); // Configure bucket for static website hosting await execa("aws", [ "s3", "website", `s3://${bucketName}`, "--index-document", "index.html", "--error-document", "index.html", "--region", region, ]); } // Sync files to S3 bucket await execa("aws", [ "s3", "sync", outputDir, `s3://${bucketName}`, "--delete", "--region", region, ]); // Get website URL const url = `http://${bucketName}.s3-website-${region}.amazonaws.com`; // Configure CloudFront if domain is specified let cloudfrontUrl = ""; if (config.domain) { const result = await this.configureDomain(config.domain); if (!result || !this.configuredDomain) { return { success: false }; } cloudfrontUrl = await this.configuredDomain; } return { success: true, url: cloudfrontUrl || url, deploymentId: new Date().toISOString(), }; } catch (error) { logger.error(`AWS deployment error: ${(error as Error).message}`); return { success: false, error: `Failed to deploy to AWS: ${(error as Error).message}`, }; } } /** * Get deployment status * @param deploymentId Deployment ID * @returns Deployment status */ async getStatus(deploymentId?: string): Promise { try { // Ensure AWS CLI is installed await this.ensureAWSCLI(); // Get bucket name const bucketName = `${process.env.NODE_ENV || "development"}-${path.basename(process.cwd())}`; const region = process.env.AWS_REGION || "us-east-1"; // Check if bucket exists try { await execa("aws", [ "s3api", "head-bucket", "--bucket", bucketName, "--region", region, ]); } catch (error) { throw new Error(`Bucket ${bucketName} does not exist`); } // Get website URL const url = `http://${bucketName}.s3-website-${region}.amazonaws.com`; return { status: "deployed", url, id: deploymentId || new Date().toISOString(), createdAt: new Date().toLocaleString(), }; } catch (error) { logger.error(`AWS status error: ${(error as Error).message}`); throw new Error( `Failed to get AWS deployment status: ${(error as Error).message}` ); } } /** * Get deployment history * @returns Deployment history */ async getHistory(): Promise { try { // Ensure AWS CLI is installed await this.ensureAWSCLI(); // Get bucket name const bucketName = `${process.env.NODE_ENV || "development"}-${path.basename(process.cwd())}`; const region = process.env.AWS_REGION || "us-east-1"; // Check if bucket exists try { await execa("aws", [ "s3api", "head-bucket", "--bucket", bucketName, "--region", region, ]); } catch (error) { return []; } // Get website URL const url = `http://${bucketName}.s3-website-${region}.amazonaws.com`; // Get CloudFront distributions const { stdout } = await execa("aws", [ "cloudfront", "list-distributions", "--region", region, ]); const distributions = JSON.parse(stdout); // Find distribution for this bucket const distribution = distributions.DistributionList?.Items?.find( (item: any) => { return item.Origins.Items.some((origin: any) => origin.DomainName.includes(bucketName) ); } ); // Return history return [ { id: new Date().toISOString(), url: distribution?.DomainName ? `https://${distribution.DomainName}` : url, status: "deployed", createdAt: new Date().toLocaleString(), }, ]; } catch (error) { logger.error(`AWS history error: ${(error as Error).message}`); throw new Error( `Failed to get AWS deployment history: ${(error as Error).message}` ); } } /** * Roll back to a previous deployment * @param deploymentId Deployment ID * @returns Rollback result */ async rollback(deploymentId: string): Promise { try { // Ensure AWS CLI is installed await this.ensureAWSCLI(); // AWS doesn't have a built-in rollback mechanism for S3 websites // We would need to implement versioning and restore from a specific version // This is a simplified implementation logger.warn("AWS rollback is not fully implemented"); return { success: false, message: "AWS rollback is not fully implemented", }; } catch (error) { logger.error(`AWS rollback error: ${(error as Error).message}`); return { success: false, message: `Failed to roll back AWS deployment: ${(error as Error).message}`, }; } } private configuredDomain: string | null = null; /** * Configure a custom domain * @param domain Custom domain * @returns CloudFront URL */ async configureDomain(domain: string): Promise { try { // Ensure AWS CLI is installed await this.ensureAWSCLI(); // Get bucket name const bucketName = `${process.env.NODE_ENV || "development"}-${path.basename(process.cwd())}`; const region = process.env.AWS_REGION || "us-east-1"; // Create CloudFront distribution logger.info( `Configuring CloudFront distribution for domain: ${domain}` ); // Check if distribution already exists const { stdout: listOutput } = await execa("aws", [ "cloudfront", "list-distributions", "--region", region, ]); const distributions = JSON.parse(listOutput); // Find distribution for this bucket const existingDistribution = distributions.DistributionList?.Items?.find((item: any) => { return item.Origins.Items.some((origin: any) => origin.DomainName.includes(bucketName) ); }); if (existingDistribution) { logger.info( `Using existing CloudFront distribution: ${existingDistribution.Id}` ); logger.info( `Service is deployed at url: https://${existingDistribution.DomainName}` ); this.configuredDomain = `https://${existingDistribution.DomainName}`; return true; } // Create new distribution const distributionConfig = { CallerReference: `${bucketName}-${Date.now()}`, Comment: `Distribution for ${bucketName}`, DefaultRootObject: "index.html", Origins: { Quantity: 1, Items: [ { Id: `S3-${bucketName}`, DomainName: `${bucketName}.s3.amazonaws.com`, S3OriginConfig: { OriginAccessIdentity: "", }, }, ], }, DefaultCacheBehavior: { TargetOriginId: `S3-${bucketName}`, ViewerProtocolPolicy: "redirect-to-https", AllowedMethods: { Quantity: 2, Items: ["GET", "HEAD"], CachedMethods: { Quantity: 2, Items: ["GET", "HEAD"], }, }, ForwardedValues: { QueryString: false, Cookies: { Forward: "none", }, }, MinTTL: 0, DefaultTTL: 86400, MaxTTL: 31536000, }, Enabled: true, }; // Write distribution config to file const configPath = path.join( process.cwd(), "cloudfront-config.json" ); await fs.writeFile( configPath, JSON.stringify(distributionConfig, null, 2), "utf8" ); // Create distribution const { stdout } = await execa("aws", [ "cloudfront", "create-distribution", "--distribution-config", `file://${configPath}`, "--region", region, ]); // Parse distribution const distribution = JSON.parse(stdout); const cloudfrontUrl = `https://${distribution.Distribution.DomainName}`; // Clean up config file await fs.remove(configPath); logger.info(`Service is deployed at url: ${cloudfrontUrl}`); this.configuredDomain = cloudfrontUrl; return true; } catch (error) { logger.error( `AWS domain configuration error: ${(error as Error).message}` ); return false; } } /** * Ensure AWS CLI is installed */ private async ensureAWSCLI(): Promise { try { await execa("aws", ["--version"]); } catch (error) { throw new Error( "AWS CLI is not installed. Please install it first." ); } } /** * Set environment variables * @param config Deployment configuration */ private async setEnvironmentVariables( config: DeploymentConfig ): Promise { try { // Check if .env file exists const envPath = path.join(process.cwd(), ".env"); if (fs.existsSync(envPath)) { // Read .env file const envContent = await fs.readFile(envPath, "utf8"); const envVars = this.parseEnvFile(envContent); // Set environment variables for (const [key, value] of Object.entries(envVars)) { process.env[key] = value; } } // Check if .env.{environment} file exists const envEnvironmentPath = path.join( process.cwd(), `.env.${config.environment}` ); if (fs.existsSync(envEnvironmentPath)) { // Read .env.{environment} file const envContent = await fs.readFile( envEnvironmentPath, "utf8" ); const envVars = this.parseEnvFile(envContent); // Set environment variables for (const [key, value] of Object.entries(envVars)) { process.env[key] = value; } } // Set AWS specific environment variables process.env.NODE_ENV = config.environment; process.env.AWS_REGION = config.region || "us-east-1"; } catch (error) { logger.warn( `Failed to set environment variables: ${(error as Error).message}` ); } } /** * Create AWS deployment configuration * @param config Deployment configuration */ private async createAWSConfig(config: DeploymentConfig): Promise { try { // Create AWS config directory if it doesn't exist const awsConfigDir = path.join( process.env.HOME || process.env.USERPROFILE || "", ".aws" ); await fs.ensureDir(awsConfigDir); // Check if AWS credentials are set const credentialsPath = path.join(awsConfigDir, "credentials"); if (!fs.existsSync(credentialsPath)) { // Prompt user to set AWS credentials logger.warn( "AWS credentials not found. Please set them up using `aws configure`" ); } // Create AWS config file if it doesn't exist const configPath = path.join(awsConfigDir, "config"); if (!fs.existsSync(configPath)) { const awsConfig = `[default] region = ${config.region || "us-east-1"} output = json `; await fs.writeFile(configPath, awsConfig, "utf8"); } } catch (error) { logger.warn( `Failed to create AWS configuration: ${(error as Error).message}` ); } } /** * Parse .env file * @param content .env file content * @returns Environment variables */ private parseEnvFile(content: string): Record { const envVars: Record = {}; const lines = content.split("\n"); for (const line of lines) { // Skip comments and empty lines if (line.startsWith("#") || line.trim() === "") { continue; } // Parse key-value pair const match = line.match(/^([^=]+)=(.*)$/); if (match) { const key = match[1].trim(); const value = match[2].trim(); envVars[key] = value; } } return envVars; } }