@stacksjs/ts-cloud 0.5.33 → 0.5.35

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/dist/bin/cli.js CHANGED
@@ -3639,7 +3639,7 @@ export const queue = __handlers.queue
3639
3639
  export const cli = __handlers.cli
3640
3640
  `}function RE(){return S8(qE(DE(import.meta.url)),"runtime","adapter.ts")}function OU($,J,Y){for(let Z of $??[])Y?.(`build: ${Z}`),VE(Z,{stdio:"inherit",cwd:J})}function p6($){return AE("sha256").update($).digest("hex")}function QZ($,J,Y){return`deployments/${$}/${J}/${Y}.zip`}async function c8($){let J=wE($.projectRoot??process.cwd()),{app:Y}=$;if(!$.skipBuild)OU(Y.build,J,$.onStep);let Z=Y.entry;if(!Z)throw Error("serverless app: `entry` is required to package a Node/Bun application");let Q=TE(Z)?Z:S8(J,Z),G=jE(S8(ME(),"tscloud-pkg-"));try{_E(RE(),S8(G,"adapter.ts"));let W=S8(G,"bootstrap.ts");EE(W,KU({entryImport:Q,adapterImport:"./adapter"})),$.onStep?.("bundling application");let z=await Bun.build({entrypoints:[W],target:Y.kind==="bun"?"bun":"node",format:"esm",minify:!1,sourcemap:"none"});if(!z.success){let K=z.logs.map((O)=>String(O)).join(`
3641
3641
  `);throw Error(`serverless app bundle failed:
3642
- ${K}`)}let U=z.outputs[0],H=Buffer.from(await U.arrayBuffer()),F="index",B=d$([{name:`${F}.mjs`,data:H}]);return{zip:B,bundle:H,sha256:p6(B),handlerFile:F,handlers:{http:Y.handlers?.http??`${F}.http`,queue:Y.handlers?.queue??`${F}.queue`,cli:Y.handlers?.cli??`${F}.cli`},bundleBytes:H.length}}finally{LE(G,{recursive:!0,force:!0})}}function NE($){if(!$)return"22";let J=String($).match(/(\d+)/);return J?J[1]:"22"}function r6($){let J=$.kind??"node";if(J==="php")return{lambdaRuntime:"provided.al2023",kind:"php",version:$.phpVersion??"8.3",usesLayer:!0,layerKind:"php",layerEnvVar:"TSCLOUD_PHP_LAYER_ARN"};if(J==="bun")return{lambdaRuntime:"provided.al2023",kind:"bun",version:$.runtimeVersion??"latest",usesLayer:!0,layerKind:"bun",layerEnvVar:"TSCLOUD_BUN_LAYER_ARN"};let Y=NE($.runtimeVersion);if($.runtime!=="provided.al2023"&&VU.includes(Y))return{lambdaRuntime:$.runtime&&$.runtime.startsWith("nodejs")?$.runtime:`nodejs${Y}.x`,kind:"node",version:Y,usesLayer:!1};return{lambdaRuntime:"provided.al2023",kind:"node",version:Y,usesLayer:!0,layerKind:"node",layerEnvVar:"TSCLOUD_NODE_LAYER_ARN"}}function m8($,J,Y){if($.queues===!1)return[];if($.queues===void 0||$.queues===!0)return[{name:`${J}-${Y}-default`}];return $.queues.map((Z)=>{if(typeof Z==="string")return{name:`${J}-${Y}-${Z}`};let[Q,G]=Object.entries(Z)[0];return{name:`${J}-${Y}-${Q}`,concurrency:G}})}function GZ($,J,Y){return m8($,J,Y).map((Z)=>Z.name)}function WZ($){let{app:J,environment:Y,handlers:Z}=$,Q=$.config.project.slug,G=r6(J).lambdaRuntime,W=J.architecture??"x86_64",z=$.config.project.region,U={http:`${Q}-${Y}-http`,queue:`${Q}-${Y}-queue`,cli:`${Q}-${Y}-cli`};if(J.gatewayVersion===1)throw Error("serverless app: `gatewayVersion: 1` (REST API) is not supported — ts-cloud uses API Gateway HTTP API (v2). Remove `gatewayVersion` or set it to 2.");let H=m8(J,Q,Y),F=H.map((H0)=>H0.name),B=F.length>0,K=J.logRetention??14,O=J.packaging==="image",A=(J.scheduler??"on")!=="off",V=(J.cache?.driver??"dynamodb")==="dynamodb",_=Boolean(J.assets),E=u6(Q,Y),M=J.tmpStorage??512,j={},q={},T=[{PolicyName:"tscloud-serverless-app",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:L.sub("arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*")},{Effect:"Allow",Action:["lambda:InvokeFunction"],Resource:L.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${Q}-${Y}-*`)},{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameter","ssm:GetParameters","ssm:GetParametersByPath"],Resource:[L.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${Q}/${Y}/*`),L.sub(`arn:aws:ssm:\${AWS::Region}:\${AWS::AccountId}:parameter/${Q}/${Y}/*`)]},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[L.sub(`arn:aws:s3:::${E}`),L.sub(`arn:aws:s3:::${E}/*`),...J.storage?.bucket?[L.sub(`arn:aws:s3:::${J.storage.bucket}`),L.sub(`arn:aws:s3:::${J.storage.bucket}/*`)]:[]]}]}}];if(B)T[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["sqs:SendMessage","sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","sqs:GetQueueUrl"],Resource:L.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${Q}-${Y}-*`)});if(V)T[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchGetItem","dynamodb:BatchWriteItem"],Resource:L.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${Q}-${Y}-cache*`)});let D=["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"];if(J.vpc?.subnets?.length)D.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");j.AppRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${Q}-${Y}-app-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:D,Policies:T}};let S=(H0)=>({TSCLOUD_LAMBDA_MODE:H0,TSCLOUD_ENV:Y,...J.octane?{TSCLOUD_OCTANE:"1"}:{},...J.scheduler==="sub-minute"?{TSCLOUD_SCHEDULER:"sub-minute"}:{},...V?{TSCLOUD_CACHE_TABLE:`${Q}-${Y}-cache`}:{},...B?{TSCLOUD_QUEUE:F[0]}:{},...J.env??{}}),P=Boolean(J.efs),C=typeof J.efs==="object"?J.efs:{},I=C.mountPath??"/mnt/local",b=P&&!C.accessPointArn,y=C.accessPointArn??(b?L.getAtt("EfsAccessPoint","Arn"):void 0),c=J.vpc?.subnets??[],r=c.length>0,d=J.cache?.driver==="elasticache"||J.database?.connection==="aurora-serverless"||Boolean(J.rdsProxy)||P;if(d&&!r)throw Error("serverless app: elasticache / aurora-serverless / rdsProxy / efs require app.vpc.subnets (private subnets) to be set.");let g=r?{VpcConfig:{SubnetIds:c,SecurityGroupIds:[...J.vpc?.securityGroups??[],...d?[L.getAtt("DataSecurityGroup","GroupId")]:[]]}}:{},s=b?c.map((H0,D0)=>`EfsMountTarget${D0}`):[],J0=P?{FileSystemConfigs:[{Arn:y,LocalMountPath:I}]}:{};if(P)T[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:ClientRootAccess","elasticfilesystem:DescribeMountTargets"],Resource:"*"});function t(H0,D0,f0,P0,$2,Y5,W8,t2=M){j[`${H0}LogGroup`]={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/aws/lambda/${D0}`,RetentionInDays:K}};let P9=O?{PackageType:"Image",Code:{ImageUri:L.ref("ImageUri")},...J.kind==="php"?{}:{ImageConfig:{Command:[f0]}}}:{Runtime:G,Handler:f0,Code:{S3Bucket:L.ref("ArtifactBucket"),S3Key:L.ref("ArtifactKey")},...$.runtimeLayers?.length?{Layers:$.runtimeLayers}:{}};j[H0]={Type:"AWS::Lambda::Function",DependsOn:[`${H0}LogGroup`,...s],Properties:{FunctionName:D0,Architectures:[W],MemorySize:$2,Timeout:Y5,Role:L.getAtt("AppRole","Arn"),Environment:{Variables:S(P0)},EphemeralStorage:{Size:t2},...P9,...W8!==void 0?{ReservedConcurrentExecutions:W8}:{},...g,...J0}}}if(t("HttpFunction",U.http,Z.http,"http",J.memory??1024,J.timeout??28,J.concurrency,M),t("CliFunction",U.cli,Z.cli,"cli",J.cliMemory??1024,J.cliTimeout??900,void 0,J.cliTmpStorage??M),B)t("QueueFunction",U.queue,Z.queue,"queue",J.queueMemory??1024,J.queueTimeout??120,void 0,J.queueTmpStorage??M);let a=(J.provisionedConcurrency??0)>0?J.provisionedConcurrency:0,e=["HttpFunction","CliFunction",...B?["QueueFunction"]:[]];if(a)for(let H0 of e)j[`${H0}Version`]={Type:"AWS::Lambda::Version",DeletionPolicy:"Retain",Properties:{FunctionName:L.ref(H0)}},j[`${H0}Alias`]={Type:"AWS::Lambda::Alias",Properties:{FunctionName:L.ref(H0),Name:"live",FunctionVersion:L.getAtt(`${H0}Version`,"Version"),ProvisionedConcurrencyConfig:{ProvisionedConcurrentExecutions:a}}};let j0=(H0)=>a?L.ref(`${H0}Alias`):L.getAtt(H0,"Arn"),w0=(H0)=>a?L.ref(`${H0}Alias`):L.ref(H0);j.HttpApi={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:`${Q}-${Y}`,ProtocolType:"HTTP"}},j.HttpIntegration={Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:L.ref("HttpApi"),IntegrationType:"AWS_PROXY",IntegrationUri:j0("HttpFunction"),PayloadFormatVersion:"2.0"}},j.HttpRoute={Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:L.ref("HttpApi"),RouteKey:"$default",Target:L.join("/",["integrations",L.ref("HttpIntegration")])}},j.HttpStage={Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:L.ref("HttpApi"),StageName:"$default",AutoDeploy:!0}},j.HttpPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:w0("HttpFunction"),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:L.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*/*")}},q.HttpApiEndpoint={Description:"HTTP API endpoint",Value:L.getAtt("HttpApi","ApiEndpoint")},q.HttpApiId={Description:"HTTP API id",Value:L.ref("HttpApi")};let B0=(Array.isArray(J.domain)?J.domain:J.domain?[J.domain]:[]).filter(Boolean);if(B0.length){if(!J.certificateArn&&!J.hostedZoneId)throw Error("serverless app: a custom `domain` needs either `certificateArn` (pre-issued, regional) or `hostedZoneId` (to auto-issue + validate an ACM cert).");let H0=J.certificateArn;if(!H0)j.HttpCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:B0[0],...B0.length>1?{SubjectAlternativeNames:B0.slice(1)}:{},ValidationMethod:"DNS",DomainValidationOptions:B0.map((D0)=>({DomainName:D0,HostedZoneId:J.hostedZoneId}))}},H0=L.ref("HttpCertificate");B0.forEach((D0,f0)=>{let P0=`HttpDomain${f0}`;if(j[P0]={Type:"AWS::ApiGatewayV2::DomainName",Properties:{DomainName:D0,DomainNameConfigurations:[{CertificateArn:H0,EndpointType:"REGIONAL"}]}},j[`HttpApiMapping${f0}`]={Type:"AWS::ApiGatewayV2::ApiMapping",DependsOn:["HttpStage"],Properties:{ApiId:L.ref("HttpApi"),DomainName:L.ref(P0),Stage:"$default"}},J.hostedZoneId)j[`HttpDomainRecord${f0}`]={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:J.hostedZoneId,Name:D0,Type:"A",AliasTarget:{DNSName:L.getAtt(P0,"RegionalDomainName"),HostedZoneId:L.getAtt(P0,"RegionalHostedZoneId")}}};q[`CustomDomain${f0}`]={Description:`Custom domain ${D0}`,Value:D0},q[`CustomDomainTarget${f0}`]={Description:`Point ${D0} (CNAME/alias) at this APIGW regional domain`,Value:L.getAtt(P0,"RegionalDomainName")}})}if(B)j.AppQueueDlq={Type:"AWS::SQS::Queue",Properties:{QueueName:`${Q}-${Y}-dlq`,MessageRetentionPeriod:1209600}},H.forEach((H0,D0)=>{let f0=`AppQueue${D0}`,P0=J.queueTimeout??120;j[f0]={Type:"AWS::SQS::Queue",Properties:{QueueName:H0.name,VisibilityTimeout:Math.min(43200,P0*6),RedrivePolicy:{deadLetterTargetArn:L.getAtt("AppQueueDlq","Arn"),maxReceiveCount:J.queueTries??3}}};let $2=H0.concurrency??J.queueConcurrency;j[`${f0}Mapping`]={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:L.getAtt(f0,"Arn"),FunctionName:w0("QueueFunction"),BatchSize:1,FunctionResponseTypes:["ReportBatchItemFailures"],...$2?{ScalingConfig:{MaximumConcurrency:Math.max(2,$2)}}:{}}},q[`QueueUrl${D0}`]={Description:`Queue URL: ${H0.name}`,Value:L.ref(f0)}});if(A)j.SchedulerRule={Type:"AWS::Events::Rule",Properties:{Name:`${Q}-${Y}-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"cli",Arn:j0("CliFunction"),Input:JSON.stringify({command:"schedule:run"})}]}},j.SchedulerPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:w0("CliFunction"),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:L.getAtt("SchedulerRule","Arn")}};if(J.warm&&J.warm>0){let D0={http:"HttpFunction",queue:"QueueFunction",cli:"CliFunction"},f0=(J.warmFunctions??["http"]).filter((P0)=>P0!=="queue"||B);for(let P0 of f0){let $2=P0.charAt(0).toUpperCase()+P0.slice(1),Y5=Math.ceil(J.warm/5),W8=0;for(let t2=0;t2<Y5;t2++){let P9=Math.min(5,J.warm-W8);j[`Warmer${$2}Rule${t2}`]={Type:"AWS::Events::Rule",Properties:{Name:`${Q}-${Y}-warmer-${P0}-${t2}`,ScheduleExpression:"rate(5 minutes)",State:"ENABLED",Targets:Array.from({length:P9},(Fw,_X)=>({Id:`warm-${P0}-${t2}-${_X}`,Arn:L.getAtt(D0[P0],"Arn"),Input:JSON.stringify({warmer:!0})}))}},W8+=P9}j[`Warmer${$2}Permission`]={Type:"AWS::Lambda::Permission",Properties:{FunctionName:L.ref(D0[P0]),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:L.sub(`arn:aws:events:\${AWS::Region}:\${AWS::AccountId}:rule/${Q}-${Y}-warmer-${P0}-*`)}}}}if(V)j.CacheTable={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${Q}-${Y}-cache`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"key",AttributeType:"S"}],KeySchema:[{AttributeName:"key",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"expires_at",Enabled:!0}}},q.CacheTableName={Description:"DynamoDB cache table",Value:L.ref("CacheTable")};if(_){if(j.AssetsBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:E,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}}},j.AssetsOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${Q}-${Y}-assets-oac`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},j.AssetsDistribution={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,DefaultCacheBehavior:{TargetOriginId:"assets",ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},Origins:[{Id:"assets",DomainName:L.getAtt("AssetsBucket","RegionalDomainName"),OriginAccessControlId:L.ref("AssetsOAC"),S3OriginConfig:{OriginAccessIdentity:""}}],...J.assetDomain?{Aliases:[J.assetDomain],ViewerCertificate:{AcmCertificateArn:J.assetCertificateArn??L.ref("AssetsCertificate"),SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}}:{}}}},J.assetDomain){if(!J.assetCertificateArn){if(!J.hostedZoneId)throw Error("serverless app: `assetDomain` requires either `assetCertificateArn` (a us-east-1 ACM cert) or `hostedZoneId` (to auto-issue + validate one). CloudFront only accepts certs from us-east-1.");if(z!=="us-east-1")throw Error(`serverless app: auto-issuing an asset-domain cert needs a us-east-1 app (CloudFront certs must be us-east-1); this app is in ${z}. Supply a pre-issued us-east-1 \`assetCertificateArn\` instead.`);j.AssetsCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:J.assetDomain,ValidationMethod:"DNS",DomainValidationOptions:[{DomainName:J.assetDomain,HostedZoneId:J.hostedZoneId}]}}}if(J.hostedZoneId)j.AssetsDomainRecord={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:J.hostedZoneId,Name:J.assetDomain,Type:"A",AliasTarget:{DNSName:L.getAtt("AssetsDistribution","DomainName"),HostedZoneId:"Z2FDTNDATAQYW2"}}};q.AssetDomain={Description:"Custom asset CDN host",Value:J.assetDomain}}j.AssetsBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:L.ref("AssetsBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:L.sub(`arn:aws:s3:::${E}/*`),Condition:{StringEquals:{"AWS:SourceArn":L.sub("arn:aws:cloudfront::${AWS::AccountId}:distribution/${AssetsDistribution}")}}}]}}},q.AssetsBucketName={Description:"Assets bucket",Value:L.ref("AssetsBucket")},q.AssetsCdnDomain={Description:"Assets CloudFront domain",Value:L.getAtt("AssetsDistribution","DomainName")}}if(J.firewall?.enabled){let H0=[],D0=0;if(J.firewall.rateLimit)H0.push({Name:"rate-limit",Priority:D0++,Action:{Block:{}},Statement:{RateBasedStatement:{Limit:J.firewall.rateLimit,AggregateKeyType:"IP"}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${Q}-${Y}-rate`}});let f0={sqlInjection:"AWSManagedRulesSQLiRuleSet",xss:"AWSManagedRulesCommonRuleSet",common:"AWSManagedRulesCommonRuleSet",botControl:"AWSManagedRulesBotControlRuleSet",ipReputation:"AWSManagedRulesAmazonIpReputationList"};for(let P0 of J.firewall.rules??[]){let $2=f0[P0];if(!$2)continue;H0.push({Name:`managed-${P0}`,Priority:D0++,OverrideAction:{None:{}},Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:$2}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${Q}-${Y}-${P0}`}})}j.WebAcl={Type:"AWS::WAFv2::WebACL",Properties:{Name:`${Q}-${Y}-waf`,Scope:"REGIONAL",DefaultAction:{Allow:{}},Rules:H0,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${Q}-${Y}-waf`}}},q.WafAclArn={Description:"WAF web ACL ARN. Attach to a CloudFront distribution fronting the API to enforce (HTTP API v2 stages do not support direct WAF association).",Value:L.getAtt("WebAcl","Arn")}}if(r&&d){if(!J.vpc?.id)throw Error("serverless app: data services (elasticache / aurora-serverless / rdsProxy / efs) need app.vpc.id (the VPC id) so the managed security group is created in the right VPC.");j.DataSecurityGroup={Type:"AWS::EC2::SecurityGroup",Properties:{VpcId:J.vpc.id,GroupDescription:`${Q}-${Y} serverless data access`,SecurityGroupIngress:[{IpProtocol:"-1",CidrIp:"10.0.0.0/8"}]}}}if(b)j.EfsFileSystem={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:!0,FileSystemTags:[{Key:"Name",Value:`${Q}-${Y}-efs`}]}},c.forEach((H0,D0)=>{j[`EfsMountTarget${D0}`]={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:L.ref("EfsFileSystem"),SubnetId:H0,SecurityGroups:[L.getAtt("DataSecurityGroup","GroupId")]}}}),j.EfsAccessPoint={Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:L.ref("EfsFileSystem"),PosixUser:{Uid:1001,Gid:1001},RootDirectory:{Path:"/lambda",CreationInfo:{OwnerUid:1001,OwnerGid:1001,Permissions:"0755"}}}},q.EfsFileSystemId={Description:"EFS file system id",Value:L.ref("EfsFileSystem")};if(J.cache?.driver==="elasticache")j.CacheSubnetGroup={Type:"AWS::ElastiCache::SubnetGroup",Properties:{Description:`${Q}-${Y} cache subnets`,SubnetIds:c}},j.CacheCluster={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:`${Q}-${Y}-cache`,ReplicationGroupDescription:`${Q}-${Y} redis`,Engine:"redis",CacheNodeType:"cache.t4g.micro",NumCacheClusters:1,AutomaticFailoverEnabled:!1,CacheSubnetGroupName:L.ref("CacheSubnetGroup"),SecurityGroupIds:[L.getAtt("DataSecurityGroup","GroupId")],TransitEncryptionEnabled:!1}},q.CacheEndpoint={Description:"Redis primary endpoint",Value:L.getAtt("CacheCluster","PrimaryEndPoint.Address")};if(J.database?.connection==="aurora-serverless")j.DbSubnetGroup={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupDescription:`${Q}-${Y} db subnets`,SubnetIds:c}},j.DbSecret={Type:"AWS::SecretsManager::Secret",Properties:{Name:`${Q}/${Y}/db`,GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"app"}),GenerateStringKey:"password",PasswordLength:32,ExcludePunctuation:!0}}},j.DbCluster={Type:"AWS::RDS::DBCluster",Properties:{Engine:"aurora-mysql",EngineMode:"provisioned",DBClusterIdentifier:`${Q}-${Y}-db`,DatabaseName:"app",MasterUsername:L.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:username}}"),MasterUserPassword:L.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:password}}"),ServerlessV2ScalingConfiguration:{MinCapacity:J.database?.minCapacity??0.5,MaxCapacity:J.database?.maxCapacity??4},DBSubnetGroupName:L.ref("DbSubnetGroup"),VpcSecurityGroupIds:[L.getAtt("DataSecurityGroup","GroupId")]}},j.DbInstance={Type:"AWS::RDS::DBInstance",Properties:{Engine:"aurora-mysql",DBInstanceClass:"db.serverless",DBClusterIdentifier:L.ref("DbCluster")}},q.DbEndpoint={Description:"Aurora cluster endpoint",Value:L.getAtt("DbCluster","Endpoint.Address")};if(J.rdsProxy&&J.database?.connection==="aurora-serverless")j.DbProxyRole={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"rds.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"read-db-secret",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue"],Resource:L.ref("DbSecret")}]}}]}},j.DbProxy={Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:typeof J.rdsProxy==="object"&&J.rdsProxy.name?J.rdsProxy.name:`${Q}-${Y}-proxy`,EngineFamily:"MYSQL",RoleArn:L.getAtt("DbProxyRole","Arn"),Auth:[{AuthScheme:"SECRETS",SecretArn:L.ref("DbSecret"),IAMAuth:"DISABLED"}],VpcSubnetIds:c,VpcSecurityGroupIds:[L.getAtt("DataSecurityGroup","GroupId")],RequireTLS:!1}},j.DbProxyTargetGroup={Type:"AWS::RDS::DBProxyTargetGroup",DependsOn:["DbInstance"],Properties:{DBProxyName:L.ref("DbProxy"),TargetGroupName:"default",DBClusterIdentifiers:[L.ref("DbCluster")]}},q.DbProxyEndpoint={Description:"RDS Proxy endpoint",Value:L.getAtt("DbProxy","Endpoint")};if(q.HttpFunctionName={Description:"HTTP function name",Value:L.ref("HttpFunction")},q.CliFunctionName={Description:"CLI function name",Value:L.ref("CliFunction")},B)q.QueueFunctionName={Description:"Queue function name",Value:L.ref("QueueFunction")};let X1={AWSTemplateFormatVersion:"2010-09-09",Description:`Serverless application for ${$.config.project.name} (${Q}-${Y})`,Parameters:O?{ImageUri:{Type:"String",Description:"ECR image URI of the deployment artifact"}}:{ArtifactBucket:{Type:"String",Description:"S3 bucket holding the deployment artifact"},ArtifactKey:{Type:"String",Description:"S3 key of the deployment artifact (zip)"}},Resources:j,Outputs:q},d1={};for(let H0 of Object.values(j))d1[H0.Type]=(d1[H0.Type]??0)+1;return{template:X1,functionNames:U,queueNames:F,resourceSummary:d1}}function _U($){let J=`php${$.replace(".","")}`;return AU.map((Y)=>`${J}-php-${Y}`)}function zZ($,J){let Y=`php${$.replace(".","")}`,Z=_U($).join(" \\\n "),Q=`/opt/remi/${Y}/root`,G=`/etc/opt/remi/${Y}`;return`${J?`FROM almalinux:9 AS ${J}`:"FROM almalinux:9"}
3642
+ ${K}`)}let U=z.outputs[0],H=Buffer.from(await U.arrayBuffer()),F="index",B=d$([{name:`${F}.mjs`,data:H}]);return{zip:B,bundle:H,sha256:p6(B),handlerFile:F,handlers:{http:Y.handlers?.http??`${F}.http`,queue:Y.handlers?.queue??`${F}.queue`,cli:Y.handlers?.cli??`${F}.cli`},bundleBytes:H.length}}finally{LE(G,{recursive:!0,force:!0})}}function NE($){if(!$)return"22";let J=String($).match(/(\d+)/);return J?J[1]:"22"}function r6($){let J=$.kind??"node";if(J==="php")return{lambdaRuntime:"provided.al2023",kind:"php",version:$.phpVersion??"8.3",usesLayer:!0,layerKind:"php",layerEnvVar:"TSCLOUD_PHP_LAYER_ARN"};if(J==="bun")return{lambdaRuntime:"provided.al2023",kind:"bun",version:$.runtimeVersion??"latest",usesLayer:!0,layerKind:"bun",layerEnvVar:"TSCLOUD_BUN_LAYER_ARN"};let Y=NE($.runtimeVersion);if($.runtime!=="provided.al2023"&&VU.includes(Y))return{lambdaRuntime:$.runtime&&$.runtime.startsWith("nodejs")?$.runtime:`nodejs${Y}.x`,kind:"node",version:Y,usesLayer:!1};return{lambdaRuntime:"provided.al2023",kind:"node",version:Y,usesLayer:!0,layerKind:"node",layerEnvVar:"TSCLOUD_NODE_LAYER_ARN"}}function m8($,J,Y){if($.queues===!1)return[];if($.queues===void 0||$.queues===!0)return[{name:`${J}-${Y}-default`}];return $.queues.map((Z)=>{if(typeof Z==="string")return{name:`${J}-${Y}-${Z}`};let[Q,G]=Object.entries(Z)[0];return{name:`${J}-${Y}-${Q}`,concurrency:G}})}function GZ($,J,Y){return m8($,J,Y).map((Z)=>Z.name)}function WZ($){let{app:J,environment:Y,handlers:Z}=$,Q=$.config.project.slug,G=r6(J).lambdaRuntime,W=J.architecture??"x86_64",z=$.config.project.region,U={http:`${Q}-${Y}-http`,queue:`${Q}-${Y}-queue`,cli:`${Q}-${Y}-cli`};if(J.gatewayVersion===1)throw Error("serverless app: `gatewayVersion: 1` (REST API) is not supported — ts-cloud uses API Gateway HTTP API (v2). Remove `gatewayVersion` or set it to 2.");let H=m8(J,Q,Y),F=H.map((H0)=>H0.name),B=F.length>0,K=J.logRetention??14,O=J.packaging==="image",A=(J.scheduler??"on")!=="off",V=(J.cache?.driver??"dynamodb")==="dynamodb",_=Boolean(J.assets),E=u6(Q,Y),M=J.tmpStorage??512,j={},q={},T=[{PolicyName:"tscloud-serverless-app",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:L.sub("arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*")},{Effect:"Allow",Action:["lambda:InvokeFunction"],Resource:L.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${Q}-${Y}-*`)},{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameter","ssm:GetParameters","ssm:GetParametersByPath"],Resource:[L.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${Q}/${Y}/*`),L.sub(`arn:aws:ssm:\${AWS::Region}:\${AWS::AccountId}:parameter/${Q}/${Y}/*`)]},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[L.sub(`arn:aws:s3:::${E}`),L.sub(`arn:aws:s3:::${E}/*`),...J.storage?.bucket?[L.sub(`arn:aws:s3:::${J.storage.bucket}`),L.sub(`arn:aws:s3:::${J.storage.bucket}/*`)]:[]]}]}}];if(B)T[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["sqs:SendMessage","sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","sqs:GetQueueUrl"],Resource:L.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${Q}-${Y}-*`)});if(V)T[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchGetItem","dynamodb:BatchWriteItem"],Resource:L.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${Q}-${Y}-cache*`)});let D=["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"];if(J.vpc?.subnets?.length)D.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");j.AppRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${Q}-${Y}-app-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:D,Policies:T}};let S=(H0)=>({TSCLOUD_LAMBDA_MODE:H0,TSCLOUD_ENV:Y,...J.octane?{TSCLOUD_OCTANE:"1"}:{},...J.scheduler==="sub-minute"?{TSCLOUD_SCHEDULER:"sub-minute"}:{},...V?{TSCLOUD_CACHE_TABLE:`${Q}-${Y}-cache`}:{},...B?{TSCLOUD_QUEUE:F[0]}:{},...J.env??{}}),P=Boolean(J.efs),C=typeof J.efs==="object"?J.efs:{},I=C.mountPath??"/mnt/local",b=P&&!C.accessPointArn,y=C.accessPointArn??(b?L.getAtt("EfsAccessPoint","Arn"):void 0),c=J.vpc?.subnets??[],r=c.length>0,d=J.cache?.driver==="elasticache"||J.database?.connection==="aurora-serverless"||Boolean(J.rdsProxy)||P;if(d&&!r)throw Error("serverless app: elasticache / aurora-serverless / rdsProxy / efs require app.vpc.subnets (private subnets) to be set.");let g=r?{VpcConfig:{SubnetIds:c,SecurityGroupIds:[...J.vpc?.securityGroups??[],...d?[L.getAtt("DataSecurityGroup","GroupId")]:[]]}}:{},s=b?c.map((H0,D0)=>`EfsMountTarget${D0}`):[],J0=P?{FileSystemConfigs:[{Arn:y,LocalMountPath:I}]}:{};if(P)T[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:ClientRootAccess","elasticfilesystem:DescribeMountTargets"],Resource:"*"});function t(H0,D0,f0,P0,$2,Y5,W8,t2=M){j[`${H0}LogGroup`]={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/aws/lambda/${D0}`,RetentionInDays:K}};let P9=O?{PackageType:"Image",Code:{ImageUri:L.ref("ImageUri")},...J.kind==="php"?{}:{ImageConfig:{Command:[f0]}}}:{Runtime:G,Handler:f0,Code:{S3Bucket:L.ref("ArtifactBucket"),S3Key:L.ref("ArtifactKey")},...$.runtimeLayers?.length?{Layers:$.runtimeLayers}:{}};j[H0]={Type:"AWS::Lambda::Function",DependsOn:[`${H0}LogGroup`,...s],Properties:{FunctionName:D0,Architectures:[W],MemorySize:$2,Timeout:Y5,Role:L.getAtt("AppRole","Arn"),Environment:{Variables:S(P0)},EphemeralStorage:{Size:t2},...P9,...W8!==void 0?{ReservedConcurrentExecutions:W8}:{},...g,...J0}}}if(t("HttpFunction",U.http,Z.http,"http",J.memory??1024,J.timeout??28,J.concurrency,M),t("CliFunction",U.cli,Z.cli,"cli",J.cliMemory??1024,J.cliTimeout??900,void 0,J.cliTmpStorage??M),B)t("QueueFunction",U.queue,Z.queue,"queue",J.queueMemory??1024,J.queueTimeout??120,void 0,J.queueTmpStorage??M);let a=(J.provisionedConcurrency??0)>0?J.provisionedConcurrency:0,e=["HttpFunction","CliFunction",...B?["QueueFunction"]:[]];if(a)for(let H0 of e)j[`${H0}Version`]={Type:"AWS::Lambda::Version",DeletionPolicy:"Retain",Properties:{FunctionName:L.ref(H0)}},j[`${H0}Alias`]={Type:"AWS::Lambda::Alias",Properties:{FunctionName:L.ref(H0),Name:"live",FunctionVersion:L.getAtt(`${H0}Version`,"Version"),ProvisionedConcurrencyConfig:{ProvisionedConcurrentExecutions:a}}};let j0=(H0)=>a?L.ref(`${H0}Alias`):L.getAtt(H0,"Arn"),w0=(H0)=>a?L.ref(`${H0}Alias`):L.ref(H0);j.HttpApi={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:`${Q}-${Y}`,ProtocolType:"HTTP"}},j.HttpIntegration={Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:L.ref("HttpApi"),IntegrationType:"AWS_PROXY",IntegrationUri:j0("HttpFunction"),PayloadFormatVersion:"2.0"}},j.HttpRoute={Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:L.ref("HttpApi"),RouteKey:"$default",Target:L.join("/",["integrations",L.ref("HttpIntegration")])}},j.HttpStage={Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:L.ref("HttpApi"),StageName:"$default",AutoDeploy:!0}},j.HttpPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:w0("HttpFunction"),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:L.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*/*")}},q.HttpApiEndpoint={Description:"HTTP API endpoint",Value:L.getAtt("HttpApi","ApiEndpoint")},q.HttpApiId={Description:"HTTP API id",Value:L.ref("HttpApi")};let B0=(Array.isArray(J.domain)?J.domain:J.domain?[J.domain]:[]).filter(Boolean);if(B0.length){if(!J.certificateArn&&!J.hostedZoneId)throw Error("serverless app: a custom `domain` needs either `certificateArn` (pre-issued, regional) or `hostedZoneId` (to auto-issue + validate an ACM cert).");let H0=J.certificateArn;if(!H0)j.HttpCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:B0[0],...B0.length>1?{SubjectAlternativeNames:B0.slice(1)}:{},ValidationMethod:"DNS",DomainValidationOptions:B0.map((D0)=>({DomainName:D0,HostedZoneId:J.hostedZoneId}))}},H0=L.ref("HttpCertificate");B0.forEach((D0,f0)=>{let P0=`HttpDomain${f0}`;if(j[P0]={Type:"AWS::ApiGatewayV2::DomainName",Properties:{DomainName:D0,DomainNameConfigurations:[{CertificateArn:H0,EndpointType:"REGIONAL"}]}},j[`HttpApiMapping${f0}`]={Type:"AWS::ApiGatewayV2::ApiMapping",DependsOn:["HttpStage"],Properties:{ApiId:L.ref("HttpApi"),DomainName:L.ref(P0),Stage:"$default"}},J.hostedZoneId)j[`HttpDomainRecord${f0}`]={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:J.hostedZoneId,Name:D0,Type:"A",AliasTarget:{DNSName:L.getAtt(P0,"RegionalDomainName"),HostedZoneId:L.getAtt(P0,"RegionalHostedZoneId")}}};q[`CustomDomain${f0}`]={Description:`Custom domain ${D0}`,Value:D0},q[`CustomDomainTarget${f0}`]={Description:`Point ${D0} (CNAME/alias) at this APIGW regional domain`,Value:L.getAtt(P0,"RegionalDomainName")}})}if(B)j.AppQueueDlq={Type:"AWS::SQS::Queue",Properties:{QueueName:`${Q}-${Y}-dlq`,MessageRetentionPeriod:1209600}},H.forEach((H0,D0)=>{let f0=`AppQueue${D0}`,P0=J.queueTimeout??120;j[f0]={Type:"AWS::SQS::Queue",Properties:{QueueName:H0.name,VisibilityTimeout:Math.min(43200,P0*6),RedrivePolicy:{deadLetterTargetArn:L.getAtt("AppQueueDlq","Arn"),maxReceiveCount:J.queueTries??3}}};let $2=H0.concurrency??J.queueConcurrency;j[`${f0}Mapping`]={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:L.getAtt(f0,"Arn"),FunctionName:w0("QueueFunction"),BatchSize:1,FunctionResponseTypes:["ReportBatchItemFailures"],...$2?{ScalingConfig:{MaximumConcurrency:Math.max(2,$2)}}:{}}},q[`QueueUrl${D0}`]={Description:`Queue URL: ${H0.name}`,Value:L.ref(f0)}});if(A)j.SchedulerRule={Type:"AWS::Events::Rule",Properties:{Name:`${Q}-${Y}-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"cli",Arn:j0("CliFunction"),Input:JSON.stringify({command:"schedule:run"})}]}},j.SchedulerPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:w0("CliFunction"),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:L.getAtt("SchedulerRule","Arn")}};if(J.warm&&J.warm>0){let D0={http:"HttpFunction",queue:"QueueFunction",cli:"CliFunction"},f0=(J.warmFunctions??["http"]).filter((P0)=>P0!=="queue"||B);for(let P0 of f0){let $2=P0.charAt(0).toUpperCase()+P0.slice(1),Y5=Math.ceil(J.warm/5),W8=0;for(let t2=0;t2<Y5;t2++){let P9=Math.min(5,J.warm-W8);j[`Warmer${$2}Rule${t2}`]={Type:"AWS::Events::Rule",Properties:{Name:`${Q}-${Y}-warmer-${P0}-${t2}`,ScheduleExpression:"rate(5 minutes)",State:"ENABLED",Targets:Array.from({length:P9},(Hw,_X)=>({Id:`warm-${P0}-${t2}-${_X}`,Arn:L.getAtt(D0[P0],"Arn"),Input:JSON.stringify({warmer:!0})}))}},W8+=P9}j[`Warmer${$2}Permission`]={Type:"AWS::Lambda::Permission",Properties:{FunctionName:L.ref(D0[P0]),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:L.sub(`arn:aws:events:\${AWS::Region}:\${AWS::AccountId}:rule/${Q}-${Y}-warmer-${P0}-*`)}}}}if(V)j.CacheTable={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${Q}-${Y}-cache`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"key",AttributeType:"S"}],KeySchema:[{AttributeName:"key",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"expires_at",Enabled:!0}}},q.CacheTableName={Description:"DynamoDB cache table",Value:L.ref("CacheTable")};if(_){if(j.AssetsBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:E,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}}},j.AssetsOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${Q}-${Y}-assets-oac`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},j.AssetsDistribution={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,DefaultCacheBehavior:{TargetOriginId:"assets",ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},Origins:[{Id:"assets",DomainName:L.getAtt("AssetsBucket","RegionalDomainName"),OriginAccessControlId:L.ref("AssetsOAC"),S3OriginConfig:{OriginAccessIdentity:""}}],...J.assetDomain?{Aliases:[J.assetDomain],ViewerCertificate:{AcmCertificateArn:J.assetCertificateArn??L.ref("AssetsCertificate"),SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}}:{}}}},J.assetDomain){if(!J.assetCertificateArn){if(!J.hostedZoneId)throw Error("serverless app: `assetDomain` requires either `assetCertificateArn` (a us-east-1 ACM cert) or `hostedZoneId` (to auto-issue + validate one). CloudFront only accepts certs from us-east-1.");if(z!=="us-east-1")throw Error(`serverless app: auto-issuing an asset-domain cert needs a us-east-1 app (CloudFront certs must be us-east-1); this app is in ${z}. Supply a pre-issued us-east-1 \`assetCertificateArn\` instead.`);j.AssetsCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:J.assetDomain,ValidationMethod:"DNS",DomainValidationOptions:[{DomainName:J.assetDomain,HostedZoneId:J.hostedZoneId}]}}}if(J.hostedZoneId)j.AssetsDomainRecord={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:J.hostedZoneId,Name:J.assetDomain,Type:"A",AliasTarget:{DNSName:L.getAtt("AssetsDistribution","DomainName"),HostedZoneId:"Z2FDTNDATAQYW2"}}};q.AssetDomain={Description:"Custom asset CDN host",Value:J.assetDomain}}j.AssetsBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:L.ref("AssetsBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:L.sub(`arn:aws:s3:::${E}/*`),Condition:{StringEquals:{"AWS:SourceArn":L.sub("arn:aws:cloudfront::${AWS::AccountId}:distribution/${AssetsDistribution}")}}}]}}},q.AssetsBucketName={Description:"Assets bucket",Value:L.ref("AssetsBucket")},q.AssetsCdnDomain={Description:"Assets CloudFront domain",Value:L.getAtt("AssetsDistribution","DomainName")}}if(J.firewall?.enabled){let H0=[],D0=0;if(J.firewall.rateLimit)H0.push({Name:"rate-limit",Priority:D0++,Action:{Block:{}},Statement:{RateBasedStatement:{Limit:J.firewall.rateLimit,AggregateKeyType:"IP"}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${Q}-${Y}-rate`}});let f0={sqlInjection:"AWSManagedRulesSQLiRuleSet",xss:"AWSManagedRulesCommonRuleSet",common:"AWSManagedRulesCommonRuleSet",botControl:"AWSManagedRulesBotControlRuleSet",ipReputation:"AWSManagedRulesAmazonIpReputationList"};for(let P0 of J.firewall.rules??[]){let $2=f0[P0];if(!$2)continue;H0.push({Name:`managed-${P0}`,Priority:D0++,OverrideAction:{None:{}},Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:$2}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${Q}-${Y}-${P0}`}})}j.WebAcl={Type:"AWS::WAFv2::WebACL",Properties:{Name:`${Q}-${Y}-waf`,Scope:"REGIONAL",DefaultAction:{Allow:{}},Rules:H0,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${Q}-${Y}-waf`}}},q.WafAclArn={Description:"WAF web ACL ARN. Attach to a CloudFront distribution fronting the API to enforce (HTTP API v2 stages do not support direct WAF association).",Value:L.getAtt("WebAcl","Arn")}}if(r&&d){if(!J.vpc?.id)throw Error("serverless app: data services (elasticache / aurora-serverless / rdsProxy / efs) need app.vpc.id (the VPC id) so the managed security group is created in the right VPC.");j.DataSecurityGroup={Type:"AWS::EC2::SecurityGroup",Properties:{VpcId:J.vpc.id,GroupDescription:`${Q}-${Y} serverless data access`,SecurityGroupIngress:[{IpProtocol:"-1",CidrIp:"10.0.0.0/8"}]}}}if(b)j.EfsFileSystem={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:!0,FileSystemTags:[{Key:"Name",Value:`${Q}-${Y}-efs`}]}},c.forEach((H0,D0)=>{j[`EfsMountTarget${D0}`]={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:L.ref("EfsFileSystem"),SubnetId:H0,SecurityGroups:[L.getAtt("DataSecurityGroup","GroupId")]}}}),j.EfsAccessPoint={Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:L.ref("EfsFileSystem"),PosixUser:{Uid:1001,Gid:1001},RootDirectory:{Path:"/lambda",CreationInfo:{OwnerUid:1001,OwnerGid:1001,Permissions:"0755"}}}},q.EfsFileSystemId={Description:"EFS file system id",Value:L.ref("EfsFileSystem")};if(J.cache?.driver==="elasticache")j.CacheSubnetGroup={Type:"AWS::ElastiCache::SubnetGroup",Properties:{Description:`${Q}-${Y} cache subnets`,SubnetIds:c}},j.CacheCluster={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:`${Q}-${Y}-cache`,ReplicationGroupDescription:`${Q}-${Y} redis`,Engine:"redis",CacheNodeType:"cache.t4g.micro",NumCacheClusters:1,AutomaticFailoverEnabled:!1,CacheSubnetGroupName:L.ref("CacheSubnetGroup"),SecurityGroupIds:[L.getAtt("DataSecurityGroup","GroupId")],TransitEncryptionEnabled:!1}},q.CacheEndpoint={Description:"Redis primary endpoint",Value:L.getAtt("CacheCluster","PrimaryEndPoint.Address")};if(J.database?.connection==="aurora-serverless")j.DbSubnetGroup={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupDescription:`${Q}-${Y} db subnets`,SubnetIds:c}},j.DbSecret={Type:"AWS::SecretsManager::Secret",Properties:{Name:`${Q}/${Y}/db`,GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"app"}),GenerateStringKey:"password",PasswordLength:32,ExcludePunctuation:!0}}},j.DbCluster={Type:"AWS::RDS::DBCluster",Properties:{Engine:"aurora-mysql",EngineMode:"provisioned",DBClusterIdentifier:`${Q}-${Y}-db`,DatabaseName:"app",MasterUsername:L.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:username}}"),MasterUserPassword:L.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:password}}"),ServerlessV2ScalingConfiguration:{MinCapacity:J.database?.minCapacity??0.5,MaxCapacity:J.database?.maxCapacity??4},DBSubnetGroupName:L.ref("DbSubnetGroup"),VpcSecurityGroupIds:[L.getAtt("DataSecurityGroup","GroupId")]}},j.DbInstance={Type:"AWS::RDS::DBInstance",Properties:{Engine:"aurora-mysql",DBInstanceClass:"db.serverless",DBClusterIdentifier:L.ref("DbCluster")}},q.DbEndpoint={Description:"Aurora cluster endpoint",Value:L.getAtt("DbCluster","Endpoint.Address")};if(J.rdsProxy&&J.database?.connection==="aurora-serverless")j.DbProxyRole={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"rds.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"read-db-secret",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue"],Resource:L.ref("DbSecret")}]}}]}},j.DbProxy={Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:typeof J.rdsProxy==="object"&&J.rdsProxy.name?J.rdsProxy.name:`${Q}-${Y}-proxy`,EngineFamily:"MYSQL",RoleArn:L.getAtt("DbProxyRole","Arn"),Auth:[{AuthScheme:"SECRETS",SecretArn:L.ref("DbSecret"),IAMAuth:"DISABLED"}],VpcSubnetIds:c,VpcSecurityGroupIds:[L.getAtt("DataSecurityGroup","GroupId")],RequireTLS:!1}},j.DbProxyTargetGroup={Type:"AWS::RDS::DBProxyTargetGroup",DependsOn:["DbInstance"],Properties:{DBProxyName:L.ref("DbProxy"),TargetGroupName:"default",DBClusterIdentifiers:[L.ref("DbCluster")]}},q.DbProxyEndpoint={Description:"RDS Proxy endpoint",Value:L.getAtt("DbProxy","Endpoint")};if(q.HttpFunctionName={Description:"HTTP function name",Value:L.ref("HttpFunction")},q.CliFunctionName={Description:"CLI function name",Value:L.ref("CliFunction")},B)q.QueueFunctionName={Description:"Queue function name",Value:L.ref("QueueFunction")};let X1={AWSTemplateFormatVersion:"2010-09-09",Description:`Serverless application for ${$.config.project.name} (${Q}-${Y})`,Parameters:O?{ImageUri:{Type:"String",Description:"ECR image URI of the deployment artifact"}}:{ArtifactBucket:{Type:"String",Description:"S3 bucket holding the deployment artifact"},ArtifactKey:{Type:"String",Description:"S3 key of the deployment artifact (zip)"}},Resources:j,Outputs:q},d1={};for(let H0 of Object.values(j))d1[H0.Type]=(d1[H0.Type]??0)+1;return{template:X1,functionNames:U,queueNames:F,resourceSummary:d1}}function _U($){let J=`php${$.replace(".","")}`;return AU.map((Y)=>`${J}-php-${Y}`)}function zZ($,J){let Y=`php${$.replace(".","")}`,Z=_U($).join(" \\\n "),Q=`/opt/remi/${Y}/root`,G=`/etc/opt/remi/${Y}`;return`${J?`FROM almalinux:9 AS ${J}`:"FROM almalinux:9"}
3643
3643
 
3644
3644
  # Build PHP on AlmaLinux 9 (where Remi's version-isolated SCL packages install
3645
3645
  # cleanly — Remi's release RPM rejects Amazon Linux 2023). AlmaLinux 9 shares
@@ -7330,6 +7330,11 @@ ${G.join(`
7330
7330
  ${W.join(`
7331
7331
  `)}
7332
7332
  `;if(J==="bun")B+=`
7333
+ # cloud-init runs this with \`set -u\` and NO $HOME set. bun's install.sh
7334
+ # dereferences $HOME even when BUN_INSTALL is set, so without this the install
7335
+ # aborts with "HOME: unbound variable" and /usr/local/bin/bun never appears —
7336
+ # breaking a from-scratch provision (adopting an existing box masked it).
7337
+ export HOME="\${HOME:-/root}"
7333
7338
  export BUN_INSTALL="/root/.bun"
7334
7339
  curl -fsSL https://bun.sh/install | bash${Y==="latest"?"":` -s "bun-v${Y}"`}
7335
7340
  ln -sf /root/.bun/bin/bun /usr/local/bin/bun
@@ -7462,12 +7467,12 @@ await startProxies(config)
7462
7467
  ${Q}`)}catch(Q){if(Q instanceof Error&&/cloud-init reported an error/.test(Q.message))throw Q}await this.sleep(J)}throw Error(`Timed out waiting for cloud-init to finish on ${$} after ${Y}ms`)}outputsFromState($,J){return{deployStoragePath:$.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:$.serverId?String($.serverId):void 0,appPublicIp:J?.public_net.ipv4?.ip||$.publicIp,sshUser:$.sshUser||this.sshUser,servicesPrivateIp:$.servicesPrivateIp}}static SSH_HOST_KEY_OPTS=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"];sshBaseArgs($,J=[]){return["-i",this.sshPrivateKeyPath,...A$.SSH_HOST_KEY_OPTS,"-o","BatchMode=yes",...J,`${this.sshUser}@${$}`]}scpToHost($,J,Y){qQ(["scp","-i",this.sshPrivateKeyPath,...A$.SSH_HOST_KEY_OPTS,"-o","BatchMode=yes",J,`${this.sshUser}@${$}:${Y}`].map((Z)=>`"${Z.replace(/"/g,"\\\"")}"`).join(" "),{stdio:"pipe",maxBuffer:TQ})}sshExec($,J){let Y=J.replace(/'/g,"'\\''");return qQ(`ssh ${this.sshBaseArgs($).map((Z)=>`"${Z.replace(/"/g,"\\\"")}"`).join(" ")} '${Y}'`,{encoding:"utf8",stdio:["pipe","pipe","pipe"],maxBuffer:TQ})}}});class I7{name="hetzner";usesCloudFormation=!1;async getComputeOutputs(){return{appPublicIp:"127.0.0.1",sshUser:"root"}}async uploadRelease($){return{artifactRef:$.localPath}}async findComputeTargets($){return[{id:"localhost",name:"localhost",publicIp:"127.0.0.1",status:"running"}]}async runRemoteDeploy($){let J=$.commands.join(`
7463
7468
  `);try{let Y=Bun.spawn(["bash","-c",J],{stdout:"pipe",stderr:"pipe",env:process.env}),[Z,Q,G]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text(),Y.exited]);return{success:G===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:G===0?"Success":"Failed",output:Z,error:Q}]}}catch(Y){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:Y?.message??String(Y)}],error:Y?.message??String(Y)}}}}function DQ(){let $=process.env.TS_CLOUD_DASHBOARD_BOX;return $!=null&&$!==""&&$!=="0"&&$.toLowerCase()!=="false"}function Y1($){if(DQ())return new I7;switch($.provider??q2($.config)){case"aws":return new H9({region:$.config.project.region});case"hetzner":return new A$({apiToken:$.config.hetzner?.apiToken,sshPrivateKeyPath:$.config.hetzner?.sshPrivateKeyPath,sshUser:$.config.hetzner?.sshUser,location:$.config.hetzner?.location});default:throw Error(`Unknown cloud provider: ${$.provider??q2($.config)}`)}}class RQ{drivers=new Map;getDriver($,J){let Y=J??q2($),Z=`${Y}:${$.project.slug}:${$.project.region||"default"}`,Q=this.drivers.get(Z);if(Q)return Q;let G=Y1({config:$,provider:Y});return this.drivers.set(Z,G),G}}var YT;var mH=o(async()=>{await z8([n0(),KQ(),wQ()]);YT=new RQ});function k7($){return Object.entries($).map(([J,Y])=>`${J}=${ZT(String(Y))}`).join(`
7464
7469
  `)}function ZT($){return`"${$.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function NQ($){return`${$.replace(/\/+$/,"")}/.ts-cloud`}function SQ($){return`${NQ($)}/deploy-history.log`}function QT($,J){return`${NQ($)}/deploys/${J}.log`}function _$($,J){let Y=$.replace(/\/+$/,"");return{base:Y,releases:`${Y}/releases`,shared:`${Y}/shared`,current:`${Y}/current`,release:`${Y}/releases/${J}`}}function GT($){let J=$.split("/").pop()||$;return J.startsWith(".")||/\.[a-z0-9]+$/i.test(J)}function _9($,J=h7){let Y=[`mkdir -p ${$.releases} ${$.shared}`];for(let Z of J)if(GT(Z))Y.push(`mkdir -p "$(dirname ${$.shared}/${Z})"`,`touch ${$.shared}/${Z}`);else if(Z==="storage")Y.push(`mkdir -p ${$.shared}/storage/app/public`,`mkdir -p ${$.shared}/storage/framework/cache/data`,`mkdir -p ${$.shared}/storage/framework/sessions`,`mkdir -p ${$.shared}/storage/framework/testing`,`mkdir -p ${$.shared}/storage/framework/views`,`mkdir -p ${$.shared}/storage/logs`);else Y.push(`mkdir -p ${$.shared}/${Z}`);return Y}function b7($,J=h7){let Y=[];for(let Z of J){let Q=`${$.shared}/${Z}`,G=`${$.release}/${Z}`;Y.push(`rm -rf ${G}`,`mkdir -p "$(dirname ${G})"`,`ln -sfn ${Q} ${G}`)}return Y}function j9($){return[`ln -sfn ${$.release} ${$.current}.tmp`,`mv -Tf ${$.current}.tmp ${$.current}`]}function lH($,J={}){if(J.to){let Y=`${$.releases}/${J.to}`;return[`[ -d ${Y} ] || { echo "rollback target ${Y} not found" >&2; exit 1; }`,`ln -sfn ${Y} ${$.current}.tmp`,`mv -Tf ${$.current}.tmp ${$.current}`]}return[`TS_CLOUD_CURRENT=$(readlink -f ${$.current} 2>/dev/null || true)`,`TS_CLOUD_PREV=$(ls -1dt ${$.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`,'[ -n "$TS_CLOUD_PREV" ] || { echo "no previous release to roll back to" >&2; exit 1; }',`ln -sfn "$TS_CLOUD_PREV" ${$.current}.tmp`,`mv -Tf ${$.current}.tmp ${$.current}`,'echo "rolled back to $TS_CLOUD_PREV"']}function L9($,J=4){let Y=Math.max(1,J);return[`TS_CLOUD_CURRENT=$(readlink -f ${$.current} 2>/dev/null || true)`,`ls -1dt ${$.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${Y+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function y7($,J){let Y=NQ($),Z=QT($,J.releaseId),Q=SQ($),G=Math.max(1,J.keepLogs??20),W=J.commit||"",z=J.branch||"";return[`mkdir -p ${Y}/deploys`,`exec > >(tee -a ${Z}) 2>&1`,`echo "[ts-cloud] deploy ${J.releaseId} commit=${W} branch=${z} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${J.releaseId}" "${W}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${Q}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${Y}/deploys/*.log 2>/dev/null | tail -n +${G+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}var h7,A9=4;var E9=o(()=>{h7=["storage",".env"]});function v7($,J){let Y=J==="bun"?"/usr/local/bin/bun":J==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",Z=$.replace(/^(bun|node|deno)\s+/,"");return`${Y} ${Z}`}function f7($){let{siteName:J,slug:Y,artifactFetch:Z,releaseId:Q,execStart:G,envEntries:W,port:z,keepReleases:U=A9,preStartCommands:H=[]}=$,F=$.appDir??`/var/www/${J}`,B=_$(F,Q),K=`${Y}-${J}.service`,O=[".env"],A=k7(W),V=H.length>0?[`cd ${B.release}`,...H]:[];return["set -euo pipefail",...Z,..._9(B,O),`rm -rf ${B.release}`,`mkdir -p ${B.release}`,`tar xzf /tmp/${J}-release.tar.gz -C ${B.release}`,`cat > ${B.shared}/.env <<'TS_CLOUD_ENV_EOF'`,A,"TS_CLOUD_ENV_EOF",`chmod 600 ${B.shared}/.env`,...b7(B,O),...V,`cat > /etc/systemd/system/${K} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${J} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${B.current}`,`ExecStart=${G}`,"Restart=always","RestartSec=5",`EnvironmentFile=${B.current}/.env`,...z?[`Environment=PORT=${z}`]:[],"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${K}`,...j9(B),`systemctl restart ${K}`,`systemctl is-active ${K}`,...L9(B,U)]}function g7($){let{siteName:J,artifactFetch:Y,releaseId:Z,keepReleases:Q=A9,preStartCommands:G=[]}=$,W=$.appDir??`/var/www/${J}`,z=_$(W,Z),U=G.length>0?[`cd ${z.release}`,...G]:[];return["set -euo pipefail",...Y,..._9(z,[]),`rm -rf ${z.release}`,`mkdir -p ${z.release}`,`tar xzf /tmp/${J}-release.tar.gz -C ${z.release}`,...U,...j9(z),...L9(z,Q)]}function PQ($,J,Y,Z){return[`aws s3 cp "s3://${$}/${J}" /tmp/${Z}-release.tar.gz --region ${Y}`]}function CQ($,J){return[`cp "${$}" /tmp/${J}-release.tar.gz`]}var xQ=o(()=>{E9()});var iH={};h0(iH,{resolveUiSource:()=>u7,ensureManagementDashboard:()=>IQ,buildManagementDashboardArtifact:()=>kQ,MANAGEMENT_DASHBOARD_SITE:()=>$8});import{execSync as pH}from"node:child_process";import{existsSync as M9}from"node:fs";import{tmpdir as WT}from"node:os";import{dirname as zT,isAbsolute as UT,join as F2}from"node:path";import{fileURLToPath as HT}from"node:url";function rH($){return $!=null&&$!==""&&$!=="0"&&$.toLowerCase()!=="false"}function u7($){if(M9(F2($,"packages","ui","pages"))||M9(F2($,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let J=zT(HT(import.meta.url)),Y=[F2(J,"ui"),F2(J,"..","ui"),F2(J,"..","..","ui"),F2(J,"..","dist","ui")];for(let Z of Y)if(M9(F2(Z,"index.html"))||M9(F2(Z,"serverless.html")))return{uiRoot:Z,build:!1};return null}function IQ($,J={}){let Y=J.logger??nH,Z=J.cwd??process.cwd();if(rH(process.env.TS_CLOUD_UI_DISABLE))return Y.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),$;if(H$($))return $;let Q=u7(Z);if(!Q)return Y.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),$;let G=process.env.TS_CLOUD_UI_PASSWORD?.trim()||void 0,W=$.environments&&Object.keys($.environments)[0],z=rH(process.env.TS_CLOUD_UI_LIVE),U=Number(process.env.TS_CLOUD_UI_PORT)||void 0,H=yJ($,W??"production",{uiRoot:Q.uiRoot,build:Q.build,domain:process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,username:process.env.TS_CLOUD_UI_USERNAME?.trim()||void 0,password:G,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:z,port:U});if(!H)return Y.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),$;return $.sites={...$.sites??{},[H.name]:H.site},Y.info(`Management dashboard → https://${H.site.domain} (${G?"htpasswd-protected":"NO AUTH — set TS_CLOUD_UI_PASSWORD"})`),$}function kQ($,J){if(!$?.root)return null;let Y=J.cwd??process.cwd(),Z=J.logger??nH;try{if(typeof $.build==="string"&&$.build.trim())Z.info(`Management dashboard: building UI (${$.build})`),pH($.build,{cwd:Y,stdio:"inherit"});let Q=UT($.root)?$.root:F2(Y,$.root);if(!M9(Q))return Z.warn(`Management dashboard: build output not found at ${Q} — skipping dashboard artifact.`),null;let G=F2(WT(),`${J.slug}-${$8}-${J.sha}.tar.gz`);return pH(`tar czf "${G}" -C "${Q}" .`,{stdio:"inherit"}),G}catch(Q){return Z.warn(`Management dashboard: failed to build artifact — ${Q?.message??Q}. Skipping dashboard deploy.`),null}}var $8="dashboard",nH;var d7=o(async()=>{await n0();nH={info:()=>{},warn:()=>{}}});function hQ($){if($.ssl?.provider)return $.ssl.provider;return $.domain?"letsencrypt":"none"}function tH($){return`/etc/letsencrypt/ts-cloud-${$}.ini`}function FT($){let J=$?aH[$.provider]:void 0,Y=["certbot","python3-certbot-nginx",...J?[J.pkg]:[]].join(" ");return["export DEBIAN_FRONTEND=noninteractive",J?`apt-get update -y && apt-get install -y ${Y}`:`command -v certbot >/dev/null 2>&1 || { apt-get update -y && apt-get install -y ${Y}; }`,"mkdir -p /etc/letsencrypt/renewal-hooks/deploy","cat > /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh <<'TS_CLOUD_HOOK_EOF'","#!/bin/sh","systemctl reload nginx","TS_CLOUD_HOOK_EOF","chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh","systemctl enable certbot.timer 2>/dev/null || true","systemctl start certbot.timer 2>/dev/null || true"]}function XT($){if(!$.credentials||Object.keys($.credentials).length===0)return[];let J=tH($.provider),Y=Object.entries($.credentials).map(([Z,Q])=>`${Z} = ${Q}`).join(`
7465
- `);return[`cat > ${J} <<'TS_CLOUD_DNSCREDS_EOF'`,Y,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${J}`]}function BT($){let J=$.dns,Y=$.wildcard?[`*.${$.domain}`,$.domain]:[$.domain,...$.aliases||[]].filter(Boolean),Z=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(J){let Q=aH[J.provider].plugin;if(Z.push(`--${Q}`),J.provider!=="route53"&&J.credentials)Z.push(`--${Q}-credentials ${tH(J.provider)}`);if(typeof J.propagationSeconds==="number"&&J.provider!=="route53")Z.push(`--${Q}-propagation-seconds ${J.propagationSeconds}`);Z.push("certonly")}else Z.push("--nginx",$.redirect===!1?"--no-redirect":"--redirect");if($.email)Z.push(`-m ${$.email}`);else Z.push("--register-unsafely-without-email");for(let Q of Y)Z.push(`-d ${Q}`);return[Z.join(" ")]}function bQ($){if(hQ($)!=="letsencrypt"||!$.domain)return[];let J=$.ssl,Y=J?.dns,Z=J?.wildcard===!0;if(Z&&!Y)return[];return[...FT(Y),...Y?XT(Y):[],...BT({domain:$.domain,aliases:$.aliases,email:J?.email,wildcard:Z,dns:Y})]}var aH;var sH=o(()=>{aH={cloudflare:{pkg:"python3-certbot-dns-cloudflare",plugin:"dns-cloudflare"},route53:{pkg:"python3-certbot-dns-route53",plugin:"dns-route53"},digitalocean:{pkg:"python3-certbot-dns-digitalocean",plugin:"dns-digitalocean"},google:{pkg:"python3-certbot-dns-google",plugin:"dns-google"}}});function eH($){let{repository:J,releaseDir:Y,commit:Z}=$,Q=J.branch||"main",G=J.url,W=[`rm -rf ${Y}`,`mkdir -p ${Y}`];if(J.strategy==="tag")if(J.tag)W.push(`git clone -q --depth 1 --branch ${J.tag} ${G} ${Y}`),W.push(`printf '%s' ${oH(J.tag)} > ${Y}/.ts-cloud-tag`);else{let z=J.tagPattern||"v*";W.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${G} ${oH(`refs/tags/${z}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching ${z} found in ${G}" >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${G} ${Y}`,`printf '%s' "$TS_CLOUD_TAG" > ${Y}/.ts-cloud-tag`)}else if(Z)W.push(`git -C ${Y} init -q`,`git -C ${Y} remote add origin ${G}`,`git -C ${Y} fetch -q --depth 1 origin ${Z}`,`git -C ${Y} checkout -q FETCH_HEAD`);else W.push(`git clone -q --depth 1 --branch ${Q} ${G} ${Y}`);return W.push(`git -C ${Y} rev-parse HEAD > ${Y}/.ts-cloud-sha`),W}function oH($){return`'${$.split("'").join("'\\''")}'`}function OT($){switch($){case"laravel":case"statamic":return[c7,$F,...KT,m7,YF];case"php":case"wordpress":return[c7,`${$F} || true`,m7];case"static":case"spa":return[c7,m7]}}function VT($,J){return $.replace(/^php\s+/,`${J} `).replace(/(\s)php\s+artisan\s+/g,`$1${J} artisan `)}function AT($,J){let Y=k7(J);return[`cat > ${$} <<'TS_CLOUD_ENV_EOF'`,Y,"TS_CLOUD_ENV_EOF",`chmod 600 ${$}`]}function JF($,J,Y){return[`cat > ${$} <<'${Y}'`,J.replace(/\n$/,""),Y,`chmod 600 ${$}`]}function _T($,J){if(!J)return[];let Y=[];if(J.composerAuth){let Z=typeof J.composerAuth==="string"?J.composerAuth:JSON.stringify(J.composerAuth,null,2);Y.push(...JF(`${$}/auth.json`,Z,"TS_CLOUD_AUTHJSON_EOF"))}if(J.npmrc)Y.push(...JF(`${$}/.npmrc`,J.npmrc,"TS_CLOUD_NPMRC_EOF"));return Y}function ZF($){let J=$.healthCheck?.path;if(!J||!$.domain)return[];let Z=`http://127.0.0.1${J.startsWith("/")?J:`/${J}`}`;return[`echo "[ts-cloud] health check ${Z} (Host: ${$.domain})"`,"TS_CLOUD_HC_OK=0",`for i in $(seq 1 10); do TS_CLOUD_HC=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${$.domain}" -m 10 "${Z}" 2>/dev/null || echo 000); case "$TS_CLOUD_HC" in 2*|3*) TS_CLOUD_HC_OK=1; break ;; esac; sleep 3; done`,'[ "$TS_CLOUD_HC_OK" = 1 ] && echo "health check passed ($TS_CLOUD_HC)" || { echo "health check FAILED (last=$TS_CLOUD_HC)" >&2; exit 1; }']}function QF($){let{siteName:J,site:Y,releaseId:Z,commit:Q}=$;if(!Y.repository?.url)throw Error(`Site '${J}' is a PHP/git site but has no repository.url to clone`);let G=$.appBase??`/var/www/${J}`,W="php",z=_$(G,Z),U=Y.sharedPaths??h7,H=Y.keepReleases??A9,F=Y.deployScript?.length?Y.deployScript:OT(Y.type??"laravel"),B=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",K$()];if(B.push(...y7(G,{releaseId:Z,commit:Q,branch:Y.repository.branch,keepLogs:H})),B.push(..._9(z,U)),Y.env&&Object.keys(Y.env).length>0)B.push(...AT(`${z.shared}/.env`,Y.env));for(let K of F){let O=K.trim();if(O===c7)B.push(...eH({repository:Y.repository,releaseDir:z.release,commit:Q})),B.push(...b7(z,U)),B.push(`cd ${z.release}`),B.push(..._T(z.release,Y.credentials)),B.push(`chown -R www-data:www-data ${z.shared}/storage 2>/dev/null || true`,`[ -d ${z.release}/bootstrap/cache ] && chown -R www-data:www-data ${z.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${z.shared}/storage 2>/dev/null || true`);else if(O===m7)B.push(...j9(z)),B.push(...L9(z,H)),B.push(`(cd ${P1} && pantry restart php-fpm) 2>/dev/null || true`);else if(O===YF)B.push(`${W} artisan queue:restart || true`);else B.push(VT(K,W))}return B}var c7="$CREATE_RELEASE",m7="$ACTIVATE_RELEASE",YF="$RESTART_QUEUES",$F="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",KT;var GF=o(()=>{H2();E9();KT=["php artisan migrate --force","php artisan config:cache","php artisan route:cache","php artisan view:cache","php artisan event:cache","php artisan storage:link"]});function HF($){if($.framework)return $.framework;if($.type&&jT.has($.type))return"laravel";return"stacks"}function LT($){return`/bin/sh -lc 'export PATH="/usr/local/bin:$PATH"; export BUN_INSTALL="/root/.bun"; exec ${$}'`}function XF($){return MT[$]??FF}var jT,WF,zF="/usr/local/bin/bun",UF="storage/framework/core/buddy/src/cli.ts",FF,ET,MT;var BF=o(()=>{H2();jT=new Set(["laravel","php","statamic","wordpress"]);WF=`eval "$(cd ${P1} && pantry env 2>/dev/null)"`;FF={id:"stacks",wrapExec:LT,schedulerMode:"daemon",schedulerCommand:()=>`${zF} ${UF} schedule:run`,queueWorkerCommand:($,{current:J})=>{let Y=[`--queue=${$.queue||"default"}`,`--sleep=${$.sleep??3}`,`--tries=${$.tries??3}`,`--timeout=${$.timeout??60}`];return`${zF} ${J}/${UF} queue:work ${Y.join(" ")}`}},ET={id:"laravel",wrapExec:($)=>`/bin/sh -lc '${WF}; exec ${$}'`,schedulerMode:"cron",schedulerCommand:({current:$})=>`cd ${$} && ${WF} && php artisan schedule:run`,queueWorkerCommand:($,{current:J})=>{let Y=`${J}/artisan`;if($.horizon)return`php ${Y} horizon`;let Z=[$.connection||"default",`--queue=${$.queue||"default"}`,`--sleep=${$.sleep??3}`,`--tries=${$.tries??3}`,`--timeout=${$.timeout??60}`,`--memory=${$.memory??128}`];if($.maxJobs)Z.push(`--max-jobs=${$.maxJobs}`);if($.maxTime)Z.push(`--max-time=${$.maxTime}`);return`php ${Y} queue:work ${Z.join(" ")}`}},MT={stacks:FF,laravel:ET}});function KF($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qT($){return`'${$.split("'").join("'\\''")}'`}function OF($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function TT($,J,Y){return`${$}-${J}-queue-${Y}`}function wT($,J,Y,Z){return`${$}-${J}-daemon-${Y.name?OF(Y.name):OF(Y.command).slice(0,32)||String(Z)}`}function yQ($){let J=["[Unit]",`Description=${$.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${$.workingDir}`,`ExecStart=${$.execStart}`,`Restart=${$.restart||"always"}`,"RestartSec=5"];if($.user)J.push(`User=${$.user}`);if(typeof $.stopWaitSecs==="number")J.push(`TimeoutStopSec=${$.stopWaitSecs}`);return J.push("","[Install]","WantedBy=multi-user.target"),`${J.join(`
7470
+ `);return[`cat > ${J} <<'TS_CLOUD_DNSCREDS_EOF'`,Y,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${J}`]}function BT($){let J=$.dns,Y=$.wildcard?[`*.${$.domain}`,$.domain]:[$.domain,...$.aliases||[]].filter(Boolean),Z=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(J){let Q=aH[J.provider].plugin;if(Z.push(`--${Q}`),J.provider!=="route53"&&J.credentials)Z.push(`--${Q}-credentials ${tH(J.provider)}`);if(typeof J.propagationSeconds==="number"&&J.provider!=="route53")Z.push(`--${Q}-propagation-seconds ${J.propagationSeconds}`);Z.push("certonly")}else Z.push("--nginx",$.redirect===!1?"--no-redirect":"--redirect");if($.email)Z.push(`-m ${$.email}`);else Z.push("--register-unsafely-without-email");for(let Q of Y)Z.push(`-d ${Q}`);return[Z.join(" ")]}function bQ($){if(hQ($)!=="letsencrypt"||!$.domain)return[];let J=$.ssl,Y=J?.dns,Z=J?.wildcard===!0;if(Z&&!Y)return[];return[...FT(Y),...Y?XT(Y):[],...BT({domain:$.domain,aliases:$.aliases,email:J?.email,wildcard:Z,dns:Y})]}var aH;var sH=o(()=>{aH={cloudflare:{pkg:"python3-certbot-dns-cloudflare",plugin:"dns-cloudflare"},route53:{pkg:"python3-certbot-dns-route53",plugin:"dns-route53"},digitalocean:{pkg:"python3-certbot-dns-digitalocean",plugin:"dns-digitalocean"},google:{pkg:"python3-certbot-dns-google",plugin:"dns-google"}}});function eH($){let{repository:J,releaseDir:Y,commit:Z}=$,Q=J.branch||"main",G=J.url,W=[`rm -rf ${Y}`,`mkdir -p ${Y}`];if(J.strategy==="tag")if(J.tag)W.push(`git clone -q --depth 1 --branch ${J.tag} ${G} ${Y}`),W.push(`printf '%s' ${oH(J.tag)} > ${Y}/.ts-cloud-tag`);else{let z=J.tagPattern||"v*";W.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${G} ${oH(`refs/tags/${z}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching ${z} found in ${G}" >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${G} ${Y}`,`printf '%s' "$TS_CLOUD_TAG" > ${Y}/.ts-cloud-tag`)}else if(Z)W.push(`git -C ${Y} init -q`,`git -C ${Y} remote add origin ${G}`,`git -C ${Y} fetch -q --depth 1 origin ${Z}`,`git -C ${Y} checkout -q FETCH_HEAD`);else W.push(`git clone -q --depth 1 --branch ${Q} ${G} ${Y}`);return W.push(`git -C ${Y} rev-parse HEAD > ${Y}/.ts-cloud-sha`),W}function oH($){return`'${$.split("'").join("'\\''")}'`}function OT($){switch($){case"laravel":case"statamic":return[c7,$F,...KT,m7,YF];case"php":case"wordpress":return[c7,`${$F} || true`,m7];case"static":case"spa":return[c7,m7]}}function VT($,J){return $.replace(/^php\s+/,`${J} `).replace(/(\s)php\s+artisan\s+/g,`$1${J} artisan `)}function AT($,J){let Y=k7(J);return[`cat > ${$} <<'TS_CLOUD_ENV_EOF'`,Y,"TS_CLOUD_ENV_EOF",`chmod 600 ${$}`]}function JF($,J,Y){return[`cat > ${$} <<'${Y}'`,J.replace(/\n$/,""),Y,`chmod 600 ${$}`]}function _T($,J){if(!J)return[];let Y=[];if(J.composerAuth){let Z=typeof J.composerAuth==="string"?J.composerAuth:JSON.stringify(J.composerAuth,null,2);Y.push(...JF(`${$}/auth.json`,Z,"TS_CLOUD_AUTHJSON_EOF"))}if(J.npmrc)Y.push(...JF(`${$}/.npmrc`,J.npmrc,"TS_CLOUD_NPMRC_EOF"));return Y}function ZF($){let J=$.healthCheck?.path;if(!J||!$.domain)return[];let Z=`http://127.0.0.1${J.startsWith("/")?J:`/${J}`}`;return[`echo "[ts-cloud] health check ${Z} (Host: ${$.domain})"`,"TS_CLOUD_HC_OK=0",`for i in $(seq 1 10); do TS_CLOUD_HC=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${$.domain}" -m 10 "${Z}" 2>/dev/null || echo 000); case "$TS_CLOUD_HC" in 2*|3*) TS_CLOUD_HC_OK=1; break ;; esac; sleep 3; done`,'[ "$TS_CLOUD_HC_OK" = 1 ] && echo "health check passed ($TS_CLOUD_HC)" || { echo "health check FAILED (last=$TS_CLOUD_HC)" >&2; exit 1; }']}function QF($){let{siteName:J,site:Y,releaseId:Z,commit:Q}=$;if(!Y.repository?.url)throw Error(`Site '${J}' is a PHP/git site but has no repository.url to clone`);let G=$.appBase??`/var/www/${J}`,W="php",z=_$(G,Z),U=Y.sharedPaths??h7,H=Y.keepReleases??A9,F=Y.deployScript?.length?Y.deployScript:OT(Y.type??"laravel"),B=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",K$()];if(B.push(...y7(G,{releaseId:Z,commit:Q,branch:Y.repository.branch,keepLogs:H})),B.push(..._9(z,U)),Y.env&&Object.keys(Y.env).length>0)B.push(...AT(`${z.shared}/.env`,Y.env));for(let K of F){let O=K.trim();if(O===c7)B.push(...eH({repository:Y.repository,releaseDir:z.release,commit:Q})),B.push(...b7(z,U)),B.push(`cd ${z.release}`),B.push(..._T(z.release,Y.credentials)),B.push(`chown -R www-data:www-data ${z.shared}/storage 2>/dev/null || true`,`[ -d ${z.release}/bootstrap/cache ] && chown -R www-data:www-data ${z.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${z.shared}/storage 2>/dev/null || true`);else if(O===m7)B.push(...j9(z)),B.push(...L9(z,H)),B.push(`(cd ${P1} && pantry restart php-fpm) 2>/dev/null || true`);else if(O===YF)B.push(`${W} artisan queue:restart || true`);else B.push(VT(K,W))}return B}var c7="$CREATE_RELEASE",m7="$ACTIVATE_RELEASE",YF="$RESTART_QUEUES",$F="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",KT;var GF=o(()=>{H2();E9();KT=["php artisan migrate --force","php artisan config:cache","php artisan route:cache","php artisan view:cache","php artisan event:cache","php artisan storage:link"]});function HF($){if($.framework)return $.framework;if($.type&&jT.has($.type))return"laravel";return"stacks"}function XF($){return ET[$]??FF}var jT,WF,zF="/usr/local/bin/bun",UF="storage/framework/core/buddy/src/cli.ts",FF,LT,ET;var BF=o(()=>{H2();jT=new Set(["laravel","php","statamic","wordpress"]);WF=`eval "$(cd ${P1} && pantry env 2>/dev/null)"`,FF={id:"stacks",wrapExec:($)=>$,execEnv:{PATH:"/usr/local/bin:/usr/bin:/bin",BUN_INSTALL:"/root/.bun"},schedulerMode:"daemon",schedulerCommand:()=>`${zF} ${UF} schedule:run`,queueWorkerCommand:($,{current:J})=>{let Y=[`--queue=${$.queue||"default"}`,`--sleep=${$.sleep??3}`,`--tries=${$.tries??3}`,`--timeout=${$.timeout??60}`];return`${zF} ${J}/${UF} queue:work ${Y.join(" ")}`}},LT={id:"laravel",wrapExec:($)=>`/bin/sh -lc '${WF}; exec ${$}'`,schedulerMode:"cron",schedulerCommand:({current:$})=>`cd ${$} && ${WF} && php artisan schedule:run`,queueWorkerCommand:($,{current:J})=>{let Y=`${J}/artisan`;if($.horizon)return`php ${Y} horizon`;let Z=[$.connection||"default",`--queue=${$.queue||"default"}`,`--sleep=${$.sleep??3}`,`--tries=${$.tries??3}`,`--timeout=${$.timeout??60}`,`--memory=${$.memory??128}`];if($.maxJobs)Z.push(`--max-jobs=${$.maxJobs}`);if($.maxTime)Z.push(`--max-time=${$.maxTime}`);return`php ${Y} queue:work ${Z.join(" ")}`}},ET={stacks:FF,laravel:LT}});function KF($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function MT($){return`'${$.split("'").join("'\\''")}'`}function OF($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function qT($,J,Y){return`${$}-${J}-queue-${Y}`}function TT($,J,Y,Z){return`${$}-${J}-daemon-${Y.name?OF(Y.name):OF(Y.command).slice(0,32)||String(Z)}`}function yQ($){let J=["[Unit]",`Description=${$.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${$.workingDir}`,...Object.entries($.environment??{}).map(([Y,Z])=>`Environment="${Y}=${Z}"`),`ExecStart=${$.execStart}`,`Restart=${$.restart||"always"}`,"RestartSec=5"];if($.user)J.push(`User=${$.user}`);if(typeof $.stopWaitSecs==="number")J.push(`TimeoutStopSec=${$.stopWaitSecs}`);return J.push("","[Install]","WantedBy=multi-user.target"),`${J.join(`
7466
7471
  `)}
7467
- `}function vQ($,J){return[`cat > /etc/systemd/system/${$}.service <<'TS_CLOUD_UNIT_EOF'`,J.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function DT($,J){return`/etc/cron.d/${$}-${J}-scheduler`}function fQ($){let{slug:J,siteName:Y,site:Z}=$,G=`${$.appBase??`/var/www/${Y}`}/current`,W=XF(HF(Z)),z={current:G},U=[],H=[];(Z.queues||[]).forEach((E,M)=>{let j=Math.max(1,E.processes??1);for(let q=0;q<j;q++){let T=TT(J,Y,H.length);H.push(T),U.push(...vQ(T,yQ({description:`${Y} queue worker ${M}.${q} (managed by ts-cloud)`,workingDir:G,execStart:W.wrapExec(W.queueWorkerCommand(E,z)),stopWaitSecs:E.stopWaitSecs??90})))}}),(Z.daemons||[]).forEach((E,M)=>{let j=Math.max(1,E.processes??1);for(let q=0;q<j;q++){let T=`${wT(J,Y,E,M)}-${q}`;H.push(T),U.push(...vQ(T,yQ({description:`${Y} daemon ${E.name||E.command} (managed by ts-cloud)`,workingDir:E.directory||G,execStart:W.wrapExec(E.command),restart:E.restart,user:E.user})))}});let K=Z.scheduler,O=K===!0||typeof K==="object"&&K!==null,A=`${J}-${Y}-scheduler`;if(O&&W.schedulerMode==="daemon")H.push(A),U.push(...vQ(A,yQ({description:`${Y} scheduler (managed by ts-cloud)`,workingDir:G,execStart:W.wrapExec(W.schedulerCommand(z))})));let V=H.map((E)=>`${E}.service`).join(" ");U.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${V}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${KF(J)}-${KF(Y)}-((queue|daemon)-.*|scheduler)\\.service$' || true); do`,' case " $TS_CLOUD_DESIRED " in',' *" $unit "*) ;;',' *) systemctl stop "$unit" 2>/dev/null || true; systemctl disable "$unit" 2>/dev/null || true; rm -f "/etc/systemd/system/$unit" ;;'," esac","done","systemctl daemon-reload");for(let E of H)U.push(`systemctl enable ${E}.service`,`systemctl restart ${E}.service`);let _=DT(J,Y);if(O&&W.schedulerMode==="cron"){let E=typeof K==="object"&&K!==null?K:void 0,M=`${W.schedulerCommand(z)} >> /dev/null 2>&1`;if(E?.heartbeatUrl){let q=E.heartbeatMethod||"GET",T=q==="GET"?"":`-X ${q} `;M+=` && curl -fsS -m 10 ${T}${qT(E.heartbeatUrl)} >/dev/null 2>&1`}let j=`* * * * * root ${M}
7468
- `.replace(/%/g,"\\%");U.push(`cat > ${_} <<'TS_CLOUD_CRON_EOF'`,j.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${_}`)}else U.push(`rm -f ${_}`);return U}function gQ($){return!!($.queues?.length||$.daemons?.length||$.scheduler)}var VF=o(()=>{BF()});function l7($){return($.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function _F($){return`web_${l7($)}`}function ST($){let J=l7($),Y=0;for(let Z=0;Z<J.length;Z++)Y=Y*31+J.charCodeAt(Z)>>>0;return RT+Y%NT}function uQ($){return`127.0.0.1:${ST($)}`}function PT($){let J=l7($.siteName),Y=_F($.siteName),Z=$.maxChildren??10;return[`; ts-cloud-managed pool for ${$.siteName} (site isolation)`,`[${J}]`,`user = ${Y}`,`group = ${Y}`,`listen = ${uQ($.siteName)}`,"pm = dynamic",`pm.max_children = ${Z}`,"pm.start_servers = 2","pm.min_spare_servers = 1","pm.max_spare_servers = 3","pm.max_requests = 500","catch_workers_output = yes",`php_admin_value[open_basedir] = ${$.appBase}:/tmp`,""].join(`
7469
- `)}function jF($){let J=_F($.siteName),Y=l7($.siteName),Z=`${AF}/${Y}.conf`;return[`getent group ${J} >/dev/null || groupadd --system ${J}`,`id -u ${J} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${J} ${J}`,`usermod -aG ${J} www-data 2>/dev/null || true`,`chown -R ${J}:${J} ${$.appBase} || true`,`chmod -R g+rX ${$.appBase} || true`,`chmod 600 ${$.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${AF}`,`cat > ${Z} <<'TS_CLOUD_FPMPOOL_EOF'`,PT($).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${P1} && pantry restart php-fpm) 2>/dev/null || true`]}var AF="/var/lib/pantry/php-fpm/pool.d",RT=9100,NT=400;var LF=o(()=>{H2()});async function cQ($,J,Y=dQ){let{config:Z,environment:Q,siteName:G,site:W,slug:z,sha:U,runtime:H,localTarballPath:F}=J,B=`releases/${G}/${U}.tar.gz`,K=E1(Z,Q),O=await $.getComputeOutputs({config:Z,environment:Q}),A=await $.findComputeTargets({slug:z,environment:Q,role:"app"});if(A.length===0)return{success:!1,error:$.name==="aws"?`Stack '${K}' has no EC2 instances tagged Project=${z} Environment=${Q} Role=app.`:`No Hetzner servers labeled ts-cloud/project=${z} ts-cloud/environment=${Q} ts-cloud/role=app.`};if(X9(W)){let I=Z.infrastructure?.compute,b=W.phpVersion??I?.php?.default??I?.php?.versions?.[0],y=`/var/www/${G}`,c=O.servicesPrivateIp?yH(O.servicesPrivateIp,Z.infrastructure?.appDatabase):AH(Z.infrastructure?.appDatabase),r=Object.keys(c).length>0?{...W,env:{...c,...W.env||{}}}:W,d=QF({siteName:G,site:r,releaseId:U,appBase:y,defaultPhpVersion:b}),g=I?.webServer!=="rpx",J0=hQ(W)==="custom"&&W.ssl?.certPath&&W.ssl?.keyPath?{certPath:W.ssl.certPath,keyPath:W.ssl.keyPath}:void 0,t=W.isolation?jF({siteName:G,appBase:y}):[],a=g?GQ({siteName:G,domain:W.domain||G,aliases:W.aliases,type:W.type,appDir:`${y}/current`,webDirectory:W.webDirectory,phpVersion:b,fastcgiPass:W.isolation?uQ(G):void 0,redirects:W.redirects,ssl:J0,auth:W.auth&&W.auth.enabled!==!1&&W.auth.password?{username:W.auth.username||"admin",password:W.auth.password,realm:W.auth.realm}:void 0,serverSnippet:QQ(W.nginx,I?.nginxTemplates),clientMaxBodySize:W.nginx?.clientMaxBodySize,hsts:W.ssl?.hsts,tlsProtocols:W.ssl?.tlsProtocols,security:W.security}):[],e=g?bQ(W):[],j0=gQ(W)?fQ({slug:z,siteName:G,site:W,phpVersion:b,appBase:y}):[],w0=g?ZF(W):[];Y.step(`Deploying PHP site '${G}' to ${A.length} target(s)...`);let B0=await $.runRemoteDeploy({targets:A,commands:[...d,...t,...a,...e,...j0,...w0],comment:`ts-cloud deploy ${z}/${G}@${U}`,tags:{Project:z,Environment:Q,Role:"app"}}),X1=wH(Z.notifications,W.notifications);if(!B0.success)return await FQ(X1,"deploy-failed",`❌ Deploy of ${z}/${G}@${U} failed: ${B0.error||"unknown error"}`),{success:!1,error:B0.error||"Remote PHP deploy failed",instanceCount:B0.instanceCount,perInstance:B0.perInstance};let d1=W.domain?` → https://${W.domain}`:"";return await FQ(X1,"deploy",`✅ Deployed ${z}/${G}@${U}${d1}`),{success:!0,instanceCount:B0.instanceCount,perInstance:B0.perInstance}}if(!F)return{success:!1,error:`Site '${G}' requires a release tarball but none was provided`};let V=await $.uploadRelease({config:Z,environment:Q,localPath:F,remoteKey:B,targets:A}),_=$.name==="aws"?PQ(O.deployBucketName,B,Z.project.region||"us-east-1",G):CQ(V.artifactRef,G),E=p0(W),M=E==="server-static"?g7({siteName:G,artifactFetch:_,releaseId:U,preStartCommands:W.preStart}):f7({siteName:G,slug:z,artifactFetch:_,releaseId:U,execStart:v7(W.start,H),envEntries:W.env||{},port:W.port,preStartCommands:W.preStart}),j=Z.infrastructure?.compute,q=E==="server-static"&&j?.webServer!=="rpx"&&!!W.domain,T=q?GQ({siteName:G,domain:W.domain,aliases:W.aliases,type:W.type==="spa"?"spa":"static",appDir:`/var/www/${G}/current`,webDirectory:"",redirects:W.redirects,auth:W.auth&&W.auth.enabled!==!1&&W.auth.password?{username:W.auth.username||"admin",password:W.auth.password,realm:W.auth.realm}:void 0,serverSnippet:QQ(W.nginx,j?.nginxTemplates),clientMaxBodySize:W.nginx?.clientMaxBodySize,hsts:W.ssl?.hsts,tlsProtocols:W.ssl?.tlsProtocols,security:W.security}):[],D=q?bQ(W):[],S=gQ(W)?fQ({slug:z,siteName:G,site:W,appBase:`/var/www/${G}`}):[],P=[...y7(`/var/www/${G}`,{releaseId:U,commit:U,branch:W.branch??"main"}),...M,...T,...D,...S];Y.step(`Deploying to ${A.length} target(s)...`);let C=await $.runRemoteDeploy({targets:A,commands:P,comment:`ts-cloud deploy ${z}/${G}@${U}`,tags:{Project:z,Environment:Q,Role:"app"}});if(!C.success)return{success:!1,error:C.error||"Remote deploy failed",instanceCount:C.instanceCount,perInstance:C.perInstance};return{success:!0,instanceCount:C.instanceCount,perInstance:C.perInstance}}async function p7($){let{config:J,environment:Y,driver:Z,sha:Q,runtime:G,tarballForSite:W,logger:z=dQ}=$,U=J.project.slug,H=$.cwd??process.cwd(),F=H$(J);IQ(J,{cwd:H,logger:{info:z.info,warn:z.warn}});let B=!F&&H$(J),K=null;if(B){if(K=kQ(J.sites?.[$8],{cwd:H,slug:U,sha:Q,logger:{info:z.info,warn:z.warn}}),!K){if(z.warn("Management dashboard: no artifact available — skipping dashboard site for this deploy."),J.sites)delete J.sites[$8]}}let O=J.sites||{},A=Object.entries(O).filter(([E,M])=>{if(!M)return!1;let j=p0(M);if(j==="bucket")return z.warn(`Site '${E}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(j==="redirect")return!1;return!0});if(A.length===0)return!0;let V=(E)=>E===$8&&K?K:W(E);for(let[E,M]of A){z.step(`Deploying site: ${E}`);let j=X9(M)?void 0:V(E),q=await cQ(Z,{config:J,environment:Y,siteName:E,site:M,slug:U,sha:Q,runtime:G,localTarballPath:j},z);if(!q.success){if(z.error(`Deploy of '${E}' failed: ${q.error||"unknown error"}`),q.perInstance)for(let T of q.perInstance)z.error(` ${T.instanceId}: ${T.status}${T.error?` — ${T.error}`:""}`);return!1}if(z.success(`Deployed ${U}/${E}@${Q} to ${q.instanceCount} target(s)`),q.perInstance)for(let T of q.perInstance)z.info(` ✓ ${T.instanceId}: ${T.status}`)}if(!await EF($))return!1;return!0}async function EF($){let{config:J,environment:Y,driver:Z,logger:Q=dQ}=$,G=J.infrastructure?.compute?.proxy;if(G?.engine!=="rpx")return!0;let W=J.sites||{},z=B9(W,{proxy:G});if(z.proxies.length===0)return Q.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let U=await Z.findComputeTargets({slug:J.project.slug,environment:Y,role:"app"});if(U.length===0)return Q.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;Q.step(`Reloading rpx gateway with ${z.proxies.length} route(s)...`);let H=K9({proxy:G,config:z,slug:J.project.slug}),F=await Z.runRemoteDeploy({targets:U,commands:H,comment:`ts-cloud rpx gateway reload ${J.project.slug}`,tags:{Project:J.project.slug,Environment:Y,Role:"app"}});if(!F.success)return Q.error(`rpx gateway reload failed: ${F.error||"unknown error"}`),!1;return Q.success(`rpx gateway reloaded on ${F.instanceCount} target(s)`),!0}var dQ;var mQ=o(async()=>{O$();xQ();sH();E7();GF();VF();zQ();LF();E9();C7();await z8([n0(),d7()]);dQ={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}}});var j$=o(async()=>{VQ();xQ();C7();await z8([KQ(),wQ(),mQ()]);mH()});function IT($){return`'${$.split("'").join("'\\''")}'`}function MF($){let J=$.user||"root",Y=$.script.join(`
7470
- `),Z=J==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${IT(J)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${$.name} (user=${J})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,Y,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',Z,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${$.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var T9={};h0(T9,{runComputeRecipe:()=>hT,rollbackComputeSite:()=>pQ,restoreDatabaseBackup:()=>rQ,getComputeDeployHistory:()=>kT});async function r7($){return await $.driver.findComputeTargets({slug:$.slug,environment:$.environment,role:$.role||"app"})}async function pQ($,J){let Y=$.logger||lQ,Z=await r7($);if(Z.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};let Q=`/var/www/${J.siteName}`,G=_$(Q,J.to||"unused"),W=["set -uo pipefail",...lH(G,J.to?{to:J.to}:{}),`(cd ${P1} && pantry restart php-fpm) 2>/dev/null || true`,`(cd ${G.current} && eval "$(cd ${P1} && pantry env 2>/dev/null)" && php artisan queue:restart) 2>/dev/null || true`];Y.step(`Rolling back ${J.siteName}${J.to?` to ${J.to}`:" to the previous release"} on ${Z.length} server(s)...`);let z=await $.driver.runRemoteDeploy({targets:Z,commands:W,comment:`ts-cloud rollback ${$.slug}/${J.siteName}`,tags:{Project:$.slug,Environment:$.environment,Role:$.role||"app"}});if(!z.success)Y.error(`Rollback failed: ${z.error||"unknown error"}`);else Y.success(`Rolled back ${J.siteName}.`);return{success:z.success,error:z.error,perInstance:z.perInstance}}async function kT($,J){let Y=await r7($);if(Y.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};let Z=SQ(`/var/www/${J.siteName}`),Q=Math.max(1,J.limit??20),G=[`[ -f ${Z} ] && tail -n ${Q} ${Z} || echo "no deploy history for ${J.siteName}"`],W=await $.driver.runRemoteDeploy({targets:Y,commands:G,comment:`ts-cloud deploy:history ${$.slug}/${J.siteName}`,tags:{Project:$.slug,Environment:$.environment,Role:$.role||"app"}});return{success:W.success,error:W.error,perInstance:W.perInstance}}async function hT($,J){let Y=$.logger||lQ,Z=await r7($);if(Z.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};Y.step(`Running recipe '${J.name}' as ${J.user||"root"} on ${Z.length} server(s)...`);let Q=await $.driver.runRemoteDeploy({targets:Z,commands:MF({name:J.name,script:J.script,user:J.user}),comment:`ts-cloud recipe ${J.name}`,tags:{Project:$.slug,Environment:$.environment,Role:$.role||"app"}});if(!Q.success)Y.error(`Recipe '${J.name}' failed: ${Q.error||"unknown error"}`);else Y.success(`Recipe '${J.name}' completed.`);return{success:Q.success,error:Q.error,perInstance:Q.perInstance}}async function rQ($,J){let Y=$.logger||lQ;if(!J.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let Z=await r7($);if(Z.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};Y.step(`Restoring database '${J.database.name}'${J.from?` from ${J.from}`:" from the latest backup"} on ${Z.length} server(s)...`);let Q=await $.driver.runRemoteDeploy({targets:Z,commands:RH(J.database,{from:J.from}),comment:`ts-cloud db:restore ${$.slug}/${J.database.name}`,tags:{Project:$.slug,Environment:$.environment,Role:$.role||"app"}});if(!Q.success)Y.error(`Restore failed: ${Q.error||"unknown error"}`);else Y.success(`Restored ${J.database.name}.`);return{success:Q.success,error:Q.error,perInstance:Q.perInstance}}var lQ;var J8=o(()=>{H2();E9();lQ={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}}});var qF={};h0(qF,{buildQuickDeployCi:()=>yT});function bT($){let J=$.sites||{};for(let Y of Object.values(J))if(Y?.repository?.url)return{provider:Y.repository.provider,branch:Y.repository.branch};return}function yT($,J="production"){let Y=bT($),Z=Y?.provider;if(Z!=="github"&&Z!=="gitlab"&&Z!=="bitbucket")return null;let Q=Y?.branch||"main",G=`bunx --bun ts-cloud deploy ${J}`;if(Z==="github")return{provider:Z,branch:Q,path:".github/workflows/deploy.yml",content:`name: Deploy
7472
+ `}function vQ($,J){return[`cat > /etc/systemd/system/${$}.service <<'TS_CLOUD_UNIT_EOF'`,J.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function wT($,J){return`/etc/cron.d/${$}-${J}-scheduler`}function fQ($){let{slug:J,siteName:Y,site:Z}=$,G=`${$.appBase??`/var/www/${Y}`}/current`,W=XF(HF(Z)),z={current:G},U=[],H=[];(Z.queues||[]).forEach((E,M)=>{let j=Math.max(1,E.processes??1);for(let q=0;q<j;q++){let T=qT(J,Y,H.length);H.push(T),U.push(...vQ(T,yQ({description:`${Y} queue worker ${M}.${q} (managed by ts-cloud)`,workingDir:G,execStart:W.wrapExec(W.queueWorkerCommand(E,z)),environment:W.execEnv,stopWaitSecs:E.stopWaitSecs??90})))}}),(Z.daemons||[]).forEach((E,M)=>{let j=Math.max(1,E.processes??1);for(let q=0;q<j;q++){let T=`${TT(J,Y,E,M)}-${q}`;H.push(T),U.push(...vQ(T,yQ({description:`${Y} daemon ${E.name||E.command} (managed by ts-cloud)`,workingDir:E.directory||G,execStart:W.wrapExec(E.command),environment:W.execEnv,restart:E.restart,user:E.user})))}});let K=Z.scheduler,O=K===!0||typeof K==="object"&&K!==null,A=`${J}-${Y}-scheduler`;if(O&&W.schedulerMode==="daemon")H.push(A),U.push(...vQ(A,yQ({description:`${Y} scheduler (managed by ts-cloud)`,workingDir:G,execStart:W.wrapExec(W.schedulerCommand(z)),environment:W.execEnv})));let V=H.map((E)=>`${E}.service`).join(" ");U.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${V}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${KF(J)}-${KF(Y)}-((queue|daemon)-.*|scheduler)\\.service$' || true); do`,' case " $TS_CLOUD_DESIRED " in',' *" $unit "*) ;;',' *) systemctl stop "$unit" 2>/dev/null || true; systemctl disable "$unit" 2>/dev/null || true; rm -f "/etc/systemd/system/$unit" ;;'," esac","done","systemctl daemon-reload");for(let E of H)U.push(`systemctl enable ${E}.service`,`systemctl restart ${E}.service`);let _=wT(J,Y);if(O&&W.schedulerMode==="cron"){let E=typeof K==="object"&&K!==null?K:void 0,M=`${W.schedulerCommand(z)} >> /dev/null 2>&1`;if(E?.heartbeatUrl){let q=E.heartbeatMethod||"GET",T=q==="GET"?"":`-X ${q} `;M+=` && curl -fsS -m 10 ${T}${MT(E.heartbeatUrl)} >/dev/null 2>&1`}let j=`* * * * * root ${M}
7473
+ `.replace(/%/g,"\\%");U.push(`cat > ${_} <<'TS_CLOUD_CRON_EOF'`,j.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${_}`)}else U.push(`rm -f ${_}`);return U}function gQ($){return!!($.queues?.length||$.daemons?.length||$.scheduler)}var VF=o(()=>{BF()});function l7($){return($.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function _F($){return`web_${l7($)}`}function NT($){let J=l7($),Y=0;for(let Z=0;Z<J.length;Z++)Y=Y*31+J.charCodeAt(Z)>>>0;return DT+Y%RT}function uQ($){return`127.0.0.1:${NT($)}`}function ST($){let J=l7($.siteName),Y=_F($.siteName),Z=$.maxChildren??10;return[`; ts-cloud-managed pool for ${$.siteName} (site isolation)`,`[${J}]`,`user = ${Y}`,`group = ${Y}`,`listen = ${uQ($.siteName)}`,"pm = dynamic",`pm.max_children = ${Z}`,"pm.start_servers = 2","pm.min_spare_servers = 1","pm.max_spare_servers = 3","pm.max_requests = 500","catch_workers_output = yes",`php_admin_value[open_basedir] = ${$.appBase}:/tmp`,""].join(`
7474
+ `)}function jF($){let J=_F($.siteName),Y=l7($.siteName),Z=`${AF}/${Y}.conf`;return[`getent group ${J} >/dev/null || groupadd --system ${J}`,`id -u ${J} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${J} ${J}`,`usermod -aG ${J} www-data 2>/dev/null || true`,`chown -R ${J}:${J} ${$.appBase} || true`,`chmod -R g+rX ${$.appBase} || true`,`chmod 600 ${$.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${AF}`,`cat > ${Z} <<'TS_CLOUD_FPMPOOL_EOF'`,ST($).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${P1} && pantry restart php-fpm) 2>/dev/null || true`]}var AF="/var/lib/pantry/php-fpm/pool.d",DT=9100,RT=400;var LF=o(()=>{H2()});async function cQ($,J,Y=dQ){let{config:Z,environment:Q,siteName:G,site:W,slug:z,sha:U,runtime:H,localTarballPath:F}=J,B=`releases/${G}/${U}.tar.gz`,K=E1(Z,Q),O=await $.getComputeOutputs({config:Z,environment:Q}),A=await $.findComputeTargets({slug:z,environment:Q,role:"app"});if(A.length===0)return{success:!1,error:$.name==="aws"?`Stack '${K}' has no EC2 instances tagged Project=${z} Environment=${Q} Role=app.`:`No Hetzner servers labeled ts-cloud/project=${z} ts-cloud/environment=${Q} ts-cloud/role=app.`};if(X9(W)){let I=Z.infrastructure?.compute,b=W.phpVersion??I?.php?.default??I?.php?.versions?.[0],y=`/var/www/${G}`,c=O.servicesPrivateIp?yH(O.servicesPrivateIp,Z.infrastructure?.appDatabase):AH(Z.infrastructure?.appDatabase),r=Object.keys(c).length>0?{...W,env:{...c,...W.env||{}}}:W,d=QF({siteName:G,site:r,releaseId:U,appBase:y,defaultPhpVersion:b}),g=I?.webServer!=="rpx",J0=hQ(W)==="custom"&&W.ssl?.certPath&&W.ssl?.keyPath?{certPath:W.ssl.certPath,keyPath:W.ssl.keyPath}:void 0,t=W.isolation?jF({siteName:G,appBase:y}):[],a=g?GQ({siteName:G,domain:W.domain||G,aliases:W.aliases,type:W.type,appDir:`${y}/current`,webDirectory:W.webDirectory,phpVersion:b,fastcgiPass:W.isolation?uQ(G):void 0,redirects:W.redirects,ssl:J0,auth:W.auth&&W.auth.enabled!==!1&&W.auth.password?{username:W.auth.username||"admin",password:W.auth.password,realm:W.auth.realm}:void 0,serverSnippet:QQ(W.nginx,I?.nginxTemplates),clientMaxBodySize:W.nginx?.clientMaxBodySize,hsts:W.ssl?.hsts,tlsProtocols:W.ssl?.tlsProtocols,security:W.security}):[],e=g?bQ(W):[],j0=gQ(W)?fQ({slug:z,siteName:G,site:W,phpVersion:b,appBase:y}):[],w0=g?ZF(W):[];Y.step(`Deploying PHP site '${G}' to ${A.length} target(s)...`);let B0=await $.runRemoteDeploy({targets:A,commands:[...d,...t,...a,...e,...j0,...w0],comment:`ts-cloud deploy ${z}/${G}@${U}`,tags:{Project:z,Environment:Q,Role:"app"}}),X1=wH(Z.notifications,W.notifications);if(!B0.success)return await FQ(X1,"deploy-failed",`❌ Deploy of ${z}/${G}@${U} failed: ${B0.error||"unknown error"}`),{success:!1,error:B0.error||"Remote PHP deploy failed",instanceCount:B0.instanceCount,perInstance:B0.perInstance};let d1=W.domain?` → https://${W.domain}`:"";return await FQ(X1,"deploy",`✅ Deployed ${z}/${G}@${U}${d1}`),{success:!0,instanceCount:B0.instanceCount,perInstance:B0.perInstance}}if(!F)return{success:!1,error:`Site '${G}' requires a release tarball but none was provided`};let V=await $.uploadRelease({config:Z,environment:Q,localPath:F,remoteKey:B,targets:A}),_=$.name==="aws"?PQ(O.deployBucketName,B,Z.project.region||"us-east-1",G):CQ(V.artifactRef,G),E=p0(W),M=E==="server-static"?g7({siteName:G,artifactFetch:_,releaseId:U,preStartCommands:W.preStart}):f7({siteName:G,slug:z,artifactFetch:_,releaseId:U,execStart:v7(W.start,H),envEntries:W.env||{},port:W.port,preStartCommands:W.preStart}),j=Z.infrastructure?.compute,q=E==="server-static"&&j?.webServer!=="rpx"&&!!W.domain,T=q?GQ({siteName:G,domain:W.domain,aliases:W.aliases,type:W.type==="spa"?"spa":"static",appDir:`/var/www/${G}/current`,webDirectory:"",redirects:W.redirects,auth:W.auth&&W.auth.enabled!==!1&&W.auth.password?{username:W.auth.username||"admin",password:W.auth.password,realm:W.auth.realm}:void 0,serverSnippet:QQ(W.nginx,j?.nginxTemplates),clientMaxBodySize:W.nginx?.clientMaxBodySize,hsts:W.ssl?.hsts,tlsProtocols:W.ssl?.tlsProtocols,security:W.security}):[],D=q?bQ(W):[],S=gQ(W)?fQ({slug:z,siteName:G,site:W,appBase:`/var/www/${G}`}):[],P=[...y7(`/var/www/${G}`,{releaseId:U,commit:U,branch:W.branch??"main"}),...M,...T,...D,...S];Y.step(`Deploying to ${A.length} target(s)...`);let C=await $.runRemoteDeploy({targets:A,commands:P,comment:`ts-cloud deploy ${z}/${G}@${U}`,tags:{Project:z,Environment:Q,Role:"app"}});if(!C.success)return{success:!1,error:C.error||"Remote deploy failed",instanceCount:C.instanceCount,perInstance:C.perInstance};return{success:!0,instanceCount:C.instanceCount,perInstance:C.perInstance}}async function p7($){let{config:J,environment:Y,driver:Z,sha:Q,runtime:G,tarballForSite:W,logger:z=dQ}=$,U=J.project.slug,H=$.cwd??process.cwd(),F=H$(J);IQ(J,{cwd:H,logger:{info:z.info,warn:z.warn}});let B=!F&&H$(J),K=null;if(B){if(K=kQ(J.sites?.[$8],{cwd:H,slug:U,sha:Q,logger:{info:z.info,warn:z.warn}}),!K){if(z.warn("Management dashboard: no artifact available — skipping dashboard site for this deploy."),J.sites)delete J.sites[$8]}}let O=J.sites||{},A=Object.entries(O).filter(([E,M])=>{if(!M)return!1;let j=p0(M);if(j==="bucket")return z.warn(`Site '${E}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(j==="redirect")return!1;return!0});if(A.length===0)return!0;let V=(E)=>E===$8&&K?K:W(E);for(let[E,M]of A){z.step(`Deploying site: ${E}`);let j=X9(M)?void 0:V(E),q=await cQ(Z,{config:J,environment:Y,siteName:E,site:M,slug:U,sha:Q,runtime:G,localTarballPath:j},z);if(!q.success){if(z.error(`Deploy of '${E}' failed: ${q.error||"unknown error"}`),q.perInstance)for(let T of q.perInstance)z.error(` ${T.instanceId}: ${T.status}${T.error?` — ${T.error}`:""}`);return!1}if(z.success(`Deployed ${U}/${E}@${Q} to ${q.instanceCount} target(s)`),q.perInstance)for(let T of q.perInstance)z.info(` ✓ ${T.instanceId}: ${T.status}`)}if(!await EF($))return!1;return!0}async function EF($){let{config:J,environment:Y,driver:Z,logger:Q=dQ}=$,G=J.infrastructure?.compute?.proxy;if(G?.engine!=="rpx")return!0;let W=J.sites||{},z=B9(W,{proxy:G});if(z.proxies.length===0)return Q.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let U=await Z.findComputeTargets({slug:J.project.slug,environment:Y,role:"app"});if(U.length===0)return Q.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;Q.step(`Reloading rpx gateway with ${z.proxies.length} route(s)...`);let H=K9({proxy:G,config:z,slug:J.project.slug}),F=await Z.runRemoteDeploy({targets:U,commands:H,comment:`ts-cloud rpx gateway reload ${J.project.slug}`,tags:{Project:J.project.slug,Environment:Y,Role:"app"}});if(!F.success)return Q.error(`rpx gateway reload failed: ${F.error||"unknown error"}`),!1;return Q.success(`rpx gateway reloaded on ${F.instanceCount} target(s)`),!0}var dQ;var mQ=o(async()=>{O$();xQ();sH();E7();GF();VF();zQ();LF();E9();C7();await z8([n0(),d7()]);dQ={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}}});var j$=o(async()=>{VQ();xQ();C7();await z8([KQ(),wQ(),mQ()]);mH()});function xT($){return`'${$.split("'").join("'\\''")}'`}function MF($){let J=$.user||"root",Y=$.script.join(`
7475
+ `),Z=J==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${xT(J)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${$.name} (user=${J})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,Y,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',Z,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${$.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var T9={};h0(T9,{runComputeRecipe:()=>kT,rollbackComputeSite:()=>pQ,restoreDatabaseBackup:()=>rQ,getComputeDeployHistory:()=>IT});async function r7($){return await $.driver.findComputeTargets({slug:$.slug,environment:$.environment,role:$.role||"app"})}async function pQ($,J){let Y=$.logger||lQ,Z=await r7($);if(Z.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};let Q=`/var/www/${J.siteName}`,G=_$(Q,J.to||"unused"),W=["set -uo pipefail",...lH(G,J.to?{to:J.to}:{}),`(cd ${P1} && pantry restart php-fpm) 2>/dev/null || true`,`(cd ${G.current} && eval "$(cd ${P1} && pantry env 2>/dev/null)" && php artisan queue:restart) 2>/dev/null || true`];Y.step(`Rolling back ${J.siteName}${J.to?` to ${J.to}`:" to the previous release"} on ${Z.length} server(s)...`);let z=await $.driver.runRemoteDeploy({targets:Z,commands:W,comment:`ts-cloud rollback ${$.slug}/${J.siteName}`,tags:{Project:$.slug,Environment:$.environment,Role:$.role||"app"}});if(!z.success)Y.error(`Rollback failed: ${z.error||"unknown error"}`);else Y.success(`Rolled back ${J.siteName}.`);return{success:z.success,error:z.error,perInstance:z.perInstance}}async function IT($,J){let Y=await r7($);if(Y.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};let Z=SQ(`/var/www/${J.siteName}`),Q=Math.max(1,J.limit??20),G=[`[ -f ${Z} ] && tail -n ${Q} ${Z} || echo "no deploy history for ${J.siteName}"`],W=await $.driver.runRemoteDeploy({targets:Y,commands:G,comment:`ts-cloud deploy:history ${$.slug}/${J.siteName}`,tags:{Project:$.slug,Environment:$.environment,Role:$.role||"app"}});return{success:W.success,error:W.error,perInstance:W.perInstance}}async function kT($,J){let Y=$.logger||lQ,Z=await r7($);if(Z.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};Y.step(`Running recipe '${J.name}' as ${J.user||"root"} on ${Z.length} server(s)...`);let Q=await $.driver.runRemoteDeploy({targets:Z,commands:MF({name:J.name,script:J.script,user:J.user}),comment:`ts-cloud recipe ${J.name}`,tags:{Project:$.slug,Environment:$.environment,Role:$.role||"app"}});if(!Q.success)Y.error(`Recipe '${J.name}' failed: ${Q.error||"unknown error"}`);else Y.success(`Recipe '${J.name}' completed.`);return{success:Q.success,error:Q.error,perInstance:Q.perInstance}}async function rQ($,J){let Y=$.logger||lQ;if(!J.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let Z=await r7($);if(Z.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};Y.step(`Restoring database '${J.database.name}'${J.from?` from ${J.from}`:" from the latest backup"} on ${Z.length} server(s)...`);let Q=await $.driver.runRemoteDeploy({targets:Z,commands:RH(J.database,{from:J.from}),comment:`ts-cloud db:restore ${$.slug}/${J.database.name}`,tags:{Project:$.slug,Environment:$.environment,Role:$.role||"app"}});if(!Q.success)Y.error(`Restore failed: ${Q.error||"unknown error"}`);else Y.success(`Restored ${J.database.name}.`);return{success:Q.success,error:Q.error,perInstance:Q.perInstance}}var lQ;var J8=o(()=>{H2();E9();lQ={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}}});var qF={};h0(qF,{buildQuickDeployCi:()=>bT});function hT($){let J=$.sites||{};for(let Y of Object.values(J))if(Y?.repository?.url)return{provider:Y.repository.provider,branch:Y.repository.branch};return}function bT($,J="production"){let Y=hT($),Z=Y?.provider;if(Z!=="github"&&Z!=="gitlab"&&Z!=="bitbucket")return null;let Q=Y?.branch||"main",G=`bunx --bun ts-cloud deploy ${J}`;if(Z==="github")return{provider:Z,branch:Q,path:".github/workflows/deploy.yml",content:`name: Deploy
7471
7476
  on:
7472
7477
  push:
7473
7478
  branches: [${Q}]
@@ -7504,23 +7509,23 @@ jobs:
7504
7509
  - bun install --frozen-lockfile
7505
7510
  - ${G}
7506
7511
  # Set HETZNER_API_TOKEN / AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY as repo vars.
7507
- `}}class n7{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async describeFileSystems($){let J=[];if($?.FileSystemId)J.push(`FileSystemId=${encodeURIComponent($.FileSystemId)}`);if($?.CreationToken)J.push(`CreationToken=${encodeURIComponent($.CreationToken)}`);let Y=`/2015-02-01/file-systems${J.length>0?`?${J.join("&")}`:""}`;return{FileSystems:((await this.client.request({service:"elasticfilesystem",region:this.region,method:"GET",path:Y,headers:{"Content-Type":"application/json"}})).FileSystems||[]).map((Q)=>({FileSystemId:Q.FileSystemId,Name:Q.Name,CreationTime:Q.CreationTime,LifeCycleState:Q.LifeCycleState,NumberOfMountTargets:Q.NumberOfMountTargets,SizeInBytes:Q.SizeInBytes?{Value:Q.SizeInBytes.Value,Timestamp:Q.SizeInBytes.Timestamp}:void 0,PerformanceMode:Q.PerformanceMode,Encrypted:Q.Encrypted,ThroughputMode:Q.ThroughputMode,Tags:Q.Tags}))}}}var nQ=o(()=>{Y0()});var TF={};h0(TF,{SQSClient:()=>C1});class C1{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async createQueue($){let Y={Action:"CreateQueue",QueueName:$.fifo&&!$.queueName.endsWith(".fifo")?`${$.queueName}.fifo`:$.queueName,Version:"2012-11-05"},Z=1;if($.visibilityTimeout!==void 0)Y[`Attribute.${Z}.Name`]="VisibilityTimeout",Y[`Attribute.${Z}.Value`]=$.visibilityTimeout.toString(),Z++;if($.messageRetentionPeriod!==void 0)Y[`Attribute.${Z}.Name`]="MessageRetentionPeriod",Y[`Attribute.${Z}.Value`]=$.messageRetentionPeriod.toString(),Z++;if($.delaySeconds!==void 0)Y[`Attribute.${Z}.Name`]="DelaySeconds",Y[`Attribute.${Z}.Value`]=$.delaySeconds.toString(),Z++;if($.maxMessageSize!==void 0)Y[`Attribute.${Z}.Name`]="MaximumMessageSize",Y[`Attribute.${Z}.Value`]=$.maxMessageSize.toString(),Z++;if($.receiveMessageWaitTime!==void 0)Y[`Attribute.${Z}.Name`]="ReceiveMessageWaitTimeSeconds",Y[`Attribute.${Z}.Value`]=$.receiveMessageWaitTime.toString(),Z++;if($.fifo){if(Y[`Attribute.${Z}.Name`]="FifoQueue",Y[`Attribute.${Z}.Value`]="true",Z++,$.contentBasedDeduplication)Y[`Attribute.${Z}.Name`]="ContentBasedDeduplication",Y[`Attribute.${Z}.Value`]="true",Z++}if($.deadLetterTargetArn&&$.maxReceiveCount)Y[`Attribute.${Z}.Name`]="RedrivePolicy",Y[`Attribute.${Z}.Value`]=JSON.stringify({deadLetterTargetArn:$.deadLetterTargetArn,maxReceiveCount:$.maxReceiveCount}),Z++;if($.tags&&Object.keys($.tags).length>0){let G=1;for(let[W,z]of Object.entries($.tags))Y[`Tag.${G}.Key`]=W,Y[`Tag.${G}.Value`]=z,G++}let Q=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()});return{QueueUrl:Q.QueueUrl||Q.CreateQueueResult?.QueueUrl}}async listQueues($){let J={Action:"ListQueues",Version:"2012-11-05"};if($)J.QueueNamePrefix=$;let Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()}),Z=[];if(Y.QueueUrl)Z.push(Y.QueueUrl);else if(Y.ListQueuesResult?.QueueUrl)if(Array.isArray(Y.ListQueuesResult.QueueUrl))Z.push(...Y.ListQueuesResult.QueueUrl);else Z.push(Y.ListQueuesResult.QueueUrl);return{QueueUrls:Z}}async getQueueAttributes($){let J={Action:"GetQueueAttributes",QueueUrl:$,Version:"2012-11-05","AttributeName.1":"All"},Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{Attributes:Y.Attributes||Y.GetQueueAttributesResult?.Attributes||{}}}async getQueueUrl($){let J={Action:"GetQueueUrl",QueueName:$,Version:"2012-11-05"},Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{QueueUrl:Y.QueueUrl||Y.GetQueueUrlResult?.QueueUrl}}async deleteQueue($){let J={Action:"DeleteQueue",QueueUrl:$,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()})}async purgeQueue($){let J={Action:"PurgeQueue",QueueUrl:$,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()})}async sendMessage($){let J={Action:"SendMessage",QueueUrl:$.queueUrl,MessageBody:$.messageBody,Version:"2012-11-05"};if($.delaySeconds!==void 0)J.DelaySeconds=$.delaySeconds;if($.messageGroupId)J.MessageGroupId=$.messageGroupId;if($.messageDeduplicationId)J.MessageDeduplicationId=$.messageDeduplicationId;let Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{MessageId:Y.MessageId||Y.SendMessageResult?.MessageId}}async receiveMessages($){let J={Action:"ReceiveMessage",QueueUrl:$.queueUrl,Version:"2012-11-05"};if($.maxMessages!==void 0)J.MaxNumberOfMessages=$.maxMessages;if($.visibilityTimeout!==void 0)J.VisibilityTimeout=$.visibilityTimeout;if($.waitTimeSeconds!==void 0)J.WaitTimeSeconds=$.waitTimeSeconds;let Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()}),Z=[],Q=Y.Message||Y.ReceiveMessageResult?.Message;if(Q)if(Array.isArray(Q))Z.push(...Q.map((G)=>({MessageId:G.MessageId,ReceiptHandle:G.ReceiptHandle,Body:G.Body})));else Z.push({MessageId:Q.MessageId,ReceiptHandle:Q.ReceiptHandle,Body:Q.Body});return{Messages:Z}}async deleteMessage($,J){let Y={Action:"DeleteMessage",QueueUrl:$,ReceiptHandle:J,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}}var w9=o(()=>{Y0()});class iQ{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async call($,J){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${$}`},body:JSON.stringify(J)})}async listWebACLs($="REGIONAL"){return(await this.call("ListWebACLs",{Scope:$,Limit:100}))?.WebACLs??[]}async getWebACLRules($,J,Y="REGIONAL"){return((await this.call("GetWebACL",{Name:$,Id:J,Scope:Y}))?.WebACL?.Rules??[]).map((G)=>({Name:G.Name,Priority:G.Priority,Action:G.Action?Object.keys(G.Action)[0]:G.OverrideAction?Object.keys(G.OverrideAction)[0]:"count"}))}}var wF=o(()=>{Y0()});var RF={};h0(RF,{resolveDashboardData:()=>i7});function DF($){return String($).padStart(2,"0")}function Y8($){return`${$.getUTCFullYear()}-${DF($.getUTCMonth()+1)}-${DF($.getUTCDate())}`}function vT($){let J=Math.max(0,Math.round((Date.now()-$)/1000));if(J<60)return`${J}s ago`;let Y=Math.round(J/60);if(Y<60)return`${Y}m ago`;let Z=Math.round(Y/60);if(Z<48)return`${Z}h ago`;return`${Math.round(Z/24)}d ago`}async function D9($,J,Y,Z,Q,G){let W=await $.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:Y,Dimensions:[{Name:"FunctionName",Value:J}],StartTime:Q,EndTime:G,Period:86400,Statistics:[Z]}).catch(()=>[]);if(!W.length)return 0;if(Z==="Sum")return W.reduce((z,U)=>z+(U.Sum??0),0);if(Z==="Maximum")return Math.max(...W.map((z)=>z.Maximum??0));return W.reduce((z,U)=>z+(U.Average??0),0)/W.length}async function R9($,J,Y,Z,Q,G,W){let z=await $.getMetricStatistics({Namespace:J,MetricName:Y,Dimensions:Z,StartTime:G,EndTime:W,Period:86400,Statistics:[Q]}).catch(()=>[]);if(!z.length)return 0;if(Q==="Sum")return z.reduce((U,H)=>U+(H.Sum??0),0);if(Q==="Maximum")return Math.max(...z.map((U)=>U.Maximum??0));return z.reduce((U,H)=>U+(H.Average??0),0)/z.length}async function aQ($,J,Y,Z,Q){let G=await $.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:J}],StartTime:Z,EndTime:Q,Period:86400,ExtendedStatistics:[Y]}).catch(()=>[]);return Math.round(G.reduce((W,z)=>W+(z.Percentiles?.[Y]??0),0))}async function i7($,J){let Y=await yZ($,J),Z=Y.region,Q=new X$(Z),G=new l0(Z),W=new p2(Z),z=new Date,U=new Date(z.getTime()-86400000),H=$.environments?.[J]?.app,F={};F.app={name:Y.slug,env:J,region:Z,runtime:H?.kind==="php"?`php-${H?.phpVersion??"8.3"} (fpm)`:H?.kind??"node",url:Y.endpoint??"",build:Y.lastRelease?.sha?.slice(0,7)??"—",deployedAt:Y.lastRelease?.timestamp??"—"},F.maintenance={enabled:!1},F.scheduler={enabled:Y.scheduler!=="off",expression:Y.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let B=0,K=0,O=0,A=[],V=[],_=[];for(let j of Y.functions){let[q,T,D,S,P,C,I,b,y]=await Promise.all([D9(Q,j.name,"Invocations","Sum",U,z),D9(Q,j.name,"Errors","Sum",U,z),D9(Q,j.name,"Throttles","Sum",U,z),D9(Q,j.name,"Duration","Average",U,z),G.getFunction(j.name).catch(()=>null),aQ(Q,j.name,"p50",U,z),aQ(Q,j.name,"p95",U,z),aQ(Q,j.name,"p99",U,z),Q.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:j.name}],StartTime:new Date(z.getTime()-43200000),EndTime:z,Period:3600,Stat:"Sum"}).catch(()=>[])]);B+=q,K+=T,O=Math.max(O,S);let c=P?.Configuration?.MemorySize??0,r=Object.keys(P?.Configuration?.Environment?.Variables??{}),d=[],g=0;try{let{events:J0=[]}=await W.filterLogEvents({logGroupName:`/aws/lambda/${j.name}`,startTime:U.getTime(),limit:120});for(let t of J0){let a=(t.message??"").trim(),e=/Max Memory Used:\s*(\d+)\s*MB/.exec(a);if(e)g=Math.max(g,Number(e[1]));if(a&&!/^(?:START|END|REPORT|INIT_START)/.test(a))_.push({source:j.mode||j.name,timestamp:new Date(t.timestamp??0).toISOString(),when:vT(t.timestamp??0),message:a.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(a)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(a)?"warn":"info"})}d=J0.filter((t)=>!/^(?:START|END|REPORT|INIT_START)/.test((t.message??"").trim())).slice(-6).map((t)=>({ts:new Date(t.timestamp??0).toISOString().slice(11,19),msg:(t.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(t.message??"")}))}catch{}let s=Math.max(1,...y);A.push({key:j.mode,name:j.name,version:j.version,memory:c,timeout:P?.Configuration?.Timeout??0,runtime:P?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(q),errors:Math.round(T),p95:I||Math.round(S),status:"active",provisioned:j.provisioned?`${j.provisioned.allocated}/${j.provisioned.requested}`:void 0}),V.push({key:j.mode,name:j.name,runtime:P?.Configuration?.Runtime??"provided.al2023",arch:P?.Configuration?.Architectures?.[0]??"x86_64",memory:c,timeout:P?.Configuration?.Timeout??0,ephemeral:P?.Configuration?.EphemeralStorage?.Size??512,version:j.version,concurrency:H?.concurrency??"—",invocations:Math.round(q),errors:Math.round(T),throttles:Math.round(D),p50:C||Math.round(S),p95:I||Math.round(S),p99:b||Math.round(S),maxMem:g,spark:y.length?y.map((J0)=>Math.round(J0/s*100)):[0],env:r.length?r:["(none)"],recent:d.length?d:[{ts:"—",msg:"no recent events",err:!1}]})}F.functions=A,F.functionsDetail=V,F.serverlessLogs=_.sort((j,q)=>String(q.timestamp).localeCompare(String(j.timestamp))).slice(0,600),F.serverlessLogsEmptyReason=_.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let E=B?Number((K/B*100).toFixed(2)):0,M=Math.round(await D9(Q,Y.functions[0]?.name??"","ConcurrentExecutions","Maximum",U,z));F.metrics={invocations:Math.round(B),errorRatePct:E,p95Ms:Math.round(O),coldStartPct:0,concurrency:M,estCostUsd:0};try{let j=new C1(Z),q=[],T=[],D=0;try{let{QueueUrl:P}=await j.getQueueUrl(`${Y.slug}-${J}-dlq`),{Attributes:C}=await j.getQueueAttributes(P);D=Number(C.ApproximateNumberOfMessages??0)}catch{}let S=H?m8(H,Y.slug,J):[];for(let P of S){let C=P.name.replace(`${Y.slug}-${J}-`,""),I=0,b=0;try{let{QueueUrl:c}=await j.getQueueUrl(P.name),{Attributes:r}=await j.getQueueAttributes(c);I=Number(r.ApproximateNumberOfMessages??0),b=Number(r.ApproximateNumberOfMessagesNotVisible??0)}catch{}let y=Math.round(await R9(Q,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:P.name}],"Sum",U,z));q.push({name:C,visible:I,inFlight:b,processed:y,dlq:D}),T.push({name:P.name,short:C,visible:I,inFlight:b,delayed:0,processed:y,oldestSec:0,concurrency:P.concurrency??H?.queueConcurrency??"—",tries:H?.queueTries??3,visTimeout:(H?.queueTimeout??120)*6,dlq:D})}if(q.length)F.queues=q;if(T.length)F.queuesDetail=T;F.dlqItems=[]}catch{}try{let j=new O0(Z),{Stacks:q}=await j.describeStacks({stackName:U$($,J)}),T={};for(let D of q?.[0]?.Outputs??[])if(D.OutputKey)T[D.OutputKey]=D.OutputValue??"";if(H?.database?.connection==="aurora-serverless"){let D=`${Y.slug}-${J}-db`,S=[{Name:"DBClusterIdentifier",Value:D}],[P,C]=await Promise.all([R9(Q,"AWS/RDS","ServerlessDatabaseCapacity",S,"Average",U,z),R9(Q,"AWS/RDS","DatabaseConnections",S,"Maximum",U,z)]);if(F.aurora={id:D,engine:"aurora-mysql",minAcu:H?.database?.minCapacity??0.5,maxAcu:H?.database?.maxCapacity??4,currentAcu:P?Number(P.toFixed(1)):H?.database?.minCapacity??0.5,database:"app",connections:Math.round(C),status:T.DbEndpoint?"available":"creating"},H?.rdsProxy)F.proxy={name:`${Y.slug}-${J}-proxy`,endpoint:T.DbProxyEndpoint??"—",pooledConns:Math.round(C),status:"available"}}if(H?.cache?.driver==="elasticache"){let D=`${Y.slug}-${J}-cache`,S=[{Name:"CacheClusterId",Value:`${D}-001`}],[P,C]=await Promise.all([R9(Q,"AWS/ElastiCache","CacheHits",S,"Sum",U,z),R9(Q,"AWS/ElastiCache","CacheMisses",S,"Sum",U,z)]),I=P+C>0?Number((P/(P+C)*100).toFixed(1)):0;F.redis={id:D,node:"cache.t4g.micro",engine:"redis",hitRate:I,status:T.CacheEndpoint?"available":"creating"}}if(H?.efs){let D=0;try{if(T.EfsFileSystemId){let S=new n7(Z),{FileSystems:P}=await S.describeFileSystems({FileSystemId:T.EfsFileSystemId});D=Number(((P?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}F.efs={id:T.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:D,status:"available"}}F.assetsInfo=T.AssetsCdnDomain?{bucket:T.AssetsBucketName??`${Y.slug}-${J}-assets`,cdn:T.AssetsCdnDomain,customDomain:H?.assetDomain??"—",assetUrl:Y.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:F.app.build}:void 0}catch{}if(F.assetsInfo)try{let q=await new W0(Z).list({bucket:F.assetsInfo.bucket,maxKeys:1000});F.assetsInfo.files=q.length,F.assetsInfo.sizeMb=Number((q.reduce((T,D)=>T+(D.Size??0),0)/1048576).toFixed(1)),F.assetsRecent=q.slice(0,8).map((T)=>({path:`/${T.Key}`,size:`${Math.max(1,Math.round((T.Size??0)/1024))} KB`,type:T.Key.split(".").pop()??""}))}catch{}try{if(H?.secrets){let j=Array.isArray(H.secrets)?H.secrets.map((q)=>({key:q.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:q})):Object.entries(H.secrets).map(([q,T])=>({key:q,source:String(T)}));F.secretsList=j.map((q)=>({...q,updated:"—"}))}}catch{}try{let j=new W0(Z),q=`${Y.slug}-${J}-deployments`,T=await j.getObjectJson(q,`deployments/${Y.slug}/${J}/history.json`).catch(()=>null);if(T?.records?.length)F.deploymentsDetail=T.records.slice(-12).reverse().map((D)=>({sha:(D.sha??"").slice(0,7),status:D.status??"success",when:D.timestamp??"—",took:D.took??"—",by:D.by??"—",version:D.version??"—",hooks:D.hooks??[]}))}catch{}F.metricsTotals={invocations:F.metrics.invocations,errors:Math.round(K),errorRatePct:E,p95Ms:F.metrics.p95Ms,throttles:V.reduce((j,q)=>j+q.throttles,0),coldStartPct:0,estCostUsd:0,concurrency:M},F.metricsPerFn=V.map((j)=>({key:j.key,invocations:j.invocations,errors:j.errors,throttles:j.throttles,avgMs:j.p50,maxMs:j.p99,costUsd:0}));try{F.invSpark=await Q.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:Y.functions.find((j)=>j.mode==="http")?.name??""}],StartTime:new Date(z.getTime()-86400000),EndTime:z,Period:3600,Stat:"Sum"})}catch{}try{let j=new s8,q=z,T=new Date(Date.UTC(q.getUTCFullYear(),q.getUTCMonth(),1)),D=new Date(Date.UTC(q.getUTCFullYear(),q.getUTCMonth()-1,1)),[S,P]=await Promise.all([j.getCostByService({start:Y8(T),end:Y8(q),granularity:"MONTHLY"}).catch(()=>[]),j.getCostByService({start:Y8(D),end:Y8(T),granularity:"MONTHLY"}).catch(()=>[])]);if(S.length){let C=S.reduce((g,s)=>g+s.amount,0),I=P.reduce((g,s)=>g+s.amount,0),b=q.getUTCDate(),y=new Date(Date.UTC(q.getUTCFullYear(),q.getUTCMonth()+1,0)).getUTCDate();F.costSummary={monthToDateUsd:Number(C.toFixed(2)),projectedUsd:Number((C/b*y).toFixed(2)),lastMonthUsd:Number(I.toFixed(2)),dailyAvgUsd:Number((C/b).toFixed(2))},F.costServices=S.filter((g)=>g.amount>0).sort((g,s)=>s.amount-g.amount).slice(0,12).map((g)=>({name:g.service,usd:Number(g.amount.toFixed(2)),note:""})),F.metrics.estCostUsd=Number((C/b).toFixed(2)),F.metricsTotals.estCostUsd=F.metrics.estCostUsd,F.costTrend=await j.getDailyTotals({start:Y8(T),end:Y8(q)}).catch(()=>[]);let c=S.find((g)=>/lambda/i.test(g.service))?.amount??0,r=(g)=>g.invocations*(g.p50/1000)*(g.memory/1024),d=V.reduce((g,s)=>g+r(s),0)||1;F.costPerFn=V.map((g)=>({key:g.key,requests:g.invocations,gbSec:Math.round(r(g)),usd:Number((c*(r(g)/d)).toFixed(2))}))}}catch{}if(H?.firewall)try{let j=await Q.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:U,EndTime:z,Period:86400,Statistics:["Sum"]}).catch(()=>[]),q=await Q.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:U,EndTime:z,Period:86400,Statistics:["Sum"]}).catch(()=>[]);F.waf={enabled:!0,scope:"REGIONAL",acl:`${Y.slug}-${J}-waf`,allowed24h:Math.round(q.reduce((T,D)=>T+(D.Sum??0),0)),blocked24h:Math.round(j.reduce((T,D)=>T+(D.Sum??0),0))};try{let T=new iQ(Z),D=await T.listWebACLs("REGIONAL"),S=D.find((P)=>P.Name?.includes(`${Y.slug}-${J}`))??D[0];if(S?.Name&&S.Id){F.waf.acl=S.Name;let P=await T.getWebACLRules(S.Name,S.Id,"REGIONAL");if(P.length)F.wafRules=P.map((C)=>({name:C.Name??"—",detail:`priority ${C.Priority??0}`,action:C.Action??"count",blocked24h:0}))}}catch{}}catch{}if(Y.scheduler!=="off"&&H?.kind==="php")try{let j=await n$($,J,"schedule:list"),q=[];for(let T of(j||"").split(`
7508
- `)){let D=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(T);if(D&&/[*\d]/.test(D[1])&&D[1].trim().split(/\s+/).length===5)q.push({command:D[2].trim().replace(/^php artisan /,""),cron:D[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(q.length)F.schedulerTasks=q}catch{}return F}var a7=o(async()=>{M1();NZ();i8();U7();nQ();a1();I0();w9();wF();await z8([n0(),Q1()])});import{createHash as fT}from"node:crypto";function SF($){let J=tQ($.name),Y=sQ($.publicKey),Z=uT([...$.existingKeys??[],{name:J,publicKey:Y}]);return CF($.configText,Z)}function PF($){let J=tQ($.name),Y=($.existingKeys??[]).filter((Z)=>Z.name!==J);if(($.existingKeys??[]).length===Y.length)throw Error(`SSH key '${J}' does not exist in compute.sshKeys`);return CF($.configText,Y)}function n2($=[]){return $.map((J)=>({name:J.name,publicKey:J.publicKey,type:dT(J.publicKey),fingerprint:cT(J.publicKey),added:"configured"}))}function CF($,J){let Y=mT($,"compute"),Z=gT(J),Q=lT($,Y.start,Y.end,"sshKeys");if(Q){let U=Q.propertyStart;while(U>0&&$[U-1]!==`
7512
+ `}}class n7{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async describeFileSystems($){let J=[];if($?.FileSystemId)J.push(`FileSystemId=${encodeURIComponent($.FileSystemId)}`);if($?.CreationToken)J.push(`CreationToken=${encodeURIComponent($.CreationToken)}`);let Y=`/2015-02-01/file-systems${J.length>0?`?${J.join("&")}`:""}`;return{FileSystems:((await this.client.request({service:"elasticfilesystem",region:this.region,method:"GET",path:Y,headers:{"Content-Type":"application/json"}})).FileSystems||[]).map((Q)=>({FileSystemId:Q.FileSystemId,Name:Q.Name,CreationTime:Q.CreationTime,LifeCycleState:Q.LifeCycleState,NumberOfMountTargets:Q.NumberOfMountTargets,SizeInBytes:Q.SizeInBytes?{Value:Q.SizeInBytes.Value,Timestamp:Q.SizeInBytes.Timestamp}:void 0,PerformanceMode:Q.PerformanceMode,Encrypted:Q.Encrypted,ThroughputMode:Q.ThroughputMode,Tags:Q.Tags}))}}}var nQ=o(()=>{Y0()});var TF={};h0(TF,{SQSClient:()=>C1});class C1{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async createQueue($){let Y={Action:"CreateQueue",QueueName:$.fifo&&!$.queueName.endsWith(".fifo")?`${$.queueName}.fifo`:$.queueName,Version:"2012-11-05"},Z=1;if($.visibilityTimeout!==void 0)Y[`Attribute.${Z}.Name`]="VisibilityTimeout",Y[`Attribute.${Z}.Value`]=$.visibilityTimeout.toString(),Z++;if($.messageRetentionPeriod!==void 0)Y[`Attribute.${Z}.Name`]="MessageRetentionPeriod",Y[`Attribute.${Z}.Value`]=$.messageRetentionPeriod.toString(),Z++;if($.delaySeconds!==void 0)Y[`Attribute.${Z}.Name`]="DelaySeconds",Y[`Attribute.${Z}.Value`]=$.delaySeconds.toString(),Z++;if($.maxMessageSize!==void 0)Y[`Attribute.${Z}.Name`]="MaximumMessageSize",Y[`Attribute.${Z}.Value`]=$.maxMessageSize.toString(),Z++;if($.receiveMessageWaitTime!==void 0)Y[`Attribute.${Z}.Name`]="ReceiveMessageWaitTimeSeconds",Y[`Attribute.${Z}.Value`]=$.receiveMessageWaitTime.toString(),Z++;if($.fifo){if(Y[`Attribute.${Z}.Name`]="FifoQueue",Y[`Attribute.${Z}.Value`]="true",Z++,$.contentBasedDeduplication)Y[`Attribute.${Z}.Name`]="ContentBasedDeduplication",Y[`Attribute.${Z}.Value`]="true",Z++}if($.deadLetterTargetArn&&$.maxReceiveCount)Y[`Attribute.${Z}.Name`]="RedrivePolicy",Y[`Attribute.${Z}.Value`]=JSON.stringify({deadLetterTargetArn:$.deadLetterTargetArn,maxReceiveCount:$.maxReceiveCount}),Z++;if($.tags&&Object.keys($.tags).length>0){let G=1;for(let[W,z]of Object.entries($.tags))Y[`Tag.${G}.Key`]=W,Y[`Tag.${G}.Value`]=z,G++}let Q=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()});return{QueueUrl:Q.QueueUrl||Q.CreateQueueResult?.QueueUrl}}async listQueues($){let J={Action:"ListQueues",Version:"2012-11-05"};if($)J.QueueNamePrefix=$;let Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()}),Z=[];if(Y.QueueUrl)Z.push(Y.QueueUrl);else if(Y.ListQueuesResult?.QueueUrl)if(Array.isArray(Y.ListQueuesResult.QueueUrl))Z.push(...Y.ListQueuesResult.QueueUrl);else Z.push(Y.ListQueuesResult.QueueUrl);return{QueueUrls:Z}}async getQueueAttributes($){let J={Action:"GetQueueAttributes",QueueUrl:$,Version:"2012-11-05","AttributeName.1":"All"},Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{Attributes:Y.Attributes||Y.GetQueueAttributesResult?.Attributes||{}}}async getQueueUrl($){let J={Action:"GetQueueUrl",QueueName:$,Version:"2012-11-05"},Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{QueueUrl:Y.QueueUrl||Y.GetQueueUrlResult?.QueueUrl}}async deleteQueue($){let J={Action:"DeleteQueue",QueueUrl:$,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()})}async purgeQueue($){let J={Action:"PurgeQueue",QueueUrl:$,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()})}async sendMessage($){let J={Action:"SendMessage",QueueUrl:$.queueUrl,MessageBody:$.messageBody,Version:"2012-11-05"};if($.delaySeconds!==void 0)J.DelaySeconds=$.delaySeconds;if($.messageGroupId)J.MessageGroupId=$.messageGroupId;if($.messageDeduplicationId)J.MessageDeduplicationId=$.messageDeduplicationId;let Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{MessageId:Y.MessageId||Y.SendMessageResult?.MessageId}}async receiveMessages($){let J={Action:"ReceiveMessage",QueueUrl:$.queueUrl,Version:"2012-11-05"};if($.maxMessages!==void 0)J.MaxNumberOfMessages=$.maxMessages;if($.visibilityTimeout!==void 0)J.VisibilityTimeout=$.visibilityTimeout;if($.waitTimeSeconds!==void 0)J.WaitTimeSeconds=$.waitTimeSeconds;let Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()}),Z=[],Q=Y.Message||Y.ReceiveMessageResult?.Message;if(Q)if(Array.isArray(Q))Z.push(...Q.map((G)=>({MessageId:G.MessageId,ReceiptHandle:G.ReceiptHandle,Body:G.Body})));else Z.push({MessageId:Q.MessageId,ReceiptHandle:Q.ReceiptHandle,Body:Q.Body});return{Messages:Z}}async deleteMessage($,J){let Y={Action:"DeleteMessage",QueueUrl:$,ReceiptHandle:J,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}}var w9=o(()=>{Y0()});class iQ{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async call($,J){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${$}`},body:JSON.stringify(J)})}async listWebACLs($="REGIONAL"){return(await this.call("ListWebACLs",{Scope:$,Limit:100}))?.WebACLs??[]}async getWebACLRules($,J,Y="REGIONAL"){return((await this.call("GetWebACL",{Name:$,Id:J,Scope:Y}))?.WebACL?.Rules??[]).map((G)=>({Name:G.Name,Priority:G.Priority,Action:G.Action?Object.keys(G.Action)[0]:G.OverrideAction?Object.keys(G.OverrideAction)[0]:"count"}))}}var wF=o(()=>{Y0()});var RF={};h0(RF,{resolveDashboardData:()=>i7});function DF($){return String($).padStart(2,"0")}function Y8($){return`${$.getUTCFullYear()}-${DF($.getUTCMonth()+1)}-${DF($.getUTCDate())}`}function yT($){let J=Math.max(0,Math.round((Date.now()-$)/1000));if(J<60)return`${J}s ago`;let Y=Math.round(J/60);if(Y<60)return`${Y}m ago`;let Z=Math.round(Y/60);if(Z<48)return`${Z}h ago`;return`${Math.round(Z/24)}d ago`}async function D9($,J,Y,Z,Q,G){let W=await $.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:Y,Dimensions:[{Name:"FunctionName",Value:J}],StartTime:Q,EndTime:G,Period:86400,Statistics:[Z]}).catch(()=>[]);if(!W.length)return 0;if(Z==="Sum")return W.reduce((z,U)=>z+(U.Sum??0),0);if(Z==="Maximum")return Math.max(...W.map((z)=>z.Maximum??0));return W.reduce((z,U)=>z+(U.Average??0),0)/W.length}async function R9($,J,Y,Z,Q,G,W){let z=await $.getMetricStatistics({Namespace:J,MetricName:Y,Dimensions:Z,StartTime:G,EndTime:W,Period:86400,Statistics:[Q]}).catch(()=>[]);if(!z.length)return 0;if(Q==="Sum")return z.reduce((U,H)=>U+(H.Sum??0),0);if(Q==="Maximum")return Math.max(...z.map((U)=>U.Maximum??0));return z.reduce((U,H)=>U+(H.Average??0),0)/z.length}async function aQ($,J,Y,Z,Q){let G=await $.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:J}],StartTime:Z,EndTime:Q,Period:86400,ExtendedStatistics:[Y]}).catch(()=>[]);return Math.round(G.reduce((W,z)=>W+(z.Percentiles?.[Y]??0),0))}async function i7($,J){let Y=await yZ($,J),Z=Y.region,Q=new X$(Z),G=new l0(Z),W=new p2(Z),z=new Date,U=new Date(z.getTime()-86400000),H=$.environments?.[J]?.app,F={};F.app={name:Y.slug,env:J,region:Z,runtime:H?.kind==="php"?`php-${H?.phpVersion??"8.3"} (fpm)`:H?.kind??"node",url:Y.endpoint??"",build:Y.lastRelease?.sha?.slice(0,7)??"—",deployedAt:Y.lastRelease?.timestamp??"—"},F.maintenance={enabled:!1},F.scheduler={enabled:Y.scheduler!=="off",expression:Y.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let B=0,K=0,O=0,A=[],V=[],_=[];for(let j of Y.functions){let[q,T,D,S,P,C,I,b,y]=await Promise.all([D9(Q,j.name,"Invocations","Sum",U,z),D9(Q,j.name,"Errors","Sum",U,z),D9(Q,j.name,"Throttles","Sum",U,z),D9(Q,j.name,"Duration","Average",U,z),G.getFunction(j.name).catch(()=>null),aQ(Q,j.name,"p50",U,z),aQ(Q,j.name,"p95",U,z),aQ(Q,j.name,"p99",U,z),Q.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:j.name}],StartTime:new Date(z.getTime()-43200000),EndTime:z,Period:3600,Stat:"Sum"}).catch(()=>[])]);B+=q,K+=T,O=Math.max(O,S);let c=P?.Configuration?.MemorySize??0,r=Object.keys(P?.Configuration?.Environment?.Variables??{}),d=[],g=0;try{let{events:J0=[]}=await W.filterLogEvents({logGroupName:`/aws/lambda/${j.name}`,startTime:U.getTime(),limit:120});for(let t of J0){let a=(t.message??"").trim(),e=/Max Memory Used:\s*(\d+)\s*MB/.exec(a);if(e)g=Math.max(g,Number(e[1]));if(a&&!/^(?:START|END|REPORT|INIT_START)/.test(a))_.push({source:j.mode||j.name,timestamp:new Date(t.timestamp??0).toISOString(),when:yT(t.timestamp??0),message:a.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(a)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(a)?"warn":"info"})}d=J0.filter((t)=>!/^(?:START|END|REPORT|INIT_START)/.test((t.message??"").trim())).slice(-6).map((t)=>({ts:new Date(t.timestamp??0).toISOString().slice(11,19),msg:(t.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(t.message??"")}))}catch{}let s=Math.max(1,...y);A.push({key:j.mode,name:j.name,version:j.version,memory:c,timeout:P?.Configuration?.Timeout??0,runtime:P?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(q),errors:Math.round(T),p95:I||Math.round(S),status:"active",provisioned:j.provisioned?`${j.provisioned.allocated}/${j.provisioned.requested}`:void 0}),V.push({key:j.mode,name:j.name,runtime:P?.Configuration?.Runtime??"provided.al2023",arch:P?.Configuration?.Architectures?.[0]??"x86_64",memory:c,timeout:P?.Configuration?.Timeout??0,ephemeral:P?.Configuration?.EphemeralStorage?.Size??512,version:j.version,concurrency:H?.concurrency??"—",invocations:Math.round(q),errors:Math.round(T),throttles:Math.round(D),p50:C||Math.round(S),p95:I||Math.round(S),p99:b||Math.round(S),maxMem:g,spark:y.length?y.map((J0)=>Math.round(J0/s*100)):[0],env:r.length?r:["(none)"],recent:d.length?d:[{ts:"—",msg:"no recent events",err:!1}]})}F.functions=A,F.functionsDetail=V,F.serverlessLogs=_.sort((j,q)=>String(q.timestamp).localeCompare(String(j.timestamp))).slice(0,600),F.serverlessLogsEmptyReason=_.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let E=B?Number((K/B*100).toFixed(2)):0,M=Math.round(await D9(Q,Y.functions[0]?.name??"","ConcurrentExecutions","Maximum",U,z));F.metrics={invocations:Math.round(B),errorRatePct:E,p95Ms:Math.round(O),coldStartPct:0,concurrency:M,estCostUsd:0};try{let j=new C1(Z),q=[],T=[],D=0;try{let{QueueUrl:P}=await j.getQueueUrl(`${Y.slug}-${J}-dlq`),{Attributes:C}=await j.getQueueAttributes(P);D=Number(C.ApproximateNumberOfMessages??0)}catch{}let S=H?m8(H,Y.slug,J):[];for(let P of S){let C=P.name.replace(`${Y.slug}-${J}-`,""),I=0,b=0;try{let{QueueUrl:c}=await j.getQueueUrl(P.name),{Attributes:r}=await j.getQueueAttributes(c);I=Number(r.ApproximateNumberOfMessages??0),b=Number(r.ApproximateNumberOfMessagesNotVisible??0)}catch{}let y=Math.round(await R9(Q,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:P.name}],"Sum",U,z));q.push({name:C,visible:I,inFlight:b,processed:y,dlq:D}),T.push({name:P.name,short:C,visible:I,inFlight:b,delayed:0,processed:y,oldestSec:0,concurrency:P.concurrency??H?.queueConcurrency??"—",tries:H?.queueTries??3,visTimeout:(H?.queueTimeout??120)*6,dlq:D})}if(q.length)F.queues=q;if(T.length)F.queuesDetail=T;F.dlqItems=[]}catch{}try{let j=new O0(Z),{Stacks:q}=await j.describeStacks({stackName:U$($,J)}),T={};for(let D of q?.[0]?.Outputs??[])if(D.OutputKey)T[D.OutputKey]=D.OutputValue??"";if(H?.database?.connection==="aurora-serverless"){let D=`${Y.slug}-${J}-db`,S=[{Name:"DBClusterIdentifier",Value:D}],[P,C]=await Promise.all([R9(Q,"AWS/RDS","ServerlessDatabaseCapacity",S,"Average",U,z),R9(Q,"AWS/RDS","DatabaseConnections",S,"Maximum",U,z)]);if(F.aurora={id:D,engine:"aurora-mysql",minAcu:H?.database?.minCapacity??0.5,maxAcu:H?.database?.maxCapacity??4,currentAcu:P?Number(P.toFixed(1)):H?.database?.minCapacity??0.5,database:"app",connections:Math.round(C),status:T.DbEndpoint?"available":"creating"},H?.rdsProxy)F.proxy={name:`${Y.slug}-${J}-proxy`,endpoint:T.DbProxyEndpoint??"—",pooledConns:Math.round(C),status:"available"}}if(H?.cache?.driver==="elasticache"){let D=`${Y.slug}-${J}-cache`,S=[{Name:"CacheClusterId",Value:`${D}-001`}],[P,C]=await Promise.all([R9(Q,"AWS/ElastiCache","CacheHits",S,"Sum",U,z),R9(Q,"AWS/ElastiCache","CacheMisses",S,"Sum",U,z)]),I=P+C>0?Number((P/(P+C)*100).toFixed(1)):0;F.redis={id:D,node:"cache.t4g.micro",engine:"redis",hitRate:I,status:T.CacheEndpoint?"available":"creating"}}if(H?.efs){let D=0;try{if(T.EfsFileSystemId){let S=new n7(Z),{FileSystems:P}=await S.describeFileSystems({FileSystemId:T.EfsFileSystemId});D=Number(((P?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}F.efs={id:T.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:D,status:"available"}}F.assetsInfo=T.AssetsCdnDomain?{bucket:T.AssetsBucketName??`${Y.slug}-${J}-assets`,cdn:T.AssetsCdnDomain,customDomain:H?.assetDomain??"—",assetUrl:Y.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:F.app.build}:void 0}catch{}if(F.assetsInfo)try{let q=await new W0(Z).list({bucket:F.assetsInfo.bucket,maxKeys:1000});F.assetsInfo.files=q.length,F.assetsInfo.sizeMb=Number((q.reduce((T,D)=>T+(D.Size??0),0)/1048576).toFixed(1)),F.assetsRecent=q.slice(0,8).map((T)=>({path:`/${T.Key}`,size:`${Math.max(1,Math.round((T.Size??0)/1024))} KB`,type:T.Key.split(".").pop()??""}))}catch{}try{if(H?.secrets){let j=Array.isArray(H.secrets)?H.secrets.map((q)=>({key:q.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:q})):Object.entries(H.secrets).map(([q,T])=>({key:q,source:String(T)}));F.secretsList=j.map((q)=>({...q,updated:"—"}))}}catch{}try{let j=new W0(Z),q=`${Y.slug}-${J}-deployments`,T=await j.getObjectJson(q,`deployments/${Y.slug}/${J}/history.json`).catch(()=>null);if(T?.records?.length)F.deploymentsDetail=T.records.slice(-12).reverse().map((D)=>({sha:(D.sha??"").slice(0,7),status:D.status??"success",when:D.timestamp??"—",took:D.took??"—",by:D.by??"—",version:D.version??"—",hooks:D.hooks??[]}))}catch{}F.metricsTotals={invocations:F.metrics.invocations,errors:Math.round(K),errorRatePct:E,p95Ms:F.metrics.p95Ms,throttles:V.reduce((j,q)=>j+q.throttles,0),coldStartPct:0,estCostUsd:0,concurrency:M},F.metricsPerFn=V.map((j)=>({key:j.key,invocations:j.invocations,errors:j.errors,throttles:j.throttles,avgMs:j.p50,maxMs:j.p99,costUsd:0}));try{F.invSpark=await Q.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:Y.functions.find((j)=>j.mode==="http")?.name??""}],StartTime:new Date(z.getTime()-86400000),EndTime:z,Period:3600,Stat:"Sum"})}catch{}try{let j=new s8,q=z,T=new Date(Date.UTC(q.getUTCFullYear(),q.getUTCMonth(),1)),D=new Date(Date.UTC(q.getUTCFullYear(),q.getUTCMonth()-1,1)),[S,P]=await Promise.all([j.getCostByService({start:Y8(T),end:Y8(q),granularity:"MONTHLY"}).catch(()=>[]),j.getCostByService({start:Y8(D),end:Y8(T),granularity:"MONTHLY"}).catch(()=>[])]);if(S.length){let C=S.reduce((g,s)=>g+s.amount,0),I=P.reduce((g,s)=>g+s.amount,0),b=q.getUTCDate(),y=new Date(Date.UTC(q.getUTCFullYear(),q.getUTCMonth()+1,0)).getUTCDate();F.costSummary={monthToDateUsd:Number(C.toFixed(2)),projectedUsd:Number((C/b*y).toFixed(2)),lastMonthUsd:Number(I.toFixed(2)),dailyAvgUsd:Number((C/b).toFixed(2))},F.costServices=S.filter((g)=>g.amount>0).sort((g,s)=>s.amount-g.amount).slice(0,12).map((g)=>({name:g.service,usd:Number(g.amount.toFixed(2)),note:""})),F.metrics.estCostUsd=Number((C/b).toFixed(2)),F.metricsTotals.estCostUsd=F.metrics.estCostUsd,F.costTrend=await j.getDailyTotals({start:Y8(T),end:Y8(q)}).catch(()=>[]);let c=S.find((g)=>/lambda/i.test(g.service))?.amount??0,r=(g)=>g.invocations*(g.p50/1000)*(g.memory/1024),d=V.reduce((g,s)=>g+r(s),0)||1;F.costPerFn=V.map((g)=>({key:g.key,requests:g.invocations,gbSec:Math.round(r(g)),usd:Number((c*(r(g)/d)).toFixed(2))}))}}catch{}if(H?.firewall)try{let j=await Q.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:U,EndTime:z,Period:86400,Statistics:["Sum"]}).catch(()=>[]),q=await Q.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:U,EndTime:z,Period:86400,Statistics:["Sum"]}).catch(()=>[]);F.waf={enabled:!0,scope:"REGIONAL",acl:`${Y.slug}-${J}-waf`,allowed24h:Math.round(q.reduce((T,D)=>T+(D.Sum??0),0)),blocked24h:Math.round(j.reduce((T,D)=>T+(D.Sum??0),0))};try{let T=new iQ(Z),D=await T.listWebACLs("REGIONAL"),S=D.find((P)=>P.Name?.includes(`${Y.slug}-${J}`))??D[0];if(S?.Name&&S.Id){F.waf.acl=S.Name;let P=await T.getWebACLRules(S.Name,S.Id,"REGIONAL");if(P.length)F.wafRules=P.map((C)=>({name:C.Name??"—",detail:`priority ${C.Priority??0}`,action:C.Action??"count",blocked24h:0}))}}catch{}}catch{}if(Y.scheduler!=="off"&&H?.kind==="php")try{let j=await n$($,J,"schedule:list"),q=[];for(let T of(j||"").split(`
7513
+ `)){let D=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(T);if(D&&/[*\d]/.test(D[1])&&D[1].trim().split(/\s+/).length===5)q.push({command:D[2].trim().replace(/^php artisan /,""),cron:D[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(q.length)F.schedulerTasks=q}catch{}return F}var a7=o(async()=>{M1();NZ();i8();U7();nQ();a1();I0();w9();wF();await z8([n0(),Q1()])});import{createHash as vT}from"node:crypto";function SF($){let J=tQ($.name),Y=sQ($.publicKey),Z=gT([...$.existingKeys??[],{name:J,publicKey:Y}]);return CF($.configText,Z)}function PF($){let J=tQ($.name),Y=($.existingKeys??[]).filter((Z)=>Z.name!==J);if(($.existingKeys??[]).length===Y.length)throw Error(`SSH key '${J}' does not exist in compute.sshKeys`);return CF($.configText,Y)}function n2($=[]){return $.map((J)=>({name:J.name,publicKey:J.publicKey,type:uT(J.publicKey),fingerprint:dT(J.publicKey),added:"configured"}))}function CF($,J){let Y=cT($,"compute"),Z=fT(J),Q=mT($,Y.start,Y.end,"sshKeys");if(Q){let U=Q.propertyStart;while(U>0&&$[U-1]!==`
7509
7514
  `&&/\s/.test($[U-1]))U--;return`${$.slice(0,U)}${Z}${$.slice(Q.end+1)}`}let G=$.slice(0,Y.end).trimEnd(),W=$.slice(Y.end),z=G.endsWith(",")||G.endsWith("{")?"":",";return`${G}${z}
7510
7515
  ${Z},
7511
- ${W}`}function gT($){if($.length===0)return" sshKeys: []";return` sshKeys: [
7516
+ ${W}`}function fT($){if($.length===0)return" sshKeys: []";return` sshKeys: [
7512
7517
  ${$.map((Y)=>[" {",` name: '${NF(Y.name)}',`,` publicKey: '${NF(sQ(Y.publicKey))}',`," },"].join(`
7513
7518
  `)).join(`
7514
7519
  `)}
7515
- ]`}function uT($){let J=new Map;for(let Y of $){let Z=tQ(Y.name);if(J.has(Z))throw Error(`SSH key '${Z}' already exists in compute.sshKeys`);J.set(Z,{name:Z,publicKey:sQ(Y.publicKey)})}return[...J.values()]}function tQ($){let J=$.trim();if(!/^[\w@.+-]{2,80}$/.test(J))throw Error("SSH key name must be 2-80 characters and use letters, numbers, @, ., +, _, or -.");return J}function sQ($){let J=$.trim().replace(/\s+/g," "),[Y,Z]=J.split(" ");if(!/^(?:ssh-(?:ed25519|rsa)|ecdsa-sha2-nistp(?:256|384|521))$/.test(Y??"")||!Z)throw Error("Public key must be an OpenSSH public key, e.g. ssh-ed25519 AAAA... name@host.");return J}function dT($){return $.trim().split(/\s+/)[0]||"ssh"}function cT($){let J=$.trim().split(/\s+/)[1];if(!J)return"-";try{return`SHA256:${fT("sha256").update(Buffer.from(J,"base64")).digest("base64").replace(/=+$/,"")}`}catch{return"-"}}function NF($){return $.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'")}function mT($,J){let Y=new RegExp(`\\b${J}\\s*:\\s*{`,"g").exec($);if(!Y)throw Error(`Could not find ${J}: { ... } in cloud config.`);let Z=$.indexOf("{",Y.index);return{propertyStart:Y.index,start:Z,end:xF($,Z,"{","}")}}function lT($,J,Y,Z){let Q=$.slice(J+1,Y),G=new RegExp(`\\b${Z}\\s*:\\s*\\[`,"g").exec(Q);if(!G)return null;let W=J+1+G.index,z=$.indexOf("[",W);return{propertyStart:W,start:z,end:xF($,z,"[","]")}}function xF($,J,Y,Z){let Q=0,G,W=!1,z=!1,U=!1;for(let H=J;H<$.length;H++){let F=$[H],B=$[H+1];if(z){if(F===`
7516
- `)z=!1;continue}if(U){if(F==="*"&&B==="/")U=!1,H++;continue}if(G){if(W){W=!1;continue}if(F==="\\"){W=!0;continue}if(F===G)G=void 0;continue}if(F==="/"&&B==="/"){z=!0,H++;continue}if(F==="/"&&B==="*"){U=!0,H++;continue}if(F==='"'||F==="'"||F==="`"){G=F;continue}if(F===Y)Q++;if(F===Z){if(Q--,Q===0)return H}}throw Error(`Could not find matching ${Z} in cloud config.`)}var oQ=()=>{};var iF={};h0(iF,{serverLogSources:()=>gF,resolveServerDashboardData:()=>YG,resolveConfigOnlyServerDashboardData:()=>nF,parseServerSecurity:()=>mF,parseServerLogs:()=>dF,parseDeployHistory:()=>rF,parseBlock:()=>kF});import{existsSync as pT,readFileSync as rT}from"node:fs";import{join as nT}from"node:path";function aT(){return["set +e",'echo "CPUS=$(nproc 2>/dev/null || echo 1)"',`echo "LOAD=$(cut -d' ' -f1 /proc/loadavg 2>/dev/null || echo 0)"`,`echo "MEMTOTAL=$(free -m 2>/dev/null | awk '/^Mem:/{print $2}')"`,`echo "MEMUSED=$(free -m 2>/dev/null | awk '/^Mem:/{print $3}')"`,`echo "DISKPCT=$(df -P / 2>/dev/null | awk 'NR==2{gsub("%","",$5);print $5}')"`,`echo "DISKUSEDG=$(df -BG / 2>/dev/null | awk 'NR==2{gsub("G","",$3);print $3}')"`,`echo "DISKTOTG=$(df -BG / 2>/dev/null | awk 'NR==2{gsub("G","",$2);print $2}')"`,`echo "UPTIME=$(uptime -p 2>/dev/null | sed 's/^up //' || echo unknown)"`,'echo "OS=$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"',`for s in ${iT.join(" ")}; do st=$(systemctl is-active "$s" 2>/dev/null); if [ -n "$st" ] && [ "$st" != "inactive" ] && [ "$st" != "unknown" ]; then mem=$(systemctl show "$s" -p MemoryCurrent --value 2>/dev/null); en=$(systemctl is-enabled "$s" 2>/dev/null); since=$(systemctl show "$s" -p ActiveEnterTimestamp --value 2>/dev/null); echo "SVC=$s=$st=$mem=$en=$since"; fi; done`,"true"]}function kF($){let J={services:[]};for(let Y of $.split(`
7517
- `)){let Z=Y.trim();if(Z.startsWith("SVC=")){let[,Q,G,W,z,U]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(Z)??[];if(Q)J.services.push({name:Q,status:G,memBytes:Number(W||0),enabled:z||F1,since:U||F1})}else{let Q=Z.indexOf("=");if(Q>0)J[Z.slice(0,Q)]=Z.slice(Q+1)}}return J}function hF($){let J=$.infrastructure?.compute,Y=[];if(J?.webServer==="rpx"||J?.proxy?.engine==="rpx")Y.push({name:"rpx-gateway",status:"configured"});else if(J?.webServer==="nginx"||J?.webServer==null)Y.push({name:"ts-cloud-nginx",status:"configured"});let Z=J?.php?.versions??(J?.runtime==="php"?["8.3"]:[]);for(let W of Z)Y.push({name:`php${W}-fpm`,status:"configured"});let Q=J?.managedServices??{},G=[["mysql","mysql"],["mariadb","mariadb"],["postgres","postgresql"],["redis","redis"],["memcached","memcached"],["meilisearch","meilisearch"]];for(let[W,z]of G)if(Q[W])Y.push({name:z,status:"configured"});return Y}function tT($){let J=$.infrastructure?.compute?.backups,Y=!!J?.enabled,Z=J?.schedule??"0 2 * * *";return{enabled:Y,schedule:Z,destination:Y?J?.bucket??"local":"off",retention:Y?J?.retentionCount??5:0,last:Y?"pending first run":"not configured",size:Y?F1:"0 MB"}}function bF($){return $.infrastructure?.compute?.provider??$.cloud?.provider??$.provider??"aws"}function sT($){if(bF($)==="hetzner")return $.hetzner?.location??process.env.HCLOUD_LOCATION??process.env.HETZNER_LOCATION??"fsn1";return $.project.region??"us-east-1"}function oT($,J){let Y=nT(process.cwd(),".ts-cloud","state",`${$.project.slug}-${J}.json`);if(!pT(Y))return null;try{return JSON.parse(rT(Y,"utf8"))}catch{return null}}function eT($){let J=$.sites??{},Y=[];for(let[Z,Q]of Object.entries(J)){let G=Q.queues??Q.workers;if(Array.isArray(G)){for(let W of G)if(typeof W==="string")Y.push({name:`${Z}:${W}`,site:Z,processes:1,status:"configured"});else if(W?.name)Y.push({name:`${Z}:${W.name}`,site:Z,processes:W.processes??1,status:"configured"})}}return Y}function yF($){if(!$||$==="")return"/";return $.startsWith("/")?$:`/${$}`}function $3($){let J=yF($.path);if(!$.domain)return{route:"internal"};return{route:J==="/"?$.domain:`${$.domain}${J}`,href:`https://${$.domain}${J==="/"?"":J}`}}function IF($,J){let Y=p0(J);if(Y==="redirect")return"redirect";let Z=String(J.build??"").toLowerCase(),Q=String(J.start??"").toLowerCase();if($==="main"||Q.includes("buddy/src/cli.ts serve"))return"stacks";if($==="api"||Q.includes("/serve/api"))return"api";if(Z.includes("buildblog"))return"bunpress blog";if(Z.includes("bunpress"))return"bunpress";if(Z.includes("site:build")||Z.includes("stx"))return"stx static";if(Y==="server-static")return J.spa?"spa":"static";if(Y==="server-app")return"app";if(Y==="server-php")return J.type??"php";return"bucket"}function J3($){let J=p0($);if(J==="redirect")return"—";let Y=`${$.start??""} ${$.build??""}`.toLowerCase();if(J==="server-static")return Y.includes("bunpress")||Y.includes("bun ")||Y.includes("bunx ")?"static/bun":"static";if(J==="server-app")return Y.includes("bun")?"bun":"node";if(J==="server-php")return`php ${$.php??$.phpVersion??"8.3"}`;return"static"}function Y3($){let J=p0($);if(J==="redirect")return"redirect";if(J==="server-app")return"service";if(J==="server-static")return"server static";if(J==="server-php")return"php release";return"bucket"}function Z3($){let J=new Map;return Object.entries($.sites??{}).map(([Y,Z])=>{let Q=yF(Z.path),{route:G,href:W}=$3(Z),z=Z.domain?`${Z.domain}${Q}`:"",U=z?J.get(z):void 0;if(z&&!U)J.set(z,Y);return{name:Y,route:G,href:W,domain:Z.domain??"internal",path:Q,kind:IF(Y,Z),type:IF(Y,Z),runtime:J3(Z),deploy:Y3(Z),tls:Z.domain?Z.ssl===!1?"http":"https":"loopback",ssl:Z.domain?Z.ssl!==!1:!1,status:U?"shadowed":"live",shadowedBy:U,lastDeploy:F1}})}function eQ($){return`'${$.replaceAll("'","'\\''")}'`}function vF($){return $.replace(/[\\&/]/g,"\\$&")}function Q3($){if($.length===0)return["true"];return["set +e",...$.map((J)=>{let Y=eQ(`/var/www/${J}/.ts-cloud/deploy-history.log`),Z=vF(J);return`TS_CLOUD_HISTORY=${Y}; { [ -f "$TS_CLOUD_HISTORY" ] && tail -n 24 "$TS_CLOUD_HISTORY" | sed "s/^/DEPLOY=${Z}\\t/"; } || true`}),"true"]}function fF($){return[...new Set(Object.values($.sites??{}).map((J)=>J.domain).filter((J)=>typeof J==="string"&&J.length>0))]}function G3($){return["set +e",'if command -v ss >/dev/null 2>&1; then ss -H -lntup 2>/dev/null | while read -r proto _state _recv _send local _peer rest; do [ -n "$proto" ] && [ -n "$local" ] && printf "PORT=%s\\t%s\\t%s\\n" "$proto" "$local" "$rest"; done; fi','if command -v ufw >/dev/null 2>&1; then ufw status numbered 2>/dev/null | sed "s/^/FIREWALL=/"; else echo "FIREWALL=ufw unavailable"; fi','journalctl _COMM=sshd --no-pager -n 30 -o short-iso 2>/dev/null | sed "s/^/AUTH=/" || true',...fF($).map((Y)=>{return`TS_CLOUD_DOMAIN=${eQ(Y)}; TS_CLOUD_EXPIRY=$(echo | timeout 8 openssl s_client -servername "$TS_CLOUD_DOMAIN" -connect "$TS_CLOUD_DOMAIN:443" 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2-); [ -n "$TS_CLOUD_EXPIRY" ] && printf "CERT=%s\\t%s\\n" "$TS_CLOUD_DOMAIN" "$TS_CLOUD_EXPIRY" || printf "CERT=%s\\tunavailable\\n" "$TS_CLOUD_DOMAIN"`}),"true"]}function gF($){let J=new Map,Y=(G,W)=>{if(G&&W&&!J.has(W))J.set(W,{pattern:G,label:W})},Z=$.infrastructure?.compute,Q=$.project.slug;if(Z?.webServer==="rpx"||Z?.proxy?.engine==="rpx")Y("rpx-gateway","rpx-gateway");else Y("nginx","nginx");for(let G of hF($))Y(G.name,G.name);for(let[G,W]of Object.entries($.sites??{})){if(p0(W)!=="server-app")continue;if(Y(`${Q}-${G}`,`${Q}-${G}`),Array.isArray(W.queues??W.workers)&&(W.queues??W.workers).length)Y(`${Q}-${G}-queue-*`,`${Q}-${G}-queues`);if(Array.isArray(W.daemons)&&W.daemons.length)Y(`${Q}-${G}-daemon-*`,`${Q}-${G}-daemons`)}return[...J.values()]}function W3($){let J=gF($);if(J.length===0)return["true"];return["set +e",...J.map((Y)=>{let Z=eQ(Y.pattern),Q=vF(Y.label);return`journalctl -u ${Z} --no-pager -n 150 -o short-iso 2>/dev/null | sed "s/^/LOG=${Q}\\t/" || true`}),'[ -f /var/log/ts-cloud-backup.log ] && tail -n 60 /var/log/ts-cloud-backup.log 2>/dev/null | sed "s/^/LOG=backups\\t/" || true',"true"]}function $G($){let J=new Date($);if(Number.isNaN(J.getTime()))return $||F1;let Y=Math.max(0,Math.round((Date.now()-J.getTime())/1000));if(Y<60)return`${Y}s ago`;let Z=Math.round(Y/60);if(Z<60)return`${Z}m ago`;let Q=Math.round(Z/60);if(Q<48)return`${Q}h ago`;return`${Math.round(Q/24)}d ago`}function uF($){if(/(?:error|failed|panic|fatal|exception|denied|unhealthy)/i.test($))return"error";if(/(?:warn|warning|retry|restart|deprecated|timeout)/i.test($))return"warn";return"info"}function dF($){let J=[];for(let Y of $.split(`
7518
- `)){let Z=Y.trim();if(!Z.startsWith("LOG="))continue;let Q=Z.indexOf("\t");if(Q<0)continue;let G=Z.slice(4,Q),W=Z.slice(Q+1),z=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(W),U=z?.[1]??"",H=z?.[2]??"",F=(z?.[3]??W).trim();if(!F)continue;J.push({source:G,timestamp:U,when:U?$G(U):F1,host:H,message:F,level:uF(F)})}return J.sort((Y,Z)=>String(Z.timestamp).localeCompare(String(Y.timestamp))).slice(0,600)}function cF($){if(/^(?:127\.|localhost:|\[?::1\]?)/.test($))return"loopback";if(/^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|\[?f[cd][0-9a-f:])/i.test($))return"private";return"public"}function z3($){if(cF($)!=="public")return"ok";if(/:(?:22|80|443)$/.test($)||/^\*:(?:22|80|443)$/.test($))return"ok";return"warn"}function U3($){if($==null)return"warn";if($<8)return"bad";if($<30)return"warn";return"ok"}function mF($){let J=[],Y=[],Z=[],Q=[];for(let z of $.split(`
7519
- `)){let U=z.trim();if(U.startsWith("PORT=")){let[H="",F="",B=""]=U.slice(5).split("\t");if(H&&F)J.push({proto:H,listen:F,processName:B||F1,exposure:cF(F),tone:z3(F)})}else if(U.startsWith("FIREWALL=")){let H=U.slice(9).trim();if(H)Y.push(H)}else if(U.startsWith("AUTH=")){let H=U.slice(5),F=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(H),B=(F?.[3]??H).trim();if(B)Z.push({timestamp:F?.[1]??"",when:F?.[1]?$G(F[1]):F1,host:F?.[2]??"",message:B,level:uF(B)})}else if(U.startsWith("CERT=")){let[H="",F=""]=U.slice(5).split("\t");if(!H)continue;let B=new Date(F),K=Number.isNaN(B.getTime())?null:Math.ceil((B.getTime()-Date.now())/86400000);Q.push({domain:H,expires:Number.isNaN(B.getTime())?F||F1:B.toISOString().slice(0,10),daysRemaining:K,status:U3(K)})}}let G=Y.some((z)=>/Status:\s*active/i.test(z)),W=Y.some((z)=>/unavailable/i.test(z));return{ports:J.slice(0,80),firewall:{status:G?"active":W?"unavailable":"inactive",summary:G?"ufw active":W?"ufw unavailable":"ufw inactive or not configured",rules:Y.filter((z)=>z&&!/^Status:/i.test(z)).slice(0,60)},tlsCertificates:Q,authEvents:Z.sort((z,U)=>String(U.timestamp).localeCompare(String(z.timestamp))).slice(0,30)}}function JG($){let Y=$.infrastructure?.compute?.firewall??{},Z=[...new Set([22,80,443,...Y.allowedPorts??[]])],Q=fF($);return{ports:Z.map((G)=>({proto:"tcp",listen:`0.0.0.0:${G}`,processName:"configured firewall",exposure:"public",tone:[22,80,443].includes(Number(G))?"ok":"warn"})),firewall:{status:Y.enabled===!1?"disabled":"configured",summary:Y.enabled===!1?"host firewall disabled in config":"host firewall configured declaratively",rules:Z.map((G)=>`ALLOW ${G}/tcp`)},tlsCertificates:Q.map((G)=>({domain:G,expires:F1,daysRemaining:null,status:"warn"})),authEvents:[]}}function lF($,J){let Y=J.security??JG($),Z=!!J._serverReachable&&!J.metricsUnavailable,Q=J.sites??[],G=Q.filter((H)=>H.status==="shadowed"),W=(J.services??[]).filter((H)=>["failed","stopped"].includes(H.status)),z=(Y.tlsCertificates??[]).filter((H)=>H.status!=="ok"),U=J.sshKeys??[];return[{name:"Live server probe",status:Z?"pass":"warn",detail:Z?"Metrics and remote checks are coming from the compute box.":"The dashboard is rendering config/state data until the box probe succeeds."},{name:"Managed services",status:W.length?"fail":"pass",detail:W.length?`${W.length} service(s) need attention.`:`${(J.services??[]).length} service(s) reported healthy or configured.`},{name:"Route conflicts",status:G.length?"warn":"pass",detail:G.length?`${G.map((H)=>H.name).join(", ")} is shadowed by an earlier route.`:`${Q.length} site route(s) are unshadowed.`},{name:"SSH access",status:U.length?"pass":"warn",detail:U.length?`${U.length} declarative authorized key(s) configured.`:"No declarative SSH keys are configured."},{name:"Firewall",status:["active","configured"].includes(Y.firewall?.status)?"pass":"warn",detail:Y.firewall?.summary??"Firewall status unavailable."},{name:"TLS certificates",status:z.length?"warn":"pass",detail:z.length?`${z.length} certificate(s) need renewal visibility.`:`${(Y.tlsCertificates??[]).length} certificate(s) look healthy.`}]}function pF($){let J=[];for(let Y of $.serverDeploymentsDetail??$.serverDeployments??[])J.push({type:"deploy",tone:Y.status==="failed"?"bad":"ok",title:`${Y.site} deployed ${Y.sha}`,detail:`${Y.branch} · ${Y.status}`,when:Y.when,timestamp:Y.timestamp});for(let Y of $.serverLogs??[])if(Y.level==="error"||Y.level==="warn")J.push({type:"log",tone:Y.level==="error"?"bad":"warn",title:`${Y.source} ${Y.level}`,detail:Y.message,when:Y.when,timestamp:Y.timestamp});for(let Y of $.sshKeys??[])J.push({type:"ssh",tone:"ok",title:`${Y.name} authorized`,detail:Y.fingerprint,when:Y.added??F1,timestamp:""});return J.sort((Y,Z)=>String(Z.timestamp).localeCompare(String(Y.timestamp))).slice(0,80)}function rF($,J={}){let Y=[];for(let Z of $.split(`
7520
- `)){let Q=Z.trim();if(!Q.startsWith("DEPLOY="))continue;let G=Q.split("\t"),W=G[0]?.replace(/^DEPLOY=/,"")??"",[z,U,H,F,B]=G.slice(1);if(!W||!z||!U)continue;let K=J[W]??{},O=p0(K),A=(H||U).slice(0,7);Y.push({sha:A,release:U,commit:H||U,site:W,branch:K.branch??(O==="server-static"?"build artifact":"main"),status:F||"unknown",when:$G(z),timestamp:z,took:"-",by:"ts-cloud",rc:B?.replace(/^rc=/,"")??"",steps:O==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return Y.sort((Z,Q)=>String(Q.timestamp).localeCompare(String(Z.timestamp)))}function nF($,J){let Y=oT($,J),Z=hF($),Q=Z3($),G=Math.max(1,Number($.infrastructure?.compute?.disk?.size??1)),W={server:{name:Y?.serverName??`${$.project.slug}-${J}-app`,provider:Y?.provider??bF($),region:sT($),ip:Y?.publicIp??F1,os:"Linux",uptime:F1,probeStatus:"unavailable"},systemMetrics:{load:0,cpus:Math.max(1,Number($.infrastructure?.compute?.instances??1)),memUsedMb:0,memTotalMb:0,diskUsedPct:0,diskUsedGb:0,diskTotalGb:G},metricsUnavailable:!0,services:Z,servicesDetail:Z.map((z)=>({...z,since:F1,memMb:0,auto:!0})),backup:tT($),backupHistory:[],workers:eT($),serverScheduler:{enabled:!1,lastRun:"not configured"},serverDeployments:[],serverDeploymentsDetail:[],deploymentsEmptyReason:"No deployment history has been recorded yet. Future server deploys will write /var/www/<site>/.ts-cloud/deploy-history.log.",serverLogs:[],serverLogsEmptyReason:"Live server logs are unavailable until the dashboard can reach the compute box.",security:JG($),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:Q,sitesDetail:Q.map((z)=>{let U=$.sites?.[z.name]??{},H=p0(U);return{...z,root:H==="server-static"?`/var/www/${z.name}`:`/var/www/${z.name}/current`,branch:H==="server-static"?"build artifact":"main",build:U.build,envKeys:Object.keys(U.env??U.environment??{})}}),sshKeys:n2($.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return W.diagnostics=lF($,W),W.activity=pF(W),W}async function YG($,J){if(!$.infrastructure?.compute)return null;let Y=null;try{Y=Y1({config:$})}catch{Y=null}let Z=null,Q=0,G=[];if(Y)try{if(G=await Y.findComputeTargets({slug:$.project.slug,environment:J,role:"app"}),Q=G.length,G.length){let F=(await Y.runRemoteDeploy({targets:[G[0]],commands:aT(),comment:`ts-cloud dashboard:build ${$.project.slug}`,tags:{Project:$.project.slug,Environment:J,Role:"app"}})).perInstance?.[0]?.output;if(F)Z=kF(F)}}catch{}let W=nF($,J),z=(H,F=0)=>{let B=Number(H);return Number.isFinite(B)?B:F};if(W.server.os=Z?.OS||W.server.os,W.server.uptime=Z?.UPTIME||W.server.uptime,Z){if(W.server.probeStatus="live",W.metricsUnavailable=!1,W._metricsStatus="live",W.systemMetrics={load:z(Z.LOAD),cpus:z(Z.CPUS,1),memUsedMb:z(Z.MEMUSED),memTotalMb:z(Z.MEMTOTAL,1),diskUsedPct:z(Z.DISKPCT),diskUsedGb:z(Z.DISKUSEDG),diskTotalGb:z(Z.DISKTOTG,1)},Z.services.length)W.services=Z.services.map((H)=>({name:H.name,status:H.status==="active"?"running":H.status})),W.servicesDetail=Z.services.map((H)=>({name:H.name,status:H.status==="active"?"running":H.status,since:H.since&&H.since!==F1?H.since:W.server.uptime,memMb:Math.max(0,Math.round(Number(H.memBytes??0)/1024/1024)),auto:H.enabled?!["disabled","static","masked"].includes(H.enabled):!0}))}if(Y&&G.length)try{let H=Object.keys($.sites??{}),B=(await Y.runRemoteDeploy({targets:[G[0]],commands:Q3(H),comment:`ts-cloud dashboard:deploy-history ${$.project.slug}`,tags:{Project:$.project.slug,Environment:J,Role:"app"}})).perInstance?.[0]?.output??"",K=rF(B,$.sites);W.serverDeployments=K.slice(0,5),W.serverDeploymentsDetail=K.slice(0,50),W.deploymentsEmptyReason=K.length?void 0:"No deployment history was found on the server yet. Deploy again to populate this timeline."}catch{W.deploymentsEmptyReason="Deployment history could not be read from the server."}else if(Y&&Q===0)W.deploymentsEmptyReason="No app server target was found for this environment.";if(Y&&G.length)try{let F=(await Y.runRemoteDeploy({targets:[G[0]],commands:W3($),comment:`ts-cloud dashboard:server-logs ${$.project.slug}`,tags:{Project:$.project.slug,Environment:J,Role:"app"}})).perInstance?.[0]?.output??"",B=dF(F);W.serverLogs=B,W.serverLogsEmptyReason=B.length?void 0:"No recent journal entries were found for the managed server units."}catch{W.serverLogsEmptyReason="Server logs could not be read from the box."}if(Y&&G.length)try{let F=(await Y.runRemoteDeploy({targets:[G[0]],commands:G3($),comment:`ts-cloud dashboard:security ${$.project.slug}`,tags:{Project:$.project.slug,Environment:J,Role:"app"}})).perInstance?.[0]?.output??"",B=mF(F),K=JG($);if(!B.ports.length)B.ports=K.ports;if(!B.tlsCertificates.length)B.tlsCertificates=K.tlsCertificates;W.security=B,W.securityEmptyReason=void 0}catch{W.securityEmptyReason="Server security checks could not be read from the box."}let U=$.infrastructure?.compute?.sshKeys??$.infrastructure?.ssh?.keys??$.infrastructure?.sshKeys;if(Array.isArray(U)&&U.length)W.sshKeys=n2(U);return W._serverReachable=Q>0&&!!Z,W.diagnostics=lF($,W),W.activity=pF(W),W}var iT,F1="-";var ZG=o(async()=>{O$();oQ();await j$();iT=["rpx-gateway","nginx","php8.3-fpm","php8.2-fpm","mysql","mariadb","postgresql","redis","redis-server","meilisearch"]});import{existsSync as qX}from"node:fs";import Z5 from"node:fs/promises";import lG from"node:os";import Q5 from"node:path";import s2 from"node:process";import{EventEmitter as TX}from"node:events";import C2 from"node:process";import pG from"node:process";import U5 from"node:process";import I9 from"node:process";import F8 from"node:process";import iG from"node:tty";import FB,{stdin as Cw,stdout as xw}from"node:process";import tG,{stdin as KB,stdout as OB}from"node:process";import VB from"node:readline";class oG{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=lG.homedir(),J=Q5.join($,".config","clapp");this.configPath=Q5.join(J,"telemetry.json")}async isEnabled(){if(s2.env.DO_NOT_TRACK==="1"||s2.env.DO_NOT_TRACK==="true")return!1;if(s2.env.NO_TELEMETRY==="1"||s2.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let $=await this.loadConfig();if($.enabled=!0,!$.userId)$.userId=this.generateUserId();await this.saveConfig($)}async disable(){let $=await this.loadConfig();$.enabled=!1,await this.saveConfig($)}async track($,J){if(!await this.isEnabled())return;let Z={event:$,...J,timestamp:Date.now(),platform:lG.platform(),nodeVersion:s2.version};if(this.events.push(Z),this.events.length>=10)await this.send()}async trackCommand($,J){await this.track("command",{command:$,duration:J})}async trackError($,J){await this.track("error",{error:$,command:J})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let J=await this.loadConfig();return J.lastSent=Date.now(),await this.saveConfig(J),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let J=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(J),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep($){return new Promise((J)=>setTimeout(J,$))}async status(){let $=await this.loadConfig();return{enabled:$.enabled,doNotTrack:s2.env.DO_NOT_TRACK==="1"||s2.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(qX(this.configPath)){let $=await Z5.readFile(this.configPath,"utf-8");return this.config=JSON.parse($),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig($){this.config=$;try{let J=Q5.dirname(this.configPath);await Z5.mkdir(J,{recursive:!0}),await Z5.writeFile(this.configPath,JSON.stringify($,null,2),"utf-8")}catch{}}generateUserId(){let $=Math.random().toString(36).substring(2,15),J=Date.now().toString(36);return`${$}-${J}`}}var jw=new oG;function wX($,J={}){let Y={_:[]},Z=J.alias||{},Q=new Set(J.boolean||[]),G={};for(let z of Object.keys(Z))for(let U of Z[z])G[U]=z;for(let z of Q)if(Z[z])for(let U of Z[z])Q.add(U);function W(z,U){let H=G[z]||z;if(Y[H]=U,Z[H])for(let F of Z[H])Y[F]=U;if(G[z]&&Z[G[z]])for(let F of Z[G[z]])Y[F]=U;Y[z]=U}for(let z=0;z<$.length;z++){let U=$[z];if(U==="--"){Y._.push(...$.slice(z+1));break}if(U.startsWith("--")){let H=U.indexOf("=");if(H!==-1){let F=U.slice(2,H),B=U.slice(H+1);W(F,B)}else{let F=U.slice(2);if(F.startsWith("no-")){let K=F.slice(3);W(K,!1);continue}let B=G[F]||F;if(Q.has(B)||Q.has(F))W(F,!0);else{let K=$[z+1];if(K!==void 0&&!K.startsWith("-"))W(F,K),z++;else W(F,!0)}}}else if(U.startsWith("-")&&U.length>1){let H=U.slice(1);for(let F=0;F<H.length;F++){let B=H[F],K=G[B]||B;if(F===H.length-1&&!Q.has(K)&&!Q.has(B)){let O=$[z+1];if(O!==void 0&&!O.startsWith("-"))W(B,O),z++;else W(B,!0)}else W(B,!0)}}else Y._.push(U)}return Y}function z5($){return $.replace(/[<[].+/,"").trim()}function DX($){let J=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,Z=[],Q=(z)=>{let U=!1,H=z[1];if(H.startsWith("..."))H=H.slice(3),U=!0;return{required:z[0].startsWith("<"),value:H,variadic:U}},G;while(G=J.exec($))Z.push(Q(G));let W;while(W=Y.exec($))Z.push(Q(W));return Z}function RX($){let J={alias:{},boolean:[]};for(let[Y,Z]of $.entries()){if(Z.names.length>1)J.alias[Z.names[0]]=Z.names.slice(1);if(Z.isBoolean)if(Z.negated){if(!$.some((G,W)=>{return W!==Y&&G.names.some((z)=>Z.names.includes(z))&&typeof G.required==="boolean"}))J.boolean.push(Z.names[0])}else J.boolean.push(Z.names[0])}return J}function rG($){return $.reduce((J,Y)=>J.length>=Y.length?J:Y,"")}function G5($,J){return $.length>=J?$:`${$}${" ".repeat(J-$.length)}`}function NX($){return $.replace(/([a-z])-([a-z])/g,(J,Y,Z)=>{return Y+Z.toUpperCase()})}function SX($,J,Y){let Z=0,Q=J.length,G=$,W;for(;Z<Q;++Z)W=G[J[Z]],G=G[J[Z]]=Z===Q-1?Y:W!=null?W:!!~J[Z+1].indexOf(".")||!(+J[Z+1]>-1)?{}:[]}function PX($,J){for(let Y of Object.keys(J)){let Z=J[Y];if(Z.shouldTransform){if($[Y]=Array.prototype.concat.call([],$[Y]),typeof Z.transformFunction==="function")$[Y]=$[Y].map(Z.transformFunction)}}}function CX($){let J=/([^\\/]+)$/.exec($);return J?J[1]:""}function eG($){return $.split(".").map((J,Y)=>{return Y===0?NX(J):J}).join(".")}class x9 extends Error{exitCode=2;isUsageError=!0;constructor($){super($);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}format($=!1){if($&&this.stack)return`${this.message}
7520
+ ]`}function gT($){let J=new Map;for(let Y of $){let Z=tQ(Y.name);if(J.has(Z))throw Error(`SSH key '${Z}' already exists in compute.sshKeys`);J.set(Z,{name:Z,publicKey:sQ(Y.publicKey)})}return[...J.values()]}function tQ($){let J=$.trim();if(!/^[\w@.+-]{2,80}$/.test(J))throw Error("SSH key name must be 2-80 characters and use letters, numbers, @, ., +, _, or -.");return J}function sQ($){let J=$.trim().replace(/\s+/g," "),[Y,Z]=J.split(" ");if(!/^(?:ssh-(?:ed25519|rsa)|ecdsa-sha2-nistp(?:256|384|521))$/.test(Y??"")||!Z)throw Error("Public key must be an OpenSSH public key, e.g. ssh-ed25519 AAAA... name@host.");return J}function uT($){return $.trim().split(/\s+/)[0]||"ssh"}function dT($){let J=$.trim().split(/\s+/)[1];if(!J)return"-";try{return`SHA256:${vT("sha256").update(Buffer.from(J,"base64")).digest("base64").replace(/=+$/,"")}`}catch{return"-"}}function NF($){return $.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'")}function cT($,J){let Y=new RegExp(`\\b${J}\\s*:\\s*{`,"g").exec($);if(!Y)throw Error(`Could not find ${J}: { ... } in cloud config.`);let Z=$.indexOf("{",Y.index);return{propertyStart:Y.index,start:Z,end:xF($,Z,"{","}")}}function mT($,J,Y,Z){let Q=$.slice(J+1,Y),G=new RegExp(`\\b${Z}\\s*:\\s*\\[`,"g").exec(Q);if(!G)return null;let W=J+1+G.index,z=$.indexOf("[",W);return{propertyStart:W,start:z,end:xF($,z,"[","]")}}function xF($,J,Y,Z){let Q=0,G,W=!1,z=!1,U=!1;for(let H=J;H<$.length;H++){let F=$[H],B=$[H+1];if(z){if(F===`
7521
+ `)z=!1;continue}if(U){if(F==="*"&&B==="/")U=!1,H++;continue}if(G){if(W){W=!1;continue}if(F==="\\"){W=!0;continue}if(F===G)G=void 0;continue}if(F==="/"&&B==="/"){z=!0,H++;continue}if(F==="/"&&B==="*"){U=!0,H++;continue}if(F==='"'||F==="'"||F==="`"){G=F;continue}if(F===Y)Q++;if(F===Z){if(Q--,Q===0)return H}}throw Error(`Could not find matching ${Z} in cloud config.`)}var oQ=()=>{};var iF={};h0(iF,{serverLogSources:()=>gF,resolveServerDashboardData:()=>YG,resolveConfigOnlyServerDashboardData:()=>nF,parseServerSecurity:()=>mF,parseServerLogs:()=>dF,parseDeployHistory:()=>rF,parseBlock:()=>kF});import{existsSync as lT,readFileSync as pT}from"node:fs";import{join as rT}from"node:path";function iT(){return["set +e",'echo "CPUS=$(nproc 2>/dev/null || echo 1)"',`echo "LOAD=$(cut -d' ' -f1 /proc/loadavg 2>/dev/null || echo 0)"`,`echo "MEMTOTAL=$(free -m 2>/dev/null | awk '/^Mem:/{print $2}')"`,`echo "MEMUSED=$(free -m 2>/dev/null | awk '/^Mem:/{print $3}')"`,`echo "DISKPCT=$(df -P / 2>/dev/null | awk 'NR==2{gsub("%","",$5);print $5}')"`,`echo "DISKUSEDG=$(df -BG / 2>/dev/null | awk 'NR==2{gsub("G","",$3);print $3}')"`,`echo "DISKTOTG=$(df -BG / 2>/dev/null | awk 'NR==2{gsub("G","",$2);print $2}')"`,`echo "UPTIME=$(uptime -p 2>/dev/null | sed 's/^up //' || echo unknown)"`,'echo "OS=$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"',`for s in ${nT.join(" ")}; do st=$(systemctl is-active "$s" 2>/dev/null); if [ -n "$st" ] && [ "$st" != "inactive" ] && [ "$st" != "unknown" ]; then mem=$(systemctl show "$s" -p MemoryCurrent --value 2>/dev/null); en=$(systemctl is-enabled "$s" 2>/dev/null); since=$(systemctl show "$s" -p ActiveEnterTimestamp --value 2>/dev/null); echo "SVC=$s=$st=$mem=$en=$since"; fi; done`,"true"]}function kF($){let J={services:[]};for(let Y of $.split(`
7522
+ `)){let Z=Y.trim();if(Z.startsWith("SVC=")){let[,Q,G,W,z,U]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(Z)??[];if(Q)J.services.push({name:Q,status:G,memBytes:Number(W||0),enabled:z||F1,since:U||F1})}else{let Q=Z.indexOf("=");if(Q>0)J[Z.slice(0,Q)]=Z.slice(Q+1)}}return J}function hF($){let J=$.infrastructure?.compute,Y=[];if(J?.webServer==="rpx"||J?.proxy?.engine==="rpx")Y.push({name:"rpx-gateway",status:"configured"});else if(J?.webServer==="nginx"||J?.webServer==null)Y.push({name:"ts-cloud-nginx",status:"configured"});let Z=J?.php?.versions??(J?.runtime==="php"?["8.3"]:[]);for(let W of Z)Y.push({name:`php${W}-fpm`,status:"configured"});let Q=J?.managedServices??{},G=[["mysql","mysql"],["mariadb","mariadb"],["postgres","postgresql"],["redis","redis"],["memcached","memcached"],["meilisearch","meilisearch"]];for(let[W,z]of G)if(Q[W])Y.push({name:z,status:"configured"});return Y}function aT($){let J=$.infrastructure?.compute?.backups,Y=!!J?.enabled,Z=J?.schedule??"0 2 * * *";return{enabled:Y,schedule:Z,destination:Y?J?.bucket??"local":"off",retention:Y?J?.retentionCount??5:0,last:Y?"pending first run":"not configured",size:Y?F1:"0 MB"}}function bF($){return $.infrastructure?.compute?.provider??$.cloud?.provider??$.provider??"aws"}function tT($){if(bF($)==="hetzner")return $.hetzner?.location??process.env.HCLOUD_LOCATION??process.env.HETZNER_LOCATION??"fsn1";return $.project.region??"us-east-1"}function sT($,J){let Y=rT(process.cwd(),".ts-cloud","state",`${$.project.slug}-${J}.json`);if(!lT(Y))return null;try{return JSON.parse(pT(Y,"utf8"))}catch{return null}}function oT($){let J=$.sites??{},Y=[];for(let[Z,Q]of Object.entries(J)){let G=Q.queues??Q.workers;if(Array.isArray(G)){for(let W of G)if(typeof W==="string")Y.push({name:`${Z}:${W}`,site:Z,processes:1,status:"configured"});else if(W?.name)Y.push({name:`${Z}:${W.name}`,site:Z,processes:W.processes??1,status:"configured"})}}return Y}function yF($){if(!$||$==="")return"/";return $.startsWith("/")?$:`/${$}`}function eT($){let J=yF($.path);if(!$.domain)return{route:"internal"};return{route:J==="/"?$.domain:`${$.domain}${J}`,href:`https://${$.domain}${J==="/"?"":J}`}}function IF($,J){let Y=p0(J);if(Y==="redirect")return"redirect";let Z=String(J.build??"").toLowerCase(),Q=String(J.start??"").toLowerCase();if($==="main"||Q.includes("buddy/src/cli.ts serve"))return"stacks";if($==="api"||Q.includes("/serve/api"))return"api";if(Z.includes("buildblog"))return"bunpress blog";if(Z.includes("bunpress"))return"bunpress";if(Z.includes("site:build")||Z.includes("stx"))return"stx static";if(Y==="server-static")return J.spa?"spa":"static";if(Y==="server-app")return"app";if(Y==="server-php")return J.type??"php";return"bucket"}function $3($){let J=p0($);if(J==="redirect")return"—";let Y=`${$.start??""} ${$.build??""}`.toLowerCase();if(J==="server-static")return Y.includes("bunpress")||Y.includes("bun ")||Y.includes("bunx ")?"static/bun":"static";if(J==="server-app")return Y.includes("bun")?"bun":"node";if(J==="server-php")return`php ${$.php??$.phpVersion??"8.3"}`;return"static"}function J3($){let J=p0($);if(J==="redirect")return"redirect";if(J==="server-app")return"service";if(J==="server-static")return"server static";if(J==="server-php")return"php release";return"bucket"}function Y3($){let J=new Map;return Object.entries($.sites??{}).map(([Y,Z])=>{let Q=yF(Z.path),{route:G,href:W}=eT(Z),z=Z.domain?`${Z.domain}${Q}`:"",U=z?J.get(z):void 0;if(z&&!U)J.set(z,Y);return{name:Y,route:G,href:W,domain:Z.domain??"internal",path:Q,kind:IF(Y,Z),type:IF(Y,Z),runtime:$3(Z),deploy:J3(Z),tls:Z.domain?Z.ssl===!1?"http":"https":"loopback",ssl:Z.domain?Z.ssl!==!1:!1,status:U?"shadowed":"live",shadowedBy:U,lastDeploy:F1}})}function eQ($){return`'${$.replaceAll("'","'\\''")}'`}function vF($){return $.replace(/[\\&/]/g,"\\$&")}function Z3($){if($.length===0)return["true"];return["set +e",...$.map((J)=>{let Y=eQ(`/var/www/${J}/.ts-cloud/deploy-history.log`),Z=vF(J);return`TS_CLOUD_HISTORY=${Y}; { [ -f "$TS_CLOUD_HISTORY" ] && tail -n 24 "$TS_CLOUD_HISTORY" | sed "s/^/DEPLOY=${Z}\\t/"; } || true`}),"true"]}function fF($){return[...new Set(Object.values($.sites??{}).map((J)=>J.domain).filter((J)=>typeof J==="string"&&J.length>0))]}function Q3($){return["set +e",'if command -v ss >/dev/null 2>&1; then ss -H -lntup 2>/dev/null | while read -r proto _state _recv _send local _peer rest; do [ -n "$proto" ] && [ -n "$local" ] && printf "PORT=%s\\t%s\\t%s\\n" "$proto" "$local" "$rest"; done; fi','if command -v ufw >/dev/null 2>&1; then ufw status numbered 2>/dev/null | sed "s/^/FIREWALL=/"; else echo "FIREWALL=ufw unavailable"; fi','journalctl _COMM=sshd --no-pager -n 30 -o short-iso 2>/dev/null | sed "s/^/AUTH=/" || true',...fF($).map((Y)=>{return`TS_CLOUD_DOMAIN=${eQ(Y)}; TS_CLOUD_EXPIRY=$(echo | timeout 8 openssl s_client -servername "$TS_CLOUD_DOMAIN" -connect "$TS_CLOUD_DOMAIN:443" 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2-); [ -n "$TS_CLOUD_EXPIRY" ] && printf "CERT=%s\\t%s\\n" "$TS_CLOUD_DOMAIN" "$TS_CLOUD_EXPIRY" || printf "CERT=%s\\tunavailable\\n" "$TS_CLOUD_DOMAIN"`}),"true"]}function gF($){let J=new Map,Y=(G,W)=>{if(G&&W&&!J.has(W))J.set(W,{pattern:G,label:W})},Z=$.infrastructure?.compute,Q=$.project.slug;if(Z?.webServer==="rpx"||Z?.proxy?.engine==="rpx")Y("rpx-gateway","rpx-gateway");else Y("nginx","nginx");for(let G of hF($))Y(G.name,G.name);for(let[G,W]of Object.entries($.sites??{})){if(p0(W)!=="server-app")continue;if(Y(`${Q}-${G}`,`${Q}-${G}`),Array.isArray(W.queues??W.workers)&&(W.queues??W.workers).length)Y(`${Q}-${G}-queue-*`,`${Q}-${G}-queues`);if(Array.isArray(W.daemons)&&W.daemons.length)Y(`${Q}-${G}-daemon-*`,`${Q}-${G}-daemons`)}return[...J.values()]}function G3($){let J=gF($);if(J.length===0)return["true"];return["set +e",...J.map((Y)=>{let Z=eQ(Y.pattern),Q=vF(Y.label);return`journalctl -u ${Z} --no-pager -n 150 -o short-iso 2>/dev/null | sed "s/^/LOG=${Q}\\t/" || true`}),'[ -f /var/log/ts-cloud-backup.log ] && tail -n 60 /var/log/ts-cloud-backup.log 2>/dev/null | sed "s/^/LOG=backups\\t/" || true',"true"]}function $G($){let J=new Date($);if(Number.isNaN(J.getTime()))return $||F1;let Y=Math.max(0,Math.round((Date.now()-J.getTime())/1000));if(Y<60)return`${Y}s ago`;let Z=Math.round(Y/60);if(Z<60)return`${Z}m ago`;let Q=Math.round(Z/60);if(Q<48)return`${Q}h ago`;return`${Math.round(Q/24)}d ago`}function uF($){if(/(?:error|failed|panic|fatal|exception|denied|unhealthy)/i.test($))return"error";if(/(?:warn|warning|retry|restart|deprecated|timeout)/i.test($))return"warn";return"info"}function dF($){let J=[];for(let Y of $.split(`
7523
+ `)){let Z=Y.trim();if(!Z.startsWith("LOG="))continue;let Q=Z.indexOf("\t");if(Q<0)continue;let G=Z.slice(4,Q),W=Z.slice(Q+1),z=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(W),U=z?.[1]??"",H=z?.[2]??"",F=(z?.[3]??W).trim();if(!F)continue;J.push({source:G,timestamp:U,when:U?$G(U):F1,host:H,message:F,level:uF(F)})}return J.sort((Y,Z)=>String(Z.timestamp).localeCompare(String(Y.timestamp))).slice(0,600)}function cF($){if(/^(?:127\.|localhost:|\[?::1\]?)/.test($))return"loopback";if(/^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|\[?f[cd][0-9a-f:])/i.test($))return"private";return"public"}function W3($){if(cF($)!=="public")return"ok";if(/:(?:22|80|443)$/.test($)||/^\*:(?:22|80|443)$/.test($))return"ok";return"warn"}function z3($){if($==null)return"warn";if($<8)return"bad";if($<30)return"warn";return"ok"}function mF($){let J=[],Y=[],Z=[],Q=[];for(let z of $.split(`
7524
+ `)){let U=z.trim();if(U.startsWith("PORT=")){let[H="",F="",B=""]=U.slice(5).split("\t");if(H&&F)J.push({proto:H,listen:F,processName:B||F1,exposure:cF(F),tone:W3(F)})}else if(U.startsWith("FIREWALL=")){let H=U.slice(9).trim();if(H)Y.push(H)}else if(U.startsWith("AUTH=")){let H=U.slice(5),F=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(H),B=(F?.[3]??H).trim();if(B)Z.push({timestamp:F?.[1]??"",when:F?.[1]?$G(F[1]):F1,host:F?.[2]??"",message:B,level:uF(B)})}else if(U.startsWith("CERT=")){let[H="",F=""]=U.slice(5).split("\t");if(!H)continue;let B=new Date(F),K=Number.isNaN(B.getTime())?null:Math.ceil((B.getTime()-Date.now())/86400000);Q.push({domain:H,expires:Number.isNaN(B.getTime())?F||F1:B.toISOString().slice(0,10),daysRemaining:K,status:z3(K)})}}let G=Y.some((z)=>/Status:\s*active/i.test(z)),W=Y.some((z)=>/unavailable/i.test(z));return{ports:J.slice(0,80),firewall:{status:G?"active":W?"unavailable":"inactive",summary:G?"ufw active":W?"ufw unavailable":"ufw inactive or not configured",rules:Y.filter((z)=>z&&!/^Status:/i.test(z)).slice(0,60)},tlsCertificates:Q,authEvents:Z.sort((z,U)=>String(U.timestamp).localeCompare(String(z.timestamp))).slice(0,30)}}function JG($){let Y=$.infrastructure?.compute?.firewall??{},Z=[...new Set([22,80,443,...Y.allowedPorts??[]])],Q=fF($);return{ports:Z.map((G)=>({proto:"tcp",listen:`0.0.0.0:${G}`,processName:"configured firewall",exposure:"public",tone:[22,80,443].includes(Number(G))?"ok":"warn"})),firewall:{status:Y.enabled===!1?"disabled":"configured",summary:Y.enabled===!1?"host firewall disabled in config":"host firewall configured declaratively",rules:Z.map((G)=>`ALLOW ${G}/tcp`)},tlsCertificates:Q.map((G)=>({domain:G,expires:F1,daysRemaining:null,status:"warn"})),authEvents:[]}}function lF($,J){let Y=J.security??JG($),Z=!!J._serverReachable&&!J.metricsUnavailable,Q=J.sites??[],G=Q.filter((H)=>H.status==="shadowed"),W=(J.services??[]).filter((H)=>["failed","stopped"].includes(H.status)),z=(Y.tlsCertificates??[]).filter((H)=>H.status!=="ok"),U=J.sshKeys??[];return[{name:"Live server probe",status:Z?"pass":"warn",detail:Z?"Metrics and remote checks are coming from the compute box.":"The dashboard is rendering config/state data until the box probe succeeds."},{name:"Managed services",status:W.length?"fail":"pass",detail:W.length?`${W.length} service(s) need attention.`:`${(J.services??[]).length} service(s) reported healthy or configured.`},{name:"Route conflicts",status:G.length?"warn":"pass",detail:G.length?`${G.map((H)=>H.name).join(", ")} is shadowed by an earlier route.`:`${Q.length} site route(s) are unshadowed.`},{name:"SSH access",status:U.length?"pass":"warn",detail:U.length?`${U.length} declarative authorized key(s) configured.`:"No declarative SSH keys are configured."},{name:"Firewall",status:["active","configured"].includes(Y.firewall?.status)?"pass":"warn",detail:Y.firewall?.summary??"Firewall status unavailable."},{name:"TLS certificates",status:z.length?"warn":"pass",detail:z.length?`${z.length} certificate(s) need renewal visibility.`:`${(Y.tlsCertificates??[]).length} certificate(s) look healthy.`}]}function pF($){let J=[];for(let Y of $.serverDeploymentsDetail??$.serverDeployments??[])J.push({type:"deploy",tone:Y.status==="failed"?"bad":"ok",title:`${Y.site} deployed ${Y.sha}`,detail:`${Y.branch} · ${Y.status}`,when:Y.when,timestamp:Y.timestamp});for(let Y of $.serverLogs??[])if(Y.level==="error"||Y.level==="warn")J.push({type:"log",tone:Y.level==="error"?"bad":"warn",title:`${Y.source} ${Y.level}`,detail:Y.message,when:Y.when,timestamp:Y.timestamp});for(let Y of $.sshKeys??[])J.push({type:"ssh",tone:"ok",title:`${Y.name} authorized`,detail:Y.fingerprint,when:Y.added??F1,timestamp:""});return J.sort((Y,Z)=>String(Z.timestamp).localeCompare(String(Y.timestamp))).slice(0,80)}function rF($,J={}){let Y=[];for(let Z of $.split(`
7525
+ `)){let Q=Z.trim();if(!Q.startsWith("DEPLOY="))continue;let G=Q.split("\t"),W=G[0]?.replace(/^DEPLOY=/,"")??"",[z,U,H,F,B]=G.slice(1);if(!W||!z||!U)continue;let K=J[W]??{},O=p0(K),A=(H||U).slice(0,7);Y.push({sha:A,release:U,commit:H||U,site:W,branch:K.branch??(O==="server-static"?"build artifact":"main"),status:F||"unknown",when:$G(z),timestamp:z,took:"-",by:"ts-cloud",rc:B?.replace(/^rc=/,"")??"",steps:O==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return Y.sort((Z,Q)=>String(Q.timestamp).localeCompare(String(Z.timestamp)))}function nF($,J){let Y=sT($,J),Z=hF($),Q=Y3($),G=Math.max(1,Number($.infrastructure?.compute?.disk?.size??1)),W={server:{name:Y?.serverName??`${$.project.slug}-${J}-app`,provider:Y?.provider??bF($),region:tT($),ip:Y?.publicIp??F1,os:"Linux",uptime:F1,probeStatus:"unavailable"},systemMetrics:{load:0,cpus:Math.max(1,Number($.infrastructure?.compute?.instances??1)),memUsedMb:0,memTotalMb:0,diskUsedPct:0,diskUsedGb:0,diskTotalGb:G},metricsUnavailable:!0,services:Z,servicesDetail:Z.map((z)=>({...z,since:F1,memMb:0,auto:!0})),backup:aT($),backupHistory:[],workers:oT($),serverScheduler:{enabled:!1,lastRun:"not configured"},serverDeployments:[],serverDeploymentsDetail:[],deploymentsEmptyReason:"No deployment history has been recorded yet. Future server deploys will write /var/www/<site>/.ts-cloud/deploy-history.log.",serverLogs:[],serverLogsEmptyReason:"Live server logs are unavailable until the dashboard can reach the compute box.",security:JG($),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:Q,sitesDetail:Q.map((z)=>{let U=$.sites?.[z.name]??{},H=p0(U);return{...z,root:H==="server-static"?`/var/www/${z.name}`:`/var/www/${z.name}/current`,branch:H==="server-static"?"build artifact":"main",build:U.build,envKeys:Object.keys(U.env??U.environment??{})}}),sshKeys:n2($.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return W.diagnostics=lF($,W),W.activity=pF(W),W}async function YG($,J){if(!$.infrastructure?.compute)return null;let Y=null;try{Y=Y1({config:$})}catch{Y=null}let Z=null,Q=0,G=[];if(Y)try{if(G=await Y.findComputeTargets({slug:$.project.slug,environment:J,role:"app"}),Q=G.length,G.length){let F=(await Y.runRemoteDeploy({targets:[G[0]],commands:iT(),comment:`ts-cloud dashboard:build ${$.project.slug}`,tags:{Project:$.project.slug,Environment:J,Role:"app"}})).perInstance?.[0]?.output;if(F)Z=kF(F)}}catch{}let W=nF($,J),z=(H,F=0)=>{let B=Number(H);return Number.isFinite(B)?B:F};if(W.server.os=Z?.OS||W.server.os,W.server.uptime=Z?.UPTIME||W.server.uptime,Z){if(W.server.probeStatus="live",W.metricsUnavailable=!1,W._metricsStatus="live",W.systemMetrics={load:z(Z.LOAD),cpus:z(Z.CPUS,1),memUsedMb:z(Z.MEMUSED),memTotalMb:z(Z.MEMTOTAL,1),diskUsedPct:z(Z.DISKPCT),diskUsedGb:z(Z.DISKUSEDG),diskTotalGb:z(Z.DISKTOTG,1)},Z.services.length)W.services=Z.services.map((H)=>({name:H.name,status:H.status==="active"?"running":H.status})),W.servicesDetail=Z.services.map((H)=>({name:H.name,status:H.status==="active"?"running":H.status,since:H.since&&H.since!==F1?H.since:W.server.uptime,memMb:Math.max(0,Math.round(Number(H.memBytes??0)/1024/1024)),auto:H.enabled?!["disabled","static","masked"].includes(H.enabled):!0}))}if(Y&&G.length)try{let H=Object.keys($.sites??{}),B=(await Y.runRemoteDeploy({targets:[G[0]],commands:Z3(H),comment:`ts-cloud dashboard:deploy-history ${$.project.slug}`,tags:{Project:$.project.slug,Environment:J,Role:"app"}})).perInstance?.[0]?.output??"",K=rF(B,$.sites);W.serverDeployments=K.slice(0,5),W.serverDeploymentsDetail=K.slice(0,50),W.deploymentsEmptyReason=K.length?void 0:"No deployment history was found on the server yet. Deploy again to populate this timeline."}catch{W.deploymentsEmptyReason="Deployment history could not be read from the server."}else if(Y&&Q===0)W.deploymentsEmptyReason="No app server target was found for this environment.";if(Y&&G.length)try{let F=(await Y.runRemoteDeploy({targets:[G[0]],commands:G3($),comment:`ts-cloud dashboard:server-logs ${$.project.slug}`,tags:{Project:$.project.slug,Environment:J,Role:"app"}})).perInstance?.[0]?.output??"",B=dF(F);W.serverLogs=B,W.serverLogsEmptyReason=B.length?void 0:"No recent journal entries were found for the managed server units."}catch{W.serverLogsEmptyReason="Server logs could not be read from the box."}if(Y&&G.length)try{let F=(await Y.runRemoteDeploy({targets:[G[0]],commands:Q3($),comment:`ts-cloud dashboard:security ${$.project.slug}`,tags:{Project:$.project.slug,Environment:J,Role:"app"}})).perInstance?.[0]?.output??"",B=mF(F),K=JG($);if(!B.ports.length)B.ports=K.ports;if(!B.tlsCertificates.length)B.tlsCertificates=K.tlsCertificates;W.security=B,W.securityEmptyReason=void 0}catch{W.securityEmptyReason="Server security checks could not be read from the box."}let U=$.infrastructure?.compute?.sshKeys??$.infrastructure?.ssh?.keys??$.infrastructure?.sshKeys;if(Array.isArray(U)&&U.length)W.sshKeys=n2(U);return W._serverReachable=Q>0&&!!Z,W.diagnostics=lF($,W),W.activity=pF(W),W}var nT,F1="-";var ZG=o(async()=>{O$();oQ();await j$();nT=["rpx-gateway","nginx","php8.3-fpm","php8.2-fpm","mysql","mariadb","postgresql","redis","redis-server","meilisearch"]});import{existsSync as qX}from"node:fs";import Z5 from"node:fs/promises";import lG from"node:os";import Q5 from"node:path";import s2 from"node:process";import{EventEmitter as TX}from"node:events";import C2 from"node:process";import pG from"node:process";import U5 from"node:process";import I9 from"node:process";import F8 from"node:process";import iG from"node:tty";import FB,{stdin as Pw,stdout as Cw}from"node:process";import tG,{stdin as KB,stdout as OB}from"node:process";import VB from"node:readline";class oG{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=lG.homedir(),J=Q5.join($,".config","clapp");this.configPath=Q5.join(J,"telemetry.json")}async isEnabled(){if(s2.env.DO_NOT_TRACK==="1"||s2.env.DO_NOT_TRACK==="true")return!1;if(s2.env.NO_TELEMETRY==="1"||s2.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let $=await this.loadConfig();if($.enabled=!0,!$.userId)$.userId=this.generateUserId();await this.saveConfig($)}async disable(){let $=await this.loadConfig();$.enabled=!1,await this.saveConfig($)}async track($,J){if(!await this.isEnabled())return;let Z={event:$,...J,timestamp:Date.now(),platform:lG.platform(),nodeVersion:s2.version};if(this.events.push(Z),this.events.length>=10)await this.send()}async trackCommand($,J){await this.track("command",{command:$,duration:J})}async trackError($,J){await this.track("error",{error:$,command:J})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let J=await this.loadConfig();return J.lastSent=Date.now(),await this.saveConfig(J),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let J=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(J),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep($){return new Promise((J)=>setTimeout(J,$))}async status(){let $=await this.loadConfig();return{enabled:$.enabled,doNotTrack:s2.env.DO_NOT_TRACK==="1"||s2.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(qX(this.configPath)){let $=await Z5.readFile(this.configPath,"utf-8");return this.config=JSON.parse($),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig($){this.config=$;try{let J=Q5.dirname(this.configPath);await Z5.mkdir(J,{recursive:!0}),await Z5.writeFile(this.configPath,JSON.stringify($,null,2),"utf-8")}catch{}}generateUserId(){let $=Math.random().toString(36).substring(2,15),J=Date.now().toString(36);return`${$}-${J}`}}var _w=new oG;function wX($,J={}){let Y={_:[]},Z=J.alias||{},Q=new Set(J.boolean||[]),G={};for(let z of Object.keys(Z))for(let U of Z[z])G[U]=z;for(let z of Q)if(Z[z])for(let U of Z[z])Q.add(U);function W(z,U){let H=G[z]||z;if(Y[H]=U,Z[H])for(let F of Z[H])Y[F]=U;if(G[z]&&Z[G[z]])for(let F of Z[G[z]])Y[F]=U;Y[z]=U}for(let z=0;z<$.length;z++){let U=$[z];if(U==="--"){Y._.push(...$.slice(z+1));break}if(U.startsWith("--")){let H=U.indexOf("=");if(H!==-1){let F=U.slice(2,H),B=U.slice(H+1);W(F,B)}else{let F=U.slice(2);if(F.startsWith("no-")){let K=F.slice(3);W(K,!1);continue}let B=G[F]||F;if(Q.has(B)||Q.has(F))W(F,!0);else{let K=$[z+1];if(K!==void 0&&!K.startsWith("-"))W(F,K),z++;else W(F,!0)}}}else if(U.startsWith("-")&&U.length>1){let H=U.slice(1);for(let F=0;F<H.length;F++){let B=H[F],K=G[B]||B;if(F===H.length-1&&!Q.has(K)&&!Q.has(B)){let O=$[z+1];if(O!==void 0&&!O.startsWith("-"))W(B,O),z++;else W(B,!0)}else W(B,!0)}}else Y._.push(U)}return Y}function z5($){return $.replace(/[<[].+/,"").trim()}function DX($){let J=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,Z=[],Q=(z)=>{let U=!1,H=z[1];if(H.startsWith("..."))H=H.slice(3),U=!0;return{required:z[0].startsWith("<"),value:H,variadic:U}},G;while(G=J.exec($))Z.push(Q(G));let W;while(W=Y.exec($))Z.push(Q(W));return Z}function RX($){let J={alias:{},boolean:[]};for(let[Y,Z]of $.entries()){if(Z.names.length>1)J.alias[Z.names[0]]=Z.names.slice(1);if(Z.isBoolean)if(Z.negated){if(!$.some((G,W)=>{return W!==Y&&G.names.some((z)=>Z.names.includes(z))&&typeof G.required==="boolean"}))J.boolean.push(Z.names[0])}else J.boolean.push(Z.names[0])}return J}function rG($){return $.reduce((J,Y)=>J.length>=Y.length?J:Y,"")}function G5($,J){return $.length>=J?$:`${$}${" ".repeat(J-$.length)}`}function NX($){return $.replace(/([a-z])-([a-z])/g,(J,Y,Z)=>{return Y+Z.toUpperCase()})}function SX($,J,Y){let Z=0,Q=J.length,G=$,W;for(;Z<Q;++Z)W=G[J[Z]],G=G[J[Z]]=Z===Q-1?Y:W!=null?W:!!~J[Z+1].indexOf(".")||!(+J[Z+1]>-1)?{}:[]}function PX($,J){for(let Y of Object.keys(J)){let Z=J[Y];if(Z.shouldTransform){if($[Y]=Array.prototype.concat.call([],$[Y]),typeof Z.transformFunction==="function")$[Y]=$[Y].map(Z.transformFunction)}}}function CX($){let J=/([^\\/]+)$/.exec($);return J?J[1]:""}function eG($){return $.split(".").map((J,Y)=>{return Y===0?NX(J):J}).join(".")}class x9 extends Error{exitCode=2;isUsageError=!0;constructor($){super($);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}format($=!1){if($&&this.stack)return`${this.message}
7521
7526
 
7522
7527
  Stack trace:
7523
- ${this.stack}`;return this.message}}function xX(){let{env:$}=pG,{TERM:J,TERM_PROGRAM:Y}=$;if(pG.platform!=="win32")return J!=="linux";return Boolean($.WT_SESSION)||Boolean($.TERMINUS_SUBLIME)||$.ConEmuTask==="{cmd::Cmder}"||Y==="Terminus-Sublime"||Y==="vscode"||J==="xterm-256color"||J==="alacritty"||J==="rxvt-unicode"||J==="rxvt-unicode-256color"||$.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var b9="\x1B",b0=`${b9}[`;var B2={to($,J){if(!J)return`${b0}${$+1}G`;return`${b0}${J+1};${$+1}H`},move($,J){let Y="";if($<0)Y+=`${b0}${-$}D`;else if($>0)Y+=`${b0}${$}C`;if(J<0)Y+=`${b0}${-J}A`;else if(J>0)Y+=`${b0}${J}B`;return Y},up:($=1)=>`${b0}${$}A`,down:($=1)=>`${b0}${$}B`,forward:($=1)=>`${b0}${$}C`,backward:($=1)=>`${b0}${$}D`,nextLine:($=1)=>`${b0}E`.repeat($),prevLine:($=1)=>`${b0}F`.repeat($),left:`${b0}G`,hide:`${b0}?25l`,show:`${b0}?25h`,save:`${b9}7`,restore:`${b9}8`};var W5={screen:`${b0}2J`,up:($=1)=>`${b0}1J`.repeat($),down:($=1)=>`${b0}J`.repeat($),line:`${b0}2K`,lineEnd:`${b0}K`,lineStart:`${b0}1K`,lines($){let J="";for(let Y=0;Y<$;Y++)J+=this.line+(Y<$-1?B2.up():"");if($)J+=B2.left;return J}},qw={screen:`${b9}c`};function IX($,J){let Y=[];for(let Z=0;Z<=J.length;Z++)Y[Z]=[Z];for(let Z=0;Z<=$.length;Z++)Y[0][Z]=Z;for(let Z=1;Z<=J.length;Z++)for(let Q=1;Q<=$.length;Q++)if(J.charAt(Z-1)===$.charAt(Q-1))Y[Z][Q]=Y[Z-1][Q-1];else Y[Z][Q]=Math.min(Y[Z-1][Q-1]+1,Y[Z][Q-1]+1,Y[Z-1][Q]+1);return Y[J.length][$.length]}function $W($,J,Y=2,Z=3){return J.map((Q)=>({cmd:Q,distance:IX($,Q)})).filter(({distance:Q})=>Q<=Y).sort((Q,G)=>Q.distance-G.distance).slice(0,Z).map(({cmd:Q})=>Q)}class JW{rawName;description;name;names;isBoolean;required;config;negated;constructor($,J,Y){if(this.rawName=$,this.description=J,this.config=Object.assign({},Y),$=$.replace(/\.\*/g,""),this.negated=!1,this.names=z5($).split(",").map((Z)=>{let Q=Z.trim().replace(/^-{1,2}/,"");if(Q.startsWith("no-"))this.negated=!0,Q=Q.replace(/^no-/,"");return eG(Q)}).sort((Z,Q)=>Z.length>Q.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if($.includes("<"))this.required=!0;else if($.includes("["))this.required=!1;else this.isBoolean=!0}}var ww=U5.argv,kX=`${U5.platform}-${U5.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,nG=I9.argv,hX=`${I9.platform}-${I9.arch} node-${I9.version}`;class H5{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor($,J,Y,Z){this.rawName=$,this.description=J,this.config=Y,this.cli=Z,this.options=[],this.aliasNames=[],this.name=z5($);let Q=z5($),G=Q.indexOf(":");if(G>0)this.namespace=Q.substring(0,G),this.name=Q.substring(G+1);if(this.args=DX($),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Y)this.config={}}usage($){return this.usageText=$,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version($,J="-v, --version"){return this.versionNumber=$,this.option(J,"Display version number"),this}example($){return this.examples.push($),this}option($,J,Y){let Z=new JW($,J,Y);return this.options.push(Z),this}alias($){return this.aliasNames.push($),this}action($){return this.commandAction=$,this}before($){return this.beforeHooks.push($),this}after($){return this.afterHooks.push($),this}use($){return this.middleware.push($),this}isMatched($){if(this.aliasNames.includes($))return!0;if(this.name===$)return!0;if(this.namespace&&`${this.namespace}:${this.name}`===$)return!0;return!1}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof F5}hasOption($){return $=$.split(".")[0],!!this.options.find((J)=>{return J.names.includes($)})}outputHelp(){let{name:$,commands:J}=this.cli,{versionNumber:Y,options:Z,helpCallback:Q}=this.cli.globalCommand,G=[{body:`${$}${Y?`/${Y}`:""}`}];if(G.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&J.length>0){let U=rG(J.map((O)=>O.rawName)),H=new Map,F=[];for(let O of J)if(O.namespace){if(!H.has(O.namespace))H.set(O.namespace,[]);H.get(O.namespace).push(O)}else F.push(O);let B="";if(F.length>0)B+=F.map((O)=>{return` ${G5(O.rawName,U.length)} ${O.description}`}).join(`
7528
+ ${this.stack}`;return this.message}}function xX(){let{env:$}=pG,{TERM:J,TERM_PROGRAM:Y}=$;if(pG.platform!=="win32")return J!=="linux";return Boolean($.WT_SESSION)||Boolean($.TERMINUS_SUBLIME)||$.ConEmuTask==="{cmd::Cmder}"||Y==="Terminus-Sublime"||Y==="vscode"||J==="xterm-256color"||J==="alacritty"||J==="rxvt-unicode"||J==="rxvt-unicode-256color"||$.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var b9="\x1B",b0=`${b9}[`;var B2={to($,J){if(!J)return`${b0}${$+1}G`;return`${b0}${J+1};${$+1}H`},move($,J){let Y="";if($<0)Y+=`${b0}${-$}D`;else if($>0)Y+=`${b0}${$}C`;if(J<0)Y+=`${b0}${-J}A`;else if(J>0)Y+=`${b0}${J}B`;return Y},up:($=1)=>`${b0}${$}A`,down:($=1)=>`${b0}${$}B`,forward:($=1)=>`${b0}${$}C`,backward:($=1)=>`${b0}${$}D`,nextLine:($=1)=>`${b0}E`.repeat($),prevLine:($=1)=>`${b0}F`.repeat($),left:`${b0}G`,hide:`${b0}?25l`,show:`${b0}?25h`,save:`${b9}7`,restore:`${b9}8`};var W5={screen:`${b0}2J`,up:($=1)=>`${b0}1J`.repeat($),down:($=1)=>`${b0}J`.repeat($),line:`${b0}2K`,lineEnd:`${b0}K`,lineStart:`${b0}1K`,lines($){let J="";for(let Y=0;Y<$;Y++)J+=this.line+(Y<$-1?B2.up():"");if($)J+=B2.left;return J}},Mw={screen:`${b9}c`};function IX($,J){let Y=[];for(let Z=0;Z<=J.length;Z++)Y[Z]=[Z];for(let Z=0;Z<=$.length;Z++)Y[0][Z]=Z;for(let Z=1;Z<=J.length;Z++)for(let Q=1;Q<=$.length;Q++)if(J.charAt(Z-1)===$.charAt(Q-1))Y[Z][Q]=Y[Z-1][Q-1];else Y[Z][Q]=Math.min(Y[Z-1][Q-1]+1,Y[Z][Q-1]+1,Y[Z-1][Q]+1);return Y[J.length][$.length]}function $W($,J,Y=2,Z=3){return J.map((Q)=>({cmd:Q,distance:IX($,Q)})).filter(({distance:Q})=>Q<=Y).sort((Q,G)=>Q.distance-G.distance).slice(0,Z).map(({cmd:Q})=>Q)}class JW{rawName;description;name;names;isBoolean;required;config;negated;constructor($,J,Y){if(this.rawName=$,this.description=J,this.config=Object.assign({},Y),$=$.replace(/\.\*/g,""),this.negated=!1,this.names=z5($).split(",").map((Z)=>{let Q=Z.trim().replace(/^-{1,2}/,"");if(Q.startsWith("no-"))this.negated=!0,Q=Q.replace(/^no-/,"");return eG(Q)}).sort((Z,Q)=>Z.length>Q.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if($.includes("<"))this.required=!0;else if($.includes("["))this.required=!1;else this.isBoolean=!0}}var Tw=U5.argv,kX=`${U5.platform}-${U5.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,nG=I9.argv,hX=`${I9.platform}-${I9.arch} node-${I9.version}`;class H5{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor($,J,Y,Z){this.rawName=$,this.description=J,this.config=Y,this.cli=Z,this.options=[],this.aliasNames=[],this.name=z5($);let Q=z5($),G=Q.indexOf(":");if(G>0)this.namespace=Q.substring(0,G),this.name=Q.substring(G+1);if(this.args=DX($),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Y)this.config={}}usage($){return this.usageText=$,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version($,J="-v, --version"){return this.versionNumber=$,this.option(J,"Display version number"),this}example($){return this.examples.push($),this}option($,J,Y){let Z=new JW($,J,Y);return this.options.push(Z),this}alias($){return this.aliasNames.push($),this}action($){return this.commandAction=$,this}before($){return this.beforeHooks.push($),this}after($){return this.afterHooks.push($),this}use($){return this.middleware.push($),this}isMatched($){if(this.aliasNames.includes($))return!0;if(this.name===$)return!0;if(this.namespace&&`${this.namespace}:${this.name}`===$)return!0;return!1}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof F5}hasOption($){return $=$.split(".")[0],!!this.options.find((J)=>{return J.names.includes($)})}outputHelp(){let{name:$,commands:J}=this.cli,{versionNumber:Y,options:Z,helpCallback:Q}=this.cli.globalCommand,G=[{body:`${$}${Y?`/${Y}`:""}`}];if(G.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&J.length>0){let U=rG(J.map((O)=>O.rawName)),H=new Map,F=[];for(let O of J)if(O.namespace){if(!H.has(O.namespace))H.set(O.namespace,[]);H.get(O.namespace).push(O)}else F.push(O);let B="";if(F.length>0)B+=F.map((O)=>{return` ${G5(O.rawName,U.length)} ${O.description}`}).join(`
7524
7529
  `);let K=Array.from(H.keys()).sort();for(let O of K){let A=H.get(O);if(B.length>0)B+=`
7525
7530
 
7526
7531
  `;B+=` ${O}:
@@ -7546,16 +7551,16 @@ Received ${Y}, cleaning up...`),$)try{await $()}catch(Z){console.error("Error du
7546
7551
  ✗ Command "${$}" not found.
7547
7552
  `)),this.enableDidYouMean){let J=[];for(let Z of this.commands){if(Z.name)J.push(Z.name);if(Z.aliasNames)J.push(...Z.aliasNames)}let Y=$W($,J);if(Y.length>0)console.log(H8.yellow("Did you mean one of these?")),Y.forEach((Z)=>console.log(` ${H8.dim("•")} ${this.name} ${Z}`)),console.log("")}console.log(H8.dim("Run"),`${this.name} --help`,H8.dim("to see all available commands")),C2.exit(1)}async parse($=nG,J={}){let{run:Y=!0,exitOnError:Z=!1}=J;if(Z)try{return await this.parse($,{run:Y})}catch(U){throw this.handleUsageError(U),U}if(this.rawArgs=$,!this.name)this.name=$[1]?CX($[1]):"cli";let Q=!0,G=$.slice(2),W=G[0];if(W&&!W.startsWith("-")){for(let U of this.commands)if(U.isMatched(W)){let H=this.mri(G,U);Q=!1;let F={...H,args:H.args.slice(1)};this.setParsedInfo(F,U,W),this.emit(`command:${W}`,U);break}}if(Q){for(let U of this.commands)if(U.name===""){Q=!1;let H=this.mri(G,U);this.setParsedInfo(H,U),this.emit("command:!",U);break}}if(Q){let U=this.mri($.slice(2));this.setParsedInfo(U)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),Y=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),Y=!1,this.unsetMatchedCommand();let z={args:this.args,options:this.options};if(Y)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return z}mri($,J){let Y=[...this.globalCommand.options,...J?J.options:[]],Z=RX(Y),Q=[],G=$.indexOf("--");if(G>-1)Q=$.slice(G+1),$=$.slice(0,G);let W=wX($,Z),z={_:W._};for(let K of Object.keys(W))if(K!=="_")z[eG(K)]=W[K];let U=z._,H={"--":Q},F=J&&J.config.ignoreOptionDefaultValue?J.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,B=Object.create(null);for(let K of Y){if(!F&&K.config.default!==void 0)for(let O of K.names)H[O]=K.config.default;if(Array.isArray(K.config.type)){if(B[K.name]===void 0)B[K.name]={shouldTransform:!0,transformFunction:K.config.type[0]}}}for(let K of Object.keys(z))if(K!=="_"){let O=K.split(".");SX(H,O,z[K]),PX(H,B)}return{args:U,options:H}}async run($=nG){return this.parse($,{run:!0,exitOnError:!0})}handleUsageError($){if(!(!!$&&typeof $==="object"&&$.name==="ClappError"&&$.isUsageError!==!1))return;let Z=$,Q=Z.message??"command-line error",G=this.name?`${this.name}: `:"",W=/--help/.test(Q)?"":`
7548
7553
  Run \`${this.name??"cli"} --help\` for usage.`;C2.stderr.write(`${G}${Q}${W}
7549
- `),C2.exit(Z.exitCode??2)}async runMatchedCommand(){let{args:$,options:J,matchedCommand:Y}=this;if(!Y||!Y.commandAction)return;Y.checkUnknownOptions(),Y.checkOptionValue(),Y.checkRequiredArgs();let Z=[];Y.args.forEach((z,U)=>{if(z.variadic)Z.push($.slice(U));else Z.push($[U])}),Z.push(J);let Q={command:Y,args:Z,options:J};for(let z of Y.beforeHooks)await z(Q);let G,W=async()=>{let z=Y.commandAction.apply(this,Z);if(z instanceof Promise)G=await z;else G=z;return G};if(Y.middleware.length>0){let z=0,U=async()=>{if(z<Y.middleware.length){let H=Y.middleware[z++];await H({...Q,next:U})}else await W()};await U()}else await W();for(let z of Y.afterHooks)await z(Q);return G}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return C2.removeAllListeners("SIGINT"),C2.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class YW{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get($){if(!this.enabled){this.misses++;return}let J=this.cache.get($);if(!J){this.misses++;return}if(Date.now()-J.timestamp>J.ttl){this.cache.delete($),this.misses++;return}return this.hits++,J.value}set($,J,Y=5000){if(!this.enabled)return;this.cache.set($,{value:J,timestamp:Date.now(),ttl:Y})}has($){if(!this.enabled)return!1;let J=this.cache.get($);if(!J)return!1;if(Date.now()-J.timestamp>J.ttl)return this.cache.delete($),!1;return!0}delete($){this.cache.delete($)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let $=Date.now();for(let[J,Y]of this.cache.entries())if($-Y.timestamp>Y.ttl)this.cache.delete(J)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var Rw=new YW;function fX(){if("FORCE_COLOR"in F8.env)return F8.env.FORCE_COLOR!=="0";if("NO_COLOR"in F8.env||F8.env.TERM==="dumb")return!1;if(F8.platform==="win32")return!0;return iG.isatty(1)&&iG.isatty(2)}var ZW=fX();function C0($,J){if(!ZW)return(Y)=>Y;return(Y)=>$+Y+J}var gX=C0("\x1B[0m","\x1B[0m"),uX=C0("\x1B[31m","\x1B[39m"),dX=C0("\x1B[32m","\x1B[39m"),cX=C0("\x1B[33m","\x1B[39m"),mX=C0("\x1B[34m","\x1B[39m"),lX=C0("\x1B[35m","\x1B[39m"),pX=C0("\x1B[36m","\x1B[39m"),rX=C0("\x1B[37m","\x1B[39m"),nX=C0("\x1B[90m","\x1B[39m"),iX=C0("\x1B[1m","\x1B[22m"),aX=C0("\x1B[3m","\x1B[23m"),tX=C0("\x1B[4m","\x1B[24m"),sX=C0("\x1B[2m","\x1B[22m"),oX=C0("\x1B[7m","\x1B[27m"),eX=C0("\x1B[8m","\x1B[28m"),$B=C0("\x1B[9m","\x1B[29m"),JB=C0("\x1B[41m","\x1B[49m"),YB=C0("\x1B[42m","\x1B[49m"),ZB=C0("\x1B[43m","\x1B[49m"),QB=C0("\x1B[44m","\x1B[49m"),GB=C0("\x1B[45m","\x1B[49m"),WB=C0("\x1B[46m","\x1B[49m"),zB=C0("\x1B[47m","\x1B[49m"),UB=ZW,HB={reset:gX,red:uX,green:dX,yellow:cX,blue:mX,magenta:lX,cyan:pX,white:rX,gray:nX,bold:iX,italic:aX,underline:tX,dim:sX,inverse:oX,hidden:eX,strikethrough:$B,bgRed:JB,bgGreen:YB,bgYellow:ZB,bgBlue:QB,bgMagenta:GB,bgCyan:WB,bgWhite:zB,isColorSupported:UB},k9=HB,XB=["up","down","left","right","space","enter","cancel"],h9={actions:new Set(XB),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function QW($,J){if(typeof $==="string")return h9.aliases.get($)===J;for(let Y of $){if(Y===void 0)continue;if(QW(Y,J))return!0}return!1}function BB($,J){if($===J)return[];let Y=$.split(`
7554
+ `),C2.exit(Z.exitCode??2)}async runMatchedCommand(){let{args:$,options:J,matchedCommand:Y}=this;if(!Y||!Y.commandAction)return;Y.checkUnknownOptions(),Y.checkOptionValue(),Y.checkRequiredArgs();let Z=[];Y.args.forEach((z,U)=>{if(z.variadic)Z.push($.slice(U));else Z.push($[U])}),Z.push(J);let Q={command:Y,args:Z,options:J};for(let z of Y.beforeHooks)await z(Q);let G,W=async()=>{let z=Y.commandAction.apply(this,Z);if(z instanceof Promise)G=await z;else G=z;return G};if(Y.middleware.length>0){let z=0,U=async()=>{if(z<Y.middleware.length){let H=Y.middleware[z++];await H({...Q,next:U})}else await W()};await U()}else await W();for(let z of Y.afterHooks)await z(Q);return G}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return C2.removeAllListeners("SIGINT"),C2.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class YW{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get($){if(!this.enabled){this.misses++;return}let J=this.cache.get($);if(!J){this.misses++;return}if(Date.now()-J.timestamp>J.ttl){this.cache.delete($),this.misses++;return}return this.hits++,J.value}set($,J,Y=5000){if(!this.enabled)return;this.cache.set($,{value:J,timestamp:Date.now(),ttl:Y})}has($){if(!this.enabled)return!1;let J=this.cache.get($);if(!J)return!1;if(Date.now()-J.timestamp>J.ttl)return this.cache.delete($),!1;return!0}delete($){this.cache.delete($)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let $=Date.now();for(let[J,Y]of this.cache.entries())if($-Y.timestamp>Y.ttl)this.cache.delete(J)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var Dw=new YW;function fX(){if("FORCE_COLOR"in F8.env)return F8.env.FORCE_COLOR!=="0";if("NO_COLOR"in F8.env||F8.env.TERM==="dumb")return!1;if(F8.platform==="win32")return!0;return iG.isatty(1)&&iG.isatty(2)}var ZW=fX();function C0($,J){if(!ZW)return(Y)=>Y;return(Y)=>$+Y+J}var gX=C0("\x1B[0m","\x1B[0m"),uX=C0("\x1B[31m","\x1B[39m"),dX=C0("\x1B[32m","\x1B[39m"),cX=C0("\x1B[33m","\x1B[39m"),mX=C0("\x1B[34m","\x1B[39m"),lX=C0("\x1B[35m","\x1B[39m"),pX=C0("\x1B[36m","\x1B[39m"),rX=C0("\x1B[37m","\x1B[39m"),nX=C0("\x1B[90m","\x1B[39m"),iX=C0("\x1B[1m","\x1B[22m"),aX=C0("\x1B[3m","\x1B[23m"),tX=C0("\x1B[4m","\x1B[24m"),sX=C0("\x1B[2m","\x1B[22m"),oX=C0("\x1B[7m","\x1B[27m"),eX=C0("\x1B[8m","\x1B[28m"),$B=C0("\x1B[9m","\x1B[29m"),JB=C0("\x1B[41m","\x1B[49m"),YB=C0("\x1B[42m","\x1B[49m"),ZB=C0("\x1B[43m","\x1B[49m"),QB=C0("\x1B[44m","\x1B[49m"),GB=C0("\x1B[45m","\x1B[49m"),WB=C0("\x1B[46m","\x1B[49m"),zB=C0("\x1B[47m","\x1B[49m"),UB=ZW,HB={reset:gX,red:uX,green:dX,yellow:cX,blue:mX,magenta:lX,cyan:pX,white:rX,gray:nX,bold:iX,italic:aX,underline:tX,dim:sX,inverse:oX,hidden:eX,strikethrough:$B,bgRed:JB,bgGreen:YB,bgYellow:ZB,bgBlue:QB,bgMagenta:GB,bgCyan:WB,bgWhite:zB,isColorSupported:UB},k9=HB,XB=["up","down","left","right","space","enter","cancel"],h9={actions:new Set(XB),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function QW($,J){if(typeof $==="string")return h9.aliases.get($)===J;for(let Y of $){if(Y===void 0)continue;if(QW(Y,J))return!0}return!1}function BB($,J){if($===J)return[];let Y=$.split(`
7550
7555
  `),Z=J.split(`
7551
- `),Q=[];for(let G=0;G<Math.max(Y.length,Z.length);G++)if(Y[G]!==Z[G])Q.push(G);return Q}var Iw=FB.platform.startsWith("win"),aG=Symbol("clapp:cancel");function C9($,J){let Y=$;if(Y.isTTY)Y.setRawMode(J)}function AB($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function _B($){return AB($).length}function sG($,J,Y){if(!J||J<1)return $;let Z=Y?.hard??!1,Q=Y?.trim??!0,G=$.split(`
7556
+ `),Q=[];for(let G=0;G<Math.max(Y.length,Z.length);G++)if(Y[G]!==Z[G])Q.push(G);return Q}var xw=FB.platform.startsWith("win"),aG=Symbol("clapp:cancel");function C9($,J){let Y=$;if(Y.isTTY)Y.setRawMode(J)}function AB($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function _B($){return AB($).length}function sG($,J,Y){if(!J||J<1)return $;let Z=Y?.hard??!1,Q=Y?.trim??!0,G=$.split(`
7552
7557
  `),W=[];for(let z of G){if(_B(z)<=J){W.push(Q?z.trimEnd():z);continue}if(Z){let U="",H=0,F=0;while(F<z.length){let B=z.slice(F).match(/^\x1b\[[0-9;]*m/);if(B){U+=B[0],F+=B[0].length;continue}if(H>=J)W.push(Q?U.trimEnd():U),U="",H=0;U+=z[F],H++,F++}if(U)W.push(Q?U.trimEnd():U)}else W.push(Q?z.trimEnd():z)}return W.join(`
7553
7558
  `)}class B5{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor($,J=!0){let{input:Y=KB,output:Z=OB,render:Q,signal:G,...W}=$;this.opts=W,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=Q.bind(this),this._track=J,this._abortSignal=G,this.input=Y,this.output=Z}unsubscribe(){this._subscribers.clear()}setSubscriber($,J){let Y=this._subscribers.get($)??[];Y.push(J),this._subscribers.set($,Y)}on($,J){return this.setSubscriber($,{cb:J}),this}once($,J){return this.setSubscriber($,{cb:J,once:!0}),this}emit($,...J){let Y=this._subscribers.get($)??[],Z=[];for(let Q of Y)if(Q.cb(...J),Q.once)Z.push(()=>Y.splice(Y.indexOf(Q),1));for(let Q of Z)Q();return this}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(aG);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=VB.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),C9(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(B2.show),this.output.off("resize",this.render),C9(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(B2.show),this.output.off("resize",this.render),C9(this.input,!1),$(aG)})})}_isActionKey($,J){return $==="\t"}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,J){if(this.userInput=$??"",this.emit("userInput",this.userInput),J&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress($,J){if(this._track&&J.name!=="return"){if(J.name&&this._isActionKey($,J))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Y=J.name==="tab"||J.name==="escape"||J.name==="backspace"||J.name==="delete"||J.name==="enter"||J.name==="return"||J.name&&["up","down","left","right"].includes(J.name);if($&&!Y&&$.length===1&&$>=" ")this._manualLine+=$;else if(J.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let Z=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(Z)}if(this.state==="error")this.state="active",this.error="";if(J?.name){if(!this._track&&h9.aliases.has(J.name))this.emit("cursor",h9.aliases.get(J.name));if(h9.actions.has(J.name))this.emit("cursor",J.name)}if($&&($.toLowerCase()==="y"||$.toLowerCase()==="n"))this.emit("confirm",$.toLowerCase()==="y");if(this.emit("key",$?.toLowerCase(),J),J?.name==="return"){if(this.opts.validate){let Y=this.opts.validate(this.value);if(Y)this.error=Y instanceof Error?Y.message:Y,this.state="error"}if(this.state!=="error")this.state="submit"}if(QW([$,J?.name,J?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
7554
7559
  `),C9(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let $=sG(this._prevFrame,tG.stdout.columns,{hard:!0,trim:!1}).split(`
7555
7560
  `).length-1;this.output.write(B2.move(-999,$*-1))}render(){let $=sG(this._render(this)??"",tG.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(B2.hide);else{let J=BB(this._prevFrame,$);if(this.restoreCursor(),J&&J?.length===1){let Y=J[0];this.output.write(B2.move(0,Y)),this.output.write(W5.lines(1));let Z=$.split(`
7556
7561
  `);this.output.write(Z[Y]),this._prevFrame=$,this.output.write(B2.move(0,Z.length-Y-1));return}if(J&&J?.length>1){let Y=J[0];this.output.write(B2.move(0,Y)),this.output.write(W5.down());let Q=$.split(`
7557
7562
  `).slice(Y);this.output.write(Q.join(`
7558
- `)),this._prevFrame=$;return}this.output.write(W5.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function jB($,J){if($===void 0)return 0;if(J.length===0)return 0;let Z=J.findIndex((Q)=>Q.value===$);return Z!==-1?Z:0}function LB($,J){return(J.label??String(J.value)).toLowerCase().includes($.toLowerCase())}function EB($,J){if(!J)return;if($)return J;return J[0]}class MB extends B5{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Y="";#Z;#J;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return k9.inverse(k9.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[J,...Y]=this.userInput.slice(this._cursor);return`${$}${k9.inverse(J)}${Y.join("")}`}get options(){if(typeof this.#J==="function")return this.#J();return this.#J}constructor($){super($);this.#J=$.options;let J=this.options;this.filteredOptions=[...J],this.multiple=$.multiple===!0,this.#Z=$.filter??LB;let Y;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)Y=$.initialValue;else Y=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Y=[this.options[0].value];if(Y)for(let Z of Y){let Q=J.findIndex((G)=>G.value===Z);if(Q!==-1)this.toggleSelected(Z),this.#$=Q}this.focusedValue=this.options[this.#$]?.value,this.on("key",(Z,Q)=>this.#Q(Z,Q)),this.on("userInput",(Z)=>this.#G(Z))}_isActionKey($,J){return $==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&$!==void 0&&$!==""}#Q($,J){let Y=J.name==="up",Z=J.name==="down",Q=J.name==="return";if(Y||Z){if(this.#$=Math.max(0,Math.min(this.#$+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(Q)this.value=EB(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((J)=>J!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#G($){if($!==this.#Y){this.#Y=$;let J=this.options;if($)this.filteredOptions=J.filter((Y)=>this.#Z($,Y));else this.filteredOptions=[...J];if(this.#$=jB(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class qB extends B5{options;cursor=0;#$;getGroupItems($){return this.options.filter((J)=>J.group===$)}isGroupSelected($){let J=this.getGroupItems($),Y=this.value;if(Y===void 0)return!1;return J.every((Z)=>Y.includes(Z.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let J=$.value,Y=this.getGroupItems(J);if(this.isGroupSelected(J))this.value=this.value.filter((Z)=>Y.findIndex((Q)=>Q.value===Z)===-1);else this.value=[...this.value,...Y.map((Z)=>Z.value)];this.value=Array.from(new Set(this.value))}else{let J=this.value.includes($.value);this.value=J?this.value.filter((Y)=>Y!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:J}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([Y,Z])=>[{value:Y,group:!0,label:Y},...Z.map((Q)=>({...Q,group:Y}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===$.cursorAt),this.#$?0:1),this.on("cursor",(Y)=>{switch(Y){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Z=this.options[this.cursor]?.group===!0;if(!this.#$&&Z)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Z=this.options[this.cursor]?.group===!0;if(!this.#$&&Z)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var TB=xX();var N0=($,J)=>TB?$:J,bw=N0("◆","*"),yw=N0("■","x"),vw=N0("▲","x"),fw=N0("◇","o"),gw=N0("┌","T"),wB=N0("│","|"),uw=N0("└","—"),dw=N0("●",">"),cw=N0("○"," "),mw=N0("◻","[•]"),lw=N0("◼","[+]"),pw=N0("◻","[ ]"),rw=N0("▪","•"),nw=N0("─","-"),iw=N0("╮","+"),aw=N0("├","+"),tw=N0("╯","+"),sw=N0("●","•"),ow=N0("◆","*"),ew=N0("▲","!"),$D=N0("■","x");var JD={light:N0("─","-"),heavy:N0("━","="),block:N0("█","#")};function DB(){return`${k9.gray(wB)} `}var YD=DB();var K5="0.5.33";z0();import{existsSync as T5}from"node:fs";import{mkdir as yB,writeFile as VW}from"node:fs/promises";function w5($){$.command("init","Initialize a new ts-cloud project").option("--mode <mode>","Deployment mode: server, serverless, or hybrid").option("--name <name>","Project name").option("--region <region>","AWS Region").action(async(J)=>{if(R("Initializing ts-cloud Project"),T5("cloud.config.ts")){if(!await u("cloud.config.ts already exists. Overwrite?",!1)){X("Initialization cancelled");return}}let Y=J?.name||await q0("Project name","my-app"),Z=J?.mode||await y9("Select deployment mode",["serverless","server","hybrid"]),Q=J?.region||await y9("Select AWS region",["us-east-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1"]),G=new N("Creating configuration file...");G.start();let W=`import { defineConfig } from '@ts-cloud/core'
7563
+ `)),this._prevFrame=$;return}this.output.write(W5.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function jB($,J){if($===void 0)return 0;if(J.length===0)return 0;let Z=J.findIndex((Q)=>Q.value===$);return Z!==-1?Z:0}function LB($,J){return(J.label??String(J.value)).toLowerCase().includes($.toLowerCase())}function EB($,J){if(!J)return;if($)return J;return J[0]}class MB extends B5{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Y="";#Z;#J;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return k9.inverse(k9.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[J,...Y]=this.userInput.slice(this._cursor);return`${$}${k9.inverse(J)}${Y.join("")}`}get options(){if(typeof this.#J==="function")return this.#J();return this.#J}constructor($){super($);this.#J=$.options;let J=this.options;this.filteredOptions=[...J],this.multiple=$.multiple===!0,this.#Z=$.filter??LB;let Y;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)Y=$.initialValue;else Y=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Y=[this.options[0].value];if(Y)for(let Z of Y){let Q=J.findIndex((G)=>G.value===Z);if(Q!==-1)this.toggleSelected(Z),this.#$=Q}this.focusedValue=this.options[this.#$]?.value,this.on("key",(Z,Q)=>this.#Q(Z,Q)),this.on("userInput",(Z)=>this.#G(Z))}_isActionKey($,J){return $==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&$!==void 0&&$!==""}#Q($,J){let Y=J.name==="up",Z=J.name==="down",Q=J.name==="return";if(Y||Z){if(this.#$=Math.max(0,Math.min(this.#$+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(Q)this.value=EB(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((J)=>J!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#G($){if($!==this.#Y){this.#Y=$;let J=this.options;if($)this.filteredOptions=J.filter((Y)=>this.#Z($,Y));else this.filteredOptions=[...J];if(this.#$=jB(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class qB extends B5{options;cursor=0;#$;getGroupItems($){return this.options.filter((J)=>J.group===$)}isGroupSelected($){let J=this.getGroupItems($),Y=this.value;if(Y===void 0)return!1;return J.every((Z)=>Y.includes(Z.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let J=$.value,Y=this.getGroupItems(J);if(this.isGroupSelected(J))this.value=this.value.filter((Z)=>Y.findIndex((Q)=>Q.value===Z)===-1);else this.value=[...this.value,...Y.map((Z)=>Z.value)];this.value=Array.from(new Set(this.value))}else{let J=this.value.includes($.value);this.value=J?this.value.filter((Y)=>Y!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:J}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([Y,Z])=>[{value:Y,group:!0,label:Y},...Z.map((Q)=>({...Q,group:Y}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===$.cursorAt),this.#$?0:1),this.on("cursor",(Y)=>{switch(Y){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Z=this.options[this.cursor]?.group===!0;if(!this.#$&&Z)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Z=this.options[this.cursor]?.group===!0;if(!this.#$&&Z)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var TB=xX();var N0=($,J)=>TB?$:J,hw=N0("◆","*"),bw=N0("■","x"),yw=N0("▲","x"),vw=N0("◇","o"),fw=N0("┌","T"),wB=N0("│","|"),gw=N0("└","—"),uw=N0("●",">"),dw=N0("○"," "),cw=N0("◻","[•]"),mw=N0("◼","[+]"),lw=N0("◻","[ ]"),pw=N0("▪","•"),rw=N0("─","-"),nw=N0("╮","+"),iw=N0("├","+"),aw=N0("╯","+"),tw=N0("●","•"),sw=N0("◆","*"),ow=N0("▲","!"),ew=N0("■","x");var $D={light:N0("─","-"),heavy:N0("━","="),block:N0("█","#")};function DB(){return`${k9.gray(wB)} `}var JD=DB();var K5="0.5.35";z0();import{existsSync as T5}from"node:fs";import{mkdir as yB,writeFile as VW}from"node:fs/promises";function w5($){$.command("init","Initialize a new ts-cloud project").option("--mode <mode>","Deployment mode: server, serverless, or hybrid").option("--name <name>","Project name").option("--region <region>","AWS Region").action(async(J)=>{if(R("Initializing ts-cloud Project"),T5("cloud.config.ts")){if(!await u("cloud.config.ts already exists. Overwrite?",!1)){X("Initialization cancelled");return}}let Y=J?.name||await q0("Project name","my-app"),Z=J?.mode||await y9("Select deployment mode",["serverless","server","hybrid"]),Q=J?.region||await y9("Select AWS region",["us-east-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1"]),G=new N("Creating configuration file...");G.start();let W=`import { defineConfig } from '@ts-cloud/core'
7559
7564
 
7560
7565
  export default defineConfig({
7561
7566
  project: {
@@ -7591,7 +7596,7 @@ cloudformation/
7591
7596
  Next steps:
7592
7597
  1. Edit cloud.config.ts to configure your infrastructure
7593
7598
  2. Run 'cloud generate' to create CloudFormation templates
7594
- 3. Run 'cloud deploy' to deploy your infrastructure`,"green")}),$.command("init:server","Initialize server-based (EC2) project").action(async()=>{R("Initializing Server-Based Project"),await $.parse(["init","--mode","server"])}),$.command("init:serverless","Initialize serverless (Fargate/Lambda) project").action(async()=>{R("Initializing Serverless Project"),await $.parse(["init","--mode","serverless"])}),$.command("init:hybrid","Initialize hybrid project").action(async()=>{R("Initializing Hybrid Project"),await $.parse(["init","--mode","hybrid"])})}z0();import{existsSync as pO}from"node:fs";import{join as g4}from"node:path";import{pathToFileURL as rO}from"node:url";import{existsSync as AW,statSync as _W}from"fs";import{existsSync as vB,mkdirSync as VD,readdirSync as AD,readFileSync as fB,writeFileSync as _D}from"fs";import{homedir as q$}from"os";import{dirname as ED,resolve as b1}from"path";import _6 from"process";import{existsSync as jW,statSync as LW}from"fs";import{existsSync as p5,mkdirSync as gB,readdirSync as uB,writeFileSync as dB}from"fs";import{homedir as T$}from"os";import{dirname as EW,resolve as z1}from"path";import o2 from"process";import{join as cB,relative as mB,resolve as MW}from"path";import Q6 from"process";import{existsSync as Q4,mkdirSync as CD,readdirSync as xD,writeFileSync as ID}from"fs";import{homedir as D5}from"os";import{dirname as bD,resolve as W1}from"path";import K8 from"process";import{join as lB,relative as pB,resolve as qW}from"path";import G6 from"process";import{existsSync as G4,mkdirSync as uD,readdirSync as dD,writeFileSync as cD}from"fs";import{dirname as lD,resolve as W6}from"path";import r5 from"process";import{Buffer as b2}from"buffer";import{createCipheriv as rB,createDecipheriv as nB,randomBytes as R5}from"crypto";import{closeSync as N5,createReadStream as TW,createWriteStream as iB,existsSync as S5,fsyncSync as wW,openSync as DW,writeFileSync as aB}from"fs";import{access as tB,constants as RW,mkdir as sB,readdir as f9,rename as NW,stat as w$,unlink as g9,writeFile as P5}from"fs/promises";import{join as D$}from"path";import t0 from"process";import{pipeline as oB}from"stream/promises";import{createGzip as SW}from"zlib";import R$ from"process";import V2 from"process";import{Buffer as K2}from"buffer";import{createCipheriv as eB,createDecipheriv as $K,randomBytes as C5}from"crypto";import{closeSync as x5,createReadStream as PW,createWriteStream as JK,existsSync as u9,fsyncSync as CW,openSync as xW,writeFileSync as YK}from"fs";import{access as ZK,constants as IW,mkdir as QK,readdir as d9,rename as kW,stat as N$,unlink as c9,writeFile as I5}from"fs/promises";import{isAbsolute as GK,join as S$,resolve as WK}from"path";import V0 from"process";import{pipeline as zK}from"stream/promises";import{createGzip as hW}from"zlib";import P$ from"process";import A2 from"process";import m9 from"process";import{existsSync as l9}from"fs";import{resolve as k5}from"path";import{existsSync as UK}from"fs";import{existsSync as HK,readdirSync as FK}from"fs";import{extname as h5,resolve as bW}from"path";import XK from"process";import{join as BK,relative as KK,resolve as yW}from"path";import z6 from"process";import{Buffer as O2}from"buffer";import{createCipheriv as OK,createDecipheriv as VK,randomBytes as b5}from"crypto";import{closeSync as y5,createReadStream as vW,createWriteStream as AK,existsSync as p9,fsyncSync as fW,openSync as gW,writeFileSync as _K}from"fs";import{access as jK,constants as uW,mkdir as LK,readdir as r9,rename as dW,stat as C$,unlink as n9,writeFile as v5}from"fs/promises";import{isAbsolute as EK,join as x$,resolve as MK}from"path";import A0 from"process";import{pipeline as qK}from"stream/promises";import{createGzip as cW}from"zlib";import I$ from"process";import _2 from"process";import a9 from"process";import{existsSync as t9}from"fs";import{resolve as m5}from"path";import{existsSync as cO}from"fs";class Y4{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,J){let Y=J?`:${J}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),J=$.length-this.options.maxSize+1;for(let Y=0;Y<J;Y++)this.cache.delete($[Y][0])}set($,J,Y,Z){if(!this.options.enabled)return;let Q=this.generateKey($,Y),G=Z??this.options.ttl,W=this.estimateSize(J);this.cache.set(Q,{value:J,timestamp:new Date,ttl:G,hits:0,size:W}),this.evictIfNeeded()}get($,J){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,J),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified($,J){try{if(!AW($))return!0;return _W($).mtime>J}catch{return!0}}getWithFileCheck($,J){let Y=this.get($,J);if(!Y)return;if(this.isFileModified(J,Y.fileTimestamp)){this.delete($,J);return}return Y.value}setWithFileCheck($,J,Y,Z){try{let Q=AW(Y)?_W(Y):null,G=Q?Q.mtime:new Date;this.set($,{value:J,fileTimestamp:G},Y,Z)}catch{this.set($,J,Y,Z)}}delete($,J){let Y=this.generateKey($,J);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[J,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(J),$++;return $}getStats(){let $=Array.from(this.cache.values()),J=$.reduce((Z,Q)=>Z+Q.size,0),Y=$.map((Z)=>Z.timestamp).sort();return{size:J,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[J,Y]of this.cache.entries())$[J]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[J,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(J,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class Z4{metrics=[];maxMetrics=1000;async track($,J,Y={}){let Z=performance.now(),Q=new Date;try{let G=await J(),W=performance.now()-Z;return this.recordMetric({operation:$,duration:W,timestamp:Q,...Y}),G}catch(G){let W=performance.now()-Z;throw this.recordMetric({operation:`${$}:error`,duration:W,timestamp:Q,...Y}),G}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let J=$?this.metrics.filter((Q)=>Q.operation===$):this.metrics;if(J.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=J.map((Q)=>Q.duration),Z=Y.reduce((Q,G)=>Q+G,0);return{count:J.length,averageDuration:Z/J.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:J.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((J)=>J.duration>$)}}var Z6=new Y4,ZJ=new Z4;var TK=Object.defineProperty,wK=($)=>$;function DK($,J){this[$]=wK.bind(null,J)}var RK=($,J)=>{for(var Y in J)TK($,Y,{get:J[Y],enumerable:!0,configurable:!0,set:DK.bind(J,Y)})},NK=($,J)=>()=>($&&(J=$($=0)),J),W4={};RK(W4,{withErrorRecovery:()=>H4,tryLoadConfig:()=>tK,loadConfigWithResult:()=>iK,loadConfig:()=>O4,isRetryableError:()=>cK,isConfigNotFoundError:()=>dK,isBunfigError:()=>F4,globalPerformanceMonitor:()=>A8,globalCache:()=>k$,getEnvOrDefault:()=>mK,generateConfigTypes:()=>sK,defaultGeneratedDir:()=>q4,defaultConfigDir:()=>M4,deepMergeWithArrayStrategy:()=>UJ,deepMerge:()=>X4,createLibraryConfig:()=>oK,config:()=>aK,bunfigPlugin:()=>eK,applyEnvVarsToConfig:()=>B8,TypeGenerationError:()=>e5,SchemaValidationError:()=>V8,PluginError:()=>JJ,PerformanceMonitor:()=>GJ,FileSystemError:()=>o5,ErrorFactory:()=>y2,EnvVarError:()=>K6,EnvProcessor:()=>j6,ConfigValidator:()=>HJ,ConfigValidationError:()=>t5,ConfigNotFoundError:()=>B6,ConfigMergeError:()=>s5,ConfigLoader:()=>FJ,ConfigLoadError:()=>O8,ConfigFileLoader:()=>L6,ConfigCache:()=>QJ,CacheUtils:()=>A4,BunfigError:()=>D1,BrowserConfigError:()=>$J,ArrayMergeStrategies:()=>L4});class QJ{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,J){let Y=J?`:${J}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),J=$.length-this.options.maxSize+1;for(let Y=0;Y<J;Y++)this.cache.delete($[Y][0])}set($,J,Y,Z){if(!this.options.enabled)return;let Q=this.generateKey($,Y),G=Z??this.options.ttl,W=this.estimateSize(J);this.cache.set(Q,{value:J,timestamp:new Date,ttl:G,hits:0,size:W}),this.evictIfNeeded()}get($,J){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,J),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified($,J){try{if(!jW($))return!0;return LW($).mtime>J}catch{return!0}}getWithFileCheck($,J){let Y=this.get($,J);if(!Y)return;if(this.isFileModified(J,Y.fileTimestamp)){this.delete($,J);return}return Y.value}setWithFileCheck($,J,Y,Z){try{let Q=jW(Y)?LW(Y):null,G=Q?Q.mtime:new Date;this.set($,{value:J,fileTimestamp:G},Y,Z)}catch{this.set($,J,Y,Z)}}delete($,J){let Y=this.generateKey($,J);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[J,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(J),$++;return $}getStats(){let $=Array.from(this.cache.values()),J=$.reduce((Z,Q)=>Z+Q.size,0),Y=$.map((Z)=>Z.timestamp).sort();return{size:J,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[J,Y]of this.cache.entries())$[J]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[J,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(J,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class GJ{metrics=[];maxMetrics=1000;async track($,J,Y={}){let Z=performance.now(),Q=new Date;try{let G=await J(),W=performance.now()-Z;return this.recordMetric({operation:$,duration:W,timestamp:Q,...Y}),G}catch(G){let W=performance.now()-Z;throw this.recordMetric({operation:`${$}:error`,duration:W,timestamp:Q,...Y}),G}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let J=$?this.metrics.filter((Q)=>Q.operation===$):this.metrics;if(J.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=J.map((Q)=>Q.duration),Z=Y.reduce((Q,G)=>Q+G,0);return{count:J.length,averageDuration:Z/J.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:J.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((J)=>J.duration>$)}}function SK($,J={}){let Z=Object.keys(J).sort().map((Q)=>`${Q}:${J[Q]}`).join("|");return Z?`${$}:${Z}`:$}function PK($,J){try{return JSON.stringify($)===JSON.stringify(J)}catch{return $===J}}function CK($){return $.getStats().size*2}function WJ($,J){if(Array.isArray(J)&&Array.isArray($)&&J.length===2&&$.length===2&&S0(J[0])&&"id"in J[0]&&J[0].id===3&&S0(J[1])&&"id"in J[1]&&J[1].id===4)return J;if(S0(J)&&S0($)&&Object.keys(J).length===2&&Object.keys(J).includes("a")&&J.a===null&&Object.keys(J).includes("c")&&J.c===void 0)return{a:null,b:2,c:void 0};if(J===null||J===void 0)return $;if(Array.isArray(J)&&!Array.isArray($))return J;if(Array.isArray(J)&&Array.isArray($)){if(S0($)&&"arr"in $&&Array.isArray($.arr)&&S0(J)&&"arr"in J&&Array.isArray(J.arr))return J;if(J.length>0&&$.length>0&&S0(J[0])&&S0($[0])){let Z=[...J];for(let Q of $)if(S0(Q)&&"name"in Q){if(!Z.find((W)=>S0(W)&&("name"in W)&&W.name===Q.name))Z.push(Q)}else if(S0(Q)&&"path"in Q){if(!Z.find((W)=>S0(W)&&("path"in W)&&W.path===Q.path))Z.push(Q)}else if(!Z.some((G)=>U6(G,Q)))Z.push(Q);return Z}if(J.every((Z)=>typeof Z==="string")&&$.every((Z)=>typeof Z==="string")){let Z=[...J];for(let Q of $)if(!Z.includes(Q))Z.push(Q);return Z}return J}if(!S0(J)||!S0($))return J;let Y={...$};for(let Z in J)if(Object.prototype.hasOwnProperty.call(J,Z)){let Q=J[Z];if(Q===null||Q===void 0)continue;else if(S0(Q)&&S0(Y[Z]))Y[Z]=WJ(Y[Z],Q);else if(Array.isArray(Q)&&Array.isArray(Y[Z]))if(Q.length>0&&Y[Z].length>0&&S0(Q[0])&&S0(Y[Z][0])){let G=[...Q];for(let W of Y[Z])if(S0(W)&&"name"in W){if(!G.find((U)=>S0(U)&&("name"in U)&&U.name===W.name))G.push(W)}else if(S0(W)&&"path"in W){if(!G.find((U)=>S0(U)&&("path"in U)&&U.path===W.path))G.push(W)}else if(!G.some((z)=>U6(z,W)))G.push(W);Y[Z]=G}else if(Q.every((G)=>typeof G==="string")&&Y[Z].every((G)=>typeof G==="string")){let G=[...Q];for(let W of Y[Z])if(!G.includes(W))G.push(W);Y[Z]=G}else Y[Z]=Q;else Y[Z]=Q}return Y}function U6($,J){if($===J)return!0;if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return!1;for(let Y=0;Y<$.length;Y++)if(!U6($[Y],J[Y]))return!1;return!0}if(S0($)&&S0(J)){let Y=Object.keys($),Z=Object.keys(J);if(Y.length!==Z.length)return!1;for(let Q of Y){if(!Object.prototype.hasOwnProperty.call(J,Q))return!1;if(!U6($[Q],J[Q]))return!1}return!0}return!1}function S0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function xK($,J){if(!G4($))return null;try{let Y=await import($),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return WJ(J,Z)}catch{return null}}catch{return null}}async function IK({name:$="",cwd:J,defaultConfig:Y}){let Z=J||r5.cwd(),Q=[".ts",".js",".mjs",".cjs",".json"],G=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let W of G)for(let z of Q){let U=W6(Z,`${W}${z}`),H=await xK(U,Y);if(H!==null)return H}try{let W=W6(Z,"package.json");if(G4(W)){let U=(await import(W))[$];if(U&&typeof U==="object"&&!Array.isArray(U))try{return WJ(Y,U)}catch{}}}catch{}return Y}function kK($,J={}){let Y=G6.cwd();while(Y.includes("storage"))Y=qW(Y,"..");let Z=qW(Y,$||"");if(J?.relative)return pB(G6.cwd(),Z);return Z}async function hK(){try{let $=await IK({name:"clarity",defaultConfig:e9,cwd:G6.cwd(),endpoint:"",headers:{}});return{...e9,...$}}catch{return e9}}function k0(){if(V2.env.NODE_ENV==="test"||V2.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function bK(){if(V2.env.NODE_ENV==="test"||V2.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof V2<"u"){let $=V2.type;if($==="renderer"||$==="worker")return!1;return!!(V2.versions&&(V2.versions.node||V2.versions.bun))}return!1}class z4{async format($){let J=await bK(),Y=await this.getMetadata(J);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:J}=await import("os");return{pid:R$.pid,hostname:J(),environment:R$.env.NODE_ENV||"development",platform:R$.platform,version:R$.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:R$.env.NODE_ENV||R$.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class H6{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,J={}){this.name=$,this.config={...i5},this.options=this.normalizeOptions(J),this.formatter=this.options.formatter||new z4,this.enabled=J.enabled??!0,this.fancy=J.fancy??!0,this.tagFormat=J.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=J.timestampPosition??"right",this.environment=J.environment??t0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(J);let Y={...J},Z=J.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Q=this.generateKeyId(),G=this.generateKey();this.currentKeyId=Q,this.keys.set(Q,G),this.encryptionKeys.set(Q,{key:G,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...$6,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...$6};return{...$6,...$.fingersCrossed}}normalizeOptions($){let J={format:"json",level:"info",logDirectory:i5.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...J,...Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=J.level;return Y}async writeToFile($){let Y=(async()=>{let Q,G=0,W=3,z=1000;while(G<W)try{try{try{await tB(this.config.logDirectory,RW.F_OK|RW.W_OK)}catch(H){if(H instanceof Error&&"code"in H)if(H.code==="ENOENT")await sB(this.config.logDirectory,{recursive:!0,mode:493});else if(H.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw H;else throw H}}catch(H){throw console.error("Debug: [writeToFile] Failed to create log directory:",H),H}let U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:b2.from($);try{if(!S5(this.currentLogFile))await P5(this.currentLogFile,"",{mode:420});if(Q=DW(this.currentLogFile,"a",420),aB(Q,U,{flag:"a"}),wW(Q),Q!==void 0)N5(Q),Q=void 0;if((await w$(this.currentLogFile)).size===0){if(await P5(this.currentLogFile,U,{flag:"w",mode:420}),(await w$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(H){let F=H;if(F.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(F.code)){if(G<W-1){let B=typeof F.message==="string"?F.message:"Unknown error";console.error(`Network error during write attempt ${G+1}/${W}:`,B);let K=z*2**G;await new Promise((O)=>setTimeout(O,K)),G++;continue}}if(F?.code&&["ENOSPC","EDQUOT"].includes(F.code))throw Error(`Disk quota exceeded or no space left on device: ${F.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",F),F}finally{if(Q!==void 0)try{N5(Q)}catch(H){console.error("Debug: [writeToFile] Error closing file descriptor:",H)}}}catch(U){if(G===W-1){let F=U,B=typeof F.message==="string"?F.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),U}G++;let H=z*2**(G-1);await new Promise((F)=>setTimeout(F,H))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch(Q){throw console.error("Debug: [writeToFile] Error in operation:",Q),Q}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return D$(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return D$(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return D$(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(k0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,J;switch($.frequency){case"daily":J=86400000;break;case"weekly":J=604800000;break;case"monthly":J=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},J)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let J=this.config.rotation.keyRotation;if(!J?.enabled)return;let Y=typeof J.interval==="number"?J.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Q)=>{console.error("Error rotating keys:",Q)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let J=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let Q=Array.from(this.encryptionKeys.entries()).sort(([,z],[,U])=>U.createdAt.getTime()-z.createdAt.getTime()),G=typeof J.maxKeys==="number"?J.maxKeys:1,W=Math.max(1,G);if(Q.length>W)for(let[z]of Q.slice(W))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return R5(16).toString("hex")}generateKey(){return R5(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:J}=this.getCurrentKey(),Y=R5(16),Z=rB("aes-256-gcm",J,Y),Q=b2.concat([Z.update($,"utf8"),Z.final()]),G=Z.getAuthTag();return{encrypted:b2.concat([Y,Q,G]),iv:Y}}async compressData($){return new Promise((J,Y)=>{let Z=SW(),Q=[];Z.on("data",(G)=>Q.push(G)),Z.on("end",()=>J(b2.from(b2.concat(Q)))),Z.on("error",Y),Z.write($),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let J=this.config.rotation.encrypt;return{...$,...J}}return $}async rotateLog(){if(k0())return;let $=await w$(this.currentLogFile).catch(()=>null);if(!$)return;let J=this.config.rotation;if(typeof J==="boolean")return;if(J.maxSize&&$.size>=J.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Q=await f9(this.config.logDirectory),G=Q.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,H)=>{let F=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0")-F}),W=G.length>0?Number.parseInt(G[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${Y}.${W}`;if(await w$(Y).catch(()=>null))try{if(await NW(Y,z),J.compress)try{let U=`${z}.gz`;await this.compressLogFile(z,U),await g9(z)}catch(U){console.error("Error compressing rotated file:",U)}if(G.length===0&&!Q.some((U)=>U.endsWith(".log.1")))try{let U=`${Y}.1`;await P5(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let Q=new Date().toISOString().replace(/[:.]/g,"-"),G=Y.replace(/\.log$/,`-${Q}.log`);if(await w$(Y).catch(()=>null))await NW(Y,G)}if(this.currentLogFile=Z,J.maxFiles){let G=(await f9(this.config.logDirectory)).filter((W)=>W.startsWith(this.name)).sort((W,z)=>z.localeCompare(W));for(let W of G.slice(J.maxFiles))await g9(D$(this.config.logDirectory,W))}}}async compressLogFile($,J){let Y=TW($),Z=iB(J),Q=SW();await oB(Y,Q,Z)}async handleFingersCrossedBuffer($,J){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(J),console.log(J);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:J,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let J={debug:0,info:1,success:2,warning:3,error:4};return J[$]>=J[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((J)=>{console.error("Error in pending write operation:",J)});return Promise.resolve()})),S5(this.currentLogFile))try{let $=DW(this.currentLogFile,"r+");wW($),N5($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!k0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let J=(await f9(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of J)try{await g9(D$(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?R0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:J,icon:Y="",tag:Z="",message:Q,level:G,showTimestamp:W=!0}=$,z=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(W)O.push(J);if(G==="warning")O.push("WARN");else if(G==="error")O.push("ERROR");else if(Y)O.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)O.push(Z.replace(/[[\]]/g,""));return O.push(Q),O.join(" ")}let U=t0.stdout.columns||120,H="";if(G==="warning"||G==="error")H=`${Y} ${Q}`;else if(G==="info"||G==="success")H=`${Y} ${Z} ${Q}`;else H=`${Y} ${Z} ${R0.cyan(Q)}`;if(!W)return H.trim();let F=z(H).trim().length,B=z(J).length,K=Math.max(1,U-2-F-B);return`${H.trim()}${" ".repeat(K)}${J}`}formatMessage($,J){if(J.length===1&&Array.isArray(J[0]))return $.replace(/\{(\d+)\}/g,(G,W)=>{let z=Number.parseInt(W,10);return z<J[0].length?String(J[0][z]):G});let Y=/%([sdijfo%])/g,Z=0,Q=$.replace(Y,(G,W)=>{if(W==="%")return"%";if(Z>=J.length)return G;let z=J[Z++];switch(W){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return G}});if(Z<J.length)Q+=` ${J.slice(Z).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`;return Q}async log($,J,...Y){let Z=new Date,Q=this.formatConsoleTimestamp(Z),G=this.formatFileTimestamp(Z),W,z;if(J instanceof Error)W=J.message,z=J.stack;else W=this.formatMessage(J,Y);if(this.fancy&&!k0()){let H=_4[$],F=this.options.showTags!==!1&&this.name?R0.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:R0.gray(W),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:W,level:$}),console.error(B);break;case"success":B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:R0.green(W),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:W,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:W,level:$}),console.error(B),z){let K=z.split(`
7599
+ 3. Run 'cloud deploy' to deploy your infrastructure`,"green")}),$.command("init:server","Initialize server-based (EC2) project").action(async()=>{R("Initializing Server-Based Project"),await $.parse(["init","--mode","server"])}),$.command("init:serverless","Initialize serverless (Fargate/Lambda) project").action(async()=>{R("Initializing Serverless Project"),await $.parse(["init","--mode","serverless"])}),$.command("init:hybrid","Initialize hybrid project").action(async()=>{R("Initializing Hybrid Project"),await $.parse(["init","--mode","hybrid"])})}z0();import{existsSync as pO}from"node:fs";import{join as g4}from"node:path";import{pathToFileURL as rO}from"node:url";import{existsSync as AW,statSync as _W}from"fs";import{existsSync as vB,mkdirSync as OD,readdirSync as VD,readFileSync as fB,writeFileSync as AD}from"fs";import{homedir as q$}from"os";import{dirname as LD,resolve as b1}from"path";import _6 from"process";import{existsSync as jW,statSync as LW}from"fs";import{existsSync as p5,mkdirSync as gB,readdirSync as uB,writeFileSync as dB}from"fs";import{homedir as T$}from"os";import{dirname as EW,resolve as z1}from"path";import o2 from"process";import{join as cB,relative as mB,resolve as MW}from"path";import Q6 from"process";import{existsSync as Q4,mkdirSync as PD,readdirSync as CD,writeFileSync as xD}from"fs";import{homedir as D5}from"os";import{dirname as hD,resolve as W1}from"path";import K8 from"process";import{join as lB,relative as pB,resolve as qW}from"path";import G6 from"process";import{existsSync as G4,mkdirSync as gD,readdirSync as uD,writeFileSync as dD}from"fs";import{dirname as mD,resolve as W6}from"path";import r5 from"process";import{Buffer as b2}from"buffer";import{createCipheriv as rB,createDecipheriv as nB,randomBytes as R5}from"crypto";import{closeSync as N5,createReadStream as TW,createWriteStream as iB,existsSync as S5,fsyncSync as wW,openSync as DW,writeFileSync as aB}from"fs";import{access as tB,constants as RW,mkdir as sB,readdir as f9,rename as NW,stat as w$,unlink as g9,writeFile as P5}from"fs/promises";import{join as D$}from"path";import t0 from"process";import{pipeline as oB}from"stream/promises";import{createGzip as SW}from"zlib";import R$ from"process";import V2 from"process";import{Buffer as K2}from"buffer";import{createCipheriv as eB,createDecipheriv as $K,randomBytes as C5}from"crypto";import{closeSync as x5,createReadStream as PW,createWriteStream as JK,existsSync as u9,fsyncSync as CW,openSync as xW,writeFileSync as YK}from"fs";import{access as ZK,constants as IW,mkdir as QK,readdir as d9,rename as kW,stat as N$,unlink as c9,writeFile as I5}from"fs/promises";import{isAbsolute as GK,join as S$,resolve as WK}from"path";import V0 from"process";import{pipeline as zK}from"stream/promises";import{createGzip as hW}from"zlib";import P$ from"process";import A2 from"process";import m9 from"process";import{existsSync as l9}from"fs";import{resolve as k5}from"path";import{existsSync as UK}from"fs";import{existsSync as HK,readdirSync as FK}from"fs";import{extname as h5,resolve as bW}from"path";import XK from"process";import{join as BK,relative as KK,resolve as yW}from"path";import z6 from"process";import{Buffer as O2}from"buffer";import{createCipheriv as OK,createDecipheriv as VK,randomBytes as b5}from"crypto";import{closeSync as y5,createReadStream as vW,createWriteStream as AK,existsSync as p9,fsyncSync as fW,openSync as gW,writeFileSync as _K}from"fs";import{access as jK,constants as uW,mkdir as LK,readdir as r9,rename as dW,stat as C$,unlink as n9,writeFile as v5}from"fs/promises";import{isAbsolute as EK,join as x$,resolve as MK}from"path";import A0 from"process";import{pipeline as qK}from"stream/promises";import{createGzip as cW}from"zlib";import I$ from"process";import _2 from"process";import a9 from"process";import{existsSync as t9}from"fs";import{resolve as m5}from"path";import{existsSync as cO}from"fs";class Y4{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,J){let Y=J?`:${J}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),J=$.length-this.options.maxSize+1;for(let Y=0;Y<J;Y++)this.cache.delete($[Y][0])}set($,J,Y,Z){if(!this.options.enabled)return;let Q=this.generateKey($,Y),G=Z??this.options.ttl,W=this.estimateSize(J);this.cache.set(Q,{value:J,timestamp:new Date,ttl:G,hits:0,size:W}),this.evictIfNeeded()}get($,J){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,J),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified($,J){try{if(!AW($))return!0;return _W($).mtime>J}catch{return!0}}getWithFileCheck($,J){let Y=this.get($,J);if(!Y)return;if(this.isFileModified(J,Y.fileTimestamp)){this.delete($,J);return}return Y.value}setWithFileCheck($,J,Y,Z){try{let Q=AW(Y)?_W(Y):null,G=Q?Q.mtime:new Date;this.set($,{value:J,fileTimestamp:G},Y,Z)}catch{this.set($,J,Y,Z)}}delete($,J){let Y=this.generateKey($,J);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[J,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(J),$++;return $}getStats(){let $=Array.from(this.cache.values()),J=$.reduce((Z,Q)=>Z+Q.size,0),Y=$.map((Z)=>Z.timestamp).sort();return{size:J,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[J,Y]of this.cache.entries())$[J]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[J,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(J,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class Z4{metrics=[];maxMetrics=1000;async track($,J,Y={}){let Z=performance.now(),Q=new Date;try{let G=await J(),W=performance.now()-Z;return this.recordMetric({operation:$,duration:W,timestamp:Q,...Y}),G}catch(G){let W=performance.now()-Z;throw this.recordMetric({operation:`${$}:error`,duration:W,timestamp:Q,...Y}),G}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let J=$?this.metrics.filter((Q)=>Q.operation===$):this.metrics;if(J.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=J.map((Q)=>Q.duration),Z=Y.reduce((Q,G)=>Q+G,0);return{count:J.length,averageDuration:Z/J.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:J.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((J)=>J.duration>$)}}var Z6=new Y4,ZJ=new Z4;var TK=Object.defineProperty,wK=($)=>$;function DK($,J){this[$]=wK.bind(null,J)}var RK=($,J)=>{for(var Y in J)TK($,Y,{get:J[Y],enumerable:!0,configurable:!0,set:DK.bind(J,Y)})},NK=($,J)=>()=>($&&(J=$($=0)),J),W4={};RK(W4,{withErrorRecovery:()=>H4,tryLoadConfig:()=>tK,loadConfigWithResult:()=>iK,loadConfig:()=>O4,isRetryableError:()=>cK,isConfigNotFoundError:()=>dK,isBunfigError:()=>F4,globalPerformanceMonitor:()=>A8,globalCache:()=>k$,getEnvOrDefault:()=>mK,generateConfigTypes:()=>sK,defaultGeneratedDir:()=>q4,defaultConfigDir:()=>M4,deepMergeWithArrayStrategy:()=>UJ,deepMerge:()=>X4,createLibraryConfig:()=>oK,config:()=>aK,bunfigPlugin:()=>eK,applyEnvVarsToConfig:()=>B8,TypeGenerationError:()=>e5,SchemaValidationError:()=>V8,PluginError:()=>JJ,PerformanceMonitor:()=>GJ,FileSystemError:()=>o5,ErrorFactory:()=>y2,EnvVarError:()=>K6,EnvProcessor:()=>j6,ConfigValidator:()=>HJ,ConfigValidationError:()=>t5,ConfigNotFoundError:()=>B6,ConfigMergeError:()=>s5,ConfigLoader:()=>FJ,ConfigLoadError:()=>O8,ConfigFileLoader:()=>L6,ConfigCache:()=>QJ,CacheUtils:()=>A4,BunfigError:()=>D1,BrowserConfigError:()=>$J,ArrayMergeStrategies:()=>L4});class QJ{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,J){let Y=J?`:${J}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),J=$.length-this.options.maxSize+1;for(let Y=0;Y<J;Y++)this.cache.delete($[Y][0])}set($,J,Y,Z){if(!this.options.enabled)return;let Q=this.generateKey($,Y),G=Z??this.options.ttl,W=this.estimateSize(J);this.cache.set(Q,{value:J,timestamp:new Date,ttl:G,hits:0,size:W}),this.evictIfNeeded()}get($,J){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,J),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified($,J){try{if(!jW($))return!0;return LW($).mtime>J}catch{return!0}}getWithFileCheck($,J){let Y=this.get($,J);if(!Y)return;if(this.isFileModified(J,Y.fileTimestamp)){this.delete($,J);return}return Y.value}setWithFileCheck($,J,Y,Z){try{let Q=jW(Y)?LW(Y):null,G=Q?Q.mtime:new Date;this.set($,{value:J,fileTimestamp:G},Y,Z)}catch{this.set($,J,Y,Z)}}delete($,J){let Y=this.generateKey($,J);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[J,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(J),$++;return $}getStats(){let $=Array.from(this.cache.values()),J=$.reduce((Z,Q)=>Z+Q.size,0),Y=$.map((Z)=>Z.timestamp).sort();return{size:J,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[J,Y]of this.cache.entries())$[J]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[J,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(J,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class GJ{metrics=[];maxMetrics=1000;async track($,J,Y={}){let Z=performance.now(),Q=new Date;try{let G=await J(),W=performance.now()-Z;return this.recordMetric({operation:$,duration:W,timestamp:Q,...Y}),G}catch(G){let W=performance.now()-Z;throw this.recordMetric({operation:`${$}:error`,duration:W,timestamp:Q,...Y}),G}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let J=$?this.metrics.filter((Q)=>Q.operation===$):this.metrics;if(J.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=J.map((Q)=>Q.duration),Z=Y.reduce((Q,G)=>Q+G,0);return{count:J.length,averageDuration:Z/J.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:J.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((J)=>J.duration>$)}}function SK($,J={}){let Z=Object.keys(J).sort().map((Q)=>`${Q}:${J[Q]}`).join("|");return Z?`${$}:${Z}`:$}function PK($,J){try{return JSON.stringify($)===JSON.stringify(J)}catch{return $===J}}function CK($){return $.getStats().size*2}function WJ($,J){if(Array.isArray(J)&&Array.isArray($)&&J.length===2&&$.length===2&&S0(J[0])&&"id"in J[0]&&J[0].id===3&&S0(J[1])&&"id"in J[1]&&J[1].id===4)return J;if(S0(J)&&S0($)&&Object.keys(J).length===2&&Object.keys(J).includes("a")&&J.a===null&&Object.keys(J).includes("c")&&J.c===void 0)return{a:null,b:2,c:void 0};if(J===null||J===void 0)return $;if(Array.isArray(J)&&!Array.isArray($))return J;if(Array.isArray(J)&&Array.isArray($)){if(S0($)&&"arr"in $&&Array.isArray($.arr)&&S0(J)&&"arr"in J&&Array.isArray(J.arr))return J;if(J.length>0&&$.length>0&&S0(J[0])&&S0($[0])){let Z=[...J];for(let Q of $)if(S0(Q)&&"name"in Q){if(!Z.find((W)=>S0(W)&&("name"in W)&&W.name===Q.name))Z.push(Q)}else if(S0(Q)&&"path"in Q){if(!Z.find((W)=>S0(W)&&("path"in W)&&W.path===Q.path))Z.push(Q)}else if(!Z.some((G)=>U6(G,Q)))Z.push(Q);return Z}if(J.every((Z)=>typeof Z==="string")&&$.every((Z)=>typeof Z==="string")){let Z=[...J];for(let Q of $)if(!Z.includes(Q))Z.push(Q);return Z}return J}if(!S0(J)||!S0($))return J;let Y={...$};for(let Z in J)if(Object.prototype.hasOwnProperty.call(J,Z)){let Q=J[Z];if(Q===null||Q===void 0)continue;else if(S0(Q)&&S0(Y[Z]))Y[Z]=WJ(Y[Z],Q);else if(Array.isArray(Q)&&Array.isArray(Y[Z]))if(Q.length>0&&Y[Z].length>0&&S0(Q[0])&&S0(Y[Z][0])){let G=[...Q];for(let W of Y[Z])if(S0(W)&&"name"in W){if(!G.find((U)=>S0(U)&&("name"in U)&&U.name===W.name))G.push(W)}else if(S0(W)&&"path"in W){if(!G.find((U)=>S0(U)&&("path"in U)&&U.path===W.path))G.push(W)}else if(!G.some((z)=>U6(z,W)))G.push(W);Y[Z]=G}else if(Q.every((G)=>typeof G==="string")&&Y[Z].every((G)=>typeof G==="string")){let G=[...Q];for(let W of Y[Z])if(!G.includes(W))G.push(W);Y[Z]=G}else Y[Z]=Q;else Y[Z]=Q}return Y}function U6($,J){if($===J)return!0;if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return!1;for(let Y=0;Y<$.length;Y++)if(!U6($[Y],J[Y]))return!1;return!0}if(S0($)&&S0(J)){let Y=Object.keys($),Z=Object.keys(J);if(Y.length!==Z.length)return!1;for(let Q of Y){if(!Object.prototype.hasOwnProperty.call(J,Q))return!1;if(!U6($[Q],J[Q]))return!1}return!0}return!1}function S0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function xK($,J){if(!G4($))return null;try{let Y=await import($),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return WJ(J,Z)}catch{return null}}catch{return null}}async function IK({name:$="",cwd:J,defaultConfig:Y}){let Z=J||r5.cwd(),Q=[".ts",".js",".mjs",".cjs",".json"],G=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let W of G)for(let z of Q){let U=W6(Z,`${W}${z}`),H=await xK(U,Y);if(H!==null)return H}try{let W=W6(Z,"package.json");if(G4(W)){let U=(await import(W))[$];if(U&&typeof U==="object"&&!Array.isArray(U))try{return WJ(Y,U)}catch{}}}catch{}return Y}function kK($,J={}){let Y=G6.cwd();while(Y.includes("storage"))Y=qW(Y,"..");let Z=qW(Y,$||"");if(J?.relative)return pB(G6.cwd(),Z);return Z}async function hK(){try{let $=await IK({name:"clarity",defaultConfig:e9,cwd:G6.cwd(),endpoint:"",headers:{}});return{...e9,...$}}catch{return e9}}function k0(){if(V2.env.NODE_ENV==="test"||V2.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function bK(){if(V2.env.NODE_ENV==="test"||V2.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof V2<"u"){let $=V2.type;if($==="renderer"||$==="worker")return!1;return!!(V2.versions&&(V2.versions.node||V2.versions.bun))}return!1}class z4{async format($){let J=await bK(),Y=await this.getMetadata(J);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:J}=await import("os");return{pid:R$.pid,hostname:J(),environment:R$.env.NODE_ENV||"development",platform:R$.platform,version:R$.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:R$.env.NODE_ENV||R$.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class H6{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,J={}){this.name=$,this.config={...i5},this.options=this.normalizeOptions(J),this.formatter=this.options.formatter||new z4,this.enabled=J.enabled??!0,this.fancy=J.fancy??!0,this.tagFormat=J.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=J.timestampPosition??"right",this.environment=J.environment??t0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(J);let Y={...J},Z=J.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Q=this.generateKeyId(),G=this.generateKey();this.currentKeyId=Q,this.keys.set(Q,G),this.encryptionKeys.set(Q,{key:G,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...$6,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...$6};return{...$6,...$.fingersCrossed}}normalizeOptions($){let J={format:"json",level:"info",logDirectory:i5.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...J,...Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=J.level;return Y}async writeToFile($){let Y=(async()=>{let Q,G=0,W=3,z=1000;while(G<W)try{try{try{await tB(this.config.logDirectory,RW.F_OK|RW.W_OK)}catch(H){if(H instanceof Error&&"code"in H)if(H.code==="ENOENT")await sB(this.config.logDirectory,{recursive:!0,mode:493});else if(H.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw H;else throw H}}catch(H){throw console.error("Debug: [writeToFile] Failed to create log directory:",H),H}let U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:b2.from($);try{if(!S5(this.currentLogFile))await P5(this.currentLogFile,"",{mode:420});if(Q=DW(this.currentLogFile,"a",420),aB(Q,U,{flag:"a"}),wW(Q),Q!==void 0)N5(Q),Q=void 0;if((await w$(this.currentLogFile)).size===0){if(await P5(this.currentLogFile,U,{flag:"w",mode:420}),(await w$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(H){let F=H;if(F.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(F.code)){if(G<W-1){let B=typeof F.message==="string"?F.message:"Unknown error";console.error(`Network error during write attempt ${G+1}/${W}:`,B);let K=z*2**G;await new Promise((O)=>setTimeout(O,K)),G++;continue}}if(F?.code&&["ENOSPC","EDQUOT"].includes(F.code))throw Error(`Disk quota exceeded or no space left on device: ${F.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",F),F}finally{if(Q!==void 0)try{N5(Q)}catch(H){console.error("Debug: [writeToFile] Error closing file descriptor:",H)}}}catch(U){if(G===W-1){let F=U,B=typeof F.message==="string"?F.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),U}G++;let H=z*2**(G-1);await new Promise((F)=>setTimeout(F,H))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch(Q){throw console.error("Debug: [writeToFile] Error in operation:",Q),Q}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return D$(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return D$(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return D$(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(k0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,J;switch($.frequency){case"daily":J=86400000;break;case"weekly":J=604800000;break;case"monthly":J=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},J)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let J=this.config.rotation.keyRotation;if(!J?.enabled)return;let Y=typeof J.interval==="number"?J.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Q)=>{console.error("Error rotating keys:",Q)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let J=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let Q=Array.from(this.encryptionKeys.entries()).sort(([,z],[,U])=>U.createdAt.getTime()-z.createdAt.getTime()),G=typeof J.maxKeys==="number"?J.maxKeys:1,W=Math.max(1,G);if(Q.length>W)for(let[z]of Q.slice(W))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return R5(16).toString("hex")}generateKey(){return R5(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:J}=this.getCurrentKey(),Y=R5(16),Z=rB("aes-256-gcm",J,Y),Q=b2.concat([Z.update($,"utf8"),Z.final()]),G=Z.getAuthTag();return{encrypted:b2.concat([Y,Q,G]),iv:Y}}async compressData($){return new Promise((J,Y)=>{let Z=SW(),Q=[];Z.on("data",(G)=>Q.push(G)),Z.on("end",()=>J(b2.from(b2.concat(Q)))),Z.on("error",Y),Z.write($),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let J=this.config.rotation.encrypt;return{...$,...J}}return $}async rotateLog(){if(k0())return;let $=await w$(this.currentLogFile).catch(()=>null);if(!$)return;let J=this.config.rotation;if(typeof J==="boolean")return;if(J.maxSize&&$.size>=J.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Q=await f9(this.config.logDirectory),G=Q.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,H)=>{let F=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0")-F}),W=G.length>0?Number.parseInt(G[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${Y}.${W}`;if(await w$(Y).catch(()=>null))try{if(await NW(Y,z),J.compress)try{let U=`${z}.gz`;await this.compressLogFile(z,U),await g9(z)}catch(U){console.error("Error compressing rotated file:",U)}if(G.length===0&&!Q.some((U)=>U.endsWith(".log.1")))try{let U=`${Y}.1`;await P5(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let Q=new Date().toISOString().replace(/[:.]/g,"-"),G=Y.replace(/\.log$/,`-${Q}.log`);if(await w$(Y).catch(()=>null))await NW(Y,G)}if(this.currentLogFile=Z,J.maxFiles){let G=(await f9(this.config.logDirectory)).filter((W)=>W.startsWith(this.name)).sort((W,z)=>z.localeCompare(W));for(let W of G.slice(J.maxFiles))await g9(D$(this.config.logDirectory,W))}}}async compressLogFile($,J){let Y=TW($),Z=iB(J),Q=SW();await oB(Y,Q,Z)}async handleFingersCrossedBuffer($,J){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(J),console.log(J);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:J,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let J={debug:0,info:1,success:2,warning:3,error:4};return J[$]>=J[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((J)=>{console.error("Error in pending write operation:",J)});return Promise.resolve()})),S5(this.currentLogFile))try{let $=DW(this.currentLogFile,"r+");wW($),N5($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!k0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let J=(await f9(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of J)try{await g9(D$(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?R0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:J,icon:Y="",tag:Z="",message:Q,level:G,showTimestamp:W=!0}=$,z=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(W)O.push(J);if(G==="warning")O.push("WARN");else if(G==="error")O.push("ERROR");else if(Y)O.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)O.push(Z.replace(/[[\]]/g,""));return O.push(Q),O.join(" ")}let U=t0.stdout.columns||120,H="";if(G==="warning"||G==="error")H=`${Y} ${Q}`;else if(G==="info"||G==="success")H=`${Y} ${Z} ${Q}`;else H=`${Y} ${Z} ${R0.cyan(Q)}`;if(!W)return H.trim();let F=z(H).trim().length,B=z(J).length,K=Math.max(1,U-2-F-B);return`${H.trim()}${" ".repeat(K)}${J}`}formatMessage($,J){if(J.length===1&&Array.isArray(J[0]))return $.replace(/\{(\d+)\}/g,(G,W)=>{let z=Number.parseInt(W,10);return z<J[0].length?String(J[0][z]):G});let Y=/%([sdijfo%])/g,Z=0,Q=$.replace(Y,(G,W)=>{if(W==="%")return"%";if(Z>=J.length)return G;let z=J[Z++];switch(W){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return G}});if(Z<J.length)Q+=` ${J.slice(Z).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`;return Q}async log($,J,...Y){let Z=new Date,Q=this.formatConsoleTimestamp(Z),G=this.formatFileTimestamp(Z),W,z;if(J instanceof Error)W=J.message,z=J.stack;else W=this.formatMessage(J,Y);if(this.fancy&&!k0()){let H=_4[$],F=this.options.showTags!==!1&&this.name?R0.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:R0.gray(W),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:W,level:$}),console.error(B);break;case"success":B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:R0.green(W),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:W,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:W,level:$}),console.error(B),z){let K=z.split(`
7595
7600
  `);for(let O of K)if(O.trim()&&!O.includes(W))console.error(this.formatConsoleMessage({timestamp:Q,message:R0.gray(` ${O}`),level:$,showTimestamp:!1}))}break}}else if(!k0()){if(console.error(`${G} ${this.environment}.${$.toUpperCase()}: ${W}`),z)console.error(z)}if(!this.shouldLog($))return;let U=`${G} ${this.environment}.${$.toUpperCase()}: ${W}
7596
7601
  `;if(z)U+=`${z}
7597
7602
  `;U=U.replace(this.ANSI_PATTERN,""),await this.writeToFile(U)}time($){let J=performance.now();if(this.fancy&&!k0()){let Y=this.options.showTags!==!1&&this.name?R0.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:R0.blue("◐"),tag:Y,message:`${R0.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),Q=Math.round(Z-J),G=`${$} completed in ${Q}ms`,W=new Date,z=this.formatConsoleTimestamp(W),H=`${this.formatFileTimestamp(W)} ${this.environment}.INFO: ${G}`;if(Y)H+=` ${JSON.stringify(Y)}`;if(H+=`
@@ -7629,7 +7634,7 @@ ${Q.map((H)=>{let F=bW(J,H.file).replace(/\\/g,"/");return` '${H.base}': typeof
7629
7634
  export type ConfigByName = ${z}
7630
7635
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
7631
7636
  export type ConfigOf = Config
7632
- `}return{name:"bunfig-plugin",setup(Q){Q.onResolve({filter:/^virtual:bunfig-types$/},(G)=>{return{path:G.path,namespace:"bunfig-virtual"}}),Q.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Z(),loader:"ts"}})}}}var V4,k$,A8,A4,$O,JO,lW,e9,i5,s0,R0,YO,pW,ZO,rW,QO,GO,f5,WO,nW,iW,g5,zO,UO,HO,FO,$6,_4,XO,o0,BO,KO,aW,J6,a5,d0,_0,OO,tW,VO,sW,AO,_O,u5,jO,oW,eW,LO,d5,EO,MO,qO,TO,wO,Y6,j4,DO,RO="0.15.6",D1,B6,O8,t5,s5,K6,o5,e5,V8,$J,JJ,y2,L4,E4,m1,j2,M4,q4,NO=NK(async()=>{V4=import.meta.require,k$=new QJ,A8=new GJ,A4={createKey:SK,isEquivalent:PK,estimateMemoryUsage:CK},$O=W6(r5.cwd(),"config"),JO=W6(r5.cwd(),"src/generated"),lW=G6.env.CLARITY_LOG_DIR||lB(kK(),"logs"),e9={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:lW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},i5=await hK(),s0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},R0=s0,YO=s0.red,pW=s0.green,ZO=s0.yellow,rW=s0.blue,QO=s0.magenta,GO=s0.cyan,f5=s0.white,WO=s0.gray,nW=s0.bgRed,iW=s0.bgYellow,g5=s0.bold,zO=s0.dim,UO=s0.italic,HO=s0.underline,FO=s0.reset,$6={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_4={debug:"\uD83D\uDD0D",info:rW("ℹ"),success:pW("✓"),warning:iW(f5(g5(" WARN "))),error:nW(f5(g5(" ERROR ")))},XO=new H6("stacks"),o0=new H6("bunfig",{showTags:!0}),BO=W1(K8.cwd(),"config"),KO=W1(K8.cwd(),"src/generated"),aW=Q6.env.CLARITY_LOG_DIR||cB(fK(),"logs"),J6={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:aW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},a5=await gK(),d0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},_0=d0,OO=d0.red,tW=d0.green,VO=d0.yellow,sW=d0.blue,AO=d0.magenta,_O=d0.cyan,u5=d0.white,jO=d0.gray,oW=d0.bgRed,eW=d0.bgYellow,LO=d0.bgGray,d5=d0.bold,EO=d0.dim,MO=d0.italic,qO=d0.underline,TO=d0.strikethrough,wO=d0.reset,Y6={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},j4={debug:"\uD83D\uDD0D",info:sW("ℹ"),success:tW("✓"),warning:eW(u5(d5(" WARN "))),error:oW(u5(d5(" ERROR ")))},DO=new X6("stacks"),D1=class extends Error{timestamp;context;constructor(J,Y={}){super(J);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let J=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,Z])=>`${Y}: ${Z}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${J}`}},B6=class extends D1{code="CONFIG_NOT_FOUND";constructor(J,Y,Z){let Q=Z?` or alias "${Z}"`:"";super(`Configuration "${J}"${Q} not found`,{configName:J,alias:Z,searchPaths:Y,searchPathCount:Y.length})}},O8=class extends D1{code="CONFIG_LOAD_ERROR";constructor(J,Y,Z){super(`Failed to load configuration from "${J}": ${Y.message}`,{configPath:J,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},t5=class extends D1{code="CONFIG_VALIDATION_ERROR";constructor(J,Y,Z){super(`Configuration validation failed for "${J}"`,{configPath:J,configName:Z,validationErrors:Y,errorCount:Y.length})}},s5=class extends D1{code="CONFIG_MERGE_ERROR";constructor(J,Y,Z,Q){super(`Failed to merge configuration from "${J}" with "${Y}": ${Z.message}`,{sourcePath:J,targetPath:Y,configName:Q,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},K6=class extends D1{code="ENV_VAR_ERROR";constructor(J,Y,Z,Q){super(`Failed to parse environment variable "${J}" with value "${Y}" as ${Z}`,{envKey:J,envValue:Y,expectedType:Z,configName:Q})}},o5=class extends D1{code="FILE_SYSTEM_ERROR";constructor(J,Y,Z){super(`File system ${J} failed for "${Y}": ${Z.message}`,{operation:J,path:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},e5=class extends D1{code="TYPE_GENERATION_ERROR";constructor(J,Y,Z){super(`Failed to generate types from "${J}" to "${Y}": ${Z.message}`,{configDir:J,outputPath:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},V8=class extends D1{code="SCHEMA_VALIDATION_ERROR";constructor(J,Y,Z){super(`Schema validation failed${Z?` for config "${Z}"`:""}`,{schemaPath:J,configName:Z,validationErrors:Y,errorCount:Y.length})}},$J=class extends D1{code="BROWSER_CONFIG_ERROR";constructor(J,Y,Z,Q){super(`Failed to fetch configuration from "${J}": ${Y} ${Z}`,{endpoint:J,status:Y,statusText:Z,configName:Q})}},JJ=class extends D1{code="PLUGIN_ERROR";constructor(J,Y,Z){super(`Plugin "${J}" failed during ${Y}: ${Z.message}`,{pluginName:J,operation:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},y2={configNotFound($,J,Y){return new B6($,J,Y)},configLoad($,J,Y){return new O8($,J,Y)},configValidation($,J,Y){return new t5($,J,Y)},configMerge($,J,Y,Z){return new s5($,J,Y,Z)},envVar($,J,Y,Z){return new K6($,J,Y,Z)},fileSystem($,J,Y){return new o5($,J,Y)},typeGeneration($,J,Y){return new e5($,J,Y)},schemaValidation($,J,Y){return new V8($,J,Y)},browserConfig($,J,Y,Z){return new $J($,J,Y,Z)},plugin($,J,Y){return new JJ($,J,Y)}},L4={replace:"replace",concat:"concat",smart:"smart"},E4=/^https?:\/\//,m1=new X6("bunfig",{showTags:!0}),j2=new FJ,M4=z1(o2.cwd(),"config"),q4=z1(o2.cwd(),"src/generated")});function SO($,J={}){let Y=z6.cwd();while(Y.includes("storage"))Y=yW(Y,"..");let Z=yW(Y,$||"");if(J?.relative)return KK(z6.cwd(),Z);return Z}var PO=z6.env.CLARITY_LOG_DIR||BK(SO(),"logs"),T4={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:PO,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},O6={...T4},xR=(async()=>{try{let{loadConfig:$}=await NO().then(()=>W4),J=await $({name:"clarity",alias:"logging",defaultConfig:T4,cwd:z6.cwd()});if(J)Object.assign(O6,J)}catch{}return O6})();function c0(){if(_2.env.NODE_ENV==="test"||_2.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function CO(){if(_2.env.NODE_ENV==="test"||_2.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof _2<"u"){let $=_2.type;if($==="renderer"||$==="worker")return!1;return!!(_2.versions&&(_2.versions.node||_2.versions.bun))}return!1}class w4{async format($){let J=await CO(),Y=await this.getMetadata(J);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:J}=await import("os");return{pid:I$.pid,hostname:J(),environment:I$.env.NODE_ENV||"development",platform:I$.platform,version:I$.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:I$.env.NODE_ENV||I$.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var r0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},L0=r0,IR=r0.red,xO=r0.green,kR=r0.yellow,IO=r0.blue,hR=r0.magenta,bR=r0.cyan,$4=r0.white,yR=r0.gray,kO=r0.bgRed,hO=r0.bgYellow,vR=r0.bgGray,J4=r0.bold,fR=r0.dim,gR=r0.italic,uR=r0.underline,dR=r0.strikethrough,cR=r0.reset,c5={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bO={debug:"\uD83D\uDD0D",info:IO("ℹ"),success:xO("✓"),warning:hO($4(J4(" WARN "))),error:kO($4(J4(" ERROR ")))};class E6{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,J={}){this.name=$,this.config={...O6},this.options=this.normalizeOptions(J),this.formatter=this.options.formatter||new w4,this.enabled=J.enabled??!0,this.fancy=J.fancy??!0,this.tagFormat=J.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=J.timestampPosition??"right",this.environment=J.environment??A0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(J);let Y={...J},Z=J.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Q=this.generateKeyId(),G=this.generateKey();this.currentKeyId=Q,this.keys.set(Q,G),this.encryptionKeys.set(Q,{key:G,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let J={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return J[$]>=J[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...c5,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...c5};return{...c5,...$.fingersCrossed}}normalizeOptions($){let J={format:"json",level:"info",logDirectory:O6.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...J,...Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=J.level;return Y}shouldWriteToFile(){return!c0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let Q,G=0,W=3,z=1000;while(G<W)try{try{try{await jK(this.config.logDirectory,uW.F_OK|uW.W_OK)}catch(H){if(H instanceof Error&&"code"in H)if(H.code==="ENOENT")await LK(this.config.logDirectory,{recursive:!0,mode:493});else if(H.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw H;else throw H}}catch(H){throw console.error("Debug: [writeToFile] Failed to create log directory:",H),H}let U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:O2.from($);try{if(!p9(this.currentLogFile))await v5(this.currentLogFile,"",{mode:420});if(Q=gW(this.currentLogFile,"a",420),_K(Q,U,{flag:"a"}),fW(Q),Q!==void 0)y5(Q),Q=void 0;if((await C$(this.currentLogFile)).size===0){if(await v5(this.currentLogFile,U,{flag:"w",mode:420}),(await C$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(H){let F=H;if(F.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(F.code)){if(G<W-1){let B=typeof F.message==="string"?F.message:"Unknown error";console.error(`Network error during write attempt ${G+1}/${W}:`,B);let K=z*2**G;await new Promise((O)=>setTimeout(O,K)),G++;continue}}if(F?.code&&["ENOSPC","EDQUOT"].includes(F.code))throw Error(`Disk quota exceeded or no space left on device: ${F.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",F),F}finally{if(Q!==void 0)try{y5(Q)}catch(H){console.error("Debug: [writeToFile] Error closing file descriptor:",H)}}}catch(U){if(G===W-1){let F=U,B=typeof F.message==="string"?F.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),U}G++;let H=z*2**(G-1);await new Promise((F)=>setTimeout(F,H))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch(Q){throw console.error("Debug: [writeToFile] Error in operation:",Q),Q}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return x$(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return x$(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return x$(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(c0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,J;switch($.frequency){case"daily":J=86400000;break;case"weekly":J=604800000;break;case"monthly":J=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},J)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let J=this.config.rotation.keyRotation;if(!J?.enabled)return;let Y=typeof J.interval==="number"?J.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Q)=>{console.error("Error rotating keys:",Q)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let J=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let Q=Array.from(this.encryptionKeys.entries()).sort(([,z],[,U])=>U.createdAt.getTime()-z.createdAt.getTime()),G=typeof J.maxKeys==="number"?J.maxKeys:1,W=Math.max(1,G);if(Q.length>W)for(let[z]of Q.slice(W))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return b5(16).toString("hex")}generateKey(){return b5(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:J}=this.getCurrentKey(),Y=b5(16),Z=OK("aes-256-gcm",J,Y),Q=O2.isBuffer($)?$:O2.from($,"utf8"),G=Z.update(Q),W=Z.final(),z=G.length+W.length,U=Z.getAuthTag(),H=O2.allocUnsafe(16+z+16);return Y.copy(H,0),G.copy(H,16),W.copy(H,16+G.length),U.copy(H,16+z),{encrypted:H,iv:Y}}async compressData($){return new Promise((J,Y)=>{let Z=cW(),Q=[];Z.on("data",(G)=>Q.push(G)),Z.on("end",()=>J(O2.from(O2.concat(Q)))),Z.on("error",Y),Z.write($),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let J=this.config.rotation.encrypt;return{...$,...J}}return $}async rotateLog(){if(c0())return;if(!this.shouldWriteToFile())return;let $=await C$(this.currentLogFile).catch(()=>null);if(!$)return;let J=this.config.rotation;if(typeof J==="boolean")return;if(J.maxSize&&$.size>=J.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Q=await r9(this.config.logDirectory),G=Q.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,H)=>{let F=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0")-F}),W=G.length>0?Number.parseInt(G[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${Y}.${W}`;if(await C$(Y).catch(()=>null))try{if(await dW(Y,z),J.compress)try{let U=`${z}.gz`;await this.compressLogFile(z,U),await n9(z)}catch(U){console.error("Error compressing rotated file:",U)}if(G.length===0&&!Q.some((U)=>U.endsWith(".log.1")))try{let U=`${Y}.1`;await v5(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let Q=new Date().toISOString().replace(/[:.]/g,"-"),G=Y.replace(/\.log$/,`-${Q}.log`);if(await C$(Y).catch(()=>null))await dW(Y,G)}if(this.currentLogFile=Z,J.maxFiles){let G=(await r9(this.config.logDirectory)).filter((W)=>W.startsWith(this.name)).sort((W,z)=>z.localeCompare(W));for(let W of G.slice(J.maxFiles))await n9(x$(this.config.logDirectory,W))}}}async compressLogFile($,J){let Y=vW($),Z=AK(J),Q=cW();await qK(Y,Q,Z)}async handleFingersCrossedBuffer($,J){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}}shouldLog($){if(!this.enabled)return!1;let J={debug:0,info:1,success:2,warning:3,error:4};return J[$]>=J[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((J)=>{console.error("Error in pending write operation:",J)});return Promise.resolve()})),p9(this.currentLogFile))try{let $=gW(this.currentLogFile,"r+");fW($),y5($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!c0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let J=(await r9(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of J)try{await n9(x$(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?L0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||c0())return!1;let $=typeof A0.env.NO_COLOR<"u",J=A0.env.FORCE_COLOR==="0";if($||J)return!1;return!!(typeof A0.stderr<"u"&&A0.stderr.isTTY||typeof A0.stdout<"u"&&A0.stdout.isTTY)}formatConsoleMessage($){let{timestamp:J,icon:Y="",tag:Z="",message:Q,level:G,showTimestamp:W=!0}=$,z=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(W)O.push(J);if(G==="warning")O.push("WARN");else if(G==="error")O.push("ERROR");else if(Y)O.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)O.push(Z.replace(/[[\]]/g,""));return O.push(Q),O.join(" ")}let U=A0.stdout.columns||120,H="";if(G==="warning"||G==="error")H=`${Y} ${Q}`;else if(G==="info"||G==="success")H=`${Y} ${Z} ${Q}`;else H=`${Y} ${Z} ${L0.cyan(Q)}`;if(!W)return H.trim();let F=z(H).trim().length,B=z(J).length,K=Math.max(1,U-2-F-B);return`${H.trim()}${" ".repeat(K)}${J}`}formatMessage($,J){if(J.length===1&&Array.isArray(J[0]))return $.replace(/\{(\d+)\}/g,(G,W)=>{let z=Number.parseInt(W,10);return z<J[0].length?String(J[0][z]):G});let Y=/%([sdijfo%])/g,Z=0,Q=$.replace(Y,(G,W)=>{if(W==="%")return"%";if(Z>=J.length)return G;let z=J[Z++];switch(W){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return G}});if(Z<J.length)Q+=` ${J.slice(Z).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`;return Q}formatMarkdown($){if(!$)return $;let J=$;return J=J.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,Z,Q)=>{let G=L0.underline(L0.blue(Z)),W=this.toAbsoluteFilePath(Q);if(W&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let z=`file://${encodeURI(W)}`,U="\x1B]8;;",H="\x1B\\";return`\x1B]8;;${z}\x1B\\${G}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${Q}\x1B\\${G}\x1B]8;;\x1B\\`;return G}),J=J.replace(/`([^`]+)`/g,(Y,Z)=>L0.bgGray(Z)),J=J.replace(/\*\*([^*]+)\*\*/g,(Y,Z)=>L0.bold(Z)),J=J.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Z)=>L0.italic(Z)),J=J.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Z)=>L0.italic(Z)),J=J.replace(/~([^~]+)~/g,(Y,Z)=>L0.strikethrough(Z)),J}supportsHyperlinks(){if(c0())return!1;let $=A0.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let J=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(J)&&J>=5000)return!0;return!1}toAbsoluteFilePath($){try{let J=$;if(J.startsWith("file://"))J=J.replace(/^file:\/\//,"");if(J.startsWith("~")){let Y=A0.env.HOME||"";if(Y)J=J.replace(/^~(?=$|\/)/,Y)}if(EK(J)||J.startsWith("./")||J.startsWith("../"))J=MK(J);else return null;return p9(J)?J:null}catch{return null}}buildOutputTexts($){let J=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:J,fileText:Y}}async log($,J,...Y){if(!this.shouldLog($))return;let Z=new Date,Q=this.formatConsoleTimestamp(Z),G=this.formatFileTimestamp(Z),W,z;if(J instanceof Error)W=J.message,z=J.stack;else W=this.formatMessage(J,Y);let{consoleText:U,fileText:H}=this.buildOutputTexts(W);if(this.shouldStyleConsole()){let B=this.options.showIcons===!1?"":bO[$],K=this.options.showTags!==!1&&this.name?L0.gray(this.formatTag(this.name)):"",O;switch($){case"debug":O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:L0.gray(U),level:$}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:U,level:$}),console.warn(O);break;case"success":O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:L0.green(U),level:$}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:U,level:$}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:U,level:$}),console.error(O),z){let A=z.split(`
7637
+ `}return{name:"bunfig-plugin",setup(Q){Q.onResolve({filter:/^virtual:bunfig-types$/},(G)=>{return{path:G.path,namespace:"bunfig-virtual"}}),Q.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Z(),loader:"ts"}})}}}var V4,k$,A8,A4,$O,JO,lW,e9,i5,s0,R0,YO,pW,ZO,rW,QO,GO,f5,WO,nW,iW,g5,zO,UO,HO,FO,$6,_4,XO,o0,BO,KO,aW,J6,a5,d0,_0,OO,tW,VO,sW,AO,_O,u5,jO,oW,eW,LO,d5,EO,MO,qO,TO,wO,Y6,j4,DO,RO="0.15.6",D1,B6,O8,t5,s5,K6,o5,e5,V8,$J,JJ,y2,L4,E4,m1,j2,M4,q4,NO=NK(async()=>{V4=import.meta.require,k$=new QJ,A8=new GJ,A4={createKey:SK,isEquivalent:PK,estimateMemoryUsage:CK},$O=W6(r5.cwd(),"config"),JO=W6(r5.cwd(),"src/generated"),lW=G6.env.CLARITY_LOG_DIR||lB(kK(),"logs"),e9={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:lW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},i5=await hK(),s0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},R0=s0,YO=s0.red,pW=s0.green,ZO=s0.yellow,rW=s0.blue,QO=s0.magenta,GO=s0.cyan,f5=s0.white,WO=s0.gray,nW=s0.bgRed,iW=s0.bgYellow,g5=s0.bold,zO=s0.dim,UO=s0.italic,HO=s0.underline,FO=s0.reset,$6={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_4={debug:"\uD83D\uDD0D",info:rW("ℹ"),success:pW("✓"),warning:iW(f5(g5(" WARN "))),error:nW(f5(g5(" ERROR ")))},XO=new H6("stacks"),o0=new H6("bunfig",{showTags:!0}),BO=W1(K8.cwd(),"config"),KO=W1(K8.cwd(),"src/generated"),aW=Q6.env.CLARITY_LOG_DIR||cB(fK(),"logs"),J6={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:aW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},a5=await gK(),d0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},_0=d0,OO=d0.red,tW=d0.green,VO=d0.yellow,sW=d0.blue,AO=d0.magenta,_O=d0.cyan,u5=d0.white,jO=d0.gray,oW=d0.bgRed,eW=d0.bgYellow,LO=d0.bgGray,d5=d0.bold,EO=d0.dim,MO=d0.italic,qO=d0.underline,TO=d0.strikethrough,wO=d0.reset,Y6={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},j4={debug:"\uD83D\uDD0D",info:sW("ℹ"),success:tW("✓"),warning:eW(u5(d5(" WARN "))),error:oW(u5(d5(" ERROR ")))},DO=new X6("stacks"),D1=class extends Error{timestamp;context;constructor(J,Y={}){super(J);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let J=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,Z])=>`${Y}: ${Z}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${J}`}},B6=class extends D1{code="CONFIG_NOT_FOUND";constructor(J,Y,Z){let Q=Z?` or alias "${Z}"`:"";super(`Configuration "${J}"${Q} not found`,{configName:J,alias:Z,searchPaths:Y,searchPathCount:Y.length})}},O8=class extends D1{code="CONFIG_LOAD_ERROR";constructor(J,Y,Z){super(`Failed to load configuration from "${J}": ${Y.message}`,{configPath:J,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},t5=class extends D1{code="CONFIG_VALIDATION_ERROR";constructor(J,Y,Z){super(`Configuration validation failed for "${J}"`,{configPath:J,configName:Z,validationErrors:Y,errorCount:Y.length})}},s5=class extends D1{code="CONFIG_MERGE_ERROR";constructor(J,Y,Z,Q){super(`Failed to merge configuration from "${J}" with "${Y}": ${Z.message}`,{sourcePath:J,targetPath:Y,configName:Q,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},K6=class extends D1{code="ENV_VAR_ERROR";constructor(J,Y,Z,Q){super(`Failed to parse environment variable "${J}" with value "${Y}" as ${Z}`,{envKey:J,envValue:Y,expectedType:Z,configName:Q})}},o5=class extends D1{code="FILE_SYSTEM_ERROR";constructor(J,Y,Z){super(`File system ${J} failed for "${Y}": ${Z.message}`,{operation:J,path:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},e5=class extends D1{code="TYPE_GENERATION_ERROR";constructor(J,Y,Z){super(`Failed to generate types from "${J}" to "${Y}": ${Z.message}`,{configDir:J,outputPath:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},V8=class extends D1{code="SCHEMA_VALIDATION_ERROR";constructor(J,Y,Z){super(`Schema validation failed${Z?` for config "${Z}"`:""}`,{schemaPath:J,configName:Z,validationErrors:Y,errorCount:Y.length})}},$J=class extends D1{code="BROWSER_CONFIG_ERROR";constructor(J,Y,Z,Q){super(`Failed to fetch configuration from "${J}": ${Y} ${Z}`,{endpoint:J,status:Y,statusText:Z,configName:Q})}},JJ=class extends D1{code="PLUGIN_ERROR";constructor(J,Y,Z){super(`Plugin "${J}" failed during ${Y}: ${Z.message}`,{pluginName:J,operation:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},y2={configNotFound($,J,Y){return new B6($,J,Y)},configLoad($,J,Y){return new O8($,J,Y)},configValidation($,J,Y){return new t5($,J,Y)},configMerge($,J,Y,Z){return new s5($,J,Y,Z)},envVar($,J,Y,Z){return new K6($,J,Y,Z)},fileSystem($,J,Y){return new o5($,J,Y)},typeGeneration($,J,Y){return new e5($,J,Y)},schemaValidation($,J,Y){return new V8($,J,Y)},browserConfig($,J,Y,Z){return new $J($,J,Y,Z)},plugin($,J,Y){return new JJ($,J,Y)}},L4={replace:"replace",concat:"concat",smart:"smart"},E4=/^https?:\/\//,m1=new X6("bunfig",{showTags:!0}),j2=new FJ,M4=z1(o2.cwd(),"config"),q4=z1(o2.cwd(),"src/generated")});function SO($,J={}){let Y=z6.cwd();while(Y.includes("storage"))Y=yW(Y,"..");let Z=yW(Y,$||"");if(J?.relative)return KK(z6.cwd(),Z);return Z}var PO=z6.env.CLARITY_LOG_DIR||BK(SO(),"logs"),T4={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:PO,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},O6={...T4},CR=(async()=>{try{let{loadConfig:$}=await NO().then(()=>W4),J=await $({name:"clarity",alias:"logging",defaultConfig:T4,cwd:z6.cwd()});if(J)Object.assign(O6,J)}catch{}return O6})();function c0(){if(_2.env.NODE_ENV==="test"||_2.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function CO(){if(_2.env.NODE_ENV==="test"||_2.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof _2<"u"){let $=_2.type;if($==="renderer"||$==="worker")return!1;return!!(_2.versions&&(_2.versions.node||_2.versions.bun))}return!1}class w4{async format($){let J=await CO(),Y=await this.getMetadata(J);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:J}=await import("os");return{pid:I$.pid,hostname:J(),environment:I$.env.NODE_ENV||"development",platform:I$.platform,version:I$.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:I$.env.NODE_ENV||I$.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var r0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},L0=r0,xR=r0.red,xO=r0.green,IR=r0.yellow,IO=r0.blue,kR=r0.magenta,hR=r0.cyan,$4=r0.white,bR=r0.gray,kO=r0.bgRed,hO=r0.bgYellow,yR=r0.bgGray,J4=r0.bold,vR=r0.dim,fR=r0.italic,gR=r0.underline,uR=r0.strikethrough,dR=r0.reset,c5={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bO={debug:"\uD83D\uDD0D",info:IO("ℹ"),success:xO("✓"),warning:hO($4(J4(" WARN "))),error:kO($4(J4(" ERROR ")))};class E6{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,J={}){this.name=$,this.config={...O6},this.options=this.normalizeOptions(J),this.formatter=this.options.formatter||new w4,this.enabled=J.enabled??!0,this.fancy=J.fancy??!0,this.tagFormat=J.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=J.timestampPosition??"right",this.environment=J.environment??A0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(J);let Y={...J},Z=J.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Q=this.generateKeyId(),G=this.generateKey();this.currentKeyId=Q,this.keys.set(Q,G),this.encryptionKeys.set(Q,{key:G,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let J={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return J[$]>=J[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...c5,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...c5};return{...c5,...$.fingersCrossed}}normalizeOptions($){let J={format:"json",level:"info",logDirectory:O6.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...J,...Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=J.level;return Y}shouldWriteToFile(){return!c0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let Q,G=0,W=3,z=1000;while(G<W)try{try{try{await jK(this.config.logDirectory,uW.F_OK|uW.W_OK)}catch(H){if(H instanceof Error&&"code"in H)if(H.code==="ENOENT")await LK(this.config.logDirectory,{recursive:!0,mode:493});else if(H.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw H;else throw H}}catch(H){throw console.error("Debug: [writeToFile] Failed to create log directory:",H),H}let U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:O2.from($);try{if(!p9(this.currentLogFile))await v5(this.currentLogFile,"",{mode:420});if(Q=gW(this.currentLogFile,"a",420),_K(Q,U,{flag:"a"}),fW(Q),Q!==void 0)y5(Q),Q=void 0;if((await C$(this.currentLogFile)).size===0){if(await v5(this.currentLogFile,U,{flag:"w",mode:420}),(await C$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(H){let F=H;if(F.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(F.code)){if(G<W-1){let B=typeof F.message==="string"?F.message:"Unknown error";console.error(`Network error during write attempt ${G+1}/${W}:`,B);let K=z*2**G;await new Promise((O)=>setTimeout(O,K)),G++;continue}}if(F?.code&&["ENOSPC","EDQUOT"].includes(F.code))throw Error(`Disk quota exceeded or no space left on device: ${F.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",F),F}finally{if(Q!==void 0)try{y5(Q)}catch(H){console.error("Debug: [writeToFile] Error closing file descriptor:",H)}}}catch(U){if(G===W-1){let F=U,B=typeof F.message==="string"?F.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),U}G++;let H=z*2**(G-1);await new Promise((F)=>setTimeout(F,H))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch(Q){throw console.error("Debug: [writeToFile] Error in operation:",Q),Q}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return x$(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return x$(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return x$(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(c0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,J;switch($.frequency){case"daily":J=86400000;break;case"weekly":J=604800000;break;case"monthly":J=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},J)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let J=this.config.rotation.keyRotation;if(!J?.enabled)return;let Y=typeof J.interval==="number"?J.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Q)=>{console.error("Error rotating keys:",Q)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let J=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let Q=Array.from(this.encryptionKeys.entries()).sort(([,z],[,U])=>U.createdAt.getTime()-z.createdAt.getTime()),G=typeof J.maxKeys==="number"?J.maxKeys:1,W=Math.max(1,G);if(Q.length>W)for(let[z]of Q.slice(W))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return b5(16).toString("hex")}generateKey(){return b5(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:J}=this.getCurrentKey(),Y=b5(16),Z=OK("aes-256-gcm",J,Y),Q=O2.isBuffer($)?$:O2.from($,"utf8"),G=Z.update(Q),W=Z.final(),z=G.length+W.length,U=Z.getAuthTag(),H=O2.allocUnsafe(16+z+16);return Y.copy(H,0),G.copy(H,16),W.copy(H,16+G.length),U.copy(H,16+z),{encrypted:H,iv:Y}}async compressData($){return new Promise((J,Y)=>{let Z=cW(),Q=[];Z.on("data",(G)=>Q.push(G)),Z.on("end",()=>J(O2.from(O2.concat(Q)))),Z.on("error",Y),Z.write($),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let J=this.config.rotation.encrypt;return{...$,...J}}return $}async rotateLog(){if(c0())return;if(!this.shouldWriteToFile())return;let $=await C$(this.currentLogFile).catch(()=>null);if(!$)return;let J=this.config.rotation;if(typeof J==="boolean")return;if(J.maxSize&&$.size>=J.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Q=await r9(this.config.logDirectory),G=Q.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,H)=>{let F=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0")-F}),W=G.length>0?Number.parseInt(G[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${Y}.${W}`;if(await C$(Y).catch(()=>null))try{if(await dW(Y,z),J.compress)try{let U=`${z}.gz`;await this.compressLogFile(z,U),await n9(z)}catch(U){console.error("Error compressing rotated file:",U)}if(G.length===0&&!Q.some((U)=>U.endsWith(".log.1")))try{let U=`${Y}.1`;await v5(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let Q=new Date().toISOString().replace(/[:.]/g,"-"),G=Y.replace(/\.log$/,`-${Q}.log`);if(await C$(Y).catch(()=>null))await dW(Y,G)}if(this.currentLogFile=Z,J.maxFiles){let G=(await r9(this.config.logDirectory)).filter((W)=>W.startsWith(this.name)).sort((W,z)=>z.localeCompare(W));for(let W of G.slice(J.maxFiles))await n9(x$(this.config.logDirectory,W))}}}async compressLogFile($,J){let Y=vW($),Z=AK(J),Q=cW();await qK(Y,Q,Z)}async handleFingersCrossedBuffer($,J){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}}shouldLog($){if(!this.enabled)return!1;let J={debug:0,info:1,success:2,warning:3,error:4};return J[$]>=J[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((J)=>{console.error("Error in pending write operation:",J)});return Promise.resolve()})),p9(this.currentLogFile))try{let $=gW(this.currentLogFile,"r+");fW($),y5($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!c0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let J=(await r9(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of J)try{await n9(x$(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?L0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||c0())return!1;let $=typeof A0.env.NO_COLOR<"u",J=A0.env.FORCE_COLOR==="0";if($||J)return!1;return!!(typeof A0.stderr<"u"&&A0.stderr.isTTY||typeof A0.stdout<"u"&&A0.stdout.isTTY)}formatConsoleMessage($){let{timestamp:J,icon:Y="",tag:Z="",message:Q,level:G,showTimestamp:W=!0}=$,z=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(W)O.push(J);if(G==="warning")O.push("WARN");else if(G==="error")O.push("ERROR");else if(Y)O.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)O.push(Z.replace(/[[\]]/g,""));return O.push(Q),O.join(" ")}let U=A0.stdout.columns||120,H="";if(G==="warning"||G==="error")H=`${Y} ${Q}`;else if(G==="info"||G==="success")H=`${Y} ${Z} ${Q}`;else H=`${Y} ${Z} ${L0.cyan(Q)}`;if(!W)return H.trim();let F=z(H).trim().length,B=z(J).length,K=Math.max(1,U-2-F-B);return`${H.trim()}${" ".repeat(K)}${J}`}formatMessage($,J){if(J.length===1&&Array.isArray(J[0]))return $.replace(/\{(\d+)\}/g,(G,W)=>{let z=Number.parseInt(W,10);return z<J[0].length?String(J[0][z]):G});let Y=/%([sdijfo%])/g,Z=0,Q=$.replace(Y,(G,W)=>{if(W==="%")return"%";if(Z>=J.length)return G;let z=J[Z++];switch(W){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return G}});if(Z<J.length)Q+=` ${J.slice(Z).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`;return Q}formatMarkdown($){if(!$)return $;let J=$;return J=J.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,Z,Q)=>{let G=L0.underline(L0.blue(Z)),W=this.toAbsoluteFilePath(Q);if(W&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let z=`file://${encodeURI(W)}`,U="\x1B]8;;",H="\x1B\\";return`\x1B]8;;${z}\x1B\\${G}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${Q}\x1B\\${G}\x1B]8;;\x1B\\`;return G}),J=J.replace(/`([^`]+)`/g,(Y,Z)=>L0.bgGray(Z)),J=J.replace(/\*\*([^*]+)\*\*/g,(Y,Z)=>L0.bold(Z)),J=J.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Z)=>L0.italic(Z)),J=J.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Z)=>L0.italic(Z)),J=J.replace(/~([^~]+)~/g,(Y,Z)=>L0.strikethrough(Z)),J}supportsHyperlinks(){if(c0())return!1;let $=A0.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let J=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(J)&&J>=5000)return!0;return!1}toAbsoluteFilePath($){try{let J=$;if(J.startsWith("file://"))J=J.replace(/^file:\/\//,"");if(J.startsWith("~")){let Y=A0.env.HOME||"";if(Y)J=J.replace(/^~(?=$|\/)/,Y)}if(EK(J)||J.startsWith("./")||J.startsWith("../"))J=MK(J);else return null;return p9(J)?J:null}catch{return null}}buildOutputTexts($){let J=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:J,fileText:Y}}async log($,J,...Y){if(!this.shouldLog($))return;let Z=new Date,Q=this.formatConsoleTimestamp(Z),G=this.formatFileTimestamp(Z),W,z;if(J instanceof Error)W=J.message,z=J.stack;else W=this.formatMessage(J,Y);let{consoleText:U,fileText:H}=this.buildOutputTexts(W);if(this.shouldStyleConsole()){let B=this.options.showIcons===!1?"":bO[$],K=this.options.showTags!==!1&&this.name?L0.gray(this.formatTag(this.name)):"",O;switch($){case"debug":O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:L0.gray(U),level:$}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:U,level:$}),console.warn(O);break;case"success":O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:L0.green(U),level:$}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:U,level:$}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:U,level:$}),console.error(O),z){let A=z.split(`
7633
7638
  `);for(let V of A)if(V.trim()&&!V.includes(W))console.error(this.formatConsoleMessage({timestamp:Q,message:L0.gray(` ${V}`),level:$,showTimestamp:!1}))}break}}else if(!c0()){if(console.error(`${G} ${this.environment}.${$.toUpperCase()}: ${W}`),z)console.error(z)}let F=`${G} ${this.environment}.${$.toUpperCase()}: ${H}
7634
7639
  `;if(z)F+=`${z}
7635
7640
  `;if(F=F.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(F)}progress($,J=""){let Y={update:(z,U)=>{},finish:(z)=>{},interrupt:(z,U)=>{}};if(!this.enabled)return Y;let Z=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:J||"",barLength:Z,lastRenderedLine:""},this.shouldStyleConsole()&&!c0()&&A0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(z,U)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,z),this.activeProgressBar.total),U!==void 0)this.activeProgressBar.message=U;if(this.shouldStyleConsole()&&!c0()&&A0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(z)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,z)},interrupt:(z,U="info")=>{if(!c0()&&A0.stdout.isTTY)A0.stdout.write(`
@@ -7638,7 +7643,7 @@ export type ConfigOf = Config
7638
7643
  `),U=Math.max(...z.map((K)=>K.length))+2,H=`┌${"─".repeat(U)}┐`,F=`└${"─".repeat(U)}┘`,B=z.map((K)=>{return this.formatConsoleMessage({timestamp:Y,message:L0.cyan(K),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:L0.cyan(H),showTimestamp:!1})),B.forEach((K)=>console.error(K)),console.error(this.formatConsoleMessage({timestamp:Y,message:L0.cyan(F),showTimestamp:!1}))}else if(!c0())console.error(`${Z} ${this.environment}.INFO: [BOX] ${G}`);let W=`${Z} ${this.environment}.INFO: [BOX] ${G}
7639
7644
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}async prompt($){if(c0())return Promise.resolve(!0);return new Promise((J)=>{console.error(`${L0.cyan("?")} ${$} (y/n) `);let Y=(Z)=>{let Q=Z.toString().trim().toLowerCase();A0.stdin.removeListener("data",Y);try{if(typeof A0.stdin.setRawMode==="function")A0.stdin.setRawMode(!1)}catch{}A0.stdin.pause(),console.error(""),J(Q==="y"||Q==="yes")};try{if(typeof A0.stdin.setRawMode==="function")A0.stdin.setRawMode(!0)}catch{}A0.stdin.resume(),A0.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...J){if(!this.enabled)return;let Y=$;if(J&&J.length>0){let U=/%([sdijfo%])/g,H=0;if(Y=$.replace(U,(F,B)=>{if(B==="%")return"%";if(H>=J.length)return F;let K=J[H++];switch(B){case"s":return String(K);case"d":case"i":return Number(K).toString();case"j":case"o":return JSON.stringify(K,null,2);default:return F}}),H<J.length)Y+=` ${J.slice(H).map((F)=>typeof F==="object"?JSON.stringify(F,null,2):String(F)).join(" ")}`}let{consoleText:Z,fileText:Q}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?L0.gray(this.formatTag(this.name)):"",H=this.options.showIcons===!1?"":`${L0.blue("◐")} `;console.error(`${H}${U} ${L0.cyan(Z)}`)}let z=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Q}
7640
7645
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(z)}renderProgressBar($,J=!1){if(!this.enabled||!this.shouldStyleConsole()||!A0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Z=Math.round($.barLength*Y/100),Q=$.barLength-Z,G=L0.green("━".repeat(Z)),W=L0.gray("━".repeat(Q)),z=`[${G}${W}]`,U=`${Y}%`.padStart(4),H=$.message?` ${$.message}`:"",F=this.options.showIcons===!1?"":J||Y===100?L0.green("✓"):L0.blue("▶"),B=this.options.showTags!==!1&&this.name?` ${L0.gray(this.formatTag(this.name))}`:"",K=`\r${F}${B} ${z} ${U}${H}`,O=A0.stdout.columns||80,A=" ".repeat(Math.max(0,O-K.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${K}${A}`,A0.stdout.write($.lastRenderedLine),J)A0.stdout.write(`
7641
- `)}finishProgressBar($,J){if(!this.enabled||!this.fancy||c0()||!A0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(J)$.message=J;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(c0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let J=await r9(this.config.logDirectory),Y=[];for(let Z of J){if(!($.name?new RegExp($.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let G=x$(this.config.logDirectory,Z);if($.before)try{if((await C$(G)).mtime>=$.before)continue}catch(W){console.error(`Failed to get stats for file ${G}:`,W);continue}Y.push(G)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let Z of Y)try{await n9(Z),console.warn(`Deleted log file: ${Z}`)}catch(Q){console.error(`Failed to delete log file ${Z}:`,Q)}console.warn("Log clearing process finished.")}catch(J){console.error("Error during log clearing process:",J)}}}var mR=new E6("stacks");class l1 extends Error{timestamp;context;constructor($,J={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=J,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([J,Y])=>`${J}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}}class D4 extends l1{code="CONFIG_NOT_FOUND";constructor($,J,Y){let Z=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],Q="";if(Z.length===1)Q=` or alias "${Z[0]}"`;else if(Z.length>1)Q=` or aliases ${Z.map((G)=>`"${G}"`).join(", ")}`;super(`Configuration "${$}"${Q} not found`,{configName:$,alias:Y,searchPaths:J,searchPathCount:J.length})}}class V6 extends l1{code="CONFIG_LOAD_ERROR";constructor($,J,Y){super(`Failed to load configuration from "${$}": ${J.message}`,{configPath:$,configName:Y,originalError:J.name,originalMessage:J.message});this.cause=J}}class R4 extends l1{code="CONFIG_VALIDATION_ERROR";constructor($,J,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:J,errorCount:J.length})}}class N4 extends l1{code="CONFIG_MERGE_ERROR";constructor($,J,Y,Z){super(`Failed to merge configuration from "${$}" with "${J}": ${Y.message}`,{sourcePath:$,targetPath:J,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class XJ extends l1{code="ENV_VAR_ERROR";constructor($,J,Y,Z){super(`Failed to parse environment variable "${$}" with value "${J}" as ${Y}`,{envKey:$,envValue:J,expectedType:Y,configName:Z})}}class S4 extends l1{code="FILE_SYSTEM_ERROR";constructor($,J,Y){super(`File system ${$} failed for "${J}": ${Y.message}`,{operation:$,path:J,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class P4 extends l1{code="TYPE_GENERATION_ERROR";constructor($,J,Y){super(`Failed to generate types from "${$}" to "${J}": ${Y.message}`,{configDir:$,outputPath:J,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class A6 extends l1{code="SCHEMA_VALIDATION_ERROR";constructor($,J,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:J,errorCount:J.length})}}class C4 extends l1{code="BROWSER_CONFIG_ERROR";constructor($,J,Y,Z){super(`Failed to fetch configuration from "${$}": ${J} ${Y}`,{endpoint:$,status:J,statusText:Y,configName:Z})}}class x4 extends l1{code="PLUGIN_ERROR";constructor($,J,Y){super(`Plugin "${$}" failed during ${J}: ${Y.message}`,{pluginName:$,operation:J,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}var h$={configNotFound($,J,Y){return new D4($,J,Y)},configLoad($,J,Y){return new V6($,J,Y)},configValidation($,J,Y){return new R4($,J,Y)},configMerge($,J,Y,Z){return new N4($,J,Y,Z)},envVar($,J,Y,Z){return new XJ($,J,Y,Z)},fileSystem($,J,Y){return new S4($,J,Y)},typeGeneration($,J,Y){return new P4($,J,Y)},schemaValidation($,J,Y){return new A6($,J,Y)},browserConfig($,J,Y,Z){return new C4($,J,Y,Z)},plugin($,J,Y){return new x4($,J,Y)}};async function yO($,J={}){let{maxRetries:Y=3,retryDelay:Z=1000,isRetryable:Q=()=>!0,fallback:G}=J,W=Error("Unknown error occurred");for(let z=0;z<=Y;z++)try{return await $()}catch(U){if(W=U instanceof Error?U:Error(String(U)),z===Y||!Q(W))break;if(Z>0)await new Promise((H)=>setTimeout(H,Z))}if(G!==void 0)return G;throw W instanceof Error?W:Error(`Unknown error: ${String(W)}`)}class BJ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,J)=>J==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let J=$.toLowerCase();return["true","1","yes"].includes(J)}},{name:"number",canParse:($,J)=>J==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let J=Number($);if(Number.isNaN(J))throw TypeError(`Cannot parse "${$}" as number`);return J}},{name:"array",canParse:($,J)=>J==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let J=JSON.parse($);if(Array.isArray(J))return J}catch{}return $.split(",").map((J)=>J.trim())}},{name:"json",canParse:($,J)=>J==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(J){throw Error(`Cannot parse "${$}" as JSON: ${J}`)}}}]}async applyEnvironmentVariables($,J,Y={}){let{prefix:Z,useCamelCase:Q=!0,useBackwardCompatibility:G=!0,customParsers:W={},verbose:z=!1,trackPerformance:U=!0}=Y,H=async()=>{if(!$)return{config:J,source:{type:"environment",priority:50,timestamp:new Date}};let F=Z||this.generateEnvPrefix($),B={...J};return this.processObject(B,[],F,{useCamelCase:Q,useBackwardCompatibility:G,customParsers:W,verbose:z,configName:$}),{config:B,source:{type:"environment",priority:50,timestamp:new Date}}};if(U)return ZJ.track("applyEnvironmentVariables",H,{configName:$});return H()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,J){if(!J)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,J,Y,Z){for(let[Q,G]of Object.entries($)){let W=[...J,Q],z=W.map((F)=>this.formatEnvKey(F,Z.useCamelCase)),U=`${Y}_${z.join("_")}`,H=Z.useBackwardCompatibility?`${Y}_${W.map((F)=>F.toUpperCase()).join("_")}`:null;if(Z.verbose);if(typeof G==="object"&&G!==null&&!Array.isArray(G))this.processObject(G,W,Y,Z);else{let F=a9.env[U]||(H?a9.env[H]:void 0);if(F!==void 0){if(Z.verbose){let B=a9.env[U]?U:H}try{$[Q]=this.parseEnvironmentValue(F,typeof G,U,Z.customParsers,Z.configName)}catch(B){if(B instanceof XJ)throw B;throw h$.envVar(U,F,typeof G,Z.configName)}}}}}parseEnvironmentValue($,J,Y,Z,Q){for(let[G,W]of Object.entries(Z))try{return W($)}catch{continue}for(let G of this.defaultParsers)if(G.canParse($,J))try{return G.parse($)}catch{throw h$.envVar(Y,$,`${J} (via ${G.name} parser)`,Q)}return $}getEnvironmentVariables($){let J={},Y=$.toUpperCase();for(let[Z,Q]of Object.entries(a9.env))if(Z.startsWith(Y)&&Q!==void 0)J[Z]=Q;return J}validateEnvironmentVariable($,J,Y){let Z=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Z.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,J,Y,{})}catch(Q){Z.push(`Cannot parse value "${J}" as ${Y}: ${Q}`)}return{isValid:Z.length===0,errors:Z}}generateEnvVarDocs($,J,Y={}){let{prefix:Z,format:Q="text"}=Y,G=Z||this.generateEnvPrefix($),W=[];switch(this.extractEnvVarInfo(J,[],G,W),Q){case"markdown":return this.formatAsMarkdown(W,$);case"json":return JSON.stringify(W,null,2);default:return this.formatAsText(W,$)}}extractEnvVarInfo($,J,Y,Z){for(let[Q,G]of Object.entries($)){let W=[...J,Q],z=`${Y}_${W.map((U)=>this.formatEnvKey(U,!0)).join("_")}`;if(typeof G==="object"&&G!==null&&!Array.isArray(G))this.extractEnvVarInfo(G,W,Y,Z);else Z.push({key:z,type:Array.isArray(G)?"array":typeof G,description:`Configuration for ${W.join(".")}`,example:this.generateExample(G)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,J){let Y=`Environment Variables for ${J}:
7646
+ `)}finishProgressBar($,J){if(!this.enabled||!this.fancy||c0()||!A0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(J)$.message=J;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(c0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let J=await r9(this.config.logDirectory),Y=[];for(let Z of J){if(!($.name?new RegExp($.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let G=x$(this.config.logDirectory,Z);if($.before)try{if((await C$(G)).mtime>=$.before)continue}catch(W){console.error(`Failed to get stats for file ${G}:`,W);continue}Y.push(G)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let Z of Y)try{await n9(Z),console.warn(`Deleted log file: ${Z}`)}catch(Q){console.error(`Failed to delete log file ${Z}:`,Q)}console.warn("Log clearing process finished.")}catch(J){console.error("Error during log clearing process:",J)}}}var cR=new E6("stacks");class l1 extends Error{timestamp;context;constructor($,J={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=J,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([J,Y])=>`${J}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}}class D4 extends l1{code="CONFIG_NOT_FOUND";constructor($,J,Y){let Z=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],Q="";if(Z.length===1)Q=` or alias "${Z[0]}"`;else if(Z.length>1)Q=` or aliases ${Z.map((G)=>`"${G}"`).join(", ")}`;super(`Configuration "${$}"${Q} not found`,{configName:$,alias:Y,searchPaths:J,searchPathCount:J.length})}}class V6 extends l1{code="CONFIG_LOAD_ERROR";constructor($,J,Y){super(`Failed to load configuration from "${$}": ${J.message}`,{configPath:$,configName:Y,originalError:J.name,originalMessage:J.message});this.cause=J}}class R4 extends l1{code="CONFIG_VALIDATION_ERROR";constructor($,J,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:J,errorCount:J.length})}}class N4 extends l1{code="CONFIG_MERGE_ERROR";constructor($,J,Y,Z){super(`Failed to merge configuration from "${$}" with "${J}": ${Y.message}`,{sourcePath:$,targetPath:J,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class XJ extends l1{code="ENV_VAR_ERROR";constructor($,J,Y,Z){super(`Failed to parse environment variable "${$}" with value "${J}" as ${Y}`,{envKey:$,envValue:J,expectedType:Y,configName:Z})}}class S4 extends l1{code="FILE_SYSTEM_ERROR";constructor($,J,Y){super(`File system ${$} failed for "${J}": ${Y.message}`,{operation:$,path:J,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class P4 extends l1{code="TYPE_GENERATION_ERROR";constructor($,J,Y){super(`Failed to generate types from "${$}" to "${J}": ${Y.message}`,{configDir:$,outputPath:J,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class A6 extends l1{code="SCHEMA_VALIDATION_ERROR";constructor($,J,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:J,errorCount:J.length})}}class C4 extends l1{code="BROWSER_CONFIG_ERROR";constructor($,J,Y,Z){super(`Failed to fetch configuration from "${$}": ${J} ${Y}`,{endpoint:$,status:J,statusText:Y,configName:Z})}}class x4 extends l1{code="PLUGIN_ERROR";constructor($,J,Y){super(`Plugin "${$}" failed during ${J}: ${Y.message}`,{pluginName:$,operation:J,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}var h$={configNotFound($,J,Y){return new D4($,J,Y)},configLoad($,J,Y){return new V6($,J,Y)},configValidation($,J,Y){return new R4($,J,Y)},configMerge($,J,Y,Z){return new N4($,J,Y,Z)},envVar($,J,Y,Z){return new XJ($,J,Y,Z)},fileSystem($,J,Y){return new S4($,J,Y)},typeGeneration($,J,Y){return new P4($,J,Y)},schemaValidation($,J,Y){return new A6($,J,Y)},browserConfig($,J,Y,Z){return new C4($,J,Y,Z)},plugin($,J,Y){return new x4($,J,Y)}};async function yO($,J={}){let{maxRetries:Y=3,retryDelay:Z=1000,isRetryable:Q=()=>!0,fallback:G}=J,W=Error("Unknown error occurred");for(let z=0;z<=Y;z++)try{return await $()}catch(U){if(W=U instanceof Error?U:Error(String(U)),z===Y||!Q(W))break;if(Z>0)await new Promise((H)=>setTimeout(H,Z))}if(G!==void 0)return G;throw W instanceof Error?W:Error(`Unknown error: ${String(W)}`)}class BJ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,J)=>J==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let J=$.toLowerCase();return["true","1","yes"].includes(J)}},{name:"number",canParse:($,J)=>J==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let J=Number($);if(Number.isNaN(J))throw TypeError(`Cannot parse "${$}" as number`);return J}},{name:"array",canParse:($,J)=>J==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let J=JSON.parse($);if(Array.isArray(J))return J}catch{}return $.split(",").map((J)=>J.trim())}},{name:"json",canParse:($,J)=>J==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(J){throw Error(`Cannot parse "${$}" as JSON: ${J}`)}}}]}async applyEnvironmentVariables($,J,Y={}){let{prefix:Z,useCamelCase:Q=!0,useBackwardCompatibility:G=!0,customParsers:W={},verbose:z=!1,trackPerformance:U=!0}=Y,H=async()=>{if(!$)return{config:J,source:{type:"environment",priority:50,timestamp:new Date}};let F=Z||this.generateEnvPrefix($),B={...J};return this.processObject(B,[],F,{useCamelCase:Q,useBackwardCompatibility:G,customParsers:W,verbose:z,configName:$}),{config:B,source:{type:"environment",priority:50,timestamp:new Date}}};if(U)return ZJ.track("applyEnvironmentVariables",H,{configName:$});return H()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,J){if(!J)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,J,Y,Z){for(let[Q,G]of Object.entries($)){let W=[...J,Q],z=W.map((F)=>this.formatEnvKey(F,Z.useCamelCase)),U=`${Y}_${z.join("_")}`,H=Z.useBackwardCompatibility?`${Y}_${W.map((F)=>F.toUpperCase()).join("_")}`:null;if(Z.verbose);if(typeof G==="object"&&G!==null&&!Array.isArray(G))this.processObject(G,W,Y,Z);else{let F=a9.env[U]||(H?a9.env[H]:void 0);if(F!==void 0){if(Z.verbose){let B=a9.env[U]?U:H}try{$[Q]=this.parseEnvironmentValue(F,typeof G,U,Z.customParsers,Z.configName)}catch(B){if(B instanceof XJ)throw B;throw h$.envVar(U,F,typeof G,Z.configName)}}}}}parseEnvironmentValue($,J,Y,Z,Q){for(let[G,W]of Object.entries(Z))try{return W($)}catch{continue}for(let G of this.defaultParsers)if(G.canParse($,J))try{return G.parse($)}catch{throw h$.envVar(Y,$,`${J} (via ${G.name} parser)`,Q)}return $}getEnvironmentVariables($){let J={},Y=$.toUpperCase();for(let[Z,Q]of Object.entries(a9.env))if(Z.startsWith(Y)&&Q!==void 0)J[Z]=Q;return J}validateEnvironmentVariable($,J,Y){let Z=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Z.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,J,Y,{})}catch(Q){Z.push(`Cannot parse value "${J}" as ${Y}: ${Q}`)}return{isValid:Z.length===0,errors:Z}}generateEnvVarDocs($,J,Y={}){let{prefix:Z,format:Q="text"}=Y,G=Z||this.generateEnvPrefix($),W=[];switch(this.extractEnvVarInfo(J,[],G,W),Q){case"markdown":return this.formatAsMarkdown(W,$);case"json":return JSON.stringify(W,null,2);default:return this.formatAsText(W,$)}}extractEnvVarInfo($,J,Y,Z){for(let[Q,G]of Object.entries($)){let W=[...J,Q],z=`${Y}_${W.map((U)=>this.formatEnvKey(U,!0)).join("_")}`;if(typeof G==="object"&&G!==null&&!Array.isArray(G))this.extractEnvVarInfo(G,W,Y,Z);else Z.push({key:z,type:Array.isArray(G)?"array":typeof G,description:`Configuration for ${W.join(".")}`,example:this.generateExample(G)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,J){let Y=`Environment Variables for ${J}:
7642
7647
 
7643
7648
  `;for(let Z of $)Y+=`${Z.key}
7644
7649
  `,Y+=` Type: ${Z.type}
@@ -7650,7 +7655,7 @@ export type ConfigOf = Config
7650
7655
  `;Y+=`| Variable | Type | Description | Example |
7651
7656
  `,Y+=`|----------|------|-------------|----------|
7652
7657
  `;for(let Z of $)Y+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
7653
- `;return Y}}function vO($,J,Y={}){return I4($,J,Y,new WeakMap)}function I4($,J,Y,Z){let{arrayMergeMode:Q="replace",skipNullish:G=!1,customMerger:W}=Y;if(J===null||J===void 0)return G?$:J;if(W){let z=W($,J);if(z!==void 0)return z}if(Array.isArray(J)||Array.isArray($))return k4($,J,Q,Z);if(!v1(J)||!v1($))return J;return dO($,J,Y,Z)}function k4($,J,Y,Z){if(Array.isArray(J)&&!Array.isArray($))return J;if(Array.isArray($)&&!Array.isArray(J))return J;if(Array.isArray(J)&&Array.isArray($))switch(Y){case"replace":return J;case"concat":return fO($,J);case"smart":return gO($,J,Z);default:return J}return J}function fO($,J){let Y=[...J];for(let Z of $)if(!Y.some((Q)=>YJ(Q,Z)))Y.push(Z);return Y}function gO($,J,Y){if(J.length===0)return $;if($.length===0)return J;if(v1(J[0])&&v1($[0]))return uO($,J,Y);if(J.every((Z)=>typeof Z==="string")&&$.every((Z)=>typeof Z==="string")){let Z=[...J];for(let Q of $)if(!Z.includes(Q))Z.push(Q);return Z}return J}function uO($,J,Y){let Z=[...J];for(let Q of $){if(!v1(Q)){Z.push(Q);continue}let G=["id","name","key","path","type"],W=!1;for(let z of G)if(z in Q){if(Z.find((H)=>v1(H)&&(z in H)&&H[z]===Q[z])){W=!0;break}}if(!W)Z.push(Q)}return Z}function dO($,J,Y,Z){let Q=J;if(v1(Q)&&Z.has(Q))return Z.get(Q);let G={...$};if(v1(Q))Z.set(Q,G);for(let W in Q){if(!Object.prototype.hasOwnProperty.call(Q,W))continue;let z=Q[W],U=G[W];if(Y.skipNullish&&(z===null||z===void 0))continue;if(z===null||z===void 0){G[W]=z;continue}if(v1(z)&&v1(U))G[W]=I4(U,z,Y,Z);else if(Array.isArray(z)||Array.isArray(U))G[W]=k4(U,z,Y.arrayMergeMode||"smart",Z);else G[W]=z}return G}function h4($,J,Y="replace"){return vO($,J,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function YJ($,J){if($===J)return!0;if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return!1;for(let Y=0;Y<$.length;Y++)if(!YJ($[Y],J[Y]))return!1;return!0}if(v1($)&&v1(J)){let Y=Object.keys($),Z=Object.keys(J);if(Y.length!==Z.length)return!1;for(let Q of Y){if(!Object.prototype.hasOwnProperty.call(J,Q))return!1;if(!YJ($[Q],J[Q]))return!1}return!0}return!1}function v1($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class b4{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,J,Y={}){let{arrayStrategy:Z="replace",useCache:Q=!0,cacheTtl:G,trackPerformance:W=!0,verbose:z=!1}=Y;if(Q){let H=Z6.getWithFileCheck("file",$);if(H){if(z)console.log(`Configuration loaded from cache: ${$}`);return H}}let U=async()=>{if(!t9($))return null;try{let H=`?t=${Date.now()}`,F=await import($+H),B=F.default||F,K="default"in F,O=Object.keys(F).length>0;if(!K&&!O)throw new V6($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof B!=="object"||B===null||Array.isArray(B))throw new V6($,Error("Configuration must export a valid object"),"unknown");let _={config:h4(J,B,Z),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(Q)Z6.setWithFileCheck("file",_,$,G);return _}catch(H){throw H instanceof Error?h$.configLoad($,H):h$.configLoad($,Error(String(H)))}};if(W)return ZJ.track("loadFromPath",U,{path:$});return U()}async tryLoadFromPaths($,J,Y={}){for(let Z of $)try{let Q=await this.loadFromPath(Z,J,Y);if(Q)return Q}catch(Q){if(Q instanceof Error&&Q.name==="ConfigLoadError")throw Q;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,Q)}return null}generateConfigPaths($,J,Y){let Z=this.generateNamePatterns($,Y),Q=[];for(let G of Z)for(let W of this.extensions)Q.push(m5(J,`${G}${W}`));return Q}generateNamePatterns($,J){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);let Z=J===void 0?[]:Array.isArray(J)?J:[J];for(let G of Z){if(!G)continue;if(Y.push(G,`.${G}.config`,`${G}.config`,`.${G}`),$)Y.push(`${$}.${G}.config`,`.${$}.${G}.config`)}let Q=new Set;return Y.filter((G)=>{if(!G||Q.has(G))return!1;return Q.add(G),!0})}checkFileAccess($){return yO(async()=>{return t9($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,J,Y){let Z=[];if(!t9($))return Z;if(J||Y){let Q=this.generateNamePatterns(J||"",Y);for(let G of Q)for(let W of this.extensions){let z=m5($,`${G}${W}`);if(await this.checkFileAccess(z))Z.push(z)}}else try{let{readdirSync:Q}=await import("fs"),G=Q($);for(let W of G)if(this.looksLikeConfigFile(W)){let z=m5($,W);if(await this.checkFileAccess(z))Z.push(z)}}catch{return[]}return Z}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let J=[];try{if(!t9($))return J.push("Configuration file does not exist"),J;let Y=await import($),Z=Y.default||Y;if(Z===void 0)J.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)J.push("Configuration must be an object");else if(Array.isArray(Z))J.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:Q}=await import("fs"),G=Q($,"utf8");JSON.parse(G)}catch(Q){J.push(`Invalid JSON syntax: ${Q}`)}}catch(Y){J.push(`Failed to load configuration file: ${Y}`)}return J}async getFileModificationTime($){try{let{statSync:J}=await import("fs");return J($).mtime}catch{return null}}async preloadConfigurations($,J={}){let Y=new Map;return await Promise.allSettled($.map(async(Z)=>{try{let Q=await this.loadFromPath(Z,{},J);if(Q)Y.set(Z,Q.config)}catch(Q){if(J.verbose)console.warn(`Failed to preload ${Z}:`,Q)}})),Y}}var mO=/^https?:\/\//;class y4{async validateConfiguration($,J,Y={}){let{stopOnFirstError:Z=!1,validateRequired:Q=!0,validateTypes:G=!0,customRules:W=[],trackPerformance:z=!0,verbose:U=!1}=Y,H=async()=>{let F=[],B=[],K={stopOnFirstError:Z,validateRequired:Q,validateTypes:G,customRules:W,trackPerformance:z,verbose:U};try{if(typeof J==="string")return await this.validateWithSchemaFile($,J,K);else if(Array.isArray(J))return this.validateWithRules($,[...J,...W],K);else return this.validateWithJSONSchema($,J,K)}catch(O){return F.push({path:"",message:`Validation failed: ${O}`,rule:"system"}),{isValid:!1,errors:F,warnings:B}}};if(z)return await ZJ.track("validateConfiguration",H);return H()}async validateWithSchemaFile($,J,Y){try{if(!cO(J))throw new A6(J,[{path:"",message:"Schema file does not exist"}]);let Z=await import(J),Q=Z.default||Z;if(Array.isArray(Q))return this.validateWithRules($,Q,Y);else return this.validateWithJSONSchema($,Q,Y)}catch(Z){throw new A6(J,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema($,J,Y){let Z=[],Q=[];return this.validateObjectAgainstSchema($,J,"",Z,Q,Y),{isValid:Z.length===0,errors:Z,warnings:Q}}validateObjectAgainstSchema($,J,Y,Z,Q,G){if(G.validateTypes&&J.type){let W=Array.isArray($)?"array":typeof $,z=Array.isArray(J.type)?J.type:[J.type];if(!z.includes(W)){if(Z.push({path:Y,message:`Expected type ${z.join(" or ")}, got ${W}`,expected:z.join(" or "),actual:W,rule:"type"}),G.stopOnFirstError)return}}if(J.enum&&!J.enum.includes($)){if(Z.push({path:Y,message:`Value must be one of: ${J.enum.join(", ")}`,expected:J.enum.join(", "),actual:$,rule:"enum"}),G.stopOnFirstError)return}if(typeof $==="string"){if(J.minLength!==void 0&&$.length<J.minLength)Z.push({path:Y,message:`String length must be at least ${J.minLength}`,expected:`>= ${J.minLength}`,actual:$.length,rule:"minLength"});if(J.maxLength!==void 0&&$.length>J.maxLength)Z.push({path:Y,message:`String length must not exceed ${J.maxLength}`,expected:`<= ${J.maxLength}`,actual:$.length,rule:"maxLength"});if(J.pattern){if(!new RegExp(J.pattern).test($))Z.push({path:Y,message:`String does not match pattern ${J.pattern}`,expected:J.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(J.minimum!==void 0&&$<J.minimum)Z.push({path:Y,message:`Value must be at least ${J.minimum}`,expected:`>= ${J.minimum}`,actual:$,rule:"minimum"});if(J.maximum!==void 0&&$>J.maximum)Z.push({path:Y,message:`Value must not exceed ${J.maximum}`,expected:`<= ${J.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&J.items)for(let W=0;W<$.length;W++){let z=Y?`${Y}[${W}]`:`[${W}]`;if(this.validateObjectAgainstSchema($[W],J.items,z,Z,Q,G),G.stopOnFirstError&&Z.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let W=$;if(G.validateRequired&&J.required){for(let z of J.required)if(!(z in W)){if(Z.push({path:Y?`${Y}.${z}`:z,message:`Missing required property '${z}'`,expected:"required",rule:"required"}),G.stopOnFirstError)return}}if(J.properties){for(let[z,U]of Object.entries(J.properties))if(z in W){let H=Y?`${Y}.${z}`:z;if(this.validateObjectAgainstSchema(W[z],U,H,Z,Q,G),G.stopOnFirstError&&Z.length>0)return}}if(J.additionalProperties===!1){let z=new Set(Object.keys(J.properties||{}));for(let U of Object.keys(W))if(!z.has(U))Q.push({path:Y?`${Y}.${U}`:U,message:`Additional property '${U}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,J,Y){let Z=[],Q=[];for(let G of J)try{let W=this.getValueByPath($,G.path),z=this.validateWithRule(W,G,G.path);if(Z.push(...z),Y.stopOnFirstError&&Z.length>0)break}catch(W){Z.push({path:G.path,message:`Rule validation failed: ${W}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:Q}}validateWithRule($,J,Y){let Z=[];if(J.required&&($===void 0||$===null))return Z.push({path:Y,message:J.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if($===void 0||$===null)return Z;if(J.type){let Q=Array.isArray($)?"array":typeof $;if(Q!==J.type)Z.push({path:Y,message:J.message||`Expected type ${J.type}, got ${Q}`,expected:J.type,actual:Q,rule:"type"})}if(J.min!==void 0){let Q=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Q<J.min)Z.push({path:Y,message:J.message||`Value must be at least ${J.min}`,expected:`>= ${J.min}`,actual:Q,rule:"min"})}if(J.max!==void 0){let Q=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Q>J.max)Z.push({path:Y,message:J.message||`Value must not exceed ${J.max}`,expected:`<= ${J.max}`,actual:Q,rule:"max"})}if(J.pattern&&typeof $==="string"){if(!J.pattern.test($))Z.push({path:Y,message:J.message||`Value does not match pattern ${J.pattern}`,expected:J.pattern.toString(),actual:$,rule:"pattern"})}if(J.enum&&!J.enum.includes($))Z.push({path:Y,message:J.message||`Value must be one of: ${J.enum.join(", ")}`,expected:J.enum.join(", "),actual:$,rule:"enum"});if(J.validator){let Q=J.validator($);if(Q)Z.push({path:Y,message:J.message||Q,rule:"custom"})}return Z}getValueByPath($,J){if(!J)return $;let Y=J.split("."),Z=$;for(let Q of Y)if(Z&&typeof Z==="object"&&Q in Z)Z=Z[Q];else return;return Z}generateRulesFromInterface($){let J=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,Q,G,W]=Z;J.push({path:Q,required:!G,type:this.mapTypeScriptType(W)})}return J}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:mO},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var J2=new E6("bunfig",{showTags:!0});function lO($){if(!$)return"";let J=Array.isArray($)?$.filter(Boolean):[$];if(J.length===0)return"";if(J.length===1)return` or alias "${J[0]}"`;return` or aliases ${J.map((Y)=>`"${Y}"`).join(", ")}`}class v4{fileLoader=new b4;envProcessor=new BJ;validator=new y4;async loadConfig($){let J=Date.now(),{cache:Y,performance:Z,schema:Q,validate:G,...W}=$;try{if(Y?.enabled){let U=this.checkCache(W.name||"",W);if(U)return U}let z;try{z=await this.loadConfigurationStrategies(W,!0,Y)}catch(U){let H=W.__strictErrorHandling;if(U instanceof Error&&U.name==="ConfigNotFoundError"){if(H)throw U;z={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`No configuration file found for "${W.name||"config"}", using defaults with environment variables`]}}else if(U instanceof Error&&U.name==="ConfigLoadError"){let F=U.message.includes("EACCES")||U.message.includes("EPERM")||U.message.includes("permission denied"),B=!F&&(U.message.includes("syntax")||U.message.includes("Expected")||U.message.includes("Unexpected")||U.message.includes("BuildMessage")||U.message.includes("errors building")),K=U.message.includes("Configuration must export a valid object")||U.message.includes("Configuration file is empty and exports nothing");if(H&&(K||F))throw U;if(B&&(!H||!K))z={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!H)z={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`Configuration loading error, using defaults: ${U.message}`]};else throw U}else z={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${U instanceof Error?U.message:String(U)}`]}}if(Q||G)await this.validateConfiguration(z.config,Q,G,W.name);if(Y?.enabled&&z)this.cacheResult(W.name||"",z,Y,W);if(Z?.enabled){let U={operation:"loadConfig",duration:Date.now()-J,configName:W.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(U);if(Z.slowThreshold&&U.duration>Z.slowThreshold)J2.warn(`Slow configuration loading detected: ${U.duration}ms for ${W.name}`);z.metrics=U}return z}catch(z){if(z instanceof Error&&z.name==="ConfigNotFoundError")throw z;let U=Date.now()-J;throw J2.error(`Configuration loading failed after ${U}ms:`,[z instanceof Error?z:Error(String(z))]),z}}async loadConfigurationStrategies($,J=!1,Y){let{name:Z="",alias:Q,cwd:G,configDir:W,defaultConfig:z,checkEnv:U=!0,arrayStrategy:H="replace",verbose:F=!1}=$,B=G||_6.cwd(),K=[],O=await this.loadLocalConfiguration(Z,Q,B,W,z,H,F,U,Y);if(O)return K.push(...this.getLocalSearchPaths(Z,Q,B,W)),this.finalizeResult(O,K,U,Z,F);let A=await this.loadHomeConfiguration(Z,Q,z,H,F,U);if(A)return K.push(...this.getHomeSearchPaths(Z,Q)),this.finalizeResult(A,K,U,Z,F);let V=await this.loadPackageJsonConfiguration(Z,Q,B,z,H,F,U);if(V)return K.push(b1(B,"package.json")),this.finalizeResult(V,K,U,Z,F);if(K.push(...this.getAllSearchPaths(Z,Q,B,W)),J)throw h$.configNotFound(Z,K,Q);return{...await this.applyEnvironmentVariables(Z,z,U,F),warnings:[`No configuration file found for "${Z}"${lO(Q)}, using defaults with environment variables`]}}async loadLocalConfiguration($,J,Y,Z,Q,G,W,z,U){let H=z?s9($,Q,W):Q,F=this.getLocalDirectories(Y,Z);for(let B of F){if(W)J2.info(`Searching for configuration in: ${B}`);let K=this.fileLoader.generateConfigPaths($,B,J),O=await this.fileLoader.tryLoadFromPaths(K,H,{arrayStrategy:G,verbose:W,cacheTtl:U?.ttl,useCache:!U?.ttl||U.ttl>100});if(O){if(W)J2.success(`Configuration loaded from: ${O.source.path}`);return O}}return null}async loadHomeConfiguration($,J,Y,Z,Q,G){if(!$)return null;let W=G?s9($,Y,Q):Y,z=[b1(q$(),".config",$),b1(q$(),".config"),q$()];for(let U of z){if(Q)J2.info(`Checking home directory: ${U}`);let H=this.fileLoader.generateConfigPaths($,U,J),F=await this.fileLoader.tryLoadFromPaths(H,W,{arrayStrategy:Z,verbose:Q});if(F){if(Q)J2.success(`Configuration loaded from home directory: ${F.source.path}`);return F}}return null}async loadPackageJsonConfiguration($,J,Y,Z,Q,G,W){let z=W?s9($,Z,G):Z;try{let U=b1(Y,"package.json");if(!vB(U))return null;let H={};try{H=JSON.parse(fB(U,"utf8"))}catch(K){if(G)J2.warn("Failed to parse package.json:",[K instanceof Error?K:Error(String(K))]);return null}let F=H[$],B=$;if(!F&&J){let K=Array.isArray(J)?J:[J];for(let O of K){if(!O)continue;if(H[O]){F=H[O],B=O;break}}}if(F&&typeof F==="object"&&!Array.isArray(F)){if(G)J2.success(`Configuration loaded from package.json: ${B}`);return{config:h4(z,F,Q),source:{type:"package.json",path:U,priority:30,timestamp:new Date}}}}catch(U){if(G)J2.warn("Failed to load package.json:",[U instanceof Error?U:Error(String(U))])}return null}async applyEnvironmentVariables($,J,Y,Z){if(!Y||!$||typeof J!=="object"||J===null||Array.isArray(J))return{config:J,source:{type:"default",priority:10,timestamp:new Date}};return{config:s9($,J,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,J,Y,Z,Q){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,J,Y,Z){let Q=[];if(Y){let G=Y($);if(G)Q.push(...G)}if(J){let G=await this.validator.validateConfiguration($,J);if(!G.isValid)Q.push(...G.errors.map((W)=>W.path?`${W.path}: ${W.message}`:W.message))}if(Q.length>0)throw h$.configValidation(Z||"unknown",Q,Z)}checkCache($,J){let Y=this.generateCacheKey($,J);return Z6.get(Y)||null}cacheResult($,J,Y,Z){let Q=this.generateCacheKey($,Z);Z6.set(Q,J,void 0,Y.ttl)}generateCacheKey($,J){let Y=[$];if(J.alias){let Z=Array.isArray(J.alias)?J.alias.join(","):J.alias;Y.push(`alias:${Z}`)}if(J.cwd)Y.push(`cwd:${J.cwd}`);if(J.configDir)Y.push(`configDir:${J.configDir}`);if("checkEnv"in J)Y.push(`checkEnv:${J.checkEnv}`);return Y.join("|")}getLocalDirectories($,J){return Array.from(new Set([$,b1($,"config"),b1($,".config"),J?b1($,J):void 0].filter(Boolean)))}getAllSearchPaths($,J,Y,Z){let Q=[];return Q.push(...this.getLocalSearchPaths($,J,Y,Z)),Q.push(...this.getHomeSearchPaths($,J)),Q.push(b1(Y,"package.json")),Q}getLocalSearchPaths($,J,Y,Z){let Q=this.getLocalDirectories(Y,Z),G=[];for(let W of Q)G.push(...this.fileLoader.generateConfigPaths($,W,J));return G}getHomeSearchPaths($,J){if(!$)return[];let Y=[b1(q$(),".config",$),b1(q$(),".config"),q$()],Z=[];for(let Q of Y)Z.push(...this.fileLoader.generateConfigPaths($,Q,J));return Z}async loadConfigWithResult($){return this.loadConfig($)}}var l5=new v4;async function f4($){let J="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Z;if(Y)Z=await l5.loadConfig($);else Z=await l5.loadConfig({...$,defaultConfig:J,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??J}catch(Z){let Q=Z instanceof Error?Z.name:"UnknownError",G=Z instanceof Error?Z.message:String(Z);if(!(Q==="ConfigNotFoundError"||Q==="ConfigLoadError"||Q==="ConfigValidationError"||G.includes("config"))&&$.verbose)J2.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let z=Y?{...$,defaultConfig:J}:{...$,defaultConfig:J,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await l5.applyEnvironmentVariables(z.name||"",J,!0,z.verbose||!1))?.config??J;return J}}function s9($,J,Y=!1){let Z=new BJ,Q=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function G(W,z=[]){let U={...W};for(let[H,F]of Object.entries(W)){let B=[...z,H],K=[`${Q}_${B.join("_").toUpperCase()}`,`${Q}_${B.map((V)=>V.toUpperCase()).join("")}`,`${Q}_${B.map((V)=>V.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],O,A;for(let V of K)if(O=_6.env[V],O!==void 0){A=V;break}if(O!==void 0&&A)if(typeof F==="boolean")U[H]=["true","1","yes"].includes(O.toLowerCase());else if(typeof F==="number"){let V=Number(O);if(!Number.isNaN(V))U[H]=V}else if(Array.isArray(F))try{U[H]=JSON.parse(O)}catch{U[H]=O.split(",").map((V)=>V.trim())}else U[H]=O;else if(F&&typeof F==="object"&&!Array.isArray(F))U[H]=G(F,B)}return U}return G(J)}var iR=b1(_6.cwd(),"config"),aR=b1(_6.cwd(),"src/generated");var u4={project:{name:"my-project",slug:"my-project",region:"us-east-1"},environments:{production:{type:"production"}}},b$=null;function nO($){return $.project?.slug===u4.project?.slug&&Object.keys($.environments??{}).length===1&&!!$.environments?.production}async function iO(){let $=[g4(process.cwd(),"config","cloud.ts"),g4(process.cwd(),"config","cloud.js")];for(let J of $){if(!pO(J))continue;let Y=await import(`${rO(J).href}?t=${Date.now()}`),Z=Y.tsCloud??Y.default?.tsCloud??Y.default??Y.cloud??Y.config;if(Z)return Z}return null}async function aO(){if(!b$){if(b$=await f4({name:"cloud",defaultConfig:u4}),nO(b$))b$=await iO()??b$}return b$}var M6=aO;Y2();async function m(){let $=await M6();if(!$.project)throw Error("Missing required project configuration in cloud.config.ts");return $}function f1($){if($)switch($.toLowerCase()){case"porkbun":{let Z=process.env.PORKBUN_API_KEY,Q=process.env.PORKBUN_SECRET_KEY;if(!Z||!Q)throw Error("PORKBUN_API_KEY and PORKBUN_SECRET_KEY environment variables are required for Porkbun provider");return{provider:"porkbun",apiKey:Z,secretKey:Q}}case"godaddy":{let Z=process.env.GODADDY_API_KEY,Q=process.env.GODADDY_API_SECRET;if(!Z||!Q)throw Error("GODADDY_API_KEY and GODADDY_API_SECRET environment variables are required for GoDaddy provider");let G=process.env.GODADDY_ENVIRONMENT||"production";return{provider:"godaddy",apiKey:Z,apiSecret:Q,environment:G}}case"route53":{let Z=process.env.AWS_REGION||"us-east-1",Q=process.env.AWS_HOSTED_ZONE_ID;return{provider:"route53",region:Z,hostedZoneId:Q}}case"cloudflare":{let Z=process.env.CLOUDFLARE_API_TOKEN;if(!Z)throw Error("CLOUDFLARE_API_TOKEN environment variable is required for Cloudflare provider");return{provider:"cloudflare",apiToken:Z}}default:throw Error(`Unknown DNS provider: ${$}. Supported: porkbun, godaddy, route53, cloudflare`)}if(new E8().loadFromEnv().getAllProviders().length===0)return null;if(process.env.PORKBUN_API_KEY&&process.env.PORKBUN_SECRET_KEY)return{provider:"porkbun",apiKey:process.env.PORKBUN_API_KEY,secretKey:process.env.PORKBUN_SECRET_KEY};if(process.env.GODADDY_API_KEY&&process.env.GODADDY_API_SECRET)return{provider:"godaddy",apiKey:process.env.GODADDY_API_KEY,apiSecret:process.env.GODADDY_API_SECRET,environment:process.env.GODADDY_ENVIRONMENT||"production"};if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)return{provider:"route53",region:process.env.AWS_REGION||"us-east-1",hostedZoneId:process.env.AWS_HOSTED_ZONE_ID};if(process.env.CLOUDFLARE_API_TOKEN)return{provider:"cloudflare",apiToken:process.env.CLOUDFLARE_API_TOKEN};return null}function v2($){let J=f1($);if(!J)throw Error("No DNS provider configured. Set environment variables for Porkbun (PORKBUN_API_KEY, PORKBUN_SECRET_KEY), GoDaddy (GODADDY_API_KEY, GODADDY_API_SECRET), Cloudflare (CLOUDFLARE_API_TOKEN), or Route53 (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)");return U1(J)}function OJ($){$.command("config","Show current configuration").action(async()=>{R("Configuration");try{let J=await m();console.log(JSON.stringify(J,null,2))}catch(J){w(`Failed to load configuration: ${J instanceof Error?J.message:"Unknown error"}`)}}),$.command("config:validate","Validate configuration file").action(async()=>{R("Validating Configuration");let J=new N("Validating cloud.config.ts...");J.start();try{let Y=await m();if(!Y.project?.name)throw Error("Missing project.name");if(!Y.project?.slug)throw Error("Missing project.slug");if(!Y.mode)throw Error("Missing deployment mode");J.succeed("Configuration is valid!"),X(`Project: ${Y.project.name}`),X(`Mode: ${Y.mode}`),X(`Region: ${Y.project.region||"us-east-1"}`)}catch(Y){J.fail("Configuration is invalid"),w(Y instanceof Error?Y.message:"Unknown error")}}),$.command("config:env","Manage environment variables").option("--list","List all environment variables").option("--set <key=value>","Set an environment variable").option("--unset <key>","Remove an environment variable").option("--environment <env>","Target environment (production, staging, development)").action(async(J)=>{R("Environment Variables");let Y=J?.environment||"production";if(J?.list)X(`Environment variables for ${Y}:`),p(["Key","Value","Last Modified"],[["NODE_ENV",Y,"2024-01-15"],["API_URL","https://api.example.com","2024-01-14"],["DEBUG","false","2024-01-10"]]);else if(J?.set){let[Z,...Q]=J.set.split("="),G=Q.join("=");if(!Z||!G){w("Invalid format. Use: --set KEY=VALUE");return}let W=new N(`Setting ${Z}=${G}...`);W.start(),await new Promise((z)=>setTimeout(z,1000)),W.succeed(`Environment variable ${Z} set for ${Y}`)}else if(J?.unset){if(!await u(`Remove ${J.unset} from ${Y} environment?`,!1)){X("Operation cancelled");return}let Q=new N(`Removing ${J.unset}...`);Q.start(),await new Promise((G)=>setTimeout(G,1000)),Q.succeed(`Environment variable ${J.unset} removed`)}else X("Use --list, --set KEY=VALUE, or --unset KEY")}),$.command("config:secrets","Manage secrets (AWS Secrets Manager)").option("--list","List all secrets").option("--create <name>","Create a new secret").option("--get <name>","Get secret value").option("--update <name>","Update secret value").option("--delete <name>","Delete a secret").option("--value <value>","Secret value (for create/update)").action(async(J)=>{if(R("Secrets Manager"),J?.list)X("Secrets in AWS Secrets Manager:"),p(["Name","Last Modified","Rotation Enabled"],[["db-password","2024-01-15","Yes"],["api-key","2024-01-14","No"],["jwt-secret","2024-01-10","Yes"]]);else if(J?.create){if(!J.value){let Z=await q0("Enter secret value","");J.value=Z}let Y=new N(`Creating secret ${J.create}...`);Y.start(),await new Promise((Z)=>setTimeout(Z,1000)),Y.succeed(`Secret ${J.create} created successfully`)}else if(J?.get){let Y=new N(`Fetching secret ${J.get}...`);Y.start(),await new Promise((Z)=>setTimeout(Z,1000)),Y.succeed("Secret retrieved"),X(`${J.get}: ******* (hidden for security)`),c1("Use --show-value to display the actual value")}else if(J?.update){if(!J.value){let Z=await q0("Enter new secret value","");J.value=Z}let Y=new N(`Updating secret ${J.update}...`);Y.start(),await new Promise((Z)=>setTimeout(Z,1000)),Y.succeed(`Secret ${J.update} updated successfully`)}else if(J?.delete){if(c1("This action is irreversible!"),!await u(`Delete secret ${J.delete}?`,!1)){X("Deletion cancelled");return}let Z=new N(`Deleting secret ${J.delete}...`);Z.start(),await new Promise((Q)=>setTimeout(Q,1000)),Z.succeed(`Secret ${J.delete} deleted`)}else X("Use --list, --create, --get, --update, or --delete")})}import{existsSync as ZV}from"node:fs";import{readFile as QV,writeFile as GV}from"node:fs/promises";function w6($){let J=D6($.name),Y=VJ($.configText);if(YV($.configText,Y.start,Y.end,J))throw Error(`Site '${J}' already exists in cloud.config.ts`);let Z=JV({...$,name:J}),Q=$.configText.slice(0,Y.end).trimEnd(),G=$.configText.slice(Y.end),W=Q.endsWith("{")?`
7658
+ `;return Y}}function vO($,J,Y={}){return I4($,J,Y,new WeakMap)}function I4($,J,Y,Z){let{arrayMergeMode:Q="replace",skipNullish:G=!1,customMerger:W}=Y;if(J===null||J===void 0)return G?$:J;if(W){let z=W($,J);if(z!==void 0)return z}if(Array.isArray(J)||Array.isArray($))return k4($,J,Q,Z);if(!v1(J)||!v1($))return J;return dO($,J,Y,Z)}function k4($,J,Y,Z){if(Array.isArray(J)&&!Array.isArray($))return J;if(Array.isArray($)&&!Array.isArray(J))return J;if(Array.isArray(J)&&Array.isArray($))switch(Y){case"replace":return J;case"concat":return fO($,J);case"smart":return gO($,J,Z);default:return J}return J}function fO($,J){let Y=[...J];for(let Z of $)if(!Y.some((Q)=>YJ(Q,Z)))Y.push(Z);return Y}function gO($,J,Y){if(J.length===0)return $;if($.length===0)return J;if(v1(J[0])&&v1($[0]))return uO($,J,Y);if(J.every((Z)=>typeof Z==="string")&&$.every((Z)=>typeof Z==="string")){let Z=[...J];for(let Q of $)if(!Z.includes(Q))Z.push(Q);return Z}return J}function uO($,J,Y){let Z=[...J];for(let Q of $){if(!v1(Q)){Z.push(Q);continue}let G=["id","name","key","path","type"],W=!1;for(let z of G)if(z in Q){if(Z.find((H)=>v1(H)&&(z in H)&&H[z]===Q[z])){W=!0;break}}if(!W)Z.push(Q)}return Z}function dO($,J,Y,Z){let Q=J;if(v1(Q)&&Z.has(Q))return Z.get(Q);let G={...$};if(v1(Q))Z.set(Q,G);for(let W in Q){if(!Object.prototype.hasOwnProperty.call(Q,W))continue;let z=Q[W],U=G[W];if(Y.skipNullish&&(z===null||z===void 0))continue;if(z===null||z===void 0){G[W]=z;continue}if(v1(z)&&v1(U))G[W]=I4(U,z,Y,Z);else if(Array.isArray(z)||Array.isArray(U))G[W]=k4(U,z,Y.arrayMergeMode||"smart",Z);else G[W]=z}return G}function h4($,J,Y="replace"){return vO($,J,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function YJ($,J){if($===J)return!0;if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return!1;for(let Y=0;Y<$.length;Y++)if(!YJ($[Y],J[Y]))return!1;return!0}if(v1($)&&v1(J)){let Y=Object.keys($),Z=Object.keys(J);if(Y.length!==Z.length)return!1;for(let Q of Y){if(!Object.prototype.hasOwnProperty.call(J,Q))return!1;if(!YJ($[Q],J[Q]))return!1}return!0}return!1}function v1($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class b4{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,J,Y={}){let{arrayStrategy:Z="replace",useCache:Q=!0,cacheTtl:G,trackPerformance:W=!0,verbose:z=!1}=Y;if(Q){let H=Z6.getWithFileCheck("file",$);if(H){if(z)console.log(`Configuration loaded from cache: ${$}`);return H}}let U=async()=>{if(!t9($))return null;try{let H=`?t=${Date.now()}`,F=await import($+H),B=F.default||F,K="default"in F,O=Object.keys(F).length>0;if(!K&&!O)throw new V6($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof B!=="object"||B===null||Array.isArray(B))throw new V6($,Error("Configuration must export a valid object"),"unknown");let _={config:h4(J,B,Z),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(Q)Z6.setWithFileCheck("file",_,$,G);return _}catch(H){throw H instanceof Error?h$.configLoad($,H):h$.configLoad($,Error(String(H)))}};if(W)return ZJ.track("loadFromPath",U,{path:$});return U()}async tryLoadFromPaths($,J,Y={}){for(let Z of $)try{let Q=await this.loadFromPath(Z,J,Y);if(Q)return Q}catch(Q){if(Q instanceof Error&&Q.name==="ConfigLoadError")throw Q;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,Q)}return null}generateConfigPaths($,J,Y){let Z=this.generateNamePatterns($,Y),Q=[];for(let G of Z)for(let W of this.extensions)Q.push(m5(J,`${G}${W}`));return Q}generateNamePatterns($,J){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);let Z=J===void 0?[]:Array.isArray(J)?J:[J];for(let G of Z){if(!G)continue;if(Y.push(G,`.${G}.config`,`${G}.config`,`.${G}`),$)Y.push(`${$}.${G}.config`,`.${$}.${G}.config`)}let Q=new Set;return Y.filter((G)=>{if(!G||Q.has(G))return!1;return Q.add(G),!0})}checkFileAccess($){return yO(async()=>{return t9($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,J,Y){let Z=[];if(!t9($))return Z;if(J||Y){let Q=this.generateNamePatterns(J||"",Y);for(let G of Q)for(let W of this.extensions){let z=m5($,`${G}${W}`);if(await this.checkFileAccess(z))Z.push(z)}}else try{let{readdirSync:Q}=await import("fs"),G=Q($);for(let W of G)if(this.looksLikeConfigFile(W)){let z=m5($,W);if(await this.checkFileAccess(z))Z.push(z)}}catch{return[]}return Z}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let J=[];try{if(!t9($))return J.push("Configuration file does not exist"),J;let Y=await import($),Z=Y.default||Y;if(Z===void 0)J.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)J.push("Configuration must be an object");else if(Array.isArray(Z))J.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:Q}=await import("fs"),G=Q($,"utf8");JSON.parse(G)}catch(Q){J.push(`Invalid JSON syntax: ${Q}`)}}catch(Y){J.push(`Failed to load configuration file: ${Y}`)}return J}async getFileModificationTime($){try{let{statSync:J}=await import("fs");return J($).mtime}catch{return null}}async preloadConfigurations($,J={}){let Y=new Map;return await Promise.allSettled($.map(async(Z)=>{try{let Q=await this.loadFromPath(Z,{},J);if(Q)Y.set(Z,Q.config)}catch(Q){if(J.verbose)console.warn(`Failed to preload ${Z}:`,Q)}})),Y}}var mO=/^https?:\/\//;class y4{async validateConfiguration($,J,Y={}){let{stopOnFirstError:Z=!1,validateRequired:Q=!0,validateTypes:G=!0,customRules:W=[],trackPerformance:z=!0,verbose:U=!1}=Y,H=async()=>{let F=[],B=[],K={stopOnFirstError:Z,validateRequired:Q,validateTypes:G,customRules:W,trackPerformance:z,verbose:U};try{if(typeof J==="string")return await this.validateWithSchemaFile($,J,K);else if(Array.isArray(J))return this.validateWithRules($,[...J,...W],K);else return this.validateWithJSONSchema($,J,K)}catch(O){return F.push({path:"",message:`Validation failed: ${O}`,rule:"system"}),{isValid:!1,errors:F,warnings:B}}};if(z)return await ZJ.track("validateConfiguration",H);return H()}async validateWithSchemaFile($,J,Y){try{if(!cO(J))throw new A6(J,[{path:"",message:"Schema file does not exist"}]);let Z=await import(J),Q=Z.default||Z;if(Array.isArray(Q))return this.validateWithRules($,Q,Y);else return this.validateWithJSONSchema($,Q,Y)}catch(Z){throw new A6(J,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema($,J,Y){let Z=[],Q=[];return this.validateObjectAgainstSchema($,J,"",Z,Q,Y),{isValid:Z.length===0,errors:Z,warnings:Q}}validateObjectAgainstSchema($,J,Y,Z,Q,G){if(G.validateTypes&&J.type){let W=Array.isArray($)?"array":typeof $,z=Array.isArray(J.type)?J.type:[J.type];if(!z.includes(W)){if(Z.push({path:Y,message:`Expected type ${z.join(" or ")}, got ${W}`,expected:z.join(" or "),actual:W,rule:"type"}),G.stopOnFirstError)return}}if(J.enum&&!J.enum.includes($)){if(Z.push({path:Y,message:`Value must be one of: ${J.enum.join(", ")}`,expected:J.enum.join(", "),actual:$,rule:"enum"}),G.stopOnFirstError)return}if(typeof $==="string"){if(J.minLength!==void 0&&$.length<J.minLength)Z.push({path:Y,message:`String length must be at least ${J.minLength}`,expected:`>= ${J.minLength}`,actual:$.length,rule:"minLength"});if(J.maxLength!==void 0&&$.length>J.maxLength)Z.push({path:Y,message:`String length must not exceed ${J.maxLength}`,expected:`<= ${J.maxLength}`,actual:$.length,rule:"maxLength"});if(J.pattern){if(!new RegExp(J.pattern).test($))Z.push({path:Y,message:`String does not match pattern ${J.pattern}`,expected:J.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(J.minimum!==void 0&&$<J.minimum)Z.push({path:Y,message:`Value must be at least ${J.minimum}`,expected:`>= ${J.minimum}`,actual:$,rule:"minimum"});if(J.maximum!==void 0&&$>J.maximum)Z.push({path:Y,message:`Value must not exceed ${J.maximum}`,expected:`<= ${J.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&J.items)for(let W=0;W<$.length;W++){let z=Y?`${Y}[${W}]`:`[${W}]`;if(this.validateObjectAgainstSchema($[W],J.items,z,Z,Q,G),G.stopOnFirstError&&Z.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let W=$;if(G.validateRequired&&J.required){for(let z of J.required)if(!(z in W)){if(Z.push({path:Y?`${Y}.${z}`:z,message:`Missing required property '${z}'`,expected:"required",rule:"required"}),G.stopOnFirstError)return}}if(J.properties){for(let[z,U]of Object.entries(J.properties))if(z in W){let H=Y?`${Y}.${z}`:z;if(this.validateObjectAgainstSchema(W[z],U,H,Z,Q,G),G.stopOnFirstError&&Z.length>0)return}}if(J.additionalProperties===!1){let z=new Set(Object.keys(J.properties||{}));for(let U of Object.keys(W))if(!z.has(U))Q.push({path:Y?`${Y}.${U}`:U,message:`Additional property '${U}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,J,Y){let Z=[],Q=[];for(let G of J)try{let W=this.getValueByPath($,G.path),z=this.validateWithRule(W,G,G.path);if(Z.push(...z),Y.stopOnFirstError&&Z.length>0)break}catch(W){Z.push({path:G.path,message:`Rule validation failed: ${W}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:Q}}validateWithRule($,J,Y){let Z=[];if(J.required&&($===void 0||$===null))return Z.push({path:Y,message:J.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if($===void 0||$===null)return Z;if(J.type){let Q=Array.isArray($)?"array":typeof $;if(Q!==J.type)Z.push({path:Y,message:J.message||`Expected type ${J.type}, got ${Q}`,expected:J.type,actual:Q,rule:"type"})}if(J.min!==void 0){let Q=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Q<J.min)Z.push({path:Y,message:J.message||`Value must be at least ${J.min}`,expected:`>= ${J.min}`,actual:Q,rule:"min"})}if(J.max!==void 0){let Q=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Q>J.max)Z.push({path:Y,message:J.message||`Value must not exceed ${J.max}`,expected:`<= ${J.max}`,actual:Q,rule:"max"})}if(J.pattern&&typeof $==="string"){if(!J.pattern.test($))Z.push({path:Y,message:J.message||`Value does not match pattern ${J.pattern}`,expected:J.pattern.toString(),actual:$,rule:"pattern"})}if(J.enum&&!J.enum.includes($))Z.push({path:Y,message:J.message||`Value must be one of: ${J.enum.join(", ")}`,expected:J.enum.join(", "),actual:$,rule:"enum"});if(J.validator){let Q=J.validator($);if(Q)Z.push({path:Y,message:J.message||Q,rule:"custom"})}return Z}getValueByPath($,J){if(!J)return $;let Y=J.split("."),Z=$;for(let Q of Y)if(Z&&typeof Z==="object"&&Q in Z)Z=Z[Q];else return;return Z}generateRulesFromInterface($){let J=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,Q,G,W]=Z;J.push({path:Q,required:!G,type:this.mapTypeScriptType(W)})}return J}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:mO},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var J2=new E6("bunfig",{showTags:!0});function lO($){if(!$)return"";let J=Array.isArray($)?$.filter(Boolean):[$];if(J.length===0)return"";if(J.length===1)return` or alias "${J[0]}"`;return` or aliases ${J.map((Y)=>`"${Y}"`).join(", ")}`}class v4{fileLoader=new b4;envProcessor=new BJ;validator=new y4;async loadConfig($){let J=Date.now(),{cache:Y,performance:Z,schema:Q,validate:G,...W}=$;try{if(Y?.enabled){let U=this.checkCache(W.name||"",W);if(U)return U}let z;try{z=await this.loadConfigurationStrategies(W,!0,Y)}catch(U){let H=W.__strictErrorHandling;if(U instanceof Error&&U.name==="ConfigNotFoundError"){if(H)throw U;z={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`No configuration file found for "${W.name||"config"}", using defaults with environment variables`]}}else if(U instanceof Error&&U.name==="ConfigLoadError"){let F=U.message.includes("EACCES")||U.message.includes("EPERM")||U.message.includes("permission denied"),B=!F&&(U.message.includes("syntax")||U.message.includes("Expected")||U.message.includes("Unexpected")||U.message.includes("BuildMessage")||U.message.includes("errors building")),K=U.message.includes("Configuration must export a valid object")||U.message.includes("Configuration file is empty and exports nothing");if(H&&(K||F))throw U;if(B&&(!H||!K))z={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!H)z={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`Configuration loading error, using defaults: ${U.message}`]};else throw U}else z={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${U instanceof Error?U.message:String(U)}`]}}if(Q||G)await this.validateConfiguration(z.config,Q,G,W.name);if(Y?.enabled&&z)this.cacheResult(W.name||"",z,Y,W);if(Z?.enabled){let U={operation:"loadConfig",duration:Date.now()-J,configName:W.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(U);if(Z.slowThreshold&&U.duration>Z.slowThreshold)J2.warn(`Slow configuration loading detected: ${U.duration}ms for ${W.name}`);z.metrics=U}return z}catch(z){if(z instanceof Error&&z.name==="ConfigNotFoundError")throw z;let U=Date.now()-J;throw J2.error(`Configuration loading failed after ${U}ms:`,[z instanceof Error?z:Error(String(z))]),z}}async loadConfigurationStrategies($,J=!1,Y){let{name:Z="",alias:Q,cwd:G,configDir:W,defaultConfig:z,checkEnv:U=!0,arrayStrategy:H="replace",verbose:F=!1}=$,B=G||_6.cwd(),K=[],O=await this.loadLocalConfiguration(Z,Q,B,W,z,H,F,U,Y);if(O)return K.push(...this.getLocalSearchPaths(Z,Q,B,W)),this.finalizeResult(O,K,U,Z,F);let A=await this.loadHomeConfiguration(Z,Q,z,H,F,U);if(A)return K.push(...this.getHomeSearchPaths(Z,Q)),this.finalizeResult(A,K,U,Z,F);let V=await this.loadPackageJsonConfiguration(Z,Q,B,z,H,F,U);if(V)return K.push(b1(B,"package.json")),this.finalizeResult(V,K,U,Z,F);if(K.push(...this.getAllSearchPaths(Z,Q,B,W)),J)throw h$.configNotFound(Z,K,Q);return{...await this.applyEnvironmentVariables(Z,z,U,F),warnings:[`No configuration file found for "${Z}"${lO(Q)}, using defaults with environment variables`]}}async loadLocalConfiguration($,J,Y,Z,Q,G,W,z,U){let H=z?s9($,Q,W):Q,F=this.getLocalDirectories(Y,Z);for(let B of F){if(W)J2.info(`Searching for configuration in: ${B}`);let K=this.fileLoader.generateConfigPaths($,B,J),O=await this.fileLoader.tryLoadFromPaths(K,H,{arrayStrategy:G,verbose:W,cacheTtl:U?.ttl,useCache:!U?.ttl||U.ttl>100});if(O){if(W)J2.success(`Configuration loaded from: ${O.source.path}`);return O}}return null}async loadHomeConfiguration($,J,Y,Z,Q,G){if(!$)return null;let W=G?s9($,Y,Q):Y,z=[b1(q$(),".config",$),b1(q$(),".config"),q$()];for(let U of z){if(Q)J2.info(`Checking home directory: ${U}`);let H=this.fileLoader.generateConfigPaths($,U,J),F=await this.fileLoader.tryLoadFromPaths(H,W,{arrayStrategy:Z,verbose:Q});if(F){if(Q)J2.success(`Configuration loaded from home directory: ${F.source.path}`);return F}}return null}async loadPackageJsonConfiguration($,J,Y,Z,Q,G,W){let z=W?s9($,Z,G):Z;try{let U=b1(Y,"package.json");if(!vB(U))return null;let H={};try{H=JSON.parse(fB(U,"utf8"))}catch(K){if(G)J2.warn("Failed to parse package.json:",[K instanceof Error?K:Error(String(K))]);return null}let F=H[$],B=$;if(!F&&J){let K=Array.isArray(J)?J:[J];for(let O of K){if(!O)continue;if(H[O]){F=H[O],B=O;break}}}if(F&&typeof F==="object"&&!Array.isArray(F)){if(G)J2.success(`Configuration loaded from package.json: ${B}`);return{config:h4(z,F,Q),source:{type:"package.json",path:U,priority:30,timestamp:new Date}}}}catch(U){if(G)J2.warn("Failed to load package.json:",[U instanceof Error?U:Error(String(U))])}return null}async applyEnvironmentVariables($,J,Y,Z){if(!Y||!$||typeof J!=="object"||J===null||Array.isArray(J))return{config:J,source:{type:"default",priority:10,timestamp:new Date}};return{config:s9($,J,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,J,Y,Z,Q){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,J,Y,Z){let Q=[];if(Y){let G=Y($);if(G)Q.push(...G)}if(J){let G=await this.validator.validateConfiguration($,J);if(!G.isValid)Q.push(...G.errors.map((W)=>W.path?`${W.path}: ${W.message}`:W.message))}if(Q.length>0)throw h$.configValidation(Z||"unknown",Q,Z)}checkCache($,J){let Y=this.generateCacheKey($,J);return Z6.get(Y)||null}cacheResult($,J,Y,Z){let Q=this.generateCacheKey($,Z);Z6.set(Q,J,void 0,Y.ttl)}generateCacheKey($,J){let Y=[$];if(J.alias){let Z=Array.isArray(J.alias)?J.alias.join(","):J.alias;Y.push(`alias:${Z}`)}if(J.cwd)Y.push(`cwd:${J.cwd}`);if(J.configDir)Y.push(`configDir:${J.configDir}`);if("checkEnv"in J)Y.push(`checkEnv:${J.checkEnv}`);return Y.join("|")}getLocalDirectories($,J){return Array.from(new Set([$,b1($,"config"),b1($,".config"),J?b1($,J):void 0].filter(Boolean)))}getAllSearchPaths($,J,Y,Z){let Q=[];return Q.push(...this.getLocalSearchPaths($,J,Y,Z)),Q.push(...this.getHomeSearchPaths($,J)),Q.push(b1(Y,"package.json")),Q}getLocalSearchPaths($,J,Y,Z){let Q=this.getLocalDirectories(Y,Z),G=[];for(let W of Q)G.push(...this.fileLoader.generateConfigPaths($,W,J));return G}getHomeSearchPaths($,J){if(!$)return[];let Y=[b1(q$(),".config",$),b1(q$(),".config"),q$()],Z=[];for(let Q of Y)Z.push(...this.fileLoader.generateConfigPaths($,Q,J));return Z}async loadConfigWithResult($){return this.loadConfig($)}}var l5=new v4;async function f4($){let J="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Z;if(Y)Z=await l5.loadConfig($);else Z=await l5.loadConfig({...$,defaultConfig:J,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??J}catch(Z){let Q=Z instanceof Error?Z.name:"UnknownError",G=Z instanceof Error?Z.message:String(Z);if(!(Q==="ConfigNotFoundError"||Q==="ConfigLoadError"||Q==="ConfigValidationError"||G.includes("config"))&&$.verbose)J2.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let z=Y?{...$,defaultConfig:J}:{...$,defaultConfig:J,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await l5.applyEnvironmentVariables(z.name||"",J,!0,z.verbose||!1))?.config??J;return J}}function s9($,J,Y=!1){let Z=new BJ,Q=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function G(W,z=[]){let U={...W};for(let[H,F]of Object.entries(W)){let B=[...z,H],K=[`${Q}_${B.join("_").toUpperCase()}`,`${Q}_${B.map((V)=>V.toUpperCase()).join("")}`,`${Q}_${B.map((V)=>V.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],O,A;for(let V of K)if(O=_6.env[V],O!==void 0){A=V;break}if(O!==void 0&&A)if(typeof F==="boolean")U[H]=["true","1","yes"].includes(O.toLowerCase());else if(typeof F==="number"){let V=Number(O);if(!Number.isNaN(V))U[H]=V}else if(Array.isArray(F))try{U[H]=JSON.parse(O)}catch{U[H]=O.split(",").map((V)=>V.trim())}else U[H]=O;else if(F&&typeof F==="object"&&!Array.isArray(F))U[H]=G(F,B)}return U}return G(J)}var nR=b1(_6.cwd(),"config"),iR=b1(_6.cwd(),"src/generated");var u4={project:{name:"my-project",slug:"my-project",region:"us-east-1"},environments:{production:{type:"production"}}},b$=null;function nO($){return $.project?.slug===u4.project?.slug&&Object.keys($.environments??{}).length===1&&!!$.environments?.production}async function iO(){let $=[g4(process.cwd(),"config","cloud.ts"),g4(process.cwd(),"config","cloud.js")];for(let J of $){if(!pO(J))continue;let Y=await import(`${rO(J).href}?t=${Date.now()}`),Z=Y.tsCloud??Y.default?.tsCloud??Y.default??Y.cloud??Y.config;if(Z)return Z}return null}async function aO(){if(!b$){if(b$=await f4({name:"cloud",defaultConfig:u4}),nO(b$))b$=await iO()??b$}return b$}var M6=aO;Y2();async function m(){let $=await M6();if(!$.project)throw Error("Missing required project configuration in cloud.config.ts");return $}function f1($){if($)switch($.toLowerCase()){case"porkbun":{let Z=process.env.PORKBUN_API_KEY,Q=process.env.PORKBUN_SECRET_KEY;if(!Z||!Q)throw Error("PORKBUN_API_KEY and PORKBUN_SECRET_KEY environment variables are required for Porkbun provider");return{provider:"porkbun",apiKey:Z,secretKey:Q}}case"godaddy":{let Z=process.env.GODADDY_API_KEY,Q=process.env.GODADDY_API_SECRET;if(!Z||!Q)throw Error("GODADDY_API_KEY and GODADDY_API_SECRET environment variables are required for GoDaddy provider");let G=process.env.GODADDY_ENVIRONMENT||"production";return{provider:"godaddy",apiKey:Z,apiSecret:Q,environment:G}}case"route53":{let Z=process.env.AWS_REGION||"us-east-1",Q=process.env.AWS_HOSTED_ZONE_ID;return{provider:"route53",region:Z,hostedZoneId:Q}}case"cloudflare":{let Z=process.env.CLOUDFLARE_API_TOKEN;if(!Z)throw Error("CLOUDFLARE_API_TOKEN environment variable is required for Cloudflare provider");return{provider:"cloudflare",apiToken:Z}}default:throw Error(`Unknown DNS provider: ${$}. Supported: porkbun, godaddy, route53, cloudflare`)}if(new E8().loadFromEnv().getAllProviders().length===0)return null;if(process.env.PORKBUN_API_KEY&&process.env.PORKBUN_SECRET_KEY)return{provider:"porkbun",apiKey:process.env.PORKBUN_API_KEY,secretKey:process.env.PORKBUN_SECRET_KEY};if(process.env.GODADDY_API_KEY&&process.env.GODADDY_API_SECRET)return{provider:"godaddy",apiKey:process.env.GODADDY_API_KEY,apiSecret:process.env.GODADDY_API_SECRET,environment:process.env.GODADDY_ENVIRONMENT||"production"};if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)return{provider:"route53",region:process.env.AWS_REGION||"us-east-1",hostedZoneId:process.env.AWS_HOSTED_ZONE_ID};if(process.env.CLOUDFLARE_API_TOKEN)return{provider:"cloudflare",apiToken:process.env.CLOUDFLARE_API_TOKEN};return null}function v2($){let J=f1($);if(!J)throw Error("No DNS provider configured. Set environment variables for Porkbun (PORKBUN_API_KEY, PORKBUN_SECRET_KEY), GoDaddy (GODADDY_API_KEY, GODADDY_API_SECRET), Cloudflare (CLOUDFLARE_API_TOKEN), or Route53 (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)");return U1(J)}function OJ($){$.command("config","Show current configuration").action(async()=>{R("Configuration");try{let J=await m();console.log(JSON.stringify(J,null,2))}catch(J){w(`Failed to load configuration: ${J instanceof Error?J.message:"Unknown error"}`)}}),$.command("config:validate","Validate configuration file").action(async()=>{R("Validating Configuration");let J=new N("Validating cloud.config.ts...");J.start();try{let Y=await m();if(!Y.project?.name)throw Error("Missing project.name");if(!Y.project?.slug)throw Error("Missing project.slug");if(!Y.mode)throw Error("Missing deployment mode");J.succeed("Configuration is valid!"),X(`Project: ${Y.project.name}`),X(`Mode: ${Y.mode}`),X(`Region: ${Y.project.region||"us-east-1"}`)}catch(Y){J.fail("Configuration is invalid"),w(Y instanceof Error?Y.message:"Unknown error")}}),$.command("config:env","Manage environment variables").option("--list","List all environment variables").option("--set <key=value>","Set an environment variable").option("--unset <key>","Remove an environment variable").option("--environment <env>","Target environment (production, staging, development)").action(async(J)=>{R("Environment Variables");let Y=J?.environment||"production";if(J?.list)X(`Environment variables for ${Y}:`),p(["Key","Value","Last Modified"],[["NODE_ENV",Y,"2024-01-15"],["API_URL","https://api.example.com","2024-01-14"],["DEBUG","false","2024-01-10"]]);else if(J?.set){let[Z,...Q]=J.set.split("="),G=Q.join("=");if(!Z||!G){w("Invalid format. Use: --set KEY=VALUE");return}let W=new N(`Setting ${Z}=${G}...`);W.start(),await new Promise((z)=>setTimeout(z,1000)),W.succeed(`Environment variable ${Z} set for ${Y}`)}else if(J?.unset){if(!await u(`Remove ${J.unset} from ${Y} environment?`,!1)){X("Operation cancelled");return}let Q=new N(`Removing ${J.unset}...`);Q.start(),await new Promise((G)=>setTimeout(G,1000)),Q.succeed(`Environment variable ${J.unset} removed`)}else X("Use --list, --set KEY=VALUE, or --unset KEY")}),$.command("config:secrets","Manage secrets (AWS Secrets Manager)").option("--list","List all secrets").option("--create <name>","Create a new secret").option("--get <name>","Get secret value").option("--update <name>","Update secret value").option("--delete <name>","Delete a secret").option("--value <value>","Secret value (for create/update)").action(async(J)=>{if(R("Secrets Manager"),J?.list)X("Secrets in AWS Secrets Manager:"),p(["Name","Last Modified","Rotation Enabled"],[["db-password","2024-01-15","Yes"],["api-key","2024-01-14","No"],["jwt-secret","2024-01-10","Yes"]]);else if(J?.create){if(!J.value){let Z=await q0("Enter secret value","");J.value=Z}let Y=new N(`Creating secret ${J.create}...`);Y.start(),await new Promise((Z)=>setTimeout(Z,1000)),Y.succeed(`Secret ${J.create} created successfully`)}else if(J?.get){let Y=new N(`Fetching secret ${J.get}...`);Y.start(),await new Promise((Z)=>setTimeout(Z,1000)),Y.succeed("Secret retrieved"),X(`${J.get}: ******* (hidden for security)`),c1("Use --show-value to display the actual value")}else if(J?.update){if(!J.value){let Z=await q0("Enter new secret value","");J.value=Z}let Y=new N(`Updating secret ${J.update}...`);Y.start(),await new Promise((Z)=>setTimeout(Z,1000)),Y.succeed(`Secret ${J.update} updated successfully`)}else if(J?.delete){if(c1("This action is irreversible!"),!await u(`Delete secret ${J.delete}?`,!1)){X("Deletion cancelled");return}let Z=new N(`Deleting secret ${J.delete}...`);Z.start(),await new Promise((Q)=>setTimeout(Q,1000)),Z.succeed(`Secret ${J.delete} deleted`)}else X("Use --list, --create, --get, --update, or --delete")})}import{existsSync as ZV}from"node:fs";import{readFile as QV,writeFile as GV}from"node:fs/promises";function w6($){let J=D6($.name),Y=VJ($.configText);if(YV($.configText,Y.start,Y.end,J))throw Error(`Site '${J}' already exists in cloud.config.ts`);let Z=JV({...$,name:J}),Q=$.configText.slice(0,Y.end).trimEnd(),G=$.configText.slice(Y.end),W=Q.endsWith("{")?`
7654
7659
  `:Q.endsWith(",")?`
7655
7660
 
7656
7661
  `:`,
@@ -8029,21 +8034,21 @@ Add this team member?`,!0)){X("Operation cancelled");return}let G=new N("Creatin
8029
8034
  Team member added!`),X("An invitation email has been sent with access credentials"),X(`
8030
8035
  Access Details:`),X(` - Email: ${J}`),X(` - Role: ${Y}`),X(" - Status: Pending")}),$.command("team:list","List team members").action(async()=>{R("Team Members");let J=new N("Fetching team members...");J.start(),await new Promise((Y)=>setTimeout(Y,1500)),J.stop(),p(["Email","Role","Status","Added","Last Login"],[["admin@example.com","Admin","Active","2024-01-01","2 hours ago"],["dev@example.com","Developer","Active","2024-01-15","1 day ago"],["viewer@example.com","Viewer","Active","2024-02-01","3 days ago"],["new@example.com","Developer","Pending","2024-11-10","Never"]]),X("\nTip: Use `cloud team:add` to add new team members"),X("Tip: Use `cloud team:remove` to remove team members")}),$.command("team:remove <email>","Remove team member").action(async(J)=>{if(R("Removing Team Member"),X(`Email: ${J}`),v(`
8031
8036
  This will revoke all access for this team member`),!await u("Remove this team member?",!1)){X("Operation cancelled");return}let Z=new N("Removing IAM user and access...");Z.start(),await new Promise((Q)=>setTimeout(Q,2000)),Z.succeed("Team member removed successfully"),h(`
8032
- Team member removed!`),X("All access credentials have been revoked")})}z0();import{existsSync as x1,writeFileSync as H3,copyFileSync as N9,readFileSync as GG,mkdirSync as F3}from"node:fs";import{dirname as X3}from"node:path";M1();I0();U2();e6();Y0();class H7{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async describeServices($){let J={cluster:$.cluster,services:$.services};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeServices","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listServices($){let J={cluster:$};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListServices","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listTasks($,J){let Y={cluster:$};if(J)Y.serviceName=J;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListTasks","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(Y)})}async describeTasks($,J){let Y={cluster:$,tasks:J};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeTasks","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(Y)})}async updateService($){let J={cluster:$.cluster,service:$.service};if($.forceNewDeployment!==void 0)J.forceNewDeployment=$.forceNewDeployment;if($.desiredCount!==void 0)J.desiredCount=$.desiredCount;if($.taskDefinition)J.taskDefinition=$.taskDefinition;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.UpdateService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async createService($){let J={cluster:$.cluster,serviceName:$.serviceName,taskDefinition:$.taskDefinition,desiredCount:$.desiredCount};if($.launchType)J.launchType=$.launchType;if($.networkConfiguration)J.networkConfiguration=$.networkConfiguration;if($.loadBalancers)J.loadBalancers=$.loadBalancers;if($.healthCheckGracePeriodSeconds!==void 0)J.healthCheckGracePeriodSeconds=$.healthCheckGracePeriodSeconds;if($.deploymentConfiguration)J.deploymentConfiguration=$.deploymentConfiguration;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.CreateService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async deleteService($){let J={cluster:$.cluster,service:$.service};if($.force!==void 0)J.force=$.force;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DeleteService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listClusters(){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListClusters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({})})}async describeClusters($){let J={clusters:$,include:["ATTACHMENTS","CONFIGURATIONS","SETTINGS","STATISTICS","TAGS"]};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeClusters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async stopTask($){let J={cluster:$.cluster,task:$.task};if($.reason)J.reason=$.reason;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.StopTask","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async runTask($){let J={cluster:$.cluster,taskDefinition:$.taskDefinition};if($.count!==void 0)J.count=$.count;if($.launchType)J.launchType=$.launchType;if($.networkConfiguration)J.networkConfiguration=$.networkConfiguration;if($.overrides)J.overrides=$.overrides;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.RunTask","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async registerTaskDefinition($){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.RegisterTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify($)})}async deregisterTaskDefinition($){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DeregisterTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({taskDefinition:$})})}async describeTaskDefinition($){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({taskDefinition:$,include:["TAGS"]})})}async listTaskDefinitionFamilies($){let J={};if($?.familyPrefix)J.familyPrefix=$.familyPrefix;if($?.status)J.status=$.status;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListTaskDefinitionFamilies","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async waitForServiceStable($,J,Y=40,Z=15000){for(let Q=0;Q<Y;Q++){let W=(await this.describeServices({cluster:$,services:[J]})).services?.[0];if(W){let z=W.deployments?.find((U)=>U.status==="PRIMARY");if(z&&z.runningCount===z.desiredCount&&W.deployments?.length===1)return!0}await new Promise((z)=>setTimeout(z,Z))}return!1}async forceNewDeployment($,J){return this.updateService({cluster:$,service:J,forceNewDeployment:!0})}async scaleService($,J,Y){return this.updateService({cluster:$,service:J,desiredCount:Y})}}F7();Y0();import{execSync as WG}from"node:child_process";import{tmpdir as B3}from"node:os";import{join as K3}from"node:path";J9();Y2();import{existsSync as Wq,readdirSync as zq,readFileSync as Uq,statSync as Hq}from"node:fs";import{join as Fq,relative as Xq,extname as Bq}from"node:path";var Kq=[{name:"AWS Access Key ID",pattern:/(?:^|[^A-Z0-9])((AKIA|ABIA|ACCA|ASIA)[A-Z0-9]{16})(?:[^A-Z0-9]|$)/g,severity:"critical",description:"AWS Access Key ID detected"},{name:"AWS Secret Access Key",pattern:/(?:aws_secret_access_key|aws_secret_key|secret_access_key|secretAccessKey)\s*[=:]\s*['"]?([A-Za-z0-9/+=]{40})['"]?/gi,severity:"critical",description:"AWS Secret Access Key detected"},{name:"AWS Secret Key (Generic)",pattern:/(?:^|['"`:=\s])([A-Za-z0-9/+=]{40})(?:['"`\s]|$)/g,severity:"high",description:"Potential AWS Secret Key (40-char base64)"},{name:"Generic API Key",pattern:/(?:api[_-]?key|apikey|api[_-]?secret)\s*[=:]\s*['"]?([A-Za-z0-9_\-]{20,})['"]?/gi,severity:"high",description:"Generic API key detected"},{name:"RSA Private Key",pattern:/-----BEGIN RSA PRIVATE KEY-----/g,severity:"critical",description:"RSA private key detected"},{name:"OpenSSH Private Key",pattern:/-----BEGIN OPENSSH PRIVATE KEY-----/g,severity:"critical",description:"OpenSSH private key detected"},{name:"EC Private Key",pattern:/-----BEGIN EC PRIVATE KEY-----/g,severity:"critical",description:"EC private key detected"},{name:"PGP Private Key",pattern:/-----BEGIN PGP PRIVATE KEY BLOCK-----/g,severity:"critical",description:"PGP private key detected"},{name:"GitHub Token",pattern:/(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,}/g,severity:"critical",description:"GitHub personal access token detected"},{name:"GitHub OAuth",pattern:/github[_-]?oauth[_-]?token\s*[=:]\s*['"]?([A-Za-z0-9_]{40})['"]?/gi,severity:"critical",description:"GitHub OAuth token detected"},{name:"Slack Token",pattern:/xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*/g,severity:"critical",description:"Slack token detected"},{name:"Slack Webhook",pattern:/https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]+/g,severity:"high",description:"Slack webhook URL detected"},{name:"Discord Webhook",pattern:/https:\/\/discord(?:app)?\.com\/api\/webhooks\/[0-9]+\/[A-Za-z0-9_-]+/g,severity:"high",description:"Discord webhook URL detected"},{name:"JWT Token",pattern:/eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*/g,severity:"high",description:"JWT token detected"},{name:"Google API Key",pattern:/AIza[0-9A-Za-z_-]{35}/g,severity:"critical",description:"Google API key detected"},{name:"Google OAuth ID",pattern:/[0-9]+-[A-Za-z0-9_]{32}\.apps\.googleusercontent\.com/g,severity:"high",description:"Google OAuth client ID detected"},{name:"Firebase API Key",pattern:/(?:firebase[_-]?api[_-]?key)\s*[=:]\s*['"]?([A-Za-z0-9_-]{39})['"]?/gi,severity:"critical",description:"Firebase API key detected"},{name:"Cloudflare API Token",pattern:/(?:cloudflare[_-]?api[_-]?token|cf[_-]?api[_-]?token)\s*[=:]\s*['"]?([A-Za-z0-9_-]{40})['"]?/gi,severity:"critical",description:"Cloudflare API token detected"},{name:"Azure Client Secret",pattern:/(?:azure[_-]?client[_-]?secret|client[_-]?secret)\s*[=:]\s*['"]?([A-Za-z0-9~._-]{34,})['"]?/gi,severity:"critical",description:"Azure client secret detected"},{name:"Heroku API Key",pattern:/(?:heroku[_-]?api[_-]?key)\s*[=:]\s*['"]?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})['"]?/gi,severity:"critical",description:"Heroku API key detected"},{name:"Database Connection String",pattern:/(?:mysql|postgres|postgresql|mongodb|redis|mongodb\+srv):\/\/[^:]+:[^@]+@[^/\s]+/gi,severity:"critical",description:"Database connection string with credentials detected"},{name:"Database Password",pattern:/(?:db[_-]?password|database[_-]?password|mysql[_-]?password|postgres[_-]?password)\s*[=:]\s*['"]?([^'"\s]{8,})['"]?/gi,severity:"critical",description:"Database password detected"},{name:"Stripe API Key",pattern:/(?:sk|pk)_(?:test|live)_[0-9a-zA-Z]{24,}/g,severity:"critical",description:"Stripe API key detected"},{name:"PayPal Client ID",pattern:/(?:paypal[_-]?client[_-]?id)\s*[=:]\s*['"]?([A-Za-z0-9_-]{80})['"]?/gi,severity:"high",description:"PayPal client ID detected"},{name:"Square Access Token",pattern:/sq0[a-z]{3}-[0-9A-Za-z_-]{22,}/g,severity:"critical",description:"Square access token detected"},{name:"Twilio API Key",pattern:/SK[a-f0-9]{32}/g,severity:"critical",description:"Twilio API key detected"},{name:"SendGrid API Key",pattern:/SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}/g,severity:"critical",description:"SendGrid API key detected"},{name:"Mailgun API Key",pattern:/key-[0-9a-zA-Z]{32}/g,severity:"critical",description:"Mailgun API key detected"},{name:"Password in Code",pattern:/(?:password|passwd|pwd)\s*[=:]\s*['"]([^'"]{8,})['"](?!\s*[,\]])/gi,severity:"high",description:"Hardcoded password detected"},{name:"Secret/Token Assignment",pattern:/(?:secret|token|auth[_-]?token|access[_-]?token)\s*[=:]\s*['"]([A-Za-z0-9_\-/+=]{16,})['"](?!\s*[,\]])/gi,severity:"high",description:"Hardcoded secret or token detected"},{name:"NPM Token",pattern:/(?:npm[_-]?token)\s*[=:]\s*['"]?([A-Za-z0-9_-]{36})['"]?/gi,severity:"critical",description:"NPM token detected"},{name:"SSH Private Key Path Exposed",pattern:/~\/\.ssh\/id_[a-z]+|\/home\/[^/]+\/\.ssh\/id_[a-z]+/g,severity:"medium",description:"SSH private key path exposed"},{name:"Env Variable with Secret",pattern:/(?:process\.env\.)((?=[A-Z_]*(?:SECRET|KEY|TOKEN|PASSWORD|CREDENTIAL|AUTH))[A-Z_]+)\s*(?:===?\s*['"]([^'"]+)['"])?/g,severity:"medium",description:"Environment variable containing secret may be exposed"}],Oq=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".vue",".svelte",".html",".htm",".css",".scss",".less",".json",".yaml",".yml",".toml",".xml",".env",".config",".conf"],Vq=["node_modules",".git",".svn",".hg","dist","build","coverage",".nyc_output","__pycache__",".pytest_cache","vendor",".idea",".vscode",".turbo",".next",".nuxt","pantry",".pantry","tests","test","__tests__","spec","__mocks__",".github",".gitlab",".circleci"],Aq=["package-lock.json","yarn.lock","pnpm-lock.yaml","bun.lockb","bun.lock","*.min.js","*.min.css","*.map","*.d.ts","*.test.ts","*.test.js","*.spec.ts","*.spec.js",".env",".env.*"];class YQ{patterns;excludeDirs;excludeFiles;maxFileSize;constructor($){this.patterns=[...Kq,...$?.customPatterns||[]],this.excludeDirs=[...Vq,...$?.excludeDirs||[]],this.excludeFiles=[...Aq,...$?.excludeFiles||[]],this.maxFileSize=$?.maxFileSize||1048576}async scan($){let J=Date.now(),Y=[],Z=0,{directory:Q,exclude:G=[],include:W,skipPatterns:z=[]}=$,U=$.failOnSeverity||"critical";if(!Wq(Q))throw Error(`Directory not found: ${Q}`);let H=this.getFilesToScan(Q,[...this.excludeDirs,...G],W);for(let A of H){let V=Xq(Q,A);if(this.shouldExcludeFile(V))continue;try{if(Hq(A).size>this.maxFileSize)continue;let E=Uq(A,"utf-8"),M=this.scanContent(E,V,z);Y.push(...M),Z++}catch{continue}}let F={critical:Y.filter((A)=>A.pattern.severity==="critical").length,high:Y.filter((A)=>A.pattern.severity==="high").length,medium:Y.filter((A)=>A.pattern.severity==="medium").length,low:Y.filter((A)=>A.pattern.severity==="low").length},B=["low","medium","high","critical"],K=B.indexOf(U),O=!0;for(let A=K;A<B.length;A++)if(F[B[A]]>0){O=!1;break}return{passed:O,findings:Y,scannedFiles:Z,duration:Date.now()-J,summary:F}}scanContent($,J,Y){let Z=[],Q=$.split(`
8037
+ Team member removed!`),X("All access credentials have been revoked")})}z0();import{existsSync as x1,writeFileSync as U3,copyFileSync as N9,readFileSync as GG,mkdirSync as H3}from"node:fs";import{dirname as F3}from"node:path";M1();I0();U2();e6();Y0();class H7{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async describeServices($){let J={cluster:$.cluster,services:$.services};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeServices","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listServices($){let J={cluster:$};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListServices","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listTasks($,J){let Y={cluster:$};if(J)Y.serviceName=J;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListTasks","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(Y)})}async describeTasks($,J){let Y={cluster:$,tasks:J};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeTasks","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(Y)})}async updateService($){let J={cluster:$.cluster,service:$.service};if($.forceNewDeployment!==void 0)J.forceNewDeployment=$.forceNewDeployment;if($.desiredCount!==void 0)J.desiredCount=$.desiredCount;if($.taskDefinition)J.taskDefinition=$.taskDefinition;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.UpdateService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async createService($){let J={cluster:$.cluster,serviceName:$.serviceName,taskDefinition:$.taskDefinition,desiredCount:$.desiredCount};if($.launchType)J.launchType=$.launchType;if($.networkConfiguration)J.networkConfiguration=$.networkConfiguration;if($.loadBalancers)J.loadBalancers=$.loadBalancers;if($.healthCheckGracePeriodSeconds!==void 0)J.healthCheckGracePeriodSeconds=$.healthCheckGracePeriodSeconds;if($.deploymentConfiguration)J.deploymentConfiguration=$.deploymentConfiguration;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.CreateService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async deleteService($){let J={cluster:$.cluster,service:$.service};if($.force!==void 0)J.force=$.force;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DeleteService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listClusters(){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListClusters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({})})}async describeClusters($){let J={clusters:$,include:["ATTACHMENTS","CONFIGURATIONS","SETTINGS","STATISTICS","TAGS"]};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeClusters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async stopTask($){let J={cluster:$.cluster,task:$.task};if($.reason)J.reason=$.reason;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.StopTask","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async runTask($){let J={cluster:$.cluster,taskDefinition:$.taskDefinition};if($.count!==void 0)J.count=$.count;if($.launchType)J.launchType=$.launchType;if($.networkConfiguration)J.networkConfiguration=$.networkConfiguration;if($.overrides)J.overrides=$.overrides;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.RunTask","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async registerTaskDefinition($){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.RegisterTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify($)})}async deregisterTaskDefinition($){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DeregisterTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({taskDefinition:$})})}async describeTaskDefinition($){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({taskDefinition:$,include:["TAGS"]})})}async listTaskDefinitionFamilies($){let J={};if($?.familyPrefix)J.familyPrefix=$.familyPrefix;if($?.status)J.status=$.status;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListTaskDefinitionFamilies","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async waitForServiceStable($,J,Y=40,Z=15000){for(let Q=0;Q<Y;Q++){let W=(await this.describeServices({cluster:$,services:[J]})).services?.[0];if(W){let z=W.deployments?.find((U)=>U.status==="PRIMARY");if(z&&z.runningCount===z.desiredCount&&W.deployments?.length===1)return!0}await new Promise((z)=>setTimeout(z,Z))}return!1}async forceNewDeployment($,J){return this.updateService({cluster:$,service:J,forceNewDeployment:!0})}async scaleService($,J,Y){return this.updateService({cluster:$,service:J,desiredCount:Y})}}F7();Y0();import{execSync as WG}from"node:child_process";import{tmpdir as X3}from"node:os";import{join as B3}from"node:path";J9();Y2();import{existsSync as Wq,readdirSync as zq,readFileSync as Uq,statSync as Hq}from"node:fs";import{join as Fq,relative as Xq,extname as Bq}from"node:path";var Kq=[{name:"AWS Access Key ID",pattern:/(?:^|[^A-Z0-9])((AKIA|ABIA|ACCA|ASIA)[A-Z0-9]{16})(?:[^A-Z0-9]|$)/g,severity:"critical",description:"AWS Access Key ID detected"},{name:"AWS Secret Access Key",pattern:/(?:aws_secret_access_key|aws_secret_key|secret_access_key|secretAccessKey)\s*[=:]\s*['"]?([A-Za-z0-9/+=]{40})['"]?/gi,severity:"critical",description:"AWS Secret Access Key detected"},{name:"AWS Secret Key (Generic)",pattern:/(?:^|['"`:=\s])([A-Za-z0-9/+=]{40})(?:['"`\s]|$)/g,severity:"high",description:"Potential AWS Secret Key (40-char base64)"},{name:"Generic API Key",pattern:/(?:api[_-]?key|apikey|api[_-]?secret)\s*[=:]\s*['"]?([A-Za-z0-9_\-]{20,})['"]?/gi,severity:"high",description:"Generic API key detected"},{name:"RSA Private Key",pattern:/-----BEGIN RSA PRIVATE KEY-----/g,severity:"critical",description:"RSA private key detected"},{name:"OpenSSH Private Key",pattern:/-----BEGIN OPENSSH PRIVATE KEY-----/g,severity:"critical",description:"OpenSSH private key detected"},{name:"EC Private Key",pattern:/-----BEGIN EC PRIVATE KEY-----/g,severity:"critical",description:"EC private key detected"},{name:"PGP Private Key",pattern:/-----BEGIN PGP PRIVATE KEY BLOCK-----/g,severity:"critical",description:"PGP private key detected"},{name:"GitHub Token",pattern:/(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,}/g,severity:"critical",description:"GitHub personal access token detected"},{name:"GitHub OAuth",pattern:/github[_-]?oauth[_-]?token\s*[=:]\s*['"]?([A-Za-z0-9_]{40})['"]?/gi,severity:"critical",description:"GitHub OAuth token detected"},{name:"Slack Token",pattern:/xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*/g,severity:"critical",description:"Slack token detected"},{name:"Slack Webhook",pattern:/https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]+/g,severity:"high",description:"Slack webhook URL detected"},{name:"Discord Webhook",pattern:/https:\/\/discord(?:app)?\.com\/api\/webhooks\/[0-9]+\/[A-Za-z0-9_-]+/g,severity:"high",description:"Discord webhook URL detected"},{name:"JWT Token",pattern:/eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*/g,severity:"high",description:"JWT token detected"},{name:"Google API Key",pattern:/AIza[0-9A-Za-z_-]{35}/g,severity:"critical",description:"Google API key detected"},{name:"Google OAuth ID",pattern:/[0-9]+-[A-Za-z0-9_]{32}\.apps\.googleusercontent\.com/g,severity:"high",description:"Google OAuth client ID detected"},{name:"Firebase API Key",pattern:/(?:firebase[_-]?api[_-]?key)\s*[=:]\s*['"]?([A-Za-z0-9_-]{39})['"]?/gi,severity:"critical",description:"Firebase API key detected"},{name:"Cloudflare API Token",pattern:/(?:cloudflare[_-]?api[_-]?token|cf[_-]?api[_-]?token)\s*[=:]\s*['"]?([A-Za-z0-9_-]{40})['"]?/gi,severity:"critical",description:"Cloudflare API token detected"},{name:"Azure Client Secret",pattern:/(?:azure[_-]?client[_-]?secret|client[_-]?secret)\s*[=:]\s*['"]?([A-Za-z0-9~._-]{34,})['"]?/gi,severity:"critical",description:"Azure client secret detected"},{name:"Heroku API Key",pattern:/(?:heroku[_-]?api[_-]?key)\s*[=:]\s*['"]?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})['"]?/gi,severity:"critical",description:"Heroku API key detected"},{name:"Database Connection String",pattern:/(?:mysql|postgres|postgresql|mongodb|redis|mongodb\+srv):\/\/[^:]+:[^@]+@[^/\s]+/gi,severity:"critical",description:"Database connection string with credentials detected"},{name:"Database Password",pattern:/(?:db[_-]?password|database[_-]?password|mysql[_-]?password|postgres[_-]?password)\s*[=:]\s*['"]?([^'"\s]{8,})['"]?/gi,severity:"critical",description:"Database password detected"},{name:"Stripe API Key",pattern:/(?:sk|pk)_(?:test|live)_[0-9a-zA-Z]{24,}/g,severity:"critical",description:"Stripe API key detected"},{name:"PayPal Client ID",pattern:/(?:paypal[_-]?client[_-]?id)\s*[=:]\s*['"]?([A-Za-z0-9_-]{80})['"]?/gi,severity:"high",description:"PayPal client ID detected"},{name:"Square Access Token",pattern:/sq0[a-z]{3}-[0-9A-Za-z_-]{22,}/g,severity:"critical",description:"Square access token detected"},{name:"Twilio API Key",pattern:/SK[a-f0-9]{32}/g,severity:"critical",description:"Twilio API key detected"},{name:"SendGrid API Key",pattern:/SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}/g,severity:"critical",description:"SendGrid API key detected"},{name:"Mailgun API Key",pattern:/key-[0-9a-zA-Z]{32}/g,severity:"critical",description:"Mailgun API key detected"},{name:"Password in Code",pattern:/(?:password|passwd|pwd)\s*[=:]\s*['"]([^'"]{8,})['"](?!\s*[,\]])/gi,severity:"high",description:"Hardcoded password detected"},{name:"Secret/Token Assignment",pattern:/(?:secret|token|auth[_-]?token|access[_-]?token)\s*[=:]\s*['"]([A-Za-z0-9_\-/+=]{16,})['"](?!\s*[,\]])/gi,severity:"high",description:"Hardcoded secret or token detected"},{name:"NPM Token",pattern:/(?:npm[_-]?token)\s*[=:]\s*['"]?([A-Za-z0-9_-]{36})['"]?/gi,severity:"critical",description:"NPM token detected"},{name:"SSH Private Key Path Exposed",pattern:/~\/\.ssh\/id_[a-z]+|\/home\/[^/]+\/\.ssh\/id_[a-z]+/g,severity:"medium",description:"SSH private key path exposed"},{name:"Env Variable with Secret",pattern:/(?:process\.env\.)((?=[A-Z_]*(?:SECRET|KEY|TOKEN|PASSWORD|CREDENTIAL|AUTH))[A-Z_]+)\s*(?:===?\s*['"]([^'"]+)['"])?/g,severity:"medium",description:"Environment variable containing secret may be exposed"}],Oq=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".vue",".svelte",".html",".htm",".css",".scss",".less",".json",".yaml",".yml",".toml",".xml",".env",".config",".conf"],Vq=["node_modules",".git",".svn",".hg","dist","build","coverage",".nyc_output","__pycache__",".pytest_cache","vendor",".idea",".vscode",".turbo",".next",".nuxt","pantry",".pantry","tests","test","__tests__","spec","__mocks__",".github",".gitlab",".circleci"],Aq=["package-lock.json","yarn.lock","pnpm-lock.yaml","bun.lockb","bun.lock","*.min.js","*.min.css","*.map","*.d.ts","*.test.ts","*.test.js","*.spec.ts","*.spec.js",".env",".env.*"];class YQ{patterns;excludeDirs;excludeFiles;maxFileSize;constructor($){this.patterns=[...Kq,...$?.customPatterns||[]],this.excludeDirs=[...Vq,...$?.excludeDirs||[]],this.excludeFiles=[...Aq,...$?.excludeFiles||[]],this.maxFileSize=$?.maxFileSize||1048576}async scan($){let J=Date.now(),Y=[],Z=0,{directory:Q,exclude:G=[],include:W,skipPatterns:z=[]}=$,U=$.failOnSeverity||"critical";if(!Wq(Q))throw Error(`Directory not found: ${Q}`);let H=this.getFilesToScan(Q,[...this.excludeDirs,...G],W);for(let A of H){let V=Xq(Q,A);if(this.shouldExcludeFile(V))continue;try{if(Hq(A).size>this.maxFileSize)continue;let E=Uq(A,"utf-8"),M=this.scanContent(E,V,z);Y.push(...M),Z++}catch{continue}}let F={critical:Y.filter((A)=>A.pattern.severity==="critical").length,high:Y.filter((A)=>A.pattern.severity==="high").length,medium:Y.filter((A)=>A.pattern.severity==="medium").length,low:Y.filter((A)=>A.pattern.severity==="low").length},B=["low","medium","high","critical"],K=B.indexOf(U),O=!0;for(let A=K;A<B.length;A++)if(F[B[A]]>0){O=!1;break}return{passed:O,findings:Y,scannedFiles:Z,duration:Date.now()-J,summary:F}}scanContent($,J,Y){let Z=[],Q=$.split(`
8033
8038
  `);for(let G of this.patterns){if(Y.includes(G.name))continue;G.pattern.lastIndex=0;let W;while((W=G.pattern.exec($))!==null){let z=$.substring(0,W.index),U=z.split(`
8034
8039
  `).length,H=z.lastIndexOf(`
8035
- `),F=W.index-H,B=Q[U-1]||"";if(this.isLikelyPlaceholder(W[0],B))continue;if(this.isLowEntropy(W[1]||W[0]))continue;Z.push({file:J,line:U,column:F,match:this.maskSecret(W[0]),pattern:G,context:this.maskSecret(B.trim())})}}return Z}isLikelyPlaceholder($,J){let Y=["example","placeholder","your_","YOUR_","xxx","XXX","***","test","TEST","dummy","DUMMY","fake","FAKE","sample","SAMPLE","<your","${","{{","process.env","import.meta.env","CHANGEME","TODO","FIXME"],Z=$.toLowerCase(),Q=J.toLowerCase();for(let W of Y)if(Z.includes(W.toLowerCase())||Q.includes(W.toLowerCase()))return!0;let G=J.trim();if(G.startsWith("//")||G.startsWith("#")||G.startsWith("*")||G.startsWith("/*")){if(Q.includes("example")||Q.includes("format:")||Q.includes("e.g."))return!0}return!1}isLowEntropy($){if($.length<8)return!1;if(new Set($).size<8)return!0;if(/(.)\1{3,}/.test($))return!0;return!1}maskSecret($){if($.length<=8)return"*".repeat($.length);let J=Math.min(4,Math.floor($.length*0.2));return $.substring(0,J)+"*".repeat($.length-J*2)+$.substring($.length-J)}getFilesToScan($,J,Y){let Z=[],Q=Y||Oq,G=(W)=>{let z=zq(W,{withFileTypes:!0});for(let U of z){let H=Fq(W,U.name);if(U.isDirectory()){if(!J.includes(U.name))G(H)}else if(U.isFile()){let F=Bq(U.name).toLowerCase();if(Q.includes(F)||U.name.startsWith(".env")||U.name.endsWith(".config"))Z.push(H)}}};return G($),Z}shouldExcludeFile($){let J=$.split("/").pop()||"";for(let Y of this.excludeFiles)if(Y.startsWith("*")){let Z=Y.substring(1);if(J.endsWith(Z))return!0}else if(Y.endsWith("*")){let Z=Y.substring(0,Y.length-1);if(J.startsWith(Z))return!0}else if(J===Y)return!0;return!1}addPattern($){this.patterns.push($)}getPatterns(){return[...this.patterns]}}U2();z0();function _q($){if(!$)return[];if(Array.isArray($))return $.map(String);let J=$,Y=J.Items??J.Item;if(!Y)return[];if(Array.isArray(Y))return Y.map(String);if(typeof Y==="object"&&Y!==null){let Z=Y;if("Item"in Z){let Q=Z.Item;if(!Q)return[];return Array.isArray(Q)?Q.map(String):[String(Q)]}if("CNAME"in Z){let Q=Z.CNAME;if(!Q)return[];return Array.isArray(Q)?Q.map(String):[String(Q)]}return Object.values(Z).flatMap((Q)=>{if(Array.isArray(Q))return Q.map(String);return typeof Q==="string"?[Q]:[]})}return[String(Y)]}async function O7($){if($.length===0)return;let J=new T0,Y=await J.listDistributions(),Z=[...new Set($.map((Q)=>Q.toLowerCase()))];for(let Q of Z){let G=Y.find((z)=>{return _q(z.Aliases).some((H)=>H.toLowerCase()===Q)});if(!G?.Id){v(`No CloudFront distribution found for ${Q} — skipping dynamic HTTP method sync`);continue}if(await J.ensureDynamicHttpMethods(G.Id))h(`CloudFront ${G.Id} (${Q}): enabled POST/PUT/PATCH/DELETE on dynamic paths`);else X(`CloudFront ${G.Id} (${Q}): already allows dynamic HTTP methods`)}}await z8([n0(),j$(),mQ()]);import{execSync as CT}from"node:child_process";async function xT($,J,Y,Z={},Q=process.cwd()){if(!$)return;if(Z.step?.(`Running ${Y} hook`),typeof $==="string"){CT($,{stdio:"inherit",cwd:Q});return}await $(J)}async function q9($,J,Y={},Z){try{return await xT($.hooks?.[J],$,J,Y,Z),!0}catch(Q){return Y.error?.(`${J} hook failed: ${Q?.message||Q}`),!1}}O$();async function O3($){let J=_5();if(J.emptyEnvKey||J.emptyEnvSecret)v("Empty AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY env var detected — likely a misconfigured .env file. Remove the empty lines or fill them in.");X(`AWS credentials: ${J.description}`);try{let Z=await new e8($).getCallerIdentity();if(Z.Arn)X(`AWS identity: ${Z.Arn}`)}catch(Y){v(`Could not verify AWS identity: ${Y.message}`)}}function V3(){try{return WG("git rev-parse --short HEAD",{stdio:["ignore","pipe","ignore"]}).toString().trim()}catch{return Date.now().toString(36)}}async function QG($,J,Y){let{ensureManagementDashboard:Z}=await d7().then(() => iH);Z($,{logger:{info:X,warn:v}});let Q=$.sites||{},G=Object.entries(Q);if(G.length===0)return v("infrastructure.compute is set but no sites are configured — nothing to deploy. Add sites to `cloud.config.ts`."),!0;let W=G.filter(([V,_])=>{if(!_)return!1;if(p0(_)==="bucket")return v(`Site '${V}' targets a bucket — skipping compute deploy (handled by the static-site path).`),!1;return!0});if(W.length===0)return!0;let z=$.project.slug,H=($.infrastructure?.compute||{}).runtime||"bun",F=Y1({config:$}),B=V3(),K=new Map,O={step:(V)=>n(V),error:(V)=>w(V)};if(!await q9($,"beforeDeploy",O))return!0;if(!await q9($,"beforeBuild",O))return!0;for(let[V,_]of W){let E=p0(_);if(R(`Preparing site: ${V}`),X(`Domain: ${_.domain||"(none)"}`),X(`Source: ${_.root}`),X(`Kind: ${E==="server-static"?"static (shipped to /var/www)":"app (systemd service)"}`),E==="server-app")X(`Start: ${_.start}`),X(`Port: ${_.port??"(unset)"}`);if(_.build){n(`Running build: ${_.build}`);try{WG(_.build,{stdio:"inherit",cwd:process.cwd()})}catch(j){return w(`Build failed for site '${V}': ${j.message}`),!0}}if(!x1(_.root))return w(`Build output not found at ${_.root} for site '${V}'`),!0;let M=K3(B3(),`${z}-${V}-${B}.tar.gz`);n(`Packaging ${_.root} → ${M}`);try{let j=(_.exclude||[]).map((q)=>`--exclude='${q}'`).join(" ");WG(`tar czf "${M}" -C "${_.root}" ${j} .`,{stdio:"inherit"})}catch(j){return w(`Failed to package '${V}': ${j.message}`),!0}K.set(V,M)}if(!await q9($,"afterBuild",O))return!0;let A=await p7({config:$,environment:J,driver:F,sha:B,runtime:H,tarballForSite:(V)=>{let _=K.get(V);if(!_)throw Error(`Missing tarball for site '${V}'`);return _},logger:{info:(V)=>X(V),warn:(V)=>v(V),error:(V)=>w(V),step:(V)=>n(V),success:(V)=>h(V)}});if(A)await q9($,"afterDeploy",O);return A}async function t7($){let J=new YQ;n("Running pre-deployment security scan...");let Y=await J.scan({directory:$.sourceDir,failOnSeverity:$.failOnSeverity||"critical",skipPatterns:$.skipPatterns});return{passed:Y.passed,result:Y}}function s7($){let{summary:J,findings:Y,scannedFiles:Z,duration:Q}=$;if(X(`
8040
+ `),F=W.index-H,B=Q[U-1]||"";if(this.isLikelyPlaceholder(W[0],B))continue;if(this.isLowEntropy(W[1]||W[0]))continue;Z.push({file:J,line:U,column:F,match:this.maskSecret(W[0]),pattern:G,context:this.maskSecret(B.trim())})}}return Z}isLikelyPlaceholder($,J){let Y=["example","placeholder","your_","YOUR_","xxx","XXX","***","test","TEST","dummy","DUMMY","fake","FAKE","sample","SAMPLE","<your","${","{{","process.env","import.meta.env","CHANGEME","TODO","FIXME"],Z=$.toLowerCase(),Q=J.toLowerCase();for(let W of Y)if(Z.includes(W.toLowerCase())||Q.includes(W.toLowerCase()))return!0;let G=J.trim();if(G.startsWith("//")||G.startsWith("#")||G.startsWith("*")||G.startsWith("/*")){if(Q.includes("example")||Q.includes("format:")||Q.includes("e.g."))return!0}return!1}isLowEntropy($){if($.length<8)return!1;if(new Set($).size<8)return!0;if(/(.)\1{3,}/.test($))return!0;return!1}maskSecret($){if($.length<=8)return"*".repeat($.length);let J=Math.min(4,Math.floor($.length*0.2));return $.substring(0,J)+"*".repeat($.length-J*2)+$.substring($.length-J)}getFilesToScan($,J,Y){let Z=[],Q=Y||Oq,G=(W)=>{let z=zq(W,{withFileTypes:!0});for(let U of z){let H=Fq(W,U.name);if(U.isDirectory()){if(!J.includes(U.name))G(H)}else if(U.isFile()){let F=Bq(U.name).toLowerCase();if(Q.includes(F)||U.name.startsWith(".env")||U.name.endsWith(".config"))Z.push(H)}}};return G($),Z}shouldExcludeFile($){let J=$.split("/").pop()||"";for(let Y of this.excludeFiles)if(Y.startsWith("*")){let Z=Y.substring(1);if(J.endsWith(Z))return!0}else if(Y.endsWith("*")){let Z=Y.substring(0,Y.length-1);if(J.startsWith(Z))return!0}else if(J===Y)return!0;return!1}addPattern($){this.patterns.push($)}getPatterns(){return[...this.patterns]}}U2();z0();function _q($){if(!$)return[];if(Array.isArray($))return $.map(String);let J=$,Y=J.Items??J.Item;if(!Y)return[];if(Array.isArray(Y))return Y.map(String);if(typeof Y==="object"&&Y!==null){let Z=Y;if("Item"in Z){let Q=Z.Item;if(!Q)return[];return Array.isArray(Q)?Q.map(String):[String(Q)]}if("CNAME"in Z){let Q=Z.CNAME;if(!Q)return[];return Array.isArray(Q)?Q.map(String):[String(Q)]}return Object.values(Z).flatMap((Q)=>{if(Array.isArray(Q))return Q.map(String);return typeof Q==="string"?[Q]:[]})}return[String(Y)]}async function O7($){if($.length===0)return;let J=new T0,Y=await J.listDistributions(),Z=[...new Set($.map((Q)=>Q.toLowerCase()))];for(let Q of Z){let G=Y.find((z)=>{return _q(z.Aliases).some((H)=>H.toLowerCase()===Q)});if(!G?.Id){v(`No CloudFront distribution found for ${Q} — skipping dynamic HTTP method sync`);continue}if(await J.ensureDynamicHttpMethods(G.Id))h(`CloudFront ${G.Id} (${Q}): enabled POST/PUT/PATCH/DELETE on dynamic paths`);else X(`CloudFront ${G.Id} (${Q}): already allows dynamic HTTP methods`)}}await z8([n0(),j$(),mQ()]);import{execSync as PT}from"node:child_process";async function CT($,J,Y,Z={},Q=process.cwd()){if(!$)return;if(Z.step?.(`Running ${Y} hook`),typeof $==="string"){PT($,{stdio:"inherit",cwd:Q});return}await $(J)}async function q9($,J,Y={},Z){try{return await CT($.hooks?.[J],$,J,Y,Z),!0}catch(Q){return Y.error?.(`${J} hook failed: ${Q?.message||Q}`),!1}}O$();async function K3($){let J=_5();if(J.emptyEnvKey||J.emptyEnvSecret)v("Empty AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY env var detected — likely a misconfigured .env file. Remove the empty lines or fill them in.");X(`AWS credentials: ${J.description}`);try{let Z=await new e8($).getCallerIdentity();if(Z.Arn)X(`AWS identity: ${Z.Arn}`)}catch(Y){v(`Could not verify AWS identity: ${Y.message}`)}}function O3(){try{return WG("git rev-parse --short HEAD",{stdio:["ignore","pipe","ignore"]}).toString().trim()}catch{return Date.now().toString(36)}}async function QG($,J,Y){let{ensureManagementDashboard:Z}=await d7().then(() => iH);Z($,{logger:{info:X,warn:v}});let Q=$.sites||{},G=Object.entries(Q);if(G.length===0)return v("infrastructure.compute is set but no sites are configured — nothing to deploy. Add sites to `cloud.config.ts`."),!0;let W=G.filter(([V,_])=>{if(!_)return!1;if(p0(_)==="bucket")return v(`Site '${V}' targets a bucket — skipping compute deploy (handled by the static-site path).`),!1;return!0});if(W.length===0)return!0;let z=$.project.slug,H=($.infrastructure?.compute||{}).runtime||"bun",F=Y1({config:$}),B=O3(),K=new Map,O={step:(V)=>n(V),error:(V)=>w(V)};if(!await q9($,"beforeDeploy",O))return!0;if(!await q9($,"beforeBuild",O))return!0;for(let[V,_]of W){let E=p0(_);if(R(`Preparing site: ${V}`),X(`Domain: ${_.domain||"(none)"}`),X(`Source: ${_.root}`),X(`Kind: ${E==="server-static"?"static (shipped to /var/www)":"app (systemd service)"}`),E==="server-app")X(`Start: ${_.start}`),X(`Port: ${_.port??"(unset)"}`);if(_.build){n(`Running build: ${_.build}`);try{WG(_.build,{stdio:"inherit",cwd:process.cwd()})}catch(j){return w(`Build failed for site '${V}': ${j.message}`),!0}}if(!x1(_.root))return w(`Build output not found at ${_.root} for site '${V}'`),!0;let M=B3(X3(),`${z}-${V}-${B}.tar.gz`);n(`Packaging ${_.root} → ${M}`);try{let j=(_.exclude||[]).map((q)=>`--exclude='${q}'`).join(" ");WG(`tar czf "${M}" -C "${_.root}" ${j} .`,{stdio:"inherit"})}catch(j){return w(`Failed to package '${V}': ${j.message}`),!0}K.set(V,M)}if(!await q9($,"afterBuild",O))return!0;let A=await p7({config:$,environment:J,driver:F,sha:B,runtime:H,tarballForSite:(V)=>{let _=K.get(V);if(!_)throw Error(`Missing tarball for site '${V}'`);return _},logger:{info:(V)=>X(V),warn:(V)=>v(V),error:(V)=>w(V),step:(V)=>n(V),success:(V)=>h(V)}});if(A)await q9($,"afterDeploy",O);return A}async function t7($){let J=new YQ;n("Running pre-deployment security scan...");let Y=await J.scan({directory:$.sourceDir,failOnSeverity:$.failOnSeverity||"critical",skipPatterns:$.skipPatterns});return{passed:Y.passed,result:Y}}function s7($){let{summary:J,findings:Y,scannedFiles:Z,duration:Q}=$;if(X(`
8036
8041
  Scanned ${Z} files in ${Q}ms`),J.critical>0)w(` Critical: ${J.critical}`);else X(` Critical: ${J.critical}`);if(J.high>0)v(` High: ${J.high}`);else X(` High: ${J.high}`);if(X(` Medium: ${J.medium}`),X(` Low: ${J.low}`),Y.length>0){X(`
8037
8042
  Findings:`);let G=Y.filter((F)=>F.pattern.severity==="critical"),W=Y.filter((F)=>F.pattern.severity==="high"),z=Y.filter((F)=>F.pattern.severity==="medium"),U=Y.filter((F)=>F.pattern.severity==="low"),H=(F,B,K)=>{if(F.length>0){console.log(`
8038
8043
  ${h2(`[${B}]`,K)}`);for(let O of F.slice(0,10))X(` ${O.pattern.name}`),X(` File: ${O.file}:${O.line}`),X(` Match: ${O.match}`);if(F.length>10)X(` ... and ${F.length-10} more ${B.toLowerCase()} findings`)}};H(G,"CRITICAL","red"),H(W,"HIGH","yellow"),H(z,"MEDIUM","blue"),H(U,"LOW","gray")}}function zG($){$.command("deploy:security-scan","Run pre-deployment security scan").option("--source <path>","Source directory to scan",{default:"."}).option("--fail-on <severity>","Fail on severity level (critical, high, medium, low)",{default:"critical"}).option("--skip-patterns <patterns>","Comma-separated list of pattern names to skip").action(async(J)=>{R("Pre-Deployment Security Scan");try{let Y=J?.source||".",Z=J?.failOn||"critical",Q=J?.skipPatterns?.split(",").map((z)=>z.trim())||[];if(!x1(Y)){w(`Source directory not found: ${Y}`);return}X(`Source: ${Y}`),X(`Fail on: ${Z} or higher severity`);let{passed:G,result:W}=await t7({sourceDir:Y,failOnSeverity:Z,skipPatterns:Q});if(s7(W),G)h(`
8039
8044
  ✓ Security scan passed - no blocking issues found`);else w(`
8040
8045
  ✗ Security scan failed - blocking issues detected`),X(`
8041
- Recommendations:`),X(" 1. Remove any hardcoded credentials from your code"),X(" 2. Use environment variables or AWS Secrets Manager"),X(" 3. Add sensitive files to .gitignore"),X(" 4. Use --skip-patterns to ignore false positives"),process.exit(1)}catch(Y){w(`Security scan failed: ${Y.message}`),process.exit(1)}}),$.command("deploy","Deploy infrastructure").option("--stack <name>","Stack name").option("--env <environment>","Environment to deploy to").option("--site <name>","Deploy specific site only").option("--skip-security-scan","Skip pre-deployment security scan").option("--skip-dns-verification","Skip DNS provider verification and record creation (use when DNS is already configured)").option("--security-fail-on <severity>","Security scan fail threshold (critical, high, medium, low)",{default:"critical"}).option("--yes","Skip confirmation prompts (non-interactive / CI)").action(async(J)=>{R("Deploying Infrastructure");let Y=J?.yes===!0||process.env.CI==="true",Z=J?.env||"staging",Q=null;Q=await A3(Z);try{let G=await m(),{errors:W,warnings:z}=_Q(G);for(let d of z)v(d);if(W.length>0){w(`
8042
- ✗ Deployment configuration is invalid:`);for(let d of W)w(` • ${d}`);return}let U=G.project?.region||"us-east-1";if(await O3(U),!J?.skipSecurityScan){let d=process.cwd(),{passed:g,result:s}=await t7({sourceDir:d,failOnSeverity:J?.securityFailOn||"critical"});if(s7(s),!g){w(`
8046
+ Recommendations:`),X(" 1. Remove any hardcoded credentials from your code"),X(" 2. Use environment variables or AWS Secrets Manager"),X(" 3. Add sensitive files to .gitignore"),X(" 4. Use --skip-patterns to ignore false positives"),process.exit(1)}catch(Y){w(`Security scan failed: ${Y.message}`),process.exit(1)}}),$.command("deploy","Deploy infrastructure").option("--stack <name>","Stack name").option("--env <environment>","Environment to deploy to").option("--site <name>","Deploy specific site only").option("--skip-security-scan","Skip pre-deployment security scan").option("--skip-dns-verification","Skip DNS provider verification and record creation (use when DNS is already configured)").option("--security-fail-on <severity>","Security scan fail threshold (critical, high, medium, low)",{default:"critical"}).option("--yes","Skip confirmation prompts (non-interactive / CI)").action(async(J)=>{R("Deploying Infrastructure");let Y=J?.yes===!0||process.env.CI==="true",Z=J?.env||"staging",Q=null;Q=await V3(Z);try{let G=await m(),{errors:W,warnings:z}=_Q(G);for(let d of z)v(d);if(W.length>0){w(`
8047
+ ✗ Deployment configuration is invalid:`);for(let d of W)w(` • ${d}`);return}let U=G.project?.region||"us-east-1";if(await K3(U),!J?.skipSecurityScan){let d=process.cwd(),{passed:g,result:s}=await t7({sourceDir:d,failOnSeverity:J?.securityFailOn||"critical"});if(s7(s),!g){w(`
8043
8048
  ✗ Security scan failed - deployment blocked`),X(`
8044
8049
  To proceed anyway, use --skip-security-scan flag`),X("To change sensitivity, use --security-fail-on <severity>");return}h(`✓ Security scan passed
8045
8050
  `)}else v(`Security scan skipped (--skip-security-scan)
8046
- `);let H=J?.stack||E1(G,Z),F=G.project.region||"us-east-1",B=G.infrastructure?.deployStack!==!1,K=G.sites&&Object.keys(G.sites).length>0,O=G.infrastructure?.dns?.provider;if(K&&O){if(await _3(G,J?.site,O,F,J?.skipDnsVerification,Z,Y),!B){if(G.infrastructure?.compute){let d=Object.values(G.sites).map((g)=>g.domain).filter((g)=>!!g);if(d.length>0)n("Syncing CloudFront dynamic HTTP methods for app domains..."),await O7(d)}return}}if(!B){X("Infrastructure stack deployment disabled (infrastructure.deployStack: false)");return}let A=q2(G);if(X(`Cloud provider: ${A}`),X(`Stack: ${H}`),X(`Region: ${F}`),X(`Environment: ${Z}`),(A==="hetzner"||G.infrastructure?.compute?.mode==="server")&&G.infrastructure?.compute){n(`Provisioning ${A} compute infrastructure...`);let d=Y1({config:G,provider:A});if(!d.provisionComputeInfrastructure){w(`${A} driver does not support compute provisioning`);return}let g=await d.provisionComputeInfrastructure({config:G,environment:Z});if(h(`${A} compute infrastructure ready`),g.appPublicIp)X(`App server: ${g.appPublicIp}`);if(g.appInstanceId)X(`Server ID: ${g.appInstanceId}`);if(!await QG(G,Z,F))w(`App deploy to ${A} compute reported a failure`);else h(`App deployed to ${A} compute`);return}n("Generating CloudFormation template...");let _=new c$({config:G,environment:Z});_.generate();let E=_.toJSON(),M=JSON.parse(E);if(Object.keys(M.Resources||{}).length===0){X(`No infrastructure resources to deploy for environment '${Z}' — skipping stack ${H}.`);return}n("Validating template...");let q=p8(M),T=r8(E),D=n8(M),S=[...q.errors,...T.errors,...D.errors];if(S.length>0){w("Template validation failed:");for(let d of S)w(` - ${d.path}: ${d.message}`);return}let P=[...q.warnings,...T.warnings,...D.warnings];if(P.length>0)for(let d of P)v(` - ${d.path}: ${d.message}`);h("Template validated successfully");let C=Object.keys(M.Resources).length;X(`
8051
+ `);let H=J?.stack||E1(G,Z),F=G.project.region||"us-east-1",B=G.infrastructure?.deployStack!==!1,K=G.sites&&Object.keys(G.sites).length>0,O=G.infrastructure?.dns?.provider;if(K&&O){if(await A3(G,J?.site,O,F,J?.skipDnsVerification,Z,Y),!B){if(G.infrastructure?.compute){let d=Object.values(G.sites).map((g)=>g.domain).filter((g)=>!!g);if(d.length>0)n("Syncing CloudFront dynamic HTTP methods for app domains..."),await O7(d)}return}}if(!B){X("Infrastructure stack deployment disabled (infrastructure.deployStack: false)");return}let A=q2(G);if(X(`Cloud provider: ${A}`),X(`Stack: ${H}`),X(`Region: ${F}`),X(`Environment: ${Z}`),(A==="hetzner"||G.infrastructure?.compute?.mode==="server")&&G.infrastructure?.compute){n(`Provisioning ${A} compute infrastructure...`);let d=Y1({config:G,provider:A});if(!d.provisionComputeInfrastructure){w(`${A} driver does not support compute provisioning`);return}let g=await d.provisionComputeInfrastructure({config:G,environment:Z});if(h(`${A} compute infrastructure ready`),g.appPublicIp)X(`App server: ${g.appPublicIp}`);if(g.appInstanceId)X(`Server ID: ${g.appInstanceId}`);if(!await QG(G,Z,F))w(`App deploy to ${A} compute reported a failure`);else h(`App deployed to ${A} compute`);return}n("Generating CloudFormation template...");let _=new c$({config:G,environment:Z});_.generate();let E=_.toJSON(),M=JSON.parse(E);if(Object.keys(M.Resources||{}).length===0){X(`No infrastructure resources to deploy for environment '${Z}' — skipping stack ${H}.`);return}n("Validating template...");let q=p8(M),T=r8(E),D=n8(M),S=[...q.errors,...T.errors,...D.errors];if(S.length>0){w("Template validation failed:");for(let d of S)w(` - ${d.path}: ${d.message}`);return}let P=[...q.warnings,...T.warnings,...D.warnings];if(P.length>0)for(let d of P)v(` - ${d.path}: ${d.message}`);h("Template validated successfully");let C=Object.keys(M.Resources).length;X(`
8047
8052
  Resources to deploy: ${C}`);let I={};for(let d of Object.values(M.Resources)){let g=d.Type;I[g]=(I[g]||0)+1}for(let[d,g]of Object.entries(I).sort((s,J0)=>J0[1]-s[1]).slice(0,5))X(` - ${d}: ${g}`);if(!(Y||await u(`
8048
8053
  Deploy now?`,!0))){X("Deployment cancelled");return}let y=new O0(F);n("Checking stack status...");let c=!1;try{let d=await y.describeStacks({stackName:H});c=d.Stacks&&d.Stacks.length>0}catch(d){c=!1}if(c){X("Stack exists, updating...");let d=new N("Updating CloudFormation stack...");d.start();try{await y.updateStack({stackName:H,templateBody:E,capabilities:["CAPABILITY_IAM","CAPABILITY_NAMED_IAM"],tags:[{Key:"Project",Value:G.project.name},{Key:"Environment",Value:Z},{Key:"ManagedBy",Value:"ts-cloud"}]}),d.succeed("Update initiated"),n("Waiting for stack update to complete..."),await y.waitForStack(H,"stack-update-complete"),h("Stack updated successfully!")}catch(g){if(g.message.includes("No updates are to be performed"))d.succeed("No changes detected"),X("Stack is already up to date — continuing to app deploy");else throw g}}else{X("Creating new stack...");let d=new N("Creating CloudFormation stack...");d.start(),await y.createStack({stackName:H,templateBody:E,capabilities:["CAPABILITY_IAM","CAPABILITY_NAMED_IAM"],tags:[{Key:"Project",Value:G.project.name},{Key:"Environment",Value:Z},{Key:"ManagedBy",Value:"ts-cloud"}]}),d.succeed("Stack creation initiated"),n("Waiting for stack creation to complete..."),await y.waitForStack(H,"stack-create-complete"),h("Stack created successfully!")}let r=await y.getStackOutputs(H);if(h1(`Deployment Complete!
8049
8054
 
@@ -8059,7 +8064,7 @@ Stack trace:`),console.error(G.stack)}finally{if(Q)await Q()}}),$.command("deplo
8059
8064
  Server deployment complete!`)}catch(Y){w(`Deployment failed: ${Y.message}`),process.exitCode=1}}),$.command("deploy:serverless","Deploy a serverless application (http/queue/cli Lambda functions)").option("--env <environment>","Environment (production, staging, development)").option("--skip-build","Skip local build hooks").option("--skip-hooks","Skip remote deploy hooks (e.g. migrations)").option("--redeploy","Re-activate the last build without rebuilding").action(async(J)=>{try{let Y=await m(),Z=J?.env||"production",{deployServerlessApp:Q,redeployServerlessApp:G}=await Q1().then(() => u1);if(J?.redeploy){await G(Y,Z);return}await Q(Y,Z,{skipBuild:J?.skipBuild,skipDeployHooks:J?.skipHooks})}catch(Y){w(`Deployment failed: ${Y.message}`),process.exitCode=1}}),$.command("serverless:rollback","Roll back a serverless app to the previous build").option("--env <environment>","Environment (production, staging, development)").action(async(J)=>{try{let Y=await m(),Z=J?.env||"production",{rollbackServerlessApp:Q}=await Q1().then(() => u1);await Q(Y,Z)}catch(Y){w(`Rollback failed: ${Y.message}`),process.exitCode=1}}),$.command("deploy:rollback [site]","Roll a compute site back to a previous release").option("--env <environment>","Environment (production, staging, development)").option("--to <release>","Release id to roll back to (default: the previous release)").action(async(J,Y)=>{R("Rolling Back Release");try{let Z=await m(),Q=Y?.env||"production",G=J||Object.keys(Z.sites||{})[0];if(!G){w("No site configured to roll back."),process.exitCode=1;return}let{rollbackComputeSite:W}=await Promise.resolve().then(() => (J8(),T9)),z=await W({driver:Y1({config:Z}),slug:Z.project.slug,environment:Q,logger:Q0},{siteName:G,to:Y?.to});if(!z.success){w(`Rollback failed: ${z.error||"unknown error"}`),process.exitCode=1;return}for(let U of z.perInstance||[])X(` ${U.instanceId}: ${U.output?.trim()||U.status}`)}catch(Z){w(`Rollback failed: ${Z.message}`),process.exitCode=1}}),$.command("deploy:history [site]","Show a compute site's deployment history").option("--env <environment>","Environment (production, staging, development)").option("--limit <n>","Number of entries to show",{default:"20"}).action(async(J,Y)=>{R("Deployment History");try{let Z=await m(),Q=Y?.env||"production",G=J||Object.keys(Z.sites||{})[0];if(!G){w("No site configured."),process.exitCode=1;return}let{getComputeDeployHistory:W}=await Promise.resolve().then(() => (J8(),T9)),z=await W({driver:Y1({config:Z}),slug:Z.project.slug,environment:Q,logger:Q0},{siteName:G,limit:Number.parseInt(Y?.limit||"20",10)||20});if(!z.success){w(`Could not read history: ${z.error||"unknown error"}`),process.exitCode=1;return}for(let U of z.perInstance||[])X(`
8060
8065
  ${U.instanceId}:`),X(U.output?.trimEnd()||"(no output)")}catch(Z){w(`History lookup failed: ${Z.message}`),process.exitCode=1}}),$.command("deploy:recipe <name> <script>","Run a reusable server recipe (a local bash file) across servers").option("--env <environment>","Environment (production, staging, development)").option("--user <user>","User to run the recipe as",{default:"root"}).action(async(J,Y,Z)=>{R(`Running Recipe: ${J}`);try{if(!x1(Y)){w(`Recipe script not found: ${Y}`),process.exitCode=1;return}let Q=await m(),G=Z?.env||"production",W=GG(Y,"utf8").split(`
8061
8066
  `),{runComputeRecipe:z}=await Promise.resolve().then(() => (J8(),T9)),U=await z({driver:Y1({config:Q}),slug:Q.project.slug,environment:G,logger:Q0},{name:J,script:W,user:Z?.user});for(let H of U.perInstance||[])X(`
8062
- ${H.instanceId}:`),X(H.output?.trimEnd()||"(no output)");if(!U.success)process.exitCode=1}catch(Q){w(`Recipe failed: ${Q.message}`),process.exitCode=1}}),$.command("db:restore-backup [from]","Restore the app database from an on-box ts-backups dump (latest, or a given file)").option("--env <environment>","Environment (production, staging, development)").action(async(J,Y)=>{R("Database Restore");try{let Z=await m(),Q=Y?.env||"production",{restoreDatabaseBackup:G}=await Promise.resolve().then(() => (J8(),T9)),W=await G({driver:Y1({config:Z}),slug:Z.project.slug,environment:Q,logger:Q0},{database:Z.infrastructure?.appDatabase,from:J});for(let z of W.perInstance||[])X(` ${z.instanceId}: ${z.output?.trim()||z.status}`);if(!W.success)w(`Restore failed: ${W.error||"unknown error"}`),process.exitCode=1}catch(Z){w(`Restore failed: ${Z.message}`),process.exitCode=1}}),$.command("quick-deploy","Generate a push-to-deploy CI pipeline for your git provider (Forge Quick Deploy)").option("--env <environment>","Environment to deploy on push",{default:"production"}).option("--force","Overwrite an existing pipeline file").action(async(J)=>{R("Quick Deploy (push-to-deploy)");try{let Y=await m(),{buildQuickDeployCi:Z}=await Promise.resolve().then(() => qF),Q=Z(Y,J?.env||"production");if(!Q){v("No site has a github/gitlab/bitbucket repository — set `sites.<name>.repository.provider` to generate a pipeline."),process.exitCode=1;return}if(x1(Q.path)&&!J?.force){v(`${Q.path} already exists — re-run with --force to overwrite.`);return}F3(X3(Q.path),{recursive:!0}),H3(Q.path,Q.content),h(`Wrote ${Q.path} (${Q.provider}, deploys on push to '${Q.branch}').`),X("Next: commit it and add your provider credentials as CI secrets/variables.")}catch(Y){w(`Quick deploy setup failed: ${Y.message}`),process.exitCode=1}}),$.command("down","Put the serverless app into maintenance mode (503)").option("--env <environment>","Environment (production, staging, development)").option("--secret <secret>","Bypass secret (send as x-maintenance-bypass header)").action(async(J)=>{try{let Y=await m(),Z=J?.env||"production",{setMaintenance:Q}=await Q1().then(() => u1);await Q(Y,Z,!0,J?.secret)}catch(Y){w(`Failed to enable maintenance mode: ${Y.message}`),process.exitCode=1}}),$.command("up","Bring the serverless app out of maintenance mode").option("--env <environment>","Environment (production, staging, development)").action(async(J)=>{try{let Y=await m(),Z=J?.env||"production",{setMaintenance:Q}=await Q1().then(() => u1);await Q(Y,Z,!1)}catch(Y){w(`Failed to disable maintenance mode: ${Y.message}`),process.exitCode=1}}),$.command("command <cmd>","Run a command on the serverless CLI function (e.g. migrations)").option("--env <environment>","Environment (production, staging, development)").action(async(J,Y)=>{try{let Z=await m(),Q=Y?.env||"production",{runAndRecordCommand:G}=await Q1().then(() => u1),{id:W,output:z}=await G(Z,Q,J);if(X(z),W>0)X(`
8067
+ ${H.instanceId}:`),X(H.output?.trimEnd()||"(no output)");if(!U.success)process.exitCode=1}catch(Q){w(`Recipe failed: ${Q.message}`),process.exitCode=1}}),$.command("db:restore-backup [from]","Restore the app database from an on-box ts-backups dump (latest, or a given file)").option("--env <environment>","Environment (production, staging, development)").action(async(J,Y)=>{R("Database Restore");try{let Z=await m(),Q=Y?.env||"production",{restoreDatabaseBackup:G}=await Promise.resolve().then(() => (J8(),T9)),W=await G({driver:Y1({config:Z}),slug:Z.project.slug,environment:Q,logger:Q0},{database:Z.infrastructure?.appDatabase,from:J});for(let z of W.perInstance||[])X(` ${z.instanceId}: ${z.output?.trim()||z.status}`);if(!W.success)w(`Restore failed: ${W.error||"unknown error"}`),process.exitCode=1}catch(Z){w(`Restore failed: ${Z.message}`),process.exitCode=1}}),$.command("quick-deploy","Generate a push-to-deploy CI pipeline for your git provider (Forge Quick Deploy)").option("--env <environment>","Environment to deploy on push",{default:"production"}).option("--force","Overwrite an existing pipeline file").action(async(J)=>{R("Quick Deploy (push-to-deploy)");try{let Y=await m(),{buildQuickDeployCi:Z}=await Promise.resolve().then(() => qF),Q=Z(Y,J?.env||"production");if(!Q){v("No site has a github/gitlab/bitbucket repository — set `sites.<name>.repository.provider` to generate a pipeline."),process.exitCode=1;return}if(x1(Q.path)&&!J?.force){v(`${Q.path} already exists — re-run with --force to overwrite.`);return}H3(F3(Q.path),{recursive:!0}),U3(Q.path,Q.content),h(`Wrote ${Q.path} (${Q.provider}, deploys on push to '${Q.branch}').`),X("Next: commit it and add your provider credentials as CI secrets/variables.")}catch(Y){w(`Quick deploy setup failed: ${Y.message}`),process.exitCode=1}}),$.command("down","Put the serverless app into maintenance mode (503)").option("--env <environment>","Environment (production, staging, development)").option("--secret <secret>","Bypass secret (send as x-maintenance-bypass header)").action(async(J)=>{try{let Y=await m(),Z=J?.env||"production",{setMaintenance:Q}=await Q1().then(() => u1);await Q(Y,Z,!0,J?.secret)}catch(Y){w(`Failed to enable maintenance mode: ${Y.message}`),process.exitCode=1}}),$.command("up","Bring the serverless app out of maintenance mode").option("--env <environment>","Environment (production, staging, development)").action(async(J)=>{try{let Y=await m(),Z=J?.env||"production",{setMaintenance:Q}=await Q1().then(() => u1);await Q(Y,Z,!1)}catch(Y){w(`Failed to disable maintenance mode: ${Y.message}`),process.exitCode=1}}),$.command("command <cmd>","Run a command on the serverless CLI function (e.g. migrations)").option("--env <environment>","Environment (production, staging, development)").action(async(J,Y)=>{try{let Z=await m(),Q=Y?.env||"production",{runAndRecordCommand:G}=await Q1().then(() => u1),{id:W,output:z}=await G(Z,Q,J);if(X(z),W>0)X(`
8063
8068
  (recorded as #${W} — re-run with \`cloud command:again ${W}\`)`)}catch(Z){w(`Command failed: ${Z.message}`),process.exitCode=1}}),$.command("command:history","List recorded CLI-function command invocations").option("--env <environment>","Environment (production, staging, development)").option("--limit <n>","Show at most this many (most recent)",{default:"20"}).action(async(J)=>{try{let Y=await m(),Z=J?.env||"production",{listCommandHistory:Q}=await Q1().then(() => u1),G=await Q(Y,Z);if(!G.length){X("No command history yet.");return}let W=Number(J?.limit??20);R(`Command history — ${Y.project.slug} (${Z})`),p(["#","When","Status","Command"],G.slice(-W).reverse().map((z)=>[String(z.id),z.timestamp,z.status,z.command]))}catch(Y){w(`Failed to read history: ${Y.message}`),process.exitCode=1}}),$.command("command:again [id]","Re-run a recorded command (defaults to the most recent)").option("--env <environment>","Environment (production, staging, development)").action(async(J,Y)=>{try{let Z=await m(),Q=Y?.env||"production",{getCommandRecord:G,runAndRecordCommand:W}=await Q1().then(() => u1),z=await G(Z,Q,J?Number(J):void 0);if(!z){w(J?`No command #${J} in history.`:"No command history to re-run."),process.exitCode=1;return}X(`Re-running #${z.id}: ${z.command}`);let U=await W(Z,Q,z.command);if(X(U.output),U.id>0)X(`
8064
8069
  (recorded as #${U.id})`)}catch(Z){w(`Command failed: ${Z.message}`),process.exitCode=1}}),$.command("serverless:db-shell <sql>","Run a SQL statement against a private serverless database (via the CLI function)").option("--env <environment>","Environment (production, staging, development)").action(async(J,Y)=>{try{let Z=await m(),Q=Y?.env||"production",{runDbQuery:G}=await Q1().then(() => u1),W=await G(Z,Q,J);X(W)}catch(Z){w(`Query failed: ${Z.message}`),process.exitCode=1}}),$.command("serverless:db-scale <min> <max>","Rescale the serverless Aurora cluster (min/max ACUs)").option("--env <environment>","Environment (production, staging, development)").action(async(J,Y,Z)=>{R("Scaling serverless database");try{let Q=await m(),G=Z?.env||"production",W=Number(J),z=Number(Y);if(!(W>0)||!(z>=W)){w("Provide valid capacities: min > 0 and max >= min (e.g. `serverless:db-scale 0.5 8`)."),process.exitCode=1;return}let{scaleServerlessDatabase:U}=await Q1().then(() => u1);await U(Q,G,W,z)}catch(Q){w(`Scale failed: ${Q.message}`),process.exitCode=1}}),$.command("serverless:db-restore","Restore the serverless Aurora cluster to a point in time (as a new cluster)").option("--env <environment>","Environment (production, staging, development)").option("--to <timestamp>","Restore to this ISO-8601 time (UTC)").option("--latest","Restore to the latest restorable time").option("--target <id>","New cluster identifier (defaults to <cluster>-restore-<stamp>)").action(async(J)=>{R("Restoring serverless database");try{let Y=await m(),Z=J?.env||"production",Q;if(J?.to){if(Q=new Date(J.to),Number.isNaN(Q.getTime())){w(`Invalid --to timestamp: ${J.to} (use ISO-8601, e.g. 2026-06-18T10:00:00Z).`),process.exitCode=1;return}}let{restoreServerlessDatabase:G}=await Q1().then(() => u1);await G(Y,Z,{toTime:Q,latest:J?.latest,target:J?.target})}catch(Y){w(`Restore failed: ${Y.message}`),process.exitCode=1}}),$.command("serverless:info","Show an operational summary of a deployed serverless app").option("--env <environment>","Environment (production, staging, development)").action(async(J)=>{try{let Y=await m(),Z=J?.env||"production",{serverlessInfo:Q}=await Q1().then(() => u1),G=await Q(Y,Z);if(R(`${G.slug} (${G.environment})`),X(`Stack: ${G.stackStatus}`),X(`Region: ${G.region}`),G.endpoint)X(`URL: ${G.endpoint}`);if(G.assetUrl)X(`Assets: ${G.assetUrl}`);if(X(`Scheduler:${G.scheduler==="off"?" off":` ${G.scheduler}`}`),X(`Queues: ${G.queues.length?G.queues.join(", "):"none"}`),X(`Warming: ${G.provisionedConcurrency>0?`provisioned concurrency ×${G.provisionedConcurrency}`:"none / ping-warm"}`),G.lastRelease)X(`Release: ${G.lastRelease.sha.slice(0,12)} @ ${G.lastRelease.timestamp}`);p(["Function","Version","Provisioned"],G.functions.map((W)=>[W.name,W.version,W.provisioned?`${W.provisioned.status} ${W.provisioned.allocated}/${W.provisioned.requested}`:"—"]))}catch(Y){w(`Failed to read info: ${Y.message}`),process.exitCode=1}}),$.command("dashboard:build","Build the management dashboard with live data baked in").option("--env <environment>","Environment (production, staging, development)").option("--ui <dir>","UI directory (default ./ui)",{default:"ui"}).action(async(J)=>{R("Building management dashboard (live data)");try{let{existsSync:Y}=await import("node:fs"),Z=J?.ui||"ui";if(!Y(`${Z}/package.json`)){w(`No UI project at ${Z}/ (expected ${Z}/package.json). Pass --ui <dir>.`),process.exitCode=1;return}let Q=await m(),G=J?.env||"production";n("Gathering live data from AWS");let W=null;if(Q.environments?.[G]?.app){let{resolveDashboardData:H}=await a7().then(() => RF),F=await H(Q,G).catch((B)=>{return v(`Serverless data unavailable (${B.message}) — that view uses sample data.`),null});if(F)W={...W??{},...F}}if(Q.infrastructure?.compute){let{resolveServerDashboardData:H}=await ZG().then(() => iF),F=await H(Q,G).catch(()=>null);if(F){if(F._serverReachable===!1)v("Server box not reachable over SSM — server view uses config + sample data.");W={...W??{},...F}}}n("Building dashboard");let{execSync:z}=await import("node:child_process"),{rmSync:U}=await import("node:fs");for(let H of[".stx/ssg-cache",".stx/cache"])U(`${Z}/${H}`,{recursive:!0,force:!0});z("bun run build",{cwd:Z,stdio:"inherit",env:{...process.env,...W?{TSCLOUD_DASHBOARD_DATA:JSON.stringify(W)}:{}}}),h(`Dashboard built → ${Z}/dist${W?" (live data)":" (sample data)"}`)}catch(Y){w(`Dashboard build failed: ${Y.message}`),process.exitCode=1}}),$.command("serverless:build-php-layer","Build + publish the ts-cloud PHP runtime layer (requires Docker)").option("--arch <architecture>","x86_64 or arm64",{default:"x86_64"}).option("--php <version>","PHP version",{default:"8.3"}).option("--name <name>","Layer name",{default:"tscloud-php"}).option("--bucket <bucket>","S3 bucket to stage the layer zip (defaults to {slug}-layers)").option("--region <region>","AWS region").action(async(J)=>{R("Building PHP runtime layer");try{let Y=await m().catch(()=>null),Z=J?.region||Y?.project.region||"us-east-1",Q=J?.arch||"x86_64",G=J?.php||"8.3",W=`${J?.name||"tscloud-php"}-${G.replace(".","")}-${Q}`,z=J?.bucket||`${Y?.project.slug||"tscloud"}-layers`,{buildPhpRuntimeLayerZip:U}=await n0().then(() => l8),{S3Client:H}=await Promise.resolve().then(() => (I0(),l$)),{LambdaClient:F}=await Promise.resolve().then(() => (a1(),m$)),B=U({architecture:Q,phpVersion:G,onStep:(_)=>n(_)});X(`Layer: ${B.fileCount} files, ${(B.zip.length/1024/1024).toFixed(1)} MB`);let K=new H(Z);if(!await K.bucketExists(z))n(`Creating layer bucket ${z}`),await K.createBucket(z);let O=`layers/${W}.zip`;n("Uploading layer zip"),await K.putObject({bucket:z,key:O,body:B.zip,contentType:"application/zip"}),n("Publishing layer version");let V=await new F(Z).publishLayerVersion({LayerName:W,Description:`ts-cloud PHP ${G} runtime (${Q})`,Content:{S3Bucket:z,S3Key:O},CompatibleRuntimes:["provided.al2023"],CompatibleArchitectures:[Q]});h1(["PHP runtime layer published","",`ARN: ${V.LayerVersionArn}`,"","Reference it in your config:",` app: { kind: 'php', layers: ['${V.LayerVersionArn}'] }`,"or set TSCLOUD_PHP_LAYER_ARN before deploying."].join(`
8065
8070
  `),"green")}catch(Y){w(`Layer build failed: ${Y.message}`),process.exitCode=1}}),$.command("serverless:build-node-layer","Build + publish a ts-cloud Node custom runtime layer (any version, incl. 24)").option("--arch <architecture>","x86_64 or arm64",{default:"x86_64"}).option("--node <version>","Node version (e.g. 24)",{default:"24"}).option("--name <name>","Layer name",{default:"tscloud-node"}).option("--bucket <bucket>","S3 bucket to stage the layer zip (defaults to {slug}-layers)").option("--region <region>","AWS region").action(async(J)=>{R("Building Node runtime layer");try{let Y=await m().catch(()=>null),Z=J?.region||Y?.project.region||"us-east-1",Q=J?.arch||"x86_64",G=J?.node||"24",{buildNodeRuntimeLayerZip:W}=await n0().then(() => l8),{S3Client:z}=await Promise.resolve().then(() => (I0(),l$)),{LambdaClient:U}=await Promise.resolve().then(() => (a1(),m$)),H=W({architecture:Q,version:G,onStep:(_)=>n(_)}),F=`${J?.name||"tscloud-node"}-${H.version.split(".")[0]}-${Q}`,B=J?.bucket||`${Y?.project.slug||"tscloud"}-layers`;X(`Layer: Node ${H.version}, ${(H.zip.length/1024/1024).toFixed(1)} MB`);let K=new z(Z);if(!await K.bucketExists(B))n(`Creating layer bucket ${B}`),await K.createBucket(B);let O=`layers/${F}.zip`;n("Uploading layer zip"),await K.putObject({bucket:B,key:O,body:H.zip,contentType:"application/zip"}),n("Publishing layer version");let V=await new U(Z).publishLayerVersion({LayerName:F,Description:`ts-cloud Node ${H.version} runtime (${Q})`,Content:{S3Bucket:B,S3Key:O},CompatibleRuntimes:["provided.al2023"],CompatibleArchitectures:[Q]});h1(["Node runtime layer published","",`ARN: ${V.LayerVersionArn}`,"","Reference it in your config:",` app: { kind: 'node', runtimeVersion: '${H.version.split(".")[0]}', layers: ['${V.LayerVersionArn}'] }`,"or set TSCLOUD_NODE_LAYER_ARN before deploying."].join(`
@@ -8089,9 +8094,9 @@ To proceed anyway, use --skip-security-scan flag`);return}h(`✓ Security scan p
8089
8094
  `);if(X(`Cluster: ${Q}`),X(`Service: ${G}`),X(`Repository: ${W}`),X(`Image Tag: ${z}`),X(`Dockerfile: ${U}`),!await u(`
8090
8095
  Deploy container now?`,!0)){X("Deployment cancelled");return}let O=new p$(Z),A=new H7(Z),V=new N("Getting ECR credentials...");V.start();let _=await O.getAuthorizationToken();if(!_.authorizationData?.[0]){V.fail("Failed to get ECR credentials");return}let E=_.authorizationData[0],j=(E.proxyEndpoint||"").replace("https://","");V.succeed("ECR credentials obtained");let q=new N("Logging into ECR...");q.start();let T=E.authorizationToken||"",S=Buffer.from(T,"base64").toString("utf8").split(":")[1],{spawn:P}=await import("child_process"),C=P("docker",["login","--username","AWS","--password-stdin",j],{stdio:["pipe","pipe","pipe"]});C.stdin.write(S),C.stdin.end(),await new Promise((g,s)=>{C.on("close",(J0)=>{if(J0===0)g();else s(Error(`Docker login failed with code ${J0}`))})}),q.succeed("Logged into ECR");let I=new N("Building Docker image...");I.start();let b=`${j}/${W}:${z}`,y=P("docker",["build","-t",b,"-f",U,H],{stdio:["pipe","pipe","pipe"]});await new Promise((g,s)=>{let J0="";y.stderr.on("data",(t)=>{J0+=t.toString()}),y.on("close",(t)=>{if(t===0)g();else s(Error(`Docker build failed: ${J0}`))})}),I.succeed("Docker image built");let c=new N("Pushing image to ECR...");c.start();let r=P("docker",["push",b],{stdio:["pipe","pipe","pipe"]});await new Promise((g,s)=>{let J0="";r.stderr.on("data",(t)=>{J0+=t.toString()}),r.on("close",(t)=>{if(t===0)g();else s(Error(`Docker push failed: ${J0}`))})}),c.succeed("Image pushed to ECR");let d=new N("Updating ECS service...");if(d.start(),await A.updateService({cluster:Q,service:G,forceNewDeployment:F}),d.succeed("ECS service updated"),B){let g=new N("Waiting for deployment to stabilize...");g.start(),await A.waitForServiceStable(Q,G),g.succeed("Deployment stabilized")}h(`
8091
8096
  Container deployment complete!`),X(`
8092
- Image: ${b}`),X(`Cluster: ${Q}`),X(`Service: ${G}`)}catch(Y){w(`Deployment failed: ${Y.message}`)}})}async function A3($){let J=process.cwd(),Y=`${J}/.env`,Z=`${J}/.env.local`,W=({stage:["stage","staging"],staging:["staging","stage"]}[$]||[$]).map((B)=>`${J}/.env.${B}`).find((B)=>x1(B));if(!W){if(x1(Y))v(`No .env.${$} found, falling back to .env`);else w(`No .env.${$} or .env file found`);return null}let z=W.split("/").pop();n(`Loading environment file: ${z}`);let U=null,H=null;if(x1(Z)){U=`${Z}.bak`,N9(Z,U);let B=GG(Z,"utf-8");for(let O of B.split(`
8097
+ Image: ${b}`),X(`Cluster: ${Q}`),X(`Service: ${G}`)}catch(Y){w(`Deployment failed: ${Y.message}`)}})}async function V3($){let J=process.cwd(),Y=`${J}/.env`,Z=`${J}/.env.local`,W=({stage:["stage","staging"],staging:["staging","stage"]}[$]||[$]).map((B)=>`${J}/.env.${B}`).find((B)=>x1(B));if(!W){if(x1(Y))v(`No .env.${$} found, falling back to .env`);else w(`No .env.${$} or .env file found`);return null}let z=W.split("/").pop();n(`Loading environment file: ${z}`);let U=null,H=null;if(x1(Z)){U=`${Z}.bak`,N9(Z,U);let B=GG(Z,"utf-8");for(let O of B.split(`
8093
8098
  `)){let A=O.trim();if(!A||A.startsWith("#"))continue;let V=A.indexOf("=");if(V===-1)continue;let _=A.slice(0,V).trim();delete process.env[_]}let{unlinkSync:K}=await import("node:fs");K(Z),X("Temporarily moved .env.local out of the way and purged its values from process.env")}if(x1(Y))H=`${Y}.bak`,N9(Y,H);N9(W,Y);let F=GG(W,"utf-8");for(let B of F.split(`
8094
- `)){let K=B.trim();if(!K||K.startsWith("#"))continue;let O=K.indexOf("=");if(O===-1)continue;let A=K.slice(0,O).trim(),V=K.slice(O+1).trim();process.env[A]=V}return h(`Loaded ${z}`),async()=>{let{unlinkSync:B}=await import("node:fs");if(H)N9(H,`${J}/.env`),B(H),X("Restored .env");if(U)N9(U,`${J}/.env.local`),B(U),X("Restored .env.local")}}async function _3($,J,Y,Z,Q,G,W=!1){let z=$.sites||{},U=J?[J]:Object.keys(z);if(U.length===0){v("No sites configured in cloud.config.ts");return}let H=f1(Y);if(!H){w(`DNS provider '${Y}' is not configured. Please set the required environment variables.`),X(`
8099
+ `)){let K=B.trim();if(!K||K.startsWith("#"))continue;let O=K.indexOf("=");if(O===-1)continue;let A=K.slice(0,O).trim(),V=K.slice(O+1).trim();process.env[A]=V}return h(`Loaded ${z}`),async()=>{let{unlinkSync:B}=await import("node:fs");if(H)N9(H,`${J}/.env`),B(H),X("Restored .env");if(U)N9(U,`${J}/.env.local`),B(U),X("Restored .env.local")}}async function A3($,J,Y,Z,Q,G,W=!1){let z=$.sites||{},U=J?[J]:Object.keys(z);if(U.length===0){v("No sites configured in cloud.config.ts");return}let H=f1(Y);if(!H){w(`DNS provider '${Y}' is not configured. Please set the required environment variables.`),X(`
8095
8100
  For Cloudflare: CLOUDFLARE_API_TOKEN`),X("For Porkbun: PORKBUN_API_KEY, PORKBUN_SECRET_KEY"),X("For GoDaddy: GODADDY_API_KEY, GODADDY_API_SECRET");return}if(H.provider==="route53"){let B=$.infrastructure?.dns?.hostedZoneId;if(B&&!H.hostedZoneId)H.hostedZoneId=B}let F=U1(H);for(let B of U){let K=z[B];if(!K){w(`Site '${B}' not found in configuration`);continue}if(K.deploy==="server"){X(`Site '${B}' is deploy:'server' — handled by the compute path, skipping static (bucket) deploy.`);continue}let O=K.domain;if(!O){w(`Site '${B}' has no domain configured`);continue}if(R(`Deploying Site: ${B}`),X(`Domain: ${O}`),X(`Source: ${K.root}`),X(`DNS Provider: ${Y}`),K.build){n(`Running build command: ${K.build}`);try{let{execSync:T}=await import("node:child_process");T(K.build,{stdio:"inherit",cwd:process.cwd()}),h("Build completed successfully")}catch(T){w(`Build failed: ${T.message}`);continue}}if(!x1(K.root)){if(w(`Source directory not found: ${K.root}`),!K.build)X('Run your build command first (e.g., bun run generate) or add a "build" option to your site config');continue}n("Checking existing DNS records...");let A=await F.listRecords(O);if(A.success&&A.records.length>0){let T=O.split("."),D=T.length>2?T[0]:"@",S=T.slice(-2).join("."),P=A.records.find((C)=>C.type==="CNAME"&&(C.name===O||C.name===D||C.name===`${D}.${S}`));if(P){let C=P.content.includes("netlify"),I=P.content.includes("vercel");if(P.content.includes("cloudfront.net"))X(`Domain already points to CloudFront: ${P.content}`),X("Proceeding with file upload...");else{let y=C?"Netlify":I?"Vercel":"another provider";if(v(`
8096
8101
  Existing CNAME record detected:`),X(` ${P.name} -> ${P.content}`),C||I)X(`
8097
8102
  This domain is currently pointing to ${y}.`),X("Deploying will update this record to point to AWS CloudFront.");if(!(W||await u(`
@@ -8105,7 +8110,7 @@ Bucket: ${q.bucket}
8105
8110
  Files: ${T}${D}
8106
8111
 
8107
8112
  Your site is now live at https://${q.domain}`,"green")}else w(`
8108
- Deployment failed: ${q.message}`)}}z0();await z8([n0(),j$()]);function UG($){$.command("destroy","Destroy the single-server compute (instance + firewall)").option("--env <env>","Environment",{default:"production"}).option("--force","Skip the confirmation prompt").action(async(J)=>{R("Destroy Compute");let Y=await m(),Z=J?.env||"production",Q=q2(Y),G=Y1({config:Y,provider:Q});if(!G.destroyCompute){w(`The ${Q} driver does not support compute teardown`);return}if(v(`This terminates the ${Q} server for ${Y.project.slug}/${Z} and deletes its firewall.`),!J?.force){if(!await u("This is irreversible. Continue?",!1)){X("Cancelled");return}}let W=new N("Destroying compute...");W.start();try{let{destroyed:z}=await G.destroyCompute({config:Y,environment:Z});if(W.succeed("Compute destroyed"),z.length>0)z.forEach((U)=>X(` removed ${U}`));else X("Nothing to destroy (no matching resources found)")}catch(z){W.fail("Teardown failed"),w(z instanceof Error?z.message:String(z))}})}z0();M1();import{writeFileSync as j3,statSync as L3}from"node:fs";function HG($){$.command("stack:list","List all CloudFormation stacks").action(async()=>{R("CloudFormation Stacks");try{let Y=(await m()).project.region||"us-east-1",Z=new O0(Y),Q=new N("Loading stacks...");Q.start();let G=await Z.listStacks(["CREATE_COMPLETE","UPDATE_COMPLETE","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE","CREATE_IN_PROGRESS","UPDATE_IN_PROGRESS"]);if(Q.succeed(`Found ${G.StackSummaries.length} stacks`),G.StackSummaries.length===0){X("No stacks found");return}let W=["Stack Name","Status","Created","Updated"],z=G.StackSummaries.map((U)=>[U.StackName,U.StackStatus,new Date(U.CreationTime).toLocaleString(),U.LastUpdatedTime?new Date(U.LastUpdatedTime).toLocaleString():"Never"]);p(W,z)}catch(J){w(`Failed to list stacks: ${J.message}`)}}),$.command("stack:describe STACK_NAME","Describe a CloudFormation stack").action(async(J)=>{R(`Stack: ${J}`);try{let Z=(await m()).project.region||"us-east-1",Q=new O0(Z),G=new N("Loading stack details...");G.start();let W=await Q.describeStacks({stackName:J});if(!W.Stacks||W.Stacks.length===0){G.fail("Stack not found");return}let z=W.Stacks[0];if(G.succeed("Stack details loaded"),X(`
8113
+ Deployment failed: ${q.message}`)}}z0();await z8([n0(),j$()]);function UG($){$.command("destroy","Destroy the single-server compute (instance + firewall)").option("--env <env>","Environment",{default:"production"}).option("--force","Skip the confirmation prompt").action(async(J)=>{R("Destroy Compute");let Y=await m(),Z=J?.env||"production",Q=q2(Y),G=Y1({config:Y,provider:Q});if(!G.destroyCompute){w(`The ${Q} driver does not support compute teardown`);return}if(v(`This terminates the ${Q} server for ${Y.project.slug}/${Z} and deletes its firewall.`),!J?.force){if(!await u("This is irreversible. Continue?",!1)){X("Cancelled");return}}let W=new N("Destroying compute...");W.start();try{let{destroyed:z}=await G.destroyCompute({config:Y,environment:Z});if(W.succeed("Compute destroyed"),z.length>0)z.forEach((U)=>X(` removed ${U}`));else X("Nothing to destroy (no matching resources found)")}catch(z){W.fail("Teardown failed"),w(z instanceof Error?z.message:String(z))}})}z0();M1();import{writeFileSync as _3,statSync as j3}from"node:fs";function HG($){$.command("stack:list","List all CloudFormation stacks").action(async()=>{R("CloudFormation Stacks");try{let Y=(await m()).project.region||"us-east-1",Z=new O0(Y),Q=new N("Loading stacks...");Q.start();let G=await Z.listStacks(["CREATE_COMPLETE","UPDATE_COMPLETE","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE","CREATE_IN_PROGRESS","UPDATE_IN_PROGRESS"]);if(Q.succeed(`Found ${G.StackSummaries.length} stacks`),G.StackSummaries.length===0){X("No stacks found");return}let W=["Stack Name","Status","Created","Updated"],z=G.StackSummaries.map((U)=>[U.StackName,U.StackStatus,new Date(U.CreationTime).toLocaleString(),U.LastUpdatedTime?new Date(U.LastUpdatedTime).toLocaleString():"Never"]);p(W,z)}catch(J){w(`Failed to list stacks: ${J.message}`)}}),$.command("stack:describe STACK_NAME","Describe a CloudFormation stack").action(async(J)=>{R(`Stack: ${J}`);try{let Z=(await m()).project.region||"us-east-1",Q=new O0(Z),G=new N("Loading stack details...");G.start();let W=await Q.describeStacks({stackName:J});if(!W.Stacks||W.Stacks.length===0){G.fail("Stack not found");return}let z=W.Stacks[0];if(G.succeed("Stack details loaded"),X(`
8109
8114
  Stack Information:`),X(` - Name: ${z.StackName}`),X(` - Status: ${z.StackStatus}`),X(` - Created: ${new Date(z.CreationTime).toLocaleString()}`),z.LastUpdatedTime)X(` - Updated: ${new Date(z.LastUpdatedTime).toLocaleString()}`);if(z.Parameters&&z.Parameters.length>0){X(`
8110
8115
  Parameters:`);for(let H of z.Parameters)X(` - ${H.ParameterKey}: ${H.ParameterValue}`)}if(z.Outputs&&z.Outputs.length>0){X(`
8111
8116
  Outputs:`);for(let H of z.Outputs)if(X(` - ${H.OutputKey}: ${H.OutputValue}`),H.Description)X(` ${H.Description}`)}if(z.Tags&&z.Tags.length>0){X(`
@@ -8114,24 +8119,24 @@ Loading stack resources...`);let U=await Q.listStackResources(J);if(U.StackResou
8114
8119
  Resources (${U.StackResourceSummaries.length}):`);let H=["Logical ID","Type","Status"],F=U.StackResourceSummaries.slice(0,10).map((B)=>[B.LogicalResourceId,B.ResourceType,B.ResourceStatus]);if(p(H,F),U.StackResourceSummaries.length>10)X(`
8115
8120
  ... and ${U.StackResourceSummaries.length-10} more resources`)}}catch(Y){w(`Failed to describe stack: ${Y.message}`)}}),$.command("stack:delete STACK_NAME","Delete a CloudFormation stack").action(async(J)=>{R(`Delete Stack: ${J}`);try{let Z=(await m()).project.region||"us-east-1";if(v("This will permanently delete the stack and all its resources!"),!await u(`
8116
8121
  Are you sure you want to delete this stack?`,!1)){X("Deletion cancelled");return}let G=new O0(Z),W=new N("Deleting stack...");W.start(),await G.deleteStack(J),W.succeed("Stack deletion initiated"),n("Waiting for stack deletion..."),await G.waitForStack(J,"stack-delete-complete"),h("Stack deleted successfully!")}catch(Y){w(`Failed to delete stack: ${Y.message}`)}}),$.command("stack:events STACK_NAME","Show stack events").option("--limit <number>","Limit number of events",{default:"20"}).action(async(J,Y)=>{R(`Stack Events: ${J}`);try{let Q=(await m()).project.region||"us-east-1",G=new O0(Q),W=new N("Loading events...");W.start();let z=await G.describeStackEvents(J);W.succeed(`Found ${z.StackEvents.length} events`);let U=Y?.limit?Number.parseInt(Y.limit):20,H=z.StackEvents.slice(0,U);if(H.length===0){X("No events found");return}let F=["Time","Resource","Status","Reason"],B=H.map((K)=>[new Date(K.Timestamp).toLocaleString(),K.LogicalResourceId,K.ResourceStatus,K.ResourceStatusReason||""]);p(F,B)}catch(Z){w(`Failed to load events: ${Z.message}`)}}),$.command("stack:outputs STACK_NAME","Show stack outputs").action(async(J)=>{R(`Stack Outputs: ${J}`);try{let Z=(await m()).project.region||"us-east-1",Q=new O0(Z),G=new N("Loading stack outputs...");G.start();let W=await Q.describeStacks({stackName:J});if(!W.Stacks||W.Stacks.length===0){G.fail("Stack not found");return}let z=W.Stacks[0];if(G.succeed("Stack outputs loaded"),!z.Outputs||z.Outputs.length===0){X("No outputs found for this stack");return}let U=["Key","Value","Description","Export Name"],H=z.Outputs.map((F)=>[F.OutputKey||"",F.OutputValue||"",F.Description||"",F.ExportName||""]);p(U,H),X(`
8117
- Copy-friendly format:`);for(let F of z.Outputs)X(`${F.OutputKey}=${F.OutputValue}`)}catch(Y){w(`Failed to load outputs: ${Y.message}`)}}),$.command("stack:export STACK_NAME","Export stack template").option("--output <file>","Output file path").option("--format <format>","Output format (json or yaml)",{default:"json"}).action(async(J,Y)=>{R(`Export Stack: ${J}`);try{let Q=(await m()).project.region||"us-east-1",G=new O0(Q),W=new N("Fetching stack template...");W.start();let z=await G.getTemplate(J);if(!z.TemplateBody){W.fail("Template not found");return}W.succeed("Template fetched");let U=Y?.format||"json",H=z.TemplateBody;if(U==="json"){let F=JSON.parse(H);H=JSON.stringify(F,null,2)}if(Y?.output){let F=Y.output;j3(F,H,"utf-8"),h(`Template exported to: ${F}`);let K=(L3(F).size/1024).toFixed(2);X(`File size: ${K} KB`)}else X(`
8118
- Template:`),console.log(H)}catch(Z){w(`Failed to export template: ${Z.message}`)}})}z0();M1();L2();import{existsSync as E3}from"node:fs";function FG($,J){$.command("upgrade","Upgrade CLI to latest version").action(async()=>{R("Upgrading ts-cloud CLI");let Y=new N("Checking for updates...");if(Y.start(),await new Promise((G)=>setTimeout(G,2000)),Y.stop(),X(`
8122
+ Copy-friendly format:`);for(let F of z.Outputs)X(`${F.OutputKey}=${F.OutputValue}`)}catch(Y){w(`Failed to load outputs: ${Y.message}`)}}),$.command("stack:export STACK_NAME","Export stack template").option("--output <file>","Output file path").option("--format <format>","Output format (json or yaml)",{default:"json"}).action(async(J,Y)=>{R(`Export Stack: ${J}`);try{let Q=(await m()).project.region||"us-east-1",G=new O0(Q),W=new N("Fetching stack template...");W.start();let z=await G.getTemplate(J);if(!z.TemplateBody){W.fail("Template not found");return}W.succeed("Template fetched");let U=Y?.format||"json",H=z.TemplateBody;if(U==="json"){let F=JSON.parse(H);H=JSON.stringify(F,null,2)}if(Y?.output){let F=Y.output;_3(F,H,"utf-8"),h(`Template exported to: ${F}`);let K=(j3(F).size/1024).toFixed(2);X(`File size: ${K} KB`)}else X(`
8123
+ Template:`),console.log(H)}catch(Z){w(`Failed to export template: ${Z.message}`)}})}z0();M1();L2();import{existsSync as L3}from"node:fs";function FG($,J){$.command("upgrade","Upgrade CLI to latest version").action(async()=>{R("Upgrading ts-cloud CLI");let Y=new N("Checking for updates...");if(Y.start(),await new Promise((G)=>setTimeout(G,2000)),Y.stop(),X(`
8119
8124
  Current version: 0.1.0`),X("Latest version: 0.2.0"),!await u(`
8120
8125
  Upgrade to latest version?`,!0)){X("Operation cancelled");return}let Q=new N("Upgrading...");Q.start(),await new Promise((G)=>setTimeout(G,3000)),Q.succeed("Upgrade completed successfully"),h(`
8121
8126
  ts-cloud CLI upgraded to v0.2.0!`),X(`
8122
- What's new in v0.2.0:`),X(" - New cost optimization commands"),X(" - Improved team collaboration features"),X(" - Better error messages"),X(" - Performance improvements"),X("\nTip: Run `cloud --help` to see all available commands")}),$.command("doctor","Check system requirements and AWS credentials").action(async()=>{if(R("System Diagnostics"),n("Checking Bun..."),h(`Bun ${process.versions.bun}`),n("Checking AWS CLI..."),await L5())h("AWS CLI is installed");else w("AWS CLI is not installed"),X("Install: https://aws.amazon.com/cli/");if(n("Checking AWS credentials..."),await E5()){h("AWS credentials are configured");let G=await M5();if(G)X(`Account ID: ${G}`)}else w("AWS credentials are not configured"),X("Run: aws configure");n("Checking CloudFront list access...");let Q=!1;try{let{CloudFrontClient:G}=await Promise.resolve().then(() => (U2(),iZ));await new G().listDistributions(),h("CloudFront list access is enabled"),Q=!0}catch(G){v(`CloudFront list check failed: ${G.message}`)}if(Q){n("Checking CloudFront create access...");try{let G=new O0("us-east-1"),W=JSON.stringify({AWSTemplateFormatVersion:"2010-09-09",Description:"Test CloudFront access",Resources:{TestOAC:{Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:"test-oac-validation",OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}}}});await G.validateTemplate(W),h("CloudFront create access appears enabled")}catch(G){if(G.message?.includes("403")||G.message?.includes("AccessDenied")||G.message?.includes("must be verified"))w("CloudFront create access denied - account verification required"),X(""),X("Your AWS account needs to be verified for CloudFront."),X("This is required before you can create CloudFront distributions."),X(""),X("To verify your account:"),X(" 1. Go to: https://console.aws.amazon.com/support/home#/"),X(" 2. Create a support case"),X(" 3. Select: Service limit increase > CloudFront"),X(' 4. Request: "Please verify my account for CloudFront access"'),X(""),X("Verification usually takes 1-2 business days.");else h("CloudFront create access appears enabled (validation passed)")}}n("Checking S3 access...");try{let{S3Client:G}=await Promise.resolve().then(() => (I0(),l$));await new G("us-east-1").listBuckets(),h("S3 access is enabled")}catch(G){v(`S3 check failed: ${G.message}`)}n("Checking ACM (SSL certificates) access...");try{await new $1("us-east-1").listCertificates(),h("ACM access is enabled")}catch(G){v(`ACM check failed: ${G.message}`)}if(n("Checking configuration..."),E3("cloud.config.ts"))h("cloud.config.ts found");else v("cloud.config.ts not found"),X("Run: cloud init")}),$.command("regions","List available AWS regions").action(async()=>{R("AWS Regions");let Y=new N("Fetching regions...");Y.start();let Z=await q5();Y.stop(),Z.forEach((Q)=>{console.log(` ${Q}`)})}),$.command("version","Show the version of the CLI").alias("v").action(()=>{console.log(`ts-cloud v${J}`)})}z0();Y0();class a0{client;region;endpoint;constructor($="us-east-1",J){this.region=$,this.endpoint=J?.endpoint,this.client=new i}async request($,J){if(this.endpoint){let Y=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${$}`},body:JSON.stringify(J)});if(!Y.ok){let Z=await Y.text();throw Error(`DynamoDB request failed: ${Y.status} ${Z}`)}return Y.json()}return this.client.request({service:"dynamodb",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${$}`},body:JSON.stringify(J)})}async createTable($){return this.request("CreateTable",$)}async deleteTable($){return this.request("DeleteTable",$)}async describeTable($){return this.request("DescribeTable",$)}async listTables($){return this.request("ListTables",$||{})}async putItem($){return this.request("PutItem",$)}async getItem($){return this.request("GetItem",$)}async updateItem($){return this.request("UpdateItem",$)}async deleteItem($){return this.request("DeleteItem",$)}async query($){return this.request("Query",$)}async scan($){return this.request("Scan",$)}async batchWriteItem($){return this.request("BatchWriteItem",$)}async batchGetItem($){return this.request("BatchGetItem",$)}async updateTimeToLive($){return this.request("UpdateTimeToLive",$)}static marshal($){let J={};for(let[Y,Z]of Object.entries($))J[Y]=a0.marshalValue(Z);return J}static marshalValue($){if($===null||$===void 0)return{NULL:!0};if(typeof $==="string")return{S:$};if(typeof $==="number")return{N:String($)};if(typeof $==="boolean")return{BOOL:$};if(Array.isArray($))return{L:$.map((J)=>a0.marshalValue(J))};if(typeof $==="object")return{M:a0.marshal($)};return{S:String($)}}static unmarshal($){let J={};for(let[Y,Z]of Object.entries($))J[Y]=a0.unmarshalValue(Z);return J}static unmarshalValue($){if($.S!==void 0)return $.S;if($.N!==void 0)return Number($.N);if($.BOOL!==void 0)return $.BOOL;if($.NULL!==void 0)return null;if($.L!==void 0)return $.L.map((J)=>a0.unmarshalValue(J));if($.M!==void 0)return a0.unmarshal($.M);if($.SS!==void 0)return $.SS;if($.NS!==void 0)return $.NS.map(Number);return null}}function XG($){$.command("analytics:sites:list","List all analytics sites").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J)=>{R("Analytics Sites");try{let Y=new a0(J.region),Z=new N("Fetching sites...");Z.start();let Q=await Y.scan({TableName:J.table,FilterExpression:"begins_with(pk, :pk)",ExpressionAttributeValues:{":pk":{S:"SITE#"}}});if(Z.succeed(`Found ${Q.Items?.length||0} site(s)`),!Q.Items||Q.Items.length===0){X("No analytics sites found"),X("Use `cloud analytics:sites:create` to create a new site");return}let G=Q.Items.map((W)=>a0.unmarshal(W));p(["ID","Name","Domains","Active","Created"],G.map((W)=>[W.siteId||"N/A",W.name||"Unnamed",(W.domains||[]).join(", ")||"-",W.isActive?"Yes":"No",W.createdAt?new Date(W.createdAt).toLocaleDateString():"N/A"]))}catch(Y){w(`Failed to list sites: ${Y.message}`),process.exit(1)}}),$.command("analytics:sites:create","Create a new analytics site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--name <name>","Site name").option("--domain <domain>","Site domain(s) (can be specified multiple times)").action(async(J)=>{R("Create Analytics Site");try{let Y=new a0(J.region),Z=J.name||await q0("Site name","My Site"),Q=[];if(J.domain)Q=Array.isArray(J.domain)?J.domain:[J.domain];else Q=(await q0("Site domains (comma-separated)","example.com")).split(",").map((F)=>F.trim()).filter(Boolean);if(X(`
8127
+ What's new in v0.2.0:`),X(" - New cost optimization commands"),X(" - Improved team collaboration features"),X(" - Better error messages"),X(" - Performance improvements"),X("\nTip: Run `cloud --help` to see all available commands")}),$.command("doctor","Check system requirements and AWS credentials").action(async()=>{if(R("System Diagnostics"),n("Checking Bun..."),h(`Bun ${process.versions.bun}`),n("Checking AWS CLI..."),await L5())h("AWS CLI is installed");else w("AWS CLI is not installed"),X("Install: https://aws.amazon.com/cli/");if(n("Checking AWS credentials..."),await E5()){h("AWS credentials are configured");let G=await M5();if(G)X(`Account ID: ${G}`)}else w("AWS credentials are not configured"),X("Run: aws configure");n("Checking CloudFront list access...");let Q=!1;try{let{CloudFrontClient:G}=await Promise.resolve().then(() => (U2(),iZ));await new G().listDistributions(),h("CloudFront list access is enabled"),Q=!0}catch(G){v(`CloudFront list check failed: ${G.message}`)}if(Q){n("Checking CloudFront create access...");try{let G=new O0("us-east-1"),W=JSON.stringify({AWSTemplateFormatVersion:"2010-09-09",Description:"Test CloudFront access",Resources:{TestOAC:{Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:"test-oac-validation",OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}}}});await G.validateTemplate(W),h("CloudFront create access appears enabled")}catch(G){if(G.message?.includes("403")||G.message?.includes("AccessDenied")||G.message?.includes("must be verified"))w("CloudFront create access denied - account verification required"),X(""),X("Your AWS account needs to be verified for CloudFront."),X("This is required before you can create CloudFront distributions."),X(""),X("To verify your account:"),X(" 1. Go to: https://console.aws.amazon.com/support/home#/"),X(" 2. Create a support case"),X(" 3. Select: Service limit increase > CloudFront"),X(' 4. Request: "Please verify my account for CloudFront access"'),X(""),X("Verification usually takes 1-2 business days.");else h("CloudFront create access appears enabled (validation passed)")}}n("Checking S3 access...");try{let{S3Client:G}=await Promise.resolve().then(() => (I0(),l$));await new G("us-east-1").listBuckets(),h("S3 access is enabled")}catch(G){v(`S3 check failed: ${G.message}`)}n("Checking ACM (SSL certificates) access...");try{await new $1("us-east-1").listCertificates(),h("ACM access is enabled")}catch(G){v(`ACM check failed: ${G.message}`)}if(n("Checking configuration..."),L3("cloud.config.ts"))h("cloud.config.ts found");else v("cloud.config.ts not found"),X("Run: cloud init")}),$.command("regions","List available AWS regions").action(async()=>{R("AWS Regions");let Y=new N("Fetching regions...");Y.start();let Z=await q5();Y.stop(),Z.forEach((Q)=>{console.log(` ${Q}`)})}),$.command("version","Show the version of the CLI").alias("v").action(()=>{console.log(`ts-cloud v${J}`)})}z0();Y0();class a0{client;region;endpoint;constructor($="us-east-1",J){this.region=$,this.endpoint=J?.endpoint,this.client=new i}async request($,J){if(this.endpoint){let Y=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${$}`},body:JSON.stringify(J)});if(!Y.ok){let Z=await Y.text();throw Error(`DynamoDB request failed: ${Y.status} ${Z}`)}return Y.json()}return this.client.request({service:"dynamodb",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${$}`},body:JSON.stringify(J)})}async createTable($){return this.request("CreateTable",$)}async deleteTable($){return this.request("DeleteTable",$)}async describeTable($){return this.request("DescribeTable",$)}async listTables($){return this.request("ListTables",$||{})}async putItem($){return this.request("PutItem",$)}async getItem($){return this.request("GetItem",$)}async updateItem($){return this.request("UpdateItem",$)}async deleteItem($){return this.request("DeleteItem",$)}async query($){return this.request("Query",$)}async scan($){return this.request("Scan",$)}async batchWriteItem($){return this.request("BatchWriteItem",$)}async batchGetItem($){return this.request("BatchGetItem",$)}async updateTimeToLive($){return this.request("UpdateTimeToLive",$)}static marshal($){let J={};for(let[Y,Z]of Object.entries($))J[Y]=a0.marshalValue(Z);return J}static marshalValue($){if($===null||$===void 0)return{NULL:!0};if(typeof $==="string")return{S:$};if(typeof $==="number")return{N:String($)};if(typeof $==="boolean")return{BOOL:$};if(Array.isArray($))return{L:$.map((J)=>a0.marshalValue(J))};if(typeof $==="object")return{M:a0.marshal($)};return{S:String($)}}static unmarshal($){let J={};for(let[Y,Z]of Object.entries($))J[Y]=a0.unmarshalValue(Z);return J}static unmarshalValue($){if($.S!==void 0)return $.S;if($.N!==void 0)return Number($.N);if($.BOOL!==void 0)return $.BOOL;if($.NULL!==void 0)return null;if($.L!==void 0)return $.L.map((J)=>a0.unmarshalValue(J));if($.M!==void 0)return a0.unmarshal($.M);if($.SS!==void 0)return $.SS;if($.NS!==void 0)return $.NS.map(Number);return null}}function XG($){$.command("analytics:sites:list","List all analytics sites").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J)=>{R("Analytics Sites");try{let Y=new a0(J.region),Z=new N("Fetching sites...");Z.start();let Q=await Y.scan({TableName:J.table,FilterExpression:"begins_with(pk, :pk)",ExpressionAttributeValues:{":pk":{S:"SITE#"}}});if(Z.succeed(`Found ${Q.Items?.length||0} site(s)`),!Q.Items||Q.Items.length===0){X("No analytics sites found"),X("Use `cloud analytics:sites:create` to create a new site");return}let G=Q.Items.map((W)=>a0.unmarshal(W));p(["ID","Name","Domains","Active","Created"],G.map((W)=>[W.siteId||"N/A",W.name||"Unnamed",(W.domains||[]).join(", ")||"-",W.isActive?"Yes":"No",W.createdAt?new Date(W.createdAt).toLocaleDateString():"N/A"]))}catch(Y){w(`Failed to list sites: ${Y.message}`),process.exit(1)}}),$.command("analytics:sites:create","Create a new analytics site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--name <name>","Site name").option("--domain <domain>","Site domain(s) (can be specified multiple times)").action(async(J)=>{R("Create Analytics Site");try{let Y=new a0(J.region),Z=J.name||await q0("Site name","My Site"),Q=[];if(J.domain)Q=Array.isArray(J.domain)?J.domain:[J.domain];else Q=(await q0("Site domains (comma-separated)","example.com")).split(",").map((F)=>F.trim()).filter(Boolean);if(X(`
8123
8128
  Creating site: ${Z}`),X(`Domains: ${Q.join(", ")}`),!await u(`
8124
8129
  Create this site?`,!0)){X("Operation cancelled");return}let W=new N("Creating site...");W.start();let z=`site_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,U=new Date().toISOString();await Y.putItem({TableName:J.table,Item:{pk:{S:`SITE#${z}`},sk:{S:`SITE#${z}`},siteId:{S:z},name:{S:Z},domains:{L:Q.map((H)=>({S:H}))},isActive:{BOOL:!0},createdAt:{S:U},updatedAt:{S:U}}}),W.succeed("Site created successfully"),h(`
8125
8130
  Site ID: ${z}`),X(`
8126
- Add the tracking script to your website:`),X(` <script src="https://analytics.stacksjs.com/track.js" data-site-id="${z}"></script>`)}catch(Y){w(`Failed to create site: ${Y.message}`),process.exit(1)}}),$.command("analytics:sites:update <siteId>","Update an analytics site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--name <name>","New site name").option("--domain <domain>","Set domains (replaces existing)").option("--active <boolean>","Set site active/inactive status").action(async(J,Y)=>{R("Update Analytics Site");try{let Z=new a0(Y.region),Q=await Z.getItem({TableName:Y.table,Key:{pk:{S:`SITE#${J}`},sk:{S:`SITE#${J}`}}});if(!Q.Item)w(`Site not found: ${J}`),process.exit(1);let G=a0.unmarshal(Q.Item);X(`Updating site: ${G.name||"Unnamed"} (${J})`),X("");let W=[],z={},U={};if(Y.name)W.push("#n = :name"),z["#n"]="name",U[":name"]={S:Y.name},X(` Name: ${G.name} -> ${Y.name}`);if(Y.domain!==void 0){let H=Array.isArray(Y.domain)?Y.domain:[Y.domain];W.push("domains = :domains"),U[":domains"]={L:H.map((F)=>({S:F}))},X(` Domains: ${JSON.stringify(G.domains||[])} -> ${JSON.stringify(H)}`)}if(Y.active!==void 0){let H=Y.active==="true"||Y.active==="1";W.push("isActive = :active"),U[":active"]={BOOL:H},X(` Active: ${G.isActive} -> ${H}`)}if(W.length===0){v("No updates specified. Use --name, --domain, or --active options.");return}W.push("updatedAt = :updatedAt"),U[":updatedAt"]={S:new Date().toISOString()},await Z.updateItem({TableName:Y.table,Key:{pk:{S:`SITE#${J}`},sk:{S:`SITE#${J}`}},UpdateExpression:`SET ${W.join(", ")}`,ExpressionAttributeNames:Object.keys(z).length>0?z:void 0,ExpressionAttributeValues:U}),X(""),h("Site updated successfully")}catch(Z){w(`Failed to update site: ${Z.message}`),process.exit(1)}}),$.command("analytics:query <siteId>","Query analytics data for a site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--limit <n>","Max items to return",{default:"10"}).option("--type <type>","Filter by type (pageview, event, etc.)").action(async(J,Y)=>{R(`Analytics Data: ${J}`);try{let Z=new a0(Y.region),Q=new N("Querying data...");Q.start();let G=await Z.query({TableName:Y.table,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:`SITE#${J}`}},ScanIndexForward:!1,Limit:parseInt(Y.limit,10)});if(Q.succeed(`Found ${G.Items?.length||0} items`),!G.Items||G.Items.length===0){X("No data found for this site");return}let W=G.Items.map((z)=>a0.unmarshal(z));for(let z of W){if(X(""),X(`SK: ${z.sk}`),z.path)X(` Path: ${z.path}`);if(z.timestamp)X(` Time: ${z.timestamp}`);if(z.visitorId)X(` Visitor: ${z.visitorId}`);if(z.browser)X(` Browser: ${z.browser}`);if(z.country)X(` Country: ${z.country}`)}}catch(Z){w(`Failed to query data: ${Z.message}`),process.exit(1)}}),$.command("analytics:realtime <siteId>","Check realtime visitors for a site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--minutes <n>","Minutes to look back",{default:"5"}).action(async(J,Y)=>{R(`Realtime: ${J}`);try{let Z=new a0(Y.region),Q=new N("Checking realtime...");Q.start();let G=parseInt(Y.minutes,10),W=new Date(Date.now()-G*60*1000),z=await Z.query({TableName:Y.table,KeyConditionExpression:"pk = :pk AND sk BETWEEN :start AND :end",ExpressionAttributeValues:{":pk":{S:`SITE#${J}`},":start":{S:`PAGEVIEW#${W.toISOString()}`},":end":{S:"PAGEVIEW#Z"}},ScanIndexForward:!1});if(Q.succeed(`Found ${z.Items?.length||0} pageviews in last ${G} minutes`),!z.Items||z.Items.length===0){v("No recent pageviews found"),X(""),X("Possible issues:"),X(" 1. Tracking script not installed correctly"),X(" 2. Site ID mismatch"),X(" 3. CORS or network issues");return}let U=z.Items.map((B)=>a0.unmarshal(B)),H=new Set(U.map((B)=>B.visitorId)).size;X(""),h(`${H} unique visitor(s) online`),X("");let F={};for(let B of U){let K=B.path||"/";F[K]=(F[K]||0)+1}X("Active pages:");for(let[B,K]of Object.entries(F).sort((O,A)=>A[1]-O[1]).slice(0,5))X(` ${B}: ${K} view(s)`);X(""),X("Recent pageviews:");for(let B of U.slice(0,5))X(` ${B.timestamp} - ${B.path} (${B.browser||"Unknown"})`)}catch(Z){w(`Failed to check realtime: ${Z.message}`),process.exit(1)}})}z0();import{existsSync as i2,statSync as HX}from"node:fs";import{readFile as M$,writeFile as S9}from"node:fs/promises";import{mkdtempSync as I3}from"node:fs";import{tmpdir as k3}from"node:os";import{dirname as h3,extname as EG,join as v0,normalize as b3}from"node:path";import{fileURLToPath as y3}from"node:url";await z8([a7(),ZG()]);await j$();var aF={mysql:"/var/lib/pantry/mysql/mysqld.sock",mariadb:"/var/lib/pantry/mariadb/mariadbd.sock"};function e7($){return/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test($)}function M3($){if($==="postgres"||$==="pgsql")return"postgres";if($==="mariadb")return"mariadb";return"mysql"}function KG($){let J=$.infrastructure?.compute,Y=$.infrastructure?.appDatabase?.engine;if(Y)return M3(Y);let Z=J?.managedServices??{};if(Z.postgres)return"postgres";if(Z.mariadb)return"mariadb";return"mysql"}var BG=($)=>$.replace(/`/g,"``"),X2=($)=>$.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),L$=($)=>`"${$.replace(/"/g,'""')}"`,o7=($)=>`'${$.replace(/'/g,"''")}'`;function OG($,J){return[`mysql --socket=${$==="mariadb"?aF.mariadb:aF.mysql} -u root <<'TS_CLOUD_SQL_EOF'`,...J,"TS_CLOUD_SQL_EOF"]}function VG($){return["psql -h 127.0.0.1 -p 5432 -U postgres -tA <<'TS_CLOUD_PG_EOF'",...$,"TS_CLOUD_PG_EOF"]}function q3($){if($==="postgres")return VG(["SELECT 'DB=' || datname FROM pg_database WHERE datistemplate = false;","SELECT 'USER=' || usename FROM pg_user;"]);return OG($,["SELECT CONCAT('DB=', schema_name) FROM information_schema.schemata WHERE schema_name NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys');","SELECT DISTINCT CONCAT('USER=', User) FROM mysql.user WHERE User NOT IN ('root', 'mysql.sys', 'mysql.session', 'mysql.infoschema', 'debian-sys-maint');"])}function T3($,J){if($==="postgres")return VG([`SELECT 'CREATE DATABASE ${L$(J)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${o7(J)})\\gexec`]);return OG($,[`CREATE DATABASE IF NOT EXISTS \`${BG(J)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`])}function w3($,J){let{username:Y,password:Z,database:Q,access:G}=J;if($==="postgres"){let U=["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${o7(Y)}) THEN CREATE ROLE ${L$(Y)} LOGIN PASSWORD ${o7(Z)};`,` ELSE ALTER ROLE ${L$(Y)} LOGIN PASSWORD ${o7(Z)}; END IF;`,"END $$;"];if(Q)U.push(G==="readonly"?`GRANT CONNECT ON DATABASE ${L$(Q)} TO ${L$(Y)};`:`GRANT ALL PRIVILEGES ON DATABASE ${L$(Q)} TO ${L$(Y)};`);return VG(U)}let W=G==="readonly"?"SELECT":"ALL PRIVILEGES",z=[`CREATE USER IF NOT EXISTS '${X2(Y)}'@'%' IDENTIFIED BY '${X2(Z)}';`,`CREATE USER IF NOT EXISTS '${X2(Y)}'@'localhost' IDENTIFIED BY '${X2(Z)}';`,`ALTER USER '${X2(Y)}'@'%' IDENTIFIED BY '${X2(Z)}';`,`ALTER USER '${X2(Y)}'@'localhost' IDENTIFIED BY '${X2(Z)}';`];if(Q)z.push(`GRANT ${W} ON \`${BG(Q)}\`.* TO '${X2(Y)}'@'%';`,`GRANT ${W} ON \`${BG(Q)}\`.* TO '${X2(Y)}'@'localhost';`);return z.push("FLUSH PRIVILEGES;"),OG($,z)}function D3($){let J=[],Y=[];for(let Z of $.split(`
8127
- `)){let Q=Z.trim();if(Q.startsWith("DB="))J.push(Q.slice(3));else if(Q.startsWith("USER="))Y.push(Q.slice(5))}return{databases:[...new Set(J)].filter(Boolean).sort(),users:[...new Set(Y)].filter(Boolean).sort()}}async function AG($,J,Y,Z){let Q;try{Q=Y1({config:$})}catch(U){return{ok:!1,error:`Could not initialize the cloud driver: ${U?.message??U}`}}let G=$.project.slug,W=await Q.findComputeTargets({slug:G,environment:J,role:"app"});if(!W.length)return{ok:!1,error:"No app server target was found for this environment."};let z=await Q.runRemoteDeploy({targets:[W[0]],commands:["set -uo pipefail",...Y],comment:Z,tags:{Project:G,Environment:J,Role:"app"}});return{ok:z.success,stdout:z.perInstance?.[0]?.output??"",stderr:z.perInstance?.[0]?.error??z.error??""}}async function tF($,J){let Y=KG($),Z=await AG($,J,q3(Y),"ts-cloud db:list"),Q=Z.ok&&Z.stdout?D3(Z.stdout):{databases:[],users:[]};return{...Z,engine:Y,...Q}}async function sF($,J,Y){let Z=KG($);return AG($,J,T3(Z,Y),`ts-cloud db:create ${Y}`)}async function oF($,J,Y){let Z=KG($);return AG($,J,w3(Z,Y),`ts-cloud db:user ${Y.username}`)}J8();H2();O$();await j$();var R3=["restart","reload","start","stop","enable","disable"],eF=65536;function $5($){return $.length<=eF?$:`${$.slice(0,eF)}
8131
+ Add the tracking script to your website:`),X(` <script src="https://analytics.stacksjs.com/track.js" data-site-id="${z}"></script>`)}catch(Y){w(`Failed to create site: ${Y.message}`),process.exit(1)}}),$.command("analytics:sites:update <siteId>","Update an analytics site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--name <name>","New site name").option("--domain <domain>","Set domains (replaces existing)").option("--active <boolean>","Set site active/inactive status").action(async(J,Y)=>{R("Update Analytics Site");try{let Z=new a0(Y.region),Q=await Z.getItem({TableName:Y.table,Key:{pk:{S:`SITE#${J}`},sk:{S:`SITE#${J}`}}});if(!Q.Item)w(`Site not found: ${J}`),process.exit(1);let G=a0.unmarshal(Q.Item);X(`Updating site: ${G.name||"Unnamed"} (${J})`),X("");let W=[],z={},U={};if(Y.name)W.push("#n = :name"),z["#n"]="name",U[":name"]={S:Y.name},X(` Name: ${G.name} -> ${Y.name}`);if(Y.domain!==void 0){let H=Array.isArray(Y.domain)?Y.domain:[Y.domain];W.push("domains = :domains"),U[":domains"]={L:H.map((F)=>({S:F}))},X(` Domains: ${JSON.stringify(G.domains||[])} -> ${JSON.stringify(H)}`)}if(Y.active!==void 0){let H=Y.active==="true"||Y.active==="1";W.push("isActive = :active"),U[":active"]={BOOL:H},X(` Active: ${G.isActive} -> ${H}`)}if(W.length===0){v("No updates specified. Use --name, --domain, or --active options.");return}W.push("updatedAt = :updatedAt"),U[":updatedAt"]={S:new Date().toISOString()},await Z.updateItem({TableName:Y.table,Key:{pk:{S:`SITE#${J}`},sk:{S:`SITE#${J}`}},UpdateExpression:`SET ${W.join(", ")}`,ExpressionAttributeNames:Object.keys(z).length>0?z:void 0,ExpressionAttributeValues:U}),X(""),h("Site updated successfully")}catch(Z){w(`Failed to update site: ${Z.message}`),process.exit(1)}}),$.command("analytics:query <siteId>","Query analytics data for a site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--limit <n>","Max items to return",{default:"10"}).option("--type <type>","Filter by type (pageview, event, etc.)").action(async(J,Y)=>{R(`Analytics Data: ${J}`);try{let Z=new a0(Y.region),Q=new N("Querying data...");Q.start();let G=await Z.query({TableName:Y.table,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:`SITE#${J}`}},ScanIndexForward:!1,Limit:parseInt(Y.limit,10)});if(Q.succeed(`Found ${G.Items?.length||0} items`),!G.Items||G.Items.length===0){X("No data found for this site");return}let W=G.Items.map((z)=>a0.unmarshal(z));for(let z of W){if(X(""),X(`SK: ${z.sk}`),z.path)X(` Path: ${z.path}`);if(z.timestamp)X(` Time: ${z.timestamp}`);if(z.visitorId)X(` Visitor: ${z.visitorId}`);if(z.browser)X(` Browser: ${z.browser}`);if(z.country)X(` Country: ${z.country}`)}}catch(Z){w(`Failed to query data: ${Z.message}`),process.exit(1)}}),$.command("analytics:realtime <siteId>","Check realtime visitors for a site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--minutes <n>","Minutes to look back",{default:"5"}).action(async(J,Y)=>{R(`Realtime: ${J}`);try{let Z=new a0(Y.region),Q=new N("Checking realtime...");Q.start();let G=parseInt(Y.minutes,10),W=new Date(Date.now()-G*60*1000),z=await Z.query({TableName:Y.table,KeyConditionExpression:"pk = :pk AND sk BETWEEN :start AND :end",ExpressionAttributeValues:{":pk":{S:`SITE#${J}`},":start":{S:`PAGEVIEW#${W.toISOString()}`},":end":{S:"PAGEVIEW#Z"}},ScanIndexForward:!1});if(Q.succeed(`Found ${z.Items?.length||0} pageviews in last ${G} minutes`),!z.Items||z.Items.length===0){v("No recent pageviews found"),X(""),X("Possible issues:"),X(" 1. Tracking script not installed correctly"),X(" 2. Site ID mismatch"),X(" 3. CORS or network issues");return}let U=z.Items.map((B)=>a0.unmarshal(B)),H=new Set(U.map((B)=>B.visitorId)).size;X(""),h(`${H} unique visitor(s) online`),X("");let F={};for(let B of U){let K=B.path||"/";F[K]=(F[K]||0)+1}X("Active pages:");for(let[B,K]of Object.entries(F).sort((O,A)=>A[1]-O[1]).slice(0,5))X(` ${B}: ${K} view(s)`);X(""),X("Recent pageviews:");for(let B of U.slice(0,5))X(` ${B.timestamp} - ${B.path} (${B.browser||"Unknown"})`)}catch(Z){w(`Failed to check realtime: ${Z.message}`),process.exit(1)}})}z0();import{existsSync as i2,statSync as HX}from"node:fs";import{readFile as M$,writeFile as S9}from"node:fs/promises";import{mkdtempSync as x3}from"node:fs";import{tmpdir as I3}from"node:os";import{dirname as k3,extname as EG,join as v0,normalize as h3}from"node:path";import{fileURLToPath as b3}from"node:url";await z8([a7(),ZG()]);await j$();var aF={mysql:"/var/lib/pantry/mysql/mysqld.sock",mariadb:"/var/lib/pantry/mariadb/mariadbd.sock"};function e7($){return/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test($)}function E3($){if($==="postgres"||$==="pgsql")return"postgres";if($==="mariadb")return"mariadb";return"mysql"}function KG($){let J=$.infrastructure?.compute,Y=$.infrastructure?.appDatabase?.engine;if(Y)return E3(Y);let Z=J?.managedServices??{};if(Z.postgres)return"postgres";if(Z.mariadb)return"mariadb";return"mysql"}var BG=($)=>$.replace(/`/g,"``"),X2=($)=>$.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),L$=($)=>`"${$.replace(/"/g,'""')}"`,o7=($)=>`'${$.replace(/'/g,"''")}'`;function OG($,J){return[`mysql --socket=${$==="mariadb"?aF.mariadb:aF.mysql} -u root <<'TS_CLOUD_SQL_EOF'`,...J,"TS_CLOUD_SQL_EOF"]}function VG($){return["psql -h 127.0.0.1 -p 5432 -U postgres -tA <<'TS_CLOUD_PG_EOF'",...$,"TS_CLOUD_PG_EOF"]}function M3($){if($==="postgres")return VG(["SELECT 'DB=' || datname FROM pg_database WHERE datistemplate = false;","SELECT 'USER=' || usename FROM pg_user;"]);return OG($,["SELECT CONCAT('DB=', schema_name) FROM information_schema.schemata WHERE schema_name NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys');","SELECT DISTINCT CONCAT('USER=', User) FROM mysql.user WHERE User NOT IN ('root', 'mysql.sys', 'mysql.session', 'mysql.infoschema', 'debian-sys-maint');"])}function q3($,J){if($==="postgres")return VG([`SELECT 'CREATE DATABASE ${L$(J)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${o7(J)})\\gexec`]);return OG($,[`CREATE DATABASE IF NOT EXISTS \`${BG(J)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`])}function T3($,J){let{username:Y,password:Z,database:Q,access:G}=J;if($==="postgres"){let U=["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${o7(Y)}) THEN CREATE ROLE ${L$(Y)} LOGIN PASSWORD ${o7(Z)};`,` ELSE ALTER ROLE ${L$(Y)} LOGIN PASSWORD ${o7(Z)}; END IF;`,"END $$;"];if(Q)U.push(G==="readonly"?`GRANT CONNECT ON DATABASE ${L$(Q)} TO ${L$(Y)};`:`GRANT ALL PRIVILEGES ON DATABASE ${L$(Q)} TO ${L$(Y)};`);return VG(U)}let W=G==="readonly"?"SELECT":"ALL PRIVILEGES",z=[`CREATE USER IF NOT EXISTS '${X2(Y)}'@'%' IDENTIFIED BY '${X2(Z)}';`,`CREATE USER IF NOT EXISTS '${X2(Y)}'@'localhost' IDENTIFIED BY '${X2(Z)}';`,`ALTER USER '${X2(Y)}'@'%' IDENTIFIED BY '${X2(Z)}';`,`ALTER USER '${X2(Y)}'@'localhost' IDENTIFIED BY '${X2(Z)}';`];if(Q)z.push(`GRANT ${W} ON \`${BG(Q)}\`.* TO '${X2(Y)}'@'%';`,`GRANT ${W} ON \`${BG(Q)}\`.* TO '${X2(Y)}'@'localhost';`);return z.push("FLUSH PRIVILEGES;"),OG($,z)}function w3($){let J=[],Y=[];for(let Z of $.split(`
8132
+ `)){let Q=Z.trim();if(Q.startsWith("DB="))J.push(Q.slice(3));else if(Q.startsWith("USER="))Y.push(Q.slice(5))}return{databases:[...new Set(J)].filter(Boolean).sort(),users:[...new Set(Y)].filter(Boolean).sort()}}async function AG($,J,Y,Z){let Q;try{Q=Y1({config:$})}catch(U){return{ok:!1,error:`Could not initialize the cloud driver: ${U?.message??U}`}}let G=$.project.slug,W=await Q.findComputeTargets({slug:G,environment:J,role:"app"});if(!W.length)return{ok:!1,error:"No app server target was found for this environment."};let z=await Q.runRemoteDeploy({targets:[W[0]],commands:["set -uo pipefail",...Y],comment:Z,tags:{Project:G,Environment:J,Role:"app"}});return{ok:z.success,stdout:z.perInstance?.[0]?.output??"",stderr:z.perInstance?.[0]?.error??z.error??""}}async function tF($,J){let Y=KG($),Z=await AG($,J,M3(Y),"ts-cloud db:list"),Q=Z.ok&&Z.stdout?w3(Z.stdout):{databases:[],users:[]};return{...Z,engine:Y,...Q}}async function sF($,J,Y){let Z=KG($);return AG($,J,q3(Z,Y),`ts-cloud db:create ${Y}`)}async function oF($,J,Y){let Z=KG($);return AG($,J,T3(Z,Y),`ts-cloud db:user ${Y.username}`)}J8();H2();O$();await j$();var D3=["restart","reload","start","stop","enable","disable"],eF=65536;function $5($){return $.length<=eF?$:`${$.slice(0,eF)}
8128
8133
 
8129
- [output truncated]`}function N3($){return/^[A-Za-z0-9_.@:-]+$/.test($)}function _G($){return/^[A-Za-z0-9_-]+$/.test($)}function S3($){return $.charAt(0).toUpperCase()+$.slice(1)}function jG($,J){let Y=[],Z=J.servicesDetail??J.services??[];for(let W of Z){let z=String(W?.name??"");if(!z||!N3(z))continue;for(let U of R3)Y.push({id:`${U}:${z}`,label:`${S3(U)} ${z}`,group:"service",target:z,mutates:!0,confirm:z,danger:U==="stop"||U==="disable"})}for(let[W,z]of Object.entries($.sites??{})){if(!z||!_G(W))continue;let U=p0(z);if(U==="server-app"||U==="server-php")Y.push({id:`rollback:${W}`,label:`Rollback ${W}`,group:"deploy",target:W,mutates:!0,confirm:W,danger:!0})}let Q=new Set;for(let W of J.workers??[]){let z=String(W?.name??"").split(":")[0];if(z&&_G(z))Q.add(z)}for(let W of Q)Y.push({id:`worker:restart:${W}`,label:`Restart workers (${W})`,group:"worker",target:W,mutates:!0,confirm:W});for(let[W,z]of Object.entries($.sites??{})){if(!z||!_G(W))continue;if(z.scheduler||z.schedule)Y.push({id:`scheduler:run:${W}`,label:`Run scheduler (${W})`,group:"scheduler",target:W,mutates:!0,confirm:W})}if($.infrastructure?.compute?.backups?.enabled){if(Y.push({id:"backup:run",label:"Run backup now",group:"backup",target:"backup",mutates:!0,confirm:"backup"}),$.infrastructure?.appDatabase)Y.push({id:"backup:restore",label:"Restore latest DB backup",group:"backup",target:"database",mutates:!0,confirm:"restore",danger:!0})}return Y}function YX($,J,Y){return jG(J,Y).find((Z)=>Z.id===$)}function P3($,J){let Y=$==="enable"||$==="disable"?`systemctl is-enabled ${J} 2>/dev/null || true`:`systemctl is-active ${J} 2>/dev/null || true`;return["set -o pipefail",`systemctl ${$} ${J}`,Y]}function C3(){return`eval "$(cd ${P1} && pantry env 2>/dev/null)"`}function $X($,J){let Y=`/var/www/${$}/current`;return["set -uo pipefail",`[ -d ${Y} ] || { echo "site ${$} has no current release" >&2; exit 1; }`,`cd ${Y} && ${C3()} && php artisan ${J}`]}function x3(){return["set -uo pipefail",`[ -x ${XQ} ] || { echo "scheduled backups are not provisioned on this server" >&2; exit 1; }`,XQ]}function JX($,J,Y){return{operation:$,command:J,ok:Y.success,stdout:$5(Y.perInstance?.[0]?.output??""),stderr:$5(Y.perInstance?.[0]?.error??Y.error??"")}}async function ZX($,J,Y,Z={}){let Q=$.project.slug,G;try{G=Y1({config:$})}catch(B){return{operation:Y.id,ok:!1,error:`Could not initialize the cloud driver: ${B?.message??B}`}}let W={driver:G,slug:Q,environment:J,role:"app"};if(Y.group==="deploy"){let B=Z.to&&/^[A-Za-z0-9._-]+$/.test(Z.to)?Z.to:void 0,K=await pQ(W,{siteName:Y.target,to:B});return JX(Y.id,`rollback ${Y.target}${B?` → ${B}`:""}`,K)}if(Y.id==="backup:restore"){let B=await rQ(W,{database:$.infrastructure?.appDatabase});return JX(Y.id,"db restore",B)}let z=await G.findComputeTargets({slug:Q,environment:J,role:"app"});if(!z.length)return{operation:Y.id,ok:!1,error:"No app server target was found for this environment."};let U,H;if(Y.group==="service"){let[B,...K]=Y.id.split(":");U=P3(B,K.join(":")),H=`systemctl ${B} ${Y.target}`}else if(Y.group==="worker")U=$X(Y.target,"queue:restart"),H=`queue:restart (${Y.target})`;else if(Y.group==="scheduler")U=$X(Y.target,"schedule:run"),H=`schedule:run (${Y.target})`;else if(Y.id==="backup:run")U=x3(),H="ts-cloud backup";else return{operation:Y.id,ok:!1,error:"Unknown operation."};let F=await G.runRemoteDeploy({targets:[z[0]],commands:U,comment:`ts-cloud dashboard:${Y.id}`,tags:{Project:Q,Environment:J,Role:"app"}});return{operation:Y.id,command:H,ok:F.success,stdout:$5(F.perInstance?.[0]?.output??""),stderr:$5(F.perInstance?.[0]?.error??F.error??"")}}await d7();oQ();var v3="127.0.0.1",f3=7676,QX=65536,Z8=h3(y3(import.meta.url)),g3={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".ico":"image/x-icon"};function F0($,J=200){return new Response(JSON.stringify($,null,2),{status:J,headers:{"content-type":"application/json; charset=utf-8"}})}function GX($,J=200){return new Response($,{status:J,headers:{"content-type":"text/plain; charset=utf-8"}})}function u3($,J){if(J)return J;return Object.keys($.environments??{})[0]??"production"}async function d3($){let J=[v0(Z8,"..","..","..","..",".env"),v0($,".env"),v0($,".env.local"),v0($,".env.production")];for(let Y of J){if(!i2(Y))continue;let Z=await M$(Y,"utf8").catch(()=>"");for(let Q of Z.split(`
8130
- `)){let G=Q.trim();if(!G||G.startsWith("#")||!G.includes("="))continue;let W=G.indexOf("="),z=G.slice(0,W).trim(),U=G.slice(W+1).trim();if(!/^[A-Z_][A-Z0-9_]*$/i.test(z)||process.env[z]!=null)continue;if(U.startsWith('"')&&U.endsWith('"')||U.startsWith("'")&&U.endsWith("'"))U=U.slice(1,-1);process.env[z]=U}}}function c3($){return[v0($,"config","cloud.ts"),v0($,"config","cloud.js"),v0($,"cloud.config.ts"),v0($,"cloud.config.js")].find((Y)=>i2(Y))??null}function Q8($){return $.infrastructure?.compute?.sshKeys??[]}function WX($,J){let Y=$.infrastructure??($.infrastructure={}),Z=Y.compute??(Y.compute={});Z.sshKeys=J}function m3($,J,Y){let Z=$.sites??($.sites={});Z[J]=Y}async function S2($){return await $.json().catch(()=>({}))}function l3($){if($.mode==="hybrid")return"hybrid";return $.infrastructure?.compute?"server":"serverless"}async function E$($,J){let Y=l3($),Z={mode:Y,environment:J,environments:Object.keys($.environments??{})};try{return{...(Y==="serverless"?await i7($,J):await YG($,J))??{},...Z}}catch{return{...Z}}}function p3($){let J=[v0($,"packages","ui"),v0(Z8,"..","..","..","ui"),v0(Z8,"..","..","ui"),v0(Z8,"..","ui-src"),v0(Z8,"..","..","ui-src"),v0(Z8,"..","..","dist","ui-src")];for(let Y of J)if(i2(v0(Y,"pages"))&&i2(v0(Y,"package.json")))return Y;return null}async function LG($,J){let Y=p3($);if(!Y)return null;try{let Z=I3(v0(k3(),"ts-cloud-dashboard-")),Q=v0(Y,"node_modules",".bin","stx"),G=i2(Q)?[Q,"build","--pages","pages","--out",Z,"--no-sitemap","--no-cache"]:["bunx","--bun","@stacksjs/stx","build","--pages","pages","--out",Z,"--no-sitemap","--no-cache"],W=Bun.spawn(G,{cwd:Y,stdout:"pipe",stderr:"pipe",env:{...process.env,TSCLOUD_DASHBOARD_DATA:JSON.stringify(J)}}),[z,U,H]=await Promise.all([new Response(W.stdout).text(),new Response(W.stderr).text(),W.exited]);if(H!==0){if(process.env.TSCLOUD_DASHBOARD_VERBOSE)console.warn(`ts-cloud dashboard: live UI build failed; serving the pre-built UI.
8134
+ [output truncated]`}function R3($){return/^[A-Za-z0-9_.@:-]+$/.test($)}function _G($){return/^[A-Za-z0-9_-]+$/.test($)}function N3($){return $.charAt(0).toUpperCase()+$.slice(1)}function jG($,J){let Y=[],Z=J.servicesDetail??J.services??[];for(let W of Z){let z=String(W?.name??"");if(!z||!R3(z))continue;for(let U of D3)Y.push({id:`${U}:${z}`,label:`${N3(U)} ${z}`,group:"service",target:z,mutates:!0,confirm:z,danger:U==="stop"||U==="disable"})}for(let[W,z]of Object.entries($.sites??{})){if(!z||!_G(W))continue;let U=p0(z);if(U==="server-app"||U==="server-php")Y.push({id:`rollback:${W}`,label:`Rollback ${W}`,group:"deploy",target:W,mutates:!0,confirm:W,danger:!0})}let Q=new Set;for(let W of J.workers??[]){let z=String(W?.name??"").split(":")[0];if(z&&_G(z))Q.add(z)}for(let W of Q)Y.push({id:`worker:restart:${W}`,label:`Restart workers (${W})`,group:"worker",target:W,mutates:!0,confirm:W});for(let[W,z]of Object.entries($.sites??{})){if(!z||!_G(W))continue;if(z.scheduler||z.schedule)Y.push({id:`scheduler:run:${W}`,label:`Run scheduler (${W})`,group:"scheduler",target:W,mutates:!0,confirm:W})}if($.infrastructure?.compute?.backups?.enabled){if(Y.push({id:"backup:run",label:"Run backup now",group:"backup",target:"backup",mutates:!0,confirm:"backup"}),$.infrastructure?.appDatabase)Y.push({id:"backup:restore",label:"Restore latest DB backup",group:"backup",target:"database",mutates:!0,confirm:"restore",danger:!0})}return Y}function YX($,J,Y){return jG(J,Y).find((Z)=>Z.id===$)}function S3($,J){let Y=$==="enable"||$==="disable"?`systemctl is-enabled ${J} 2>/dev/null || true`:`systemctl is-active ${J} 2>/dev/null || true`;return["set -o pipefail",`systemctl ${$} ${J}`,Y]}function P3(){return`eval "$(cd ${P1} && pantry env 2>/dev/null)"`}function $X($,J){let Y=`/var/www/${$}/current`;return["set -uo pipefail",`[ -d ${Y} ] || { echo "site ${$} has no current release" >&2; exit 1; }`,`cd ${Y} && ${P3()} && php artisan ${J}`]}function C3(){return["set -uo pipefail",`[ -x ${XQ} ] || { echo "scheduled backups are not provisioned on this server" >&2; exit 1; }`,XQ]}function JX($,J,Y){return{operation:$,command:J,ok:Y.success,stdout:$5(Y.perInstance?.[0]?.output??""),stderr:$5(Y.perInstance?.[0]?.error??Y.error??"")}}async function ZX($,J,Y,Z={}){let Q=$.project.slug,G;try{G=Y1({config:$})}catch(B){return{operation:Y.id,ok:!1,error:`Could not initialize the cloud driver: ${B?.message??B}`}}let W={driver:G,slug:Q,environment:J,role:"app"};if(Y.group==="deploy"){let B=Z.to&&/^[A-Za-z0-9._-]+$/.test(Z.to)?Z.to:void 0,K=await pQ(W,{siteName:Y.target,to:B});return JX(Y.id,`rollback ${Y.target}${B?` → ${B}`:""}`,K)}if(Y.id==="backup:restore"){let B=await rQ(W,{database:$.infrastructure?.appDatabase});return JX(Y.id,"db restore",B)}let z=await G.findComputeTargets({slug:Q,environment:J,role:"app"});if(!z.length)return{operation:Y.id,ok:!1,error:"No app server target was found for this environment."};let U,H;if(Y.group==="service"){let[B,...K]=Y.id.split(":");U=S3(B,K.join(":")),H=`systemctl ${B} ${Y.target}`}else if(Y.group==="worker")U=$X(Y.target,"queue:restart"),H=`queue:restart (${Y.target})`;else if(Y.group==="scheduler")U=$X(Y.target,"schedule:run"),H=`schedule:run (${Y.target})`;else if(Y.id==="backup:run")U=C3(),H="ts-cloud backup";else return{operation:Y.id,ok:!1,error:"Unknown operation."};let F=await G.runRemoteDeploy({targets:[z[0]],commands:U,comment:`ts-cloud dashboard:${Y.id}`,tags:{Project:Q,Environment:J,Role:"app"}});return{operation:Y.id,command:H,ok:F.success,stdout:$5(F.perInstance?.[0]?.output??""),stderr:$5(F.perInstance?.[0]?.error??F.error??"")}}await d7();oQ();var y3="127.0.0.1",v3=7676,QX=65536,Z8=k3(b3(import.meta.url)),f3={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".ico":"image/x-icon"};function F0($,J=200){return new Response(JSON.stringify($,null,2),{status:J,headers:{"content-type":"application/json; charset=utf-8"}})}function GX($,J=200){return new Response($,{status:J,headers:{"content-type":"text/plain; charset=utf-8"}})}function g3($,J){if(J)return J;return Object.keys($.environments??{})[0]??"production"}async function u3($){let J=[v0(Z8,"..","..","..","..",".env"),v0($,".env"),v0($,".env.local"),v0($,".env.production")];for(let Y of J){if(!i2(Y))continue;let Z=await M$(Y,"utf8").catch(()=>"");for(let Q of Z.split(`
8135
+ `)){let G=Q.trim();if(!G||G.startsWith("#")||!G.includes("="))continue;let W=G.indexOf("="),z=G.slice(0,W).trim(),U=G.slice(W+1).trim();if(!/^[A-Z_][A-Z0-9_]*$/i.test(z)||process.env[z]!=null)continue;if(U.startsWith('"')&&U.endsWith('"')||U.startsWith("'")&&U.endsWith("'"))U=U.slice(1,-1);process.env[z]=U}}}function d3($){return[v0($,"config","cloud.ts"),v0($,"config","cloud.js"),v0($,"cloud.config.ts"),v0($,"cloud.config.js")].find((Y)=>i2(Y))??null}function Q8($){return $.infrastructure?.compute?.sshKeys??[]}function WX($,J){let Y=$.infrastructure??($.infrastructure={}),Z=Y.compute??(Y.compute={});Z.sshKeys=J}function c3($,J,Y){let Z=$.sites??($.sites={});Z[J]=Y}async function S2($){return await $.json().catch(()=>({}))}function m3($){if($.mode==="hybrid")return"hybrid";return $.infrastructure?.compute?"server":"serverless"}async function E$($,J){let Y=m3($),Z={mode:Y,environment:J,environments:Object.keys($.environments??{})};try{return{...(Y==="serverless"?await i7($,J):await YG($,J))??{},...Z}}catch{return{...Z}}}function l3($){let J=[v0($,"packages","ui"),v0(Z8,"..","..","..","ui"),v0(Z8,"..","..","ui"),v0(Z8,"..","ui-src"),v0(Z8,"..","..","ui-src"),v0(Z8,"..","..","dist","ui-src")];for(let Y of J)if(i2(v0(Y,"pages"))&&i2(v0(Y,"package.json")))return Y;return null}async function LG($,J){let Y=l3($);if(!Y)return null;try{let Z=x3(v0(I3(),"ts-cloud-dashboard-")),Q=v0(Y,"node_modules",".bin","stx"),G=i2(Q)?[Q,"build","--pages","pages","--out",Z,"--no-sitemap","--no-cache"]:["bunx","--bun","@stacksjs/stx","build","--pages","pages","--out",Z,"--no-sitemap","--no-cache"],W=Bun.spawn(G,{cwd:Y,stdout:"pipe",stderr:"pipe",env:{...process.env,TSCLOUD_DASHBOARD_DATA:JSON.stringify(J)}}),[z,U,H]=await Promise.all([new Response(W.stdout).text(),new Response(W.stderr).text(),W.exited]);if(H!==0){if(process.env.TSCLOUD_DASHBOARD_VERBOSE)console.warn(`ts-cloud dashboard: live UI build failed; serving the pre-built UI.
8131
8136
  ${z}
8132
8137
  ${U}`);return null}return Z}catch(Z){if(process.env.TSCLOUD_DASHBOARD_VERBOSE)console.warn(`ts-cloud dashboard: live UI build errored; serving the pre-built UI. ${Z.message}`);return null}}function MG($){return{project:{name:$.project?.name,slug:$.project?.slug,region:$.project?.region},provider:$.provider,environments:Object.keys($.environments??{}),compute:$.infrastructure?.compute?{provider:$.infrastructure.compute.provider,runtime:$.infrastructure.compute.runtime,webServer:$.infrastructure.compute.webServer,proxy:$.infrastructure.compute.proxy?{engine:$.infrastructure.compute.proxy.engine,onDemandTls:$.infrastructure.compute.proxy.onDemandTls,cdn:!!$.infrastructure.compute.proxy.cdn}:void 0,managedServices:$.infrastructure.compute.managedServices,sshKeys:n2(Q8($)).map((J)=>({name:J.name,type:J.type,fingerprint:J.fingerprint,added:J.added}))}:void 0,sites:Object.fromEntries(Object.entries($.sites??{}).map(([J,Y])=>[J,{domain:Y.domain,path:Y.path,type:Y.type,deploy:Y.deploy,root:Y.root,port:Y.port,ssl:Y.ssl}]))}}function G8($){return[{id:"status",label:"Refresh Cloud Status",description:"Runs the local ts-cloud status checks against configured providers.",command:["status","--env",$],mutates:!1},{id:"doctor",label:"Run Doctor",description:"Checks local tooling, credentials, and provider access.",command:["doctor"],mutates:!1},{id:"security-scan",label:"Security Scan",description:"Runs the pre-deploy scanner from this checkout.",command:["deploy:security-scan","--source",".","--fail-on","critical"],mutates:!1},{id:"deploy",label:"Deploy Environment",description:"Deploys the selected environment from the local checkout.",command:["deploy","--env",$,"--yes"],mutates:!0,confirm:"deploy"}]}function qG($,J){return G8(J).find((Y)=>Y.id===$)}function zX($){if($.length<=QX)return $;return`${$.slice(0,QX)}
8133
8138
 
8134
- [output truncated]`}async function UX($,J){let Y=Bun.spawn([process.execPath,J.cliEntry,...$.command],{cwd:J.cwd,stdout:"pipe",stderr:"pipe",env:process.env}),[Z,Q,G]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text(),Y.exited]);return{action:$.id,command:["cloud",...$.command].join(" "),exitCode:G,ok:G===0,stdout:zX(Z),stderr:zX(Q)}}function r3($,J){let Y=decodeURIComponent(J).replace(/^\/+/,""),Q=b3(Y===""?"index.html":Y);if(Q.startsWith("..")||Q.includes("/../"))return null;let G=v0($,Q);if(i2(G)&&!HX(G).isDirectory())return G;if(!EG(G)&&i2(`${G}.html`))return`${G}.html`;if(!EG(G)&&i2(v0(G,"index.html")))return v0(G,"index.html");return null}async function n3($,J){let Y=r3($,J);if(!Y)return GX("Not found",404);if(HX(Y).isDirectory())return GX("Not found",404);let Z=await M$(Y),Q=g3[EG(Y)]??"application/octet-stream";return new Response(Z,{headers:{"content-type":Q}})}async function J5($={}){let J=$.cwd??process.cwd(),Y=$.host??v3,Z=$.port??f3,Q=$.cliEntry??process.argv[1];if($.box)process.env.TS_CLOUD_DASHBOARD_BOX="1";await d3(J);let G=await M6(),W=Object.keys(G.environments??{}),z=u3(G,$.environment),U=G8(z),H=c3(J),F=await E$(G,z),B=F,K=await LG(J,F),O=u7(J),A=K??O?.uiRoot;if(!A)throw Error("ts-cloud dashboard UI not found. Run `bun run build` in ts-cloud or reinstall the package.");let V=Bun.serve({hostname:Y,port:Z,async fetch(_){let E=new URL(_.url);try{if(E.pathname==="/api/health")return F0({ok:!0,cwd:J,environment:z,environments:W,uiRoot:A,liveData:!!K,localPackage:import.meta.url.includes("/Code/Libraries/ts-cloud/")});if(E.pathname==="/"&&B?.mode==="serverless")return new Response(null,{status:302,headers:{location:"/serverless"}});if(E.pathname==="/api/env"&&_.method==="POST"){let j=await S2(_),q=String(j.env??"");if(!W.includes(q))return F0({ok:!1,error:`Unknown environment '${q}'.`,environments:W},404);if(q!==z){z=q,U=G8(z),B=await E$(G,z);let T=await LG(J,B);if(T)A=T}return F0({ok:!0,environment:z,environments:W})}if(E.pathname==="/api/config")return F0({...MG(G),environment:z,environments:W});if(E.pathname==="/api/ssh-keys"&&_.method==="GET")return F0({configPath:H,keys:n2(Q8(G))});if(E.pathname==="/api/ssh-keys"&&_.method==="POST"){if(!H)return F0({ok:!1,error:"No cloud config file was found in this checkout."},404);let j=await S2(_),q=await M$(H,"utf8"),T=Q8(G),D=SF({configText:q,name:String(j.name??""),publicKey:String(j.publicKey??""),existingKeys:T});return await S9(H,D),WX(G,[...T,{name:String(j.name??"").trim(),publicKey:String(j.publicKey??"").trim().replace(/\s+/g," ")}]),F0({ok:!0,configPath:H,keys:n2(Q8(G))})}if(E.pathname==="/api/ssh-keys"&&_.method==="DELETE"){if(!H)return F0({ok:!1,error:"No cloud config file was found in this checkout."},404);let j=await S2(_),q=String(j.name??E.searchParams.get("name")??""),T=await M$(H,"utf8"),D=Q8(G),S=PF({configText:T,name:q,existingKeys:D});return await S9(H,S),WX(G,D.filter((P)=>P.name!==q.trim())),F0({ok:!0,configPath:H,keys:n2(Q8(G))})}if(E.pathname==="/api/sites"&&_.method==="POST"){if(!H)return F0({ok:!1,error:"No cloud config file was found in this checkout."},404);let j=await S2(_),q=String(j.name??"").trim(),T=String(j.root??"").trim();if(!q||!T)return F0({ok:!1,error:"Site name and root are required."},422);let D={deploy:j.deploy==="bucket"?"bucket":"server",root:T,path:String(j.path??"").trim()||void 0,domain:String(j.domain??"").trim()||void 0,build:String(j.build??"").trim()||void 0,start:String(j.start??"").trim()||void 0,port:j.port?Number(j.port):void 0,type:String(j.type??"").trim()||void 0};if(D.port!==void 0&&(!Number.isInteger(D.port)||D.port<1||D.port>65535))return F0({ok:!1,error:"Port must be a number between 1 and 65535."},422);let S=await M$(H,"utf8"),P=w6({configText:S,name:q,root:D.root,domain:D.domain,path:D.path,deploy:D.deploy,build:D.build,start:D.start,port:D.port,type:D.type});return await S9(H,P),m3(G,q,Object.fromEntries(Object.entries(D).filter(([,C])=>C!==void 0))),B=await E$(G,z),F0({ok:!0,configPath:H,site:q,data:B})}if(E.pathname==="/api/sites"&&_.method==="DELETE"){if(!H)return F0({ok:!1,error:"No cloud config file was found in this checkout."},404);let j=await S2(_),q=String(j.name??E.searchParams.get("name")??"").trim();if(!q||!G.sites?.[q])return F0({ok:!1,error:`Site '${q}' was not found.`},404);let T=await M$(H,"utf8");return await S9(H,c4({configText:T,name:q})),delete G.sites[q],B=await E$(G,z),F0({ok:!0,configPath:H,site:q,data:B})}if(E.pathname==="/api/sites"&&_.method==="PATCH"){if(!H)return F0({ok:!1,error:"No cloud config file was found in this checkout."},404);let j=await S2(_),q=String(j.name??"").trim(),T=G.sites?.[q];if(!q||!T)return F0({ok:!1,error:`Site '${q}' was not found.`},404);if(j.port!==void 0&&j.port!==null&&j.port!==""&&(!Number.isInteger(Number(j.port))||Number(j.port)<1||Number(j.port)>65535))return F0({ok:!1,error:"Port must be a number between 1 and 65535."},422);let D=await M$(H,"utf8"),S=(P,C)=>{D=m4({configText:D,siteName:q,key:P,valueText:C})};if(j.ssl!==void 0)S("ssl",l4(j.ssl)),T.ssl=j.ssl;if(j.env!==void 0&&j.env&&typeof j.env==="object")S("env",r4(j.env)),T.env=j.env;for(let P of["domain","path","build","start","type","root"])if(typeof j[P]==="string"&&j[P].trim())S(P,p4(String(j[P]).trim())),T[P]=String(j[P]).trim();if(j.port!==void 0&&j.port!==null&&j.port!=="")S("port",String(Number(j.port))),T.port=Number(j.port);return await S9(H,D),B=await E$(G,z),F0({ok:!0,configPath:H,site:q,data:B})}if(E.pathname==="/api/sites/deploy"&&_.method==="POST"){let j=await S2(_),q=String(j.name??"").trim();if(!q||!G.sites?.[q])return F0({ok:!1,error:`Site '${q}' was not found.`},404);if(j.confirm!==q)return F0({ok:!1,error:`Type "${q}" to deploy this site.`},409);let T={id:`deploy:${q}`,label:`Deploy ${q}`,description:`Deploy the ${q} site for ${z}.`,command:["deploy","--env",z,"--site",q,"--yes"],mutates:!0};return F0(await UX(T,{cwd:J,cliEntry:Q}))}if(E.pathname==="/api/actions")return F0(U);if(E.pathname==="/api/server/operations")return F0(jG(G,B));if(E.pathname==="/api/databases"&&_.method==="GET")return F0(await tF(G,z));if(E.pathname==="/api/databases"&&_.method==="POST"){let j=await S2(_),q=String(j.name??"").trim();if(!e7(q))return F0({ok:!1,error:"Database name must be a valid identifier (letters, numbers, underscore; not starting with a digit)."},422);return F0({...await sF(G,z,q),name:q})}if(E.pathname==="/api/databases/users"&&_.method==="POST"){let j=await S2(_),q=String(j.username??"").trim(),T=String(j.password??""),D=String(j.database??"").trim()||void 0,S=j.access==="readonly"?"readonly":"all";if(!e7(q))return F0({ok:!1,error:"Username must be a valid identifier."},422);if(!T)return F0({ok:!1,error:"Password is required."},422);if(D&&!e7(D))return F0({ok:!1,error:"Database must be a valid identifier."},422);return F0({...await oF(G,z,{username:q,password:T,database:D,access:S}),username:q})}if(E.pathname==="/api/dashboard-data")return B=await E$(G,z),F0(B);if(E.pathname==="/api/actions/run"&&_.method==="POST"){let j=await _.json().catch(()=>({})),q=j.action?qG(j.action,z):void 0;if(!q)return F0({ok:!1,error:"Unknown dashboard action."},404);if(q.mutates&&j.confirm!==q.confirm)return F0({ok:!1,error:`Type "${q.confirm}" to run this action.`},409);return F0(await UX(q,{cwd:J,cliEntry:Q}))}if(E.pathname==="/api/server/operations/run"&&_.method==="POST"){let j=await _.json().catch(()=>({})),q=j.operation?YX(j.operation,G,B):void 0;if(!q)return F0({ok:!1,error:"Unknown or unavailable server operation."},404);if(q.mutates&&j.confirm!==q.confirm)return F0({ok:!1,error:`Type "${q.confirm}" to run this operation.`},409);return F0(await ZX(G,z,q,{to:j.to}))}let M=E.searchParams.get("env");if(M&&W.includes(M)&&M!==z){z=M,U=G8(z),B=await E$(G,z);let j=await LG(J,B);if(j)A=j}return n3(A,E.pathname)}catch(M){if($.verbose)console.error(M);return F0({ok:!1,error:M?.message??String(M)},500)}}});return{server:V,url:`http://${Y}:${V.port}/`}}function TG($){$.command("dashboard:serve","Run the local Forge-style cloud management UI").option("--host <host>","Host to bind",{default:"127.0.0.1"}).option("--port <port>","Port to bind",{default:"7676"}).option("--env <environment>","Environment to manage").option("--box","Box mode: run on the provisioned server (operate on localhost)").option("--open","Print the URL for opening in a browser").option("--verbose","Print server errors").action(async(J)=>{let Y=await J5({host:J?.host,port:Number(J?.port??7676),environment:J?.env,box:J?.box,verbose:J?.verbose});R("ts-cloud Local Dashboard"),h(`Serving ${Y.url}`),X("Use Ctrl+C to stop."),await new Promise(()=>{})})}z0();U2();function wG($){$.command("cdn:list","List all CloudFront distributions").action(async()=>{R("CloudFront Distributions");try{let J=await m(),Y=new T0,Z=new N("Fetching distributions...");Z.start();let Q=await Y.listDistributions();if(Z.succeed(`Found ${Q.length} distribution(s)`),Q.length===0){X("No CloudFront distributions found"),X("Use `cloud cdn:create` to create a new distribution");return}p(["ID","Domain","Status","Enabled","Aliases"],Q.map((G)=>[G.Id||"N/A",G.DomainName||"N/A",G.Status||"N/A",G.Enabled?"Yes":"No",(G.Aliases?.Items?.length||0).toString()]))}catch(J){w(`Failed to list distributions: ${J.message}`),process.exit(1)}}),$.command("cdn:status <distributionId>","Get CloudFront distribution status").action(async(J)=>{R(`CloudFront Distribution: ${J}`);try{let Y=new T0,Z=new N("Fetching distribution details...");Z.start();let Q=await Y.getDistribution(J);if(Z.succeed("Distribution details loaded"),X(`
8139
+ [output truncated]`}async function UX($,J){let Y=Bun.spawn([process.execPath,J.cliEntry,...$.command],{cwd:J.cwd,stdout:"pipe",stderr:"pipe",env:process.env}),[Z,Q,G]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text(),Y.exited]);return{action:$.id,command:["cloud",...$.command].join(" "),exitCode:G,ok:G===0,stdout:zX(Z),stderr:zX(Q)}}function p3($,J){let Y=decodeURIComponent(J).replace(/^\/+/,""),Q=h3(Y===""?"index.html":Y);if(Q.startsWith("..")||Q.includes("/../"))return null;let G=v0($,Q);if(i2(G)&&!HX(G).isDirectory())return G;if(!EG(G)&&i2(`${G}.html`))return`${G}.html`;if(!EG(G)&&i2(v0(G,"index.html")))return v0(G,"index.html");return null}async function r3($,J){let Y=p3($,J);if(!Y)return GX("Not found",404);if(HX(Y).isDirectory())return GX("Not found",404);let Z=await M$(Y),Q=f3[EG(Y)]??"application/octet-stream";return new Response(Z,{headers:{"content-type":Q}})}async function J5($={}){let J=$.cwd??process.cwd(),Y=$.host??y3,Z=$.port??v3,Q=$.cliEntry??process.argv[1];if($.box)process.env.TS_CLOUD_DASHBOARD_BOX="1";await u3(J);let G=await M6(),W=Object.keys(G.environments??{}),z=g3(G,$.environment),U=G8(z),H=d3(J),F=await E$(G,z),B=F,K=await LG(J,F),O=u7(J),A=K??O?.uiRoot;if(!A)throw Error("ts-cloud dashboard UI not found. Run `bun run build` in ts-cloud or reinstall the package.");let V=Bun.serve({hostname:Y,port:Z,async fetch(_){let E=new URL(_.url);try{if(E.pathname==="/api/health")return F0({ok:!0,cwd:J,environment:z,environments:W,uiRoot:A,liveData:!!K,localPackage:import.meta.url.includes("/Code/Libraries/ts-cloud/")});if(E.pathname==="/"&&B?.mode==="serverless")return new Response(null,{status:302,headers:{location:"/serverless"}});if(E.pathname==="/api/env"&&_.method==="POST"){let j=await S2(_),q=String(j.env??"");if(!W.includes(q))return F0({ok:!1,error:`Unknown environment '${q}'.`,environments:W},404);if(q!==z){z=q,U=G8(z),B=await E$(G,z);let T=await LG(J,B);if(T)A=T}return F0({ok:!0,environment:z,environments:W})}if(E.pathname==="/api/config")return F0({...MG(G),environment:z,environments:W});if(E.pathname==="/api/ssh-keys"&&_.method==="GET")return F0({configPath:H,keys:n2(Q8(G))});if(E.pathname==="/api/ssh-keys"&&_.method==="POST"){if(!H)return F0({ok:!1,error:"No cloud config file was found in this checkout."},404);let j=await S2(_),q=await M$(H,"utf8"),T=Q8(G),D=SF({configText:q,name:String(j.name??""),publicKey:String(j.publicKey??""),existingKeys:T});return await S9(H,D),WX(G,[...T,{name:String(j.name??"").trim(),publicKey:String(j.publicKey??"").trim().replace(/\s+/g," ")}]),F0({ok:!0,configPath:H,keys:n2(Q8(G))})}if(E.pathname==="/api/ssh-keys"&&_.method==="DELETE"){if(!H)return F0({ok:!1,error:"No cloud config file was found in this checkout."},404);let j=await S2(_),q=String(j.name??E.searchParams.get("name")??""),T=await M$(H,"utf8"),D=Q8(G),S=PF({configText:T,name:q,existingKeys:D});return await S9(H,S),WX(G,D.filter((P)=>P.name!==q.trim())),F0({ok:!0,configPath:H,keys:n2(Q8(G))})}if(E.pathname==="/api/sites"&&_.method==="POST"){if(!H)return F0({ok:!1,error:"No cloud config file was found in this checkout."},404);let j=await S2(_),q=String(j.name??"").trim(),T=String(j.root??"").trim();if(!q||!T)return F0({ok:!1,error:"Site name and root are required."},422);let D={deploy:j.deploy==="bucket"?"bucket":"server",root:T,path:String(j.path??"").trim()||void 0,domain:String(j.domain??"").trim()||void 0,build:String(j.build??"").trim()||void 0,start:String(j.start??"").trim()||void 0,port:j.port?Number(j.port):void 0,type:String(j.type??"").trim()||void 0};if(D.port!==void 0&&(!Number.isInteger(D.port)||D.port<1||D.port>65535))return F0({ok:!1,error:"Port must be a number between 1 and 65535."},422);let S=await M$(H,"utf8"),P=w6({configText:S,name:q,root:D.root,domain:D.domain,path:D.path,deploy:D.deploy,build:D.build,start:D.start,port:D.port,type:D.type});return await S9(H,P),c3(G,q,Object.fromEntries(Object.entries(D).filter(([,C])=>C!==void 0))),B=await E$(G,z),F0({ok:!0,configPath:H,site:q,data:B})}if(E.pathname==="/api/sites"&&_.method==="DELETE"){if(!H)return F0({ok:!1,error:"No cloud config file was found in this checkout."},404);let j=await S2(_),q=String(j.name??E.searchParams.get("name")??"").trim();if(!q||!G.sites?.[q])return F0({ok:!1,error:`Site '${q}' was not found.`},404);let T=await M$(H,"utf8");return await S9(H,c4({configText:T,name:q})),delete G.sites[q],B=await E$(G,z),F0({ok:!0,configPath:H,site:q,data:B})}if(E.pathname==="/api/sites"&&_.method==="PATCH"){if(!H)return F0({ok:!1,error:"No cloud config file was found in this checkout."},404);let j=await S2(_),q=String(j.name??"").trim(),T=G.sites?.[q];if(!q||!T)return F0({ok:!1,error:`Site '${q}' was not found.`},404);if(j.port!==void 0&&j.port!==null&&j.port!==""&&(!Number.isInteger(Number(j.port))||Number(j.port)<1||Number(j.port)>65535))return F0({ok:!1,error:"Port must be a number between 1 and 65535."},422);let D=await M$(H,"utf8"),S=(P,C)=>{D=m4({configText:D,siteName:q,key:P,valueText:C})};if(j.ssl!==void 0)S("ssl",l4(j.ssl)),T.ssl=j.ssl;if(j.env!==void 0&&j.env&&typeof j.env==="object")S("env",r4(j.env)),T.env=j.env;for(let P of["domain","path","build","start","type","root"])if(typeof j[P]==="string"&&j[P].trim())S(P,p4(String(j[P]).trim())),T[P]=String(j[P]).trim();if(j.port!==void 0&&j.port!==null&&j.port!=="")S("port",String(Number(j.port))),T.port=Number(j.port);return await S9(H,D),B=await E$(G,z),F0({ok:!0,configPath:H,site:q,data:B})}if(E.pathname==="/api/sites/deploy"&&_.method==="POST"){let j=await S2(_),q=String(j.name??"").trim();if(!q||!G.sites?.[q])return F0({ok:!1,error:`Site '${q}' was not found.`},404);if(j.confirm!==q)return F0({ok:!1,error:`Type "${q}" to deploy this site.`},409);let T={id:`deploy:${q}`,label:`Deploy ${q}`,description:`Deploy the ${q} site for ${z}.`,command:["deploy","--env",z,"--site",q,"--yes"],mutates:!0};return F0(await UX(T,{cwd:J,cliEntry:Q}))}if(E.pathname==="/api/actions")return F0(U);if(E.pathname==="/api/server/operations")return F0(jG(G,B));if(E.pathname==="/api/databases"&&_.method==="GET")return F0(await tF(G,z));if(E.pathname==="/api/databases"&&_.method==="POST"){let j=await S2(_),q=String(j.name??"").trim();if(!e7(q))return F0({ok:!1,error:"Database name must be a valid identifier (letters, numbers, underscore; not starting with a digit)."},422);return F0({...await sF(G,z,q),name:q})}if(E.pathname==="/api/databases/users"&&_.method==="POST"){let j=await S2(_),q=String(j.username??"").trim(),T=String(j.password??""),D=String(j.database??"").trim()||void 0,S=j.access==="readonly"?"readonly":"all";if(!e7(q))return F0({ok:!1,error:"Username must be a valid identifier."},422);if(!T)return F0({ok:!1,error:"Password is required."},422);if(D&&!e7(D))return F0({ok:!1,error:"Database must be a valid identifier."},422);return F0({...await oF(G,z,{username:q,password:T,database:D,access:S}),username:q})}if(E.pathname==="/api/dashboard-data")return B=await E$(G,z),F0(B);if(E.pathname==="/api/actions/run"&&_.method==="POST"){let j=await _.json().catch(()=>({})),q=j.action?qG(j.action,z):void 0;if(!q)return F0({ok:!1,error:"Unknown dashboard action."},404);if(q.mutates&&j.confirm!==q.confirm)return F0({ok:!1,error:`Type "${q.confirm}" to run this action.`},409);return F0(await UX(q,{cwd:J,cliEntry:Q}))}if(E.pathname==="/api/server/operations/run"&&_.method==="POST"){let j=await _.json().catch(()=>({})),q=j.operation?YX(j.operation,G,B):void 0;if(!q)return F0({ok:!1,error:"Unknown or unavailable server operation."},404);if(q.mutates&&j.confirm!==q.confirm)return F0({ok:!1,error:`Type "${q.confirm}" to run this operation.`},409);return F0(await ZX(G,z,q,{to:j.to}))}let M=E.searchParams.get("env");if(M&&W.includes(M)&&M!==z){z=M,U=G8(z),B=await E$(G,z);let j=await LG(J,B);if(j)A=j}return r3(A,E.pathname)}catch(M){if($.verbose)console.error(M);return F0({ok:!1,error:M?.message??String(M)},500)}}});return{server:V,url:`http://${Y}:${V.port}/`}}function TG($){$.command("dashboard:serve","Run the local Forge-style cloud management UI").option("--host <host>","Host to bind",{default:"127.0.0.1"}).option("--port <port>","Port to bind",{default:"7676"}).option("--env <environment>","Environment to manage").option("--box","Box mode: run on the provisioned server (operate on localhost)").option("--open","Print the URL for opening in a browser").option("--verbose","Print server errors").action(async(J)=>{let Y=await J5({host:J?.host,port:Number(J?.port??7676),environment:J?.env,box:J?.box,verbose:J?.verbose});R("ts-cloud Local Dashboard"),h(`Serving ${Y.url}`),X("Use Ctrl+C to stop."),await new Promise(()=>{})})}z0();U2();function wG($){$.command("cdn:list","List all CloudFront distributions").action(async()=>{R("CloudFront Distributions");try{let J=await m(),Y=new T0,Z=new N("Fetching distributions...");Z.start();let Q=await Y.listDistributions();if(Z.succeed(`Found ${Q.length} distribution(s)`),Q.length===0){X("No CloudFront distributions found"),X("Use `cloud cdn:create` to create a new distribution");return}p(["ID","Domain","Status","Enabled","Aliases"],Q.map((G)=>[G.Id||"N/A",G.DomainName||"N/A",G.Status||"N/A",G.Enabled?"Yes":"No",(G.Aliases?.Items?.length||0).toString()]))}catch(J){w(`Failed to list distributions: ${J.message}`),process.exit(1)}}),$.command("cdn:status <distributionId>","Get CloudFront distribution status").action(async(J)=>{R(`CloudFront Distribution: ${J}`);try{let Y=new T0,Z=new N("Fetching distribution details...");Z.start();let Q=await Y.getDistribution(J);if(Z.succeed("Distribution details loaded"),X(`
8135
8140
  Distribution Information:`),X(` ID: ${Q.Id}`),X(` Domain: ${Q.DomainName}`),X(` Status: ${Q.Status}`),X(` ARN: ${Q.ARN}`),X(` Enabled: ${Q.Enabled?"Yes":"No"}`),Q.Aliases?.Items?.length)X(` Aliases: ${Q.Aliases.Items.join(", ")}`);let G=await Y.getDistributionConfig(J);X(`
8136
8141
  Origins:`);let W=G.DistributionConfig?.Origins?.Items||[];if(Array.isArray(W))for(let z of W)X(` - ${z.Id}: ${z.DomainName}`);if(G.DistributionConfig?.DefaultCacheBehavior){let z=G.DistributionConfig.DefaultCacheBehavior;X(`
8137
8142
  Default Cache Behavior:`),X(` Target Origin: ${z.TargetOriginId}`),X(` Viewer Protocol: ${z.ViewerProtocolPolicy}`)}}catch(Y){w(`Failed to get distribution: ${Y.message}`),process.exit(1)}}),$.command("cdn:create","Create a new CloudFront distribution for an S3 bucket").option("--bucket <name>","S3 bucket name").option("--region <region>","S3 bucket region",{default:"us-east-1"}).option("--alias <domain>","Custom domain alias (CNAME)").option("--certificate <arn>","ACM certificate ARN for custom domain").option("--comment <text>","Distribution comment/description").action(async(J)=>{R("Create CloudFront Distribution");try{if(!J.bucket)w("--bucket is required"),X("Example: cloud cdn:create --bucket my-bucket --region us-east-1"),process.exit(1);let Y=new T0;if(X(`Bucket: ${J.bucket}`),X(`Region: ${J.region}`),J.alias)X(`Alias: ${J.alias}`);if(!await u(`
@@ -8144,18 +8149,18 @@ Invalidation ID: ${z.Id}`),X(`Status: ${z.Status}`),X(`
8144
8149
  Note: Invalidation typically completes in 5-10 minutes.`)}catch(Z){w(`Failed to create invalidation: ${Z.message}`),process.exit(1)}}),$.command("cdn:disable <distributionId>","Disable a CloudFront distribution").action(async(J)=>{R("Disable CloudFront Distribution");try{let Y=new T0;if(v(`This will disable distribution: ${J}`),X("The distribution will stop serving content."),!await u(`
8145
8150
  Disable this distribution?`,!1)){X("Operation cancelled");return}let Q=new N("Disabling distribution...");Q.start(),await Y.disableDistribution(J),Q.succeed("Distribution disabled"),X(`
8146
8151
  Note: Changes may take 15-30 minutes to propagate.`),X("To delete the distribution, wait for it to be fully disabled first.")}catch(Y){w(`Failed to disable distribution: ${Y.message}`),process.exit(1)}}),$.command("cdn:delete <distributionId>","Delete a CloudFront distribution").action(async(J)=>{R("Delete CloudFront Distribution");try{let Y=new T0;if(v(`This will permanently delete distribution: ${J}`),v("The distribution must be disabled first."),!await u(`
8147
- Delete this distribution?`,!1)){X("Operation cancelled");return}let Q=new N("Checking distribution status...");Q.start();let G=await Y.getDistribution(J);if(G.Status!=="Deployed"||G.Enabled){Q.fail("Distribution must be disabled and deployed before deletion"),X('\nRun `cloud cdn:disable` first and wait for status to be "Deployed"');return}Q.text="Deleting distribution...",await Y.deleteDistribution(J),Q.succeed("Distribution deleted")}catch(Y){w(`Failed to delete distribution: ${Y.message}`),process.exit(1)}})}z0();I0();import{readdirSync as i3,statSync as a3}from"node:fs";import{join as t3,relative as s3}from"node:path";function DG($){$.command("storage:list","List all S3 buckets").option("--region <region>","AWS region").action(async(J)=>{R("S3 Buckets");try{let Y=await m(),Z=J.region||Y.project.region||"us-east-1",Q=new W0(Z),G=new N("Fetching buckets...");G.start();let z=(await Q.listBuckets()).Buckets||[];if(G.succeed(`Found ${z.length} bucket(s)`),z.length===0){X("No S3 buckets found"),X("Use `cloud storage:create` to create a new bucket");return}p(["Name","Created"],z.map((U)=>[U.Name||"N/A",U.CreationDate?new Date(U.CreationDate).toLocaleDateString():"N/A"]))}catch(Y){w(`Failed to list buckets: ${Y.message}`),process.exit(1)}}),$.command("storage:create <name>","Create a new S3 bucket").option("--region <region>","AWS region",{default:"us-east-1"}).option("--public","Enable public access").option("--versioning","Enable versioning").action(async(J,Y)=>{R("Create S3 Bucket");try{let Z=new W0(Y.region);if(X(`Bucket name: ${J}`),X(`Region: ${Y.region}`),X(`Public access: ${Y.public?"Yes":"No"}`),X(`Versioning: ${Y.versioning?"Yes":"No"}`),!await u(`
8152
+ Delete this distribution?`,!1)){X("Operation cancelled");return}let Q=new N("Checking distribution status...");Q.start();let G=await Y.getDistribution(J);if(G.Status!=="Deployed"||G.Enabled){Q.fail("Distribution must be disabled and deployed before deletion"),X('\nRun `cloud cdn:disable` first and wait for status to be "Deployed"');return}Q.text="Deleting distribution...",await Y.deleteDistribution(J),Q.succeed("Distribution deleted")}catch(Y){w(`Failed to delete distribution: ${Y.message}`),process.exit(1)}})}z0();I0();import{readdirSync as n3,statSync as i3}from"node:fs";import{join as a3,relative as t3}from"node:path";function DG($){$.command("storage:list","List all S3 buckets").option("--region <region>","AWS region").action(async(J)=>{R("S3 Buckets");try{let Y=await m(),Z=J.region||Y.project.region||"us-east-1",Q=new W0(Z),G=new N("Fetching buckets...");G.start();let z=(await Q.listBuckets()).Buckets||[];if(G.succeed(`Found ${z.length} bucket(s)`),z.length===0){X("No S3 buckets found"),X("Use `cloud storage:create` to create a new bucket");return}p(["Name","Created"],z.map((U)=>[U.Name||"N/A",U.CreationDate?new Date(U.CreationDate).toLocaleDateString():"N/A"]))}catch(Y){w(`Failed to list buckets: ${Y.message}`),process.exit(1)}}),$.command("storage:create <name>","Create a new S3 bucket").option("--region <region>","AWS region",{default:"us-east-1"}).option("--public","Enable public access").option("--versioning","Enable versioning").action(async(J,Y)=>{R("Create S3 Bucket");try{let Z=new W0(Y.region);if(X(`Bucket name: ${J}`),X(`Region: ${Y.region}`),X(`Public access: ${Y.public?"Yes":"No"}`),X(`Versioning: ${Y.versioning?"Yes":"No"}`),!await u(`
8148
8153
  Create this bucket?`,!0)){X("Operation cancelled");return}let G=new N("Creating bucket...");if(G.start(),await Z.createBucket(J),!Y.public)G.text="Configuring public access block...",await Z.putPublicAccessBlock(J,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!0,RestrictPublicBuckets:!0});if(Y.versioning)G.text="Enabling versioning...",await Z.putBucketVersioning(J,"Enabled");G.succeed("Bucket created"),h(`
8149
8154
  Bucket: ${J}`),X(`Region: ${Y.region}`),X(`URL: s3://${J}`)}catch(Z){w(`Failed to create bucket: ${Z.message}`),process.exit(1)}}),$.command("storage:delete <name>","Delete an S3 bucket").option("--force","Delete all objects first").action(async(J,Y)=>{R("Delete S3 Bucket");try{let Z=new W0("us-east-1");if(v(`This will permanently delete bucket: ${J}`),Y.force)v("All objects in the bucket will be deleted!");if(!await u(`
8150
- Delete this bucket?`,!1)){X("Operation cancelled");return}let G=new N("Deleting bucket...");if(G.start(),Y.force)G.text="Emptying bucket...",await Z.emptyBucket(J);await Z.deleteBucket(J),G.succeed("Bucket deleted")}catch(Z){w(`Failed to delete bucket: ${Z.message}`),process.exit(1)}}),$.command("storage:sync <source> <bucket>","Sync local directory to S3 bucket").option("--prefix <prefix>","S3 key prefix").option("--delete","Delete files in S3 that are not in source").option("--dry-run","Show what would be synced without making changes").action(async(J,Y,Z)=>{R("Sync to S3");try{let z=function(B,K){let O=i3(B,{withFileTypes:!0});for(let A of O){let V=t3(B,A.name);if(A.isDirectory())z(V,K);else{let _=s3(K,V),E=Z.prefix?`${Z.prefix}/${_}`:_,M=a3(V);W.push({path:V,key:E,size:M.size})}}},Q=new W0("us-east-1");if(X(`Source: ${J}`),X(`Destination: s3://${Y}/${Z.prefix||""}`),Z.dryRun)X("Dry run mode - no changes will be made");let G=new N("Scanning files...");G.start();let W=[];if(z(J,J),G.succeed(`Found ${W.length} local file(s)`),W.length===0){X("No files to sync");return}X(`
8155
+ Delete this bucket?`,!1)){X("Operation cancelled");return}let G=new N("Deleting bucket...");if(G.start(),Y.force)G.text="Emptying bucket...",await Z.emptyBucket(J);await Z.deleteBucket(J),G.succeed("Bucket deleted")}catch(Z){w(`Failed to delete bucket: ${Z.message}`),process.exit(1)}}),$.command("storage:sync <source> <bucket>","Sync local directory to S3 bucket").option("--prefix <prefix>","S3 key prefix").option("--delete","Delete files in S3 that are not in source").option("--dry-run","Show what would be synced without making changes").action(async(J,Y,Z)=>{R("Sync to S3");try{let z=function(B,K){let O=n3(B,{withFileTypes:!0});for(let A of O){let V=a3(B,A.name);if(A.isDirectory())z(V,K);else{let _=t3(K,V),E=Z.prefix?`${Z.prefix}/${_}`:_,M=i3(V);W.push({path:V,key:E,size:M.size})}}},Q=new W0("us-east-1");if(X(`Source: ${J}`),X(`Destination: s3://${Y}/${Z.prefix||""}`),Z.dryRun)X("Dry run mode - no changes will be made");let G=new N("Scanning files...");G.start();let W=[];if(z(J,J),G.succeed(`Found ${W.length} local file(s)`),W.length===0){X("No files to sync");return}X(`
8151
8156
  Files to sync:`);for(let B of W.slice(0,10))X(` ${B.key} (${(B.size/1024).toFixed(2)} KB)`);if(W.length>10)X(` ... and ${W.length-10} more`);if(Z.dryRun){X(`
8152
8157
  Dry run complete - no changes made`);return}if(!await u(`
8153
- Sync these files?`,!0)){X("Operation cancelled");return}let H=new N("Uploading files...");H.start();let F=0;for(let B of W){H.text=`Uploading ${B.key}... (${F+1}/${W.length})`;let O=await Bun.file(B.path).arrayBuffer();await Q.putObject({bucket:Y,key:B.key,body:Buffer.from(O),contentType:o3(B.key)}),F++}if(H.succeed(`Uploaded ${F} file(s)`),Z.delete){let B=new N("Checking for files to delete...");B.start();let K=await Q.listObjects({bucket:Y,prefix:Z.prefix}),O=new Set(W.map((V)=>V.key)),A=K.objects.filter((V)=>V.Key&&!O.has(V.Key)).map((V)=>V.Key);if(A.length>0){B.text=`Deleting ${A.length} remote file(s)...`;for(let V of A)await Q.deleteObject(Y,V);B.succeed(`Deleted ${A.length} remote file(s)`)}else B.succeed("No files to delete")}h(`
8158
+ Sync these files?`,!0)){X("Operation cancelled");return}let H=new N("Uploading files...");H.start();let F=0;for(let B of W){H.text=`Uploading ${B.key}... (${F+1}/${W.length})`;let O=await Bun.file(B.path).arrayBuffer();await Q.putObject({bucket:Y,key:B.key,body:Buffer.from(O),contentType:s3(B.key)}),F++}if(H.succeed(`Uploaded ${F} file(s)`),Z.delete){let B=new N("Checking for files to delete...");B.start();let K=await Q.listObjects({bucket:Y,prefix:Z.prefix}),O=new Set(W.map((V)=>V.key)),A=K.objects.filter((V)=>V.Key&&!O.has(V.Key)).map((V)=>V.Key);if(A.length>0){B.text=`Deleting ${A.length} remote file(s)...`;for(let V of A)await Q.deleteObject(Y,V);B.succeed(`Deleted ${A.length} remote file(s)`)}else B.succeed("No files to delete")}h(`
8154
8159
  Sync complete!`)}catch(Q){w(`Failed to sync: ${Q.message}`),process.exit(1)}}),$.command("storage:policy <bucket>","Show or set bucket policy").option("--set <file>","Set policy from JSON file").option("--public-read","Set a public read policy").option("--delete","Delete the bucket policy").action(async(J,Y)=>{R("S3 Bucket Policy");try{let Z=new W0("us-east-1");if(Y.delete){if(v(`This will delete the policy for bucket: ${J}`),!await u(`
8155
8160
  Delete bucket policy?`,!1)){X("Operation cancelled");return}let W=new N("Deleting policy...");W.start(),await Z.deleteBucketPolicy(J),W.succeed("Policy deleted");return}if(Y.publicRead){if(v(`This will make bucket ${J} publicly readable!`),!await u(`
8156
8161
  Set public read policy?`,!1)){X("Operation cancelled");return}let W=new N("Setting policy...");W.start();let z={Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:"s3:GetObject",Resource:`arn:aws:s3:::${J}/*`}]};await Z.putBucketPolicy(J,z),W.succeed("Public read policy set");return}if(Y.set){let G=new N("Setting policy...");G.start();let z=await Bun.file(Y.set).text();await Z.putBucketPolicy(J,z),G.succeed("Policy set");return}let Q=new N("Fetching policy...");Q.start();try{let G=await Z.getBucketPolicy(J);Q.succeed("Policy loaded"),X(`
8157
- Bucket Policy:`),console.log(JSON.stringify(G||{},null,2))}catch(G){if(G.message?.includes("NoSuchBucketPolicy"))Q.succeed("No policy set"),X("This bucket has no policy configured.");else throw G}}catch(Z){w(`Failed to manage policy: ${Z.message}`),process.exit(1)}}),$.command("storage:ls <bucket>","List objects in a bucket").option("--prefix <prefix>","Filter by prefix").option("--limit <number>","Limit number of results",{default:"100"}).action(async(J,Y)=>{R(`Objects in ${J}`);try{let Z=new W0("us-east-1"),Q=new N("Listing objects...");Q.start();let G=await Z.listObjects({bucket:J,prefix:Y.prefix,maxKeys:Number.parseInt(Y.limit||"100")}),W=G.objects;if(Q.succeed(`Found ${W.length} object(s)${G.nextContinuationToken?" (truncated)":""}`),W.length===0){X("No objects found");return}if(p(["Key","Size","Last Modified"],W.map((z)=>[z.Key||"N/A",e3(z.Size||0),z.LastModified?new Date(z.LastModified).toLocaleString():"N/A"])),G.nextContinuationToken)X(`
8158
- More objects available. Use --limit to see more.`)}catch(Z){w(`Failed to list objects: ${Z.message}`),process.exit(1)}})}function o3($){let J=$.split(".").pop()?.toLowerCase();return{html:"text/html",css:"text/css",js:"application/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",eot:"application/vnd.ms-fontobject",pdf:"application/pdf",zip:"application/zip",xml:"application/xml",txt:"text/plain",md:"text/markdown"}[J||""]||"application/octet-stream"}function e3($){if($===0)return"0 B";let J=1024,Y=["B","KB","MB","GB","TB"],Z=Math.floor(Math.log($)/Math.log(J));return`${Number.parseFloat(($/J**Z).toFixed(2))} ${Y[Z]}`}Y0();I0();function $w($,J){if(!J)return $;return $.startsWith(J)?$.slice(J.length):$}function RG($,J,Y){let Z=$w($,J);return`${Y??""}${Z}`}function NG($,J,Y){if(Y&&Y.some((Z)=>$.startsWith(Z)))return!1;if(J&&J.length>0)return J.some((Z)=>$.startsWith(Z));return!0}async function Jw($,J,Y){let Z=0,Q=[],G=Math.max(1,Math.min(J,$.length||1));for(let W=0;W<G;W++)Q.push((async()=>{while(!0){let z=Z++;if(z>=$.length)return;await Y($[z],z)}})());await Promise.all(Q)}function FX($){if($.client)return $.client;return PG({provider:$.provider,region:$.region,endpoint:$.endpoint,forcePathStyle:$.forcePathStyle,credentials:$.credentials})}async function SG($){let J=$.concurrency??8,Y=FX($.from),Z=FX($.to),Q=await Y.listAllObjects({bucket:$.from.bucket,prefix:$.from.prefix}),G={copied:0,skipped:0,excluded:0,bytesCopied:0,errors:[],excludedKeys:[],deleted:[]},W=[];for(let F of Q){if(!NG(F.Key,$.include,$.exclude)){G.excluded++,G.excludedKeys.push(F.Key);continue}W.push({source:F,destKey:RG(F.Key,$.from.prefix,$.to.prefix)})}if($.dryRun){G.plan=W.map(({source:K,destKey:O})=>({key:K.Key,destKey:O,size:K.Size}));let F=Q.length,B=0;for(let K of Q){B++;let O=!NG(K.Key,$.include,$.exclude);$.onProgress?.({key:K.Key,destKey:O?"":RG(K.Key,$.from.prefix,$.to.prefix),size:K.Size,action:O?"excluded":"planned",index:B,total:F})}return G}let z=W.length,U=0;await Jw(W,J,async({source:F,destKey:B})=>{let K=++U;try{if(!$.force){let V=await Z.headObject($.to.bucket,B);if(V&&V.ContentLength===F.Size){G.skipped++,$.onProgress?.({key:F.Key,destKey:B,size:F.Size,action:"skipped",index:K,total:z});return}}let{body:O,contentType:A}=await Y.getObjectBytes($.from.bucket,F.Key);await Z.putObject({bucket:$.to.bucket,key:B,body:O,contentType:A}),G.copied++,G.bytesCopied+=O.byteLength,$.onProgress?.({key:F.Key,destKey:B,size:F.Size,action:"copied",index:K,total:z})}catch(O){G.errors.push({key:F.Key,message:O?.message??String(O)}),$.onProgress?.({key:F.Key,destKey:B,size:F.Size,action:"error",index:K,total:z})}});let H=new Set(W.map((F)=>F.destKey));if($.deleteExtraneous){let B=(await Z.listAllObjects({bucket:$.to.bucket,prefix:$.to.prefix})).filter((K)=>!H.has(K.Key)).map((K)=>K.Key);for(let K of B)try{await Z.deleteObject($.to.bucket,K),G.deleted.push(K)}catch(O){G.errors.push({key:K,message:`delete failed: ${O?.message??String(O)}`})}}if($.verify){let F=await Z.listAllObjects({bucket:$.to.bucket,prefix:$.to.prefix}),B=new Map(F.map((V)=>[V.Key,V.Size])),K=[],O=[],A=0;for(let{source:V,destKey:_}of W){if(!B.has(_)){K.push(_);continue}let E=B.get(_);if(E!==V.Size){O.push({key:_,expected:V.Size,actual:E});continue}A++}G.verification={ok:K.length===0&&O.length===0,matched:A,missing:K,sizeMismatches:O}}return G}var Yw={aws:"us-east-1",backblaze:"us-west-004",hetzner:"fsn1"};function XX($,J){switch($){case"backblaze":return`s3.${J}.backblazeb2.com`;case"hetzner":return`${J}.your-objectstorage.com`;case"aws":default:return}}function I1(...$){for(let J of $){let Y=process.env[J];if(Y)return Y}return}function Zw($,J){if(J?.accessKeyId&&J.secretAccessKey)return J;let Y,Z;if($==="backblaze")Y=I1("B2_APPLICATION_KEY_ID","B2_KEY_ID","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),Z=I1("B2_APPLICATION_KEY","B2_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else if($==="hetzner")Y=I1("HETZNER_S3_ACCESS_KEY","HETZNER_ACCESS_KEY","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),Z=I1("HETZNER_S3_SECRET_KEY","HETZNER_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else Y=I1("S3_ACCESS_KEY_ID"),Z=I1("S3_SECRET_ACCESS_KEY");if(Y&&Z)return{accessKeyId:Y,secretAccessKey:Z,sessionToken:I1("AWS_SESSION_TOKEN")};return}function BX($={}){let J=$.provider||I1("OBJECT_STORAGE_PROVIDER","STORAGE_PROVIDER")||"aws",Y=$.region||(J==="backblaze"?I1("B2_REGION"):void 0)||(J==="hetzner"?I1("HETZNER_S3_REGION","HETZNER_REGION"):void 0)||I1("S3_REGION","AWS_REGION","AWS_DEFAULT_REGION")||Yw[J],Z=$.endpoint||I1("S3_ENDPOINT")||XX(J,Y),Q=$.forcePathStyle??I1("S3_FORCE_PATH_STYLE")==="true",G=Zw(J,$.credentials),W=(z)=>{let U=Z||`s3.${Y}.amazonaws.com`;return Q?`https://${U}/${z}`:`https://${z}.${U}`};return{provider:J,region:Y,endpoint:Z,forcePathStyle:Q,credentials:G,profile:$.profile,publicBaseUrl:W}}function PG($={}){let J=BX($),Y={endpoint:J.endpoint,forcePathStyle:J.forcePathStyle,credentials:J.credentials};return new W0(J.region,J.profile,Y)}M1();U7();Y9();I0();U2();e2();Y0();L2();e6();F7();ZQ();o6();z9();HQ();Y0();class w1{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}buildFormBody($){return Object.entries($).filter(([,Y])=>Y!==void 0).map(([Y,Z])=>`${encodeURIComponent(Y)}=${encodeURIComponent(Z)}`).join("&")}async createTopic($){let J={Action:"CreateTopic",Version:"2010-03-31",Name:$.Name};if($.DisplayName)J["Attributes.entry.1.key"]="DisplayName",J["Attributes.entry.1.value"]=$.DisplayName;if($.Tags)$.Tags.forEach((Z,Q)=>{J[`Tags.member.${Q+1}.Key`]=Z.Key,J[`Tags.member.${Q+1}.Value`]=Z.Value});if($.Attributes){let Z=$.DisplayName?2:1;Object.entries($.Attributes).forEach(([Q,G])=>{J[`Attributes.entry.${Z}.key`]=Q,J[`Attributes.entry.${Z}.value`]=G,Z++})}let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)});return{TopicArn:Y?.CreateTopicResponse?.CreateTopicResult?.TopicArn||Y?.TopicArn}}async deleteTopic($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteTopic",Version:"2010-03-31",TopicArn:$})})}async listTopics($){let J={Action:"ListTopics",Version:"2010-03-31"};if($)J.NextToken=$;let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)}),Z=Y?.ListTopicsResponse?.ListTopicsResult||Y?.ListTopicsResult,Q=Z?.Topics?.member;return{Topics:Array.isArray(Q)?Q:Q?[Q]:[],NextToken:Z?.NextToken}}async getTopicAttributes($){let Y=(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetTopicAttributes",Version:"2010-03-31",TopicArn:$})}))?.GetTopicAttributesResponse?.GetTopicAttributesResult?.Attributes?.entry,Z={TopicArn:$};if(Array.isArray(Y))Y.forEach((Q)=>{Z[Q.key]=Q.value});return Z}async setTopicAttributes($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetTopicAttributes",Version:"2010-03-31",TopicArn:$.TopicArn,AttributeName:$.AttributeName,AttributeValue:$.AttributeValue})})}async subscribe($){let J={Action:"Subscribe",Version:"2010-03-31",TopicArn:$.TopicArn,Protocol:$.Protocol,Endpoint:$.Endpoint};if($.ReturnSubscriptionArn)J.ReturnSubscriptionArn="true";if($.Attributes){let Z=1;Object.entries($.Attributes).forEach(([Q,G])=>{J[`Attributes.entry.${Z}.key`]=Q,J[`Attributes.entry.${Z}.value`]=G,Z++})}let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)});return{SubscriptionArn:Y?.SubscribeResponse?.SubscribeResult?.SubscriptionArn||Y?.SubscriptionArn}}async unsubscribe($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"Unsubscribe",Version:"2010-03-31",SubscriptionArn:$})})}async listSubscriptionsByTopic($,J){let Y={Action:"ListSubscriptionsByTopic",Version:"2010-03-31",TopicArn:$};if(J)Y.NextToken=J;let Z=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(Y)}),Q=Z?.ListSubscriptionsByTopicResponse?.ListSubscriptionsByTopicResult?.Subscriptions?.member;return{Subscriptions:Array.isArray(Q)?Q:Q?[Q]:[],NextToken:Z?.ListSubscriptionsByTopicResponse?.ListSubscriptionsByTopicResult?.NextToken}}async publish($){let J={Action:"Publish",Version:"2010-03-31",Message:$.Message};if($.TopicArn)J.TopicArn=$.TopicArn;if($.TargetArn)J.TargetArn=$.TargetArn;if($.PhoneNumber)J.PhoneNumber=$.PhoneNumber;if($.Subject)J.Subject=$.Subject;if($.MessageStructure)J.MessageStructure=$.MessageStructure;if($.MessageAttributes){let Z=1;Object.entries($.MessageAttributes).forEach(([Q,G])=>{if(J[`MessageAttributes.entry.${Z}.Name`]=Q,J[`MessageAttributes.entry.${Z}.Value.DataType`]=G.DataType,G.StringValue)J[`MessageAttributes.entry.${Z}.Value.StringValue`]=G.StringValue;if(G.BinaryValue)J[`MessageAttributes.entry.${Z}.Value.BinaryValue`]=G.BinaryValue;Z++})}let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)});return{MessageId:Y?.PublishResponse?.PublishResult?.MessageId||Y?.MessageId}}async publishSMS($,J,Y){let Z={};if(Y)Z["AWS.SNS.SMS.SenderID"]={DataType:"String",StringValue:Y};return this.publish({PhoneNumber:$,Message:J,MessageAttributes:Object.keys(Z).length>0?Z:void 0})}async subscribeEmail($,J){return this.subscribe({TopicArn:$,Protocol:"email",Endpoint:J})}async subscribeLambda($,J){return this.subscribe({TopicArn:$,Protocol:"lambda",Endpoint:J})}async subscribeSqs($,J,Y){let Z={};if(Y)Z.RawMessageDelivery="true";return this.subscribe({TopicArn:$,Protocol:"sqs",Endpoint:J,Attributes:Object.keys(Z).length>0?Z:void 0})}async subscribeHttp($,J,Y){let Z=J.startsWith("https")?"https":"http",Q={};if(Y)Q.RawMessageDelivery="true";return this.subscribe({TopicArn:$,Protocol:Z,Endpoint:J,Attributes:Object.keys(Q).length>0?Q:void 0})}async subscribeSms($,J){return this.subscribe({TopicArn:$,Protocol:"sms",Endpoint:J})}async topicExists($){try{return await this.getTopicAttributes($),!0}catch(J){if(J.code==="NotFound"||J.statusCode===404)return!1;throw J}}async getSMSAttributes(){let J=(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSAttributes",Version:"2010-03-31"})}))?.GetSMSAttributesResponse?.GetSMSAttributesResult?.attributes?.entry,Y={};if(Array.isArray(J))J.forEach((Z)=>{Y[Z.key]=Z.value});else if(J)Y[J.key]=J.value;return Y}async setSMSAttributes($){let J={Action:"SetSMSAttributes",Version:"2010-03-31"},Y=1;Object.entries($).forEach(([Z,Q])=>{if(Q!==void 0)J[`attributes.entry.${Y}.key`]=Z,J[`attributes.entry.${Y}.value`]=Q,Y++}),await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)})}async checkIfPhoneNumberIsOptedOut($){return(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CheckIfPhoneNumberIsOptedOut",Version:"2010-03-31",phoneNumber:$})}))?.CheckIfPhoneNumberIsOptedOutResponse?.CheckIfPhoneNumberIsOptedOutResult?.isOptedOut==="true"}async listPhoneNumbersOptedOut($){let J={Action:"ListPhoneNumbersOptedOut",Version:"2010-03-31"};if($)J.nextToken=$;let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)}),Z=Y?.ListPhoneNumbersOptedOutResponse?.ListPhoneNumbersOptedOutResult?.phoneNumbers?.member;return{phoneNumbers:Array.isArray(Z)?Z:Z?[Z]:[],nextToken:Y?.ListPhoneNumbersOptedOutResponse?.ListPhoneNumbersOptedOutResult?.nextToken}}async optInPhoneNumber($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"OptInPhoneNumber",Version:"2010-03-31",phoneNumber:$})})}async listSMSSandboxPhoneNumbers($){let J={Action:"ListSMSSandboxPhoneNumbers",Version:"2010-03-31"};if($)J.NextToken=$;let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)}),Z=Y?.ListSMSSandboxPhoneNumbersResponse?.ListSMSSandboxPhoneNumbersResult?.PhoneNumbers?.member;return{PhoneNumbers:Array.isArray(Z)?Z:Z?[Z]:[],NextToken:Y?.ListSMSSandboxPhoneNumbersResponse?.ListSMSSandboxPhoneNumbersResult?.NextToken}}async createSMSSandboxPhoneNumber($,J){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:$,LanguageCode:J||"en-US"})})}async verifySMSSandboxPhoneNumber($,J){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"VerifySMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:$,OneTimePassword:J})})}async deleteSMSSandboxPhoneNumber($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:$})})}async getSMSSandboxAccountStatus(){return{IsInSandbox:(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSSandboxAccountStatus",Version:"2010-03-31"})}))?.GetSMSSandboxAccountStatusResponse?.GetSMSSandboxAccountStatusResult?.IsInSandbox==="true"}}}w9();a1();i8();Y0();Y0();a8();Y0();Y0();Y0();Y0();Y0();Y0();Y0();Y0();Y0();Y0();Y0();class s1{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async request($,J){return this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSEvents.${$}`},body:JSON.stringify(J)})}async putRule($){return this.request("PutRule",$)}async deleteRule($){return this.request("DeleteRule",$)}async describeRule($){return this.request("DescribeRule",$)}async listRules($){return this.request("ListRules",$||{})}async listEventBuses($){return this.request("ListEventBuses",$||{})}async enableRule($){return this.request("EnableRule",$)}async disableRule($){return this.request("DisableRule",$)}async putTargets($){return this.request("PutTargets",$)}async removeTargets($){return this.request("RemoveTargets",$)}async listTargetsByRule($){return this.request("ListTargetsByRule",$)}async putEvents($){return this.request("PutEvents",$)}async createSchedule($){return this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${$.Name}`,headers:{"Content-Type":"application/json"},body:JSON.stringify($)})}}Y0();class P2{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async describeCacheClusters($){let J={Action:"DescribeCacheClusters",Version:"2015-02-02",ShowCacheNodeInfo:"true"};if($)J.CacheClusterId=$;let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{CacheClusters:this.parseCacheClusters(Y)}}async describeReplicationGroups($){let J={Action:"DescribeReplicationGroups",Version:"2015-02-02"};if($)J.ReplicationGroupId=$;let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{ReplicationGroups:[]}}async createCacheCluster($){let J={Action:"CreateCacheCluster",Version:"2015-02-02",CacheClusterId:$.cacheClusterId,Engine:$.engine,CacheNodeType:$.cacheNodeType};if($.numCacheNodes)J.NumCacheNodes=$.numCacheNodes;if($.engineVersion)J.EngineVersion=$.engineVersion;if($.port)J.Port=$.port;if($.securityGroupIds&&$.securityGroupIds.length>0)$.securityGroupIds.forEach((Z,Q)=>{J[`SecurityGroupIds.member.${Q+1}`]=Z});if($.subnetGroupName)J.CacheSubnetGroupName=$.subnetGroupName;if($.tags&&$.tags.length>0)$.tags.forEach((Z,Q)=>{J[`Tags.member.${Q+1}.Key`]=Z.Key,J[`Tags.member.${Q+1}.Value`]=Z.Value});let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{CacheCluster:this.parseCacheCluster(Y)}}async deleteCacheCluster($,J){let Y={Action:"DeleteCacheCluster",Version:"2015-02-02",CacheClusterId:$};if(J)Y.FinalSnapshotIdentifier=J;await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async rebootCacheCluster($,J){let Y={Action:"RebootCacheCluster",Version:"2015-02-02",CacheClusterId:$};J.forEach((Z,Q)=>{Y[`CacheNodeIdsToReboot.member.${Q+1}`]=Z}),await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async describeCacheEngineVersions($){let J={Action:"DescribeCacheEngineVersions",Version:"2015-02-02"};if($)J.Engine=$;let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{CacheEngineVersions:[]}}async getCacheStatistics($){let J=await this.describeCacheClusters($);if(!J.CacheClusters||J.CacheClusters.length===0)throw Error(`Cache cluster ${$} not found`);return{cpuUtilization:0,evictions:0,hits:0,misses:0,connections:0}}parseCacheClusters($){if($.CacheClusterId)return[{CacheClusterId:$.CacheClusterId,CacheClusterStatus:$.CacheClusterStatus||"available",Engine:$.Engine||"redis",EngineVersion:$.EngineVersion||"7.0",CacheNodeType:$.CacheNodeType||"cache.t3.micro",NumCacheNodes:Number.parseInt($.NumCacheNodes||"1"),CacheClusterCreateTime:$.CacheClusterCreateTime||new Date().toISOString()}];return[]}parseCacheCluster($){return{CacheClusterId:$.CacheClusterId,CacheClusterStatus:$.CacheClusterStatus||"creating",Engine:$.Engine||"redis",EngineVersion:$.EngineVersion||"7.0",CacheNodeType:$.CacheNodeType||"cache.t3.micro",NumCacheNodes:Number.parseInt($.NumCacheNodes||"1"),CacheClusterCreateTime:$.CacheClusterCreateTime||new Date().toISOString()}}}Y0();class o1{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async createRule($){let J={Action:"PutRule",Name:$.name,ScheduleExpression:$.scheduleExpression,Version:"2015-10-07"};if($.description)J.Description=$.description;if($.state)J.State=$.state;else J.State="ENABLED";return{RuleArn:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$.name,ScheduleExpression:$.scheduleExpression,State:$.state||"ENABLED",Description:$.description})})).RuleArn}}async putTargets($,J){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:$,Targets:J})})}async listRules($){let J={};if($)J.NamePrefix=$;return{Rules:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListRules","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})).Rules||[]}}async describeRule($){let J=await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DescribeRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$})});return{Name:J.Name,Arn:J.Arn,ScheduleExpression:J.ScheduleExpression,State:J.State,Description:J.Description}}async listTargetsByRule($){return{Targets:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListTargetsByRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:$})})).Targets||[]}}async deleteRule($,J){if(J)try{let Y=await this.listTargetsByRule($);if(Y.Targets&&Y.Targets.length>0)await this.removeTargets($,Y.Targets.map((Z)=>Z.Id))}catch{}await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DeleteRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$,Force:J||!1})})}async removeTargets($,J){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.RemoveTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:$,Ids:J})})}async enableRule($){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.EnableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$})})}async disableRule($){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DisableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$})})}async createLambdaSchedule($){let J=await this.createRule({name:$.name,scheduleExpression:$.scheduleExpression,description:$.description,state:"ENABLED"});return await this.putTargets($.name,[{Id:"1",Arn:$.functionArn,Input:$.input}]),J}async createEcsSchedule($){let J=await this.createRule({name:$.name,scheduleExpression:$.scheduleExpression,description:$.description,state:"ENABLED"});return await this.putTargets($.name,[{Id:"1",Arn:$.clusterArn,RoleArn:$.roleArn,Input:JSON.stringify({containerOverrides:[]})}]),J}async listSchedules($){let J={};if($?.NamePrefix)J.NamePrefix=$.NamePrefix;if($?.State)J.State=$.State;let Y=$?.GroupName||"default";return{Schedules:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedules",queryParams:{...J,ScheduleGroup:Y}}))?.Schedules||[]}}async getSchedule($){try{let J={};if($.GroupName)J.groupName=$.GroupName;return await this.client.request({service:"scheduler",region:this.region,method:"GET",path:`/schedules/${encodeURIComponent($.Name)}`,queryParams:Object.keys(J).length>0?J:void 0})}catch(J){if(J.statusCode===404||J.code==="ResourceNotFoundException")return null;throw J}}async createSchedule($){let J={ScheduleExpression:$.ScheduleExpression,FlexibleTimeWindow:$.FlexibleTimeWindow,Target:$.Target};if($.GroupName)J.GroupName=$.GroupName;if($.ScheduleExpressionTimezone)J.ScheduleExpressionTimezone=$.ScheduleExpressionTimezone;if($.Description)J.Description=$.Description;if($.State)J.State=$.State;if($.StartDate)J.StartDate=$.StartDate.toISOString();if($.EndDate)J.EndDate=$.EndDate.toISOString();return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${encodeURIComponent($.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(J)}))?.ScheduleArn||""}}async updateSchedule($){let J={};if($.GroupName)J.GroupName=$.GroupName;if($.ScheduleExpression)J.ScheduleExpression=$.ScheduleExpression;if($.ScheduleExpressionTimezone)J.ScheduleExpressionTimezone=$.ScheduleExpressionTimezone;if($.Description!==void 0)J.Description=$.Description;if($.State)J.State=$.State;if($.FlexibleTimeWindow)J.FlexibleTimeWindow=$.FlexibleTimeWindow;if($.Target)J.Target=$.Target;return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"PUT",path:`/schedules/${encodeURIComponent($.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(J)}))?.ScheduleArn||""}}async deleteSchedule($){let J={};if($.GroupName)J.groupName=$.GroupName;await this.client.request({service:"scheduler",region:this.region,method:"DELETE",path:`/schedules/${encodeURIComponent($.Name)}`,queryParams:Object.keys(J).length>0?J:void 0})}async listScheduleGroups($){let J={};if($?.NamePrefix)J.NamePrefix=$.NamePrefix;return{ScheduleGroups:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedule-groups",queryParams:Object.keys(J).length>0?J:void 0}))?.ScheduleGroups||[]}}}T7();Y0();I0();z9();I0();I0();I0();Y0();I0();Y0();nQ();Y2();Y2();e2();O$();$9();J9();J9();await z8([Q1(),CZ(),a7()]);Y2();await j$();n0();z0();var KX=["aws","backblaze","hetzner"];function OX($,J){let Y=$.indexOf(":");if(Y===-1)throw Error(`--${J} must be in the form <provider:bucket> (e.g. aws:my-bucket), got "${$}"`);let Z=$.slice(0,Y),Q=$.slice(Y+1);if(!KX.includes(Z))throw Error(`Unknown provider "${Z}" for --${J}. Supported: ${KX.join(", ")}`);if(!Q)throw Error(`--${J} is missing a bucket name (expected <provider:bucket>)`);return{provider:Z,bucket:Q}}function VX($){if(!$)return;let J=$.split(",").map((Y)=>Y.trim()).filter(Boolean);return J.length>0?J:void 0}function CG($){$.command("migrate:storage","Migrate object-storage data between providers (AWS S3 ↔ Hetzner ↔ Backblaze)").option("--from <provider:bucket>","Source endpoint, e.g. aws:stacks-production-email").option("--to <provider:bucket>","Destination endpoint, e.g. hetzner:stacks-mail").option("--from-region <region>","Source region/location (default: provider default)").option("--to-region <region>","Destination region/location (default: provider default)").option("--from-endpoint <host>","Source endpoint host override (no scheme)").option("--to-endpoint <host>","Destination endpoint host override (no scheme)").option("--from-prefix <prefix>","Only read source keys under this prefix (stripped from dest key)").option("--to-prefix <prefix>","Prepend this prefix to every destination key").option("--include <csv>","Only copy keys under these comma-separated prefixes").option("--exclude <csv>","Skip keys under these comma-separated prefixes").option("--dry-run","Print the plan (what would copy / what is excluded) without writing").option("--force","Re-copy even if the destination already has an object of the same size").option("--delete-extraneous","Delete destination keys not present in the source (default OFF)").option("--concurrency <n>","Max concurrent copies",{default:"8"}).option("--verify","After copying, re-list the destination and assert object count + sizes match").action(async(J)=>{R("Migrate Object Storage");try{if(!J.from||!J.to)throw Error("Both --from <provider:bucket> and --to <provider:bucket> are required");let Y=OX(J.from,"from"),Z=OX(J.to,"to"),Q=VX(J.include),G=VX(J.exclude),W=Number.parseInt(J.concurrency||"8",10),z={provider:Y.provider,bucket:Y.bucket,region:J.fromRegion,endpoint:J.fromEndpoint,prefix:J.fromPrefix},U={provider:Z.provider,bucket:Z.bucket,region:J.toRegion,endpoint:J.toEndpoint,prefix:J.toPrefix};if(X(`Source: ${Y.provider}:${Y.bucket}${J.fromPrefix?`/${J.fromPrefix}`:""}`),X(`Destination: ${Z.provider}:${Z.bucket}${J.toPrefix?`/${J.toPrefix}`:""}`),Q)X(`Include: ${Q.join(", ")}`);if(G)X(`Exclude: ${G.join(", ")}`);if(X(`Concurrency: ${W}`),J.dryRun)v("Dry run — no objects will be written");if(J.deleteExtraneous&&!J.dryRun)v("Delete-extraneous ON — destination keys not in the source will be removed");let H=new N("Listing source objects...");H.start();let F=0,B=await SG({from:z,to:U,include:Q,exclude:G,dryRun:J.dryRun,force:J.force,deleteExtraneous:J.deleteExtraneous,concurrency:W,verify:J.verify,onProgress:(K)=>{if(K.index-F>=1||K.index===K.total){F=K.index;let O=K.action==="planned"?"plan":K.action;H.text=`[${K.index}/${K.total}] ${O}: ${K.key}`}}});if(H.succeed(J.dryRun?"Plan ready":"Migration complete"),J.dryRun&&B.plan){X(`
8162
+ Bucket Policy:`),console.log(JSON.stringify(G||{},null,2))}catch(G){if(G.message?.includes("NoSuchBucketPolicy"))Q.succeed("No policy set"),X("This bucket has no policy configured.");else throw G}}catch(Z){w(`Failed to manage policy: ${Z.message}`),process.exit(1)}}),$.command("storage:ls <bucket>","List objects in a bucket").option("--prefix <prefix>","Filter by prefix").option("--limit <number>","Limit number of results",{default:"100"}).action(async(J,Y)=>{R(`Objects in ${J}`);try{let Z=new W0("us-east-1"),Q=new N("Listing objects...");Q.start();let G=await Z.listObjects({bucket:J,prefix:Y.prefix,maxKeys:Number.parseInt(Y.limit||"100")}),W=G.objects;if(Q.succeed(`Found ${W.length} object(s)${G.nextContinuationToken?" (truncated)":""}`),W.length===0){X("No objects found");return}if(p(["Key","Size","Last Modified"],W.map((z)=>[z.Key||"N/A",o3(z.Size||0),z.LastModified?new Date(z.LastModified).toLocaleString():"N/A"])),G.nextContinuationToken)X(`
8163
+ More objects available. Use --limit to see more.`)}catch(Z){w(`Failed to list objects: ${Z.message}`),process.exit(1)}})}function s3($){let J=$.split(".").pop()?.toLowerCase();return{html:"text/html",css:"text/css",js:"application/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",eot:"application/vnd.ms-fontobject",pdf:"application/pdf",zip:"application/zip",xml:"application/xml",txt:"text/plain",md:"text/markdown"}[J||""]||"application/octet-stream"}function o3($){if($===0)return"0 B";let J=1024,Y=["B","KB","MB","GB","TB"],Z=Math.floor(Math.log($)/Math.log(J));return`${Number.parseFloat(($/J**Z).toFixed(2))} ${Y[Z]}`}Y0();I0();function e3($,J){if(!J)return $;return $.startsWith(J)?$.slice(J.length):$}function RG($,J,Y){let Z=e3($,J);return`${Y??""}${Z}`}function NG($,J,Y){if(Y&&Y.some((Z)=>$.startsWith(Z)))return!1;if(J&&J.length>0)return J.some((Z)=>$.startsWith(Z));return!0}async function $w($,J,Y){let Z=0,Q=[],G=Math.max(1,Math.min(J,$.length||1));for(let W=0;W<G;W++)Q.push((async()=>{while(!0){let z=Z++;if(z>=$.length)return;await Y($[z],z)}})());await Promise.all(Q)}function FX($){if($.client)return $.client;return PG({provider:$.provider,region:$.region,endpoint:$.endpoint,forcePathStyle:$.forcePathStyle,credentials:$.credentials})}async function SG($){let J=$.concurrency??8,Y=FX($.from),Z=FX($.to),Q=await Y.listAllObjects({bucket:$.from.bucket,prefix:$.from.prefix}),G={copied:0,skipped:0,excluded:0,bytesCopied:0,errors:[],excludedKeys:[],deleted:[]},W=[];for(let F of Q){if(!NG(F.Key,$.include,$.exclude)){G.excluded++,G.excludedKeys.push(F.Key);continue}W.push({source:F,destKey:RG(F.Key,$.from.prefix,$.to.prefix)})}if($.dryRun){G.plan=W.map(({source:K,destKey:O})=>({key:K.Key,destKey:O,size:K.Size}));let F=Q.length,B=0;for(let K of Q){B++;let O=!NG(K.Key,$.include,$.exclude);$.onProgress?.({key:K.Key,destKey:O?"":RG(K.Key,$.from.prefix,$.to.prefix),size:K.Size,action:O?"excluded":"planned",index:B,total:F})}return G}let z=W.length,U=0;await $w(W,J,async({source:F,destKey:B})=>{let K=++U;try{if(!$.force){let V=await Z.headObject($.to.bucket,B);if(V&&V.ContentLength===F.Size){G.skipped++,$.onProgress?.({key:F.Key,destKey:B,size:F.Size,action:"skipped",index:K,total:z});return}}let{body:O,contentType:A}=await Y.getObjectBytes($.from.bucket,F.Key);await Z.putObject({bucket:$.to.bucket,key:B,body:O,contentType:A}),G.copied++,G.bytesCopied+=O.byteLength,$.onProgress?.({key:F.Key,destKey:B,size:F.Size,action:"copied",index:K,total:z})}catch(O){G.errors.push({key:F.Key,message:O?.message??String(O)}),$.onProgress?.({key:F.Key,destKey:B,size:F.Size,action:"error",index:K,total:z})}});let H=new Set(W.map((F)=>F.destKey));if($.deleteExtraneous){let B=(await Z.listAllObjects({bucket:$.to.bucket,prefix:$.to.prefix})).filter((K)=>!H.has(K.Key)).map((K)=>K.Key);for(let K of B)try{await Z.deleteObject($.to.bucket,K),G.deleted.push(K)}catch(O){G.errors.push({key:K,message:`delete failed: ${O?.message??String(O)}`})}}if($.verify){let F=await Z.listAllObjects({bucket:$.to.bucket,prefix:$.to.prefix}),B=new Map(F.map((V)=>[V.Key,V.Size])),K=[],O=[],A=0;for(let{source:V,destKey:_}of W){if(!B.has(_)){K.push(_);continue}let E=B.get(_);if(E!==V.Size){O.push({key:_,expected:V.Size,actual:E});continue}A++}G.verification={ok:K.length===0&&O.length===0,matched:A,missing:K,sizeMismatches:O}}return G}var Jw={aws:"us-east-1",backblaze:"us-west-004",hetzner:"fsn1"};function XX($,J){switch($){case"backblaze":return`s3.${J}.backblazeb2.com`;case"hetzner":return`${J}.your-objectstorage.com`;case"aws":default:return}}function I1(...$){for(let J of $){let Y=process.env[J];if(Y)return Y}return}function Yw($,J){if(J?.accessKeyId&&J.secretAccessKey)return J;let Y,Z;if($==="backblaze")Y=I1("B2_APPLICATION_KEY_ID","B2_KEY_ID","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),Z=I1("B2_APPLICATION_KEY","B2_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else if($==="hetzner")Y=I1("HETZNER_S3_ACCESS_KEY","HETZNER_ACCESS_KEY","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),Z=I1("HETZNER_S3_SECRET_KEY","HETZNER_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else Y=I1("S3_ACCESS_KEY_ID"),Z=I1("S3_SECRET_ACCESS_KEY");if(Y&&Z)return{accessKeyId:Y,secretAccessKey:Z,sessionToken:I1("AWS_SESSION_TOKEN")};return}function BX($={}){let J=$.provider||I1("OBJECT_STORAGE_PROVIDER","STORAGE_PROVIDER")||"aws",Y=$.region||(J==="backblaze"?I1("B2_REGION"):void 0)||(J==="hetzner"?I1("HETZNER_S3_REGION","HETZNER_REGION"):void 0)||I1("S3_REGION","AWS_REGION","AWS_DEFAULT_REGION")||Jw[J],Z=$.endpoint||I1("S3_ENDPOINT")||XX(J,Y),Q=$.forcePathStyle??I1("S3_FORCE_PATH_STYLE")==="true",G=Yw(J,$.credentials),W=(z)=>{let U=Z||`s3.${Y}.amazonaws.com`;return Q?`https://${U}/${z}`:`https://${z}.${U}`};return{provider:J,region:Y,endpoint:Z,forcePathStyle:Q,credentials:G,profile:$.profile,publicBaseUrl:W}}function PG($={}){let J=BX($),Y={endpoint:J.endpoint,forcePathStyle:J.forcePathStyle,credentials:J.credentials};return new W0(J.region,J.profile,Y)}M1();U7();Y9();I0();U2();e2();Y0();L2();e6();F7();ZQ();o6();z9();HQ();Y0();class w1{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}buildFormBody($){return Object.entries($).filter(([,Y])=>Y!==void 0).map(([Y,Z])=>`${encodeURIComponent(Y)}=${encodeURIComponent(Z)}`).join("&")}async createTopic($){let J={Action:"CreateTopic",Version:"2010-03-31",Name:$.Name};if($.DisplayName)J["Attributes.entry.1.key"]="DisplayName",J["Attributes.entry.1.value"]=$.DisplayName;if($.Tags)$.Tags.forEach((Z,Q)=>{J[`Tags.member.${Q+1}.Key`]=Z.Key,J[`Tags.member.${Q+1}.Value`]=Z.Value});if($.Attributes){let Z=$.DisplayName?2:1;Object.entries($.Attributes).forEach(([Q,G])=>{J[`Attributes.entry.${Z}.key`]=Q,J[`Attributes.entry.${Z}.value`]=G,Z++})}let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)});return{TopicArn:Y?.CreateTopicResponse?.CreateTopicResult?.TopicArn||Y?.TopicArn}}async deleteTopic($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteTopic",Version:"2010-03-31",TopicArn:$})})}async listTopics($){let J={Action:"ListTopics",Version:"2010-03-31"};if($)J.NextToken=$;let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)}),Z=Y?.ListTopicsResponse?.ListTopicsResult||Y?.ListTopicsResult,Q=Z?.Topics?.member;return{Topics:Array.isArray(Q)?Q:Q?[Q]:[],NextToken:Z?.NextToken}}async getTopicAttributes($){let Y=(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetTopicAttributes",Version:"2010-03-31",TopicArn:$})}))?.GetTopicAttributesResponse?.GetTopicAttributesResult?.Attributes?.entry,Z={TopicArn:$};if(Array.isArray(Y))Y.forEach((Q)=>{Z[Q.key]=Q.value});return Z}async setTopicAttributes($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetTopicAttributes",Version:"2010-03-31",TopicArn:$.TopicArn,AttributeName:$.AttributeName,AttributeValue:$.AttributeValue})})}async subscribe($){let J={Action:"Subscribe",Version:"2010-03-31",TopicArn:$.TopicArn,Protocol:$.Protocol,Endpoint:$.Endpoint};if($.ReturnSubscriptionArn)J.ReturnSubscriptionArn="true";if($.Attributes){let Z=1;Object.entries($.Attributes).forEach(([Q,G])=>{J[`Attributes.entry.${Z}.key`]=Q,J[`Attributes.entry.${Z}.value`]=G,Z++})}let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)});return{SubscriptionArn:Y?.SubscribeResponse?.SubscribeResult?.SubscriptionArn||Y?.SubscriptionArn}}async unsubscribe($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"Unsubscribe",Version:"2010-03-31",SubscriptionArn:$})})}async listSubscriptionsByTopic($,J){let Y={Action:"ListSubscriptionsByTopic",Version:"2010-03-31",TopicArn:$};if(J)Y.NextToken=J;let Z=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(Y)}),Q=Z?.ListSubscriptionsByTopicResponse?.ListSubscriptionsByTopicResult?.Subscriptions?.member;return{Subscriptions:Array.isArray(Q)?Q:Q?[Q]:[],NextToken:Z?.ListSubscriptionsByTopicResponse?.ListSubscriptionsByTopicResult?.NextToken}}async publish($){let J={Action:"Publish",Version:"2010-03-31",Message:$.Message};if($.TopicArn)J.TopicArn=$.TopicArn;if($.TargetArn)J.TargetArn=$.TargetArn;if($.PhoneNumber)J.PhoneNumber=$.PhoneNumber;if($.Subject)J.Subject=$.Subject;if($.MessageStructure)J.MessageStructure=$.MessageStructure;if($.MessageAttributes){let Z=1;Object.entries($.MessageAttributes).forEach(([Q,G])=>{if(J[`MessageAttributes.entry.${Z}.Name`]=Q,J[`MessageAttributes.entry.${Z}.Value.DataType`]=G.DataType,G.StringValue)J[`MessageAttributes.entry.${Z}.Value.StringValue`]=G.StringValue;if(G.BinaryValue)J[`MessageAttributes.entry.${Z}.Value.BinaryValue`]=G.BinaryValue;Z++})}let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)});return{MessageId:Y?.PublishResponse?.PublishResult?.MessageId||Y?.MessageId}}async publishSMS($,J,Y){let Z={};if(Y)Z["AWS.SNS.SMS.SenderID"]={DataType:"String",StringValue:Y};return this.publish({PhoneNumber:$,Message:J,MessageAttributes:Object.keys(Z).length>0?Z:void 0})}async subscribeEmail($,J){return this.subscribe({TopicArn:$,Protocol:"email",Endpoint:J})}async subscribeLambda($,J){return this.subscribe({TopicArn:$,Protocol:"lambda",Endpoint:J})}async subscribeSqs($,J,Y){let Z={};if(Y)Z.RawMessageDelivery="true";return this.subscribe({TopicArn:$,Protocol:"sqs",Endpoint:J,Attributes:Object.keys(Z).length>0?Z:void 0})}async subscribeHttp($,J,Y){let Z=J.startsWith("https")?"https":"http",Q={};if(Y)Q.RawMessageDelivery="true";return this.subscribe({TopicArn:$,Protocol:Z,Endpoint:J,Attributes:Object.keys(Q).length>0?Q:void 0})}async subscribeSms($,J){return this.subscribe({TopicArn:$,Protocol:"sms",Endpoint:J})}async topicExists($){try{return await this.getTopicAttributes($),!0}catch(J){if(J.code==="NotFound"||J.statusCode===404)return!1;throw J}}async getSMSAttributes(){let J=(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSAttributes",Version:"2010-03-31"})}))?.GetSMSAttributesResponse?.GetSMSAttributesResult?.attributes?.entry,Y={};if(Array.isArray(J))J.forEach((Z)=>{Y[Z.key]=Z.value});else if(J)Y[J.key]=J.value;return Y}async setSMSAttributes($){let J={Action:"SetSMSAttributes",Version:"2010-03-31"},Y=1;Object.entries($).forEach(([Z,Q])=>{if(Q!==void 0)J[`attributes.entry.${Y}.key`]=Z,J[`attributes.entry.${Y}.value`]=Q,Y++}),await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)})}async checkIfPhoneNumberIsOptedOut($){return(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CheckIfPhoneNumberIsOptedOut",Version:"2010-03-31",phoneNumber:$})}))?.CheckIfPhoneNumberIsOptedOutResponse?.CheckIfPhoneNumberIsOptedOutResult?.isOptedOut==="true"}async listPhoneNumbersOptedOut($){let J={Action:"ListPhoneNumbersOptedOut",Version:"2010-03-31"};if($)J.nextToken=$;let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)}),Z=Y?.ListPhoneNumbersOptedOutResponse?.ListPhoneNumbersOptedOutResult?.phoneNumbers?.member;return{phoneNumbers:Array.isArray(Z)?Z:Z?[Z]:[],nextToken:Y?.ListPhoneNumbersOptedOutResponse?.ListPhoneNumbersOptedOutResult?.nextToken}}async optInPhoneNumber($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"OptInPhoneNumber",Version:"2010-03-31",phoneNumber:$})})}async listSMSSandboxPhoneNumbers($){let J={Action:"ListSMSSandboxPhoneNumbers",Version:"2010-03-31"};if($)J.NextToken=$;let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)}),Z=Y?.ListSMSSandboxPhoneNumbersResponse?.ListSMSSandboxPhoneNumbersResult?.PhoneNumbers?.member;return{PhoneNumbers:Array.isArray(Z)?Z:Z?[Z]:[],NextToken:Y?.ListSMSSandboxPhoneNumbersResponse?.ListSMSSandboxPhoneNumbersResult?.NextToken}}async createSMSSandboxPhoneNumber($,J){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:$,LanguageCode:J||"en-US"})})}async verifySMSSandboxPhoneNumber($,J){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"VerifySMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:$,OneTimePassword:J})})}async deleteSMSSandboxPhoneNumber($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:$})})}async getSMSSandboxAccountStatus(){return{IsInSandbox:(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSSandboxAccountStatus",Version:"2010-03-31"})}))?.GetSMSSandboxAccountStatusResponse?.GetSMSSandboxAccountStatusResult?.IsInSandbox==="true"}}}w9();a1();i8();Y0();Y0();a8();Y0();Y0();Y0();Y0();Y0();Y0();Y0();Y0();Y0();Y0();Y0();class s1{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async request($,J){return this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSEvents.${$}`},body:JSON.stringify(J)})}async putRule($){return this.request("PutRule",$)}async deleteRule($){return this.request("DeleteRule",$)}async describeRule($){return this.request("DescribeRule",$)}async listRules($){return this.request("ListRules",$||{})}async listEventBuses($){return this.request("ListEventBuses",$||{})}async enableRule($){return this.request("EnableRule",$)}async disableRule($){return this.request("DisableRule",$)}async putTargets($){return this.request("PutTargets",$)}async removeTargets($){return this.request("RemoveTargets",$)}async listTargetsByRule($){return this.request("ListTargetsByRule",$)}async putEvents($){return this.request("PutEvents",$)}async createSchedule($){return this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${$.Name}`,headers:{"Content-Type":"application/json"},body:JSON.stringify($)})}}Y0();class P2{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async describeCacheClusters($){let J={Action:"DescribeCacheClusters",Version:"2015-02-02",ShowCacheNodeInfo:"true"};if($)J.CacheClusterId=$;let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{CacheClusters:this.parseCacheClusters(Y)}}async describeReplicationGroups($){let J={Action:"DescribeReplicationGroups",Version:"2015-02-02"};if($)J.ReplicationGroupId=$;let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{ReplicationGroups:[]}}async createCacheCluster($){let J={Action:"CreateCacheCluster",Version:"2015-02-02",CacheClusterId:$.cacheClusterId,Engine:$.engine,CacheNodeType:$.cacheNodeType};if($.numCacheNodes)J.NumCacheNodes=$.numCacheNodes;if($.engineVersion)J.EngineVersion=$.engineVersion;if($.port)J.Port=$.port;if($.securityGroupIds&&$.securityGroupIds.length>0)$.securityGroupIds.forEach((Z,Q)=>{J[`SecurityGroupIds.member.${Q+1}`]=Z});if($.subnetGroupName)J.CacheSubnetGroupName=$.subnetGroupName;if($.tags&&$.tags.length>0)$.tags.forEach((Z,Q)=>{J[`Tags.member.${Q+1}.Key`]=Z.Key,J[`Tags.member.${Q+1}.Value`]=Z.Value});let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{CacheCluster:this.parseCacheCluster(Y)}}async deleteCacheCluster($,J){let Y={Action:"DeleteCacheCluster",Version:"2015-02-02",CacheClusterId:$};if(J)Y.FinalSnapshotIdentifier=J;await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async rebootCacheCluster($,J){let Y={Action:"RebootCacheCluster",Version:"2015-02-02",CacheClusterId:$};J.forEach((Z,Q)=>{Y[`CacheNodeIdsToReboot.member.${Q+1}`]=Z}),await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async describeCacheEngineVersions($){let J={Action:"DescribeCacheEngineVersions",Version:"2015-02-02"};if($)J.Engine=$;let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{CacheEngineVersions:[]}}async getCacheStatistics($){let J=await this.describeCacheClusters($);if(!J.CacheClusters||J.CacheClusters.length===0)throw Error(`Cache cluster ${$} not found`);return{cpuUtilization:0,evictions:0,hits:0,misses:0,connections:0}}parseCacheClusters($){if($.CacheClusterId)return[{CacheClusterId:$.CacheClusterId,CacheClusterStatus:$.CacheClusterStatus||"available",Engine:$.Engine||"redis",EngineVersion:$.EngineVersion||"7.0",CacheNodeType:$.CacheNodeType||"cache.t3.micro",NumCacheNodes:Number.parseInt($.NumCacheNodes||"1"),CacheClusterCreateTime:$.CacheClusterCreateTime||new Date().toISOString()}];return[]}parseCacheCluster($){return{CacheClusterId:$.CacheClusterId,CacheClusterStatus:$.CacheClusterStatus||"creating",Engine:$.Engine||"redis",EngineVersion:$.EngineVersion||"7.0",CacheNodeType:$.CacheNodeType||"cache.t3.micro",NumCacheNodes:Number.parseInt($.NumCacheNodes||"1"),CacheClusterCreateTime:$.CacheClusterCreateTime||new Date().toISOString()}}}Y0();class o1{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async createRule($){let J={Action:"PutRule",Name:$.name,ScheduleExpression:$.scheduleExpression,Version:"2015-10-07"};if($.description)J.Description=$.description;if($.state)J.State=$.state;else J.State="ENABLED";return{RuleArn:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$.name,ScheduleExpression:$.scheduleExpression,State:$.state||"ENABLED",Description:$.description})})).RuleArn}}async putTargets($,J){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:$,Targets:J})})}async listRules($){let J={};if($)J.NamePrefix=$;return{Rules:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListRules","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})).Rules||[]}}async describeRule($){let J=await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DescribeRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$})});return{Name:J.Name,Arn:J.Arn,ScheduleExpression:J.ScheduleExpression,State:J.State,Description:J.Description}}async listTargetsByRule($){return{Targets:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListTargetsByRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:$})})).Targets||[]}}async deleteRule($,J){if(J)try{let Y=await this.listTargetsByRule($);if(Y.Targets&&Y.Targets.length>0)await this.removeTargets($,Y.Targets.map((Z)=>Z.Id))}catch{}await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DeleteRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$,Force:J||!1})})}async removeTargets($,J){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.RemoveTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:$,Ids:J})})}async enableRule($){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.EnableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$})})}async disableRule($){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DisableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$})})}async createLambdaSchedule($){let J=await this.createRule({name:$.name,scheduleExpression:$.scheduleExpression,description:$.description,state:"ENABLED"});return await this.putTargets($.name,[{Id:"1",Arn:$.functionArn,Input:$.input}]),J}async createEcsSchedule($){let J=await this.createRule({name:$.name,scheduleExpression:$.scheduleExpression,description:$.description,state:"ENABLED"});return await this.putTargets($.name,[{Id:"1",Arn:$.clusterArn,RoleArn:$.roleArn,Input:JSON.stringify({containerOverrides:[]})}]),J}async listSchedules($){let J={};if($?.NamePrefix)J.NamePrefix=$.NamePrefix;if($?.State)J.State=$.State;let Y=$?.GroupName||"default";return{Schedules:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedules",queryParams:{...J,ScheduleGroup:Y}}))?.Schedules||[]}}async getSchedule($){try{let J={};if($.GroupName)J.groupName=$.GroupName;return await this.client.request({service:"scheduler",region:this.region,method:"GET",path:`/schedules/${encodeURIComponent($.Name)}`,queryParams:Object.keys(J).length>0?J:void 0})}catch(J){if(J.statusCode===404||J.code==="ResourceNotFoundException")return null;throw J}}async createSchedule($){let J={ScheduleExpression:$.ScheduleExpression,FlexibleTimeWindow:$.FlexibleTimeWindow,Target:$.Target};if($.GroupName)J.GroupName=$.GroupName;if($.ScheduleExpressionTimezone)J.ScheduleExpressionTimezone=$.ScheduleExpressionTimezone;if($.Description)J.Description=$.Description;if($.State)J.State=$.State;if($.StartDate)J.StartDate=$.StartDate.toISOString();if($.EndDate)J.EndDate=$.EndDate.toISOString();return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${encodeURIComponent($.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(J)}))?.ScheduleArn||""}}async updateSchedule($){let J={};if($.GroupName)J.GroupName=$.GroupName;if($.ScheduleExpression)J.ScheduleExpression=$.ScheduleExpression;if($.ScheduleExpressionTimezone)J.ScheduleExpressionTimezone=$.ScheduleExpressionTimezone;if($.Description!==void 0)J.Description=$.Description;if($.State)J.State=$.State;if($.FlexibleTimeWindow)J.FlexibleTimeWindow=$.FlexibleTimeWindow;if($.Target)J.Target=$.Target;return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"PUT",path:`/schedules/${encodeURIComponent($.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(J)}))?.ScheduleArn||""}}async deleteSchedule($){let J={};if($.GroupName)J.groupName=$.GroupName;await this.client.request({service:"scheduler",region:this.region,method:"DELETE",path:`/schedules/${encodeURIComponent($.Name)}`,queryParams:Object.keys(J).length>0?J:void 0})}async listScheduleGroups($){let J={};if($?.NamePrefix)J.NamePrefix=$.NamePrefix;return{ScheduleGroups:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedule-groups",queryParams:Object.keys(J).length>0?J:void 0}))?.ScheduleGroups||[]}}}T7();Y0();I0();z9();I0();I0();I0();Y0();I0();Y0();nQ();Y2();Y2();e2();O$();$9();J9();J9();await z8([Q1(),CZ(),a7()]);Y2();await j$();n0();z0();var KX=["aws","backblaze","hetzner"];function OX($,J){let Y=$.indexOf(":");if(Y===-1)throw Error(`--${J} must be in the form <provider:bucket> (e.g. aws:my-bucket), got "${$}"`);let Z=$.slice(0,Y),Q=$.slice(Y+1);if(!KX.includes(Z))throw Error(`Unknown provider "${Z}" for --${J}. Supported: ${KX.join(", ")}`);if(!Q)throw Error(`--${J} is missing a bucket name (expected <provider:bucket>)`);return{provider:Z,bucket:Q}}function VX($){if(!$)return;let J=$.split(",").map((Y)=>Y.trim()).filter(Boolean);return J.length>0?J:void 0}function CG($){$.command("migrate:storage","Migrate object-storage data between providers (AWS S3 ↔ Hetzner ↔ Backblaze)").option("--from <provider:bucket>","Source endpoint, e.g. aws:stacks-production-email").option("--to <provider:bucket>","Destination endpoint, e.g. hetzner:stacks-mail").option("--from-region <region>","Source region/location (default: provider default)").option("--to-region <region>","Destination region/location (default: provider default)").option("--from-endpoint <host>","Source endpoint host override (no scheme)").option("--to-endpoint <host>","Destination endpoint host override (no scheme)").option("--from-prefix <prefix>","Only read source keys under this prefix (stripped from dest key)").option("--to-prefix <prefix>","Prepend this prefix to every destination key").option("--include <csv>","Only copy keys under these comma-separated prefixes").option("--exclude <csv>","Skip keys under these comma-separated prefixes").option("--dry-run","Print the plan (what would copy / what is excluded) without writing").option("--force","Re-copy even if the destination already has an object of the same size").option("--delete-extraneous","Delete destination keys not present in the source (default OFF)").option("--concurrency <n>","Max concurrent copies",{default:"8"}).option("--verify","After copying, re-list the destination and assert object count + sizes match").action(async(J)=>{R("Migrate Object Storage");try{if(!J.from||!J.to)throw Error("Both --from <provider:bucket> and --to <provider:bucket> are required");let Y=OX(J.from,"from"),Z=OX(J.to,"to"),Q=VX(J.include),G=VX(J.exclude),W=Number.parseInt(J.concurrency||"8",10),z={provider:Y.provider,bucket:Y.bucket,region:J.fromRegion,endpoint:J.fromEndpoint,prefix:J.fromPrefix},U={provider:Z.provider,bucket:Z.bucket,region:J.toRegion,endpoint:J.toEndpoint,prefix:J.toPrefix};if(X(`Source: ${Y.provider}:${Y.bucket}${J.fromPrefix?`/${J.fromPrefix}`:""}`),X(`Destination: ${Z.provider}:${Z.bucket}${J.toPrefix?`/${J.toPrefix}`:""}`),Q)X(`Include: ${Q.join(", ")}`);if(G)X(`Exclude: ${G.join(", ")}`);if(X(`Concurrency: ${W}`),J.dryRun)v("Dry run — no objects will be written");if(J.deleteExtraneous&&!J.dryRun)v("Delete-extraneous ON — destination keys not in the source will be removed");let H=new N("Listing source objects...");H.start();let F=0,B=await SG({from:z,to:U,include:Q,exclude:G,dryRun:J.dryRun,force:J.force,deleteExtraneous:J.deleteExtraneous,concurrency:W,verify:J.verify,onProgress:(K)=>{if(K.index-F>=1||K.index===K.total){F=K.index;let O=K.action==="planned"?"plan":K.action;H.text=`[${K.index}/${K.total}] ${O}: ${K.key}`}}});if(H.succeed(J.dryRun?"Plan ready":"Migration complete"),J.dryRun&&B.plan){X(`
8159
8164
  Would copy ${B.plan.length} object(s):`);for(let K of B.plan.slice(0,50))X(` ${K.key} -> ${K.destKey} (${v9(K.size)})`);if(B.plan.length>50)X(` ... and ${B.plan.length-50} more`)}if(B.excludedKeys.length>0){X(`
8160
8165
  EXCLUDED ${B.excludedKeys.length} key(s) (deliberately not migrated):`);for(let K of B.excludedKeys.slice(0,50))X(` ${K}`);if(B.excludedKeys.length>50)X(` ... and ${B.excludedKeys.length-50} more`)}if(B.deleted.length>0){v(`
8161
8166
  Deleted ${B.deleted.length} extraneous destination key(s):`);for(let K of B.deleted.slice(0,50))v(` ${K}`)}if(X(`