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"; /** * Vercel platform adapter */ export class VercelAdapter implements PlatformAdapter { /** * Deploy the application to Vercel * @param config Deployment configuration * @returns Deployment result */ async deploy(config: DeploymentConfig): Promise { try { // Ensure Vercel CLI is installed await this.ensureVercelCLI(); // Set environment variables await this.setEnvironmentVariables(config); // Build the application if needed if (config.buildCommand) { await execa("pnpm", ["run", config.buildCommand], { stdio: "inherit", }); } // Deploy to Vercel const args = ["--prod", "--yes"]; // Add environment flag if not production if (config.environment !== "production") { args.push("--environment", config.environment); } // Add project path if specified if (config.projectPath) { args.push(config.projectPath); } logger.info(`Deploying to Vercel with args: ${args.join(" ")}`); const { stdout } = await execa("vercel", args); // Parse deployment URL and ID const url = this.parseDeploymentUrl(stdout); const id = this.parseDeploymentId(stdout); // Configure domain if specified if (config.domain) { await this.configureDomain(config.domain); } return { success: true, url, deploymentId: id, }; } catch (error) { logger.error( `Vercel deployment error: ${(error as Error).message}` ); return { success: false, error: `Failed to deploy to Vercel: ${(error as Error).message}`, }; } } /** * Get deployment status * @param deploymentId Deployment ID * @returns Deployment status */ async getStatus(deploymentId?: string): Promise { try { // Ensure Vercel CLI is installed await this.ensureVercelCLI(); // Get deployment status const args = ["list", "--limit", "1"]; if (deploymentId) { args.push("--deployment", deploymentId); } args.push("--json"); const { stdout } = await execa("vercel", args); const deployments = JSON.parse(stdout); const deployment = deployments[0]; return { status: deployment.state, url: deployment.url, id: deployment.uid, createdAt: new Date(deployment.created).toLocaleString(), }; } catch (error) { logger.error(`Vercel status error: ${(error as Error).message}`); throw new Error( `Failed to get Vercel deployment status: ${(error as Error).message}` ); } } /** * Get deployment history * @returns Deployment history */ async getHistory(): Promise { try { // Ensure Vercel CLI is installed await this.ensureVercelCLI(); // Get deployment history const { stdout } = await execa("vercel", ["list", "--json"]); const deployments = JSON.parse(stdout); return deployments.map((deployment: any) => ({ id: deployment.uid, url: deployment.url, status: deployment.state, createdAt: new Date(deployment.created).toLocaleString(), })); } catch (error) { logger.error(`Vercel history error: ${(error as Error).message}`); throw new Error( `Failed to get Vercel 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 Vercel CLI is installed await this.ensureVercelCLI(); // Roll back to previous deployment const { stdout } = await execa("vercel", [ "rollback", deploymentId, ]); const success = stdout.includes("Success"); if (success) { // Get deployment status const status = await this.getStatus(deploymentId); return { success: true, message: "Rollback successful", url: status.url, }; } else { return { success: false, message: "Rollback failed", }; } } catch (error) { logger.error(`Vercel rollback error: ${(error as Error).message}`); return { success: false, message: `Failed to roll back Vercel deployment: ${(error as Error).message}`, }; } } /** * Configure a custom domain * @param domain Custom domain * @returns Success status */ async configureDomain(domain: string): Promise { try { // Ensure Vercel CLI is installed await this.ensureVercelCLI(); // Configure domain const { stdout } = await execa("vercel", [ "domains", "add", domain, ]); return stdout.includes("Success"); } catch (error) { logger.error( `Vercel domain configuration error: ${(error as Error).message}` ); return false; } } /** * Ensure Vercel CLI is installed */ private async ensureVercelCLI(): Promise { try { await execa("vercel", ["--version"]); } catch (error) { logger.info("Vercel CLI not found, installing..."); await execa("pnpm", ["install", "-g", "vercel"]); } } /** * 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)) { await execa("vercel", ["env", "add", 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)) { await execa("vercel", [ "env", "add", key, value, "--environment", config.environment, ]); } } } catch (error) { logger.warn( `Failed to set environment variables: ${(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; } /** * Parse deployment URL from Vercel output * @param output Vercel output * @returns Deployment URL */ private parseDeploymentUrl(output: string): string { const match = output.match(/https:\/\/[a-zA-Z0-9-]+\.vercel\.app/); return match ? match[0] : ""; } /** * Parse deployment ID from Vercel output * @param output Vercel output * @returns Deployment ID */ private parseDeploymentId(output: string): string { const match = output.match(/Deployment ID: ([a-zA-Z0-9]+)/); return match ? match[1] : ""; } }