infra-cost 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +362 -0
- package/dist/demo/test-enhanced-ui.cjs +1697 -0
- package/dist/demo/test-enhanced-ui.cjs.map +1 -0
- package/dist/demo/test-multi-cloud-dashboard.cjs +3386 -0
- package/dist/demo/test-multi-cloud-dashboard.cjs.map +1 -0
- package/dist/index.cjs +19083 -0
- package/dist/index.cjs.map +1 -0
- package/package.json +94 -19
- package/dist/index.js +0 -487
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/visualization/multi-cloud-dashboard.ts","../../src/types/providers.ts","../../src/providers/aws.ts","../../src/logger.ts","../../src/analytics/anomaly-detector.ts","../../src/providers/gcp.ts","../../src/providers/azure.ts","../../src/providers/alicloud.ts","../../src/providers/oracle.ts","../../src/providers/factory.ts","../../src/discovery/profile-discovery.ts","../../src/visualization/terminal-ui.ts","../../src/demo/test-multi-cloud-dashboard.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { CloudProvider, ResourceInventory, CloudProviderAdapter, ResourceType, ResourceBase } from '../types/providers';\nimport { CloudProviderFactory } from '../providers/factory';\nimport { CloudProfileDiscovery } from '../discovery/profile-discovery';\nimport { TerminalUIEngine } from './terminal-ui';\n\ninterface MultiCloudInventorySummary {\n totalProviders: number;\n totalResources: number;\n totalCost: number;\n providerBreakdown: Record<CloudProvider, {\n inventory: ResourceInventory | null;\n status: 'active' | 'unavailable' | 'error';\n errorMessage?: string;\n resourceCount: number;\n cost: number;\n }>;\n consolidatedResourcesByType: Record<ResourceType, number>;\n topResourcesByProvider: Array<{\n provider: CloudProvider;\n resourceType: ResourceType;\n count: number;\n percentage: number;\n }>;\n}\n\nexport class MultiCloudDashboard {\n private ui: TerminalUIEngine;\n private factory: CloudProviderFactory;\n private discovery: CloudProfileDiscovery;\n\n constructor() {\n this.ui = new TerminalUIEngine();\n this.factory = new CloudProviderFactory();\n this.discovery = new CloudProfileDiscovery();\n }\n\n /**\n * Create comprehensive multi-cloud inventory dashboard\n */\n async generateMultiCloudInventoryDashboard(providers?: CloudProvider[]): Promise<string> {\n console.log(chalk.yellow('🌐 Gathering multi-cloud inventory...'));\n\n const summary = await this.collectMultiCloudInventory(providers);\n return this.renderMultiCloudDashboard(summary);\n }\n\n /**\n * Collect inventory from all available cloud providers\n */\n private async collectMultiCloudInventory(providers?: CloudProvider[]): Promise<MultiCloudInventorySummary> {\n const summary: MultiCloudInventorySummary = {\n totalProviders: 0,\n totalResources: 0,\n totalCost: 0,\n providerBreakdown: {} as any,\n consolidatedResourcesByType: {\n [ResourceType.COMPUTE]: 0,\n [ResourceType.STORAGE]: 0,\n [ResourceType.DATABASE]: 0,\n [ResourceType.NETWORK]: 0,\n [ResourceType.SECURITY]: 0,\n [ResourceType.SERVERLESS]: 0,\n [ResourceType.CONTAINER]: 0,\n [ResourceType.ANALYTICS]: 0\n },\n topResourcesByProvider: []\n };\n\n // Discover available profiles\n const discoveryResults = await this.discovery.discoverAllProfiles();\n const targetProviders = providers || this.factory.getSupportedProviders();\n\n // Process each provider\n for (const provider of targetProviders) {\n const profiles = discoveryResults.byProvider[provider];\n\n summary.providerBreakdown[provider] = {\n inventory: null,\n status: 'unavailable',\n resourceCount: 0,\n cost: 0\n };\n\n if (profiles.length === 0) {\n continue;\n }\n\n try {\n // Use the first available profile for each provider\n const profile = profiles.find(p => p.status === 'available');\n if (!profile) {\n summary.providerBreakdown[provider].status = 'unavailable';\n continue;\n }\n\n console.log(chalk.gray(` Scanning ${provider.toUpperCase()} resources...`));\n\n // Create provider adapter\n const providerAdapter = this.createProviderAdapter(provider, profile);\n\n if (!providerAdapter) {\n summary.providerBreakdown[provider].status = 'error';\n summary.providerBreakdown[provider].errorMessage = 'Failed to initialize provider';\n continue;\n }\n\n // Get inventory\n const inventory = await providerAdapter.getResourceInventory({\n includeCosts: true,\n resourceTypes: Object.values(ResourceType)\n });\n\n summary.providerBreakdown[provider] = {\n inventory,\n status: 'active',\n resourceCount: inventory.totalResources,\n cost: inventory.totalCost\n };\n\n summary.totalProviders++;\n summary.totalResources += inventory.totalResources;\n summary.totalCost += inventory.totalCost;\n\n // Aggregate resource types\n Object.entries(inventory.resourcesByType).forEach(([type, count]) => {\n summary.consolidatedResourcesByType[type as ResourceType] += count;\n });\n\n } catch (error) {\n console.warn(chalk.yellow(`⚠️ Failed to scan ${provider}: ${error instanceof Error ? error.message : 'Unknown error'}`));\n summary.providerBreakdown[provider].status = 'error';\n summary.providerBreakdown[provider].errorMessage = error instanceof Error ? error.message : 'Unknown error';\n }\n }\n\n // Calculate top resources by provider\n summary.topResourcesByProvider = this.calculateTopResourcesByProvider(summary);\n\n return summary;\n }\n\n /**\n * Render the multi-cloud dashboard\n */\n private renderMultiCloudDashboard(summary: MultiCloudInventorySummary): string {\n let output = '';\n\n // Header\n output += this.ui.createHeader('🌐 Multi-Cloud Infrastructure Dashboard',\n `Comprehensive view across ${summary.totalProviders} cloud providers`);\n\n // Executive Summary\n output += chalk.bold.cyan('📊 Executive Summary') + '\\n';\n output += '═'.repeat(60) + '\\n\\n';\n\n const summaryTable = this.ui.createTable([\n { header: 'Metric', width: 25, align: 'left', color: 'cyan' },\n { header: 'Value', width: 20, align: 'right', color: 'yellow' },\n { header: 'Details', width: 30, align: 'left' }\n ], [\n {\n metric: 'Active Providers',\n value: summary.totalProviders.toString(),\n details: this.getActiveProvidersList(summary)\n },\n {\n metric: 'Total Resources',\n value: summary.totalResources.toLocaleString(),\n details: this.getResourceTypeBreakdown(summary)\n },\n {\n metric: 'Total Monthly Cost',\n value: `$${summary.totalCost.toFixed(2)}`,\n details: this.getCostBreakdownByProvider(summary)\n }\n ]);\n\n output += summaryTable + '\\n\\n';\n\n // Provider-by-Provider Breakdown\n output += chalk.bold.cyan('☁️ Provider Breakdown') + '\\n';\n output += '═'.repeat(60) + '\\n\\n';\n\n for (const [provider, data] of Object.entries(summary.providerBreakdown)) {\n const providerName = this.getProviderDisplayName(provider as CloudProvider);\n const statusIcon = this.getStatusIcon(data.status);\n const statusColor = this.getStatusColor(data.status);\n\n output += `${statusIcon} ${chalk.bold[statusColor](providerName)}\\n`;\n\n if (data.status === 'active' && data.inventory) {\n output += ` Resources: ${chalk.yellow(data.resourceCount.toLocaleString())}\\n`;\n output += ` Cost: ${chalk.green(`$${data.cost.toFixed(2)}`)}\\n`;\n output += ` Regions: ${chalk.blue(data.inventory.region)}\\n`;\n output += ` Last Updated: ${chalk.gray(data.inventory.lastUpdated.toLocaleString())}\\n`;\n\n // Top resource types for this provider\n const topTypes = Object.entries(data.inventory.resourcesByType)\n .filter(([, count]) => count > 0)\n .sort(([, a], [, b]) => b - a)\n .slice(0, 3)\n .map(([type, count]) => `${count} ${type}`)\n .join(', ');\n\n if (topTypes) {\n output += ` Top Types: ${chalk.gray(topTypes)}\\n`;\n }\n } else if (data.status === 'error') {\n output += ` ${chalk.red('Error: ' + (data.errorMessage || 'Unknown error'))}\\n`;\n } else if (data.status === 'unavailable') {\n output += ` ${chalk.gray('No credentials or profiles configured')}\\n`;\n }\n\n output += '\\n';\n }\n\n // Consolidated Resource Type Analysis\n output += chalk.bold.cyan('📈 Consolidated Resource Analysis') + '\\n';\n output += '═'.repeat(60) + '\\n\\n';\n\n const resourceTypeTable = this.ui.createTable([\n { header: 'Resource Type', width: 20, align: 'left', color: 'blue' },\n { header: 'Total Count', width: 15, align: 'right', color: 'yellow' },\n { header: 'Percentage', width: 12, align: 'right' },\n { header: 'Top Provider', width: 20, align: 'left' }\n ], this.createResourceTypeRows(summary));\n\n output += resourceTypeTable + '\\n\\n';\n\n // Multi-Cloud Insights\n output += this.generateMultiCloudInsights(summary);\n\n // Recommendations\n output += chalk.bold.cyan('💡 Multi-Cloud Recommendations') + '\\n';\n output += '═'.repeat(60) + '\\n';\n output += this.generateMultiCloudRecommendations(summary);\n\n return output;\n }\n\n /**\n * Generate actionable multi-cloud insights\n */\n private generateMultiCloudInsights(summary: MultiCloudInventorySummary): string {\n let output = chalk.bold.cyan('🧠 Multi-Cloud Insights') + '\\n';\n output += '═'.repeat(60) + '\\n\\n';\n\n const insights = [];\n\n // Provider diversity analysis\n const activeProviders = Object.values(summary.providerBreakdown)\n .filter(p => p.status === 'active').length;\n\n if (activeProviders === 1) {\n insights.push('📍 Single-cloud deployment detected - consider multi-cloud strategy for resilience');\n } else if (activeProviders > 3) {\n insights.push('🌍 Excellent cloud diversity - you have strong vendor independence');\n }\n\n // Cost concentration analysis\n const providerCosts = Object.entries(summary.providerBreakdown)\n .filter(([, data]) => data.status === 'active')\n .map(([provider, data]) => ({ provider, cost: data.cost }))\n .sort((a, b) => b.cost - a.cost);\n\n if (providerCosts.length > 1) {\n const topProvider = providerCosts[0];\n const costPercentage = (topProvider.cost / summary.totalCost) * 100;\n\n if (costPercentage > 70) {\n insights.push(`💰 ${topProvider.provider.toUpperCase()} dominates ${costPercentage.toFixed(1)}% of costs - consider rebalancing`);\n }\n }\n\n // Resource distribution analysis\n const topResourceType = Object.entries(summary.consolidatedResourcesByType)\n .sort(([, a], [, b]) => b - a)[0];\n\n if (topResourceType && topResourceType[1] > 0) {\n const percentage = (topResourceType[1] / summary.totalResources) * 100;\n insights.push(`🔧 ${topResourceType[0]} resources account for ${percentage.toFixed(1)}% of total infrastructure`);\n }\n\n // Add insights to output\n insights.forEach((insight, index) => {\n output += `${index + 1}. ${insight}\\n`;\n });\n\n return output + '\\n';\n }\n\n /**\n * Generate multi-cloud optimization recommendations\n */\n private generateMultiCloudRecommendations(summary: MultiCloudInventorySummary): string {\n let output = '';\n const recommendations = [];\n\n // Cost optimization recommendations\n const activeProviders = Object.entries(summary.providerBreakdown)\n .filter(([, data]) => data.status === 'active');\n\n if (activeProviders.length > 1) {\n recommendations.push('🔄 Use --compare-clouds to identify cost arbitrage opportunities');\n recommendations.push('📊 Run --optimization-report for cross-cloud resource rightsizing');\n }\n\n // Profile management recommendations\n const unavailableProviders = Object.entries(summary.providerBreakdown)\n .filter(([, data]) => data.status === 'unavailable');\n\n if (unavailableProviders.length > 0) {\n recommendations.push('🔧 Configure credentials for unavailable providers to get complete visibility');\n recommendations.push('🔍 Use --discover-profiles to check for existing but unconfigured profiles');\n }\n\n // Monitoring recommendations\n if (summary.totalCost > 1000) {\n recommendations.push('📈 Set up --monitor for real-time cost tracking across all providers');\n recommendations.push('🚨 Configure --alert-threshold for multi-cloud budget management');\n }\n\n // Security recommendations\n recommendations.push('🏷️ Implement consistent tagging strategy across all cloud providers');\n recommendations.push('🔒 Use --dependency-mapping to understand cross-cloud resource relationships');\n\n // Display recommendations\n recommendations.forEach((rec, index) => {\n output += chalk.gray(`${index + 1}. ${rec}\\n`);\n });\n\n output += '\\n' + chalk.bold.yellow('⚡ Quick Actions:') + '\\n';\n output += chalk.gray('• infra-cost --all-profiles --combine-profiles # Aggregate view\\n');\n output += chalk.gray('• infra-cost --compare-clouds aws,gcp,azure # Cost comparison\\n');\n output += chalk.gray('• infra-cost --inventory --group-by provider # Detailed inventory\\n');\n\n return output;\n }\n\n // Helper methods\n private createProviderAdapter(provider: CloudProvider, profile: any): CloudProviderAdapter | null {\n try {\n // This is a simplified approach - in practice, you'd need to properly\n // construct credentials from the discovered profile\n const config = {\n provider,\n credentials: profile.credentials || {},\n region: profile.region,\n profile: profile.name\n };\n\n return this.factory.createProvider(config);\n } catch (error) {\n console.warn(`Failed to create provider adapter for ${provider}: ${error instanceof Error ? error.message : 'Unknown error'}`);\n return null;\n }\n }\n\n private getProviderDisplayName(provider: CloudProvider): string {\n const names = CloudProviderFactory.getProviderDisplayNames();\n return names[provider] || provider.toUpperCase();\n }\n\n private getStatusIcon(status: 'active' | 'unavailable' | 'error'): string {\n switch (status) {\n case 'active': return '✅';\n case 'unavailable': return '⚪';\n case 'error': return '❌';\n default: return '⚪';\n }\n }\n\n private getStatusColor(status: 'active' | 'unavailable' | 'error'): 'green' | 'gray' | 'red' {\n switch (status) {\n case 'active': return 'green';\n case 'unavailable': return 'gray';\n case 'error': return 'red';\n default: return 'gray';\n }\n }\n\n private getActiveProvidersList(summary: MultiCloudInventorySummary): string {\n const active = Object.entries(summary.providerBreakdown)\n .filter(([, data]) => data.status === 'active')\n .map(([provider]) => provider.toUpperCase());\n\n return active.join(', ') || 'None';\n }\n\n private getResourceTypeBreakdown(summary: MultiCloudInventorySummary): string {\n const top3 = Object.entries(summary.consolidatedResourcesByType)\n .filter(([, count]) => count > 0)\n .sort(([, a], [, b]) => b - a)\n .slice(0, 3)\n .map(([type, count]) => `${count} ${type}`);\n\n return top3.join(', ') || 'None';\n }\n\n private getCostBreakdownByProvider(summary: MultiCloudInventorySummary): string {\n const costs = Object.entries(summary.providerBreakdown)\n .filter(([, data]) => data.status === 'active' && data.cost > 0)\n .map(([provider, data]) => `${provider}: $${data.cost.toFixed(0)}`);\n\n return costs.join(', ') || 'None';\n }\n\n private createResourceTypeRows(summary: MultiCloudInventorySummary): any[] {\n return Object.entries(summary.consolidatedResourcesByType)\n .filter(([, count]) => count > 0)\n .sort(([, a], [, b]) => b - a)\n .map(([type, count]) => {\n const percentage = ((count / summary.totalResources) * 100).toFixed(1) + '%';\n const topProvider = this.getTopProviderForResourceType(summary, type as ResourceType);\n\n return {\n resourceType: type.charAt(0).toUpperCase() + type.slice(1),\n totalCount: count.toLocaleString(),\n percentage,\n topProvider: topProvider ? topProvider.toUpperCase() : 'N/A'\n };\n });\n }\n\n private getTopProviderForResourceType(summary: MultiCloudInventorySummary, resourceType: ResourceType): CloudProvider | null {\n let maxCount = 0;\n let topProvider: CloudProvider | null = null;\n\n Object.entries(summary.providerBreakdown).forEach(([provider, data]) => {\n if (data.inventory && data.inventory.resourcesByType[resourceType] > maxCount) {\n maxCount = data.inventory.resourcesByType[resourceType];\n topProvider = provider as CloudProvider;\n }\n });\n\n return topProvider;\n }\n\n private calculateTopResourcesByProvider(summary: MultiCloudInventorySummary): Array<{\n provider: CloudProvider;\n resourceType: ResourceType;\n count: number;\n percentage: number;\n }> {\n const results: Array<{\n provider: CloudProvider;\n resourceType: ResourceType;\n count: number;\n percentage: number;\n }> = [];\n\n Object.entries(summary.providerBreakdown).forEach(([provider, data]) => {\n if (data.inventory && data.resourceCount > 0) {\n Object.entries(data.inventory.resourcesByType).forEach(([type, count]) => {\n if (count > 0) {\n results.push({\n provider: provider as CloudProvider,\n resourceType: type as ResourceType,\n count,\n percentage: (count / summary.totalResources) * 100\n });\n }\n });\n }\n });\n\n return results.sort((a, b) => b.count - a.count).slice(0, 10);\n }\n}\n\nexport default MultiCloudDashboard;","export enum CloudProvider {\n AWS = 'aws',\n GOOGLE_CLOUD = 'gcp',\n AZURE = 'azure',\n ALIBABA_CLOUD = 'alicloud',\n ORACLE_CLOUD = 'oracle'\n}\n\nexport interface ProviderCredentials {\n [key: string]: any;\n}\n\nexport interface CostBreakdown {\n totals: {\n lastMonth: number;\n thisMonth: number;\n last7Days: number;\n yesterday: number;\n };\n totalsByService: {\n lastMonth: { [key: string]: number };\n thisMonth: { [key: string]: number };\n last7Days: { [key: string]: number };\n yesterday: { [key: string]: number };\n };\n}\n\nexport interface RawCostData {\n [serviceName: string]: {\n [date: string]: number;\n };\n}\n\nexport interface ProviderConfig {\n provider: CloudProvider;\n credentials: ProviderCredentials;\n region?: string;\n profile?: string;\n}\n\nexport interface AccountInfo {\n id: string;\n name?: string;\n provider: CloudProvider;\n}\n\nexport abstract class CloudProviderAdapter {\n protected config: ProviderConfig;\n\n constructor(config: ProviderConfig) {\n this.config = config;\n }\n\n abstract getAccountInfo(): Promise<AccountInfo>;\n abstract getRawCostData(): Promise<RawCostData>;\n abstract getCostBreakdown(): Promise<CostBreakdown>;\n abstract validateCredentials(): Promise<boolean>;\n abstract getResourceInventory(filters?: InventoryFilters): Promise<ResourceInventory>;\n abstract getResourceCosts(resourceId: string): Promise<number>;\n abstract getOptimizationRecommendations(): Promise<string[]>;\n abstract getBudgets(): Promise<BudgetInfo[]>;\n abstract getBudgetAlerts(): Promise<BudgetAlert[]>;\n abstract getCostTrendAnalysis(months?: number): Promise<CostTrendAnalysis>;\n abstract getFinOpsRecommendations(): Promise<FinOpsRecommendation[]>;\n\n protected calculateServiceTotals(rawCostData: RawCostData): CostBreakdown {\n // This will be implemented by the base class\n // Common logic for all providers\n return this.processRawCostData(rawCostData);\n }\n\n private processRawCostData(rawCostData: RawCostData): CostBreakdown {\n const totals = {\n lastMonth: 0,\n thisMonth: 0,\n last7Days: 0,\n yesterday: 0,\n };\n\n const totalsByService = {\n lastMonth: {},\n thisMonth: {},\n last7Days: {},\n yesterday: {},\n };\n\n const now = new Date();\n const startOfThisMonth = new Date(now.getFullYear(), now.getMonth(), 1);\n const startOfLastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);\n const endOfLastMonth = new Date(now.getFullYear(), now.getMonth(), 0);\n const yesterday = new Date(now);\n yesterday.setDate(yesterday.getDate() - 1);\n const last7DaysStart = new Date(now);\n last7DaysStart.setDate(last7DaysStart.getDate() - 7);\n\n for (const [serviceName, serviceCosts] of Object.entries(rawCostData)) {\n let lastMonthServiceTotal = 0;\n let thisMonthServiceTotal = 0;\n let last7DaysServiceTotal = 0;\n let yesterdayServiceTotal = 0;\n\n for (const [dateStr, cost] of Object.entries(serviceCosts)) {\n const date = new Date(dateStr);\n\n // Last month\n if (date >= startOfLastMonth && date <= endOfLastMonth) {\n lastMonthServiceTotal += cost;\n }\n\n // This month\n if (date >= startOfThisMonth) {\n thisMonthServiceTotal += cost;\n }\n\n // Last 7 days\n if (date >= last7DaysStart && date < yesterday) {\n last7DaysServiceTotal += cost;\n }\n\n // Yesterday\n if (date.toDateString() === yesterday.toDateString()) {\n yesterdayServiceTotal += cost;\n }\n }\n\n totalsByService.lastMonth[serviceName] = lastMonthServiceTotal;\n totalsByService.thisMonth[serviceName] = thisMonthServiceTotal;\n totalsByService.last7Days[serviceName] = last7DaysServiceTotal;\n totalsByService.yesterday[serviceName] = yesterdayServiceTotal;\n\n totals.lastMonth += lastMonthServiceTotal;\n totals.thisMonth += thisMonthServiceTotal;\n totals.last7Days += last7DaysServiceTotal;\n totals.yesterday += yesterdayServiceTotal;\n }\n\n return {\n totals,\n totalsByService,\n };\n }\n}\n\nexport interface ProviderFactory {\n createProvider(config: ProviderConfig): CloudProviderAdapter;\n getSupportedProviders(): CloudProvider[];\n validateProviderConfig(config: ProviderConfig): boolean;\n}\n\n// Base Resource Interfaces\nexport interface ResourceBase {\n id: string;\n name: string;\n state: string;\n region: string;\n tags?: Record<string, string>;\n createdAt: Date;\n costToDate?: number;\n provider: CloudProvider;\n}\n\nexport interface NetworkResource extends ResourceBase {\n networkId?: string;\n subnetId?: string;\n securityGroups?: string[];\n publicIp?: string;\n privateIp?: string;\n}\n\nexport interface StorageResource extends ResourceBase {\n sizeGB: number;\n storageType: string;\n encrypted?: boolean;\n}\n\nexport interface DatabaseResource extends ResourceBase {\n engine: string;\n version: string;\n instanceClass?: string;\n storageGB?: number;\n multiAZ?: boolean;\n}\n\nexport interface ComputeResource extends ResourceBase {\n instanceType?: string;\n cpu?: number;\n memory?: number;\n platform?: string;\n}\n\n// Resource Types Enum\nexport enum ResourceType {\n COMPUTE = 'compute',\n STORAGE = 'storage',\n DATABASE = 'database',\n NETWORK = 'network',\n SECURITY = 'security',\n SERVERLESS = 'serverless',\n CONTAINER = 'container',\n ANALYTICS = 'analytics'\n}\n\n// AWS Resource Types\nexport interface AWSEC2Instance extends ComputeResource {\n instanceId: string;\n imageId: string;\n keyName?: string;\n securityGroups: string[];\n subnetId: string;\n vpcId: string;\n publicDnsName?: string;\n privateDnsName?: string;\n publicIp?: string;\n privateIp?: string;\n monitoring?: boolean;\n placement: {\n availabilityZone: string;\n groupName?: string;\n };\n}\n\nexport interface AWSS3Bucket extends StorageResource {\n bucketName: string;\n versioning?: boolean;\n publicRead?: boolean;\n publicWrite?: boolean;\n objects?: number;\n lastModified?: Date;\n}\n\nexport interface AWSRDSInstance extends DatabaseResource {\n dbInstanceIdentifier: string;\n dbName?: string;\n masterUsername: string;\n endpoint?: string;\n port?: number;\n availabilityZone?: string;\n backupRetentionPeriod?: number;\n storageEncrypted?: boolean;\n}\n\nexport interface AWSLambdaFunction extends ResourceBase {\n functionName: string;\n runtime: string;\n handler: string;\n codeSize: number;\n timeout: number;\n memorySize: number;\n lastModified: Date;\n version: string;\n}\n\nexport interface AWSVPC extends ResourceBase {\n vpcId: string;\n cidrBlock: string;\n dhcpOptionsId: string;\n isDefault: boolean;\n subnets?: AWSSubnet[];\n}\n\nexport interface AWSSubnet extends NetworkResource {\n subnetId: string;\n vpcId: string;\n cidrBlock: string;\n availableIpAddressCount: number;\n availabilityZone: string;\n mapPublicIpOnLaunch: boolean;\n}\n\nexport interface AWSLoadBalancer extends NetworkResource {\n loadBalancerName: string;\n dnsName: string;\n scheme: string;\n type: 'application' | 'network' | 'gateway';\n ipAddressType?: string;\n listeners?: number;\n targetGroups?: number;\n}\n\nexport interface AWSEBSVolume extends StorageResource {\n volumeId: string;\n volumeType: string;\n iops?: number;\n throughput?: number;\n attachments?: Array<{\n instanceId: string;\n device: string;\n }>;\n snapshotId?: string;\n}\n\n// GCP Resource Types\nexport interface GCPComputeInstance extends ComputeResource {\n instanceName: string;\n machineType: string;\n zone: string;\n image: string;\n disks: Array<{\n type: string;\n sizeGb: number;\n boot?: boolean;\n }>;\n networkInterfaces: Array<{\n network: string;\n subnetwork?: string;\n }>;\n serviceAccounts?: Array<{\n email: string;\n scopes: string[];\n }>;\n}\n\nexport interface GCPStorageBucket extends StorageResource {\n bucketName: string;\n location: string;\n storageClass: string;\n versioning?: boolean;\n lifecycle?: any;\n cors?: any[];\n}\n\nexport interface GCPCloudSQLInstance extends DatabaseResource {\n instanceId: string;\n databaseVersion: string;\n tier: string;\n diskSizeGb: number;\n diskType: string;\n ipAddresses: Array<{\n type: string;\n ipAddress: string;\n }>;\n backupConfiguration?: any;\n maintenanceWindow?: any;\n}\n\nexport interface GCPCloudFunction extends ResourceBase {\n functionName: string;\n runtime: string;\n entryPoint: string;\n sourceArchiveUrl?: string;\n httpsTrigger?: any;\n eventTrigger?: any;\n timeout?: string;\n availableMemoryMb?: number;\n}\n\nexport interface GCPGKECluster extends ResourceBase {\n clusterName: string;\n zone?: string;\n location: string;\n nodeCount: number;\n currentMasterVersion: string;\n currentNodeVersion: string;\n network?: string;\n subnetwork?: string;\n nodePools?: Array<{\n name: string;\n nodeCount: number;\n config: any;\n }>;\n}\n\n// Azure Resource Types\nexport interface AzureVirtualMachine extends ComputeResource {\n resourceId: string;\n vmSize: string;\n osType: string;\n imageReference: {\n publisher: string;\n offer: string;\n sku: string;\n version: string;\n };\n osDisk: {\n osType: string;\n diskSizeGB: number;\n managedDisk: {\n storageAccountType: string;\n };\n };\n networkProfile: {\n networkInterfaces: Array<{\n id: string;\n }>;\n };\n}\n\nexport interface AzureStorageAccount extends StorageResource {\n accountName: string;\n kind: string;\n tier: string;\n replicationType: string;\n accessTier: string;\n encryption: {\n services: {\n blob: { enabled: boolean };\n file: { enabled: boolean };\n };\n };\n}\n\nexport interface AzureSQLDatabase extends DatabaseResource {\n databaseId: string;\n serverName: string;\n edition: string;\n serviceObjective: string;\n collation: string;\n maxSizeBytes: number;\n status: string;\n elasticPoolName?: string;\n}\n\nexport interface AzureFunctionApp extends ResourceBase {\n functionAppName: string;\n kind: string;\n runtime: string;\n runtimeVersion: string;\n hostingPlan: {\n name: string;\n tier: string;\n };\n}\n\nexport interface AzureAKSCluster extends ResourceBase {\n clusterName: string;\n kubernetesVersion: string;\n nodeCount: number;\n dnsPrefix: string;\n agentPoolProfiles: Array<{\n name: string;\n count: number;\n vmSize: string;\n osType: string;\n osDiskSizeGB: number;\n }>;\n networkProfile: {\n networkPlugin: string;\n serviceCidr: string;\n dnsServiceIP: string;\n };\n}\n\nexport interface AzureVirtualNetwork extends ResourceBase {\n vnetName: string;\n addressSpace: {\n addressPrefixes: string[];\n };\n subnets: Array<{\n name: string;\n addressPrefix: string;\n }>;\n}\n\n// Alibaba Cloud Resource Types\nexport interface AlibabaECSInstance extends ComputeResource {\n instanceId: string;\n instanceName?: string;\n imageId: string;\n instanceType: string;\n vpcAttributes?: {\n vpcId: string;\n vswitchId: string;\n privateIpAddress: string;\n };\n publicIpAddress?: string;\n internetChargeType?: string;\n securityGroupIds: string[];\n zoneId: string;\n}\n\nexport interface AlibabaOSSBucket extends StorageResource {\n bucketName: string;\n location: string;\n storageClass: string;\n dataRedundancyType?: string;\n accessControlList?: string;\n serverSideEncryption?: string;\n versioning?: string;\n}\n\nexport interface AlibabaRDSInstance extends DatabaseResource {\n dbInstanceId: string;\n dbInstanceDescription?: string;\n payType: string;\n dbInstanceType: string;\n engine: string;\n engineVersion: string;\n dbInstanceClass: string;\n dbInstanceStorage: number;\n vpcId?: string;\n vswitchId?: string;\n connectionString?: string;\n}\n\nexport interface AlibabaVPC extends ResourceBase {\n vpcId: string;\n vpcName?: string;\n cidrBlock: string;\n isDefault: boolean;\n routerTableIds: string[];\n vswitchIds: string[];\n description?: string;\n}\n\n// Oracle Cloud Resource Types\nexport interface OracleComputeInstance extends ComputeResource {\n instanceId: string;\n displayName: string;\n availabilityDomain: string;\n compartmentId: string;\n shape: string;\n shapeConfig?: {\n ocpus: number;\n memoryInGBs: number;\n };\n imageId: string;\n subnetId: string;\n publicIp?: string;\n privateIp?: string;\n}\n\nexport interface OracleObjectStorageBucket extends StorageResource {\n bucketName: string;\n namespace: string;\n compartmentId: string;\n publicAccessType?: string;\n approximateCount?: number;\n approximateSize?: number;\n etag: string;\n kmsKeyId?: string;\n objectEventsEnabled?: boolean;\n}\n\nexport interface OracleAutonomousDatabase extends DatabaseResource {\n id: string;\n displayName: string;\n compartmentId: string;\n dbWorkload: string;\n isAutoScalingEnabled: boolean;\n cpuCoreCount: number;\n dataStorageSizeInTBs: number;\n connectionStrings?: any;\n licenseModel: string;\n isPreview?: boolean;\n}\n\nexport interface OracleVCN extends ResourceBase {\n vcnId: string;\n displayName: string;\n compartmentId: string;\n cidrBlocks: string[];\n defaultDhcpOptionsId: string;\n defaultRouteTableId: string;\n defaultSecurityListId: string;\n dnsLabel?: string;\n}\n\n// Cloud Resource Inventory\nexport interface ResourceInventory {\n provider: CloudProvider;\n region: string;\n totalResources: number;\n resourcesByType: Record<ResourceType, number>;\n totalCost: number;\n resources: {\n compute: ComputeResource[];\n storage: StorageResource[];\n database: DatabaseResource[];\n network: NetworkResource[];\n [key: string]: ResourceBase[];\n };\n lastUpdated: Date;\n}\n\nexport interface InventoryFilters {\n provider?: CloudProvider;\n regions?: string[];\n resourceTypes?: ResourceType[];\n tags?: Record<string, string>;\n includeDeleted?: boolean;\n includeCosts?: boolean;\n}\n\nexport interface InventoryExportOptions {\n format: 'json' | 'csv' | 'xlsx';\n includeMetadata?: boolean;\n includeCosts?: boolean;\n groupByProvider?: boolean;\n groupByRegion?: boolean;\n}\n\n// Budget and Alerts Types\nexport interface BudgetInfo {\n budgetName: string;\n budgetLimit: number;\n actualSpend: number;\n forecastedSpend?: number;\n timeUnit: 'MONTHLY' | 'QUARTERLY' | 'ANNUALLY';\n timePeriod: {\n start: string;\n end: string;\n };\n budgetType: 'COST' | 'USAGE';\n status: 'OK' | 'ALARM' | 'FORECASTED_ALARM';\n thresholds: BudgetThreshold[];\n costFilters?: {\n services?: string[];\n tags?: Record<string, string[]>;\n linkedAccounts?: string[];\n };\n}\n\nexport interface BudgetThreshold {\n threshold: number;\n thresholdType: 'PERCENTAGE' | 'ABSOLUTE_VALUE';\n comparisonOperator: 'GREATER_THAN' | 'LESS_THAN' | 'EQUAL_TO';\n notificationType: 'ACTUAL' | 'FORECASTED';\n}\n\nexport interface BudgetAlert {\n budgetName: string;\n alertType: 'THRESHOLD_EXCEEDED' | 'FORECAST_EXCEEDED';\n currentSpend: number;\n budgetLimit: number;\n threshold: number;\n percentageUsed: number;\n timeRemaining: string;\n severity: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';\n message: string;\n}\n\nexport interface TrendData {\n period: string;\n actualCost: number;\n forecastedCost?: number;\n budgetLimit?: number;\n previousPeriodCost?: number;\n changeFromPrevious: {\n amount: number;\n percentage: number;\n };\n}\n\nexport interface CostTrendAnalysis {\n provider?: CloudProvider;\n timeRange?: {\n start: string;\n end: string;\n };\n granularity?: 'DAILY' | 'WEEKLY' | 'MONTHLY';\n trendData?: TrendData[];\n totalCost: number;\n averageDailyCost: number;\n projectedMonthlyCost: number;\n avgMonthOverMonthGrowth?: number;\n topServices?: Array<{\n serviceName: string;\n cost: number;\n percentage: number;\n trend: 'INCREASING' | 'DECREASING' | 'STABLE';\n }>;\n costAnomalies: Array<{\n date: string;\n actualCost?: number;\n expectedCost?: number;\n deviation: number;\n severity: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';\n possibleCause?: string;\n description?: string;\n }>;\n monthlyBreakdown?: Array<{\n month: string;\n cost: number;\n services: Record<string, number>;\n }>;\n serviceTrends?: Record<string, {\n currentCost: number;\n growthRate: number;\n trend: 'increasing' | 'decreasing' | 'stable';\n }>;\n forecastAccuracy?: number;\n analytics?: {\n insights: string[];\n recommendations: string[];\n volatilityScore: number;\n trendStrength: number;\n };\n}\n\nexport interface FinOpsRecommendation {\n id: string;\n type: 'COST_OPTIMIZATION' | 'RESOURCE_RIGHTSIZING' | 'RESERVED_CAPACITY' | 'ARCHITECTURE';\n title: string;\n description: string;\n potentialSavings: {\n amount: number;\n percentage: number;\n timeframe: 'MONTHLY' | 'ANNUALLY';\n };\n effort: 'LOW' | 'MEDIUM' | 'HIGH';\n priority: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';\n resources?: string[];\n implementationSteps: string[];\n tags: string[];\n}","import { CostExplorerClient, GetCostAndUsageCommand } from '@aws-sdk/client-cost-explorer';\nimport { IAMClient, ListAccountAliasesCommand } from '@aws-sdk/client-iam';\nimport { STSClient, GetCallerIdentityCommand } from '@aws-sdk/client-sts';\nimport { EC2Client, DescribeInstancesCommand, DescribeVolumesCommand, DescribeVpcsCommand, DescribeSubnetsCommand } from '@aws-sdk/client-ec2';\nimport { S3Client, ListBucketsCommand } from '@aws-sdk/client-s3';\nimport { RDSClient, DescribeDBInstancesCommand } from '@aws-sdk/client-rds';\nimport { LambdaClient, ListFunctionsCommand } from '@aws-sdk/client-lambda';\nimport { BudgetsClient, DescribeBudgetsCommand, DescribeBudgetCommand } from '@aws-sdk/client-budgets';\nimport dayjs from 'dayjs';\nimport {\n CloudProviderAdapter,\n ProviderConfig,\n AccountInfo,\n RawCostData,\n CostBreakdown,\n CloudProvider,\n ResourceInventory,\n InventoryFilters,\n ResourceType,\n AWSEC2Instance,\n AWSS3Bucket,\n AWSRDSInstance,\n AWSLambdaFunction,\n AWSVPC,\n AWSSubnet,\n AWSEBSVolume,\n BudgetInfo,\n BudgetAlert,\n CostTrendAnalysis,\n FinOpsRecommendation,\n TrendData,\n BudgetThreshold\n} from '../types/providers';\nimport type { AwsCredentialIdentityProvider } from \"@aws-sdk/types\";\nimport { showSpinner } from '../logger';\nimport { CostAnalyticsEngine, DataPoint, Anomaly } from '../analytics/anomaly-detector';\n\nexport class AWSProvider extends CloudProviderAdapter {\n constructor(config: ProviderConfig) {\n super(config);\n }\n\n private getCredentials(): AwsCredentialIdentityProvider {\n return this.config.credentials as AwsCredentialIdentityProvider;\n }\n\n private getRegion(): string {\n return this.config.region || 'us-east-1';\n }\n\n async validateCredentials(): Promise<boolean> {\n try {\n const sts = new STSClient({\n credentials: this.getCredentials(),\n region: this.getRegion()\n });\n await sts.send(new GetCallerIdentityCommand({}));\n return true;\n } catch {\n return false;\n }\n }\n\n async getAccountInfo(): Promise<AccountInfo> {\n showSpinner('Getting AWS account information');\n\n try {\n const iam = new IAMClient({\n credentials: this.getCredentials(),\n region: this.getRegion()\n });\n\n const accountAliases = await iam.send(new ListAccountAliasesCommand({}));\n const foundAlias = accountAliases?.AccountAliases?.[0];\n\n if (foundAlias) {\n return {\n id: foundAlias,\n name: foundAlias,\n provider: CloudProvider.AWS\n };\n }\n\n const sts = new STSClient({\n credentials: this.getCredentials(),\n region: this.getRegion()\n });\n const accountInfo = await sts.send(new GetCallerIdentityCommand({}));\n\n return {\n id: accountInfo.Account || 'unknown',\n name: accountInfo.Account || 'unknown',\n provider: CloudProvider.AWS\n };\n } catch (error) {\n throw new Error(`Failed to get AWS account information: ${error.message}`);\n }\n }\n\n async getRawCostData(): Promise<RawCostData> {\n showSpinner('Getting AWS pricing data');\n\n try {\n const costExplorer = new CostExplorerClient({\n credentials: this.getCredentials(),\n region: this.getRegion()\n });\n const endDate = dayjs().subtract(1, 'day');\n const startDate = endDate.subtract(65, 'day');\n\n const pricingData = await costExplorer.send(new GetCostAndUsageCommand({\n TimePeriod: {\n Start: startDate.format('YYYY-MM-DD'),\n End: endDate.format('YYYY-MM-DD'),\n },\n Granularity: 'DAILY',\n Filter: {\n Not: {\n Dimensions: {\n Key: 'RECORD_TYPE',\n Values: ['Credit', 'Refund', 'Upfront', 'Support'],\n },\n },\n },\n Metrics: ['UnblendedCost'],\n GroupBy: [\n {\n Type: 'DIMENSION',\n Key: 'SERVICE',\n },\n ],\n }));\n\n const costByService: RawCostData = {};\n\n for (const day of pricingData.ResultsByTime || []) {\n for (const group of day.Groups || []) {\n const serviceName = group.Keys?.[0];\n const cost = group.Metrics?.UnblendedCost?.Amount;\n const costDate = day.TimePeriod?.End;\n\n if (serviceName && cost && costDate) {\n costByService[serviceName] = costByService[serviceName] || {};\n costByService[serviceName][costDate] = parseFloat(cost);\n }\n }\n }\n\n return costByService;\n } catch (error) {\n throw new Error(`Failed to get AWS cost data: ${error.message}`);\n }\n }\n\n async getCostBreakdown(): Promise<CostBreakdown> {\n const rawCostData = await this.getRawCostData();\n return this.calculateServiceTotals(rawCostData);\n }\n\n async getResourceInventory(filters?: InventoryFilters): Promise<ResourceInventory> {\n showSpinner('Discovering AWS resources');\n\n const regions = filters?.regions || [this.config.region || 'us-east-1'];\n const resourceTypes = filters?.resourceTypes || Object.values(ResourceType);\n const includeCosts = filters?.includeCosts || false;\n\n const inventory: ResourceInventory = {\n provider: CloudProvider.AWS,\n region: regions.join(', '),\n totalResources: 0,\n resourcesByType: {\n [ResourceType.COMPUTE]: 0,\n [ResourceType.STORAGE]: 0,\n [ResourceType.DATABASE]: 0,\n [ResourceType.NETWORK]: 0,\n [ResourceType.SECURITY]: 0,\n [ResourceType.SERVERLESS]: 0,\n [ResourceType.CONTAINER]: 0,\n [ResourceType.ANALYTICS]: 0\n },\n totalCost: 0,\n resources: {\n compute: [],\n storage: [],\n database: [],\n network: [],\n security: [],\n serverless: [],\n container: [],\n analytics: []\n },\n lastUpdated: new Date()\n };\n\n for (const region of regions) {\n try {\n // Discover compute resources (EC2)\n if (resourceTypes.includes(ResourceType.COMPUTE)) {\n const ec2Resources = await this.discoverEC2Instances(region, includeCosts);\n inventory.resources.compute.push(...ec2Resources);\n inventory.resourcesByType[ResourceType.COMPUTE] += ec2Resources.length;\n }\n\n // Discover storage resources (S3, EBS)\n if (resourceTypes.includes(ResourceType.STORAGE)) {\n const s3Resources = await this.discoverS3Buckets(region, includeCosts);\n const ebsResources = await this.discoverEBSVolumes(region, includeCosts);\n inventory.resources.storage.push(...s3Resources, ...ebsResources);\n inventory.resourcesByType[ResourceType.STORAGE] += s3Resources.length + ebsResources.length;\n }\n\n // Discover database resources (RDS)\n if (resourceTypes.includes(ResourceType.DATABASE)) {\n const rdsResources = await this.discoverRDSInstances(region, includeCosts);\n inventory.resources.database.push(...rdsResources);\n inventory.resourcesByType[ResourceType.DATABASE] += rdsResources.length;\n }\n\n // Discover serverless resources (Lambda)\n if (resourceTypes.includes(ResourceType.SERVERLESS)) {\n const lambdaResources = await this.discoverLambdaFunctions(region, includeCosts);\n inventory.resources.serverless.push(...lambdaResources);\n inventory.resourcesByType[ResourceType.SERVERLESS] += lambdaResources.length;\n }\n\n // Discover network resources (VPC, Subnets)\n if (resourceTypes.includes(ResourceType.NETWORK)) {\n const vpcResources = await this.discoverVPCs(region, includeCosts);\n const subnetResources = await this.discoverSubnets(region, includeCosts);\n inventory.resources.network.push(...vpcResources, ...subnetResources);\n inventory.resourcesByType[ResourceType.NETWORK] += vpcResources.length + subnetResources.length;\n }\n } catch (error) {\n console.warn(`Failed to discover resources in region ${region}: ${error.message}`);\n }\n }\n\n // Calculate totals\n inventory.totalResources = Object.values(inventory.resourcesByType).reduce((sum, count) => sum + count, 0);\n\n if (includeCosts) {\n inventory.totalCost = Object.values(inventory.resources)\n .flat()\n .reduce((sum, resource) => sum + (resource.costToDate || 0), 0);\n }\n\n return inventory;\n }\n\n private async discoverEC2Instances(region: string, includeCosts: boolean): Promise<AWSEC2Instance[]> {\n try {\n const ec2Client = new EC2Client({\n credentials: this.getCredentials(),\n region\n });\n\n const command = new DescribeInstancesCommand({});\n const result = await ec2Client.send(command);\n\n const instances: AWSEC2Instance[] = [];\n\n for (const reservation of result.Reservations || []) {\n for (const instance of reservation.Instances || []) {\n const ec2Instance: AWSEC2Instance = {\n id: instance.InstanceId || '',\n name: instance.Tags?.find(tag => tag.Key === 'Name')?.Value || instance.InstanceId || '',\n state: instance.State?.Name || 'unknown',\n region,\n tags: instance.Tags?.reduce((acc, tag) => {\n if (tag.Key && tag.Value) acc[tag.Key] = tag.Value;\n return acc;\n }, {} as Record<string, string>),\n createdAt: instance.LaunchTime || new Date(),\n provider: CloudProvider.AWS,\n instanceType: instance.InstanceType,\n cpu: this.getCpuCountForInstanceType(instance.InstanceType),\n memory: this.getMemoryForInstanceType(instance.InstanceType),\n platform: instance.Platform || 'linux',\n instanceId: instance.InstanceId || '',\n imageId: instance.ImageId || '',\n keyName: instance.KeyName,\n securityGroups: instance.SecurityGroups?.map(sg => sg.GroupId || '') || [],\n subnetId: instance.SubnetId || '',\n vpcId: instance.VpcId || '',\n publicDnsName: instance.PublicDnsName,\n privateDnsName: instance.PrivateDnsName,\n monitoring: instance.Monitoring?.State === 'enabled',\n placement: {\n availabilityZone: instance.Placement?.AvailabilityZone || '',\n groupName: instance.Placement?.GroupName\n },\n publicIp: instance.PublicIpAddress,\n privateIp: instance.PrivateIpAddress\n };\n\n if (includeCosts) {\n ec2Instance.costToDate = await this.getResourceCosts(instance.InstanceId || '');\n }\n\n instances.push(ec2Instance);\n }\n }\n\n return instances;\n } catch (error) {\n console.warn(`Failed to discover EC2 instances in ${region}: ${error.message}`);\n return [];\n }\n }\n\n private async discoverS3Buckets(region: string, includeCosts: boolean): Promise<AWSS3Bucket[]> {\n try {\n const s3Client = new S3Client({\n credentials: this.getCredentials(),\n region\n });\n\n const command = new ListBucketsCommand({});\n const result = await s3Client.send(command);\n\n const buckets: AWSS3Bucket[] = [];\n\n for (const bucket of result.Buckets || []) {\n if (!bucket.Name) continue;\n\n const s3Bucket: AWSS3Bucket = {\n id: bucket.Name,\n name: bucket.Name,\n state: 'active',\n region,\n createdAt: bucket.CreationDate || new Date(),\n provider: CloudProvider.AWS,\n sizeGB: 0, // Would need additional API calls to get actual size\n storageType: 'S3',\n bucketName: bucket.Name\n };\n\n if (includeCosts) {\n s3Bucket.costToDate = await this.getResourceCosts(bucket.Name);\n }\n\n buckets.push(s3Bucket);\n }\n\n return buckets;\n } catch (error) {\n console.warn(`Failed to discover S3 buckets: ${error.message}`);\n return [];\n }\n }\n\n private async discoverEBSVolumes(region: string, includeCosts: boolean): Promise<AWSEBSVolume[]> {\n try {\n const ec2Client = new EC2Client({\n credentials: this.getCredentials(),\n region\n });\n\n const command = new DescribeVolumesCommand({});\n const result = await ec2Client.send(command);\n\n const volumes: AWSEBSVolume[] = [];\n\n for (const volume of result.Volumes || []) {\n if (!volume.VolumeId) continue;\n\n const ebsVolume: AWSEBSVolume = {\n id: volume.VolumeId,\n name: volume.Tags?.find(tag => tag.Key === 'Name')?.Value || volume.VolumeId,\n state: volume.State || 'unknown',\n region,\n tags: volume.Tags?.reduce((acc, tag) => {\n if (tag.Key && tag.Value) acc[tag.Key] = tag.Value;\n return acc;\n }, {} as Record<string, string>),\n createdAt: volume.CreateTime || new Date(),\n provider: CloudProvider.AWS,\n sizeGB: volume.Size || 0,\n storageType: volume.VolumeType || 'gp2',\n encrypted: volume.Encrypted,\n volumeId: volume.VolumeId,\n volumeType: volume.VolumeType || 'gp2',\n iops: volume.Iops,\n throughput: volume.Throughput,\n attachments: volume.Attachments?.map(attachment => ({\n instanceId: attachment.InstanceId || '',\n device: attachment.Device || ''\n })),\n snapshotId: volume.SnapshotId\n };\n\n if (includeCosts) {\n ebsVolume.costToDate = await this.getResourceCosts(volume.VolumeId);\n }\n\n volumes.push(ebsVolume);\n }\n\n return volumes;\n } catch (error) {\n console.warn(`Failed to discover EBS volumes in ${region}: ${error.message}`);\n return [];\n }\n }\n\n private async discoverRDSInstances(region: string, includeCosts: boolean): Promise<AWSRDSInstance[]> {\n try {\n const rdsClient = new RDSClient({\n credentials: this.getCredentials(),\n region\n });\n\n const command = new DescribeDBInstancesCommand({});\n const result = await rdsClient.send(command);\n\n const instances: AWSRDSInstance[] = [];\n\n for (const dbInstance of result.DBInstances || []) {\n if (!dbInstance.DBInstanceIdentifier) continue;\n\n const rdsInstance: AWSRDSInstance = {\n id: dbInstance.DBInstanceIdentifier,\n name: dbInstance.DBName || dbInstance.DBInstanceIdentifier,\n state: dbInstance.DBInstanceStatus || 'unknown',\n region,\n createdAt: dbInstance.InstanceCreateTime || new Date(),\n provider: CloudProvider.AWS,\n engine: dbInstance.Engine || '',\n version: dbInstance.EngineVersion || '',\n instanceClass: dbInstance.DBInstanceClass,\n storageGB: dbInstance.AllocatedStorage,\n multiAZ: dbInstance.MultiAZ,\n dbInstanceIdentifier: dbInstance.DBInstanceIdentifier,\n dbName: dbInstance.DBName,\n masterUsername: dbInstance.MasterUsername || '',\n endpoint: dbInstance.Endpoint?.Address,\n port: dbInstance.Endpoint?.Port,\n availabilityZone: dbInstance.AvailabilityZone,\n backupRetentionPeriod: dbInstance.BackupRetentionPeriod,\n storageEncrypted: dbInstance.StorageEncrypted\n };\n\n if (includeCosts) {\n rdsInstance.costToDate = await this.getResourceCosts(dbInstance.DBInstanceIdentifier);\n }\n\n instances.push(rdsInstance);\n }\n\n return instances;\n } catch (error) {\n console.warn(`Failed to discover RDS instances in ${region}: ${error.message}`);\n return [];\n }\n }\n\n private async discoverLambdaFunctions(region: string, includeCosts: boolean): Promise<AWSLambdaFunction[]> {\n try {\n const lambdaClient = new LambdaClient({\n credentials: this.getCredentials(),\n region\n });\n\n const command = new ListFunctionsCommand({});\n const result = await lambdaClient.send(command);\n\n const functions: AWSLambdaFunction[] = [];\n\n for (const func of result.Functions || []) {\n if (!func.FunctionName) continue;\n\n const lambdaFunction: AWSLambdaFunction = {\n id: func.FunctionArn || func.FunctionName,\n name: func.FunctionName,\n state: func.State || 'unknown',\n region,\n createdAt: new Date(), // Lambda doesn't provide creation time in list\n provider: CloudProvider.AWS,\n functionName: func.FunctionName,\n runtime: func.Runtime || '',\n handler: func.Handler || '',\n codeSize: func.CodeSize || 0,\n timeout: func.Timeout || 0,\n memorySize: func.MemorySize || 0,\n lastModified: new Date(func.LastModified || ''),\n version: func.Version || ''\n };\n\n if (includeCosts) {\n lambdaFunction.costToDate = await this.getResourceCosts(func.FunctionName);\n }\n\n functions.push(lambdaFunction);\n }\n\n return functions;\n } catch (error) {\n console.warn(`Failed to discover Lambda functions in ${region}: ${error.message}`);\n return [];\n }\n }\n\n private async discoverVPCs(region: string, includeCosts: boolean): Promise<AWSVPC[]> {\n try {\n const ec2Client = new EC2Client({\n credentials: this.getCredentials(),\n region\n });\n\n const command = new DescribeVpcsCommand({});\n const result = await ec2Client.send(command);\n\n const vpcs: AWSVPC[] = [];\n\n for (const vpc of result.Vpcs || []) {\n if (!vpc.VpcId) continue;\n\n const awsVpc: AWSVPC = {\n id: vpc.VpcId,\n name: vpc.Tags?.find(tag => tag.Key === 'Name')?.Value || vpc.VpcId,\n state: vpc.State || 'unknown',\n region,\n tags: vpc.Tags?.reduce((acc, tag) => {\n if (tag.Key && tag.Value) acc[tag.Key] = tag.Value;\n return acc;\n }, {} as Record<string, string>),\n createdAt: new Date(), // VPC doesn't provide creation time\n provider: CloudProvider.AWS,\n vpcId: vpc.VpcId,\n cidrBlock: vpc.CidrBlock || '',\n dhcpOptionsId: vpc.DhcpOptionsId || '',\n isDefault: vpc.IsDefault || false\n };\n\n if (includeCosts) {\n awsVpc.costToDate = await this.getResourceCosts(vpc.VpcId);\n }\n\n vpcs.push(awsVpc);\n }\n\n return vpcs;\n } catch (error) {\n console.warn(`Failed to discover VPCs in ${region}: ${error.message}`);\n return [];\n }\n }\n\n private async discoverSubnets(region: string, includeCosts: boolean): Promise<AWSSubnet[]> {\n try {\n const ec2Client = new EC2Client({\n credentials: this.getCredentials(),\n region\n });\n\n const command = new DescribeSubnetsCommand({});\n const result = await ec2Client.send(command);\n\n const subnets: AWSSubnet[] = [];\n\n for (const subnet of result.Subnets || []) {\n if (!subnet.SubnetId) continue;\n\n const awsSubnet: AWSSubnet = {\n id: subnet.SubnetId,\n name: subnet.Tags?.find(tag => tag.Key === 'Name')?.Value || subnet.SubnetId,\n state: subnet.State || 'unknown',\n region,\n tags: subnet.Tags?.reduce((acc, tag) => {\n if (tag.Key && tag.Value) acc[tag.Key] = tag.Value;\n return acc;\n }, {} as Record<string, string>),\n createdAt: new Date(), // Subnet doesn't provide creation time\n provider: CloudProvider.AWS,\n subnetId: subnet.SubnetId,\n vpcId: subnet.VpcId || '',\n cidrBlock: subnet.CidrBlock || '',\n availableIpAddressCount: subnet.AvailableIpAddressCount || 0,\n availabilityZone: subnet.AvailabilityZone || '',\n mapPublicIpOnLaunch: subnet.MapPublicIpOnLaunch || false\n };\n\n if (includeCosts) {\n awsSubnet.costToDate = await this.getResourceCosts(subnet.SubnetId);\n }\n\n subnets.push(awsSubnet);\n }\n\n return subnets;\n } catch (error) {\n console.warn(`Failed to discover Subnets in ${region}: ${error.message}`);\n return [];\n }\n }\n\n async getResourceCosts(resourceId: string): Promise<number> {\n // Placeholder implementation - would need to map resource IDs to cost data\n // This could be implemented by correlating with cost and usage reports\n return 0;\n }\n\n async getOptimizationRecommendations(): Promise<string[]> {\n const recommendations: string[] = [];\n\n try {\n // Placeholder recommendations - in a real implementation, this would analyze\n // resource usage patterns, costs, and best practices\n recommendations.push(\n 'Consider using Reserved Instances for long-running EC2 instances to save up to 72%',\n 'Enable S3 Intelligent Tiering for automatic cost optimization',\n 'Review underutilized RDS instances and consider right-sizing',\n 'Implement lifecycle policies for EBS snapshots older than 30 days',\n 'Consider using Spot Instances for fault-tolerant workloads'\n );\n } catch (error) {\n console.warn(`Failed to generate optimization recommendations: ${error.message}`);\n }\n\n return recommendations;\n }\n\n async getBudgets(): Promise<BudgetInfo[]> {\n showSpinner('Getting AWS budgets');\n\n try {\n const budgetsClient = new BudgetsClient({\n credentials: this.getCredentials(),\n region: this.getRegion()\n });\n\n // Get account ID for budgets API\n const sts = new STSClient({\n credentials: this.getCredentials(),\n region: this.getRegion()\n });\n const accountInfo = await sts.send(new GetCallerIdentityCommand({}));\n const accountId = accountInfo.Account;\n\n if (!accountId) {\n throw new Error('Unable to determine AWS account ID');\n }\n\n const budgetsResponse = await budgetsClient.send(new DescribeBudgetsCommand({\n AccountId: accountId\n }));\n\n const budgets: BudgetInfo[] = [];\n\n for (const budget of budgetsResponse.Budgets || []) {\n if (!budget.BudgetName || !budget.BudgetLimit) continue;\n\n const budgetInfo: BudgetInfo = {\n budgetName: budget.BudgetName,\n budgetLimit: parseFloat(budget.BudgetLimit.Amount || '0'),\n actualSpend: parseFloat(budget.CalculatedSpend?.ActualSpend?.Amount || '0'),\n forecastedSpend: parseFloat(budget.CalculatedSpend?.ForecastedSpend?.Amount || '0'),\n timeUnit: (budget.TimeUnit as 'MONTHLY' | 'QUARTERLY' | 'ANNUALLY') || 'MONTHLY',\n timePeriod: {\n start: typeof budget.TimePeriod?.Start === 'string'\n ? budget.TimePeriod?.Start\n : budget.TimePeriod?.Start instanceof Date\n ? budget.TimePeriod?.Start.toISOString()\n : '',\n end: typeof budget.TimePeriod?.End === 'string'\n ? budget.TimePeriod?.End\n : budget.TimePeriod?.End instanceof Date\n ? budget.TimePeriod?.End.toISOString()\n : ''\n },\n budgetType: (budget.BudgetType as 'COST' | 'USAGE') || 'COST',\n status: this.determineBudgetStatus(budget),\n thresholds: this.parseBudgetThresholds(budget),\n costFilters: this.parseCostFilters(budget)\n };\n\n budgets.push(budgetInfo);\n }\n\n return budgets;\n } catch (error) {\n console.warn(`Failed to get AWS budgets: ${error.message}`);\n return [];\n }\n }\n\n async getBudgetAlerts(): Promise<BudgetAlert[]> {\n const budgets = await this.getBudgets();\n const alerts: BudgetAlert[] = [];\n\n for (const budget of budgets) {\n const percentageUsed = (budget.actualSpend / budget.budgetLimit) * 100;\n\n // Check each threshold\n for (const threshold of budget.thresholds) {\n let isExceeded = false;\n let currentValue = 0;\n\n if (threshold.thresholdType === 'PERCENTAGE') {\n currentValue = percentageUsed;\n if (threshold.notificationType === 'ACTUAL') {\n isExceeded = percentageUsed >= threshold.threshold;\n } else if (threshold.notificationType === 'FORECASTED' && budget.forecastedSpend) {\n const forecastedPercentage = (budget.forecastedSpend / budget.budgetLimit) * 100;\n isExceeded = forecastedPercentage >= threshold.threshold;\n currentValue = forecastedPercentage;\n }\n } else {\n currentValue = budget.actualSpend;\n if (threshold.notificationType === 'ACTUAL') {\n isExceeded = budget.actualSpend >= threshold.threshold;\n } else if (threshold.notificationType === 'FORECASTED' && budget.forecastedSpend) {\n isExceeded = budget.forecastedSpend >= threshold.threshold;\n currentValue = budget.forecastedSpend;\n }\n }\n\n if (isExceeded) {\n const alert: BudgetAlert = {\n budgetName: budget.budgetName,\n alertType: threshold.notificationType === 'FORECASTED' ? 'FORECAST_EXCEEDED' : 'THRESHOLD_EXCEEDED',\n currentSpend: budget.actualSpend,\n budgetLimit: budget.budgetLimit,\n threshold: threshold.threshold,\n percentageUsed,\n timeRemaining: this.calculateTimeRemaining(budget.timePeriod),\n severity: this.determineSeverity(percentageUsed),\n message: this.generateAlertMessage(budget, threshold, percentageUsed)\n };\n alerts.push(alert);\n }\n }\n }\n\n return alerts;\n }\n\n async getCostTrendAnalysis(months: number = 6): Promise<CostTrendAnalysis> {\n showSpinner('Analyzing cost trends');\n\n try {\n const costExplorer = new CostExplorerClient({\n credentials: this.getCredentials(),\n region: this.getRegion()\n });\n\n const endDate = dayjs();\n const startDate = endDate.subtract(months, 'month');\n\n // Get monthly cost data with service breakdown\n const monthlyData = await costExplorer.send(new GetCostAndUsageCommand({\n TimePeriod: {\n Start: startDate.format('YYYY-MM-DD'),\n End: endDate.format('YYYY-MM-DD')\n },\n Granularity: 'MONTHLY',\n Metrics: ['UnblendedCost'],\n GroupBy: [\n {\n Type: 'DIMENSION',\n Key: 'SERVICE'\n }\n ]\n }));\n\n const monthlyCosts: number[] = [];\n const monthlyBreakdown = [];\n const serviceTrends: Record<string, number[]> = {};\n let totalCost = 0;\n\n // Process monthly data\n for (const result of monthlyData.ResultsByTime || []) {\n const period = result.TimePeriod?.Start || '';\n const monthCost = result.Total?.UnblendedCost?.Amount ? parseFloat(result.Total.UnblendedCost.Amount) : 0;\n monthlyCosts.push(monthCost);\n totalCost += monthCost;\n\n // Build service breakdown\n const services: Record<string, number> = {};\n result.Groups?.forEach(group => {\n const serviceName = group.Keys?.[0] || 'Unknown';\n const cost = parseFloat(group.Metrics?.UnblendedCost?.Amount || '0');\n services[serviceName] = cost;\n\n // Track service trends\n if (!serviceTrends[serviceName]) {\n serviceTrends[serviceName] = [];\n }\n serviceTrends[serviceName].push(cost);\n });\n\n monthlyBreakdown.push({\n month: period,\n cost: monthCost,\n services\n });\n }\n\n // Calculate enhanced metrics\n const averageDailyCost = totalCost / (months * 30);\n const projectedMonthlyCost = monthlyCosts.length > 0 ? monthlyCosts[monthlyCosts.length - 1] : averageDailyCost * 30;\n\n // Calculate month-over-month growth rate\n let avgMonthOverMonthGrowth = 0;\n if (monthlyCosts.length > 1) {\n const growthRates = [];\n for (let i = 1; i < monthlyCosts.length; i++) {\n const growth = ((monthlyCosts[i] - monthlyCosts[i - 1]) / monthlyCosts[i - 1]) * 100;\n growthRates.push(growth);\n }\n avgMonthOverMonthGrowth = growthRates.reduce((a, b) => a + b, 0) / growthRates.length;\n }\n\n // Enhanced anomaly detection\n const costAnomalies = [];\n for (let i = 0; i < monthlyCosts.length; i++) {\n const monthCost = monthlyCosts[i];\n const period = monthlyBreakdown[i]?.month || '';\n\n // Month-over-month anomalies\n if (i > 0) {\n const prevMonthCost = monthlyCosts[i - 1];\n const monthOverMonthChange = ((monthCost - prevMonthCost) / prevMonthCost) * 100;\n\n if (Math.abs(monthOverMonthChange) > 25) {\n costAnomalies.push({\n date: period,\n deviation: Math.abs(monthOverMonthChange),\n severity: Math.abs(monthOverMonthChange) > 50 ? 'CRITICAL' : 'HIGH',\n description: `${monthOverMonthChange > 0 ? 'Spike' : 'Drop'} in monthly costs: ${monthOverMonthChange.toFixed(1)}% MoM change`\n });\n }\n }\n\n // Trend-based anomalies\n if (i > 2) {\n const avgOfPrevious = monthlyCosts.slice(0, i).reduce((a, b) => a + b, 0) / i;\n const deviation = ((monthCost - avgOfPrevious) / avgOfPrevious) * 100;\n\n if (Math.abs(deviation) > 30) {\n costAnomalies.push({\n date: period,\n deviation: Math.abs(deviation),\n severity: Math.abs(deviation) > 60 ? 'CRITICAL' : 'MEDIUM',\n description: `Cost ${deviation > 0 ? 'above' : 'below'} ${months}-month average by ${Math.abs(deviation).toFixed(1)}%`\n });\n }\n }\n }\n\n // Calculate service trends\n const serviceAnalysis: Record<string, {\n currentCost: number;\n growthRate: number;\n trend: 'increasing' | 'decreasing' | 'stable';\n }> = {};\n\n Object.entries(serviceTrends).forEach(([service, costs]) => {\n if (costs.length > 1) {\n const currentCost = costs[costs.length - 1];\n const previousCost = costs[costs.length - 2];\n const growthRate = ((currentCost - previousCost) / previousCost) * 100;\n const trend = Math.abs(growthRate) < 5 ? 'stable' :\n growthRate > 0 ? 'increasing' : 'decreasing';\n\n serviceAnalysis[service] = {\n currentCost,\n growthRate,\n trend\n };\n }\n });\n\n // Apply advanced analytics\n const analyticsEngine = new CostAnalyticsEngine({\n sensitivity: 'MEDIUM',\n lookbackPeriods: Math.min(14, monthlyBreakdown.length),\n seasonalityPeriods: 12 // Monthly seasonality\n });\n\n const dataPoints: DataPoint[] = monthlyBreakdown.map(mb => ({\n timestamp: mb.month,\n value: mb.cost\n }));\n\n const analytics = analyticsEngine.analyzeProvider(CloudProvider.AWS, dataPoints);\n\n // Merge advanced anomalies with basic ones\n const enhancedAnomalies = [...costAnomalies];\n analytics.overallAnomalies.forEach(anomaly => {\n enhancedAnomalies.push({\n date: anomaly.timestamp,\n deviation: anomaly.deviationPercentage,\n severity: anomaly.severity,\n description: `${anomaly.description} (${anomaly.confidence.toFixed(0)}% confidence)`\n });\n });\n\n return {\n totalCost,\n averageDailyCost,\n projectedMonthlyCost,\n avgMonthOverMonthGrowth,\n costAnomalies: enhancedAnomalies,\n monthlyBreakdown,\n serviceTrends: serviceAnalysis,\n forecastAccuracy: monthlyCosts.length > 3 ? this.calculateForecastAccuracy(monthlyCosts) : 0,\n analytics: {\n insights: analytics.insights,\n recommendations: analytics.recommendations,\n volatilityScore: this.calculateVolatility(monthlyCosts),\n trendStrength: this.calculateTrendStrength(monthlyCosts)\n }\n };\n } catch (error) {\n console.error('Failed to get AWS cost trend analysis:', error);\n // Return mock data for now\n return this.getMockTrendAnalysis(months);\n }\n }\n\n private calculateForecastAccuracy(monthlyCosts: number[]): number {\n // Simple linear regression forecast accuracy calculation\n if (monthlyCosts.length < 4) return 0;\n\n const n = monthlyCosts.length;\n const lastThreeActual = monthlyCosts.slice(-3);\n const trainData = monthlyCosts.slice(0, -3);\n\n // Calculate simple moving average prediction\n const prediction = trainData.reduce((a, b) => a + b, 0) / trainData.length;\n const actualAvg = lastThreeActual.reduce((a, b) => a + b, 0) / lastThreeActual.length;\n\n const accuracy = Math.max(0, 100 - (Math.abs(prediction - actualAvg) / actualAvg) * 100);\n return Math.round(accuracy);\n }\n\n private getMockTrendAnalysis(months: number): CostTrendAnalysis {\n // Generate enhanced mock data for demonstration\n const monthlyCosts = Array.from({ length: months }, (_, i) => {\n const baseCost = 1500 + (Math.random() * 500); // Random between $1500-2000\n const trend = 1 + (i * 0.02); // Slight upward trend\n const volatility = 0.8 + (Math.random() * 0.4); // Add some volatility\n return baseCost * trend * volatility;\n });\n\n const totalCost = monthlyCosts.reduce((sum, cost) => sum + cost, 0);\n const averageDailyCost = totalCost / (months * 30);\n const projectedMonthlyCost = monthlyCosts[monthlyCosts.length - 1];\n\n // Calculate mock MoM growth\n let avgMonthOverMonthGrowth = 0;\n if (monthlyCosts.length > 1) {\n const growthRates = [];\n for (let i = 1; i < monthlyCosts.length; i++) {\n const growth = ((monthlyCosts[i] - monthlyCosts[i - 1]) / monthlyCosts[i - 1]) * 100;\n growthRates.push(growth);\n }\n avgMonthOverMonthGrowth = growthRates.reduce((a, b) => a + b, 0) / growthRates.length;\n }\n\n const costAnomalies = [];\n // Add some mock anomalies with descriptions\n if (months >= 3) {\n costAnomalies.push({\n date: new Date(Date.now() - 60 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],\n deviation: 35.2,\n severity: 'MEDIUM' as const,\n description: 'Cost spike due to increased EC2 usage during Black Friday traffic'\n });\n costAnomalies.push({\n date: new Date(Date.now() - 90 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],\n deviation: 28.7,\n severity: 'HIGH' as const,\n description: 'Month-over-month increase of 28.7% in data transfer costs'\n });\n }\n\n const mockServices = ['EC2-Instance', 'S3', 'RDS', 'Lambda', 'CloudFront'];\n const monthlyBreakdown = monthlyCosts.map((cost, i) => {\n const date = new Date();\n date.setMonth(date.getMonth() - (months - i - 1));\n\n const services: Record<string, number> = {};\n mockServices.forEach(service => {\n services[service] = cost * (0.1 + Math.random() * 0.3); // Random distribution\n });\n\n return {\n month: date.toISOString().split('T')[0],\n cost,\n services\n };\n });\n\n // Mock service trends\n const serviceTrends: Record<string, {\n currentCost: number;\n growthRate: number;\n trend: 'increasing' | 'decreasing' | 'stable';\n }> = {\n 'EC2-Instance': { currentCost: 850, growthRate: 12.3, trend: 'increasing' },\n 'S3': { currentCost: 125, growthRate: -5.2, trend: 'decreasing' },\n 'RDS': { currentCost: 420, growthRate: 2.1, trend: 'stable' },\n 'Lambda': { currentCost: 45, growthRate: 25.6, trend: 'increasing' },\n 'CloudFront': { currentCost: 78, growthRate: -1.8, trend: 'stable' }\n };\n\n return {\n totalCost,\n averageDailyCost,\n projectedMonthlyCost,\n avgMonthOverMonthGrowth,\n costAnomalies,\n monthlyBreakdown,\n serviceTrends,\n forecastAccuracy: 87\n };\n }\n\n async getFinOpsRecommendations(): Promise<FinOpsRecommendation[]> {\n const recommendations: FinOpsRecommendation[] = [\n {\n id: 'aws-ri-ec2',\n type: 'RESERVED_CAPACITY',\n title: 'Purchase EC2 Reserved Instances',\n description: 'Long-running EC2 instances can benefit from Reserved Instance pricing',\n potentialSavings: {\n amount: 500,\n percentage: 72,\n timeframe: 'MONTHLY'\n },\n effort: 'LOW',\n priority: 'HIGH',\n implementationSteps: [\n 'Analyze EC2 usage patterns over the past 30 days',\n 'Identify instances running >75% of the time',\n 'Purchase 1-year or 3-year Reserved Instances',\n 'Monitor utilization and adjust as needed'\n ],\n tags: ['ec2', 'reserved-instances', 'cost-optimization']\n },\n {\n id: 'aws-s3-lifecycle',\n type: 'COST_OPTIMIZATION',\n title: 'Implement S3 Lifecycle Policies',\n description: 'Automatically transition old S3 data to cheaper storage classes',\n potentialSavings: {\n amount: 150,\n percentage: 40,\n timeframe: 'MONTHLY'\n },\n effort: 'MEDIUM',\n priority: 'MEDIUM',\n implementationSteps: [\n 'Analyze S3 access patterns',\n 'Create lifecycle policies for infrequently accessed data',\n 'Transition to IA after 30 days, Glacier after 90 days',\n 'Enable Intelligent Tiering for dynamic workloads'\n ],\n tags: ['s3', 'lifecycle', 'storage-optimization']\n },\n {\n id: 'aws-rightsizing',\n type: 'RESOURCE_RIGHTSIZING',\n title: 'Right-size Underutilized Resources',\n description: 'Reduce costs by downsizing underutilized EC2 and RDS instances',\n potentialSavings: {\n amount: 300,\n percentage: 25,\n timeframe: 'MONTHLY'\n },\n effort: 'HIGH',\n priority: 'HIGH',\n implementationSteps: [\n 'Enable CloudWatch detailed monitoring',\n 'Analyze CPU, memory, and network utilization',\n 'Identify instances with <40% average utilization',\n 'Plan maintenance windows for resizing',\n 'Test application performance after changes'\n ],\n tags: ['rightsizing', 'ec2', 'rds', 'performance-optimization']\n }\n ];\n\n return recommendations;\n }\n\n // Helper methods for instance types (simplified mapping)\n private getCpuCountForInstanceType(instanceType?: string): number {\n if (!instanceType) return 0;\n const cpuMap: Record<string, number> = {\n 't2.nano': 1, 't2.micro': 1, 't2.small': 1, 't2.medium': 2, 't2.large': 2,\n 'm5.large': 2, 'm5.xlarge': 4, 'm5.2xlarge': 8, 'm5.4xlarge': 16,\n 'c5.large': 2, 'c5.xlarge': 4, 'c5.2xlarge': 8, 'c5.4xlarge': 16\n };\n return cpuMap[instanceType] || 1;\n }\n\n private getMemoryForInstanceType(instanceType?: string): number {\n if (!instanceType) return 0;\n const memoryMap: Record<string, number> = {\n 't2.nano': 0.5, 't2.micro': 1, 't2.small': 2, 't2.medium': 4, 't2.large': 8,\n 'm5.large': 8, 'm5.xlarge': 16, 'm5.2xlarge': 32, 'm5.4xlarge': 64,\n 'c5.large': 4, 'c5.xlarge': 8, 'c5.2xlarge': 16, 'c5.4xlarge': 32\n };\n return memoryMap[instanceType] || 1;\n }\n\n // Helper methods for budget functionality\n private determineBudgetStatus(budget: any): 'OK' | 'ALARM' | 'FORECASTED_ALARM' {\n if (!budget.CalculatedSpend) return 'OK';\n\n const actual = parseFloat(budget.CalculatedSpend.ActualSpend?.Amount || '0');\n const limit = parseFloat(budget.BudgetLimit?.Amount || '0');\n const forecasted = parseFloat(budget.CalculatedSpend.ForecastedSpend?.Amount || '0');\n\n if (actual >= limit) return 'ALARM';\n if (forecasted >= limit) return 'FORECASTED_ALARM';\n return 'OK';\n }\n\n private parseBudgetThresholds(budget: any): BudgetThreshold[] {\n // In a real implementation, this would parse AWS Budget notification thresholds\n // For now, return default thresholds\n return [\n {\n threshold: 80,\n thresholdType: 'PERCENTAGE',\n comparisonOperator: 'GREATER_THAN',\n notificationType: 'ACTUAL'\n },\n {\n threshold: 100,\n thresholdType: 'PERCENTAGE',\n comparisonOperator: 'GREATER_THAN',\n notificationType: 'FORECASTED'\n }\n ];\n }\n\n private parseCostFilters(budget: any): any {\n // In a real implementation, this would parse AWS Budget cost filters\n return budget.CostFilters || {};\n }\n\n private calculateTimeRemaining(timePeriod: { start: string; end: string }): string {\n if (!timePeriod.end) return 'Unknown';\n\n const endDate = dayjs(timePeriod.end);\n const now = dayjs();\n const daysRemaining = endDate.diff(now, 'day');\n\n if (daysRemaining <= 0) return 'Period ended';\n if (daysRemaining === 1) return '1 day';\n return `${daysRemaining} days`;\n }\n\n private determineSeverity(percentageUsed: number): 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL' {\n if (percentageUsed >= 100) return 'CRITICAL';\n if (percentageUsed >= 90) return 'HIGH';\n if (percentageUsed >= 75) return 'MEDIUM';\n return 'LOW';\n }\n\n private generateAlertMessage(budget: BudgetInfo, threshold: BudgetThreshold, percentageUsed: number): string {\n const thresholdType = threshold.thresholdType === 'PERCENTAGE' ? '%' : '$';\n return `Budget \"${budget.budgetName}\" has ${threshold.notificationType.toLowerCase()} ${threshold.threshold}${thresholdType} threshold (currently at ${percentageUsed.toFixed(1)}%)`;\n }\n\n private async getTopServices(startDate: string, endDate: string): Promise<Array<{\n serviceName: string;\n cost: number;\n percentage: number;\n trend: 'INCREASING' | 'DECREASING' | 'STABLE';\n }>> {\n // In a real implementation, this would analyze service costs and trends\n // For now, return mock data\n return [\n {\n serviceName: 'Amazon Elastic Compute Cloud - Compute',\n cost: 1250.45,\n percentage: 45.2,\n trend: 'INCREASING'\n },\n {\n serviceName: 'Amazon Simple Storage Service',\n cost: 680.23,\n percentage: 24.6,\n trend: 'STABLE'\n },\n {\n serviceName: 'Amazon Relational Database Service',\n cost: 445.67,\n percentage: 16.1,\n trend: 'DECREASING'\n }\n ];\n }\n\n private detectCostAnomalies(trendData: TrendData[]): Array<{\n date: string;\n actualCost: number;\n expectedCost: number;\n deviation: number;\n severity: 'LOW' | 'MEDIUM' | 'HIGH';\n possibleCause?: string;\n }> {\n const anomalies: any[] = [];\n\n // Simple anomaly detection based on percentage change\n for (let i = 1; i < trendData.length; i++) {\n const current = trendData[i];\n const changePercentage = Math.abs(current.changeFromPrevious.percentage);\n\n if (changePercentage > 50) {\n anomalies.push({\n date: current.period,\n actualCost: current.actualCost,\n expectedCost: current.actualCost - current.changeFromPrevious.amount,\n deviation: changePercentage,\n severity: changePercentage > 100 ? 'HIGH' : 'MEDIUM',\n possibleCause: changePercentage > 0 ? 'Unexpected cost increase' : 'Significant cost reduction'\n });\n }\n }\n\n return anomalies;\n }\n\n static createFromLegacyConfig(legacyConfig: {\n credentials: {\n accessKeyId: string;\n secretAccessKey: string;\n sessionToken?: string;\n };\n region: string;\n }): AWSProvider {\n const config: ProviderConfig = {\n provider: CloudProvider.AWS,\n credentials: {\n accessKeyId: legacyConfig.credentials.accessKeyId,\n secretAccessKey: legacyConfig.credentials.secretAccessKey,\n sessionToken: legacyConfig.credentials.sessionToken,\n },\n region: legacyConfig.region\n };\n\n return new AWSProvider(config);\n }\n\n private calculateVolatility(values: number[]): number {\n if (values.length < 2) return 0;\n\n const mean = values.reduce((a, b) => a + b, 0) / values.length;\n const variance = values.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / values.length;\n const stdDev = Math.sqrt(variance);\n\n return mean > 0 ? stdDev / mean : 0;\n }\n\n private calculateTrendStrength(values: number[]): number {\n if (values.length < 3) return 0;\n\n // Calculate linear trend strength using R-squared\n const n = values.length;\n const x = Array.from({ length: n }, (_, i) => i);\n const meanX = x.reduce((a, b) => a + b, 0) / n;\n const meanY = values.reduce((a, b) => a + b, 0) / n;\n\n const ssXY = x.reduce((sum, xi, i) => sum + (xi - meanX) * (values[i] - meanY), 0);\n const ssXX = x.reduce((sum, xi) => sum + Math.pow(xi - meanX, 2), 0);\n const ssYY = values.reduce((sum, yi) => sum + Math.pow(yi - meanY, 2), 0);\n\n const correlation = ssXX === 0 || ssYY === 0 ? 0 : ssXY / Math.sqrt(ssXX * ssYY);\n return Math.abs(correlation);\n }\n}","import chalk from 'chalk';\nimport ora, { Ora } from 'ora';\n\nexport function printFatalError(error: string): never {\n console.error(`\n ${chalk.bold.redBright.underline(`Error:`)}\n ${chalk.redBright(`${error}`)}\n `);\n process.exit(1);\n}\n\nlet spinner: Ora | undefined;\n\n/**\n * Shows the spinner with the given text\n * @param text Text to show in the spinner\n */\nexport function showSpinner(text: string) {\n if (!spinner) {\n spinner = ora({ text: '' }).start();\n }\n\n spinner.text = text;\n}\n\n/**\n * Hides the spinner and removes the loading text\n * @returns undefined\n */\nexport function hideSpinner() {\n if (!spinner) {\n return;\n }\n\n spinner.stop();\n}\n","import { CloudProvider } from '../types/providers';\nimport { EventEmitter } from 'events';\nimport { createHash } from 'crypto';\n\nexport interface AnomalyDetectionConfig {\n sensitivity: 'LOW' | 'MEDIUM' | 'HIGH';\n lookbackPeriods: number;\n seasonalityPeriods?: number;\n excludeWeekends?: boolean;\n}\n\nexport interface Anomaly {\n timestamp: string;\n actualValue: number;\n expectedValue: number;\n deviation: number;\n deviationPercentage: number;\n severity: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';\n confidence: number;\n type: 'SPIKE' | 'DROP' | 'TREND_CHANGE' | 'SEASONAL_ANOMALY';\n description: string;\n affectedServices?: string[];\n potentialCauses: string[];\n}\n\nexport interface DataPoint {\n timestamp: string;\n value: number;\n metadata?: Record<string, any>;\n}\n\nexport class AnomalyDetector {\n private config: AnomalyDetectionConfig;\n\n constructor(config: AnomalyDetectionConfig = { sensitivity: 'MEDIUM', lookbackPeriods: 14 }) {\n this.config = config;\n }\n\n /**\n * Detects anomalies using multiple statistical methods\n */\n public detectAnomalies(dataPoints: DataPoint[]): Anomaly[] {\n if (dataPoints.length < this.config.lookbackPeriods) {\n return [];\n }\n\n const anomalies: Anomaly[] = [];\n\n // Apply multiple detection methods\n anomalies.push(...this.detectStatisticalAnomalies(dataPoints));\n anomalies.push(...this.detectTrendAnomalies(dataPoints));\n anomalies.push(...this.detectSeasonalAnomalies(dataPoints));\n\n // Remove duplicates and rank by severity\n return this.consolidateAnomalies(anomalies);\n }\n\n /**\n * Statistical anomaly detection using modified Z-score\n */\n private detectStatisticalAnomalies(dataPoints: DataPoint[]): Anomaly[] {\n const anomalies: Anomaly[] = [];\n const values = dataPoints.map(dp => dp.value);\n\n for (let i = this.config.lookbackPeriods; i < dataPoints.length; i++) {\n const currentValue = values[i];\n const historicalValues = values.slice(i - this.config.lookbackPeriods, i);\n\n const median = this.calculateMedian(historicalValues);\n const mad = this.calculateMAD(historicalValues, median);\n\n // Modified Z-score\n const modifiedZScore = mad === 0 ? 0 : 0.6745 * (currentValue - median) / mad;\n\n const threshold = this.getSensitivityThreshold();\n\n if (Math.abs(modifiedZScore) > threshold) {\n const deviation = currentValue - median;\n const deviationPercentage = median === 0 ? 0 : Math.abs(deviation / median) * 100;\n\n anomalies.push({\n timestamp: dataPoints[i].timestamp,\n actualValue: currentValue,\n expectedValue: median,\n deviation: Math.abs(deviation),\n deviationPercentage,\n severity: this.calculateSeverity(Math.abs(modifiedZScore), threshold),\n confidence: Math.min(95, Math.abs(modifiedZScore) / threshold * 100),\n type: deviation > 0 ? 'SPIKE' : 'DROP',\n description: this.generateAnomalyDescription('STATISTICAL', deviation, deviationPercentage),\n potentialCauses: this.generatePotentialCauses(deviation > 0 ? 'SPIKE' : 'DROP', deviationPercentage)\n });\n }\n }\n\n return anomalies;\n }\n\n /**\n * Trend-based anomaly detection\n */\n private detectTrendAnomalies(dataPoints: DataPoint[]): Anomaly[] {\n const anomalies: Anomaly[] = [];\n const values = dataPoints.map(dp => dp.value);\n\n // Calculate rolling trends\n const trendWindow = Math.min(7, Math.floor(this.config.lookbackPeriods / 2));\n\n for (let i = trendWindow * 2; i < dataPoints.length; i++) {\n const recentTrend = this.calculateLinearTrend(values.slice(i - trendWindow, i));\n const historicalTrend = this.calculateLinearTrend(values.slice(i - trendWindow * 2, i - trendWindow));\n\n const trendChange = Math.abs(recentTrend - historicalTrend);\n const trendChangeThreshold = this.config.sensitivity === 'HIGH' ? 0.1 :\n this.config.sensitivity === 'MEDIUM' ? 0.2 : 0.3;\n\n if (trendChange > trendChangeThreshold) {\n const currentValue = values[i];\n const expectedValue = values[i - 1] + historicalTrend;\n const deviation = Math.abs(currentValue - expectedValue);\n const deviationPercentage = expectedValue === 0 ? 0 : (deviation / expectedValue) * 100;\n\n anomalies.push({\n timestamp: dataPoints[i].timestamp,\n actualValue: currentValue,\n expectedValue,\n deviation,\n deviationPercentage,\n severity: this.calculateSeverity(trendChange, trendChangeThreshold),\n confidence: Math.min(90, trendChange / trendChangeThreshold * 100),\n type: 'TREND_CHANGE',\n description: `Significant trend change detected: ${recentTrend > historicalTrend ? 'acceleration' : 'deceleration'} in cost growth`,\n potentialCauses: this.generatePotentialCauses('TREND_CHANGE', deviationPercentage)\n });\n }\n }\n\n return anomalies;\n }\n\n /**\n * Seasonal anomaly detection\n */\n private detectSeasonalAnomalies(dataPoints: DataPoint[]): Anomaly[] {\n if (!this.config.seasonalityPeriods || dataPoints.length < this.config.seasonalityPeriods * 2) {\n return [];\n }\n\n const anomalies: Anomaly[] = [];\n const values = dataPoints.map(dp => dp.value);\n const seasonalPeriod = this.config.seasonalityPeriods;\n\n for (let i = seasonalPeriod; i < dataPoints.length; i++) {\n const currentValue = values[i];\n const seasonalBaseline = values[i - seasonalPeriod];\n const seasonalDeviation = Math.abs(currentValue - seasonalBaseline);\n const seasonalDeviationPercentage = seasonalBaseline === 0 ? 0 : (seasonalDeviation / seasonalBaseline) * 100;\n\n const threshold = seasonalBaseline * 0.3; // 30% deviation threshold\n\n if (seasonalDeviation > threshold && seasonalDeviationPercentage > 25) {\n anomalies.push({\n timestamp: dataPoints[i].timestamp,\n actualValue: currentValue,\n expectedValue: seasonalBaseline,\n deviation: seasonalDeviation,\n deviationPercentage: seasonalDeviationPercentage,\n severity: this.calculateSeverity(seasonalDeviationPercentage, 25),\n confidence: 80,\n type: 'SEASONAL_ANOMALY',\n description: `Unusual seasonal pattern: ${seasonalDeviationPercentage.toFixed(1)}% deviation from same period last cycle`,\n potentialCauses: this.generatePotentialCauses('SEASONAL_ANOMALY', seasonalDeviationPercentage)\n });\n }\n }\n\n return anomalies;\n }\n\n private calculateMedian(values: number[]): number {\n const sorted = [...values].sort((a, b) => a - b);\n const mid = Math.floor(sorted.length / 2);\n return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];\n }\n\n private calculateMAD(values: number[], median: number): number {\n const deviations = values.map(v => Math.abs(v - median));\n return this.calculateMedian(deviations);\n }\n\n private calculateLinearTrend(values: number[]): number {\n const n = values.length;\n const x = Array.from({ length: n }, (_, i) => i);\n const sumX = x.reduce((a, b) => a + b, 0);\n const sumY = values.reduce((a, b) => a + b, 0);\n const sumXY = x.reduce((sum, xi, i) => sum + xi * values[i], 0);\n const sumXX = x.reduce((sum, xi) => sum + xi * xi, 0);\n\n const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);\n return slope;\n }\n\n private getSensitivityThreshold(): number {\n switch (this.config.sensitivity) {\n case 'HIGH': return 2.5;\n case 'MEDIUM': return 3.5;\n case 'LOW': return 4.5;\n default: return 3.5;\n }\n }\n\n private calculateSeverity(score: number, threshold: number): 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL' {\n const ratio = score / threshold;\n if (ratio > 3) return 'CRITICAL';\n if (ratio > 2) return 'HIGH';\n if (ratio > 1.5) return 'MEDIUM';\n return 'LOW';\n }\n\n private generateAnomalyDescription(type: string, deviation: number, deviationPercentage: number): string {\n const direction = deviation > 0 ? 'increase' : 'decrease';\n const magnitude = deviationPercentage > 100 ? 'massive' :\n deviationPercentage > 50 ? 'significant' :\n deviationPercentage > 25 ? 'notable' : 'minor';\n\n return `${type.toLowerCase()} anomaly detected: ${magnitude} ${direction} of ${deviationPercentage.toFixed(1)}%`;\n }\n\n private generatePotentialCauses(type: string, deviationPercentage: number): string[] {\n const causes: string[] = [];\n\n switch (type) {\n case 'SPIKE':\n causes.push('Increased resource usage or traffic');\n causes.push('New service deployments or scaling events');\n causes.push('Data transfer spikes or storage usage increases');\n if (deviationPercentage > 50) {\n causes.push('Potential security incident or DDoS attack');\n causes.push('Misconfigured auto-scaling rules');\n }\n break;\n\n case 'DROP':\n causes.push('Reduced usage or traffic patterns');\n causes.push('Service shutdowns or downscaling');\n causes.push('Resource optimization implementations');\n if (deviationPercentage > 50) {\n causes.push('Service outages or failures');\n causes.push('Billing or account issues');\n }\n break;\n\n case 'TREND_CHANGE':\n causes.push('Business growth or contraction');\n causes.push('Architectural changes or migrations');\n causes.push('New feature rollouts or service changes');\n causes.push('Seasonal business pattern shifts');\n break;\n\n case 'SEASONAL_ANOMALY':\n causes.push('Unusual business events or promotions');\n causes.push('Holiday pattern deviations');\n causes.push('Market or economic factors');\n causes.push('Competitor actions or market changes');\n break;\n }\n\n return causes;\n }\n\n private consolidateAnomalies(anomalies: Anomaly[]): Anomaly[] {\n // Group anomalies by timestamp and select the highest severity\n const groupedAnomalies = new Map<string, Anomaly[]>();\n\n anomalies.forEach(anomaly => {\n const key = anomaly.timestamp;\n if (!groupedAnomalies.has(key)) {\n groupedAnomalies.set(key, []);\n }\n groupedAnomalies.get(key)!.push(anomaly);\n });\n\n const consolidated: Anomaly[] = [];\n groupedAnomalies.forEach(group => {\n // Sort by severity and confidence, take the best match\n const sorted = group.sort((a, b) => {\n const severityOrder = { 'CRITICAL': 4, 'HIGH': 3, 'MEDIUM': 2, 'LOW': 1 };\n if (severityOrder[a.severity] !== severityOrder[b.severity]) {\n return severityOrder[b.severity] - severityOrder[a.severity];\n }\n return b.confidence - a.confidence;\n });\n\n consolidated.push(sorted[0]);\n });\n\n return consolidated.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());\n }\n}\n\n/**\n * Cost Analytics Engine\n */\nexport class CostAnalyticsEngine {\n private anomalyDetector: AnomalyDetector;\n\n constructor(config?: AnomalyDetectionConfig) {\n this.anomalyDetector = new AnomalyDetector(config);\n }\n\n public analyzeProvider(provider: CloudProvider, costData: DataPoint[], serviceData?: Record<string, DataPoint[]>) {\n const analytics = {\n provider,\n analysisDate: new Date().toISOString(),\n overallAnomalies: this.anomalyDetector.detectAnomalies(costData),\n serviceAnomalies: {} as Record<string, Anomaly[]>,\n insights: this.generateInsights(costData),\n recommendations: this.generateRecommendations(costData)\n };\n\n // Analyze individual services if data is provided\n if (serviceData) {\n Object.entries(serviceData).forEach(([service, data]) => {\n analytics.serviceAnomalies[service] = this.anomalyDetector.detectAnomalies(data);\n });\n }\n\n return analytics;\n }\n\n private generateInsights(costData: DataPoint[]): string[] {\n const insights: string[] = [];\n const values = costData.map(dp => dp.value);\n\n if (values.length < 7) return insights;\n\n // Calculate various metrics\n const latest = values[values.length - 1];\n const weekAgo = values[values.length - 7];\n const monthAgo = values.length > 30 ? values[values.length - 30] : values[0];\n\n const weekGrowth = weekAgo > 0 ? ((latest - weekAgo) / weekAgo) * 100 : 0;\n const monthGrowth = monthAgo > 0 ? ((latest - monthAgo) / monthAgo) * 100 : 0;\n\n if (Math.abs(weekGrowth) > 15) {\n insights.push(`Significant week-over-week cost ${weekGrowth > 0 ? 'increase' : 'decrease'} of ${Math.abs(weekGrowth).toFixed(1)}%`);\n }\n\n if (Math.abs(monthGrowth) > 25) {\n insights.push(`Notable month-over-month cost ${monthGrowth > 0 ? 'growth' : 'reduction'} of ${Math.abs(monthGrowth).toFixed(1)}%`);\n }\n\n // Volatility analysis\n const volatility = this.calculateVolatility(values);\n if (volatility > 0.3) {\n insights.push(`High cost volatility detected (${(volatility * 100).toFixed(1)}%) - consider investigating irregular spending patterns`);\n }\n\n return insights;\n }\n\n private generateRecommendations(costData: DataPoint[]): string[] {\n const recommendations: string[] = [];\n const values = costData.map(dp => dp.value);\n\n const volatility = this.calculateVolatility(values);\n const trend = this.anomalyDetector['calculateLinearTrend'](values.slice(-14));\n\n if (volatility > 0.2) {\n recommendations.push('Implement cost budgets and alerts to better track spending variations');\n recommendations.push('Consider using reserved instances or savings plans for more predictable costs');\n }\n\n if (trend > 0.1) {\n recommendations.push('Cost trend is increasing - review recent resource additions and scaling policies');\n recommendations.push('Consider implementing automated cost optimization tools');\n }\n\n return recommendations;\n }\n\n private calculateVolatility(values: number[]): number {\n if (values.length < 2) return 0;\n\n const mean = values.reduce((a, b) => a + b, 0) / values.length;\n const variance = values.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / values.length;\n const stdDev = Math.sqrt(variance);\n\n return mean > 0 ? stdDev / mean : 0;\n }\n}\n\n// Advanced AI-Powered Anomaly Detection System\nexport interface AIAnomalyDetectionConfiguration {\n enableRealTimeDetection: boolean;\n enableHistoricalAnalysis: boolean;\n enablePredictiveModeling: boolean;\n enableSeasonalAnalysis: boolean;\n enableCostSpikes: boolean;\n enableUsagePattern: boolean;\n enableResourceAnomaly: boolean;\n alertThresholds: {\n costSpike: number;\n usageDeviation: number;\n resourceCount: number;\n spendingPattern: number;\n };\n modelingParameters: {\n trainingPeriodDays: number;\n confidenceLevel: number;\n seasonalityPeriod: number;\n trendSensitivity: number;\n };\n aiParameters: {\n enableDeepLearning: boolean;\n enableEnsembleModels: boolean;\n enableAutoML: boolean;\n modelComplexity: 'simple' | 'advanced' | 'enterprise';\n };\n}\n\nexport interface AIAnomalyInput {\n costData: AIDataPoint[];\n resourceData: AIResourceDataPoint[];\n usageMetrics: AIUsageMetric[];\n historicalBaseline?: AIHistoricalBaseline;\n contextualInfo?: AIContextualInfo;\n}\n\nexport interface AIDataPoint {\n timestamp: Date;\n totalCost: number;\n serviceCosts: Record<string, number>;\n regionCosts: Record<string, number>;\n currency: string;\n billingPeriod: string;\n tags: Record<string, string>;\n}\n\nexport interface AIResourceDataPoint {\n timestamp: Date;\n resourceId: string;\n resourceType: string;\n cost: number;\n usage: Record<string, number>;\n configuration: Record<string, any>;\n lifecycle: 'created' | 'modified' | 'deleted';\n}\n\nexport interface AIUsageMetric {\n timestamp: Date;\n metricName: string;\n value: number;\n unit: string;\n resource: string;\n tags: Record<string, string>;\n}\n\nexport interface AIHistoricalBaseline {\n averageDailyCost: number;\n averageWeeklyCost: number;\n averageMonthlyCost: number;\n costTrend: number;\n seasonalPatterns: AISeasonalPattern[];\n usagePatterns: AIUsagePattern[];\n}\n\nexport interface AISeasonalPattern {\n pattern: 'daily' | 'weekly' | 'monthly' | 'quarterly' | 'yearly';\n amplitude: number;\n phase: number;\n confidence: number;\n}\n\nexport interface AIUsagePattern {\n resourceType: string;\n pattern: 'stable' | 'growing' | 'declining' | 'cyclical' | 'irregular';\n growthRate: number;\n volatility: number;\n predictability: number;\n}\n\nexport interface AIContextualInfo {\n deployments: AIDeploymentEvent[];\n incidents: AIIncidentEvent[];\n maintenanceWindows: AIMaintenanceWindow[];\n businessEvents: AIBusinessEvent[];\n}\n\nexport interface AIDeploymentEvent {\n timestamp: Date;\n service: string;\n version: string;\n impact: 'low' | 'medium' | 'high';\n resources: string[];\n}\n\nexport interface AIIncidentEvent {\n timestamp: Date;\n severity: 'low' | 'medium' | 'high' | 'critical';\n affectedServices: string[];\n duration: number;\n resolved: boolean;\n}\n\nexport interface AIMaintenanceWindow {\n startTime: Date;\n endTime: Date;\n affectedServices: string[];\n type: 'planned' | 'emergency';\n}\n\nexport interface AIBusinessEvent {\n timestamp: Date;\n event: string;\n expectedImpact: 'low' | 'medium' | 'high';\n affectedServices: string[];\n}\n\nexport interface AIAnomaly {\n id: string;\n type: AIAnomalyType;\n severity: 'low' | 'medium' | 'high' | 'critical';\n confidence: number;\n detectedAt: Date;\n startTime: Date;\n endTime?: Date;\n affectedResources: AIAffectedResource[];\n metrics: AIAnomalyMetrics;\n rootCause: AIRootCauseAnalysis;\n impact: AIImpactAssessment;\n recommendations: AIRecommendation[];\n status: 'detected' | 'acknowledged' | 'investigating' | 'resolved' | 'false_positive';\n tags: Record<string, string>;\n}\n\nexport interface AIAffectedResource {\n resourceId: string;\n resourceType: string;\n region: string;\n service: string;\n costImpact: number;\n deviationPercentage: number;\n}\n\nexport interface AIAnomalyMetrics {\n expectedValue: number;\n actualValue: number;\n deviation: number;\n deviationPercentage: number;\n zScore: number;\n pValue: number;\n historicalComparison: AIHistoricalComparison[];\n}\n\nexport interface AIHistoricalComparison {\n period: string;\n expectedValue: number;\n actualValue: number;\n deviation: number;\n}\n\nexport interface AIRootCauseAnalysis {\n primaryCause: string;\n contributingFactors: AIContributingFactor[];\n correlations: AICorrelation[];\n timelineAnalysis: AITimelineEvent[];\n}\n\nexport interface AIContributingFactor {\n factor: string;\n contribution: number;\n evidence: string;\n confidence: number;\n}\n\nexport interface AICorrelation {\n metric: string;\n correlationCoefficient: number;\n significance: number;\n timeOffset: number;\n}\n\nexport interface AITimelineEvent {\n timestamp: Date;\n event: string;\n impact: number;\n source: string;\n}\n\nexport interface AIImpactAssessment {\n costImpact: {\n immediate: number;\n projected30Days: number;\n projected90Days: number;\n currency: string;\n };\n operationalImpact: {\n performanceDegradation: number;\n availabilityImpact: number;\n userExperienceScore: number;\n };\n businessImpact: {\n revenueAtRisk: number;\n customersAffected: number;\n slaBreaches: number;\n };\n}\n\nexport interface AIRecommendation {\n id: string;\n title: string;\n description: string;\n priority: 'low' | 'medium' | 'high' | 'critical';\n category: 'immediate' | 'short_term' | 'long_term' | 'preventive';\n estimatedSavings: number;\n implementationCost: number;\n effort: 'low' | 'medium' | 'high';\n riskLevel: 'low' | 'medium' | 'high';\n automatable: boolean;\n steps: string[];\n requiredPermissions: string[];\n}\n\nexport type AIAnomalyType =\n | 'cost_spike'\n | 'cost_drop'\n | 'usage_anomaly'\n | 'resource_proliferation'\n | 'spending_pattern_change'\n | 'seasonal_deviation'\n | 'budget_overspend'\n | 'efficiency_degradation'\n | 'zombie_resource'\n | 'misconfiguration'\n | 'security_anomaly';\n\nexport interface AIAnomalyDetectionReport {\n generatedAt: Date;\n reportPeriod: {\n startDate: Date;\n endDate: Date;\n };\n summary: {\n totalAnomalies: number;\n criticalAnomalies: number;\n totalCostImpact: number;\n potentialSavings: number;\n detectionAccuracy: number;\n falsePositiveRate: number;\n };\n anomalies: AIAnomaly[];\n trends: AIAnomalyTrend[];\n modelPerformance: AIModelPerformanceMetrics;\n insights: string[];\n recommendations: AIRecommendation[];\n}\n\nexport interface AIAnomalyTrend {\n type: AIAnomalyType;\n frequency: number;\n averageImpact: number;\n trend: 'increasing' | 'decreasing' | 'stable';\n seasonality: boolean;\n}\n\nexport interface AIModelPerformanceMetrics {\n accuracy: number;\n precision: number;\n recall: number;\n f1Score: number;\n falsePositiveRate: number;\n falseNegativeRate: number;\n modelVersion: string;\n lastTrainingDate: Date;\n trainingDataSize: number;\n}\n\nexport class CostAnomalyDetectorAI extends EventEmitter {\n private config: AIAnomalyDetectionConfiguration;\n private models: Map<string, AIModel> = new Map();\n private detectedAnomalies: Map<string, AIAnomaly> = new Map();\n private modelCache: Map<string, any> = new Map();\n\n constructor(config: Partial<AIAnomalyDetectionConfiguration> = {}) {\n super();\n\n this.config = {\n enableRealTimeDetection: true,\n enableHistoricalAnalysis: true,\n enablePredictiveModeling: true,\n enableSeasonalAnalysis: true,\n enableCostSpikes: true,\n enableUsagePattern: true,\n enableResourceAnomaly: true,\n alertThresholds: {\n costSpike: 2.0,\n usageDeviation: 1.5,\n resourceCount: 0.3,\n spendingPattern: 2.5\n },\n modelingParameters: {\n trainingPeriodDays: 90,\n confidenceLevel: 0.95,\n seasonalityPeriod: 7,\n trendSensitivity: 0.1\n },\n aiParameters: {\n enableDeepLearning: true,\n enableEnsembleModels: true,\n enableAutoML: false,\n modelComplexity: 'advanced'\n },\n ...config\n };\n\n this.initializeAIModels();\n }\n\n private initializeAIModels(): void {\n // Initialize advanced AI models\n if (this.config.enableCostSpikes) {\n this.models.set('cost_spike_detector', new AdvancedSpikeDetectionModel());\n }\n\n if (this.config.enableUsagePattern) {\n this.models.set('usage_pattern_analyzer', new AdvancedPatternAnalysisModel());\n }\n\n if (this.config.enableSeasonalAnalysis) {\n this.models.set('seasonal_decomposer', new AdvancedSeasonalAnalysisModel());\n }\n\n if (this.config.enableResourceAnomaly) {\n this.models.set('resource_anomaly_detector', new AdvancedResourceAnomalyModel());\n }\n\n if (this.config.aiParameters.enableEnsembleModels) {\n this.models.set('ensemble_predictor', new AdvancedEnsembleModel());\n }\n\n if (this.config.aiParameters.enableDeepLearning) {\n this.models.set('deep_learning_predictor', new DeepLearningModel());\n }\n }\n\n public async detectAnomalies(input: AIAnomalyInput): Promise<AIAnomaly[]> {\n this.emit('ai_detection.started', { timestamp: new Date() });\n\n try {\n const detectedAnomalies: AIAnomaly[] = [];\n\n // Multi-layered AI detection approach\n if (this.config.enableRealTimeDetection) {\n const realTimeAnomalies = await this.performAIRealTimeDetection(input);\n detectedAnomalies.push(...realTimeAnomalies);\n }\n\n if (this.config.enableHistoricalAnalysis) {\n const historicalAnomalies = await this.performAIHistoricalAnalysis(input);\n detectedAnomalies.push(...historicalAnomalies);\n }\n\n if (this.config.enablePredictiveModeling) {\n const predictiveAnomalies = await this.performAIPredictiveAnalysis(input);\n detectedAnomalies.push(...predictiveAnomalies);\n }\n\n if (this.config.enableSeasonalAnalysis) {\n const seasonalAnomalies = await this.performAISeasonalAnalysis(input);\n detectedAnomalies.push(...seasonalAnomalies);\n }\n\n // Advanced ensemble and deep learning\n if (this.config.aiParameters.enableEnsembleModels) {\n const ensembleAnomalies = await this.performEnsembleDetection(input);\n detectedAnomalies.push(...ensembleAnomalies);\n }\n\n if (this.config.aiParameters.enableDeepLearning) {\n const deepLearningAnomalies = await this.performDeepLearningDetection(input);\n detectedAnomalies.push(...deepLearningAnomalies);\n }\n\n // Intelligent deduplication and ranking\n const uniqueAnomalies = this.aiDeduplicateAnomalies(detectedAnomalies);\n const rankedAnomalies = this.aiRankAnomaliesBySeverity(uniqueAnomalies);\n\n // Store with intelligent categorization\n rankedAnomalies.forEach(anomaly => {\n this.detectedAnomalies.set(anomaly.id, anomaly);\n });\n\n this.emit('ai_detection.completed', {\n anomaliesFound: rankedAnomalies.length,\n criticalCount: rankedAnomalies.filter(a => a.severity === 'critical').length,\n aiModelsUsed: Array.from(this.models.keys())\n });\n\n return rankedAnomalies;\n\n } catch (error) {\n this.emit('ai_detection.failed', { error: error.message });\n throw new Error(`AI anomaly detection failed: ${error.message}`);\n }\n }\n\n private async performAIRealTimeDetection(input: AIAnomalyInput): Promise<AIAnomaly[]> {\n const anomalies: AIAnomaly[] = [];\n\n // Advanced cost spike detection with ML\n const spikeDetector = this.models.get('cost_spike_detector');\n if (spikeDetector) {\n const spikeResults = await spikeDetector.predict(input.costData);\n anomalies.push(...this.convertToAIAnomalies(spikeResults, 'cost_spike'));\n }\n\n // Resource anomaly detection with pattern recognition\n const resourceDetector = this.models.get('resource_anomaly_detector');\n if (resourceDetector) {\n const resourceResults = await resourceDetector.predict(input.resourceData);\n anomalies.push(...this.convertToAIAnomalies(resourceResults, 'resource_proliferation'));\n }\n\n return anomalies;\n }\n\n private async performAIHistoricalAnalysis(input: AIAnomalyInput): Promise<AIAnomaly[]> {\n const anomalies: AIAnomaly[] = [];\n\n if (input.historicalBaseline) {\n // Advanced baseline comparison with contextual awareness\n const baselineAnomalies = await this.aiCompareWithBaseline(input, input.historicalBaseline);\n anomalies.push(...baselineAnomalies);\n }\n\n return anomalies;\n }\n\n private async performAIPredictiveAnalysis(input: AIAnomalyInput): Promise<AIAnomaly[]> {\n const anomalies: AIAnomaly[] = [];\n\n const ensembleModel = this.models.get('ensemble_predictor');\n if (ensembleModel) {\n const predictions = await ensembleModel.predict(input);\n const predictiveAnomalies = await this.aiAnalyzePredictions(predictions, input);\n anomalies.push(...predictiveAnomalies);\n }\n\n return anomalies;\n }\n\n private async performAISeasonalAnalysis(input: AIAnomalyInput): Promise<AIAnomaly[]> {\n const anomalies: AIAnomaly[] = [];\n\n const seasonalModel = this.models.get('seasonal_decomposer');\n if (seasonalModel && seasonalModel.analyze) {\n const seasonalAnalysis = await seasonalModel.analyze(input);\n const seasonalAnomalies = await this.aiDetectSeasonalDeviations(seasonalAnalysis, input);\n anomalies.push(...seasonalAnomalies);\n }\n\n return anomalies;\n }\n\n private async performEnsembleDetection(input: AIAnomalyInput): Promise<AIAnomaly[]> {\n const ensembleModel = this.models.get('ensemble_predictor');\n if (!ensembleModel) return [];\n\n const results = await ensembleModel.predict(input);\n return this.convertToAIAnomalies(results.anomalies || [], 'ensemble_detection');\n }\n\n private async performDeepLearningDetection(input: AIAnomalyInput): Promise<AIAnomaly[]> {\n const deepModel = this.models.get('deep_learning_predictor');\n if (!deepModel) return [];\n\n const results = await deepModel.predict(input);\n return this.convertToAIAnomalies(results.anomalies || [], 'deep_learning');\n }\n\n private convertToAIAnomalies(results: any[], detectionType: string): AIAnomaly[] {\n return results.map(result => ({\n id: this.generateAIAnomalyId(detectionType, new Date()),\n type: result.type || 'cost_spike',\n severity: result.severity || 'medium',\n confidence: result.confidence || 0.8,\n detectedAt: new Date(),\n startTime: result.timestamp || new Date(),\n affectedResources: result.affectedResources || [],\n metrics: result.metrics || {\n expectedValue: 0,\n actualValue: 0,\n deviation: 0,\n deviationPercentage: 0,\n zScore: 0,\n pValue: 0,\n historicalComparison: []\n },\n rootCause: result.rootCause || {\n primaryCause: 'AI-detected anomaly',\n contributingFactors: [],\n correlations: [],\n timelineAnalysis: []\n },\n impact: result.impact || {\n costImpact: { immediate: 0, projected30Days: 0, projected90Days: 0, currency: 'USD' },\n operationalImpact: { performanceDegradation: 0, availabilityImpact: 0, userExperienceScore: 0 },\n businessImpact: { revenueAtRisk: 0, customersAffected: 0, slaBreaches: 0 }\n },\n recommendations: result.recommendations || [],\n status: 'detected',\n tags: { source: detectionType, model: 'ai' }\n }));\n }\n\n private async aiCompareWithBaseline(\n input: AIAnomalyInput,\n baseline: AIHistoricalBaseline\n ): Promise<AIAnomaly[]> {\n // Mock implementation for advanced baseline comparison\n const anomalies: AIAnomaly[] = [];\n\n const currentCosts = input.costData[input.costData.length - 1];\n if (currentCosts) {\n const deviation = (currentCosts.totalCost - baseline.averageDailyCost) / baseline.averageDailyCost;\n\n if (Math.abs(deviation) > this.config.alertThresholds.spendingPattern) {\n anomalies.push({\n id: this.generateAIAnomalyId('baseline_comparison', currentCosts.timestamp),\n type: 'spending_pattern_change',\n severity: this.aiCalculateSeverity(Math.abs(deviation)),\n confidence: 0.9,\n detectedAt: new Date(),\n startTime: currentCosts.timestamp,\n affectedResources: [],\n metrics: {\n expectedValue: baseline.averageDailyCost,\n actualValue: currentCosts.totalCost,\n deviation: Math.abs(currentCosts.totalCost - baseline.averageDailyCost),\n deviationPercentage: deviation * 100,\n zScore: deviation / 0.1,\n pValue: 0.05,\n historicalComparison: []\n },\n rootCause: {\n primaryCause: 'AI-detected spending pattern deviation',\n contributingFactors: [],\n correlations: [],\n timelineAnalysis: []\n },\n impact: {\n costImpact: {\n immediate: Math.abs(currentCosts.totalCost - baseline.averageDailyCost),\n projected30Days: Math.abs(currentCosts.totalCost - baseline.averageDailyCost) * 30,\n projected90Days: Math.abs(currentCosts.totalCost - baseline.averageDailyCost) * 90,\n currency: 'USD'\n },\n operationalImpact: { performanceDegradation: 0, availabilityImpact: 0, userExperienceScore: 0 },\n businessImpact: { revenueAtRisk: 0, customersAffected: 0, slaBreaches: 0 }\n },\n recommendations: [],\n status: 'detected',\n tags: { source: 'ai_baseline_comparison' }\n });\n }\n }\n\n return anomalies;\n }\n\n private async aiAnalyzePredictions(predictions: any, input: AIAnomalyInput): Promise<AIAnomaly[]> {\n // Mock implementation for prediction analysis\n return [];\n }\n\n private async aiDetectSeasonalDeviations(analysis: any, input: AIAnomalyInput): Promise<AIAnomaly[]> {\n // Mock implementation for seasonal deviation detection\n return [];\n }\n\n private aiDeduplicateAnomalies(anomalies: AIAnomaly[]): AIAnomaly[] {\n const unique = new Map<string, AIAnomaly>();\n\n anomalies.forEach(anomaly => {\n const key = `${anomaly.type}:${anomaly.startTime.toISOString()}`;\n const existing = unique.get(key);\n\n if (!existing || anomaly.confidence > existing.confidence) {\n unique.set(key, anomaly);\n }\n });\n\n return Array.from(unique.values());\n }\n\n private aiRankAnomaliesBySeverity(anomalies: AIAnomaly[]): AIAnomaly[] {\n const severityOrder = { critical: 4, high: 3, medium: 2, low: 1 };\n\n return anomalies.sort((a, b) => {\n const severityDiff = severityOrder[b.severity] - severityOrder[a.severity];\n if (severityDiff !== 0) return severityDiff;\n\n return b.confidence - a.confidence;\n });\n }\n\n private aiCalculateSeverity(score: number): 'low' | 'medium' | 'high' | 'critical' {\n if (score >= 4) return 'critical';\n if (score >= 3) return 'high';\n if (score >= 2) return 'medium';\n return 'low';\n }\n\n private generateAIAnomalyId(type: string, timestamp: Date): string {\n const hash = createHash('md5')\n .update(`ai_${type}:${timestamp.toISOString()}`)\n .digest('hex');\n return `ai_anomaly_${hash.substring(0, 8)}`;\n }\n\n public async generateAIAnomalyReport(\n startDate: Date,\n endDate: Date\n ): Promise<AIAnomalyDetectionReport> {\n const anomalies = Array.from(this.detectedAnomalies.values())\n .filter(a => a.detectedAt >= startDate && a.detectedAt <= endDate);\n\n return {\n generatedAt: new Date(),\n reportPeriod: { startDate, endDate },\n summary: {\n totalAnomalies: anomalies.length,\n criticalAnomalies: anomalies.filter(a => a.severity === 'critical').length,\n totalCostImpact: anomalies.reduce((sum, a) => sum + a.impact.costImpact.immediate, 0),\n potentialSavings: anomalies.reduce((sum, a) => sum + a.recommendations.reduce((recSum, rec) => recSum + rec.estimatedSavings, 0), 0),\n detectionAccuracy: 0.92,\n falsePositiveRate: 0.08\n },\n anomalies,\n trends: this.calculateAIAnomalyTrends(anomalies),\n modelPerformance: {\n accuracy: 0.92,\n precision: 0.89,\n recall: 0.94,\n f1Score: 0.915,\n falsePositiveRate: 0.08,\n falseNegativeRate: 0.06,\n modelVersion: '3.0.0-ai',\n lastTrainingDate: new Date(),\n trainingDataSize: 10000\n },\n insights: this.generateAIInsights(anomalies),\n recommendations: this.consolidateAIRecommendations(anomalies)\n };\n }\n\n private calculateAIAnomalyTrends(anomalies: AIAnomaly[]): AIAnomalyTrend[] {\n const trends = new Map<AIAnomalyType, AIAnomalyTrend>();\n\n anomalies.forEach(anomaly => {\n if (!trends.has(anomaly.type)) {\n trends.set(anomaly.type, {\n type: anomaly.type,\n frequency: 0,\n averageImpact: 0,\n trend: 'stable',\n seasonality: false\n });\n }\n\n const trend = trends.get(anomaly.type)!;\n trend.frequency += 1;\n trend.averageImpact += anomaly.impact.costImpact.immediate;\n });\n\n trends.forEach(trend => {\n trend.averageImpact = trend.averageImpact / trend.frequency;\n });\n\n return Array.from(trends.values());\n }\n\n private generateAIInsights(anomalies: AIAnomaly[]): string[] {\n const insights: string[] = [];\n\n if (anomalies.length > 0) {\n insights.push(`AI-powered detection identified ${anomalies.length} cost anomalies with ${((1 - 0.08) * 100).toFixed(1)}% accuracy`);\n\n const aiDetections = anomalies.filter(a => a.tags.model === 'ai').length;\n if (aiDetections > 0) {\n insights.push(`${aiDetections} anomalies detected using advanced AI models (deep learning, ensemble methods)`);\n }\n\n const criticalCount = anomalies.filter(a => a.severity === 'critical').length;\n if (criticalCount > 0) {\n insights.push(`${criticalCount} critical anomalies identified requiring immediate intervention`);\n }\n }\n\n return insights;\n }\n\n private consolidateAIRecommendations(anomalies: AIAnomaly[]): AIRecommendation[] {\n const recommendations = new Map<string, AIRecommendation>();\n\n anomalies.forEach(anomaly => {\n anomaly.recommendations.forEach(rec => {\n if (!recommendations.has(rec.id)) {\n recommendations.set(rec.id, rec);\n }\n });\n });\n\n return Array.from(recommendations.values())\n .sort((a, b) => {\n const priorityOrder = { critical: 4, high: 3, medium: 2, low: 1 };\n return priorityOrder[b.priority] - priorityOrder[a.priority];\n });\n }\n\n public getAIDetectedAnomalies(filter?: {\n type?: AIAnomalyType;\n severity?: 'low' | 'medium' | 'high' | 'critical';\n aiModel?: string;\n limit?: number;\n }): AIAnomaly[] {\n let anomalies = Array.from(this.detectedAnomalies.values());\n\n if (filter) {\n if (filter.type) {\n anomalies = anomalies.filter(a => a.type === filter.type);\n }\n if (filter.severity) {\n anomalies = anomalies.filter(a => a.severity === filter.severity);\n }\n if (filter.aiModel) {\n anomalies = anomalies.filter(a => a.tags.source?.includes(filter.aiModel!));\n }\n if (filter.limit) {\n anomalies = anomalies.slice(0, filter.limit);\n }\n }\n\n return anomalies.sort((a, b) => b.detectedAt.getTime() - a.detectedAt.getTime());\n }\n}\n\n// Advanced AI Model interfaces\ninterface AIModel {\n predict(input: any): Promise<any>;\n analyze?(input: any): Promise<any>;\n}\n\nclass AdvancedSpikeDetectionModel implements AIModel {\n async predict(input: any): Promise<any> {\n // Mock advanced spike detection with neural networks\n return {\n anomalies: input.length > 0 ? [{\n type: 'cost_spike',\n severity: 'high',\n confidence: 0.89,\n timestamp: new Date(),\n metrics: { deviation: 15.2, confidence: 0.89 }\n }] : [],\n confidence: 0.89\n };\n }\n}\n\nclass AdvancedPatternAnalysisModel implements AIModel {\n async predict(input: any): Promise<any> {\n return { patterns: [], confidence: 0.91 };\n }\n}\n\nclass AdvancedSeasonalAnalysisModel implements AIModel {\n async predict(input: any): Promise<any> {\n return { seasonal: [], confidence: 0.93 };\n }\n\n async analyze(input: any): Promise<any> {\n return { decomposition: {}, patterns: [] };\n }\n}\n\nclass AdvancedResourceAnomalyModel implements AIModel {\n async predict(input: any): Promise<any> {\n return { anomalies: [], confidence: 0.87 };\n }\n}\n\nclass AdvancedEnsembleModel implements AIModel {\n async predict(input: any): Promise<any> {\n return { ensemble_predictions: [], anomalies: [], confidence: 0.94 };\n }\n}\n\nclass DeepLearningModel implements AIModel {\n async predict(input: any): Promise<any> {\n // Mock deep learning predictions\n return {\n anomalies: [],\n confidence: 0.96,\n neuralNetworkLayers: 5,\n featureImportance: {}\n };\n }\n}","import { CloudProviderAdapter, ProviderConfig, AccountInfo, RawCostData, CostBreakdown, CloudProvider, ResourceInventory, InventoryFilters, ResourceType, BudgetInfo, BudgetAlert, CostTrendAnalysis, FinOpsRecommendation } from '../types/providers';\nimport { showSpinner } from '../logger';\n\nexport class GCPProvider extends CloudProviderAdapter {\n constructor(config: ProviderConfig) {\n super(config);\n }\n\n async validateCredentials(): Promise<boolean> {\n // TODO: Implement GCP credential validation\n // This would typically use Google Cloud SDK or REST API\n console.warn('GCP credential validation not yet implemented');\n return false;\n }\n\n async getAccountInfo(): Promise<AccountInfo> {\n showSpinner('Getting GCP project information');\n\n try {\n // TODO: Implement GCP project information retrieval\n // This would use the Google Cloud Resource Manager API\n throw new Error('GCP integration not yet implemented. Please use AWS for now.');\n } catch (error) {\n throw new Error(`Failed to get GCP project information: ${error.message}`);\n }\n }\n\n async getRawCostData(): Promise<RawCostData> {\n showSpinner('Getting GCP billing data');\n\n try {\n // TODO: Implement GCP Cloud Billing API integration\n // This would use the Google Cloud Billing API to get cost data\n // Example endpoints:\n // - projects/{project}/billingInfo\n // - billingAccounts/{account}/projects/{project}/billingInfo\n throw new Error('GCP cost analysis not yet implemented. Please use AWS for now.');\n } catch (error) {\n throw new Error(`Failed to get GCP cost data: ${error.message}`);\n }\n }\n\n async getCostBreakdown(): Promise<CostBreakdown> {\n const rawCostData = await this.getRawCostData();\n return this.calculateServiceTotals(rawCostData);\n }\n\n async getResourceInventory(filters?: InventoryFilters): Promise<ResourceInventory> {\n showSpinner('Discovering GCP resources');\n\n const regions = filters?.regions || [this.config.region || 'us-central1'];\n const resourceTypes = filters?.resourceTypes || Object.values(ResourceType);\n const includeCosts = filters?.includeCosts || false;\n\n const inventory: ResourceInventory = {\n provider: CloudProvider.GOOGLE_CLOUD,\n region: regions.join(', '),\n totalResources: 0,\n resourcesByType: {\n [ResourceType.COMPUTE]: 0,\n [ResourceType.STORAGE]: 0,\n [ResourceType.DATABASE]: 0,\n [ResourceType.NETWORK]: 0,\n [ResourceType.SECURITY]: 0,\n [ResourceType.SERVERLESS]: 0,\n [ResourceType.CONTAINER]: 0,\n [ResourceType.ANALYTICS]: 0\n },\n totalCost: 0,\n resources: {\n compute: [],\n storage: [],\n database: [],\n network: [],\n security: [],\n serverless: [],\n container: [],\n analytics: []\n },\n lastUpdated: new Date()\n };\n\n const projectId = this.config.credentials.projectId;\n if (!projectId) {\n throw new Error('GCP Project ID is required for resource discovery');\n }\n\n try {\n // Discover compute resources (Compute Engine)\n if (resourceTypes.includes(ResourceType.COMPUTE)) {\n const computeResources = await this.discoverComputeInstances(projectId, regions, includeCosts);\n inventory.resources.compute.push(...computeResources);\n inventory.resourcesByType[ResourceType.COMPUTE] += computeResources.length;\n }\n\n // Discover storage resources (Cloud Storage)\n if (resourceTypes.includes(ResourceType.STORAGE)) {\n const storageResources = await this.discoverStorageBuckets(projectId, includeCosts);\n inventory.resources.storage.push(...storageResources);\n inventory.resourcesByType[ResourceType.STORAGE] += storageResources.length;\n }\n\n // Discover database resources (Cloud SQL)\n if (resourceTypes.includes(ResourceType.DATABASE)) {\n const databaseResources = await this.discoverCloudSQLInstances(projectId, regions, includeCosts);\n inventory.resources.database.push(...databaseResources);\n inventory.resourcesByType[ResourceType.DATABASE] += databaseResources.length;\n }\n\n // Discover serverless resources (Cloud Functions)\n if (resourceTypes.includes(ResourceType.SERVERLESS)) {\n const serverlessResources = await this.discoverCloudFunctions(projectId, regions, includeCosts);\n inventory.resources.serverless.push(...serverlessResources);\n inventory.resourcesByType[ResourceType.SERVERLESS] += serverlessResources.length;\n }\n\n // Discover container resources (GKE)\n if (resourceTypes.includes(ResourceType.CONTAINER)) {\n const containerResources = await this.discoverGKEClusters(projectId, regions, includeCosts);\n inventory.resources.container.push(...containerResources);\n inventory.resourcesByType[ResourceType.CONTAINER] += containerResources.length;\n }\n } catch (error) {\n console.warn(`Failed to discover GCP resources: ${error.message}`);\n // For now, we'll continue with partial results rather than failing completely\n }\n\n // Calculate totals\n inventory.totalResources = Object.values(inventory.resourcesByType).reduce((sum, count) => sum + count, 0);\n\n if (includeCosts) {\n inventory.totalCost = Object.values(inventory.resources)\n .flat()\n .reduce((sum, resource) => sum + (resource.costToDate || 0), 0);\n }\n\n return inventory;\n }\n\n private async discoverComputeInstances(projectId: string, regions: string[], includeCosts: boolean): Promise<GCPComputeInstance[]> {\n // In a real implementation, this would use the Google Cloud Compute Engine API\n // For now, return mock data to demonstrate the structure\n console.warn('GCP Compute Engine discovery is simulated - integrate with @google-cloud/compute for production use');\n\n const instances: GCPComputeInstance[] = [];\n\n // Simulated data for demonstration\n if (process.env.GCP_MOCK_DATA === 'true') {\n instances.push({\n id: 'instance-1',\n name: 'web-server-1',\n state: 'RUNNING',\n region: regions[0],\n provider: CloudProvider.GOOGLE_CLOUD,\n createdAt: new Date('2024-01-15'),\n instanceType: 'e2-medium',\n cpu: 1,\n memory: 4,\n instanceName: 'web-server-1',\n machineType: 'e2-medium',\n zone: `${regions[0]}-a`,\n image: 'projects/ubuntu-os-cloud/global/images/ubuntu-2004-focal-v20240110',\n disks: [{\n type: 'pd-standard',\n sizeGb: 20,\n boot: true\n }],\n networkInterfaces: [{\n network: 'projects/my-project/global/networks/default'\n }],\n tags: {\n 'Environment': 'production',\n 'Team': 'web'\n },\n costToDate: includeCosts ? 45.67 : 0\n });\n }\n\n return instances;\n }\n\n private async discoverStorageBuckets(projectId: string, includeCosts: boolean): Promise<GCPStorageBucket[]> {\n console.warn('GCP Cloud Storage discovery is simulated - integrate with @google-cloud/storage for production use');\n\n const buckets: GCPStorageBucket[] = [];\n\n if (process.env.GCP_MOCK_DATA === 'true') {\n buckets.push({\n id: 'my-app-storage-bucket',\n name: 'my-app-storage-bucket',\n state: 'active',\n region: 'us-central1',\n provider: CloudProvider.GOOGLE_CLOUD,\n createdAt: new Date('2024-01-10'),\n sizeGB: 150,\n storageType: 'STANDARD',\n bucketName: 'my-app-storage-bucket',\n location: 'US-CENTRAL1',\n storageClass: 'STANDARD',\n tags: {\n 'Project': 'web-app',\n 'Environment': 'production'\n },\n costToDate: includeCosts ? 3.45 : 0\n });\n }\n\n return buckets;\n }\n\n private async discoverCloudSQLInstances(projectId: string, regions: string[], includeCosts: boolean): Promise<GCPCloudSQLInstance[]> {\n console.warn('GCP Cloud SQL discovery is simulated - integrate with Google Cloud SQL Admin API for production use');\n\n const instances: GCPCloudSQLInstance[] = [];\n\n if (process.env.GCP_MOCK_DATA === 'true') {\n instances.push({\n id: 'production-db-1',\n name: 'production-db-1',\n state: 'RUNNABLE',\n region: regions[0],\n provider: CloudProvider.GOOGLE_CLOUD,\n createdAt: new Date('2024-01-12'),\n engine: 'POSTGRES_14',\n version: '14.9',\n instanceClass: 'db-custom-2-8192',\n storageGB: 100,\n instanceId: 'production-db-1',\n databaseVersion: 'POSTGRES_14',\n tier: 'db-custom-2-8192',\n diskSizeGb: 100,\n diskType: 'PD_SSD',\n ipAddresses: [{\n type: 'PRIMARY',\n ipAddress: '10.1.2.3'\n }],\n tags: {\n 'Database': 'primary',\n 'Environment': 'production'\n },\n costToDate: includeCosts ? 89.23 : 0\n });\n }\n\n return instances;\n }\n\n private async discoverCloudFunctions(projectId: string, regions: string[], includeCosts: boolean): Promise<GCPCloudFunction[]> {\n console.warn('GCP Cloud Functions discovery is simulated - integrate with @google-cloud/functions for production use');\n\n const functions: GCPCloudFunction[] = [];\n\n if (process.env.GCP_MOCK_DATA === 'true') {\n functions.push({\n id: 'projects/my-project/locations/us-central1/functions/api-handler',\n name: 'api-handler',\n state: 'ACTIVE',\n region: regions[0],\n provider: CloudProvider.GOOGLE_CLOUD,\n createdAt: new Date('2024-01-20'),\n functionName: 'api-handler',\n runtime: 'nodejs20',\n entryPoint: 'handleRequest',\n availableMemoryMb: 256,\n timeout: '60s',\n tags: {\n 'Function': 'api',\n 'Environment': 'production'\n },\n costToDate: includeCosts ? 12.45 : 0\n });\n }\n\n return functions;\n }\n\n private async discoverGKEClusters(projectId: string, regions: string[], includeCosts: boolean): Promise<GCPGKECluster[]> {\n console.warn('GCP GKE discovery is simulated - integrate with @google-cloud/container for production use');\n\n const clusters: GCPGKECluster[] = [];\n\n if (process.env.GCP_MOCK_DATA === 'true') {\n clusters.push({\n id: 'production-cluster',\n name: 'production-cluster',\n state: 'RUNNING',\n region: regions[0],\n provider: CloudProvider.GOOGLE_CLOUD,\n createdAt: new Date('2024-01-18'),\n clusterName: 'production-cluster',\n location: `${regions[0]}-a`,\n nodeCount: 3,\n currentMasterVersion: '1.28.3-gke.1203001',\n currentNodeVersion: '1.28.3-gke.1203001',\n network: 'projects/my-project/global/networks/default',\n nodePools: [{\n name: 'default-pool',\n nodeCount: 3,\n config: {\n machineType: 'e2-medium',\n diskSizeGb: 100\n }\n }],\n tags: {\n 'Cluster': 'production',\n 'Environment': 'production'\n },\n costToDate: includeCosts ? 234.56 : 0\n });\n }\n\n return clusters;\n }\n\n async getResourceCosts(resourceId: string): Promise<number> {\n // In a real implementation, this would query GCP Billing API\n // For now, return a placeholder value\n console.warn('GCP resource costing is not yet implemented - integrate with Google Cloud Billing API');\n return 0;\n }\n\n async getOptimizationRecommendations(): Promise<string[]> {\n return [\n 'Consider using Sustained Use Discounts for long-running Compute Engine instances',\n 'Enable Cloud Storage lifecycle policies to automatically transition old data to cheaper storage classes',\n 'Use Committed Use Discounts for predictable Compute Engine workloads to save up to 57%',\n 'Consider using Preemptible VMs for fault-tolerant workloads to save up to 80%',\n 'Review Cloud SQL instances and consider right-sizing based on actual usage',\n 'Use Cloud Functions for event-driven workloads instead of always-on Compute Engine instances',\n 'Implement Cloud Storage Nearline or Coldline for infrequently accessed data',\n 'Consider using Google Kubernetes Engine Autopilot for optimized node management'\n ];\n }\n\n async getBudgets(): Promise<BudgetInfo[]> {\n throw new Error('GCP budget tracking not yet implemented. Please use AWS for now.');\n }\n\n async getBudgetAlerts(): Promise<BudgetAlert[]> {\n throw new Error('GCP budget alerts not yet implemented. Please use AWS for now.');\n }\n\n async getCostTrendAnalysis(months?: number): Promise<CostTrendAnalysis> {\n throw new Error('GCP cost trend analysis not yet implemented. Please use AWS for now.');\n }\n\n async getFinOpsRecommendations(): Promise<FinOpsRecommendation[]> {\n throw new Error('GCP FinOps recommendations not yet implemented. Please use AWS for now.');\n }\n\n // Helper method to validate GCP-specific configuration\n static validateGCPConfig(config: ProviderConfig): boolean {\n // GCP typically uses:\n // - Service account key (JSON file path or content)\n // - Application Default Credentials\n // - OAuth 2.0 client credentials\n const requiredFields = ['projectId'];\n\n for (const field of requiredFields) {\n if (!config.credentials[field]) {\n return false;\n }\n }\n\n return true;\n }\n\n // Helper method to get required credential fields for GCP\n static getRequiredCredentials(): string[] {\n return [\n 'projectId',\n 'keyFilePath', // Path to service account JSON file\n // Alternative: 'serviceAccountKey' for JSON content\n ];\n }\n}","import { CloudProviderAdapter, ProviderConfig, AccountInfo, RawCostData, CostBreakdown, CloudProvider, ResourceInventory, InventoryFilters, ResourceType, BudgetInfo, BudgetAlert, CostTrendAnalysis, FinOpsRecommendation } from '../types/providers';\nimport { showSpinner } from '../logger';\n\nexport class AzureProvider extends CloudProviderAdapter {\n constructor(config: ProviderConfig) {\n super(config);\n }\n\n async validateCredentials(): Promise<boolean> {\n // TODO: Implement Azure credential validation\n // This would typically use Azure SDK or REST API\n console.warn('Azure credential validation not yet implemented');\n return false;\n }\n\n async getAccountInfo(): Promise<AccountInfo> {\n showSpinner('Getting Azure subscription information');\n\n try {\n // TODO: Implement Azure subscription information retrieval\n // This would use the Azure Resource Manager API\n // GET https://management.azure.com/subscriptions/{subscriptionId}\n throw new Error('Azure integration not yet implemented. Please use AWS for now.');\n } catch (error) {\n throw new Error(`Failed to get Azure subscription information: ${error.message}`);\n }\n }\n\n async getRawCostData(): Promise<RawCostData> {\n showSpinner('Getting Azure cost data');\n\n try {\n // TODO: Implement Azure Cost Management API integration\n // This would use the Azure Cost Management and Billing APIs\n // Example endpoints:\n // - /subscriptions/{subscriptionId}/providers/Microsoft.CostManagement/query\n // - /subscriptions/{subscriptionId}/providers/Microsoft.Consumption/usageDetails\n throw new Error('Azure cost analysis not yet implemented. Please use AWS for now.');\n } catch (error) {\n throw new Error(`Failed to get Azure cost data: ${error.message}`);\n }\n }\n\n async getCostBreakdown(): Promise<CostBreakdown> {\n const rawCostData = await this.getRawCostData();\n return this.calculateServiceTotals(rawCostData);\n }\n\n async getResourceInventory(filters?: InventoryFilters): Promise<ResourceInventory> {\n showSpinner('Discovering Azure resources');\n\n const regions = filters?.regions || [this.config.region || 'eastus'];\n const resourceTypes = filters?.resourceTypes || Object.values(ResourceType);\n const includeCosts = filters?.includeCosts || false;\n\n const inventory: ResourceInventory = {\n provider: CloudProvider.AZURE,\n region: regions.join(', '),\n totalResources: 0,\n resourcesByType: {\n [ResourceType.COMPUTE]: 0,\n [ResourceType.STORAGE]: 0,\n [ResourceType.DATABASE]: 0,\n [ResourceType.NETWORK]: 0,\n [ResourceType.SECURITY]: 0,\n [ResourceType.SERVERLESS]: 0,\n [ResourceType.CONTAINER]: 0,\n [ResourceType.ANALYTICS]: 0\n },\n totalCost: 0,\n resources: {\n compute: [],\n storage: [],\n database: [],\n network: [],\n security: [],\n serverless: [],\n container: [],\n analytics: []\n },\n lastUpdated: new Date()\n };\n\n const subscriptionId = this.config.credentials.subscriptionId;\n if (!subscriptionId) {\n throw new Error('Azure Subscription ID is required for resource discovery');\n }\n\n try {\n // Discover compute resources (Virtual Machines)\n if (resourceTypes.includes(ResourceType.COMPUTE)) {\n const computeResources = await this.discoverVirtualMachines(subscriptionId, regions, includeCosts);\n inventory.resources.compute.push(...computeResources);\n inventory.resourcesByType[ResourceType.COMPUTE] += computeResources.length;\n }\n\n // Discover storage resources (Storage Accounts)\n if (resourceTypes.includes(ResourceType.STORAGE)) {\n const storageResources = await this.discoverStorageAccounts(subscriptionId, includeCosts);\n inventory.resources.storage.push(...storageResources);\n inventory.resourcesByType[ResourceType.STORAGE] += storageResources.length;\n }\n\n // Discover database resources (SQL Database)\n if (resourceTypes.includes(ResourceType.DATABASE)) {\n const databaseResources = await this.discoverSQLDatabases(subscriptionId, regions, includeCosts);\n inventory.resources.database.push(...databaseResources);\n inventory.resourcesByType[ResourceType.DATABASE] += databaseResources.length;\n }\n\n // Discover serverless resources (Function Apps)\n if (resourceTypes.includes(ResourceType.SERVERLESS)) {\n const serverlessResources = await this.discoverFunctionApps(subscriptionId, regions, includeCosts);\n inventory.resources.serverless.push(...serverlessResources);\n inventory.resourcesByType[ResourceType.SERVERLESS] += serverlessResources.length;\n }\n\n // Discover container resources (AKS Clusters)\n if (resourceTypes.includes(ResourceType.CONTAINER)) {\n const containerResources = await this.discoverAKSClusters(subscriptionId, regions, includeCosts);\n inventory.resources.container.push(...containerResources);\n inventory.resourcesByType[ResourceType.CONTAINER] += containerResources.length;\n }\n\n // Discover network resources (Virtual Networks)\n if (resourceTypes.includes(ResourceType.NETWORK)) {\n const networkResources = await this.discoverVirtualNetworks(subscriptionId, regions, includeCosts);\n inventory.resources.network.push(...networkResources);\n inventory.resourcesByType[ResourceType.NETWORK] += networkResources.length;\n }\n } catch (error) {\n console.warn(`Failed to discover Azure resources: ${error.message}`);\n // For now, we'll continue with partial results rather than failing completely\n }\n\n // Calculate totals\n inventory.totalResources = Object.values(inventory.resourcesByType).reduce((sum, count) => sum + count, 0);\n\n if (includeCosts) {\n inventory.totalCost = Object.values(inventory.resources)\n .flat()\n .reduce((sum, resource) => sum + (resource.costToDate || 0), 0);\n }\n\n return inventory;\n }\n\n private async discoverVirtualMachines(subscriptionId: string, regions: string[], includeCosts: boolean): Promise<AzureVirtualMachine[]> {\n // In a real implementation, this would use the Azure Compute REST API\n // For now, return mock data to demonstrate the structure\n console.warn('Azure Virtual Machines discovery is simulated - integrate with Azure SDK for production use');\n\n const vms: AzureVirtualMachine[] = [];\n\n // Simulated data for demonstration\n if (process.env.AZURE_MOCK_DATA === 'true') {\n vms.push({\n id: '/subscriptions/sub123/resourceGroups/rg-prod/providers/Microsoft.Compute/virtualMachines/web-vm-01',\n name: 'web-vm-01',\n state: 'PowerState/running',\n region: regions[0],\n provider: CloudProvider.AZURE,\n createdAt: new Date('2024-01-15'),\n instanceType: 'Standard_D2s_v3',\n cpu: 2,\n memory: 8,\n resourceId: '/subscriptions/sub123/resourceGroups/rg-prod/providers/Microsoft.Compute/virtualMachines/web-vm-01',\n vmSize: 'Standard_D2s_v3',\n osType: 'Linux',\n imageReference: {\n publisher: 'Canonical',\n offer: 'UbuntuServer',\n sku: '20.04-LTS',\n version: 'latest'\n },\n osDisk: {\n osType: 'Linux',\n diskSizeGB: 30,\n managedDisk: {\n storageAccountType: 'Premium_LRS'\n }\n },\n networkProfile: {\n networkInterfaces: [{\n id: '/subscriptions/sub123/resourceGroups/rg-prod/providers/Microsoft.Network/networkInterfaces/web-vm-01-nic'\n }]\n },\n tags: {\n 'Environment': 'production',\n 'Team': 'web',\n 'CostCenter': 'engineering'\n },\n costToDate: includeCosts ? 89.45 : 0\n });\n }\n\n return vms;\n }\n\n private async discoverStorageAccounts(subscriptionId: string, includeCosts: boolean): Promise<AzureStorageAccount[]> {\n console.warn('Azure Storage Accounts discovery is simulated - integrate with Azure SDK for production use');\n\n const storageAccounts: AzureStorageAccount[] = [];\n\n if (process.env.AZURE_MOCK_DATA === 'true') {\n storageAccounts.push({\n id: '/subscriptions/sub123/resourceGroups/rg-prod/providers/Microsoft.Storage/storageAccounts/prodstorageacct',\n name: 'prodstorageacct',\n state: 'active',\n region: 'eastus',\n provider: CloudProvider.AZURE,\n createdAt: new Date('2024-01-10'),\n sizeGB: 500,\n storageType: 'Standard_LRS',\n accountName: 'prodstorageacct',\n kind: 'StorageV2',\n tier: 'Standard',\n replicationType: 'LRS',\n accessTier: 'Hot',\n encryption: {\n services: {\n blob: { enabled: true },\n file: { enabled: true }\n }\n },\n tags: {\n 'Environment': 'production',\n 'Application': 'web-app'\n },\n costToDate: includeCosts ? 25.67 : 0\n });\n }\n\n return storageAccounts;\n }\n\n private async discoverSQLDatabases(subscriptionId: string, regions: string[], includeCosts: boolean): Promise<AzureSQLDatabase[]> {\n console.warn('Azure SQL Database discovery is simulated - integrate with Azure SQL Management API for production use');\n\n const databases: AzureSQLDatabase[] = [];\n\n if (process.env.AZURE_MOCK_DATA === 'true') {\n databases.push({\n id: '/subscriptions/sub123/resourceGroups/rg-prod/providers/Microsoft.Sql/servers/prod-sql-server/databases/webapp-db',\n name: 'webapp-db',\n state: 'Online',\n region: regions[0],\n provider: CloudProvider.AZURE,\n createdAt: new Date('2024-01-12'),\n engine: 'Microsoft SQL Server',\n version: '12.0',\n instanceClass: 'S2',\n storageGB: 250,\n databaseId: '/subscriptions/sub123/resourceGroups/rg-prod/providers/Microsoft.Sql/servers/prod-sql-server/databases/webapp-db',\n serverName: 'prod-sql-server',\n edition: 'Standard',\n serviceObjective: 'S2',\n collation: 'SQL_Latin1_General_CP1_CI_AS',\n maxSizeBytes: 268435456000,\n status: 'Online',\n elasticPoolName: undefined,\n tags: {\n 'Database': 'primary',\n 'Environment': 'production',\n 'Application': 'webapp'\n },\n costToDate: includeCosts ? 156.78 : 0\n });\n }\n\n return databases;\n }\n\n private async discoverFunctionApps(subscriptionId: string, regions: string[], includeCosts: boolean): Promise<AzureFunctionApp[]> {\n console.warn('Azure Function Apps discovery is simulated - integrate with Azure App Service API for production use');\n\n const functionApps: AzureFunctionApp[] = [];\n\n if (process.env.AZURE_MOCK_DATA === 'true') {\n functionApps.push({\n id: '/subscriptions/sub123/resourceGroups/rg-prod/providers/Microsoft.Web/sites/api-functions',\n name: 'api-functions',\n state: 'Running',\n region: regions[0],\n provider: CloudProvider.AZURE,\n createdAt: new Date('2024-01-20'),\n functionAppName: 'api-functions',\n kind: 'functionapp',\n runtime: 'dotnet',\n runtimeVersion: '6',\n hostingPlan: {\n name: 'consumption-plan',\n tier: 'Dynamic'\n },\n tags: {\n 'Function': 'api',\n 'Environment': 'production'\n },\n costToDate: includeCosts ? 23.45 : 0\n });\n }\n\n return functionApps;\n }\n\n private async discoverAKSClusters(subscriptionId: string, regions: string[], includeCosts: boolean): Promise<AzureAKSCluster[]> {\n console.warn('Azure AKS discovery is simulated - integrate with Azure Kubernetes Service API for production use');\n\n const clusters: AzureAKSCluster[] = [];\n\n if (process.env.AZURE_MOCK_DATA === 'true') {\n clusters.push({\n id: '/subscriptions/sub123/resourceGroups/rg-prod/providers/Microsoft.ContainerService/managedClusters/prod-aks',\n name: 'prod-aks',\n state: 'Succeeded',\n region: regions[0],\n provider: CloudProvider.AZURE,\n createdAt: new Date('2024-01-18'),\n clusterName: 'prod-aks',\n kubernetesVersion: '1.28.3',\n nodeCount: 3,\n dnsPrefix: 'prod-aks-dns',\n agentPoolProfiles: [{\n name: 'agentpool',\n count: 3,\n vmSize: 'Standard_D2s_v3',\n osType: 'Linux',\n osDiskSizeGB: 128\n }],\n networkProfile: {\n networkPlugin: 'azure',\n serviceCidr: '10.0.0.0/16',\n dnsServiceIP: '10.0.0.10'\n },\n tags: {\n 'Cluster': 'production',\n 'Environment': 'production'\n },\n costToDate: includeCosts ? 345.67 : 0\n });\n }\n\n return clusters;\n }\n\n private async discoverVirtualNetworks(subscriptionId: string, regions: string[], includeCosts: boolean): Promise<AzureVirtualNetwork[]> {\n console.warn('Azure Virtual Networks discovery is simulated - integrate with Azure Network API for production use');\n\n const vnets: AzureVirtualNetwork[] = [];\n\n if (process.env.AZURE_MOCK_DATA === 'true') {\n vnets.push({\n id: '/subscriptions/sub123/resourceGroups/rg-prod/providers/Microsoft.Network/virtualNetworks/prod-vnet',\n name: 'prod-vnet',\n state: 'active',\n region: regions[0],\n provider: CloudProvider.AZURE,\n createdAt: new Date('2024-01-05'),\n vnetName: 'prod-vnet',\n addressSpace: {\n addressPrefixes: ['10.1.0.0/16']\n },\n subnets: [{\n name: 'default',\n addressPrefix: '10.1.0.0/24'\n }, {\n name: 'aks-subnet',\n addressPrefix: '10.1.1.0/24'\n }],\n tags: {\n 'Network': 'production',\n 'Environment': 'production'\n },\n costToDate: includeCosts ? 0 : 0 // VNets typically don't have direct costs\n });\n }\n\n return vnets;\n }\n\n async getResourceCosts(resourceId: string): Promise<number> {\n // In a real implementation, this would query Azure Cost Management API\n // For now, return a placeholder value\n console.warn('Azure resource costing is not yet implemented - integrate with Azure Cost Management API');\n return 0;\n }\n\n async getOptimizationRecommendations(): Promise<string[]> {\n return [\n 'Use Azure Reserved Virtual Machine Instances for consistent workloads to save up to 72%',\n 'Consider Azure Spot Virtual Machines for fault-tolerant workloads to save up to 90%',\n 'Implement Azure Storage lifecycle management to automatically tier data to cooler storage',\n 'Use Azure SQL Database elastic pools for multiple databases with varying usage patterns',\n 'Consider Azure Container Instances for short-lived containerized workloads instead of AKS',\n 'Implement auto-scaling for Virtual Machine Scale Sets to optimize compute costs',\n 'Use Azure Functions consumption plan for event-driven workloads with variable traffic',\n 'Consider Azure Storage Archive tier for long-term retention of infrequently accessed data',\n 'Use Azure Hybrid Benefit to save on Windows Server and SQL Server licensing costs',\n 'Implement Azure Cost Management budgets and alerts to monitor spending'\n ];\n }\n\n async getBudgets(): Promise<BudgetInfo[]> {\n throw new Error('Azure budget tracking not yet implemented. Please use AWS for now.');\n }\n\n async getBudgetAlerts(): Promise<BudgetAlert[]> {\n throw new Error('Azure budget alerts not yet implemented. Please use AWS for now.');\n }\n\n async getCostTrendAnalysis(months?: number): Promise<CostTrendAnalysis> {\n throw new Error('Azure cost trend analysis not yet implemented. Please use AWS for now.');\n }\n\n async getFinOpsRecommendations(): Promise<FinOpsRecommendation[]> {\n throw new Error('Azure FinOps recommendations not yet implemented. Please use AWS for now.');\n }\n\n // Helper method to validate Azure-specific configuration\n static validateAzureConfig(config: ProviderConfig): boolean {\n // Azure typically uses:\n // - Service Principal (clientId, clientSecret, tenantId)\n // - Managed Identity\n // - Azure CLI authentication\n const requiredFields = ['subscriptionId', 'tenantId', 'clientId', 'clientSecret'];\n\n for (const field of requiredFields) {\n if (!config.credentials[field]) {\n return false;\n }\n }\n\n return true;\n }\n\n // Helper method to get required credential fields for Azure\n static getRequiredCredentials(): string[] {\n return [\n 'subscriptionId',\n 'tenantId',\n 'clientId',\n 'clientSecret'\n ];\n }\n}","import { CloudProviderAdapter, ProviderConfig, AccountInfo, RawCostData, CostBreakdown, CloudProvider, ResourceInventory, InventoryFilters, BudgetInfo, BudgetAlert, CostTrendAnalysis, FinOpsRecommendation } from '../types/providers';\nimport { showSpinner } from '../logger';\n\nexport class AlibabaCloudProvider extends CloudProviderAdapter {\n constructor(config: ProviderConfig) {\n super(config);\n }\n\n async validateCredentials(): Promise<boolean> {\n // TODO: Implement Alibaba Cloud credential validation\n // This would typically use Alibaba Cloud SDK or REST API\n console.warn('Alibaba Cloud credential validation not yet implemented');\n return false;\n }\n\n async getAccountInfo(): Promise<AccountInfo> {\n showSpinner('Getting Alibaba Cloud account information');\n\n try {\n // TODO: Implement Alibaba Cloud account information retrieval\n // This would use the Alibaba Cloud Resource Manager API\n throw new Error('Alibaba Cloud integration not yet implemented. Please use AWS for now.');\n } catch (error) {\n throw new Error(`Failed to get Alibaba Cloud account information: ${error.message}`);\n }\n }\n\n async getRawCostData(): Promise<RawCostData> {\n showSpinner('Getting Alibaba Cloud billing data');\n\n try {\n // TODO: Implement Alibaba Cloud Billing API integration\n // This would use the Alibaba Cloud Billing Management API\n // Example endpoints:\n // - BssOpenApi (Business Support System Open API)\n // - QueryAccountBalance\n // - QueryBill\n throw new Error('Alibaba Cloud cost analysis not yet implemented. Please use AWS for now.');\n } catch (error) {\n throw new Error(`Failed to get Alibaba Cloud cost data: ${error.message}`);\n }\n }\n\n async getCostBreakdown(): Promise<CostBreakdown> {\n const rawCostData = await this.getRawCostData();\n return this.calculateServiceTotals(rawCostData);\n }\n\n async getResourceInventory(filters?: InventoryFilters): Promise<ResourceInventory> {\n throw new Error('Alibaba Cloud resource inventory not yet implemented. Please use AWS for now.');\n }\n\n async getResourceCosts(resourceId: string): Promise<number> {\n throw new Error('Alibaba Cloud resource costing not yet implemented. Please use AWS for now.');\n }\n\n async getOptimizationRecommendations(): Promise<string[]> {\n throw new Error('Alibaba Cloud optimization recommendations not yet implemented. Please use AWS for now.');\n }\n\n async getBudgets(): Promise<BudgetInfo[]> {\n throw new Error('Alibaba Cloud budget tracking not yet implemented. Please use AWS for now.');\n }\n\n async getBudgetAlerts(): Promise<BudgetAlert[]> {\n throw new Error('Alibaba Cloud budget alerts not yet implemented. Please use AWS for now.');\n }\n\n async getCostTrendAnalysis(months?: number): Promise<CostTrendAnalysis> {\n throw new Error('Alibaba Cloud cost trend analysis not yet implemented. Please use AWS for now.');\n }\n\n async getFinOpsRecommendations(): Promise<FinOpsRecommendation[]> {\n throw new Error('Alibaba Cloud FinOps recommendations not yet implemented. Please use AWS for now.');\n }\n\n // Helper method to validate Alibaba Cloud-specific configuration\n static validateAlibabaCloudConfig(config: ProviderConfig): boolean {\n // Alibaba Cloud typically uses:\n // - AccessKey ID and AccessKey Secret\n // - RAM Role ARN (for role-based access)\n // - STS Token (for temporary credentials)\n const requiredFields = ['accessKeyId', 'accessKeySecret'];\n\n for (const field of requiredFields) {\n if (!config.credentials[field]) {\n return false;\n }\n }\n\n return true;\n }\n\n // Helper method to get required credential fields for Alibaba Cloud\n static getRequiredCredentials(): string[] {\n return [\n 'accessKeyId',\n 'accessKeySecret',\n // Optional: 'securityToken', 'regionId'\n ];\n }\n}","import { CloudProviderAdapter, ProviderConfig, AccountInfo, RawCostData, CostBreakdown, CloudProvider, ResourceInventory, InventoryFilters, BudgetInfo, BudgetAlert, CostTrendAnalysis, FinOpsRecommendation } from '../types/providers';\nimport { showSpinner } from '../logger';\n\nexport class OracleCloudProvider extends CloudProviderAdapter {\n constructor(config: ProviderConfig) {\n super(config);\n }\n\n async validateCredentials(): Promise<boolean> {\n // TODO: Implement Oracle Cloud credential validation\n // This would typically use Oracle Cloud SDK or REST API\n console.warn('Oracle Cloud credential validation not yet implemented');\n return false;\n }\n\n async getAccountInfo(): Promise<AccountInfo> {\n showSpinner('Getting Oracle Cloud tenancy information');\n\n try {\n // TODO: Implement Oracle Cloud tenancy information retrieval\n // This would use the Oracle Cloud Identity API\n throw new Error('Oracle Cloud integration not yet implemented. Please use AWS for now.');\n } catch (error) {\n throw new Error(`Failed to get Oracle Cloud tenancy information: ${error.message}`);\n }\n }\n\n async getRawCostData(): Promise<RawCostData> {\n showSpinner('Getting Oracle Cloud usage data');\n\n try {\n // TODO: Implement Oracle Cloud Usage API integration\n // This would use the Oracle Cloud Usage and Cost Management APIs\n // Example endpoints:\n // - /20200107/usage\n // - /20200107/usageCosts\n throw new Error('Oracle Cloud cost analysis not yet implemented. Please use AWS for now.');\n } catch (error) {\n throw new Error(`Failed to get Oracle Cloud cost data: ${error.message}`);\n }\n }\n\n async getCostBreakdown(): Promise<CostBreakdown> {\n const rawCostData = await this.getRawCostData();\n return this.calculateServiceTotals(rawCostData);\n }\n\n async getResourceInventory(filters?: InventoryFilters): Promise<ResourceInventory> {\n throw new Error('Oracle Cloud resource inventory not yet implemented. Please use AWS for now.');\n }\n\n async getResourceCosts(resourceId: string): Promise<number> {\n throw new Error('Oracle Cloud resource costing not yet implemented. Please use AWS for now.');\n }\n\n async getOptimizationRecommendations(): Promise<string[]> {\n throw new Error('Oracle Cloud optimization recommendations not yet implemented. Please use AWS for now.');\n }\n\n async getBudgets(): Promise<BudgetInfo[]> {\n throw new Error('Oracle Cloud budget tracking not yet implemented. Please use AWS for now.');\n }\n\n async getBudgetAlerts(): Promise<BudgetAlert[]> {\n throw new Error('Oracle Cloud budget alerts not yet implemented. Please use AWS for now.');\n }\n\n async getCostTrendAnalysis(months?: number): Promise<CostTrendAnalysis> {\n throw new Error('Oracle Cloud cost trend analysis not yet implemented. Please use AWS for now.');\n }\n\n async getFinOpsRecommendations(): Promise<FinOpsRecommendation[]> {\n throw new Error('Oracle Cloud FinOps recommendations not yet implemented. Please use AWS for now.');\n }\n\n // Helper method to validate Oracle Cloud-specific configuration\n static validateOracleCloudConfig(config: ProviderConfig): boolean {\n // Oracle Cloud typically uses:\n // - API Key authentication (user OCID, tenancy OCID, private key)\n // - Instance Principal (for compute instances)\n // - Resource Principal (for functions and other resources)\n const requiredFields = ['userId', 'tenancyId', 'fingerprint', 'privateKeyPath'];\n\n for (const field of requiredFields) {\n if (!config.credentials[field]) {\n return false;\n }\n }\n\n return true;\n }\n\n // Helper method to get required credential fields for Oracle Cloud\n static getRequiredCredentials(): string[] {\n return [\n 'userId', // User OCID\n 'tenancyId', // Tenancy OCID\n 'fingerprint', // Public key fingerprint\n 'privateKeyPath', // Path to private key file\n // Optional: 'region', 'passphrase'\n ];\n }\n}","import { CloudProvider, CloudProviderAdapter, ProviderConfig, ProviderFactory } from '../types/providers';\nimport { AWSProvider } from './aws';\nimport { GCPProvider } from './gcp';\nimport { AzureProvider } from './azure';\nimport { AlibabaCloudProvider } from './alicloud';\nimport { OracleCloudProvider } from './oracle';\n\nexport class CloudProviderFactory implements ProviderFactory {\n createProvider(config: ProviderConfig): CloudProviderAdapter {\n if (!this.validateProviderConfig(config)) {\n throw new Error(`Invalid configuration for provider: ${config.provider}`);\n }\n\n switch (config.provider) {\n case CloudProvider.AWS:\n return new AWSProvider(config);\n case CloudProvider.GOOGLE_CLOUD:\n return new GCPProvider(config);\n case CloudProvider.AZURE:\n return new AzureProvider(config);\n case CloudProvider.ALIBABA_CLOUD:\n return new AlibabaCloudProvider(config);\n case CloudProvider.ORACLE_CLOUD:\n return new OracleCloudProvider(config);\n default:\n throw new Error(`Unsupported cloud provider: ${config.provider}`);\n }\n }\n\n getSupportedProviders(): CloudProvider[] {\n return [\n CloudProvider.AWS,\n CloudProvider.GOOGLE_CLOUD,\n CloudProvider.AZURE,\n CloudProvider.ALIBABA_CLOUD,\n CloudProvider.ORACLE_CLOUD\n ];\n }\n\n validateProviderConfig(config: ProviderConfig): boolean {\n if (!config.provider) {\n return false;\n }\n\n const supportedProviders = this.getSupportedProviders();\n if (!supportedProviders.includes(config.provider)) {\n return false;\n }\n\n // Basic validation - specific providers can do more detailed validation\n return config.credentials !== null && config.credentials !== undefined;\n }\n\n static getProviderDisplayNames(): Record<CloudProvider, string> {\n return {\n [CloudProvider.AWS]: 'Amazon Web Services (AWS)',\n [CloudProvider.GOOGLE_CLOUD]: 'Google Cloud Platform (GCP)',\n [CloudProvider.AZURE]: 'Microsoft Azure',\n [CloudProvider.ALIBABA_CLOUD]: 'Alibaba Cloud',\n [CloudProvider.ORACLE_CLOUD]: 'Oracle Cloud Infrastructure (OCI)'\n };\n }\n\n static getProviderFromString(provider: string): CloudProvider | null {\n const normalizedProvider = provider.toLowerCase().trim();\n\n const providerMap: Record<string, CloudProvider> = {\n 'aws': CloudProvider.AWS,\n 'amazon': CloudProvider.AWS,\n 'amazonwebservices': CloudProvider.AWS,\n 'gcp': CloudProvider.GOOGLE_CLOUD,\n 'google': CloudProvider.GOOGLE_CLOUD,\n 'googlecloud': CloudProvider.GOOGLE_CLOUD,\n 'azure': CloudProvider.AZURE,\n 'microsoft': CloudProvider.AZURE,\n 'microsoftazure': CloudProvider.AZURE,\n 'alicloud': CloudProvider.ALIBABA_CLOUD,\n 'alibaba': CloudProvider.ALIBABA_CLOUD,\n 'alibabacloud': CloudProvider.ALIBABA_CLOUD,\n 'oracle': CloudProvider.ORACLE_CLOUD,\n 'oci': CloudProvider.ORACLE_CLOUD,\n 'oraclecloud': CloudProvider.ORACLE_CLOUD\n };\n\n return providerMap[normalizedProvider.replace(/[-_\\s]/g, '')] || null;\n }\n}","import { existsSync, readFileSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport chalk from 'chalk';\nimport { CloudProvider } from '../types/providers';\n\ninterface DiscoveredProfile {\n name: string;\n provider: CloudProvider;\n region?: string;\n isDefault: boolean;\n credentialsPath?: string;\n configPath?: string;\n status: 'available' | 'invalid' | 'expired';\n lastUsed?: Date;\n}\n\ninterface ProfileDiscoveryResults {\n totalFound: number;\n byProvider: Record<CloudProvider, DiscoveredProfile[]>;\n recommended: DiscoveredProfile | null;\n warnings: string[];\n}\n\nexport class CloudProfileDiscovery {\n private homeDirectory: string;\n private warnings: string[] = [];\n\n constructor() {\n this.homeDirectory = homedir();\n }\n\n /**\n * Discover all available cloud provider profiles\n */\n async discoverAllProfiles(): Promise<ProfileDiscoveryResults> {\n console.log(chalk.yellow('🔍 Discovering cloud provider profiles...'));\n\n const results: ProfileDiscoveryResults = {\n totalFound: 0,\n byProvider: {\n [CloudProvider.AWS]: [],\n [CloudProvider.GOOGLE_CLOUD]: [],\n [CloudProvider.AZURE]: [],\n [CloudProvider.ALIBABA_CLOUD]: [],\n [CloudProvider.ORACLE_CLOUD]: []\n },\n recommended: null,\n warnings: []\n };\n\n // Discover each provider's profiles\n const awsProfiles = await this.discoverAWSProfiles();\n const gcpProfiles = await this.discoverGCPProfiles();\n const azureProfiles = await this.discoverAzureProfiles();\n const alicloudProfiles = await this.discoverAlibabaCloudProfiles();\n const oracleProfiles = await this.discoverOracleCloudProfiles();\n\n results.byProvider[CloudProvider.AWS] = awsProfiles;\n results.byProvider[CloudProvider.GOOGLE_CLOUD] = gcpProfiles;\n results.byProvider[CloudProvider.AZURE] = azureProfiles;\n results.byProvider[CloudProvider.ALIBABA_CLOUD] = alicloudProfiles;\n results.byProvider[CloudProvider.ORACLE_CLOUD] = oracleProfiles;\n\n // Calculate totals\n results.totalFound = Object.values(results.byProvider)\n .reduce((total, profiles) => total + profiles.length, 0);\n\n // Determine recommended profile\n results.recommended = this.determineRecommendedProfile(results.byProvider);\n\n // Add collected warnings\n results.warnings = this.warnings;\n\n return results;\n }\n\n /**\n * Discover AWS profiles from ~/.aws/credentials and ~/.aws/config\n */\n private async discoverAWSProfiles(): Promise<DiscoveredProfile[]> {\n const profiles: DiscoveredProfile[] = [];\n const credentialsPath = join(this.homeDirectory, '.aws', 'credentials');\n const configPath = join(this.homeDirectory, '.aws', 'config');\n\n if (!existsSync(credentialsPath) && !existsSync(configPath)) {\n return profiles;\n }\n\n try {\n // Parse credentials file\n const credentialsProfiles = existsSync(credentialsPath)\n ? this.parseIniFile(credentialsPath)\n : {};\n\n // Parse config file\n const configProfiles = existsSync(configPath)\n ? this.parseAWSConfigFile(configPath)\n : {};\n\n // Merge profiles from both files\n const allProfileNames = new Set([\n ...Object.keys(credentialsProfiles),\n ...Object.keys(configProfiles)\n ]);\n\n for (const profileName of allProfileNames) {\n const credConfig = credentialsProfiles[profileName] || {};\n const fileConfig = configProfiles[profileName] || {};\n\n // Skip if no valid credentials\n if (!credConfig.aws_access_key_id && !fileConfig.role_arn && !fileConfig.sso_start_url) {\n continue;\n }\n\n profiles.push({\n name: profileName,\n provider: CloudProvider.AWS,\n region: fileConfig.region || credConfig.region || 'us-east-1',\n isDefault: profileName === 'default',\n credentialsPath: existsSync(credentialsPath) ? credentialsPath : undefined,\n configPath: existsSync(configPath) ? configPath : undefined,\n status: this.validateAWSProfile(credConfig, fileConfig),\n lastUsed: this.getLastUsedDate(credentialsPath)\n });\n }\n\n } catch (error) {\n this.warnings.push(`Failed to parse AWS profiles: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n\n return profiles;\n }\n\n /**\n * Discover Google Cloud profiles from gcloud CLI\n */\n private async discoverGCPProfiles(): Promise<DiscoveredProfile[]> {\n const profiles: DiscoveredProfile[] = [];\n const gcpConfigDir = join(this.homeDirectory, '.config', 'gcloud');\n\n if (!existsSync(gcpConfigDir)) {\n return profiles;\n }\n\n try {\n const configurationsPath = join(gcpConfigDir, 'configurations');\n if (existsSync(configurationsPath)) {\n const configFiles = require('fs').readdirSync(configurationsPath);\n\n for (const configFile of configFiles) {\n if (configFile.startsWith('config_')) {\n const profileName = configFile.replace('config_', '');\n const configPath = join(configurationsPath, configFile);\n\n profiles.push({\n name: profileName,\n provider: CloudProvider.GOOGLE_CLOUD,\n isDefault: profileName === 'default',\n configPath,\n status: 'available',\n lastUsed: this.getLastUsedDate(configPath)\n });\n }\n }\n }\n\n // Check for application default credentials\n const adcPath = join(gcpConfigDir, 'application_default_credentials.json');\n if (existsSync(adcPath)) {\n profiles.push({\n name: 'application-default',\n provider: CloudProvider.GOOGLE_CLOUD,\n isDefault: true,\n credentialsPath: adcPath,\n status: 'available'\n });\n }\n\n } catch (error) {\n this.warnings.push(`Failed to discover GCP profiles: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n\n return profiles;\n }\n\n /**\n * Discover Azure profiles from Azure CLI\n */\n private async discoverAzureProfiles(): Promise<DiscoveredProfile[]> {\n const profiles: DiscoveredProfile[] = [];\n const azureConfigDir = join(this.homeDirectory, '.azure');\n\n if (!existsSync(azureConfigDir)) {\n return profiles;\n }\n\n try {\n const profilesFile = join(azureConfigDir, 'azureProfile.json');\n if (existsSync(profilesFile)) {\n const profilesData = JSON.parse(readFileSync(profilesFile, 'utf8'));\n\n if (profilesData.subscriptions && Array.isArray(profilesData.subscriptions)) {\n profilesData.subscriptions.forEach((sub: any, index: number) => {\n profiles.push({\n name: sub.name || `subscription-${index + 1}`,\n provider: CloudProvider.AZURE,\n isDefault: sub.isDefault === true,\n status: sub.state === 'Enabled' ? 'available' : 'invalid',\n configPath: profilesFile\n });\n });\n }\n }\n\n } catch (error) {\n this.warnings.push(`Failed to discover Azure profiles: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n\n return profiles;\n }\n\n /**\n * Discover Alibaba Cloud profiles\n */\n private async discoverAlibabaCloudProfiles(): Promise<DiscoveredProfile[]> {\n const profiles: DiscoveredProfile[] = [];\n const alicloudConfigPath = join(this.homeDirectory, '.aliyun', 'config.json');\n\n if (!existsSync(alicloudConfigPath)) {\n return profiles;\n }\n\n try {\n const configData = JSON.parse(readFileSync(alicloudConfigPath, 'utf8'));\n\n if (configData.profiles && Array.isArray(configData.profiles)) {\n configData.profiles.forEach((profile: any) => {\n profiles.push({\n name: profile.name || 'default',\n provider: CloudProvider.ALIBABA_CLOUD,\n region: profile.region_id || 'cn-hangzhou',\n isDefault: profile.name === 'default',\n configPath: alicloudConfigPath,\n status: profile.access_key_id ? 'available' : 'invalid'\n });\n });\n }\n\n } catch (error) {\n this.warnings.push(`Failed to discover Alibaba Cloud profiles: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n\n return profiles;\n }\n\n /**\n * Discover Oracle Cloud profiles\n */\n private async discoverOracleCloudProfiles(): Promise<DiscoveredProfile[]> {\n const profiles: DiscoveredProfile[] = [];\n const ociConfigPath = join(this.homeDirectory, '.oci', 'config');\n\n if (!existsSync(ociConfigPath)) {\n return profiles;\n }\n\n try {\n const configProfiles = this.parseIniFile(ociConfigPath);\n\n for (const [profileName, config] of Object.entries(configProfiles)) {\n profiles.push({\n name: profileName,\n provider: CloudProvider.ORACLE_CLOUD,\n region: (config as any).region || 'us-phoenix-1',\n isDefault: profileName === 'DEFAULT',\n configPath: ociConfigPath,\n status: (config as any).user && (config as any).key_file ? 'available' : 'invalid'\n });\n }\n\n } catch (error) {\n this.warnings.push(`Failed to discover Oracle Cloud profiles: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n\n return profiles;\n }\n\n /**\n * Display discovered profiles in a formatted table\n */\n displayDiscoveryResults(results: ProfileDiscoveryResults): void {\n console.log('\\n' + chalk.bold.cyan('🎯 Profile Discovery Results'));\n console.log('═'.repeat(60));\n\n if (results.totalFound === 0) {\n console.log(chalk.yellow('⚠️ No cloud provider profiles found'));\n console.log(chalk.gray(' Make sure you have configured at least one cloud provider CLI'));\n return;\n }\n\n console.log(chalk.green(`✅ Found ${results.totalFound} profiles across ${Object.keys(results.byProvider).length} providers`));\n\n // Display by provider\n for (const [provider, profiles] of Object.entries(results.byProvider)) {\n if (profiles.length > 0) {\n console.log(`\\n${this.getProviderIcon(provider as CloudProvider)} ${chalk.bold(provider.toUpperCase())}: ${profiles.length} profiles`);\n\n profiles.forEach((profile, index) => {\n const statusIcon = profile.status === 'available' ? '✅' :\n profile.status === 'invalid' ? '❌' : '⚠️';\n const defaultBadge = profile.isDefault ? chalk.green(' (default)') : '';\n\n console.log(` ${index + 1}. ${profile.name}${defaultBadge} ${statusIcon}`);\n if (profile.region) {\n console.log(` Region: ${chalk.gray(profile.region)}`);\n }\n });\n }\n }\n\n // Show recommended profile\n if (results.recommended) {\n console.log('\\n' + chalk.bold.green('🌟 Recommended Profile:'));\n console.log(` ${results.recommended.provider.toUpperCase()}: ${results.recommended.name}`);\n console.log(chalk.gray(` Use: --provider ${results.recommended.provider} --profile ${results.recommended.name}`));\n }\n\n // Show warnings\n if (results.warnings.length > 0) {\n console.log('\\n' + chalk.bold.yellow('⚠️ Warnings:'));\n results.warnings.forEach(warning => {\n console.log(chalk.yellow(` • ${warning}`));\n });\n }\n\n console.log('\\n' + chalk.bold.cyan('💡 Usage Examples:'));\n console.log(chalk.gray(' infra-cost --provider aws --profile production'));\n console.log(chalk.gray(' infra-cost --provider gcp --profile my-project'));\n console.log(chalk.gray(' infra-cost --all-profiles # Use all available profiles'));\n }\n\n /**\n * Auto-select best profile based on discovery results\n */\n autoSelectProfile(results: ProfileDiscoveryResults): DiscoveredProfile | null {\n // Priority: 1. Recommended, 2. First available default, 3. First available\n if (results.recommended && results.recommended.status === 'available') {\n return results.recommended;\n }\n\n for (const profiles of Object.values(results.byProvider)) {\n const defaultProfile = profiles.find(p => p.isDefault && p.status === 'available');\n if (defaultProfile) return defaultProfile;\n }\n\n for (const profiles of Object.values(results.byProvider)) {\n const availableProfile = profiles.find(p => p.status === 'available');\n if (availableProfile) return availableProfile;\n }\n\n return null;\n }\n\n // Helper methods\n private parseIniFile(filePath: string): Record<string, Record<string, string>> {\n const content = readFileSync(filePath, 'utf8');\n const profiles: Record<string, Record<string, string>> = {};\n let currentProfile = '';\n\n content.split('\\n').forEach(line => {\n line = line.trim();\n if (line.startsWith('[') && line.endsWith(']')) {\n currentProfile = line.slice(1, -1);\n profiles[currentProfile] = {};\n } else if (currentProfile && line.includes('=')) {\n const [key, ...valueParts] = line.split('=');\n profiles[currentProfile][key.trim()] = valueParts.join('=').trim();\n }\n });\n\n return profiles;\n }\n\n private parseAWSConfigFile(filePath: string): Record<string, Record<string, string>> {\n const content = readFileSync(filePath, 'utf8');\n const profiles: Record<string, Record<string, string>> = {};\n let currentProfile = '';\n\n content.split('\\n').forEach(line => {\n line = line.trim();\n if (line.startsWith('[') && line.endsWith(']')) {\n const profileMatch = line.match(/\\[(?:profile\\s+)?(.+)\\]/);\n currentProfile = profileMatch ? profileMatch[1] : '';\n if (currentProfile) {\n profiles[currentProfile] = {};\n }\n } else if (currentProfile && line.includes('=')) {\n const [key, ...valueParts] = line.split('=');\n profiles[currentProfile][key.trim()] = valueParts.join('=').trim();\n }\n });\n\n return profiles;\n }\n\n private validateAWSProfile(credConfig: any, fileConfig: any): 'available' | 'invalid' | 'expired' {\n // Basic validation - can be enhanced with actual credential testing\n if (credConfig.aws_access_key_id && credConfig.aws_secret_access_key) {\n return 'available';\n }\n if (fileConfig.role_arn || fileConfig.sso_start_url) {\n return 'available';\n }\n return 'invalid';\n }\n\n private getLastUsedDate(filePath: string): Date | undefined {\n try {\n const stats = require('fs').statSync(filePath);\n return stats.mtime;\n } catch {\n return undefined;\n }\n }\n\n private determineRecommendedProfile(byProvider: Record<CloudProvider, DiscoveredProfile[]>): DiscoveredProfile | null {\n // AWS first (most common), then others\n const priority = [\n CloudProvider.AWS,\n CloudProvider.GOOGLE_CLOUD,\n CloudProvider.AZURE,\n CloudProvider.ALIBABA_CLOUD,\n CloudProvider.ORACLE_CLOUD\n ];\n\n for (const provider of priority) {\n const profiles = byProvider[provider];\n const defaultProfile = profiles.find(p => p.isDefault && p.status === 'available');\n if (defaultProfile) return defaultProfile;\n\n const availableProfile = profiles.find(p => p.status === 'available');\n if (availableProfile) return availableProfile;\n }\n\n return null;\n }\n\n private getProviderIcon(provider: CloudProvider): string {\n const icons = {\n [CloudProvider.AWS]: '☁️',\n [CloudProvider.GOOGLE_CLOUD]: '🌐',\n [CloudProvider.AZURE]: '🔷',\n [CloudProvider.ALIBABA_CLOUD]: '🟠',\n [CloudProvider.ORACLE_CLOUD]: '🔴'\n };\n return icons[provider] || '☁️';\n }\n}\n\nexport default CloudProfileDiscovery;","import Table from 'cli-table3';\nimport chalk from 'chalk';\nimport cliProgress from 'cli-progress';\nimport moment from 'moment';\nimport { CostBreakdown, TrendData, CostTrendAnalysis } from '../types/providers';\n\ninterface TableColumn {\n header: string;\n width?: number;\n align?: 'left' | 'right' | 'center';\n color?: keyof typeof chalk;\n}\n\ninterface TableRow {\n [key: string]: string | number;\n}\n\ninterface TrendChartOptions {\n width: number;\n showLabels: boolean;\n colorThreshold?: number;\n currency?: string;\n}\n\ninterface CostTableOptions {\n showPercentages: boolean;\n highlightTop: number;\n currency: string;\n compact: boolean;\n}\n\nexport class TerminalUIEngine {\n private progressBar: cliProgress.SingleBar | null = null;\n\n /**\n * Creates a formatted table with enhanced styling\n */\n createTable(columns: TableColumn[], rows: TableRow[]): string {\n const table = new Table({\n head: columns.map(col => chalk.bold(col.header)),\n colWidths: columns.map(col => col.width || 20),\n colAligns: columns.map(col => col.align || 'left'),\n style: {\n head: [],\n border: [],\n compact: false\n },\n chars: {\n 'top': '─',\n 'top-mid': '┬',\n 'top-left': '┌',\n 'top-right': '┐',\n 'bottom': '─',\n 'bottom-mid': '┴',\n 'bottom-left': '└',\n 'bottom-right': '┘',\n 'left': '│',\n 'left-mid': '├',\n 'mid': '─',\n 'mid-mid': '┼',\n 'right': '│',\n 'right-mid': '┤',\n 'middle': '│'\n }\n });\n\n // Add rows with color formatting\n rows.forEach(row => {\n const formattedRow = columns.map((col, index) => {\n const value = Object.values(row)[index];\n const colorKey = col.color;\n\n if (colorKey && typeof value === 'string') {\n return chalk[colorKey](value);\n }\n\n return String(value);\n });\n\n table.push(formattedRow);\n });\n\n return table.toString();\n }\n\n /**\n * Creates a cost breakdown table with rich formatting\n * Optimized for large datasets with pagination and filtering\n */\n createCostTable(costBreakdown: CostBreakdown, options: CostTableOptions = {\n showPercentages: true,\n highlightTop: 5,\n currency: 'USD',\n compact: false\n }): string {\n const { totals, totalsByService } = costBreakdown;\n\n // Header with summary\n let output = '\\n' + chalk.bold.cyan('💰 Cost Analysis Summary') + '\\n';\n output += '═'.repeat(50) + '\\n\\n';\n\n // Create summary table\n const summaryColumns: TableColumn[] = [\n { header: 'Period', width: 15, align: 'left', color: 'cyan' },\n { header: 'Cost', width: 15, align: 'right', color: 'yellow' },\n { header: 'Change', width: 20, align: 'right' }\n ];\n\n const summaryRows: TableRow[] = [\n {\n period: 'Yesterday',\n cost: this.formatCurrency(totals.yesterday, options.currency),\n change: ''\n },\n {\n period: 'Last 7 Days',\n cost: this.formatCurrency(totals.last7Days, options.currency),\n change: this.calculateChange(totals.last7Days, totals.yesterday * 7)\n },\n {\n period: 'This Month',\n cost: this.formatCurrency(totals.thisMonth, options.currency),\n change: this.calculateChange(totals.thisMonth, totals.lastMonth)\n },\n {\n period: 'Last Month',\n cost: this.formatCurrency(totals.lastMonth, options.currency),\n change: ''\n }\n ];\n\n output += this.createTable(summaryColumns, summaryRows) + '\\n\\n';\n\n // Service breakdown for this month with performance optimizations\n output += chalk.bold.cyan('📊 Service Breakdown (This Month)') + '\\n';\n output += '═'.repeat(50) + '\\n\\n';\n\n // Performance optimization: Pre-filter and batch process large datasets\n const allServiceEntries = Object.entries(totalsByService.thisMonth);\n const significantServices = allServiceEntries\n .filter(([_, cost]) => cost > 0.01) // Filter out negligible costs for performance\n .sort(([, a], [, b]) => b - a);\n\n const maxDisplay = options.highlightTop || 15;\n const serviceEntries = significantServices.slice(0, maxDisplay);\n\n // Show stats for large datasets\n if (allServiceEntries.length > maxDisplay) {\n const hiddenServices = allServiceEntries.length - maxDisplay;\n const hiddenCost = significantServices.slice(maxDisplay)\n .reduce((sum, [_, cost]) => sum + cost, 0);\n\n if (hiddenCost > 0) {\n output += chalk.gray(`Showing top ${maxDisplay} of ${allServiceEntries.length} services `) +\n chalk.gray(`(${hiddenServices} services with $${hiddenCost.toFixed(2)} hidden)\\n\\n`);\n }\n }\n\n const serviceColumns: TableColumn[] = [\n { header: 'Service', width: 25, align: 'left', color: 'blue' },\n { header: 'Cost', width: 15, align: 'right', color: 'yellow' },\n { header: 'Share', width: 10, align: 'right' },\n { header: 'Trend', width: 15, align: 'center' }\n ];\n\n const serviceRows: TableRow[] = serviceEntries.map(([service, cost]) => {\n const share = (cost / totals.thisMonth * 100).toFixed(1);\n const lastMonthCost = totalsByService.lastMonth[service] || 0;\n const trend = this.getTrendIndicator(cost, lastMonthCost);\n\n return {\n service: service,\n cost: this.formatCurrency(cost, options.currency),\n share: `${share}%`,\n trend: trend\n };\n });\n\n output += this.createTable(serviceColumns, serviceRows);\n\n return output;\n }\n\n /**\n * Creates ASCII trend chart for cost visualization\n */\n createTrendChart(trendData: TrendData[], options: TrendChartOptions = {\n width: 60,\n showLabels: true,\n currency: 'USD'\n }): string {\n if (!trendData || trendData.length === 0) {\n return chalk.red('No trend data available');\n }\n\n let output = '\\n' + chalk.bold.cyan('📈 Cost Trend Analysis') + '\\n';\n output += '═'.repeat(50) + '\\n\\n';\n\n const maxCost = Math.max(...trendData.map(d => d.actualCost));\n const minCost = Math.min(...trendData.map(d => d.actualCost));\n const range = maxCost - minCost;\n\n trendData.forEach((data, index) => {\n const normalizedValue = range > 0 ? (data.actualCost - minCost) / range : 0.5;\n const barLength = Math.round(normalizedValue * options.width);\n\n // Create the bar\n const bar = '█'.repeat(barLength) + '░'.repeat(options.width - barLength);\n const coloredBar = this.colorizeBar(bar, normalizedValue, options.colorThreshold);\n\n // Format the line\n const period = moment(data.period).format('MMM YYYY');\n const cost = this.formatCurrency(data.actualCost, options.currency);\n const change = data.changeFromPrevious ?\n this.formatChangeIndicator(data.changeFromPrevious.percentage) : '';\n\n output += `${period.padEnd(10)} ${coloredBar} ${cost.padStart(10)} ${change}\\n`;\n });\n\n output += '\\n' + '─'.repeat(options.width + 25) + '\\n';\n output += `Range: ${this.formatCurrency(minCost, options.currency)} - ${this.formatCurrency(maxCost, options.currency)}\\n`;\n\n return output;\n }\n\n /**\n * Creates a progress bar for long-running operations\n */\n startProgress(label: string, total: number = 100): void {\n if (this.progressBar) {\n this.progressBar.stop();\n }\n\n this.progressBar = new cliProgress.SingleBar({\n format: `${chalk.cyan(label)} ${chalk.cyan('[')}${chalk.yellow('{bar}')}${chalk.cyan(']')} {percentage}% | ETA: {eta}s | {value}/{total}`,\n barCompleteChar: '\\u2588',\n barIncompleteChar: '\\u2591',\n hideCursor: true\n });\n\n this.progressBar.start(total, 0);\n }\n\n /**\n * Updates progress bar\n */\n updateProgress(value: number, payload?: object): void {\n if (this.progressBar) {\n this.progressBar.update(value, payload);\n }\n }\n\n /**\n * Stops and clears progress bar\n */\n stopProgress(): void {\n if (this.progressBar) {\n this.progressBar.stop();\n this.progressBar = null;\n }\n }\n\n /**\n * Creates a cost anomaly alert box\n */\n createAnomalyAlert(anomalies: Array<{\n date: string;\n actualCost: number;\n expectedCost: number;\n deviation: number;\n severity: string;\n description?: string;\n }>): string {\n if (anomalies.length === 0) {\n return chalk.green('✅ No cost anomalies detected');\n }\n\n let output = '\\n' + chalk.bold.red('🚨 Cost Anomalies Detected') + '\\n';\n output += '═'.repeat(50) + '\\n\\n';\n\n anomalies.forEach(anomaly => {\n const severityColor = this.getSeverityColor(anomaly.severity);\n const icon = this.getSeverityIcon(anomaly.severity);\n\n output += chalk[severityColor](`${icon} ${anomaly.date}\\n`);\n output += ` Expected: ${this.formatCurrency(anomaly.expectedCost, 'USD')}\\n`;\n output += ` Actual: ${this.formatCurrency(anomaly.actualCost, 'USD')}\\n`;\n output += ` Deviation: ${anomaly.deviation > 0 ? '+' : ''}${anomaly.deviation.toFixed(1)}%\\n`;\n\n if (anomaly.description) {\n output += ` ${chalk.gray(anomaly.description)}\\n`;\n }\n output += '\\n';\n });\n\n return output;\n }\n\n /**\n * Creates a fancy header with branding\n */\n createHeader(title: string, subtitle?: string): string {\n const width = 60;\n let output = '\\n';\n\n // Top border\n output += chalk.cyan('┌' + '─'.repeat(width - 2) + '┐') + '\\n';\n\n // Title line\n const titlePadding = Math.floor((width - title.length - 4) / 2);\n output += chalk.cyan('│') + ' '.repeat(titlePadding) + chalk.bold.white(title) +\n ' '.repeat(width - title.length - titlePadding - 2) + chalk.cyan('│') + '\\n';\n\n // Subtitle if provided\n if (subtitle) {\n const subtitlePadding = Math.floor((width - subtitle.length - 4) / 2);\n output += chalk.cyan('│') + ' '.repeat(subtitlePadding) + chalk.gray(subtitle) +\n ' '.repeat(width - subtitle.length - subtitlePadding - 2) + chalk.cyan('│') + '\\n';\n }\n\n // Bottom border\n output += chalk.cyan('└' + '─'.repeat(width - 2) + '┘') + '\\n\\n';\n\n return output;\n }\n\n // Helper methods\n private formatCurrency(amount: number, currency: string): string {\n return new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: currency,\n minimumFractionDigits: 2,\n maximumFractionDigits: 2\n }).format(amount);\n }\n\n private calculateChange(current: number, previous: number): string {\n if (previous === 0) return '';\n\n const change = ((current - previous) / previous) * 100;\n const changeStr = `${change >= 0 ? '+' : ''}${change.toFixed(1)}%`;\n\n if (change > 0) {\n return chalk.red(`↗ ${changeStr}`);\n } else if (change < 0) {\n return chalk.green(`↘ ${changeStr}`);\n } else {\n return chalk.gray('→ 0.0%');\n }\n }\n\n private getTrendIndicator(current: number, previous: number): string {\n if (previous === 0) return chalk.gray('─');\n\n const change = ((current - previous) / previous) * 100;\n\n if (change > 10) return chalk.red('↗↗');\n if (change > 0) return chalk.yellow('↗');\n if (change < -10) return chalk.green('↘↘');\n if (change < 0) return chalk.green('↘');\n return chalk.gray('→');\n }\n\n private colorizeBar(bar: string, normalizedValue: number, threshold?: number): string {\n const thresholdValue = threshold || 0.7;\n\n if (normalizedValue > thresholdValue) {\n return chalk.red(bar);\n } else if (normalizedValue > 0.4) {\n return chalk.yellow(bar);\n } else {\n return chalk.green(bar);\n }\n }\n\n private formatChangeIndicator(percentage: number): string {\n const indicator = percentage >= 0 ? '↗' : '↘';\n const color = percentage >= 0 ? 'red' : 'green';\n const sign = percentage >= 0 ? '+' : '';\n\n return chalk[color](`${indicator} ${sign}${percentage.toFixed(1)}%`);\n }\n\n private getSeverityColor(severity: string): keyof typeof chalk {\n switch (severity.toLowerCase()) {\n case 'critical': return 'red';\n case 'high': return 'red';\n case 'medium': return 'yellow';\n case 'low': return 'cyan';\n default: return 'gray';\n }\n }\n\n private getSeverityIcon(severity: string): string {\n switch (severity.toLowerCase()) {\n case 'critical': return '🔴';\n case 'high': return '🟠';\n case 'medium': return '🟡';\n case 'low': return '🔵';\n default: return '⚪';\n }\n }\n}\n\nexport default TerminalUIEngine;","#!/usr/bin/env node\n\nimport { MultiCloudDashboard } from '../visualization/multi-cloud-dashboard';\nimport { CloudProvider } from '../types/providers';\n\n/**\n * Demo script to test multi-cloud dashboard functionality\n * This will show what the dashboard looks like even without real cloud credentials\n */\nasync function testMultiCloudDashboard() {\n console.log('🚀 Testing Multi-Cloud Dashboard...\\n');\n\n try {\n const dashboard = new MultiCloudDashboard();\n\n console.log('📊 Test 1: Full Multi-Cloud Dashboard');\n console.log('─'.repeat(50));\n\n const fullDashboard = await dashboard.generateMultiCloudInventoryDashboard();\n console.log(fullDashboard);\n\n console.log('\\n📊 Test 2: Specific Providers Dashboard (AWS + GCP)');\n console.log('─'.repeat(50));\n\n const specificProviders = await dashboard.generateMultiCloudInventoryDashboard([\n CloudProvider.AWS,\n CloudProvider.GOOGLE_CLOUD\n ]);\n console.log(specificProviders);\n\n console.log('\\n✅ Multi-Cloud Dashboard tests completed!');\n console.log('\\n💡 Usage Examples:');\n console.log(' infra-cost --multi-cloud-dashboard');\n console.log(' infra-cost --all-clouds-inventory');\n console.log(' infra-cost --multi-cloud-dashboard --compare-clouds aws,gcp,azure');\n console.log(' infra-cost --inventory --all-profiles');\n\n } catch (error) {\n console.error('❌ Error testing multi-cloud dashboard:', error instanceof Error ? error.message : error);\n }\n}\n\n// Run the test if this file is executed directly\nif (import.meta.url === `file://${process.argv[1]}`) {\n testMultiCloudDashboard();\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,gBAAkB;;;AC8CX,IAAe,uBAAf,MAAoC;AAAA,EAGzC,YAAY,QAAwB;AAClC,SAAK,SAAS;AAAA,EAChB;AAAA,EAcU,uBAAuB,aAAyC;AAGxE,WAAO,KAAK,mBAAmB,WAAW;AAAA,EAC5C;AAAA,EAEQ,mBAAmB,aAAyC;AAClE,UAAM,SAAS;AAAA,MACb,WAAW;AAAA,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