@stacksjs/ts-cloud 0.1.9 → 0.1.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -17
- package/dist/aws/setup-sms.d.ts +1 -0
- package/dist/bin/cli.js +11 -11
- package/dist/config.d.ts +1 -1
- package/dist/generators/infrastructure.d.ts +2 -2
- package/dist/index.d.ts +3 -3
- package/dist/index.js +43 -43
- package/dist/types.d.ts +1 -1
- package/dist/validation/template.d.ts +1 -1
- package/package.json +5 -6
- package/src/aws/acm.ts +0 -768
- package/src/aws/application-autoscaling.ts +0 -845
- package/src/aws/bedrock.ts +0 -4074
- package/src/aws/client.ts +0 -891
- package/src/aws/cloudformation.ts +0 -896
- package/src/aws/cloudfront.ts +0 -1531
- package/src/aws/cloudwatch-logs.ts +0 -154
- package/src/aws/comprehend.ts +0 -839
- package/src/aws/connect.ts +0 -1056
- package/src/aws/deploy-imap.ts +0 -384
- package/src/aws/dynamodb.ts +0 -340
- package/src/aws/ec2.ts +0 -1385
- package/src/aws/ecr.ts +0 -621
- package/src/aws/ecs.ts +0 -615
- package/src/aws/elasticache.ts +0 -301
- package/src/aws/elbv2.ts +0 -942
- package/src/aws/email.ts +0 -928
- package/src/aws/eventbridge.ts +0 -248
- package/src/aws/iam.ts +0 -1689
- package/src/aws/imap-server.ts +0 -2100
- package/src/aws/index.ts +0 -213
- package/src/aws/kendra.ts +0 -1097
- package/src/aws/lambda.ts +0 -786
- package/src/aws/opensearch.ts +0 -158
- package/src/aws/personalize.ts +0 -977
- package/src/aws/polly.ts +0 -559
- package/src/aws/rds.ts +0 -888
- package/src/aws/rekognition.ts +0 -846
- package/src/aws/route53-domains.ts +0 -359
- package/src/aws/route53.ts +0 -1046
- package/src/aws/s3.ts +0 -2334
- package/src/aws/scheduler.ts +0 -571
- package/src/aws/secrets-manager.ts +0 -769
- package/src/aws/ses.ts +0 -1081
- package/src/aws/setup-phone.ts +0 -104
- package/src/aws/setup-sms.ts +0 -580
- package/src/aws/sms.ts +0 -1735
- package/src/aws/smtp-server.ts +0 -531
- package/src/aws/sns.ts +0 -758
- package/src/aws/sqs.ts +0 -382
- package/src/aws/ssm.ts +0 -807
- package/src/aws/sts.ts +0 -92
- package/src/aws/support.ts +0 -391
- package/src/aws/test-imap.ts +0 -86
- package/src/aws/textract.ts +0 -780
- package/src/aws/transcribe.ts +0 -108
- package/src/aws/translate.ts +0 -641
- package/src/aws/voice.ts +0 -1379
- package/src/config.ts +0 -35
- package/src/deploy/index.ts +0 -7
- package/src/deploy/static-site-external-dns.ts +0 -945
- package/src/deploy/static-site.ts +0 -1175
- package/src/dns/cloudflare.ts +0 -548
- package/src/dns/godaddy.ts +0 -412
- package/src/dns/index.ts +0 -205
- package/src/dns/porkbun.ts +0 -362
- package/src/dns/route53-adapter.ts +0 -414
- package/src/dns/types.ts +0 -119
- package/src/dns/validator.ts +0 -369
- package/src/generators/index.ts +0 -5
- package/src/generators/infrastructure.ts +0 -1660
- package/src/index.ts +0 -163
- package/src/push/apns.ts +0 -452
- package/src/push/fcm.ts +0 -506
- package/src/push/index.ts +0 -58
- package/src/security/pre-deploy-scanner.ts +0 -655
- package/src/ssl/acme-client.ts +0 -478
- package/src/ssl/index.ts +0 -7
- package/src/ssl/letsencrypt.ts +0 -747
- package/src/types.ts +0 -2
- package/src/utils/cli.ts +0 -398
- package/src/validation/index.ts +0 -5
- package/src/validation/template.ts +0 -405
package/dist/index.js
CHANGED
|
@@ -148,7 +148,7 @@ ${Object.entries($).filter(([W])=>!W.startsWith("@_")).map(([W,U])=>Q(W,U," ","
|
|
|
148
148
|
</FunctionConfig>
|
|
149
149
|
<FunctionCode>${Buffer.from(_).toString("base64")}</FunctionCode>
|
|
150
150
|
</UpdateFunctionRequest>`,U=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/function/${J}`,body:W,headers:{"Content-Type":"application/xml","If-Match":Q},returnHeaders:!0});return{ETag:U.headers?.etag||U.ETag||"",FunctionSummary:U.body?.FunctionSummary||U.FunctionSummary||U.body||U}}async deleteFunction($,J){let _=J;if(!_){let Y=await this.getFunction($,"DEVELOPMENT");if(!Y)return;_=Y.ETag}await this.client.request({service:"cloudfront",region:"us-east-1",method:"DELETE",path:`/2020-05-31/function/${$}`,headers:{"If-Match":_}})}async createIndexRewriteFunction($){return this.createFunction({name:$,code:`function handler(event) {
|
|
151
|
-
|
|
151
|
+
const request = event.request;
|
|
152
152
|
var uri = request.uri;
|
|
153
153
|
|
|
154
154
|
// Check if the request is for a directory (ends with /)
|
|
@@ -287,7 +287,7 @@ ${Object.entries($).filter(([W])=>!W.startsWith("@_")).map(([W,U])=>Q(W,U," ","
|
|
|
287
287
|
</Changes>
|
|
288
288
|
</ChangeBatch>
|
|
289
289
|
</ChangeResourceRecordSetsRequest>`;let Y=await this.client.request({service:"route53",region:this.region,method:"POST",path:`/2013-04-01/hostedzone/${J}/rrset`,headers:{"content-type":"application/xml"},body:_});return this.parseChangeResourceRecordSetsResponse(Y)}escapeXml($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}parseCreateHostedZoneResponse($){let J=$.CreateHostedZoneResponse||$;return{HostedZone:this.parseHostedZone(J.HostedZone),ChangeInfo:{Id:J.ChangeInfo?.Id||"",Status:J.ChangeInfo?.Status||"",SubmittedAt:J.ChangeInfo?.SubmittedAt||""},DelegationSet:this.parseDelegationSet(J.DelegationSet),Location:J.Location||""}}parseListHostedZonesResponse($){let J=$.ListHostedZonesResponse||$.ListHostedZonesByNameResponse||$,_=J.HostedZones?.HostedZone||J.HostedZones||[];if(!Array.isArray(_))_=_?[_]:[];return{HostedZones:_.map((Y)=>this.parseHostedZone(Y)),IsTruncated:J.IsTruncated==="true"||J.IsTruncated===!0,MaxItems:J.MaxItems||"100",Marker:J.Marker,NextMarker:J.NextMarker}}parseGetHostedZoneResponse($){let J=$.GetHostedZoneResponse||$;return{HostedZone:this.parseHostedZone(J.HostedZone),DelegationSet:this.parseDelegationSet(J.DelegationSet),VPCs:J.VPCs?.VPC?Array.isArray(J.VPCs.VPC)?J.VPCs.VPC:[J.VPCs.VPC]:void 0}}parseListResourceRecordSetsResponse($){let J=$.ListResourceRecordSetsResponse||$,_=J.ResourceRecordSets?.ResourceRecordSet||J.ResourceRecordSets||[];if(!Array.isArray(_))_=_?[_]:[];return{ResourceRecordSets:_.map((Y)=>this.parseResourceRecordSet(Y)),IsTruncated:J.IsTruncated==="true"||J.IsTruncated===!0,MaxItems:J.MaxItems||"100",NextRecordName:J.NextRecordName,NextRecordType:J.NextRecordType,NextRecordIdentifier:J.NextRecordIdentifier}}parseChangeResourceRecordSetsResponse($){let J=$.ChangeResourceRecordSetsResponse||$;return{ChangeInfo:{Id:J.ChangeInfo?.Id||"",Status:J.ChangeInfo?.Status||"",SubmittedAt:J.ChangeInfo?.SubmittedAt||"",Comment:J.ChangeInfo?.Comment}}}parseHostedZone($){if(!$)return{Id:"",Name:""};return{Id:$.Id||"",Name:$.Name||"",CallerReference:$.CallerReference,Config:$.Config?{Comment:$.Config.Comment,PrivateZone:$.Config.PrivateZone==="true"||$.Config.PrivateZone===!0}:void 0,ResourceRecordSetCount:$.ResourceRecordSetCount?Number($.ResourceRecordSetCount):void 0}}parseDelegationSet($){if(!$)return{NameServers:[]};let J=$.NameServers?.NameServer||$.NameServers||[];if(!Array.isArray(J))J=J?[J]:[];return{Id:$.Id,CallerReference:$.CallerReference,NameServers:J}}parseResourceRecordSet($){if(!$)return{Name:"",Type:""};let J=$.ResourceRecords?.ResourceRecord||$.ResourceRecords||[];if(!Array.isArray(J))J=J?[J]:[];return{Name:$.Name||"",Type:$.Type||"",TTL:$.TTL?Number($.TTL):void 0,ResourceRecords:J.map((_)=>({Value:_.Value||_})),AliasTarget:$.AliasTarget?{HostedZoneId:$.AliasTarget.HostedZoneId,DNSName:$.AliasTarget.DNSName,EvaluateTargetHealth:$.AliasTarget.EvaluateTargetHealth==="true"||$.AliasTarget.EvaluateTargetHealth===!0}:void 0,SetIdentifier:$.SetIdentifier,Weight:$.Weight?Number($.Weight):void 0,Region:$.Region,GeoLocation:$.GeoLocation,Failover:$.Failover,HealthCheckId:$.HealthCheckId}}async findHostedZoneByName($){let J=$.endsWith(".")?$:`${$}.`;return(await this.listHostedZonesByName({DNSName:J})).HostedZones.find((Q)=>Q.Name===J)||null}async createARecord($){let J=Array.isArray($.Value)?$.Value:[$.Value];return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:$.Name,Type:"A",TTL:$.TTL||300,ResourceRecords:J.map((_)=>({Value:_}))}}]}})}async createCnameRecord($){return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:$.Name,Type:"CNAME",TTL:$.TTL||300,ResourceRecords:[{Value:$.Value}]}}]}})}async createAliasRecord($){return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:$.Name,Type:$.Type||"A",AliasTarget:{HostedZoneId:$.TargetHostedZoneId,DNSName:$.TargetDNSName,EvaluateTargetHealth:$.EvaluateTargetHealth??!1}}}]}})}async createTxtRecord($){let _=(Array.isArray($.Value)?$.Value:[$.Value]).map((Y)=>{if(!Y.startsWith('"'))return`"${Y}"`;return Y});return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:$.Name,Type:"TXT",TTL:$.TTL||300,ResourceRecords:_.map((Y)=>({Value:Y}))}}]}})}async createMxRecord($){return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:$.Name,Type:"MX",TTL:$.TTL||300,ResourceRecords:$.Values.map((J)=>({Value:`${J.priority} ${J.mailServer}`}))}}]}})}async deleteRecord($){return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"DELETE",ResourceRecordSet:$.RecordSet}]}})}async waitForChange($,J=60,_=5000){let Y=$.replace("/change/","");for(let Q=0;Q<J;Q++){let W=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/change/${Y}`});if((W.GetChangeResponse?.ChangeInfo?.Status||W.ChangeInfo?.Status)==="INSYNC")return!0;await new Promise((Z)=>setTimeout(Z,_))}return!1}async findOrCreateHostedZone($){let J=$.domainName.endsWith(".")?$.domainName:`${$.domainName}.`,_=await this.findHostedZoneByName(J);if(_){let Q=await this.getHostedZone({Id:_.Id});return{hostedZone:_,nameServers:Q.DelegationSet.NameServers,isNew:!1}}let Y=await this.createHostedZone({Name:J,HostedZoneConfig:{Comment:$.comment||`Hosted zone for ${$.domainName}`,PrivateZone:$.privateZone},VPC:$.vpc});return{hostedZone:Y.HostedZone,nameServers:Y.DelegationSet.NameServers,isNew:!0}}static getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length<=2)return $;return J.slice(-2).join(".")}async findHostedZoneForDomain($){let _=$.replace(/\.$/,"").split(".");for(let Y=0;Y<_.length-1;Y++){let Q=_.slice(Y).join("."),W=await this.findHostedZoneByName(Q);if(W)return W}return null}async ensureHostedZone($){let J=await this.findOrCreateHostedZone({domainName:$.domainName,comment:$.comment});return{hostedZoneId:J.hostedZone.Id.replace("/hostedzone/",""),nameServers:J.nameServers,isNew:J.isNew,action:J.isNew?"created":"found"}}async setupDomainDns($){let{domain:J,createIfNotExists:_=!0}=$,Y=await this.findHostedZoneByName(J);if(Y){let W=await this.getHostedZone({Id:Y.Id});return{success:!0,hostedZoneId:Y.Id.replace("/hostedzone/",""),nameServers:W.DelegationSet.NameServers,isNew:!1,message:`Found existing hosted zone for ${J}`}}if(!_)return{success:!1,hostedZoneId:null,nameServers:[],isNew:!1,message:`No hosted zone found for ${J} and createIfNotExists is false`};let Q=await this.createHostedZone({Name:J,HostedZoneConfig:{Comment:`Created automatically by ts-cloud for ${J}`}});return{success:!0,hostedZoneId:Q.HostedZone.Id.replace("/hostedzone/",""),nameServers:Q.DelegationSet.NameServers,isNew:!0,message:`Created new hosted zone for ${J}. Please update your domain registrar with these name servers: ${Q.DelegationSet.NameServers.join(", ")}`}}static CloudFrontHostedZoneId="Z2FDTNDATAQYW2";static S3WebsiteHostedZoneIds={"us-east-1":"Z3AQBSTGFYJSTF","us-east-2":"Z2O1EMRO9K5GLX","us-west-1":"Z2F56UZL2M1ACD","us-west-2":"Z3BJ6K6RIION7M","ap-east-1":"ZNB98KWMFR0R6","ap-south-1":"Z11RGJOFQNVJUP","ap-northeast-1":"Z2M4EHUR26P7ZW","ap-northeast-2":"Z3W03O7B5YMIYP","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"Z3O0J2DXBE1FTB","ap-southeast-2":"Z1WCIGYICN2BYD","ca-central-1":"Z1QDHH18159H29","eu-central-1":"Z21DNDUVLTQW6Q","eu-west-1":"Z1BKCTXD74EZPE","eu-west-2":"Z3GKZC51ZF0DB4","eu-west-3":"Z3R1K369G5AVDG","eu-north-1":"Z3BAZG2TWCNX0D","sa-east-1":"Z7KQH4QJS55SO"};static ALBHostedZoneIds={"us-east-1":"Z35SXDOTRQ7X7K","us-east-2":"Z3AADJGX6KTTL2","us-west-1":"Z368ELLRRE2KJ0","us-west-2":"Z1H1FL5HABSF5","ap-east-1":"Z3DQVH9N71FHZ0","ap-south-1":"ZP97RAFLXTNZK","ap-northeast-1":"Z14GRHDCWA56QT","ap-northeast-2":"ZWKZPGTI48KDX","ap-northeast-3":"Z5LXEBD8Y73MNV","ap-southeast-1":"Z1LMS91P8CMLE5","ap-southeast-2":"Z1GM3OXH4ZPM65","ca-central-1":"ZQSVJUPU6J1EY","eu-central-1":"Z215JYRZR1TBD5","eu-west-1":"Z32O12XQLNTSW2","eu-west-2":"ZHURV8PSTC4K8","eu-west-3":"Z3Q77PNBQS71R4","eu-north-1":"Z23TAZ6LKFMNIO","sa-east-1":"Z2P70J7HTTTPLU"};static APIGatewayHostedZoneIds={"us-east-1":"Z1UJRXOUMOOFQ8","us-east-2":"ZOJJZC49E0EPZ","us-west-1":"Z2MUQ32089INYE","us-west-2":"Z2OJLYMUO9EFXC","ap-east-1":"Z3FD1VL90ND7K5","ap-south-1":"Z3VO1THU9YC4UR","ap-northeast-1":"Z1YSHQZHG15GKL","ap-northeast-2":"Z20JF4UZKIW1U8","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"ZL327KTPIQFUL","ap-southeast-2":"Z2RPCDW04V8134","ca-central-1":"Z19DQILCV0OWEC","eu-central-1":"Z1U9ULNL0V5AJ3","eu-west-1":"ZLY8HYME6SFDD","eu-west-2":"ZJ5UAJN8Y3Z2Q","eu-west-3":"Z3KY65QIEKYHQQ","eu-north-1":"Z3UWIKFBOOGXPP","sa-east-1":"ZCMLWB8V5SYIT"}}});class _1{name="porkbun";apiKey;secretKey;constructor($,J){this.apiKey=$,this.secretKey=J}async request($,J={}){let _=await fetch(`https://api.porkbun.com/api/json/v3${$}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...J})});if(!_.ok)throw Error(`Porkbun API error: ${_.status} ${_.statusText}`);let Y=await _.json();if(Y.status==="ERROR")throw Error(`Porkbun API error: ${Y.message||"Unknown error"}`);return Y}getSubdomain($,J){let _=$.replace(/\.$/,""),Y=J.replace(/\.$/,"");if(_===Y)return"";if(_.endsWith(`.${Y}`))return _.slice(0,-(Y.length+1));return _}getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return $}async createRecord($,J){try{let _=this.getRootDomain($),Y=this.getSubdomain(J.name,_),Q={type:J.type,content:J.content,ttl:String(J.ttl||600)};if(Y)Q.name=Y;if((J.type==="MX"||J.type==="SRV")&&J.priority!==void 0)Q.prio=String(J.priority);if(J.type==="SRV"&&J.weight!==void 0&&J.port!==void 0)Q.content=`${J.weight} ${J.port} ${J.content}`;return{success:!0,id:(await this.request(`/dns/create/${_}`,Q)).id?.toString(),message:"Record created successfully"}}catch(_){return{success:!1,message:_ instanceof Error?_.message:"Unknown error"}}}async upsertRecord($,J){try{let _=this.getRootDomain($),Y=this.getSubdomain(J.name,_),Q=await this.listRecords($,J.type);if(Q.success){let W=Q.records.find((U)=>{return this.getSubdomain(U.name,_)===Y&&U.type===J.type});if(W?.id){let U={type:J.type,content:J.content,ttl:String(J.ttl||600)};if(Y)U.name=Y;if((J.type==="MX"||J.type==="SRV")&&J.priority!==void 0)U.prio=String(J.priority);if(J.type==="SRV"&&J.weight!==void 0&&J.port!==void 0)U.content=`${J.weight} ${J.port} ${J.content}`;return await this.request(`/dns/edit/${_}/${W.id}`,U),{success:!0,id:W.id,message:"Record updated successfully"}}}return this.createRecord($,J)}catch(_){return this.createRecord($,J)}}async deleteRecord($,J){try{let _=this.getRootDomain($),Y=this.getSubdomain(J.name,_),Q=await this.listRecords($,J.type);if(!Q.success)return{success:!1,message:"Failed to list records"};let W=Q.records.find((U)=>{return this.getSubdomain(U.name,_)===Y&&U.type===J.type&&U.content===J.content});if(!W?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${_}/${W.id}`),{success:!0,message:"Record deleted successfully"}}catch(_){return{success:!1,message:_ instanceof Error?_.message:"Unknown error"}}}async listRecords($,J){try{let _=this.getRootDomain($),Y=`/dns/retrieve/${_}`;if(J)Y=`/dns/retrieveByNameType/${_}/${J}`;return{success:!0,records:((await this.request(Y)).records||[]).map((U)=>({id:U.id,name:U.name||_,type:U.type,content:U.content,ttl:Number.parseInt(U.ttl,10),priority:U.prio?Number.parseInt(U.prio,10):void 0}))}}catch(_){return{success:!1,records:[],message:_ instanceof Error?_.message:"Unknown error"}}}async canManageDomain($){try{let J=this.getRootDomain($);return await this.request(`/dns/retrieve/${J}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((J)=>J.domain)}catch{return[]}}async getNameServers($){try{let J=this.getRootDomain($);return(await this.request(`/dns/getNS/${J}`)).ns||[]}catch{return[]}}async updateNameServers($,J){try{let _=this.getRootDomain($);return await this.request(`/dns/updateNS/${_}`,{ns:J}),!0}catch{return!1}}}class Y1{name="godaddy";apiKey;apiSecret;baseUrl;constructor($,J,_="production"){this.apiKey=$,this.apiSecret=J,this.baseUrl=_==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}async request($,J,_){let Y=`${this.baseUrl}${J}`,Q={Authorization:`sso-key ${this.apiKey}:${this.apiSecret}`,"Content-Type":"application/json",Accept:"application/json"},W={method:$,headers:Q};if(_)W.body=JSON.stringify(_);let U=await fetch(Y,W);if(U.status===204)return{};if(U.ok){let O=await U.text();if(O)return JSON.parse(O);return{}}let Z=`GoDaddy API error: ${U.status} ${U.statusText}`;try{let O=await U.json();if(O.message)Z=`GoDaddy API error: ${O.message}`;if(O.fields)Z+=` - Fields: ${JSON.stringify(O.fields)}`}catch{}throw Error(Z)}getSubdomain($,J){let _=$.replace(/\.$/,""),Y=J.replace(/\.$/,"");if(_===Y)return"@";if(_.endsWith(`.${Y}`))return _.slice(0,-(Y.length+1));return _}getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return $}toGoDaddyRecord($,J){let _=this.getRootDomain(J),Y=this.getSubdomain($.name,_),Q={type:$.type,name:Y,data:$.content,ttl:$.ttl||600};if($.type==="MX"&&$.priority!==void 0)Q.priority=$.priority;return Q}fromGoDaddyRecord($,J){let _=this.getRootDomain(J),Y=$.name;if(Y==="@")Y=_;else if(!Y.endsWith(_))Y=`${Y}.${_}`;return{name:Y,type:$.type,content:$.data,ttl:$.ttl,priority:$.priority}}async createRecord($,J){try{let _=this.getRootDomain($),Y=this.toGoDaddyRecord(J,$);return await this.request("PATCH",`/v1/domains/${_}/records`,[Y]),{success:!0,message:"Record created successfully"}}catch(_){return{success:!1,message:_ instanceof Error?_.message:"Unknown error"}}}async upsertRecord($,J){try{let _=this.getRootDomain($),Y=this.toGoDaddyRecord(J,$);return await this.request("PUT",`/v1/domains/${_}/records/${J.type}/${Y.name}`,[Y]),{success:!0,message:"Record upserted successfully"}}catch(_){return this.createRecord($,J)}}async deleteRecord($,J){try{let _=this.getRootDomain($),Y=this.getSubdomain(J.name,_),Q=await this.request("GET",`/v1/domains/${_}/records/${J.type}/${Y}`),W=Q.filter((U)=>U.data!==J.content);if(W.length===Q.length)return{success:!1,message:"Record not found"};if(W.length===0)try{await this.request("DELETE",`/v1/domains/${_}/records/${J.type}/${Y}`)}catch{}else await this.request("PUT",`/v1/domains/${_}/records/${J.type}/${Y}`,W);return{success:!0,message:"Record deleted successfully"}}catch(_){return{success:!1,message:_ instanceof Error?_.message:"Unknown error"}}}async listRecords($,J){try{let _=this.getRootDomain($),Y=`/v1/domains/${_}/records`;if(J)Y=`/v1/domains/${_}/records/${J}`;return{success:!0,records:(await this.request("GET",Y)).map((W)=>this.fromGoDaddyRecord(W,$))}}catch(_){return{success:!1,records:[],message:_ instanceof Error?_.message:"Unknown error"}}}async canManageDomain($){try{let J=this.getRootDomain($);return await this.request("GET",`/v1/domains/${J}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((J)=>J.domain)}catch{return[]}}async getDomainDetails($){try{let J=this.getRootDomain($),_=await this.request("GET",`/v1/domains/${J}`);return{domain:_.domain,status:_.status,nameServers:_.nameServers,expires:_.expires}}catch{return null}}async updateNameServers($,J){try{let _=this.getRootDomain($);return await this.request("PUT",`/v1/domains/${_}/records/NS`,J.map((Y)=>({type:"NS",name:"@",data:Y,ttl:3600}))),!0}catch{return!1}}async checkDomainAvailability($){try{let J=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent($)}`);return{available:J.available,price:J.price,currency:J.currency}}catch{return{available:!1}}}}class o1{name="cloudflare";apiToken;zoneCache=new Map;constructor($){this.apiToken=$}async request($,J,_){let Y=`https://api.cloudflare.com/client/v4${J}`,Q={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},W={method:$,headers:Q};if(_)W.body=JSON.stringify(_);let Z=await(await fetch(Y,W)).json();if(!Z.success){let O=Z.errors.map((z)=>z.message).join(", ");throw Error(`Cloudflare API error: ${O}`)}return Z}getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return $}async getZoneId($){let J=this.getRootDomain($),_=this.zoneCache.get(J);if(_)return _;let Y=await this.request("GET",`/zones?name=${encodeURIComponent(J)}`);if(!Y.result||Y.result.length===0)throw Error(`Zone not found for domain: ${J}`);let Q=Y.result[0].id;return this.zoneCache.set(J,Q),Q}getFullRecordName($,J){let _=this.getRootDomain(J),Y=$.replace(/\.$/,"");if(!Y||Y===_||Y==="@")return _;if(Y.endsWith(`.${_}`))return Y;return`${Y}.${_}`}toCloudflareRecord($,J){let _={type:$.type,name:this.getFullRecordName($.name,J),content:$.content||$.value||"",ttl:$.ttl||1};if($.type==="MX"&&$.priority!==void 0)_.priority=$.priority;if($.type==="SRV"){if($.priority!==void 0)_.priority=$.priority}return _}fromCloudflareRecord($){return{id:$.id,name:$.name,type:$.type,content:$.content,ttl:$.ttl,priority:$.priority}}async createRecord($,J){try{let _=await this.getZoneId($),Y=this.toCloudflareRecord(J,$);return{success:!0,id:(await this.request("POST",`/zones/${_}/dns_records`,Y)).result.id,message:"Record created successfully"}}catch(_){return{success:!1,message:_ instanceof Error?_.message:"Unknown error"}}}async upsertRecord($,J){try{let _=await this.getZoneId($),Y=this.getFullRecordName(J.name,$),Q=await this.request("GET",`/zones/${_}/dns_records?type=${J.type}&name=${encodeURIComponent(Y)}`),W=this.toCloudflareRecord(J,$);if(Q.result&&Q.result.length>0){let Z=Q.result[0].id;return{success:!0,id:(await this.request("PUT",`/zones/${_}/dns_records/${Z}`,W)).result.id,message:"Record updated successfully"}}return{success:!0,id:(await this.request("POST",`/zones/${_}/dns_records`,W)).result.id,message:"Record created successfully"}}catch(_){return this.createRecord($,J)}}async deleteRecord($,J){try{let _=await this.getZoneId($),Y=this.getFullRecordName(J.name,$),Q=await this.request("GET",`/zones/${_}/dns_records?type=${J.type}&name=${encodeURIComponent(Y)}`);if(!Q.result||Q.result.length===0)return{success:!1,message:"Record not found"};let W=Q.result.find((U)=>U.content===J.content);if(!W)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${_}/dns_records/${W.id}`),{success:!0,message:"Record deleted successfully"}}catch(_){return{success:!1,message:_ instanceof Error?_.message:"Unknown error"}}}async listRecords($,J){try{let Y=`/zones/${await this.getZoneId($)}/dns_records?per_page=100`;if(J)Y+=`&type=${J}`;let Q=[],W=1,U=!0;while(U){let Z=await this.request("GET",`${Y}&page=${W}`);if(Q.push(...Z.result||[]),Z.result_info)U=W<Z.result_info.total_pages,W++;else U=!1}return{success:!0,records:Q.map((Z)=>this.fromCloudflareRecord(Z))}}catch(_){return{success:!1,records:[],message:_ instanceof Error?_.message:"Unknown error"}}}async canManageDomain($){try{return await this.getZoneId($),!0}catch{return!1}}async listDomains(){try{let $=[],J=1,_=!0;while(_){let Y=await this.request("GET",`/zones?per_page=50&page=${J}`);if($.push(...Y.result||[]),Y.result_info)_=J<Y.result_info.total_pages,J++;else _=!1}return $.map((Y)=>Y.name)}catch{return[]}}async getZoneDetails($){try{let J=await this.getZoneId($),_=await this.request("GET",`/zones/${J}`);return{id:_.result.id,name:_.result.name,status:_.result.status,nameServers:_.result.name_servers,paused:_.result.paused}}catch{return null}}async purgeCache($,J){try{let _=await this.getZoneId($),Y={};if(J?.purgeEverything)Y.purge_everything=!0;else{if(J?.files)Y.files=J.files;if(J?.tags)Y.tags=J.tags;if(J?.hosts)Y.hosts=J.hosts}if(Object.keys(Y).length===0)Y.purge_everything=!0;return await this.request("POST",`/zones/${_}/purge_cache`,Y),!0}catch{return!1}}async getRecordProxyStatus($,J){try{let _=await this.getZoneId($),Y=this.getFullRecordName(J.name,$),Q=await this.request("GET",`/zones/${_}/dns_records?type=${J.type}&name=${encodeURIComponent(Y)}`);if(Q.result&&Q.result.length>0)return Q.result.find((U)=>U.content===J.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus($,J,_){try{let Y=await this.getZoneId($),Q=this.getFullRecordName(J.name,$),W=await this.request("GET",`/zones/${Y}/dns_records?type=${J.type}&name=${encodeURIComponent(Q)}`);if(!W.result||W.result.length===0)return!1;let U=W.result.find((Z)=>Z.content===J.content);if(!U)return!1;return await this.request("PATCH",`/zones/${Y}/dns_records/${U.id}`,{proxied:_}),!0}catch{return!1}}}class Q1{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor($="us-east-1",J){this.client=new $0($),this.providedHostedZoneId=J}getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return $}async getHostedZoneId($){if(this.providedHostedZoneId)return this.providedHostedZoneId;let J=this.getRootDomain($),_=this.hostedZoneCache.get(J);if(_)return _;let Y=await this.client.findHostedZoneForDomain($);if(Y){let Q=Y.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(J,Q),Q}return null}normalizeName($){return $.endsWith(".")?$:`${$}.`}async createRecord($,J){try{let _=await this.getHostedZoneId($);if(!_)return{success:!1,message:`No hosted zone found for domain: ${$}`};let Y=this.normalizeName(J.name),Q=J.content;if(J.type==="TXT"&&!Q.startsWith('"'))Q=`"${Q}"`;if(J.type==="MX"&&J.priority!==void 0)Q=`${J.priority} ${Q}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:_,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:"CREATE",ResourceRecordSet:{Name:Y,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:Q}]}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(_){return{success:!1,message:_ instanceof Error?_.message:"Unknown error"}}}async upsertRecord($,J){try{let _=await this.getHostedZoneId($);if(!_)return{success:!1,message:`No hosted zone found for domain: ${$}`};let Y=this.normalizeName(J.name),Q=J.content;if(J.type==="TXT"&&!Q.startsWith('"'))Q=`"${Q}"`;if(J.type==="MX"&&J.priority!==void 0)Q=`${J.priority} ${Q}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:_,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:Y,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:Q}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(_){return{success:!1,message:_ instanceof Error?_.message:"Unknown error"}}}async deleteRecord($,J){try{let _=await this.getHostedZoneId($);if(!_)return{success:!1,message:`No hosted zone found for domain: ${$}`};let Y=this.normalizeName(J.name),Q=J.content;if(J.type==="TXT"&&!Q.startsWith('"'))Q=`"${Q}"`;if(J.type==="MX"&&J.priority!==void 0)Q=`${J.priority} ${Q}`;return await this.client.changeResourceRecordSets({HostedZoneId:_,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:Y,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:Q}]}}]}}),{success:!0,message:"Record deleted successfully"}}catch(_){return{success:!1,message:_ instanceof Error?_.message:"Unknown error"}}}async listRecords($,J){try{let _=await this.getHostedZoneId($);if(!_)return{success:!1,records:[],message:`No hosted zone found for domain: ${$}`};let Y=await this.client.listResourceRecordSets({HostedZoneId:_,StartRecordType:J}),Q=[];for(let W of Y.ResourceRecordSets){if(J&&W.Type!==J)continue;if(W.AliasTarget)continue;for(let U of W.ResourceRecords||[]){let Z=U.Value,O;if(W.Type==="MX"){let z=Z.split(" ");if(z.length>=2)O=Number.parseInt(z[0],10),Z=z.slice(1).join(" ")}if(W.Type==="TXT"&&Z.startsWith('"')&&Z.endsWith('"'))Z=Z.slice(1,-1);Q.push({name:W.Name.replace(/\.$/,""),type:W.Type,content:Z,ttl:W.TTL,priority:O})}}return{success:!0,records:Q}}catch(_){return{success:!1,records:[],message:_ instanceof Error?_.message:"Unknown error"}}}async canManageDomain($){return await this.getHostedZoneId($)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((J)=>J.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord($){try{let J=await this.getHostedZoneId($.domain);if(!J)return{success:!1,message:`No hosted zone found for domain: ${$.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:J,Name:this.normalizeName($.name),TargetHostedZoneId:$.targetHostedZoneId,TargetDNSName:$.targetDnsName,EvaluateTargetHealth:$.evaluateTargetHealth,Type:$.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(J){return{success:!1,message:J instanceof Error?J.message:"Unknown error"}}}async createCloudFrontAlias($){return this.createAliasRecord({domain:$.domain,name:$.name,targetHostedZoneId:$0.CloudFrontHostedZoneId,targetDnsName:$.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias($){let J=$0.ALBHostedZoneIds[$.region];if(!J)return{success:!1,message:`Unknown region for ALB: ${$.region}`};return this.createAliasRecord({domain:$.domain,name:$.name,targetHostedZoneId:J,targetDnsName:$.albDnsName,evaluateTargetHealth:!0})}}var I2=t(()=>{V$()});class W${acm;dnsProvider;constructor($,J="us-east-1"){if(this.acm=new a0(J),"provider"in $)this.dnsProvider=j0($);else this.dnsProvider=$}getProvider(){return this.dnsProvider}async requestAndValidate($){let{domainName:J,subjectAlternativeNames:_=[],waitForValidation:Y=!1,maxWaitMinutes:Q=30}=$,{CertificateArn:W}=await this.acm.requestCertificate({DomainName:J,SubjectAlternativeNames:_.length>0?[J,..._]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(W);let U=await this.acm.getDnsValidationRecords(W);for(let O of U){let z=await this.dnsProvider.upsertRecord(J,{name:O.recordName,type:O.recordType,content:O.recordValue,ttl:300});if(!z.success)console.warn(`Failed to create validation record for ${O.domainName}: ${z.message}`)}let Z="pending";if(Y)Z=(await this.acm.waitForCertificateValidation(W,Q*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:W,validationRecords:U.map((O)=>({domainName:O.domainName,recordName:O.recordName,recordType:O.recordType,recordValue:O.recordValue})),isNew:!0,status:Z}}async createValidationRecords($){let{certificateArn:J,domain:_}=$,Y=[],Q=await this.acm.getDnsValidationRecords(J);for(let W of Q){let U=await this.dnsProvider.upsertRecord(_,{name:W.recordName,type:W.recordType,content:W.recordValue,ttl:300});if(!U.success)Y.push(`Failed to create record for ${W.domainName}: ${U.message}`)}return{success:Y.length===0,records:Q.map((W)=>({domainName:W.domainName,recordName:W.recordName,recordType:W.recordType,recordValue:W.recordValue})),errors:Y}}async deleteValidationRecords($){let{certificateArn:J,domain:_}=$,Y=[],Q=await this.acm.getDnsValidationRecords(J);for(let W of Q){let U=await this.dnsProvider.deleteRecord(_,{name:W.recordName,type:W.recordType,content:W.recordValue});if(!U.success)Y.push(`Failed to delete record for ${W.domainName}: ${U.message}`)}return{success:Y.length===0,errors:Y}}async findOrCreateCertificate($){let{domainName:J,subjectAlternativeNames:_=[],waitForValidation:Y=!0,maxWaitMinutes:Q}=$,W=await this.acm.findCertificateByDomain(J);if(W&&W.Status==="ISSUED"){let U=W.SubjectAlternativeNames||[W.DomainName],Z=U.some((z)=>z===`*.${J}`);if(_.every((z)=>U.includes(z)||Z))return{certificateArn:W.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:J,subjectAlternativeNames:_,waitForValidation:Y,maxWaitMinutes:Q})}async requestCertificateWithCommonSans($){let{domainName:J,includeWww:_=!0,includeWildcard:Y=!1,additionalSans:Q=[],waitForValidation:W=!1}=$,U=[];if(_)U.push(`www.${J}`);if(Y)U.push(`*.${J}`);return U.push(...Q),this.requestAndValidate({domainName:J,subjectAlternativeNames:U,waitForValidation:W})}async waitForValidationOptions($,J=30){for(let _=0;_<J;_++){let Y=await this.acm.describeCertificate({CertificateArn:$});if(Y.DomainValidationOptions&&Y.DomainValidationOptions.length>0&&Y.DomainValidationOptions[0].ResourceRecord)return;await new Promise((Q)=>setTimeout(Q,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus($){let J=await this.acm.describeCertificate({CertificateArn:$});return{status:J.Status,domainValidations:(J.DomainValidationOptions||[]).map((_)=>({domain:_.DomainName,status:_.ValidationStatus||"UNKNOWN"}))}}}function rJ($,J,_){return new W$({provider:"porkbun",apiKey:$,secretKey:J},_)}function nJ($,J,_,Y){return new W$({provider:"godaddy",apiKey:$,apiSecret:J,environment:Y},_)}function tJ($,J,_){return new W$({provider:"route53",region:$,hostedZoneId:J},_||$)}var h2=t(()=>{W1();M$()});function j0($){switch($.provider){case"route53":return new Q1($.region,$.hostedZoneId);case"porkbun":return new _1($.apiKey,$.secretKey);case"godaddy":return new Y1($.apiKey,$.apiSecret,$.environment);case"cloudflare":return new o1($.apiToken);default:throw Error(`Unknown DNS provider: ${$.provider}`)}}async function yQ($,J){for(let _ of J){let Y=j0(_);if(await Y.canManageDomain($))return Y}return null}class v2{providers=new Map;configs=[];addConfig($){return this.configs.push($),this}addRoute53($,J){return this.configs.push({provider:"route53",region:$,hostedZoneId:J}),this}addPorkbun($,J){return this.configs.push({provider:"porkbun",apiKey:$,secretKey:J}),this}addGoDaddy($,J,_){return this.configs.push({provider:"godaddy",apiKey:$,apiSecret:J,environment:_}),this}addCloudflare($){return this.configs.push({provider:"cloudflare",apiToken:$}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let $=process.env.PORKBUN_API_KEY,J=process.env.PORKBUN_SECRET_KEY;if($&&J)this.addPorkbun($,J);let _=process.env.GODADDY_API_KEY,Y=process.env.GODADDY_API_SECRET;if(_&&Y){let W=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(_,Y,W)}let Q=process.env.CLOUDFLARE_API_TOKEN;if(Q)this.addCloudflare(Q);return this}getProvider($){let J=this.providers.get($);if(J)return J;let _=this.configs.find((Q)=>Q.provider===$);if(!_)return null;let Y=j0(_);return this.providers.set($,Y),Y}async getProviderForDomain($){for(let J of this.configs){let _=j0(J);if(await _.canManageDomain($))return _}return null}getAllProviders(){return this.configs.map(($)=>j0($))}}var fQ;var M$=t(()=>{I2();h2();I2();fQ=new v2});class a0{client;region;constructor($="us-east-1"){this.client=new I,this.region=$}async requestCertificate($){let J={DomainName:$.DomainName,ValidationMethod:$.ValidationMethod||"DNS"};if($.SubjectAlternativeNames)J.SubjectAlternativeNames=$.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(J)})).CertificateArn||""}}async describeCertificate($){let _=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:$.CertificateArn})})).Certificate||{};return{CertificateArn:_.CertificateArn||"",DomainName:_.DomainName||"",SubjectAlternativeNames:_.SubjectAlternativeNames,Status:_.Status||"PENDING_VALIDATION",Type:_.Type,DomainValidationOptions:_.DomainValidationOptions?.map((Y)=>({DomainName:Y.DomainName,ValidationDomain:Y.ValidationDomain,ValidationStatus:Y.ValidationStatus,ResourceRecord:Y.ResourceRecord?{Name:Y.ResourceRecord.Name,Type:Y.ResourceRecord.Type,Value:Y.ResourceRecord.Value}:void 0,ValidationMethod:Y.ValidationMethod})),CreatedAt:_.CreatedAt,IssuedAt:_.IssuedAt,NotBefore:_.NotBefore,NotAfter:_.NotAfter}}async listCertificates($){let J={};if($?.CertificateStatuses)J.CertificateStatuses=$.CertificateStatuses;if($?.MaxItems)J.MaxItems=$.MaxItems;if($?.NextToken)J.NextToken=$.NextToken;let _=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(J)});return{CertificateSummaryList:(_.CertificateSummaryList||[]).map((Y)=>({CertificateArn:Y.CertificateArn,DomainName:Y.DomainName})),NextToken:_.NextToken}}async deleteCertificate($){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:$.CertificateArn})})}async listTagsForCertificate($){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:$.CertificateArn})})).Tags||[]}}async addTagsToCertificate($){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:$.CertificateArn,Tags:$.Tags})})}async resendValidationEmail($){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:$.CertificateArn,Domain:$.Domain,ValidationDomain:$.ValidationDomain})})}async findCertificateByDomain($){let _=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((Y)=>Y.DomainName===$||Y.DomainName===`*.${$.split(".").slice(1).join(".")}`);if(!_)return null;return this.describeCertificate({CertificateArn:_.CertificateArn})}async waitForCertificateValidation($,J=60,_=30000){for(let Y=0;Y<J;Y++){let Q=await this.describeCertificate({CertificateArn:$});if(Q.Status==="ISSUED")return Q;if(Q.Status==="FAILED"||Q.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((W)=>setTimeout(W,_))}return null}async getDnsValidationRecords($){let J=await this.describeCertificate({CertificateArn:$});if(!J.DomainValidationOptions)return[];return J.DomainValidationOptions.filter((_)=>_.ResourceRecord&&_.ValidationMethod==="DNS").map((_)=>({domainName:_.DomainName,recordName:_.ResourceRecord.Name,recordType:_.ResourceRecord.Type,recordValue:_.ResourceRecord.Value}))}async requestCertificateWithSans($){let J=new Set;if(J.add($.DomainName),$.IncludeWww!==!1)J.add(`www.${$.DomainName}`);if($.IncludeWildcard)J.add(`*.${$.DomainName}`);if($.AdditionalSans)for(let _ of $.AdditionalSans)J.add(_);return this.requestCertificate({DomainName:$.DomainName,SubjectAlternativeNames:Array.from(J),ValidationMethod:"DNS"})}async isCertificateValidForDomain($,J){let _=await this.describeCertificate({CertificateArn:$});if(_.Status!=="ISSUED")return!1;if(_.DomainName===J)return!0;if(_.DomainName?.startsWith("*.")){let Y=_.DomainName.slice(2),Q=J.split("."),W=Y.split(".");if(Q.slice(-W.length).join(".")===Y)return!0}if(_.SubjectAlternativeNames)for(let Y of _.SubjectAlternativeNames){if(Y===J)return!0;if(Y.startsWith("*.")){let Q=Y.slice(2),W=J.split("."),U=Q.split(".");if(W.slice(-U.length).join(".")===Q)return!0}}return!1}}class e1{acm;route53;dnsProvider;constructor($="us-east-1",J){if(this.acm=new a0($),this.route53=new $0,J&&J.provider!=="route53")this.dnsProvider=j0(J)}async requestAndValidate($){let{domainName:J,hostedZoneId:_,subjectAlternativeNames:Y=[],waitForValidation:Q=!1,maxWaitMinutes:W=30}=$;if(!this.dnsProvider&&!_)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:U}=await this.acm.requestCertificate({DomainName:J,SubjectAlternativeNames:Y.length>0?[J,...Y]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(U);let Z=await this.acm.getDnsValidationRecords(U);if(this.dnsProvider)for(let O of Z){let z=await this.dnsProvider.upsertRecord(J,{name:O.recordName,type:O.recordType,content:O.recordValue,ttl:300});if(!z.success)console.warn(`Failed to create validation record for ${O.domainName}: ${z.message}`)}else if(_)for(let O of Z)await this.route53.changeResourceRecordSets({HostedZoneId:_,ChangeBatch:{Comment:`ACM DNS validation for ${O.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:O.recordName,Type:O.recordType,TTL:300,ResourceRecords:[{Value:O.recordValue}]}}]}});if(Q){if(!await this.acm.waitForCertificateValidation(U,W*2,30000))throw Error(`Certificate validation timed out after ${W} minutes`)}return{certificateArn:U,validationRecords:Z}}async waitForValidationOptions($,J=30){for(let _=0;_<J;_++){let Y=await this.acm.describeCertificate({CertificateArn:$});if(Y.DomainValidationOptions&&Y.DomainValidationOptions.length>0&&Y.DomainValidationOptions[0].ResourceRecord)return;await new Promise((Q)=>setTimeout(Q,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords($){let{certificateArn:J,hostedZoneId:_,domain:Y}=$;if(!this.dnsProvider&&!_)throw Error("Either hostedZoneId or external DNS provider configuration is required");let Q=await this.acm.getDnsValidationRecords(J),W=[];if(this.dnsProvider){let U=Y||Q[0]?.domainName;for(let Z of Q){let O=await this.dnsProvider.upsertRecord(U,{name:Z.recordName,type:Z.recordType,content:Z.recordValue,ttl:300});W.push({...Z,changeId:O.success?O.id:void 0})}}else if(_)for(let U of Q){let Z=await this.route53.changeResourceRecordSets({HostedZoneId:_,ChangeBatch:{Comment:`ACM DNS validation for ${U.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:U.recordName,Type:U.recordType,TTL:300,ResourceRecords:[{Value:U.recordValue}]}}]}});W.push({...U,changeId:Z.ChangeInfo?.Id})}return W}async deleteValidationRecords($){let{certificateArn:J,hostedZoneId:_,domain:Y}=$,Q=await this.acm.getDnsValidationRecords(J);if(this.dnsProvider){let W=Y||Q[0]?.domainName;for(let U of Q)try{await this.dnsProvider.deleteRecord(W,{name:U.recordName,type:U.recordType,content:U.recordValue})}catch{}}else if(_)for(let W of Q)try{await this.route53.changeResourceRecordSets({HostedZoneId:_,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${W.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:W.recordName,Type:W.recordType,TTL:300,ResourceRecords:[{Value:W.recordValue}]}}]}})}catch{}}async findOrCreateCertificate($){let{domainName:J,hostedZoneId:_,subjectAlternativeNames:Y,waitForValidation:Q=!0}=$;if(!this.dnsProvider&&!_)throw Error("Either hostedZoneId or external DNS provider configuration is required");let W=await this.acm.findCertificateByDomain(J);if(W&&W.Status==="ISSUED")return{certificateArn:W.CertificateArn,isNew:!1};let{certificateArn:U}=await this.requestAndValidate({domainName:J,hostedZoneId:_,subjectAlternativeNames:Y,waitForValidation:Q});return{certificateArn:U,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}var W1=t(()=>{y();V$();M$()});function F5($){let{bucketName:J,domain:_,aliases:Y,certificateArn:Q,defaultRootObject:W="index.html",errorDocument:U="404.html"}=$,Z={},O={};Z.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:J,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:W,ErrorDocument:U}}},O.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},O.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},Z.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${J}`,Description:`OAC for ${J}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},Z.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
290
|
-
|
|
290
|
+
const request = event.request;
|
|
291
291
|
var uri = request.uri;
|
|
292
292
|
|
|
293
293
|
// If URI ends with /, serve index.html
|
|
@@ -319,7 +319,7 @@ ${Object.entries($).filter(([W])=>!W.startsWith("@_")).map(([W,U])=>Q(W,U," ","
|
|
|
319
319
|
│ Verification typically takes 1-2 business days. │
|
|
320
320
|
│ After verification, re-run: bunx bunpress deploy │
|
|
321
321
|
└─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:L,stackName:W,bucket:V,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:L,stackName:W,bucket:V,message:`Stack deployment failed: ${C.message}`}}let S=(await U.describeStacks({stackName:W})).Stacks[0]?.Outputs||[],N=(C)=>S.find((x)=>x.OutputKey===C)?.OutputValue,k=N("DistributionDomain");if(k&&O)console.log(`Creating DNS records via ${O.name}...`),await c2(O,Y,k);else if(k&&!O)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:L,stackName:W,bucket:N("BucketName")||V,distributionId:N("DistributionId"),distributionDomain:k,domain:Y,certificateArn:z,message:"Static site infrastructure deployed successfully with external DNS"}}async function c2($,J,_){if(!$){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(J.split(".").length===2){if(console.log(`Creating ALIAS record for apex domain ${J} -> ${_}`),!(await $.upsertRecord(J,{name:J,type:"ALIAS",content:_,ttl:600})).success){console.log("ALIAS record failed, trying CNAME with @ subdomain...");let O=await $.upsertRecord(J,{name:J,type:"CNAME",content:_,ttl:600});if(!O.success)console.warn(`Warning: Could not create DNS record: ${O.message}`),console.warn("Please manually create a CNAME or ALIAS record:"),console.warn(` ${J} -> ${_}`);else console.log(`Created CNAME record: ${J} -> ${_}`)}else console.log(`Created ALIAS record: ${J} -> ${_}`);let U=`www.${J}`;console.log(`Creating CNAME record for ${U} -> ${_}`);let Z=await $.upsertRecord(J,{name:U,type:"CNAME",content:_,ttl:600});if(!Z.success)console.warn(`Warning: Could not create www DNS record: ${Z.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${U} -> ${_}`);else console.log(`Created CNAME record: ${U} -> ${_}`)}else{console.log(`Creating CNAME record for ${J} -> ${_}`);let W=await $.upsertRecord(J,{name:J,type:"CNAME",content:_,ttl:600});if(!W.success)console.warn(`Warning: Could not create DNS record: ${W.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${J} -> ${_}`);else console.log(`Created CNAME record: ${J} -> ${_}`)}}async function iQ($){let{sourceDir:J,cleanBucket:_=!1,onProgress:Y,...Q}=$;Y?.("infrastructure","Deploying CloudFormation stack...");let W=await W9(Q);if(!W.success)return W;if(_){Y?.("clean","Cleaning old files from S3...");try{await new o(Q.region||"us-east-1").emptyBucket(W.bucket)}catch(z){console.log(`Note: Could not clean bucket: ${z.message}`)}}Y?.("upload","Uploading files to S3...");let{uploadStaticFiles:U}=await Promise.resolve().then(() => (Q9(),m2)),Z=await U({sourceDir:J,bucket:W.bucket,region:Q.region||"us-east-1",cacheControl:Q.cacheControl,onProgress:(z,H,G)=>{Y?.("upload",`${z}/${H}: ${G}`)}});if(Z.errors.length>0)return{...W,success:!1,message:`Upload errors: ${Z.errors.join(", ")}`,filesUploaded:Z.uploaded};if(W.distributionId&&Z.uploaded>0){Y?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:z}=await Promise.resolve().then(() => (Q9(),m2));await z(W.distributionId)}Y?.("complete","Deployment complete!");let O=Z.skipped>0?`Deployed ${Z.uploaded} files (${Z.skipped} unchanged) with external DNS`:`Deployed ${Z.uploaded} files successfully with external DNS`;return{...W,filesUploaded:Z.uploaded,filesSkipped:Z.skipped,message:O}}var l2=t(()=>{s1();g0();a1();W1();M$();h2()});var m2={};c0(m2,{uploadStaticFiles:()=>n2,invalidateCache:()=>t2,generateStaticSiteTemplate:()=>p2,deployStaticSiteFull:()=>w5,deployStaticSite:()=>r2,deleteStaticSite:()=>T5});function p2($){let{bucketName:J,domain:_,certificateArn:Y,hostedZoneId:Q,defaultRootObject:W="index.html",errorDocument:U="404.html"}=$,Z={},O={};Z.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:J,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:W,ErrorDocument:U}}},O.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},O.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},Z.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${J}`,Description:`OAC for ${J}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},Z.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
322
|
-
|
|
322
|
+
const request = event.request;
|
|
323
323
|
var uri = request.uri;
|
|
324
324
|
|
|
325
325
|
// If URI ends with /, serve index.html
|
|
@@ -2079,7 +2079,7 @@ function resolveTemplate(template, data) {
|
|
|
2079
2079
|
return result;
|
|
2080
2080
|
}
|
|
2081
2081
|
`;var m8=`
|
|
2082
|
-
const { DynamoDBClient, PutItemCommand,
|
|
2082
|
+
const { DynamoDBClient, PutItemCommand, DeleteItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
2083
2083
|
const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
|
|
2084
2084
|
|
|
2085
2085
|
const dynamodb = new DynamoDBClient({});
|
|
@@ -2357,11 +2357,11 @@ exports.handler = async (event) => {
|
|
|
2357
2357
|
| filter @message like /ERROR|WARN|Exception/
|
|
2358
2358
|
| sort @timestamp desc
|
|
2359
2359
|
| limit 50`,region:Y,title:"Recent Errors and Warnings"}}),U+=6;return k1.createDashboard({slug:J,environment:_,widgets:W})}static DashboardTemplates={staticWebsite:($)=>({slug:$.slug,environment:$.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${$.slug.toUpperCase()} Static Website Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"CloudFront Requests",region:"us-east-1",metrics:[["AWS/CloudFront","Requests","DistributionId",$.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"Error Rate",region:"us-east-1",metrics:[["AWS/CloudFront","4xxErrorRate","DistributionId",$.cloudFrontDistributionId,"Region","Global",{label:"4XX"}],["AWS/CloudFront","5xxErrorRate","DistributionId",$.cloudFrontDistributionId,"Region","Global",{label:"5XX"}]],period:300,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Bytes Downloaded",region:"us-east-1",metrics:[["AWS/CloudFront","BytesDownloaded","DistributionId",$.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:0,y:7,width:12,height:6,properties:{title:"S3 Bucket Size",region:$.region||"us-east-1",metrics:[["AWS/S3","BucketSizeBytes","BucketName",$.s3BucketName,"StorageType","StandardStorage"]],period:86400,stat:"Average"}},{type:"metric",x:12,y:7,width:12,height:6,properties:{title:"S3 Number of Objects",region:$.region||"us-east-1",metrics:[["AWS/S3","NumberOfObjects","BucketName",$.s3BucketName,"StorageType","AllStorageTypes"]],period:86400,stat:"Average"}}]}),serverlessApi:($)=>({slug:$.slug,environment:$.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${$.slug.toUpperCase()} Serverless API Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"API Requests",region:$.region||"us-east-1",metrics:[["AWS/ApiGateway","Count","ApiName",$.apiGatewayName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"API Latency",region:$.region||"us-east-1",metrics:[["AWS/ApiGateway","Latency","ApiName",$.apiGatewayName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"API Errors",region:$.region||"us-east-1",metrics:[["AWS/ApiGateway","4XXError","ApiName",$.apiGatewayName,{label:"4XX"}],["AWS/ApiGateway","5XXError","ApiName",$.apiGatewayName,{label:"5XX"}]],period:60,stat:"Sum"}},...$.lambdaFunctionNames.map((J,_)=>({type:"metric",x:_%3*8,y:7+Math.floor(_/3)*6,width:8,height:6,properties:{title:`${J} Metrics`,region:$.region||"us-east-1",metrics:[["AWS/Lambda","Invocations","FunctionName",J],["AWS/Lambda","Duration","FunctionName",J],["AWS/Lambda","Errors","FunctionName",J]],period:300,stat:"Sum"}}))]}),containerService:($)=>({slug:$.slug,environment:$.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${$.slug.toUpperCase()} Container Service Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"ECS CPU",region:$.region||"us-east-1",metrics:[["AWS/ECS","CPUUtilization","ClusterName",$.ecsClusterName,"ServiceName",$.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"ECS Memory",region:$.region||"us-east-1",metrics:[["AWS/ECS","MemoryUtilization","ClusterName",$.ecsClusterName,"ServiceName",$.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Running Tasks",region:$.region||"us-east-1",metrics:[["ECS/ContainerInsights","RunningTaskCount","ClusterName",$.ecsClusterName,"ServiceName",$.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:0,y:7,width:8,height:6,properties:{title:"ALB Requests",region:$.region||"us-east-1",metrics:[["AWS/ApplicationELB","RequestCount","LoadBalancer",$.albName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:7,width:8,height:6,properties:{title:"Response Time",region:$.region||"us-east-1",metrics:[["AWS/ApplicationELB","TargetResponseTime","LoadBalancer",$.albName]],period:60,stat:"Average"}},{type:"metric",x:16,y:7,width:8,height:6,properties:{title:"Healthy Hosts",region:$.region||"us-east-1",metrics:[["AWS/ApplicationELB","HealthyHostCount","LoadBalancer",$.albName]],period:60,stat:"Average"}},...$.rdsInstanceId?[{type:"metric",x:0,y:13,width:12,height:6,properties:{title:"RDS CPU",region:$.region||"us-east-1",metrics:[["AWS/RDS","CPUUtilization","DBInstanceIdentifier",$.rdsInstanceId]],period:300,stat:"Average"}},{type:"metric",x:12,y:13,width:12,height:6,properties:{title:"RDS Connections",region:$.region||"us-east-1",metrics:[["AWS/RDS","DatabaseConnections","DBInstanceIdentifier",$.rdsInstanceId]],period:60,stat:"Sum"}}]:[]]})};static Config={createAlarmConfig:($)=>{let{metricName:J,namespace:_,threshold:Y,comparisonOperator:Q="GreaterThanThreshold",evaluationPeriods:W=1,period:U=300,statistic:Z="Average",treatMissingData:O="missing"}=$;return{MetricName:J,Namespace:_,Threshold:Y,ComparisonOperator:Q,EvaluationPeriods:W,Period:U,Statistic:Z,TreatMissingData:O}},namespaces:{ec2:"AWS/EC2",ecs:"AWS/ECS",lambda:"AWS/Lambda",rds:"AWS/RDS",sqs:"AWS/SQS",sns:"AWS/SNS",s3:"AWS/S3",cloudfront:"AWS/CloudFront",alb:"AWS/ApplicationELB",nlb:"AWS/NetworkELB",apiGateway:"AWS/ApiGateway",dynamodb:"AWS/DynamoDB",elasticache:"AWS/ElastiCache"},comparisonOperators:{greaterThan:"GreaterThanThreshold",greaterOrEqual:"GreaterThanOrEqualToThreshold",lessThan:"LessThanThreshold",lessOrEqual:"LessThanOrEqualToThreshold"},metrics:{ec2:{cpu:{metricName:"CPUUtilization",namespace:"AWS/EC2"},networkIn:{metricName:"NetworkIn",namespace:"AWS/EC2"},networkOut:{metricName:"NetworkOut",namespace:"AWS/EC2"},statusCheck:{metricName:"StatusCheckFailed",namespace:"AWS/EC2"}},ecs:{cpu:{metricName:"CPUUtilization",namespace:"AWS/ECS"},memory:{metricName:"MemoryUtilization",namespace:"AWS/ECS"}},lambda:{invocations:{metricName:"Invocations",namespace:"AWS/Lambda"},errors:{metricName:"Errors",namespace:"AWS/Lambda"},duration:{metricName:"Duration",namespace:"AWS/Lambda"},throttles:{metricName:"Throttles",namespace:"AWS/Lambda"},concurrentExecutions:{metricName:"ConcurrentExecutions",namespace:"AWS/Lambda"}},rds:{cpu:{metricName:"CPUUtilization",namespace:"AWS/RDS"},connections:{metricName:"DatabaseConnections",namespace:"AWS/RDS"},freeStorage:{metricName:"FreeStorageSpace",namespace:"AWS/RDS"},readLatency:{metricName:"ReadLatency",namespace:"AWS/RDS"},writeLatency:{metricName:"WriteLatency",namespace:"AWS/RDS"}},alb:{requestCount:{metricName:"RequestCount",namespace:"AWS/ApplicationELB"},responseTime:{metricName:"TargetResponseTime",namespace:"AWS/ApplicationELB"},httpCode4xx:{metricName:"HTTPCode_Target_4XX_Count",namespace:"AWS/ApplicationELB"},httpCode5xx:{metricName:"HTTPCode_Target_5XX_Count",namespace:"AWS/ApplicationELB"},healthyHosts:{metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB"}},sqs:{messagesVisible:{metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS"},messagesDelayed:{metricName:"ApproximateNumberOfMessagesDelayed",namespace:"AWS/SQS"},messageAge:{metricName:"ApproximateAgeOfOldestMessage",namespace:"AWS/SQS"}}},presets:{highCpu:($=80)=>({metricName:"CPUUtilization",threshold:$,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highMemory:($=80)=>({metricName:"MemoryUtilization",threshold:$,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highErrors:($=10)=>({metricName:"Errors",threshold:$,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:1,period:60,statistic:"Sum"}),highLatency:($=5000)=>({metricName:"Duration",threshold:$,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowHealthyHosts:($=1)=>({metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB",threshold:$,comparisonOperator:"LessThanThreshold",evaluationPeriods:2,period:60,statistic:"Minimum"}),queueDepth:($=1000)=>({metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",threshold:$,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowStorage:($=10737418240)=>({metricName:"FreeStorageSpace",namespace:"AWS/RDS",threshold:$,comparisonOperator:"LessThanThreshold",evaluationPeriods:1,period:300,statistic:"Average"})}}}class L0{static createUserPool($){let{slug:J,environment:_,userPoolName:Y,aliasAttributes:Q,autoVerifiedAttributes:W,passwordPolicy:U,mfaConfiguration:Z,emailConfiguration:O,smsConfiguration:z,lambdaTriggers:H,userPoolAddOns:G,accountRecoverySetting:B}=$,K=Y||w({slug:J,environment:_,resourceType:"user-pool"}),E=j(K),V={Type:"AWS::Cognito::UserPool",Properties:{UserPoolName:K,Policies:U?{PasswordPolicy:{MinimumLength:U.minimumLength,RequireLowercase:U.requireLowercase,RequireUppercase:U.requireUppercase,RequireNumbers:U.requireNumbers,RequireSymbols:U.requireSymbols,TemporaryPasswordValidityDays:U.temporaryPasswordValidityDays}}:void 0,MfaConfiguration:Z,Schema:[{Name:"email",AttributeDataType:"String",Required:!0,Mutable:!1}]}};if(Q&&Q.length>0)V.Properties.UsernameAttributes=Q;if(W&&W.length>0)V.Properties.AutoVerifiedAttributes=W;if(O)V.Properties.EmailConfiguration={EmailSendingAccount:O.emailSendingAccount,From:O.from,ReplyToEmailAddress:O.replyToEmailAddress,SourceArn:O.sourceArn,ConfigurationSet:O.configurationSet};if(z)V.Properties.SmsConfiguration={ExternalId:z.externalId,SnsCallerArn:z.snsCallerArn};if(H)V.Properties.LambdaConfig={PreSignUp:H.preSignUp,PostConfirmation:H.postConfirmation,PreAuthentication:H.preAuthentication,PostAuthentication:H.postAuthentication,CustomMessage:H.customMessage,DefineAuthChallenge:H.defineAuthChallenge,CreateAuthChallenge:H.createAuthChallenge,VerifyAuthChallengeResponse:H.verifyAuthChallengeResponse,PreTokenGeneration:H.preTokenGeneration,UserMigration:H.userMigration};if(G)V.Properties.UserPoolAddOns={AdvancedSecurityMode:G.advancedSecurityMode};if(B)V.Properties.AccountRecoverySetting={RecoveryMechanisms:B.recoveryMechanisms};return{userPool:V,logicalId:E}}static createUserPoolClient($,J){let{slug:_,environment:Y,clientName:Q,generateSecret:W=!1,refreshTokenValidity:U,accessTokenValidity:Z,idTokenValidity:O,tokenValidityUnits:z,readAttributes:H,writeAttributes:G,explicitAuthFlows:B,preventUserExistenceErrors:K,enableTokenRevocation:E,callbackURLs:V,logoutURLs:M,allowedOAuthFlows:F,allowedOAuthScopes:T,allowedOAuthFlowsUserPoolClient:L,supportedIdentityProviders:D}=J,R=Q||w({slug:_,environment:Y,resourceType:"user-pool-client"}),S=j(R);return{client:{Type:"AWS::Cognito::UserPoolClient",Properties:{ClientName:R,UserPoolId:A.Ref($),GenerateSecret:W,RefreshTokenValidity:U,AccessTokenValidity:Z,IdTokenValidity:O,TokenValidityUnits:z,ReadAttributes:H,WriteAttributes:G,ExplicitAuthFlows:B,PreventUserExistenceErrors:K,EnableTokenRevocation:E,CallbackURLs:V,LogoutURLs:M,AllowedOAuthFlows:F,AllowedOAuthScopes:T,AllowedOAuthFlowsUserPoolClient:L,SupportedIdentityProviders:D}},logicalId:S}}static createUserPoolDomain($,J){let{slug:_,environment:Y,domain:Q,customDomainConfig:W}=J,U=w({slug:_,environment:Y,resourceType:"user-pool-domain"}),Z=j(U);return{domain:{Type:"AWS::Cognito::UserPoolDomain",Properties:{Domain:Q,UserPoolId:A.Ref($),CustomDomainConfig:W}},logicalId:Z}}static createIdentityPool($){let{slug:J,environment:_,identityPoolName:Y,allowUnauthenticatedIdentities:Q=!1,cognitoIdentityProviders:W,supportedLoginProviders:U,samlProviderARNs:Z,openIdConnectProviderARNs:O}=$,z=Y||w({slug:J,environment:_,resourceType:"identity-pool"}),H=j(z);return{identityPool:{Type:"AWS::Cognito::IdentityPool",Properties:{IdentityPoolName:z,AllowUnauthenticatedIdentities:Q,CognitoIdentityProviders:W,SupportedLoginProviders:U,SamlProviderARNs:Z,OpenIdConnectProviderARNs:O}},logicalId:H}}static createIdentityPoolRoleAttachment($,J){let{slug:_,environment:Y,authenticatedRole:Q,unauthenticatedRole:W,roleMappings:U}=J,Z=w({slug:_,environment:Y,resourceType:"identity-pool-role-attachment"}),O=j(Z),z={authenticated:Q};if(W)z.unauthenticated=W;return{attachment:{Type:"AWS::Cognito::IdentityPoolRoleAttachment",Properties:{IdentityPoolId:A.Ref($),Roles:z,RoleMappings:U}},logicalId:O}}static createAuthenticatedRole($){let{slug:J,environment:_,identityPoolLogicalId:Y}=$,Q=w({slug:J,environment:_,resourceType:"cognito-authenticated-role"}),W=j(Q);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:Q,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":A.Ref(Y)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"authenticated"}}}]},Policies:[{PolicyName:"CognitoAuthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*","cognito-identity:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:Q},{Key:"Environment",Value:_}]}},logicalId:W}}static createUnauthenticatedRole($){let{slug:J,environment:_,identityPoolLogicalId:Y}=$,Q=w({slug:J,environment:_,resourceType:"cognito-unauthenticated-role"}),W=j(Q);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:Q,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":A.Ref(Y)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"unauthenticated"}}}]},Policies:[{PolicyName:"CognitoUnauthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:Q},{Key:"Environment",Value:_}]}},logicalId:W}}static PasswordPolicies={relaxed:()=>({minimumLength:8,requireLowercase:!1,requireUppercase:!1,requireNumbers:!1,requireSymbols:!1,temporaryPasswordValidityDays:7}),standard:()=>({minimumLength:8,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!1,temporaryPasswordValidityDays:3}),strict:()=>({minimumLength:12,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!0,temporaryPasswordValidityDays:1})};static AuthFlows={standard:["ALLOW_USER_SRP_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],admin:["ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],custom:["ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],all:["ALLOW_USER_SRP_AUTH","ALLOW_USER_PASSWORD_AUTH","ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"]};static OAuthScopes={basic:["openid","email","profile"],all:["openid","email","profile","phone","aws.cognito.signin.user.admin"]};static UseCases={webApp:($,J,_)=>{let{userPool:Y,logicalId:Q}=L0.createUserPool({slug:$,environment:J,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:L0.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:W,logicalId:U}=L0.createUserPoolClient(Q,{slug:$,environment:J,explicitAuthFlows:[...L0.AuthFlows.standard],callbackURLs:[_],allowedOAuthFlows:["code"],allowedOAuthScopes:[...L0.OAuthScopes.basic],allowedOAuthFlowsUserPoolClient:!0});return{userPool:Y,poolId:Q,client:W,clientId:U}},mobileApp:($,J)=>{let{userPool:_,logicalId:Y}=L0.createUserPool({slug:$,environment:J,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:L0.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:Q,logicalId:W}=L0.createUserPoolClient(Y,{slug:$,environment:J,explicitAuthFlows:[...L0.AuthFlows.standard]}),{identityPool:U,logicalId:Z}=L0.createIdentityPool({slug:$,environment:J,allowUnauthenticatedIdentities:!1,cognitoIdentityProviders:[{ClientId:A.Ref(W),ProviderName:A.GetAtt(Y,"ProviderName")}]}),{role:O,logicalId:z}=L0.createAuthenticatedRole({slug:$,environment:J,identityPoolLogicalId:Z}),{attachment:H,logicalId:G}=L0.createIdentityPoolRoleAttachment(Z,{slug:$,environment:J,authenticatedRole:A.GetAtt(z,"Arn")});return{userPool:_,poolId:Y,client:Q,clientId:W,identityPool:U,identityPoolId:Z,authRole:O,authRoleId:z,attachment:H,attachmentId:G}}}}import{createHash as y_}from"node:crypto";import{readFileSync as I1,readdirSync as f_,statSync as g_,existsSync as k9,writeFileSync as h1,copyFileSync as u_}from"node:fs";import{join as u$,basename as d_,dirname as p8,extname as r8}from"node:path";class R0{static createApplication($){let{slug:J,environment:_,applicationName:Y,computePlatform:Q}=$,W=Y||w({slug:J,environment:_,resourceType:"deploy-app"}),U=j(W);return{application:{Type:"AWS::CodeDeploy::Application",Properties:{ApplicationName:W,ComputePlatform:Q,Tags:[{Key:"Name",Value:W},{Key:"Environment",Value:_}]}},logicalId:U}}static createDeploymentGroup($,J){let{slug:_,environment:Y,deploymentGroupName:Q,serviceRoleArn:W,autoScalingGroups:U,ec2TagFilters:Z,deploymentConfigName:O,autoRollbackConfiguration:z,alarmConfiguration:H,loadBalancerInfo:G,blueGreenDeploymentConfiguration:B}=J,K=Q||w({slug:_,environment:Y,resourceType:"deploy-group"}),E=j(K);return{deploymentGroup:{Type:"AWS::CodeDeploy::DeploymentGroup",Properties:{ApplicationName:A.Ref($),DeploymentGroupName:K,ServiceRoleArn:W,AutoScalingGroups:U,Ec2TagFilters:Z?.map((M)=>({Key:M.key,Value:M.value,Type:M.type})),DeploymentConfigName:O,AutoRollbackConfiguration:z?{Enabled:z.enabled,Events:z.events}:void 0,AlarmConfiguration:H?{Enabled:H.enabled,Alarms:H.alarms?.map((M)=>({Name:M.name})),IgnorePollAlarmFailure:H.ignorePollAlarmFailure}:void 0,LoadBalancerInfo:G?{TargetGroupInfoList:G.targetGroupInfoList?.map((M)=>({Name:M.name})),ElbInfoList:G.elbInfoList?.map((M)=>({Name:M.name}))}:void 0,BlueGreenDeploymentConfiguration:B?{TerminateBlueInstancesOnDeploymentSuccess:B.terminateBlueInstancesOnDeploymentSuccess?{Action:B.terminateBlueInstancesOnDeploymentSuccess.action,TerminationWaitTimeInMinutes:B.terminateBlueInstancesOnDeploymentSuccess.terminationWaitTimeInMinutes}:void 0,DeploymentReadyOption:B.deploymentReadyOption?{ActionOnTimeout:B.deploymentReadyOption.actionOnTimeout,WaitTimeInMinutes:B.deploymentReadyOption.waitTimeInMinutes}:void 0,GreenFleetProvisioningOption:B.greenFleetProvisioningOption?{Action:B.greenFleetProvisioningOption.action}:void 0}:void 0,Tags:[{Key:"Name",Value:K},{Key:"Environment",Value:Y}]}},logicalId:E}}static createDeploymentConfig($){let{slug:J,environment:_,deploymentConfigName:Y,minimumHealthyHosts:Q,trafficRoutingConfig:W}=$,U=Y||w({slug:J,environment:_,resourceType:"deploy-config"}),Z=j(U);return{deploymentConfig:{Type:"AWS::CodeDeploy::DeploymentConfig",Properties:{DeploymentConfigName:U,MinimumHealthyHosts:Q?{Type:Q.type,Value:Q.value}:void 0,TrafficRoutingConfig:W?{Type:W.type,TimeBasedCanary:W.timeBasedCanary?{CanaryPercentage:W.timeBasedCanary.canaryPercentage,CanaryInterval:W.timeBasedCanary.canaryInterval}:void 0,TimeBasedLinear:W.timeBasedLinear?{LinearPercentage:W.timeBasedLinear.linearPercentage,LinearInterval:W.timeBasedLinear.linearInterval}:void 0}:void 0}},logicalId:Z}}static DeploymentConfigs={allAtOnce:()=>({type:"FLEET_PERCENT",value:0}),halfAtATime:()=>({type:"FLEET_PERCENT",value:50}),oneAtATime:()=>({type:"HOST_COUNT",value:1}),custom:($,J)=>({type:$,value:J})};static TrafficRouting={allAtOnce:()=>({type:"AllAtOnce"}),canary:($,J)=>({type:"TimeBasedCanary",timeBasedCanary:{canaryPercentage:$,canaryInterval:J}}),linear:($,J)=>({type:"TimeBasedLinear",timeBasedLinear:{linearPercentage:$,linearInterval:J}})};static RollbackConfigs={onFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE"]}),onAlarmOrFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM"]}),onAllEvents:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM","DEPLOYMENT_STOP_ON_REQUEST"]}),disabled:()=>({enabled:!1})};static BlueGreenConfigs={standard:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withDelay:($)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:$},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withManualApproval:($)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"STOP_DEPLOYMENT",waitTimeInMinutes:$},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),keepBlue:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"KEEP_ALIVE"},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}})};static UseCases={ec2Deployment:($,J,_,Y)=>{let{application:Q,logicalId:W}=R0.createApplication({slug:$,environment:J,computePlatform:"Server"}),{deploymentGroup:U,logicalId:Z}=R0.createDeploymentGroup(W,{slug:$,environment:J,serviceRoleArn:_,autoScalingGroups:Y,deploymentConfigName:"CodeDeployDefault.OneAtATime",autoRollbackConfiguration:R0.RollbackConfigs.onFailure()});return{application:Q,appId:W,deploymentGroup:U,groupId:Z}},lambdaCanaryDeployment:($,J,_,Y=10,Q=5)=>{let{application:W,logicalId:U}=R0.createApplication({slug:$,environment:J,computePlatform:"Lambda"}),{deploymentConfig:Z,logicalId:O}=R0.createDeploymentConfig({slug:$,environment:J,trafficRoutingConfig:R0.TrafficRouting.canary(Y,Q)}),{deploymentGroup:z,logicalId:H}=R0.createDeploymentGroup(U,{slug:$,environment:J,serviceRoleArn:_,deploymentConfigName:A.Ref(O),autoRollbackConfiguration:R0.RollbackConfigs.onAlarmOrFailure()});return{application:W,appId:U,deploymentConfig:Z,configId:O,deploymentGroup:z,groupId:H}},ecsBlueGreenDeployment:($,J,_,Y)=>{let{application:Q,logicalId:W}=R0.createApplication({slug:$,environment:J,computePlatform:"ECS"}),{deploymentGroup:U,logicalId:Z}=R0.createDeploymentGroup(W,{slug:$,environment:J,serviceRoleArn:_,loadBalancerInfo:{targetGroupInfoList:[{name:Y}]},blueGreenDeploymentConfiguration:R0.BlueGreenConfigs.standard(),autoRollbackConfiguration:R0.RollbackConfigs.onFailure()});return{application:Q,appId:W,deploymentGroup:U,groupId:Z}}};static Strategies={rolling:($=25)=>({type:"rolling",batchPercentage:$}),blueGreen:()=>({type:"blue-green"}),canary:($=10,J=5)=>({type:"canary",canaryPercentage:$,canaryInterval:J}),allAtOnce:()=>({type:"all-at-once"})}}class z0{static ContentTypes={".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".mjs":"application/javascript",".json":"application/json",".xml":"application/xml",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".map":"application/json"};static NoHashPatterns=[/^index\.html$/,/^favicon\.ico$/,/^robots\.txt$/,/^sitemap\.xml$/,/^manifest\.json$/,/^\.well-known\//,/^_redirects$/,/^_headers$/];static computeFileHash($,J="md5"){let _=I1($);return y_(J).update(_).digest("hex")}static computeShortHash($){return z0.computeFileHash($).slice(0,8)}static getContentType($){let J=r8($).toLowerCase();return z0.ContentTypes[J]||"application/octet-stream"}static shouldHashFile($,J){return![...z0.NoHashPatterns,...J||[]].some((Y)=>Y.test($))}static generateHashedFilename($,J){let _=r8($),Y=d_($,_),Q=p8($);if(Q===".")return`${Y}.${J}${_}`;return u$(Q,`${Y}.${J}${_}`)}static collectFiles($,J){let _=[],Y=J||$;if(!k9($))return _;let Q=f_($,{withFileTypes:!0});for(let W of Q){let U=u$($,W.name);if(W.isDirectory())_.push(...z0.collectFiles(U,Y));else if(W.isFile())_.push(U)}return _}static hashDirectory($){let{sourceDir:J,outputDir:_,excludePatterns:Y=[],hashAlgorithm:Q="md5",copyUnhashed:W=!0}=$,U=z0.collectFiles(J),Z=[],O={};for(let H of U){let G=H.replace(J,"").replace(/^[/\\]/,""),B=z0.shouldHashFile(G,Y),K=g_(H),E=B?z0.computeFileHash(H,Q).slice(0,8):"",V=B?z0.generateHashedFilename(G,E):G,M={originalPath:G,hashedPath:V,hash:E,size:K.size,contentType:z0.getContentType(H)};if(Z.push(M),O[G]=V,_){let F=u$(_,V),T=p8(F);if(!k9(T)){let{mkdirSync:L}=p("node:fs");L(T,{recursive:!0})}if(B||W)u_(H,F)}}let z={version:"1.0",timestamp:new Date().toISOString(),assets:Z,hashMap:O};if(_){let H=u$(_,"asset-manifest.json");h1(H,JSON.stringify(z,null,2))}return z}static getInvalidationPaths($,J){let _=[];if(!$)return["/*"];let Y=$.hashMap,Q=J.hashMap;for(let[W,U]of Object.entries(Q)){let Z=Y[W];if(!Z||Z!==U){if(_.push(`/${W}`),Z&&Z!==U)_.push(`/${Z}`)}}for(let[W,U]of Object.entries(Y))if(!Q[W])_.push(`/${W}`),_.push(`/${U}`);if(_.length>100)return["/*"];return[...new Set(_)]}static updateHtmlReferences($){let{htmlDir:J,manifest:_,basePath:Y=""}=$,Q=z0.collectFiles(J).filter((W)=>W.endsWith(".html")||W.endsWith(".htm"));for(let W of Q){let U=I1(W,"utf-8");for(let[Z,O]of Object.entries(_.hashMap)){if(Z===O)continue;let z=[new RegExp(`(src|href)=["']${Y}/?${z0.escapeRegExp(Z)}["']`,"g"),new RegExp(`url\\(["']?${Y}/?${z0.escapeRegExp(Z)}["']?\\)`,"g")];for(let H of z)U=U.replace(H,(G)=>{return G.replace(Z,O)})}h1(W,U)}}static updateCssReferences($){let{cssDir:J,manifest:_,basePath:Y=""}=$,Q=z0.collectFiles(J).filter((W)=>W.endsWith(".css"));for(let W of Q){let U=I1(W,"utf-8");for(let[Z,O]of Object.entries(_.hashMap)){if(Z===O)continue;let z=new RegExp(`url\\(["']?${Y}/?${z0.escapeRegExp(Z)}["']?\\)`,"g");U=U.replace(z,`url(${Y}/${O})`)}h1(W,U)}}static escapeRegExp($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}static generateS3DeploymentManifest($){let{sourceDir:J,keyPrefix:_="",excludePatterns:Y=[],cacheControl:Q={hashed:"public, max-age=31536000, immutable",unhashed:"public, max-age=3600",html:"public, max-age=0, must-revalidate"}}=$;return z0.hashDirectory({sourceDir:J,excludePatterns:Y}).assets.map((U)=>{let Z=U.hash!=="",O=U.contentType==="text/html",z=Q.unhashed||"public, max-age=3600";if(O)z=Q.html||"public, max-age=0, must-revalidate";else if(Z)z=Q.hashed||"public, max-age=31536000, immutable";return{localPath:u$(J,U.originalPath),s3Key:_?`${_}/${U.hashedPath}`:U.hashedPath,contentType:U.contentType,cacheControl:z,hash:U.hash}})}static compareManifests($,J){let _={added:[],removed:[],changed:[],unchanged:[]},Y=new Set(Object.keys($.hashMap)),Q=new Set(Object.keys(J.hashMap));for(let W of Q)if(!Y.has(W))_.added.push(W);for(let W of Y)if(!Q.has(W))_.removed.push(W);for(let W of Q)if(Y.has(W))if($.hashMap[W]!==J.hashMap[W])_.changed.push(W);else _.unchanged.push(W);return _}static loadManifest($){if(!k9($))return null;try{let J=I1($,"utf-8");return JSON.parse(J)}catch{return null}}static saveManifest($,J){h1(J,JSON.stringify($,null,2))}}class d${static createSecret($){let{slug:J,environment:_,secretName:Y,description:Q,secretString:W,kmsKeyId:U,tags:Z}=$,O=Y||w({slug:J,environment:_,resourceType:"secret"}),z=j(O),H={Type:"AWS::SecretsManager::Secret",Properties:{Name:O,Description:Q,SecretString:W,Tags:[{Key:"Name",Value:O},{Key:"Environment",Value:_},...Z?Object.entries(Z).map(([G,B])=>({Key:G,Value:B})):[]]}};if(U)H.Properties.KmsKeyId=U;return{secret:H,logicalId:z}}static createGeneratedSecret($){let{slug:J,environment:_,secretName:Y,description:Q,excludeCharacters:W,excludeLowercase:U,excludeNumbers:Z,excludePunctuation:O,excludeUppercase:z,passwordLength:H,requireEachIncludedType:G,kmsKeyId:B,tags:K}=$,E=Y||w({slug:J,environment:_,resourceType:"secret"}),V=j(E),M={Type:"AWS::SecretsManager::Secret",Properties:{Name:E,Description:Q,GenerateSecretString:{ExcludeCharacters:W,ExcludeLowercase:U,ExcludeNumbers:Z,ExcludePunctuation:O,ExcludeUppercase:z,PasswordLength:H||32,RequireEachIncludedType:G!==!1},Tags:[{Key:"Name",Value:E},{Key:"Environment",Value:_},...K?Object.entries(K).map(([F,T])=>({Key:F,Value:T})):[]]}};if(B)M.Properties.KmsKeyId=B;return{secret:M,logicalId:V}}static createDatabaseSecret($){let{slug:J,environment:_,secretName:Y,username:Q,dbname:W,engine:U,host:Z,port:O,kmsKeyId:z}=$,H=Y||w({slug:J,environment:_,resourceType:"db-secret"}),G=j(H),B={username:Q};if(W)B.dbname=W;if(U)B.engine=U;if(Z)B.host=Z;if(O)B.port=O;let K={Type:"AWS::SecretsManager::Secret",Properties:{Name:H,Description:`Database credentials for ${Q}`,GenerateSecretString:{SecretStringTemplate:JSON.stringify(B),GenerateStringKey:"password",PasswordLength:32,ExcludeCharacters:'"@/\\',RequireEachIncludedType:!0},Tags:[{Key:"Name",Value:H},{Key:"Environment",Value:_},{Key:"Type",Value:"database"}]}};if(z)K.Properties.KmsKeyId=z;return{secret:K,logicalId:G}}static attachToDatabase($){let{slug:J,environment:_,secretId:Y,targetId:Q,targetType:W}=$,U=w({slug:J,environment:_,resourceType:"secret-attachment"}),Z=j(U);return{attachment:{Type:"AWS::SecretsManager::SecretTargetAttachment",Properties:{SecretId:Y,TargetId:Q,TargetType:W}},logicalId:Z}}static enableRotation($){let{slug:J,environment:_,secretId:Y,rotationLambdaArn:Q,automaticallyAfterDays:W,rotationType:U,kmsKeyArn:Z,vpcSecurityGroupIds:O,vpcSubnetIds:z}=$,H=w({slug:J,environment:_,resourceType:"secret-rotation"}),G=j(H),B={Type:"AWS::SecretsManager::RotationSchedule",Properties:{SecretId:Y,RotationRules:{AutomaticallyAfterDays:W||30}}};if(Q)B.Properties.RotationLambdaARN=Q;else if(U)B.Properties.HostedRotationLambda={RotationType:U,KmsKeyArn:Z,VpcSecurityGroupIds:O,VpcSubnetIds:z};return{rotation:B,logicalId:G}}static SecretTypes={apiKey:($,J,_)=>{return d$.createGeneratedSecret({slug:$,environment:J,secretName:`${$}-${J}-${_}-api-key`,description:`API key for ${_}`,passwordLength:32,excludePunctuation:!0,excludeLowercase:!1,excludeUppercase:!1,excludeNumbers:!1})},oauthClientSecret:($,J,_)=>{return d$.createGeneratedSecret({slug:$,environment:J,secretName:`${$}-${J}-${_}-oauth-secret`,description:`OAuth client secret for ${_}`,passwordLength:64,excludeCharacters:"\"'`\\/@",requireEachIncludedType:!0})},jwtSecret:($,J)=>{return d$.createGeneratedSecret({slug:$,environment:J,secretName:`${$}-${J}-jwt-secret`,description:"JWT signing secret",passwordLength:64,excludePunctuation:!0})},encryptionKey:($,J)=>{return d$.createGeneratedSecret({slug:$,environment:J,secretName:`${$}-${J}-encryption-key`,description:"Data encryption key",passwordLength:64,excludeCharacters:"+/=",excludePunctuation:!0})}};static RotationTypes={MySQLSingleUser:"MySQLSingleUser",MySQLMultiUser:"MySQLMultiUser",PostgreSQLSingleUser:"PostgreSQLSingleUser",PostgreSQLMultiUser:"PostgreSQLMultiUser",OracleSingleUser:"OracleSingleUser",OracleMultiUser:"OracleMultiUser",MariaDBSingleUser:"MariaDBSingleUser",MariaDBMultiUser:"MariaDBMultiUser",SQLServerSingleUser:"SQLServerSingleUser",SQLServerMultiUser:"SQLServerMultiUser",RedshiftSingleUser:"RedshiftSingleUser",RedshiftMultiUser:"RedshiftMultiUser",MongoDBSingleUser:"MongoDBSingleUser",MongoDBMultiUser:"MongoDBMultiUser"}}class Y0{static createParameter($){let{slug:J,environment:_,parameterName:Y,value:Q,type:W="String",description:U,tier:Z="Standard",tags:O}=$,z=Y||w({slug:J,environment:_,resourceType:"parameter"}),H=j(z);return{parameter:{Type:"AWS::SSM::Parameter",Properties:{Name:`/${J}/${_}/${z}`,Type:W,Value:Q,Description:U,Tier:Z,Tags:{Name:z,Environment:_,...O}}},logicalId:H}}static createString($,J,_,Y,Q){return Y0.createParameter({slug:$,environment:J,parameterName:_,value:Y,type:"String",description:Q})}static createSecureString($,J,_,Y,Q){return Y0.createParameter({slug:$,environment:J,parameterName:_,value:Y,type:"SecureString",description:Q})}static createStringList($,J,_,Y,Q){return Y0.createParameter({slug:$,environment:J,parameterName:_,value:Y.join(","),type:"StringList",description:Q})}static Parameters={databaseUrl:($,J,_)=>{return Y0.createSecureString($,J,"database-url",_,"Database connection URL")},apiEndpoint:($,J,_)=>{return Y0.createString($,J,"api-endpoint",_,"API endpoint URL")},appVersion:($,J,_)=>{return Y0.createString($,J,"app-version",_,"Application version")},featureFlags:($,J,_)=>{return Y0.createStringList($,J,"feature-flags",_,"Enabled feature flags")},apiKey:($,J,_,Y)=>{return Y0.createSecureString($,J,`${_}-api-key`,Y,`API key for ${_}`)},oauthCredentials:($,J,_,Y)=>{let Q=Y0.createString($,J,"oauth-client-id",_,"OAuth client ID"),W=Y0.createSecureString($,J,"oauth-client-secret",Y,"OAuth client secret");return{clientId:Q,clientSecret:W}},smtpCredentials:($,J,_,Y,Q,W)=>{let U=Y0.createString($,J,"smtp-username",_,"SMTP username"),Z=Y0.createSecureString($,J,"smtp-password",Y,"SMTP password"),O=Y0.createString($,J,"smtp-host",Q,"SMTP host"),z=Y0.createString($,J,"smtp-port",W.toString(),"SMTP port");return{username:U,password:Z,host:O,port:z}},redisUrl:($,J,_)=>{return Y0.createSecureString($,J,"redis-url",_,"Redis connection URL")},s3Bucket:($,J,_)=>{return Y0.createString($,J,"s3-bucket",_,"S3 bucket name")},cloudFrontDistribution:($,J,_)=>{return Y0.createString($,J,"cloudfront-distribution-id",_,"CloudFront distribution ID")}}}class c${static createDomain($){let{slug:J,environment:_,domainName:Y,engineVersion:Q="OpenSearch_2.11",instanceType:W="t3.small.search",instanceCount:U=1,volumeSize:Z=10,volumeType:O="gp3",dedicatedMaster:z=!1,dedicatedMasterType:H,dedicatedMasterCount:G=3,multiAz:B=!1,availabilityZoneCount:K=2,vpc:E,encryption:V,enforceHttps:M=!0,tlsSecurityPolicy:F="Policy-Min-TLS-1-2-2019-07",advancedSecurity:T,autoSnapshotHour:L=0,autoTune:D=!0,tags:R={}}=$,S=Y||w({slug:J,environment:_,resourceType:"search"}),N=j(S);return{domain:{Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:S,EngineVersion:Q,ClusterConfig:{InstanceType:W,InstanceCount:U,DedicatedMasterEnabled:z,...z&&{DedicatedMasterType:H||W,DedicatedMasterCount:G},ZoneAwarenessEnabled:B,...B&&{ZoneAwarenessConfig:{AvailabilityZoneCount:K}}},EBSOptions:{EBSEnabled:!0,VolumeType:O,VolumeSize:Z},DomainEndpointOptions:{EnforceHTTPS:M,TLSSecurityPolicy:F},SnapshotOptions:{AutomatedSnapshotStartHour:L},...E&&{VPCOptions:{SubnetIds:E.subnetIds,SecurityGroupIds:E.securityGroupIds}},...V&&{EncryptionAtRestOptions:{Enabled:V.atRest??!0,...V.kmsKeyId&&{KmsKeyId:V.kmsKeyId}},NodeToNodeEncryptionOptions:{Enabled:V.nodeToNode??!0}},...T&&{AdvancedSecurityOptions:{Enabled:T.enabled,InternalUserDatabaseEnabled:T.internalUserDatabase??!0,...T.masterUserName&&T.masterUserPassword&&{MasterUserOptions:{MasterUserName:T.masterUserName,MasterUserPassword:T.masterUserPassword}},...T.masterUserArn&&{MasterUserOptions:{MasterUserARN:T.masterUserArn}}}},...D&&{AutoTuneOptions:{DesiredState:"ENABLED"}},Tags:[{Key:"Name",Value:S},{Key:"Environment",Value:_},...Object.entries(R).map(([C,x])=>({Key:C,Value:x}))]}},logicalId:N}}static createAccessPolicy($,J){let{ipAddresses:_,iamPrincipalArns:Y,allowAll:Q,vpcEndpoint:W}=J;if(Q)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:$}]};let U=[];if(Y&&Y.length>0)U.push({Effect:"Allow",Principal:{AWS:Y},Action:"es:*",Resource:$});if(_&&_.length>0)U.push({Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:$,Condition:{IpAddress:{"aws:SourceIp":_}}});if(W)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:$}]};return{Version:"2012-10-17",Statement:U}}static DomainPresets={development:($,J)=>{return c$.createDomain({slug:$,environment:J,instanceType:"t3.small.search",instanceCount:1,volumeSize:10,multiAz:!1,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!1})},production:($,J,_)=>{return c$.createDomain({slug:$,environment:J,instanceType:"m6g.large.search",instanceCount:3,volumeSize:100,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"m6g.large.search",dedicatedMasterCount:3,vpc:_,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!0},autoTune:!0})},costOptimized:($,J)=>{return c$.createDomain({slug:$,environment:J,instanceType:"t3.medium.search",instanceCount:2,volumeSize:20,volumeType:"gp3",multiAz:!0,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!0})},highPerformance:($,J,_)=>{return c$.createDomain({slug:$,environment:J,instanceType:"r6g.2xlarge.search",instanceCount:6,volumeSize:500,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"c6g.xlarge.search",dedicatedMasterCount:3,vpc:_,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!1},autoTune:!0})}};static InstanceTypes={"t3.small.search":"t3.small.search","t3.medium.search":"t3.medium.search","m6g.large.search":"m6g.large.search","m6g.xlarge.search":"m6g.xlarge.search","m6g.2xlarge.search":"m6g.2xlarge.search","r6g.large.search":"r6g.large.search","r6g.xlarge.search":"r6g.xlarge.search","r6g.2xlarge.search":"r6g.2xlarge.search","r6g.4xlarge.search":"r6g.4xlarge.search","c6g.large.search":"c6g.large.search","c6g.xlarge.search":"c6g.xlarge.search","c6g.2xlarge.search":"c6g.2xlarge.search"};static EngineVersions={"OpenSearch_2.11":"OpenSearch_2.11","OpenSearch_2.9":"OpenSearch_2.9","OpenSearch_2.7":"OpenSearch_2.7","OpenSearch_1.3":"OpenSearch_1.3","Elasticsearch_7.10":"Elasticsearch_7.10"}}class v1{static createDomainRedirectBucket($){let{slug:J,environment:_,sourceDomain:Y,targetDomain:Q,protocol:W="https"}=$,U=w({slug:J,environment:_,resourceType:"s3",suffix:"redirect"}),Z=j(U),O=j(`${U}-policy`),z={Type:"AWS::S3::Bucket",Properties:{BucketName:Y,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:Q,Protocol:W}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1},Tags:[{Key:"Name",Value:U},{Key:"Environment",Value:_},{Key:"Purpose",Value:"Domain Redirect"}]}},H={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:A.Ref(Z),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[A.Join("",[A.GetAtt(Z,"Arn"),"/*"])]}]}}};return{bucket:z,bucketPolicy:H,logicalId:Z,policyLogicalId:O}}static createPathRedirectFunction($){let{slug:J,environment:_,rules:Y}=$,Q=w({slug:J,environment:_,resourceType:"cf-redirect"}),W=j(Q),U=v1.generateRedirectFunctionCode(Y);return{function:{Type:"AWS::CloudFront::Function",Properties:{Name:Q,AutoPublish:!0,FunctionConfig:{Comment:`Path redirect function for ${J} (${_})`,Runtime:"cloudfront-js-2.0"},FunctionCode:U}},logicalId:W,functionCode:U}}static generateRedirectFunctionCode($){return`function handler(event) {
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2360
|
+
const request = event.request;
|
|
2361
|
+
const uri = request.uri;
|
|
2362
|
+
const querystring = request.querystring;
|
|
2363
2363
|
|
|
2364
|
-
|
|
2364
|
+
const redirects = {
|
|
2365
2365
|
${$.map((_)=>{let Y=_.preserveQueryString!==!1,Q=_.statusCode||301;return` '${_.source}': { target: '${_.target}', statusCode: ${Q}, preserveQs: ${Y} }`}).join(`,
|
|
2366
2366
|
`)}
|
|
2367
2367
|
};
|
|
@@ -2386,8 +2386,8 @@ ${$.map((_)=>{let Y=_.preserveQueryString!==!1,Q=_.statusCode||301;return` '${_
|
|
|
2386
2386
|
|
|
2387
2387
|
// Preserve query string if configured
|
|
2388
2388
|
if (redirect.preserveQs && Object.keys(querystring).length > 0) {
|
|
2389
|
-
|
|
2390
|
-
|
|
2389
|
+
const qs = Object.keys(querystring).map(function(key) {
|
|
2390
|
+
const val = querystring[key];
|
|
2391
2391
|
if (val.value) {
|
|
2392
2392
|
return key + '=' + val.value;
|
|
2393
2393
|
}
|
|
@@ -2431,7 +2431,7 @@ exports.handler = async (event) => {
|
|
|
2431
2431
|
console.log('Outbound email:', JSON.stringify(event, null, 2));
|
|
2432
2432
|
const { to, from, subject, html, text } = JSON.parse(event.body || '{}');
|
|
2433
2433
|
// Build and send email
|
|
2434
|
-
const
|
|
2434
|
+
const _boundary = '----=_Part_' + Date.now();
|
|
2435
2435
|
let raw = 'From: ' + from + '\\r\\n';
|
|
2436
2436
|
raw += 'To: ' + to + '\\r\\n';
|
|
2437
2437
|
raw += 'Subject: ' + subject + '\\r\\n';
|
|
@@ -2443,17 +2443,17 @@ exports.handler = async (event) => {
|
|
|
2443
2443
|
}));
|
|
2444
2444
|
return { statusCode: 200, body: JSON.stringify({ messageId: result.MessageId }) };
|
|
2445
2445
|
};`;static EmailSchedulerCode=`
|
|
2446
|
-
const { S3Client,
|
|
2446
|
+
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
|
|
2447
2447
|
const { SESClient, SendRawEmailCommand } = require('@aws-sdk/client-ses');
|
|
2448
2448
|
const s3 = new S3Client({});
|
|
2449
2449
|
const ses = new SESClient({});
|
|
2450
|
-
exports.handler = async (
|
|
2450
|
+
exports.handler = async (_event) => {
|
|
2451
2451
|
console.log('Email scheduler running');
|
|
2452
2452
|
// Check for scheduled emails and send them
|
|
2453
2453
|
return { statusCode: 200 };
|
|
2454
2454
|
};`;static EmailThreadingCode=`
|
|
2455
2455
|
const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
|
|
2456
|
-
const
|
|
2456
|
+
const _crypto = require('crypto');
|
|
2457
2457
|
const s3 = new S3Client({});
|
|
2458
2458
|
exports.handler = async (event) => {
|
|
2459
2459
|
console.log('Email threading:', JSON.stringify(event, null, 2));
|
|
@@ -2466,12 +2466,12 @@ const dynamodb = new DynamoDBClient({});
|
|
|
2466
2466
|
const sns = new SNSClient({});
|
|
2467
2467
|
exports.handler = async (event) => {
|
|
2468
2468
|
console.log('Incoming call:', JSON.stringify(event, null, 2));
|
|
2469
|
-
const
|
|
2469
|
+
const _contactData = event.Details?.ContactData || {};
|
|
2470
2470
|
// Log call and send notification
|
|
2471
2471
|
return { statusCode: 200 };
|
|
2472
2472
|
};`;static VoicemailCode=`
|
|
2473
|
-
const { S3Client
|
|
2474
|
-
const { TranscribeClient
|
|
2473
|
+
const { S3Client } = require('@aws-sdk/client-s3');
|
|
2474
|
+
const { TranscribeClient } = require('@aws-sdk/client-transcribe');
|
|
2475
2475
|
const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
|
|
2476
2476
|
const s3 = new S3Client({});
|
|
2477
2477
|
const transcribe = new TranscribeClient({});
|
|
@@ -2482,7 +2482,7 @@ exports.handler = async (event) => {
|
|
|
2482
2482
|
return { statusCode: 200 };
|
|
2483
2483
|
};`;static SendSmsCode=`
|
|
2484
2484
|
const { PinpointClient, SendMessagesCommand } = require('@aws-sdk/client-pinpoint');
|
|
2485
|
-
const { DynamoDBClient, PutItemCommand
|
|
2485
|
+
const { DynamoDBClient, PutItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
2486
2486
|
const pinpoint = new PinpointClient({});
|
|
2487
2487
|
const dynamodb = new DynamoDBClient({});
|
|
2488
2488
|
exports.handler = async (event) => {
|
|
@@ -2500,7 +2500,7 @@ exports.handler = async (event) => {
|
|
|
2500
2500
|
}));
|
|
2501
2501
|
return { statusCode: 200, body: JSON.stringify(result) };
|
|
2502
2502
|
};`;static ReceiveSmsCode=`
|
|
2503
|
-
const { DynamoDBClient
|
|
2503
|
+
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
|
|
2504
2504
|
const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
|
|
2505
2505
|
const dynamodb = new DynamoDBClient({});
|
|
2506
2506
|
const sns = new SNSClient({});
|
|
@@ -3652,7 +3652,7 @@ workflows:
|
|
|
3652
3652
|
${Q}
|
|
3653
3653
|
`}class e9{backupPlans=new Map;backupVaults=new Map;restoreJobs=new Map;continuousBackups=new Map;planCounter=0;restoreCounter=0;continuousBackupCounter=0;createVault($){this.backupVaults.set($.name,$)}getVault($){return this.backupVaults.get($)}createBackupPlan($){let J=`backup-plan-${Date.now()}-${this.planCounter++}`,_={id:J,...$};return this.backupPlans.set(J,_),_}getBackupPlan($){return this.backupPlans.get($)}listBackupPlans(){return Array.from(this.backupPlans.values())}createRDSBackupPlan($){let{dbInstanceArn:J,schedule:_="0 2 * * *",retentionDays:Y=7,vaultName:Q="default-vault"}=$;return this.createBackupPlan({name:"RDS Daily Backup",schedule:_,retentionDays:Y,vaultName:Q,resources:[{resourceArn:J,resourceType:"rds",region:"us-east-1"}],lifecycle:{moveTocoldStorageAfterDays:30,deleteAfterDays:Y}})}createDynamoDBBackupPlan($){let{tableArn:J,schedule:_="0 3 * * *",retentionDays:Y=35,crossRegionCopy:Q}=$;return this.createBackupPlan({name:"DynamoDB Daily Backup",schedule:_,retentionDays:Y,vaultName:"dynamodb-vault",resources:[{resourceArn:J,resourceType:"dynamodb",region:"us-east-1"}],lifecycle:{deleteAfterDays:Y},tags:Q?{CrossRegionCopy:Q.join(",")}:void 0})}createEFSBackupPlan($){let{fileSystemArn:J,schedule:_="0 1 * * *",retentionDays:Y=30}=$;return this.createBackupPlan({name:"EFS Daily Backup",schedule:_,retentionDays:Y,vaultName:"efs-vault",resources:[{resourceArn:J,resourceType:"efs",region:"us-east-1"}],lifecycle:{deleteAfterDays:Y}})}enableContinuousBackup($,J=35){let _=`continuous-backup-${Date.now()}-${this.continuousBackupCounter++}`,Y={id:_,resourceId:$,enabled:!0,retentionDays:J};return this.continuousBackups.set(_,Y),Y}getContinuousBackup($){return this.continuousBackups.get($)}enablePointInTimeRecovery($,J){return{enabled:!0,earliestRestorableTime:new Date(Date.now()-604800000),latestRestorableTime:new Date}}async restoreFromBackup($){let{backupId:J,resourceType:_,targetRegion:Y}=$,Q={id:`restore-${Date.now()}-${this.restoreCounter++}`,backupId:J,resourceType:_,status:"pending",startTime:new Date,targetRegion:Y};return this.restoreJobs.set(Q.id,Q),setTimeout(()=>{Q.status="running"},100),setTimeout(()=>{Q.status="completed",Q.endTime=new Date},1000),Q}async restoreToPointInTime($){let{sourceResourceArn:J,targetResourceName:_,restoreTime:Y,resourceType:Q}=$,W={id:`pitr-${Date.now()}-${this.restoreCounter++}`,backupId:`pitr-${Y.getTime()}`,resourceType:Q,status:"pending",startTime:new Date};return this.restoreJobs.set(W.id,W),console.log(`Restoring ${Q} from ${J} to ${_} at ${Y.toISOString()}`),setTimeout(()=>{W.status="completed",W.endTime=new Date},2000),W}getRestoreJob($){return this.restoreJobs.get($)}listRestoreJobs(){return Array.from(this.restoreJobs.values())}setupCrossRegionReplication($){let{sourceVault:J,sourceRegion:_,targetRegions:Y}=$;console.log("Setting up cross-region replication:"),console.log(` Source: ${J} in ${_}`),console.log(` Targets: ${Y.join(", ")}`)}generateBackupVaultCF($){return{Type:"AWS::Backup::BackupVault",Properties:{BackupVaultName:$.name,...$.encryptionKeyArn&&{EncryptionKeyArn:$.encryptionKeyArn},...$.accessPolicy&&{AccessPolicy:$.accessPolicy}}}}generateBackupPlanCF($){return{Type:"AWS::Backup::BackupPlan",Properties:{BackupPlan:{BackupPlanName:$.name,BackupPlanRule:[{RuleName:"DailyBackup",TargetBackupVault:$.vaultName,ScheduleExpression:`cron(${$.schedule})`,StartWindowMinutes:60,CompletionWindowMinutes:120,Lifecycle:$.lifecycle?{...$.lifecycle.moveTocoldStorageAfterDays&&{MoveToColdStorageAfterDays:$.lifecycle.moveTocoldStorageAfterDays},...$.lifecycle.deleteAfterDays&&{DeleteAfterDays:$.lifecycle.deleteAfterDays}}:void 0}]},...$.tags&&{BackupPlanTags:$.tags}}}}generateBackupSelectionCF($){return{Type:"AWS::Backup::BackupSelection",Properties:{BackupPlanId:{Ref:`BackupPlan${$.id}`},BackupSelection:{SelectionName:`${$.name}Selection`,IamRoleArn:"arn:aws:iam::123456789012:role/service-role/AWSBackupDefaultServiceRole",Resources:$.resources.map((J)=>J.resourceArn)}}}}clear(){this.backupPlans.clear(),this.backupVaults.clear(),this.restoreJobs.clear(),this.continuousBackups.clear(),this.planCounter=0,this.restoreCounter=0,this.continuousBackupCounter=0}}var wY=new e9;class $2{drPlans=new Map;failoverTests=new Map;planCounter=0;testCounter=0;createDRPlan($){let J=`dr-plan-${Date.now()}-${this.planCounter++}`,_={id:J,...$};return this.drPlans.set(J,_),_}createRDSDRPlan($){let{primaryDbArn:J,secondaryDbArn:_,primaryRegion:Y,secondaryRegion:Q,rto:W=60,rpo:U=5}=$;return this.createDRPlan({name:"RDS Multi-Region DR",primaryRegion:Y,secondaryRegion:Q,rto:W,rpo:U,resources:[{resourceId:"primary-db",resourceType:"rds",primaryArn:J,secondaryArn:_,replicationEnabled:!0}],runbook:this.generateRDSRunbook(Y,Q),testSchedule:"0 0 1 * *"})}createDynamoDBDRPlan($){let{tableArn:J,regions:_,rto:Y=15,rpo:Q=1}=$;return this.createDRPlan({name:"DynamoDB Global Tables DR",primaryRegion:_[0],secondaryRegion:_[1],rto:Y,rpo:Q,resources:[{resourceId:"dynamodb-table",resourceType:"dynamodb",primaryArn:J,replicationEnabled:!0}],runbook:this.generateDynamoDBRunbook(_)})}generateRDSRunbook($,J){return{estimatedDuration:60,requiredApprovals:["cto","engineering-lead"],steps:[{order:1,name:"Verify Primary Database Failure",description:"Confirm that the primary database is truly unavailable and not experiencing temporary issues",action:"aws rds describe-db-instances --region "+$,automatable:!0,estimatedDuration:2,rollbackable:!1},{order:2,name:"Check Replication Lag",description:"Verify that the read replica is up to date",action:"Check ReplicaLag metric in CloudWatch",automatable:!0,estimatedDuration:1,rollbackable:!1},{order:3,name:"Promote Read Replica",description:"Promote the read replica in the secondary region to be the new primary",action:"aws rds promote-read-replica --db-instance-identifier replica --region "+J,automatable:!0,estimatedDuration:10,rollbackable:!1},{order:4,name:"Update DNS Records",description:"Update Route53 records to point to the new primary database",action:"Update Route53 failover record set",automatable:!0,estimatedDuration:5,rollbackable:!0},{order:5,name:"Update Application Configuration",description:"Update application connection strings if needed",action:"Deploy configuration update to ECS/Lambda",automatable:!0,estimatedDuration:10,rollbackable:!0},{order:6,name:"Verify Application Connectivity",description:"Test that applications can connect to the new primary",action:"Run smoke tests",automatable:!0,estimatedDuration:5,rollbackable:!1},{order:7,name:"Monitor for Issues",description:"Monitor CloudWatch metrics and application logs",action:"Monitor for 30 minutes",automatable:!1,estimatedDuration:30,rollbackable:!1}]}}generateDynamoDBRunbook($){return{estimatedDuration:15,steps:[{order:1,name:"Verify Primary Region Failure",description:"Confirm that the primary region is experiencing an outage",action:"Check AWS Health Dashboard",automatable:!0,estimatedDuration:2,rollbackable:!1},{order:2,name:"Update Route53 Failover",description:"Update Route53 to direct traffic to secondary region",action:"Update Route53 health check and failover records",automatable:!0,estimatedDuration:5,rollbackable:!0},{order:3,name:"Update Application Endpoints",description:"Update Lambda/ECS to use secondary region DynamoDB endpoint",action:"Deploy configuration update",automatable:!0,estimatedDuration:5,rollbackable:!0},{order:4,name:"Verify Data Consistency",description:"Verify that data is consistent in secondary region",action:"Run data validation queries",automatable:!0,estimatedDuration:3,rollbackable:!1}]}}async executeFailover($,J=!1){let _=this.drPlans.get($);if(!_)throw Error(`DR plan not found: ${$}`);let Y=Date.now(),Q=0;console.log(`${J?"[DRY RUN] ":""}Executing failover for plan: ${_.name}`),console.log(`Primary: ${_.primaryRegion} -> Secondary: ${_.secondaryRegion}`),console.log(`RTO: ${_.rto} minutes, RPO: ${_.rpo} minutes`),console.log("");for(let U of _.runbook.steps){if(console.log(`Step ${U.order}: ${U.name}`),console.log(` ${U.description}`),console.log(` Action: ${U.action}`),console.log(` Estimated: ${U.estimatedDuration} minutes`),J)console.log(" [SKIPPED - DRY RUN]");else if(U.automatable)console.log(" [AUTOMATED]");else console.log(" [MANUAL - WAITING]");Q++,console.log("")}return{success:!0,duration:(Date.now()-Y)/1000/60,completedSteps:Q}}scheduleFailoverTest($,J){let _={id:`failover-test-${Date.now()}-${this.testCounter++}`,planId:$,status:"scheduled",startTime:J};return this.failoverTests.set(_.id,_),_}async runFailoverTest($){let J=this.drPlans.get($);if(!J)throw Error(`DR plan not found: ${$}`);let _={id:`failover-test-${Date.now()}-${this.testCounter++}`,planId:$,status:"running",startTime:new Date,results:[]};this.failoverTests.set(_.id,_),console.log(`Running failover test for plan: ${J.name}`),console.log("This is a non-destructive test using test resources"),console.log("");for(let Y of J.runbook.steps){let Q=Date.now();console.log(`Testing step ${Y.order}: ${Y.name}`);let W={step:Y.name,status:"success",duration:(Date.now()-Q)/1000,message:`Successfully validated step ${Y.order}`};_.results.push(W)}return _.status="completed",_.endTime=new Date,_}getDRPlan($){return this.drPlans.get($)}listDRPlans(){return Array.from(this.drPlans.values())}getFailoverTest($){return this.failoverTests.get($)}listFailoverTests(){return Array.from(this.failoverTests.values())}validateDRPlan($){let J=[],_=[];if($.rto<$.rpo)_.push("RTO cannot be less than RPO");if($.rto>240)J.push("RTO exceeds 4 hours - consider improving recovery time");if($.rpo>60)J.push("RPO exceeds 1 hour - consider more frequent backups");if($.resources.length===0)_.push("No resources defined in DR plan");for(let W of $.resources){if(!W.replicationEnabled)J.push(`Resource ${W.resourceId} does not have replication enabled`);if(!W.secondaryArn&&W.resourceType!=="dynamodb")J.push(`Resource ${W.resourceId} does not have secondary resource defined`)}if($.runbook.steps.length===0)_.push("No recovery steps defined in runbook");let Y=$.runbook.steps.reduce((W,U)=>W+U.estimatedDuration,0);if(Y>$.rto)J.push(`Estimated recovery duration (${Y}m) exceeds RTO (${$.rto}m)`);let Q=$.runbook.steps.filter((W)=>!W.automatable);if(Q.length>0)J.push(`${Q.length} manual steps in runbook - consider automation`);return{valid:_.length===0,warnings:J,errors:_}}clear(){this.drPlans.clear(),this.failoverTests.clear(),this.planCounter=0,this.testCounter=0}}var LY=new $2;class J2{configRules=new Map;configRecorders=new Map;deliveryChannels=new Map;ruleCounter=0;createConfigRecorder($){return this.configRecorders.set($.name,$),$}createDeliveryChannel($){return this.deliveryChannels.set($.name,$),$}createConfigRule($){let J=`config-rule-${Date.now()}-${this.ruleCounter++}`,_={id:J,...$};return this.configRules.set(J,_),_}createS3EncryptionRule(){return this.createConfigRule({name:"s3-bucket-server-side-encryption-enabled",description:"Checks that S3 buckets have server-side encryption enabled",source:"AWS_MANAGED",identifier:"S3_BUCKET_SERVER_SIDE_ENCRYPTION_ENABLED",scope:{complianceResourceTypes:["AWS::S3::Bucket"]}})}createS3PublicAccessBlockRule(){return this.createConfigRule({name:"s3-bucket-public-read-prohibited",description:"Checks that S3 buckets do not allow public read access",source:"AWS_MANAGED",identifier:"S3_BUCKET_PUBLIC_READ_PROHIBITED",scope:{complianceResourceTypes:["AWS::S3::Bucket"]}})}createS3VersioningRule(){return this.createConfigRule({name:"s3-bucket-versioning-enabled",description:"Checks whether versioning is enabled for S3 buckets",source:"AWS_MANAGED",identifier:"S3_BUCKET_VERSIONING_ENABLED",scope:{complianceResourceTypes:["AWS::S3::Bucket"]}})}createRdsEncryptionRule(){return this.createConfigRule({name:"rds-storage-encrypted",description:"Checks whether storage encryption is enabled for RDS DB instances",source:"AWS_MANAGED",identifier:"RDS_STORAGE_ENCRYPTED",scope:{complianceResourceTypes:["AWS::RDS::DBInstance"]}})}createRdsSnapshotEncryptionRule(){return this.createConfigRule({name:"rds-snapshots-public-prohibited",description:"Checks if RDS snapshots are public",source:"AWS_MANAGED",identifier:"RDS_SNAPSHOTS_PUBLIC_PROHIBITED",scope:{complianceResourceTypes:["AWS::RDS::DBSnapshot","AWS::RDS::DBClusterSnapshot"]}})}createRdsBackupRule($=7){return this.createConfigRule({name:"db-backup-enabled",description:"Checks whether RDS DB instances have backups enabled",source:"AWS_MANAGED",identifier:"DB_BACKUP_ENABLED",inputParameters:{backupRetentionPeriod:$},scope:{complianceResourceTypes:["AWS::RDS::DBInstance"]}})}createEc2InstanceProfileRule(){return this.createConfigRule({name:"ec2-instance-managed-by-systems-manager",description:"Checks if EC2 instances are managed by Systems Manager",source:"AWS_MANAGED",identifier:"EC2_INSTANCE_MANAGED_BY_SSM",scope:{complianceResourceTypes:["AWS::EC2::Instance"]}})}createEbsEncryptionRule(){return this.createConfigRule({name:"encrypted-volumes",description:"Checks whether EBS volumes are encrypted",source:"AWS_MANAGED",identifier:"ENCRYPTED_VOLUMES",scope:{complianceResourceTypes:["AWS::EC2::Volume"]}})}createIamPasswordPolicyRule(){return this.createConfigRule({name:"iam-password-policy",description:"Checks whether the IAM password policy meets specified requirements",source:"AWS_MANAGED",identifier:"IAM_PASSWORD_POLICY",inputParameters:{RequireUppercaseCharacters:!0,RequireLowercaseCharacters:!0,RequireSymbols:!0,RequireNumbers:!0,MinimumPasswordLength:14,PasswordReusePrevention:24,MaxPasswordAge:90}})}createIamMfaRule(){return this.createConfigRule({name:"iam-user-mfa-enabled",description:"Checks whether IAM users have MFA enabled",source:"AWS_MANAGED",identifier:"IAM_USER_MFA_ENABLED"})}createRootAccountMfaRule(){return this.createConfigRule({name:"root-account-mfa-enabled",description:"Checks whether the root account has MFA enabled",source:"AWS_MANAGED",identifier:"ROOT_ACCOUNT_MFA_ENABLED"})}createVpcFlowLogsRule(){return this.createConfigRule({name:"vpc-flow-logs-enabled",description:"Checks whether VPC Flow Logs is enabled",source:"AWS_MANAGED",identifier:"VPC_FLOW_LOGS_ENABLED",scope:{complianceResourceTypes:["AWS::EC2::VPC"]}})}createCloudTrailEnabledRule(){return this.createConfigRule({name:"cloudtrail-enabled",description:"Checks whether CloudTrail is enabled",source:"AWS_MANAGED",identifier:"CLOUD_TRAIL_ENABLED",maxExecutionFrequency:"TwentyFour_Hours"})}createCloudWatchAlarmRule(){return this.createConfigRule({name:"cloudwatch-alarm-action-check",description:"Checks whether CloudWatch alarms have actions configured",source:"AWS_MANAGED",identifier:"CLOUDWATCH_ALARM_ACTION_CHECK",inputParameters:{alarmActionRequired:!0,insufficientDataActionRequired:!1,okActionRequired:!1},scope:{complianceResourceTypes:["AWS::CloudWatch::Alarm"]}})}createCustomLambdaRule($){return this.createConfigRule({name:$.name,description:$.description,source:"CUSTOM_LAMBDA",lambdaFunctionArn:$.lambdaFunctionArn,scope:$.resourceTypes?{complianceResourceTypes:$.resourceTypes}:void 0,maxExecutionFrequency:$.maxExecutionFrequency,inputParameters:$.inputParameters})}createCompliancePreset($){let J=[];switch($){case"hipaa":J.push(this.createS3EncryptionRule(),this.createRdsEncryptionRule(),this.createEbsEncryptionRule(),this.createCloudTrailEnabledRule(),this.createIamPasswordPolicyRule(),this.createRdsBackupRule(7),this.createVpcFlowLogsRule());break;case"pci-dss":J.push(this.createS3EncryptionRule(),this.createS3PublicAccessBlockRule(),this.createRdsEncryptionRule(),this.createEbsEncryptionRule(),this.createCloudTrailEnabledRule(),this.createIamPasswordPolicyRule(),this.createIamMfaRule(),this.createRootAccountMfaRule(),this.createVpcFlowLogsRule());break;case"sox":J.push(this.createS3VersioningRule(),this.createCloudTrailEnabledRule(),this.createRdsBackupRule(30),this.createIamPasswordPolicyRule());break;case"gdpr":J.push(this.createS3EncryptionRule(),this.createRdsEncryptionRule(),this.createEbsEncryptionRule(),this.createCloudTrailEnabledRule(),this.createRdsSnapshotEncryptionRule());break;case"basic":J.push(this.createS3EncryptionRule(),this.createS3PublicAccessBlockRule(),this.createRdsEncryptionRule(),this.createCloudTrailEnabledRule(),this.createIamMfaRule(),this.createRootAccountMfaRule());break}return J}getConfigRule($){return this.configRules.get($)}listConfigRules(){return Array.from(this.configRules.values())}getConfigRecorder($){return this.configRecorders.get($)}listConfigRecorders(){return Array.from(this.configRecorders.values())}getDeliveryChannel($){return this.deliveryChannels.get($)}listDeliveryChannels(){return Array.from(this.deliveryChannels.values())}generateConfigRuleCF($){let J={Type:"AWS::Config::ConfigRule",Properties:{ConfigRuleName:$.name,Description:$.description,Source:{Owner:$.source==="AWS_MANAGED"?"AWS":"CUSTOM_LAMBDA"}}};if($.source==="AWS_MANAGED"&&$.identifier)J.Properties.Source.SourceIdentifier=$.identifier;if($.source==="CUSTOM_LAMBDA"&&$.lambdaFunctionArn)J.Properties.Source.SourceIdentifier=$.lambdaFunctionArn,J.Properties.Source.SourceDetails=[{EventSource:"aws.config",MessageType:"ConfigurationItemChangeNotification"}];if($.inputParameters)J.Properties.InputParameters=JSON.stringify($.inputParameters);if($.scope){if(J.Properties.Scope={},$.scope.complianceResourceTypes)J.Properties.Scope.ComplianceResourceTypes=$.scope.complianceResourceTypes;if($.scope.tagKey)J.Properties.Scope.TagKey=$.scope.tagKey;if($.scope.tagValue)J.Properties.Scope.TagValue=$.scope.tagValue}if($.maxExecutionFrequency)J.Properties.MaximumExecutionFrequency=$.maxExecutionFrequency;return J}generateConfigRecorderCF($){return{Type:"AWS::Config::ConfigurationRecorder",Properties:{Name:$.name,RoleArn:$.roleArn,RecordingGroup:$.recordingGroup||{AllSupported:!0,IncludeGlobalResourceTypes:!0}}}}generateDeliveryChannelCF($){return{Type:"AWS::Config::DeliveryChannel",Properties:{Name:$.name,S3BucketName:$.s3BucketName,...$.s3KeyPrefix&&{S3KeyPrefix:$.s3KeyPrefix},...$.snsTopicArn&&{SnsTopicARN:$.snsTopicArn},...$.configSnapshotDeliveryProperties&&{ConfigSnapshotDeliveryProperties:$.configSnapshotDeliveryProperties}}}}clear(){this.configRules.clear(),this.configRecorders.clear(),this.deliveryChannels.clear(),this.ruleCounter=0}}var RY=new J2;class _2{trails=new Map;trailCounter=0;createTrail($){let J=`trail-${Date.now()}-${this.trailCounter++}`,_={id:J,...$};return this.trails.set(J,_),_}createOrganizationTrail($){return this.createTrail({name:$.name,s3BucketName:$.s3BucketName,s3KeyPrefix:"organization-trail",includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,kmsKeyId:$.kmsKeyId,cloudWatchLogsLogGroupArn:$.cloudWatchLogsLogGroupArn,cloudWatchLogsRoleArn:$.cloudWatchLogsRoleArn})}createSecurityAuditTrail($){return this.createTrail({name:$.name,s3BucketName:$.s3BucketName,s3KeyPrefix:"security-audit",includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,kmsKeyId:$.kmsKeyId,cloudWatchLogsLogGroupArn:$.cloudWatchLogsLogGroupArn,cloudWatchLogsRoleArn:$.cloudWatchLogsRoleArn,eventSelectors:[{readWriteType:"All",includeManagementEvents:!0,excludeManagementEventSources:[]}],insightSelectors:[{insightType:"ApiCallRateInsight"},{insightType:"ApiErrorRateInsight"}]})}createDataEventsTrail($){let J=[];if($.s3DataBuckets&&$.s3DataBuckets.length>0)J.push({type:"AWS::S3::Object",values:$.s3DataBuckets.map((_)=>`arn:aws:s3:::${_}/*`)});if($.lambdaFunctions&&$.lambdaFunctions.length>0)J.push({type:"AWS::Lambda::Function",values:$.lambdaFunctions});return this.createTrail({name:$.name,s3BucketName:$.s3BucketName,s3KeyPrefix:"data-events",includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,eventSelectors:[{readWriteType:"All",includeManagementEvents:!1,dataResources:J}]})}createAdvancedTrail($){return this.createTrail({name:$.name,s3BucketName:$.s3BucketName,includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,advancedEventSelectors:$.selectors})}createReadOnlyTrail($){return this.createTrail({name:$.name,s3BucketName:$.s3BucketName,includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,eventSelectors:[{readWriteType:"ReadOnly",includeManagementEvents:!0}]})}createWriteOnlyTrail($){return this.createTrail({name:$.name,s3BucketName:$.s3BucketName,includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,eventSelectors:[{readWriteType:"WriteOnly",includeManagementEvents:!0}]})}getTrail($){return this.trails.get($)}listTrails(){return Array.from(this.trails.values())}generateTrailCF($){let J={Type:"AWS::CloudTrail::Trail",Properties:{TrailName:$.name,S3BucketName:$.s3BucketName,IsLogging:!0,IncludeGlobalServiceEvents:$.includeGlobalServiceEvents??!0,IsMultiRegionTrail:$.isMultiRegionTrail??!0,EnableLogFileValidation:$.enableLogFileValidation??!0}};if($.s3KeyPrefix)J.Properties.S3KeyPrefix=$.s3KeyPrefix;if($.cloudWatchLogsLogGroupArn)J.Properties.CloudWatchLogsLogGroupArn=$.cloudWatchLogsLogGroupArn;if($.cloudWatchLogsRoleArn)J.Properties.CloudWatchLogsRoleArn=$.cloudWatchLogsRoleArn;if($.snsTopicName)J.Properties.SnsTopicName=$.snsTopicName;if($.kmsKeyId)J.Properties.KMSKeyId=$.kmsKeyId;if($.eventSelectors)J.Properties.EventSelectors=$.eventSelectors.map((_)=>({ReadWriteType:_.readWriteType,IncludeManagementEvents:_.includeManagementEvents??!0,..._.dataResources&&{DataResources:_.dataResources.map((Y)=>({Type:Y.type,Values:Y.values}))},..._.excludeManagementEventSources&&{ExcludeManagementEventSources:_.excludeManagementEventSources}}));if($.insightSelectors)J.Properties.InsightSelectors=$.insightSelectors.map((_)=>({InsightType:_.insightType}));if($.advancedEventSelectors)J.Properties.AdvancedEventSelectors=$.advancedEventSelectors.map((_)=>({Name:_.name,FieldSelectors:_.fieldSelectors.map((Y)=>({Field:Y.field,...Y.equals&&{Equals:Y.equals},...Y.startsWith&&{StartsWith:Y.startsWith},...Y.endsWith&&{EndsWith:Y.endsWith},...Y.notEquals&&{NotEquals:Y.notEquals},...Y.notStartsWith&&{NotStartsWith:Y.notStartsWith},...Y.notEndsWith&&{NotEndsWith:Y.notEndsWith}}))}));return J}generateBucketPolicy($,J){return{Version:"2012-10-17",Statement:[{Sid:"AWSCloudTrailAclCheck",Effect:"Allow",Principal:{Service:"cloudtrail.amazonaws.com"},Action:"s3:GetBucketAcl",Resource:`arn:aws:s3:::${$}`},{Sid:"AWSCloudTrailWrite",Effect:"Allow",Principal:{Service:"cloudtrail.amazonaws.com"},Action:"s3:PutObject",Resource:J.map((_)=>`arn:aws:s3:::${$}/AWSLogs/${_}/*`),Condition:{StringEquals:{"s3:x-amz-acl":"bucket-owner-full-control"}}}]}}clear(){this.trails.clear(),this.trailCounter=0}}var AY=new _2;class Y2{detectors=new Map;threatIntelSets=new Map;ipSets=new Map;filters=new Map;detectorCounter=0;threatIntelCounter=0;ipSetCounter=0;filterCounter=0;createDetector($){let J=`detector-${Date.now()}-${this.detectorCounter++}`,_={id:J,...$};return this.detectors.set(J,_),_}createComprehensiveDetector(){return this.createDetector({enable:!0,findingPublishingFrequency:"FIFTEEN_MINUTES",dataSources:{s3Logs:{enable:!0},kubernetes:{auditLogs:{enable:!0}},malwareProtection:{scanEc2InstanceWithFindings:{ebsVolumes:{enable:!0}}}},features:[{name:"S3_DATA_EVENTS",status:"ENABLED"},{name:"EKS_AUDIT_LOGS",status:"ENABLED"},{name:"EBS_MALWARE_PROTECTION",status:"ENABLED"},{name:"RDS_LOGIN_EVENTS",status:"ENABLED"},{name:"LAMBDA_NETWORK_LOGS",status:"ENABLED"}]})}createBasicDetector(){return this.createDetector({enable:!0,findingPublishingFrequency:"SIX_HOURS"})}createThreatIntelSet($){let J=`threat-intel-${Date.now()}-${this.threatIntelCounter++}`,_={id:J,...$};return this.threatIntelSets.set(J,_),_}createIPSet($){let J=`ip-set-${Date.now()}-${this.ipSetCounter++}`,_={id:J,...$};return this.ipSets.set(J,_),_}createFindingFilter($){let J=`filter-${Date.now()}-${this.filterCounter++}`,_={id:J,...$};return this.filters.set(J,_),_}createLowSeverityArchiveFilter($){return this.createFindingFilter({detectorId:$,name:"archive-low-severity",description:"Automatically archive low severity findings",action:"ARCHIVE",rank:1,findingCriteria:{criterion:{severity:{lt:4}}}})}createFindingTypeFilter($,J,_){return this.createFindingFilter({detectorId:$,name:`filter-finding-types-${_.toLowerCase()}`,description:`${_==="ARCHIVE"?"Archive":"Keep"} specific finding types`,action:_,rank:2,findingCriteria:{criterion:{type:{eq:J}}}})}createTrustedIPFilter($,J){return this.createFindingFilter({detectorId:$,name:"trusted-ip-addresses",description:"Archive findings from trusted IP addresses",action:"ARCHIVE",rank:3,findingCriteria:{criterion:{"resource.instanceDetails.networkInterfaces.privateIpAddress":{eq:J}}}})}getDetector($){return this.detectors.get($)}listDetectors(){return Array.from(this.detectors.values())}getThreatIntelSet($){return this.threatIntelSets.get($)}listThreatIntelSets(){return Array.from(this.threatIntelSets.values())}getIPSet($){return this.ipSets.get($)}listIPSets(){return Array.from(this.ipSets.values())}getFindingFilter($){return this.filters.get($)}listFindingFilters(){return Array.from(this.filters.values())}generateDetectorCF($){let J={Type:"AWS::GuardDuty::Detector",Properties:{Enable:$.enable}};if($.findingPublishingFrequency)J.Properties.FindingPublishingFrequency=$.findingPublishingFrequency;if($.dataSources){if(J.Properties.DataSources={},$.dataSources.s3Logs)J.Properties.DataSources.S3Logs={Enable:$.dataSources.s3Logs.enable};if($.dataSources.kubernetes)J.Properties.DataSources.Kubernetes={AuditLogs:{Enable:$.dataSources.kubernetes.auditLogs.enable}};if($.dataSources.malwareProtection)J.Properties.DataSources.MalwareProtection={ScanEc2InstanceWithFindings:{EbsVolumes:{Enable:$.dataSources.malwareProtection.scanEc2InstanceWithFindings.ebsVolumes.enable}}}}if($.features)J.Properties.Features=$.features.map((_)=>({Name:_.name,Status:_.status,..._.additionalConfiguration&&{AdditionalConfiguration:_.additionalConfiguration}}));return J}generateThreatIntelSetCF($){return{Type:"AWS::GuardDuty::ThreatIntelSet",Properties:{DetectorId:$.detectorId,Name:$.name,Format:$.format,Location:$.location,Activate:$.activate}}}generateIPSetCF($){return{Type:"AWS::GuardDuty::IPSet",Properties:{DetectorId:$.detectorId,Name:$.name,Format:$.format,Location:$.location,Activate:$.activate}}}generateFilterCF($){return{Type:"AWS::GuardDuty::Filter",Properties:{DetectorId:$.detectorId,Name:$.name,Description:$.description,Action:$.action,Rank:$.rank,FindingCriteria:{Criterion:$.findingCriteria.criterion}}}}clear(){this.detectors.clear(),this.threatIntelSets.clear(),this.ipSets.clear(),this.filters.clear(),this.detectorCounter=0,this.threatIntelCounter=0,this.ipSetCounter=0,this.filterCounter=0}}var SY=new Y2;class H${hubs=new Map;hubCounter=0;ruleCounter=0;static Standards={AWS_FOUNDATIONAL_SECURITY:{arn:"arn:aws:securityhub:::ruleset/aws-foundational-security-best-practices/v/1.0.0",name:"AWS Foundational Security Best Practices",description:"AWS recommended security best practices"},CIS_AWS_FOUNDATIONS_1_2:{arn:"arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0",name:"CIS AWS Foundations Benchmark v1.2.0",description:"CIS AWS Foundations Benchmark v1.2.0"},CIS_AWS_FOUNDATIONS_1_4:{arn:"arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.4.0",name:"CIS AWS Foundations Benchmark v1.4.0",description:"CIS AWS Foundations Benchmark v1.4.0"},PCI_DSS:{arn:"arn:aws:securityhub:us-east-1::standards/pci-dss/v/3.2.1",name:"PCI DSS v3.2.1",description:"Payment Card Industry Data Security Standard"},NIST_800_53:{arn:"arn:aws:securityhub:us-east-1::standards/nist-800-53/v/5.0.0",name:"NIST SP 800-53 Rev. 5",description:"NIST Special Publication 800-53 Revision 5"}};createHub($){let J=`hub-${Date.now()}-${this.hubCounter++}`,_={id:J,...$};return this.hubs.set(J,_),_}createComprehensiveHub(){return this.createHub({enable:!0,controlFindingGenerator:"SECURITY_CONTROL",enableDefaultStandards:!0,standards:[{id:"aws-foundational",...H$.Standards.AWS_FOUNDATIONAL_SECURITY,enabled:!0},{id:"cis-1-4",...H$.Standards.CIS_AWS_FOUNDATIONS_1_4,enabled:!0},{id:"pci-dss",...H$.Standards.PCI_DSS,enabled:!0}]})}createBasicHub(){return this.createHub({enable:!0,controlFindingGenerator:"STANDARD_CONTROL",enableDefaultStandards:!0,standards:[{id:"aws-foundational",...H$.Standards.AWS_FOUNDATIONAL_SECURITY,enabled:!0}]})}createLowSeveritySuppressionRule(){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:"Suppress Low Severity Informational Findings",description:"Automatically suppress informational findings",actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{workflow:{status:"SUPPRESSED"},note:{text:"Automatically suppressed low severity finding",updatedBy:"SecurityHub Automation"}}}],criteria:{severityLabel:[{value:"INFORMATIONAL",comparison:"EQUALS"}],recordState:[{value:"ACTIVE",comparison:"EQUALS"}]},ruleStatus:"ENABLED",ruleOrder:1}}createResourceTypeNotificationRule($){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:"Notify on Critical Resource Findings",description:"Set findings for critical resources to NOTIFIED status",actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{workflow:{status:"NOTIFIED"},note:{text:"Critical resource finding requires attention",updatedBy:"SecurityHub Automation"}}}],criteria:{resourceType:$.map((J)=>({value:J,comparison:"EQUALS"})),severityLabel:[{value:"HIGH",comparison:"EQUALS"},{value:"CRITICAL",comparison:"EQUALS"}],workflowStatus:[{value:"NEW",comparison:"EQUALS"}]},ruleStatus:"ENABLED",ruleOrder:2}}createComplianceFailureRule(){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:"Flag Compliance Failures",description:"Increase severity for compliance failures",actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{severity:{label:"HIGH"},workflow:{status:"NOTIFIED"},note:{text:"Compliance failure detected - requires immediate attention",updatedBy:"SecurityHub Automation"}}}],criteria:{complianceStatus:[{value:"FAILED",comparison:"EQUALS"}],recordState:[{value:"ACTIVE",comparison:"EQUALS"}]},ruleStatus:"ENABLED",ruleOrder:3}}createFalsePositiveSuppressionRule($,J){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:`Suppress False Positives - ${$}`,description:`Automatically suppress known false positives from ${$}`,actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{workflow:{status:"SUPPRESSED"},note:{text:"Known false positive - automatically suppressed",updatedBy:"SecurityHub Automation"}}}],criteria:{productName:[{value:$,comparison:"EQUALS"}],title:J.map((_)=>({value:_,comparison:"PREFIX"}))},ruleStatus:"ENABLED",ruleOrder:10}}getHub($){return this.hubs.get($)}listHubs(){return Array.from(this.hubs.values())}generateHubCF($){let J={Type:"AWS::SecurityHub::Hub",Properties:{}};if($.controlFindingGenerator)J.Properties.ControlFindingGenerator=$.controlFindingGenerator;if($.enableDefaultStandards!==void 0)J.Properties.EnableDefaultStandards=$.enableDefaultStandards;return J}generateStandardCF($){let J={Type:"AWS::SecurityHub::Standard",Properties:{StandardsArn:$.arn}};if($.disabledControls&&$.disabledControls.length>0)J.Properties.DisabledStandardsControls=$.disabledControls.map((_)=>({StandardsControlArn:_,Reason:"Disabled by configuration"}));return J}generateAutomationRuleCF($){return{Type:"AWS::SecurityHub::AutomationRule",Properties:{RuleName:$.ruleName,Description:$.description,Actions:$.actions.map((J)=>({Type:J.type,FindingFieldsUpdate:J.findingFieldsUpdate})),Criteria:$.criteria,RuleStatus:$.ruleStatus,RuleOrder:$.ruleOrder}}}clear(){this.hubs.clear(),this.hubCounter=0,this.ruleCounter=0}}var DY=new H$;class Q2{deployments=new Map;deploymentHistory=new Map;deploymentCounter=0;resultCounter=0;createDeployment($){let J=`bg-deployment-${Date.now()}-${this.deploymentCounter++}`,_={id:J,...$};return this.deployments.set(J,_),_}createALBDeployment($){return this.createDeployment({name:$.name,blueEnvironment:{name:"blue",targetGroupArn:$.blueTargetGroupArn,weight:100},greenEnvironment:{name:"green",targetGroupArn:$.greenTargetGroupArn,weight:0},activeEnvironment:"blue",routingConfig:{type:"alb",listenerArn:$.listenerArn,switchoverTimeSeconds:0},autoPromote:$.autoPromote,healthCheckConfig:$.healthCheckConfig})}createRoute53Deployment($){return this.createDeployment({name:$.name,blueEnvironment:{name:"blue",targetGroupArn:$.blueTargetGroupArn,weight:100},greenEnvironment:{name:"green",targetGroupArn:$.greenTargetGroupArn,weight:0},activeEnvironment:"blue",routingConfig:{type:"route53",hostedZoneId:$.hostedZoneId,switchoverTimeSeconds:$.switchoverTimeSeconds||60}})}createECSDeployment($){return this.createDeployment({name:$.name,blueEnvironment:{name:"blue",targetGroupArn:$.blueTargetGroupArn,taskDefinitionArn:$.blueTaskDefinitionArn,weight:100},greenEnvironment:{name:"green",targetGroupArn:$.greenTargetGroupArn,taskDefinitionArn:$.greenTaskDefinitionArn,weight:0},activeEnvironment:"blue",routingConfig:{type:"alb",listenerArn:$.listenerArn},autoRollback:$.autoRollback??!0})}async executeDeployment($,J=!1){let _=this.deployments.get($);if(!_)throw Error(`Deployment not found: ${$}`);let Y={success:!1,deploymentId:`result-${Date.now()}-${this.resultCounter++}`,startTime:new Date,healthChecksPassed:!1,errors:[]};console.log(`${J?"[DRY RUN] ":""}Starting blue/green deployment: ${_.name}`),console.log(` Active environment: ${_.activeEnvironment}`),console.log(` Routing type: ${_.routingConfig.type}`);let Q=_.activeEnvironment==="blue"?"green":"blue";if(console.log(` Switching to: ${Q}`),console.log(`\\n1. Deploying to ${Q} environment`),!J)await new Promise((W)=>setTimeout(W,100));if(console.log(`\\n2. Running health checks on ${Q} environment`),_.healthCheckConfig){let W=await this.runHealthChecks(_,Q,J);if(Y.healthChecksPassed=W,!W){if(Y.errors?.push("Health checks failed"),Y.endTime=new Date,_.autoRollback)console.log(" Auto-rollback enabled - keeping current environment active"),Y.rolledBackAt=new Date;return this.recordDeployment($,Y),Y}}else Y.healthChecksPassed=!0;if(console.log(`\\n3. Switching traffic to ${Q} environment`),!J)_.activeEnvironment=Q,Y.switchedAt=new Date;if(console.log(`\\n4. Monitoring ${Q} environment`),!J)await new Promise((W)=>setTimeout(W,100));return Y.success=!0,Y.endTime=new Date,console.log("\\n✓ Deployment completed successfully"),this.recordDeployment($,Y),Y}async rollback($){let J=this.deployments.get($);if(!J)throw Error(`Deployment not found: ${$}`);let _={success:!1,deploymentId:`result-${Date.now()}-${this.resultCounter++}`,startTime:new Date,healthChecksPassed:!0,errors:[]};console.log(`Rolling back deployment: ${J.name}`);let Y=J.activeEnvironment==="blue"?"green":"blue";return J.activeEnvironment=Y,_.success=!0,_.rolledBackAt=new Date,_.endTime=new Date,console.log(` Switched back to: ${Y}`),this.recordDeployment($,_),_}async runHealthChecks($,J,_){let Y=$.healthCheckConfig;if(console.log(` Health check path: ${Y.path||"/"}`),console.log(` Healthy threshold: ${Y.healthyThreshold}`),console.log(` Interval: ${Y.interval}s`),_)return console.log(" [SKIPPED - DRY RUN]"),!0;let Q=0,W=Y.healthyThreshold+2;for(let U=0;U<W;U++)if(await new Promise((O)=>setTimeout(O,50)),Math.random()>0.1){if(Q++,console.log(` Check ${U+1}: ✓ Healthy (${Q}/${Y.healthyThreshold})`),Q>=Y.healthyThreshold)return!0}else Q=0,console.log(` Check ${U+1}: ✗ Unhealthy`);return!1}recordDeployment($,J){if(!this.deploymentHistory.has($))this.deploymentHistory.set($,[]);this.deploymentHistory.get($).push(J)}getDeployment($){return this.deployments.get($)}listDeployments(){return Array.from(this.deployments.values())}getDeploymentHistory($){return this.deploymentHistory.get($)||[]}generateALBListenerCF($){let J=$.activeEnvironment==="blue"?$.blueEnvironment:$.greenEnvironment;return{Type:"AWS::ElasticLoadBalancingV2::ListenerRule",Properties:{ListenerArn:$.routingConfig.listenerArn,Priority:1,Conditions:[{Field:"path-pattern",Values:["/*"]}],Actions:[{Type:"forward",TargetGroupArn:J.targetGroupArn}]}}}generateRoute53RecordSetCF($,J){return[{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:$.routingConfig.hostedZoneId,Name:J,Type:"A",SetIdentifier:"blue",Weight:$.activeEnvironment==="blue"?100:0,AliasTarget:{HostedZoneId:$.routingConfig.hostedZoneId,DNSName:$.blueEnvironment.targetGroupArn,EvaluateTargetHealth:!0}}},{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:$.routingConfig.hostedZoneId,Name:J,Type:"A",SetIdentifier:"green",Weight:$.activeEnvironment==="green"?100:0,AliasTarget:{HostedZoneId:$.routingConfig.hostedZoneId,DNSName:$.greenEnvironment.targetGroupArn,EvaluateTargetHealth:!0}}}]}clear(){this.deployments.clear(),this.deploymentHistory.clear(),this.deploymentCounter=0,this.resultCounter=0}}var CY=new Q2;class a${deployments=new Map;deploymentHistory=new Map;deploymentCounter=0;resultCounter=0;static Strategies={CONSERVATIVE:[{name:"Initial Canary",trafficPercentage:10,durationMinutes:10},{name:"Quarter Traffic",trafficPercentage:25,durationMinutes:10},{name:"Half Traffic",trafficPercentage:50,durationMinutes:15},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}],BALANCED:[{name:"Initial Canary",trafficPercentage:20,durationMinutes:5},{name:"Half Traffic",trafficPercentage:50,durationMinutes:10},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}],AGGRESSIVE:[{name:"Half Traffic",trafficPercentage:50,durationMinutes:5},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}],LINEAR_10:[{name:"Canary 10%",trafficPercentage:10,durationMinutes:5},{name:"Canary 20%",trafficPercentage:20,durationMinutes:5},{name:"Canary 30%",trafficPercentage:30,durationMinutes:5},{name:"Canary 40%",trafficPercentage:40,durationMinutes:5},{name:"Canary 50%",trafficPercentage:50,durationMinutes:5},{name:"Canary 60%",trafficPercentage:60,durationMinutes:5},{name:"Canary 70%",trafficPercentage:70,durationMinutes:5},{name:"Canary 80%",trafficPercentage:80,durationMinutes:5},{name:"Canary 90%",trafficPercentage:90,durationMinutes:5},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}]};createDeployment($){let J=`canary-${Date.now()}-${this.deploymentCounter++}`,_={id:J,...$};return this.deployments.set(J,_),_}createLambdaCanaryDeployment($){let J=$.strategy||"BALANCED",_=a$.Strategies[J].map((Y)=>({...Y,alarmThresholds:{errorRate:$.errorRateThreshold||1,latencyP99:$.latencyThreshold||1000}}));return this.createDeployment({name:$.name,baselineVersion:{version:"baseline",functionVersionArn:$.baselineVersionArn,weight:100},canaryVersion:{version:"canary",functionVersionArn:$.canaryVersionArn,weight:0},stages:_,currentStage:0,status:"pending",autoPromote:$.autoPromote??!0,autoRollback:!0})}createECSCanaryDeployment($){let J=$.strategy||"CONSERVATIVE",_=a$.Strategies[J];return this.createDeployment({name:$.name,baselineVersion:{version:"baseline",taskDefinitionArn:$.baselineTaskDefinitionArn,targetGroupArn:$.baselineTargetGroupArn,weight:100},canaryVersion:{version:"canary",taskDefinitionArn:$.canaryTaskDefinitionArn,targetGroupArn:$.canaryTargetGroupArn,weight:0},stages:_,currentStage:0,status:"pending",autoRollback:!0})}async executeDeployment($,J=!1){let _=this.deployments.get($);if(!_)throw Error(`Deployment not found: ${$}`);let Y={success:!1,deploymentId:`result-${Date.now()}-${this.resultCounter++}`,startTime:new Date,completedStages:0,rolledBack:!1};console.log(`${J?"[DRY RUN] ":""}Starting canary deployment: ${_.name}`),console.log(` Strategy: ${_.stages.length} stages`),console.log(` Auto-promote: ${_.autoPromote}`),console.log(` Auto-rollback: ${_.autoRollback}`),console.log(""),_.status="in_progress";for(let Q=0;Q<_.stages.length;Q++){let W=_.stages[Q];if(_.currentStage=Q,console.log(`Stage ${Q+1}/${_.stages.length}: ${W.name}`),console.log(` Traffic: ${W.trafficPercentage}% canary, ${100-W.trafficPercentage}% baseline`),console.log(` Duration: ${W.durationMinutes} minutes`),!J)_.baselineVersion.weight=100-W.trafficPercentage,_.canaryVersion.weight=W.trafficPercentage;if(!await this.monitorStage(_,W,J)){if(console.log(" ✗ Stage failed - metrics exceeded thresholds"),_.autoRollback)console.log("\\n Rolling back deployment..."),await this.rollback($,J),Y.rolledBack=!0,Y.reason="Metrics exceeded thresholds";return Y.endTime=new Date,_.status="rolled_back",this.recordDeployment($,Y),Y}console.log(" ✓ Stage completed successfully"),Y.completedStages++,console.log("")}return _.status="completed",Y.success=!0,Y.endTime=new Date,console.log("✓ Canary deployment completed successfully"),this.recordDeployment($,Y),Y}async monitorStage($,J,_){if(console.log(" Monitoring metrics..."),_)return console.log(" [SKIPPED - DRY RUN]"),!0;await new Promise((Q)=>setTimeout(Q,100));let Y={baselineErrorRate:Math.random()*0.5,canaryErrorRate:Math.random()*0.8,baselineLatencyP99:200+Math.random()*100,canaryLatencyP99:180+Math.random()*150,baselineRequestCount:Math.floor(Math.random()*1000)+500,canaryRequestCount:Math.floor((Math.random()*1000+500)*J.trafficPercentage/100)};if($.metrics=Y,console.log(` Baseline: ${Y.baselineErrorRate.toFixed(2)}% errors, ${Y.baselineLatencyP99.toFixed(0)}ms P99`),console.log(` Canary: ${Y.canaryErrorRate.toFixed(2)}% errors, ${Y.canaryLatencyP99.toFixed(0)}ms P99`),J.alarmThresholds){let{errorRate:Q,latencyP99:W}=J.alarmThresholds;if(Q&&Y.canaryErrorRate>Q)return console.log(` ⚠ Error rate exceeded threshold: ${Y.canaryErrorRate.toFixed(2)}% > ${Q}%`),!1;if(W&&Y.canaryLatencyP99>W)return console.log(` ⚠ Latency P99 exceeded threshold: ${Y.canaryLatencyP99.toFixed(0)}ms > ${W}ms`),!1}return!0}async rollback($,J=!1){let _=this.deployments.get($);if(!_)throw Error(`Deployment not found: ${$}`);if(console.log(`${J?"[DRY RUN] ":""}Rolling back canary deployment: ${_.name}`),!J)_.baselineVersion.weight=100,_.canaryVersion.weight=0,_.status="rolled_back";console.log(" Traffic restored to baseline: 100%")}promoteCanary($){let J=this.deployments.get($);if(!J)throw Error(`Deployment not found: ${$}`);console.log(`Promoting canary to baseline: ${J.name}`);let _=J.baselineVersion;J.baselineVersion=J.canaryVersion,J.canaryVersion=_,J.baselineVersion.weight=100,J.canaryVersion.weight=0,J.status="completed",console.log(" Canary promoted successfully")}recordDeployment($,J){if(!this.deploymentHistory.has($))this.deploymentHistory.set($,[]);this.deploymentHistory.get($).push(J)}getDeployment($){return this.deployments.get($)}listDeployments(){return Array.from(this.deployments.values())}getDeploymentHistory($){return this.deploymentHistory.get($)||[]}generateLambdaAliasCF($,J){return{Type:"AWS::Lambda::Alias",Properties:{FunctionName:{Ref:"LambdaFunction"},Name:J,FunctionVersion:$.canaryVersion.version,RoutingConfig:{AdditionalVersionWeights:[{FunctionVersion:$.baselineVersion.version,FunctionWeight:$.baselineVersion.weight/100}]}}}}generateALBListenerRuleCF($){return{Type:"AWS::ElasticLoadBalancingV2::ListenerRule",Properties:{ListenerArn:{Ref:"LoadBalancerListener"},Priority:1,Conditions:[{Field:"path-pattern",Values:["/*"]}],Actions:[{Type:"forward",ForwardConfig:{TargetGroups:[{TargetGroupArn:$.baselineVersion.targetGroupArn,Weight:$.baselineVersion.weight},{TargetGroupArn:$.canaryVersion.targetGroupArn,Weight:$.canaryVersion.weight}],TargetGroupStickinessConfig:{Enabled:!1}}}]}}}clear(){this.deployments.clear(),this.deploymentHistory.clear(),this.deploymentCounter=0,this.resultCounter=0}}var PY=new a$;class W2{tests=new Map;testCounter=0;createTest($){let J=`abtest-${Date.now()}-${this.testCounter++}`,_={id:J,...$};return this.tests.set(J,_),_}createSimpleABTest($){let J=$.variantTrafficPercentage||50;return this.createTest({name:$.name,description:$.description,variants:[{id:"control",name:"Control",description:"Original version",trafficPercentage:100-J,targetGroupArn:$.controlTargetGroupArn,weight:100-J},{id:"variant-a",name:"Variant A",description:"Test version",trafficPercentage:J,targetGroupArn:$.variantTargetGroupArn,weight:J}],routingStrategy:{type:$.stickySession?"cookie":"random",cookieName:$.stickySession?"ab_variant":void 0,stickySession:$.stickySession??!1,sessionDuration:1440},startTime:new Date,status:"draft"})}createMultivariateTest($){let J=$.variants.reduce((_,Y)=>_+Y.trafficPercentage,0);if(J!==100)throw Error(`Traffic percentages must sum to 100, got ${J}`);return this.createTest({name:$.name,description:$.description,variants:$.variants.map((_,Y)=>({id:`variant-${Y}`,name:_.name,description:_.description,trafficPercentage:_.trafficPercentage,targetGroupArn:_.targetGroupArn,weight:_.trafficPercentage})),routingStrategy:$.routingStrategy||{type:"random",stickySession:!1},startTime:new Date,status:"draft"})}createHeaderBasedTest($){return this.createTest({name:$.name,description:`Route based on ${$.headerName} header`,variants:[{id:"control",name:"Control",trafficPercentage:50,targetGroupArn:$.controlTargetGroupArn,weight:50},{id:"variant-a",name:"Variant A",trafficPercentage:50,targetGroupArn:$.variantTargetGroupArn,weight:50}],routingStrategy:{type:"header",headerName:$.headerName,stickySession:!1},startTime:new Date,status:"draft"})}createGeoBasedTest($){return this.createTest({name:$.name,description:"Route based on geographic location",variants:[{id:"control",name:"Control (Rest of World)",trafficPercentage:50,targetGroupArn:$.controlTargetGroupArn,weight:50},{id:"variant-a",name:`Variant A (${$.regions.join(", ")})`,trafficPercentage:50,targetGroupArn:$.variantTargetGroupArn,weight:50}],routingStrategy:{type:"geo",stickySession:!0,sessionDuration:1440},startTime:new Date,status:"draft"})}startTest($){let J=this.tests.get($);if(!J)throw Error(`Test not found: ${$}`);if(J.status!=="draft"&&J.status!=="paused")throw Error(`Cannot start test in ${J.status} status`);J.status="active",J.startTime=new Date,console.log(`Started A/B test: ${J.name}`),console.log(` Variants: ${J.variants.length}`),J.variants.forEach((_)=>{console.log(` - ${_.name}: ${_.trafficPercentage}%`)})}pauseTest($){let J=this.tests.get($);if(!J)throw Error(`Test not found: ${$}`);J.status="paused",console.log(`Paused A/B test: ${J.name}`)}updateTrafficSplit($,J,_){let Y=this.tests.get($);if(!Y)throw Error(`Test not found: ${$}`);let Q=Y.variants.find((U)=>U.id===J);if(!Q)throw Error(`Variant not found: ${J}`);let W=Q.trafficPercentage;Q.trafficPercentage=_,Q.weight=_,console.log(`Updated ${Q.name} traffic: ${W}% → ${_}%`)}analyzeResults($){let J=this.tests.get($);if(!J)throw Error(`Test not found: ${$}`);if(!J.metrics)J.metrics=this.collectMetrics(J);let _=J.variants[0],Y=0;for(let z of J.variants){let H=J.metrics.variants[z.id];if(H&&H.conversionRate>Y)Y=H.conversionRate,_=z}let Q=J.metrics.variants.control||J.metrics.variants[J.variants[0].id],W=J.metrics.variants[_.id],U=(W.conversionRate-Q.conversionRate)/Q.conversionRate*100,Z=100,O=W.requests>Z&&Q.requests>Z&&Math.abs(U)>10;return{testId:$,winningVariant:_.name,confidence:O?95:75,improvement:U,statisticalSignificance:O,metrics:J.metrics,recommendation:this.generateRecommendation(U,O,_.name)}}declareWinner($,J){let _=this.tests.get($);if(!_)throw Error(`Test not found: ${$}`);let Y=_.variants.find((Q)=>Q.id===J);if(!Y)throw Error(`Variant not found: ${J}`);_.variants.forEach((Q)=>{if(Q.id===J)Q.trafficPercentage=100,Q.weight=100;else Q.trafficPercentage=0,Q.weight=0}),_.status="completed",_.endTime=new Date,_.winner=J,console.log(`Declared winner: ${Y.name}`),console.log(` All traffic now routed to ${Y.name}`)}collectMetrics($){let J={},_=0;for(let Y of $.variants){let Q=Math.floor(Math.random()*1000)+500,W=Math.floor(Q*(Math.random()*0.1+0.05)),U=W/Q*100;J[Y.id]={requests:Q,conversions:W,conversionRate:U,averageLatency:150+Math.random()*100,errorRate:Math.random()*0.5,revenue:W*(Math.random()*50+100)},_+=Q}return{variants:J,totalRequests:_,startTime:$.startTime,lastUpdated:new Date}}generateRecommendation($,J,_){if(!J)return"Continue test - sample size too small or no significant difference detected";if($>20)return`Strong winner detected - ${_} shows ${$.toFixed(1)}% improvement. Recommend deploying to all traffic.`;if($>10)return`Moderate improvement - ${_} shows ${$.toFixed(1)}% improvement. Consider deploying.`;if($>0)return`Minor improvement - ${_} shows ${$.toFixed(1)}% improvement. May not be worth the complexity.`;return"No improvement detected - consider reverting to control variant"}getTest($){return this.tests.get($)}listTests(){return Array.from(this.tests.values())}generateALBListenerRuleCF($){return{Type:"AWS::ElasticLoadBalancingV2::ListenerRule",Properties:{ListenerArn:{Ref:"LoadBalancerListener"},Priority:1,Conditions:[{Field:"path-pattern",Values:["/*"]}],Actions:[{Type:"forward",ForwardConfig:{TargetGroups:$.variants.map((J)=>({TargetGroupArn:J.targetGroupArn,Weight:J.weight})),TargetGroupStickinessConfig:{Enabled:$.routingStrategy.stickySession||!1,DurationSeconds:$.routingStrategy.sessionDuration?$.routingStrategy.sessionDuration*60:void 0}}}]}}}generateLambdaEdgeFunction($){return`'use strict';
|
|
3654
3654
|
|
|
3655
|
-
exports.handler = (event,
|
|
3655
|
+
exports.handler = (event, _context, _callback) => {
|
|
3656
3656
|
const request = event.Records[0].cf.request;
|
|
3657
3657
|
const headers = request.headers;
|
|
3658
3658
|
|
|
@@ -3672,7 +3672,7 @@ exports.handler = (event, context, callback) => {
|
|
|
3672
3672
|
// Assign variant if not already assigned
|
|
3673
3673
|
if (!variant) {
|
|
3674
3674
|
const random = Math.random() * 100;
|
|
3675
|
-
|
|
3675
|
+
const _cumulative = 0;
|
|
3676
3676
|
|
|
3677
3677
|
${$.variants.map((J,_)=>{return`if (random < ${J.trafficPercentage+(_>0?$.variants.slice(0,_).reduce((Y,Q)=>Y+Q.trafficPercentage,0):0)}) {
|
|
3678
3678
|
variant = '${J.id}';
|
|
@@ -3680,7 +3680,7 @@ exports.handler = (event, context, callback) => {
|
|
|
3680
3680
|
}
|
|
3681
3681
|
|
|
3682
3682
|
// Set variant cookie
|
|
3683
|
-
const
|
|
3683
|
+
const _response = {
|
|
3684
3684
|
status: '200',
|
|
3685
3685
|
statusDescription: 'OK',
|
|
3686
3686
|
headers: {
|
|
@@ -3733,7 +3733,7 @@ const log = require('SyntheticsLogger');
|
|
|
3733
3733
|
|
|
3734
3734
|
const apiCheck = async function () {
|
|
3735
3735
|
const page = await synthetics.getPage();
|
|
3736
|
-
let
|
|
3736
|
+
let _response;
|
|
3737
3737
|
|
|
3738
3738
|
${$.endpoints.map((Y,Q)=>`
|
|
3739
3739
|
// Endpoint ${Q+1}: ${Y.method} ${Y.path}
|
|
@@ -3944,7 +3944,7 @@ async function indexDocument(doc) {
|
|
|
3944
3944
|
});
|
|
3945
3945
|
}
|
|
3946
3946
|
`;static getIndexMapping(){return{mappings:{properties:{messageId:{type:"keyword"},from:{type:"keyword"},fromName:{type:"text"},to:{type:"keyword"},toName:{type:"text"},cc:{type:"keyword"},subject:{type:"text",analyzer:"standard",fields:{keyword:{type:"keyword"}}},body:{type:"text",analyzer:"standard"},bodyPreview:{type:"text"},date:{type:"date"},receivedAt:{type:"date"},hasAttachments:{type:"boolean"},attachmentNames:{type:"keyword"},labels:{type:"keyword"},folder:{type:"keyword"},threadId:{type:"keyword"},isRead:{type:"boolean"},isStarred:{type:"boolean"},mailbox:{type:"keyword"}}},settings:{number_of_shards:1,number_of_replicas:0}}}static buildSearchQuery($){let J=[],_=[];if($.query)J.push({multi_match:{query:$.query,fields:["subject^3","body","fromName","toName"],type:"best_fields",fuzziness:"AUTO"}});if($.from)_.push({term:{from:$.from}});if($.to)_.push({term:{to:$.to}});if($.subject)J.push({match_phrase:{subject:$.subject}});if($.hasAttachments!==void 0)_.push({term:{hasAttachments:$.hasAttachments}});if($.folder)_.push({term:{folder:$.folder}});if($.labels&&$.labels.length>0)_.push({terms:{labels:$.labels}});if($.isRead!==void 0)_.push({term:{isRead:$.isRead}});if($.dateFrom||$.dateTo){let W={date:{}};if($.dateFrom)W.date.gte=$.dateFrom;if($.dateTo)W.date.lte=$.dateTo;_.push({range:W})}let Y={bool:{}};if(J.length>0)Y.bool.must=J;if(_.length>0)Y.bool.filter=_;if(J.length===0&&_.length===0)Y.bool.must=[{match_all:{}}];let Q=[];if($.sort==="relevance"&&$.query)Q.push({_score:$.sortOrder||"desc"});return Q.push({date:$.sortOrder||"desc"}),{query:Y,sort:Q,from:$.offset||0,size:$.limit||20,highlight:{fields:{subject:{},body:{fragment_size:150,number_of_fragments:3}}}}}}class X2{static ThreadingLambdaCode=`
|
|
3947
|
-
const { S3Client, GetObjectCommand, PutObjectCommand
|
|
3947
|
+
const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
|
|
3948
3948
|
const crypto = require('crypto');
|
|
3949
3949
|
|
|
3950
3950
|
const s3 = new S3Client({});
|
|
@@ -3994,7 +3994,7 @@ exports.handler = async (event) => {
|
|
|
3994
3994
|
return { statusCode: 200 };
|
|
3995
3995
|
};
|
|
3996
3996
|
|
|
3997
|
-
function generateThreadId(subject, from,
|
|
3997
|
+
function generateThreadId(subject, from, _to) {
|
|
3998
3998
|
// Normalize subject (remove Re:, Fwd:, etc.)
|
|
3999
3999
|
const normalizedSubject = subject
|
|
4000
4000
|
.replace(/^(Re|Fwd|Fw|RE|FWD|FW):\\s*/gi, '')
|
|
@@ -4207,7 +4207,7 @@ function buildRawEmail(email) {
|
|
|
4207
4207
|
return raw;
|
|
4208
4208
|
}
|
|
4209
4209
|
`;static createSchedulerLambda($){return{[`${$.slug}EmailSchedulerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-email-scheduler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:300,MemorySize:256,Code:{ZipFile:E2.SchedulerLambdaCode},Environment:{Variables:{EMAIL_BUCKET:$.emailBucket}}}}}}static createSchedulerRule($){return{[`${$.slug}EmailSchedulerRule`]:{Type:"AWS::Events::Rule",Properties:{Name:`${$.slug}-email-scheduler`,Description:"Trigger email scheduler every minute",ScheduleExpression:$.scheduleExpression||"rate(1 minute)",State:"ENABLED",Targets:[{Id:"EmailSchedulerTarget",Arn:$.lambdaArn}]}},[`${$.slug}EmailSchedulerPermission`]:{Type:"AWS::Lambda::Permission",Properties:{FunctionName:$.lambdaArn,Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:{"Fn::GetAtt":[`${$.slug}EmailSchedulerRule`,"Arn"]}}}}}static async scheduleEmail($){let{s3Client:J,bucket:_,email:Y,scheduledFor:Q,timezone:W}=$,U=`sched-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Z={id:U,email:Y,scheduledFor:typeof Q==="string"?Q:Q.toISOString(),timezone:W,status:"pending",createdAt:new Date().toISOString()};return await J.send({Bucket:_,Key:`scheduled/${U}.json`,Body:JSON.stringify(Z,null,2),ContentType:"application/json"}),Z}static async cancelScheduledEmail($){let{s3Client:J,bucket:_,id:Y}=$;try{let Q=await J.send({Bucket:_,Key:`scheduled/${Y}.json`}),W=JSON.parse(Q.Body);if(W.status!=="pending")return!1;return W.status="cancelled",await J.send({Bucket:_,Key:`scheduled/${Y}.json`,Body:JSON.stringify(W,null,2),ContentType:"application/json"}),!0}catch{return!1}}static async listScheduledEmails($){let{s3Client:J,bucket:_,status:Y}=$,Q=await J.send({Bucket:_,Prefix:"scheduled/"}),W=[];for(let U of Q.Contents||[]){if(!U.Key.endsWith(".json"))continue;try{let Z=await J.send({Bucket:_,Key:U.Key}),O=JSON.parse(Z.Body);if(!Y||O.status===Y)W.push(O)}catch{}}return W.sort((U,Z)=>new Date(U.scheduledFor).getTime()-new Date(Z.scheduledFor).getTime()),W}}class o${static TrackingPixelLambdaCode=`
|
|
4210
|
-
const { DynamoDBClient, UpdateItemCommand
|
|
4210
|
+
const { DynamoDBClient, UpdateItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
4211
4211
|
|
|
4212
4212
|
const dynamodb = new DynamoDBClient({});
|
|
4213
4213
|
const ANALYTICS_TABLE = process.env.ANALYTICS_TABLE;
|
|
@@ -4416,7 +4416,7 @@ exports.handler = async (event) => {
|
|
|
4416
4416
|
console.log('Template render request:', JSON.stringify(event, null, 2));
|
|
4417
4417
|
|
|
4418
4418
|
try {
|
|
4419
|
-
const { templateId, data, locale, timezone } = JSON.parse(event.body || '{}');
|
|
4419
|
+
const { templateId, data, locale: _locale, timezone: _timezone } = JSON.parse(event.body || '{}');
|
|
4420
4420
|
|
|
4421
4421
|
if (!templateId) {
|
|
4422
4422
|
return {
|
|
@@ -4467,19 +4467,19 @@ function renderTemplate(template, data) {
|
|
|
4467
4467
|
});
|
|
4468
4468
|
|
|
4469
4469
|
// Handle {{#if condition}}...{{/if}} syntax
|
|
4470
|
-
result = result.replace(/\\{\\{#if\\s+([\\w.]+)\\}\\}([\\s\\S]*?)\\{\\{\\/if\\}\\}/g, (
|
|
4470
|
+
result = result.replace(/\\{\\{#if\\s+([\\w.]+)\\}\\}([\\s\\S]*?)\\{\\{\\/if\\}\\}/g, (_match, key, content) => {
|
|
4471
4471
|
const value = getNestedValue(data, key);
|
|
4472
4472
|
return value ? content : '';
|
|
4473
4473
|
});
|
|
4474
4474
|
|
|
4475
4475
|
// Handle {{#unless condition}}...{{/unless}} syntax
|
|
4476
|
-
result = result.replace(/\\{\\{#unless\\s+([\\w.]+)\\}\\}([\\s\\S]*?)\\{\\{\\/unless\\}\\}/g, (
|
|
4476
|
+
result = result.replace(/\\{\\{#unless\\s+([\\w.]+)\\}\\}([\\s\\S]*?)\\{\\{\\/unless\\}\\}/g, (_match, key, content) => {
|
|
4477
4477
|
const value = getNestedValue(data, key);
|
|
4478
4478
|
return !value ? content : '';
|
|
4479
4479
|
});
|
|
4480
4480
|
|
|
4481
4481
|
// Handle {{#each array}}...{{/each}} syntax
|
|
4482
|
-
result = result.replace(/\\{\\{#each\\s+([\\w.]+)\\}\\}([\\s\\S]*?)\\{\\{\\/each\\}\\}/g, (
|
|
4482
|
+
result = result.replace(/\\{\\{#each\\s+([\\w.]+)\\}\\}([\\s\\S]*?)\\{\\{\\/each\\}\\}/g, (_match, key, content) => {
|
|
4483
4483
|
const array = getNestedValue(data, key);
|
|
4484
4484
|
if (!Array.isArray(array)) return '';
|
|
4485
4485
|
return array.map((item, index) => {
|
|
@@ -4661,7 +4661,7 @@ The {{appName}} Team`,variables:["appName","userName","resetUrl","expiresIn"],ca
|
|
|
4661
4661
|
<p>Best regards,<br>The {{appName}} Team</p>
|
|
4662
4662
|
</body>
|
|
4663
4663
|
</html>`,variables:["invoiceNumber","customerName","period","items","total","paymentUrl","appName"],category:"billing"}};static createTemplateBucket($){return{[`${$.slug}EmailTemplateBucket`]:{Type:"AWS::S3::Bucket",Properties:{BucketName:`${$.slug}-email-templates`,VersioningConfiguration:{Status:"Enabled"}}}}}static createTemplateRendererLambda($){return{[`${$.slug}TemplateRendererLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-template-renderer`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:B$.TemplateRendererCode},Environment:{Variables:{TEMPLATE_BUCKET:$.templateBucket}}}}}}static render($,J){if(!$||!J)return $;let _=$;return _=_.replace(/\{\{\s*([\w.]+)\s*\}\}/g,(Y,Q)=>{let W=B$.getNestedValue(J,Q);return W!==void 0?String(W):Y}),_=_.replace(/\{\{#if\s+([\w.]+)\}\}([\s\S]*?)\{\{\/if\}\}/g,(Y,Q,W)=>{return B$.getNestedValue(J,Q)?W:""}),_=_.replace(/\{\{#unless\s+([\w.]+)\}\}([\s\S]*?)\{\{\/unless\}\}/g,(Y,Q,W)=>{return!B$.getNestedValue(J,Q)?W:""}),_=_.replace(/\{\{#each\s+([\w.]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(Y,Q,W)=>{let U=B$.getNestedValue(J,Q);if(!Array.isArray(U))return"";return U.map((Z,O)=>{let z=W;if(z=z.replace(/\{\{this\}\}/g,String(Z)),z=z.replace(/\{\{@index\}\}/g,String(O)),typeof Z==="object")Object.entries(Z).forEach(([H,G])=>{z=z.replace(new RegExp(`\\{\\{\\s*${H}\\s*\\}\\}`,"g"),String(G))});return z}).join("")}),_}static getNestedValue($,J){return J.split(".").reduce((_,Y)=>_?.[Y],$)}static extractVariables($){let J=new Set,_=$.matchAll(/\{\{\s*([\w.]+)\s*\}\}/g);for(let Q of _)if(!Q[1].startsWith("#")&&!Q[1].startsWith("/")&&!Q[1].startsWith("@"))J.add(Q[1].split(".")[0]);let Y=$.matchAll(/\{\{#(?:if|unless|each)\s+([\w.]+)\}\}/g);for(let Q of Y)J.add(Q[1].split(".")[0]);return Array.from(J)}}class V2{static SharedMailboxLambdaCode=`
|
|
4664
|
-
const { S3Client, GetObjectCommand
|
|
4664
|
+
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
|
|
4665
4665
|
const { DynamoDBClient, GetItemCommand, PutItemCommand, QueryCommand, UpdateItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
4666
4666
|
|
|
4667
4667
|
const s3 = new S3Client({});
|
|
@@ -4823,7 +4823,7 @@ async function assignMessage(mailboxId, data) {
|
|
|
4823
4823
|
};
|
|
4824
4824
|
}
|
|
4825
4825
|
|
|
4826
|
-
async function getMailboxMessages(mailboxId,
|
|
4826
|
+
async function getMailboxMessages(mailboxId, _queryParams) {
|
|
4827
4827
|
const mailbox = await getMailbox(mailboxId);
|
|
4828
4828
|
if (mailbox.statusCode !== 200) return mailbox;
|
|
4829
4829
|
|
|
@@ -5506,8 +5506,8 @@ exports.handler = async (event) => {
|
|
|
5506
5506
|
return { statusCode: 200, body: 'OK' };
|
|
5507
5507
|
};
|
|
5508
5508
|
`;var KJ={};c0(KJ,{IVRBuilder:()=>I$,Callbacks:()=>m1,CallRecording:()=>j2,CallAnalytics:()=>q2});class j2{static RecordingProcessorCode=`
|
|
5509
|
-
const { S3Client, GetObjectCommand
|
|
5510
|
-
const { TranscribeClient, StartTranscriptionJobCommand
|
|
5509
|
+
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
|
|
5510
|
+
const { TranscribeClient, StartTranscriptionJobCommand } = require('@aws-sdk/client-transcribe');
|
|
5511
5511
|
const { DynamoDBClient, PutItemCommand, UpdateItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
5512
5512
|
|
|
5513
5513
|
const s3 = new S3Client({});
|
|
@@ -5695,7 +5695,7 @@ exports.handler = async (event) => {
|
|
|
5695
5695
|
return { statusCode: 200 };
|
|
5696
5696
|
};
|
|
5697
5697
|
`;static createRecordingsTable($){return{[`${$.slug}CallRecordingsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-call-recordings`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"recordingId",AttributeType:"S"},{AttributeName:"transcriptionJobName",AttributeType:"S"}],KeySchema:[{AttributeName:"recordingId",KeyType:"HASH"}],GlobalSecondaryIndexes:[{IndexName:"job-index",KeySchema:[{AttributeName:"transcriptionJobName",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createRecordingProcessorLambda($){return{[`${$.slug}RecordingProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-recording-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:60,MemorySize:256,Code:{ZipFile:j2.RecordingProcessorCode},Environment:{Variables:{RECORDING_BUCKET:$.recordingBucket,RECORDINGS_TABLE:$.recordingsTable}}}}}}}class I${nodes=[];connections=[];startNodeId="";static create($){return new I$}start(){let $={id:this.generateId(),type:"start",position:{x:0,y:0},config:{}};return this.nodes.push($),this.startNodeId=$.id,this}playPrompt($,J){let _={id:this.generateId(),type:"play-prompt",position:{x:0,y:0},config:{text:$,textType:J?.ssml?"ssml":"text",voice:J?.voice||"Joanna"}};return this.nodes.push(_),this.connectToLast(_.id),this}getInput($,J){let _={id:this.generateId(),type:"get-input",position:{x:0,y:0},config:{prompt:$,maxDigits:J?.maxDigits||1,timeout:J?.timeout||5,errorPrompt:J?.errorPrompt||"Sorry, I didn't get that."}};return this.nodes.push(_),this.connectToLast(_.id),this}menu($,J){let _={id:this.generateId(),type:"menu",position:{x:0,y:0},config:{prompt:$,options:J}};return this.nodes.push(_),this.connectToLast(_.id),this}transferToQueue($,J){let _={id:this.generateId(),type:"transfer-queue",position:{x:0,y:0},config:{queueArn:$,priority:J?.priority||5}};return this.nodes.push(_),this.connectToLast(_.id),this}transferToPhone($){let J={id:this.generateId(),type:"transfer-phone",position:{x:0,y:0},config:{phoneNumber:$}};return this.nodes.push(J),this.connectToLast(J.id),this}invokeLambda($,J){let _={id:this.generateId(),type:"invoke-lambda",position:{x:0,y:0},config:{functionArn:$,timeout:J?.timeout||8}};return this.nodes.push(_),this.connectToLast(_.id),this}setAttribute($,J){let _={id:this.generateId(),type:"set-attribute",position:{x:0,y:0},config:{key:$,value:J}};return this.nodes.push(_),this.connectToLast(_.id),this}checkHours($){let J={id:this.generateId(),type:"check-hours",position:{x:0,y:0},config:{hoursOfOperationArn:$}};return this.nodes.push(J),this.connectToLast(J.id),this}recordVoicemail($){let J={id:this.generateId(),type:"record-voicemail",position:{x:0,y:0},config:{maxDuration:$?.maxDuration||120,greeting:$?.greeting||"Please leave a message after the beep.",beep:$?.beep!==!1}};return this.nodes.push(J),this.connectToLast(J.id),this}wait($){let J={id:this.generateId(),type:"wait",position:{x:0,y:0},config:{seconds:$}};return this.nodes.push(J),this.connectToLast(J.id),this}disconnect(){let $={id:this.generateId(),type:"disconnect",position:{x:0,y:0},config:{}};return this.nodes.push($),this.connectToLast($.id),this}build(){return{id:this.generateId(),name:"IVR Flow",nodes:this.nodes,connections:this.connections,startNodeId:this.startNodeId,version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}toContactFlow(){let $=[],J=new Map(this.nodes.map((Y)=>[Y.id,Y]));for(let Y of this.nodes){let Q=this.nodeToAction(Y,J);if(Q)$.push(Q)}let _={Version:"2019-10-30",StartAction:this.startNodeId,Actions:$};return JSON.stringify(_,null,2)}nodeToAction($,J){let _=this.getNextNodeId($.id),Y={NextAction:_||"disconnect",Errors:[{NextAction:"disconnect"}]};switch($.type){case"start":return null;case"play-prompt":return{Identifier:$.id,Type:"MessageParticipant",Parameters:{Text:$.config.text,TextType:$.config.textType},Transitions:Y};case"get-input":return{Identifier:$.id,Type:"GetParticipantInput",Parameters:{Text:$.config.prompt,InputTimeLimitSeconds:$.config.timeout,MaxDigits:$.config.maxDigits},Transitions:{...Y,Conditions:[]}};case"transfer-queue":return{Identifier:$.id,Type:"TransferToQueue",Parameters:{QueueId:$.config.queueArn},Transitions:Y};case"transfer-phone":return{Identifier:$.id,Type:"TransferToPhoneNumber",Parameters:{PhoneNumber:$.config.phoneNumber},Transitions:Y};case"invoke-lambda":return{Identifier:$.id,Type:"InvokeLambdaFunction",Parameters:{LambdaFunctionARN:$.config.functionArn,InvocationTimeLimitSeconds:$.config.timeout},Transitions:Y};case"set-attribute":return{Identifier:$.id,Type:"UpdateContactAttributes",Parameters:{Attributes:{[$.config.key]:$.config.value}},Transitions:Y};case"check-hours":return{Identifier:$.id,Type:"CheckHoursOfOperation",Parameters:{HoursOfOperationId:$.config.hoursOfOperationArn},Transitions:{NextAction:_,Conditions:[{NextAction:_,Condition:{Operator:"Equals",Operands:["True"]}}],Errors:[{NextAction:"disconnect"}]}};case"wait":return{Identifier:$.id,Type:"Wait",Parameters:{Seconds:$.config.seconds},Transitions:Y};case"disconnect":return{Identifier:$.id,Type:"DisconnectParticipant",Parameters:{},Transitions:{}};default:return null}}connectToLast($){if(this.nodes.length>1){let J=this.nodes[this.nodes.length-2];this.connections.push({id:this.generateId(),sourceNodeId:J.id,targetNodeId:$,sourcePort:"default"})}}getNextNodeId($){return this.connections.find((_)=>_.sourceNodeId===$)?.targetNodeId||null}generateId(){return`node-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}static Templates={basicSupport:()=>{return I$.create("Basic Support").start().playPrompt("Welcome to customer support.").menu("Press 1 for sales, 2 for support, or 3 to leave a message.",{"1":"sales","2":"support","3":"voicemail"})},afterHours:($)=>{return I$.create("After Hours").start().playPrompt($).recordVoicemail({greeting:"Please leave your name, number, and a brief message.",maxDuration:120}).playPrompt("Thank you for your message. Goodbye.").disconnect()},callbackRequest:($)=>{return I$.create("Callback Request").start().playPrompt("All agents are currently busy.").getInput("Press 1 to request a callback, or 2 to wait.",{maxDigits:1}).invokeLambda($).playPrompt("We will call you back shortly. Goodbye.").disconnect()}}}class q2{static MetricsAggregatorCode=`
|
|
5698
|
-
const { DynamoDBClient,
|
|
5698
|
+
const { DynamoDBClient, PutItemCommand, ScanCommand } = require('@aws-sdk/client-dynamodb');
|
|
5699
5699
|
|
|
5700
5700
|
const dynamodb = new DynamoDBClient({});
|
|
5701
5701
|
const CALL_LOG_TABLE = process.env.CALL_LOG_TABLE;
|
|
@@ -5892,7 +5892,7 @@ exports.handler = async (event) => {
|
|
|
5892
5892
|
}
|
|
5893
5893
|
};
|
|
5894
5894
|
`;static createMetricsTable($){return{[`${$.slug}CallMetricsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-call-metrics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"period",AttributeType:"S"}],KeySchema:[{AttributeName:"period",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createMetricsAggregatorLambda($){return{[`${$.slug}CallMetricsAggregatorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-call-metrics-aggregator`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:60,MemorySize:256,Code:{ZipFile:q2.MetricsAggregatorCode},Environment:{Variables:{CALL_LOG_TABLE:$.callLogTable,METRICS_TABLE:$.metricsTable}}}}}}static createMetricsSchedule($){return{[`${$.slug}CallMetricsSchedule`]:{Type:"AWS::Events::Rule",Properties:{Name:`${$.slug}-call-metrics-schedule`,Description:"Aggregate call metrics hourly",ScheduleExpression:"rate(1 hour)",State:"ENABLED",Targets:[{Id:"MetricsAggregatorTarget",Arn:$.lambdaArn}]}}}}}class m1{static CallbackRequestCode=`
|
|
5895
|
-
const { DynamoDBClient, PutItemCommand,
|
|
5895
|
+
const { DynamoDBClient, PutItemCommand, UpdateItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
5896
5896
|
const { ConnectClient, StartOutboundVoiceContactCommand } = require('@aws-sdk/client-connect');
|
|
5897
5897
|
const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
|
|
5898
5898
|
|
|
@@ -6258,7 +6258,7 @@ async function getCampaign(id) {
|
|
|
6258
6258
|
};
|
|
6259
6259
|
}
|
|
6260
6260
|
|
|
6261
|
-
async function listCampaigns(
|
|
6261
|
+
async function listCampaigns(_params) {
|
|
6262
6262
|
const result = await dynamodb.send(new ScanCommand({
|
|
6263
6263
|
TableName: CAMPAIGNS_TABLE,
|
|
6264
6264
|
}));
|
|
@@ -6352,7 +6352,7 @@ function unmarshallCampaign(item) {
|
|
|
6352
6352
|
};
|
|
6353
6353
|
}
|
|
6354
6354
|
`;static CampaignExecutorCode=`
|
|
6355
|
-
const { DynamoDBClient,
|
|
6355
|
+
const { DynamoDBClient, UpdateItemCommand, ScanCommand } = require('@aws-sdk/client-dynamodb');
|
|
6356
6356
|
const { PinpointClient, SendMessagesCommand } = require('@aws-sdk/client-pinpoint');
|
|
6357
6357
|
|
|
6358
6358
|
const dynamodb = new DynamoDBClient({});
|
|
@@ -6558,7 +6558,7 @@ function unmarshallCampaign(item) {
|
|
|
6558
6558
|
};
|
|
6559
6559
|
}
|
|
6560
6560
|
`;static createCampaignsTable($){return{[`${$.slug}SmsCampaignsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-sms-campaigns`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}}static createCampaignManagerLambda($){return{[`${$.slug}SmsCampaignManagerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-sms-campaign-manager`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:F2.CampaignManagerCode},Environment:{Variables:{CAMPAIGNS_TABLE:$.campaignsTable}}}}}}}class T2{static AnalyticsAggregatorCode=`
|
|
6561
|
-
const { DynamoDBClient, ScanCommand, PutItemCommand
|
|
6561
|
+
const { DynamoDBClient, ScanCommand, PutItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
6562
6562
|
|
|
6563
6563
|
const dynamodb = new DynamoDBClient({});
|
|
6564
6564
|
const MESSAGE_LOG_TABLE = process.env.MESSAGE_LOG_TABLE;
|
|
@@ -6751,7 +6751,7 @@ exports.handler = async (event) => {
|
|
|
6751
6751
|
return { statusCode: 200 };
|
|
6752
6752
|
};
|
|
6753
6753
|
`;static createAnalyticsTable($){return{[`${$.slug}SmsAnalyticsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-sms-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"period",AttributeType:"S"}],KeySchema:[{AttributeName:"period",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createDeliveryReportsTable($){return{[`${$.slug}SmsDeliveryReportsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-sms-delivery-reports`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createAnalyticsAggregatorLambda($){return{[`${$.slug}SmsAnalyticsAggregatorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-sms-analytics-aggregator`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:60,MemorySize:256,Code:{ZipFile:T2.AnalyticsAggregatorCode},Environment:{Variables:{MESSAGE_LOG_TABLE:$.messageLogTable,ANALYTICS_TABLE:$.analyticsTable}}}}}}}class w2{static MmsSenderCode=`
|
|
6754
|
-
const { S3Client, PutObjectCommand
|
|
6754
|
+
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
|
|
6755
6755
|
const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
|
|
6756
6756
|
const { DynamoDBClient, PutItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
6757
6757
|
|
|
@@ -7336,7 +7336,7 @@ exports.handler = async (event) => {
|
|
|
7336
7336
|
};
|
|
7337
7337
|
`.trim()}generateMessageHandlerCode(){return`
|
|
7338
7338
|
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
|
|
7339
|
-
const { DynamoDBDocumentClient, PutCommand, DeleteCommand, QueryCommand
|
|
7339
|
+
const { DynamoDBDocumentClient, PutCommand, DeleteCommand, QueryCommand } = require('@aws-sdk/lib-dynamodb');
|
|
7340
7340
|
const { ApiGatewayManagementApiClient, PostToConnectionCommand } = require('@aws-sdk/client-apigatewaymanagementapi');
|
|
7341
7341
|
|
|
7342
7342
|
const dynamoClient = new DynamoDBClient({});
|
|
@@ -7805,7 +7805,7 @@ const hasCerts = existsSync(\`\${CERT_PATH}/fullchain.pem\`) && existsSync(\`\${
|
|
|
7805
7805
|
|
|
7806
7806
|
if (hasCerts) {
|
|
7807
7807
|
// Start HTTPS server
|
|
7808
|
-
const
|
|
7808
|
+
const _httpsServer = Bun.serve({
|
|
7809
7809
|
port: HTTPS_PORT,
|
|
7810
7810
|
tls: {
|
|
7811
7811
|
cert: Bun.file(\`\${CERT_PATH}/fullchain.pem\`),
|
|
@@ -7878,4 +7878,4 @@ async function handleRequest(request: Request): Promise<Response> {
|
|
|
7878
7878
|
return new Response('Hello from Stacks!')
|
|
7879
7879
|
}
|
|
7880
7880
|
`}async function hq($){let{domain:J,challengeValue:_,hostedZoneId:Y,dnsProvider:Q,region:W="us-east-1"}=$;if(Q){let Z=await j0(Q).upsertRecord(J,{name:`_acme-challenge.${J}`,type:"TXT",content:_,ttl:60});if(!Z.success)throw Error(`Failed to create DNS challenge record: ${Z.message}`);return}if(Y){await new $0(W).changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:"ACME DNS-01 challenge",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:`_acme-challenge.${J}`,Type:"TXT",TTL:60,ResourceRecords:[{Value:`"${_}"`}]}}]}});return}throw Error("Either dnsProvider or hostedZoneId must be provided")}async function vq($){let{domain:J,challengeValue:_,hostedZoneId:Y,dnsProvider:Q,region:W="us-east-1"}=$;if(Q){let Z=await j0(Q).deleteRecord(J,{name:`_acme-challenge.${J}`,type:"TXT",content:_});if(!Z.success)console.warn(`Failed to delete DNS challenge record: ${Z.message}`);return}if(Y){await new $0(W).changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:"Remove ACME DNS-01 challenge",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:`_acme-challenge.${J}`,Type:"TXT",TTL:60,ResourceRecords:[{Value:`"${_}"`}]}}]}});return}throw Error("Either dnsProvider or hostedZoneId must be provided")}function bq($){try{let{execSync:J}=p("node:child_process"),_=J(`openssl x509 -checkend 2592000 -noout -in ${$}/cert.pem`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return!1}catch{return!0}}import{createHash as M5,createSign as nQ,generateKeyPairSync as j5}from"node:crypto";var q5={production:"https://acme-v02.api.letsencrypt.org/directory",staging:"https://acme-staging-v02.api.letsencrypt.org/directory"};class tQ{directoryUrl;email;accountKey;accountUrl=null;directory=null;nonce=null;constructor($){this.directoryUrl=$.staging?q5.staging:q5.production,this.email=$.email,this.accountKey=$.accountKey||this.generateAccountKey()}generateAccountKey(){let{privateKey:$}=j5("ec",{namedCurve:"P-256"});return $.export({type:"pkcs8",format:"pem"})}async getDirectory(){if(this.directory)return this.directory;let $=await fetch(this.directoryUrl);if(!$.ok)throw Error(`Failed to fetch ACME directory: ${$.status}`);return this.directory=await $.json(),this.directory}async getNonce(){if(this.nonce){let Y=this.nonce;return this.nonce=null,Y}let $=await this.getDirectory(),_=(await fetch($.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!_)throw Error("Failed to get nonce from ACME server");return _}getJwk(){let $=this.accountKey.split(`
|
|
7881
|
-
`).filter((W)=>!W.startsWith("-----")).join(""),J=Buffer.from($,"base64"),_=J.length-65,Y=J.subarray(_+1,_+33),Q=J.subarray(_+33,_+65);return{kty:"EC",crv:"P-256",x:this.base64UrlEncode(Y),y:this.base64UrlEncode(Q)}}getJwkThumbprint(){let $=this.getJwk(),J=JSON.stringify({crv:$.crv,kty:$.kty,x:$.x,y:$.y}),_=M5("sha256").update(J).digest();return this.base64UrlEncode(_)}base64UrlEncode($){return(typeof $==="string"?Buffer.from($):$).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async signPayload($,J){let _=await this.getNonce(),Y=this.getJwk(),Q={alg:"ES256",nonce:_,url:$};if(this.accountUrl)Q.kid=this.accountUrl;else Q.jwk=Y;let W=this.base64UrlEncode(JSON.stringify(Q)),U=J===""?"":this.base64UrlEncode(JSON.stringify(J)),Z=`${W}.${U}`,O=nQ("SHA256");O.update(Z);let z=O.sign(this.accountKey),H=z.subarray(4,4+z[3]),G=4+z[3]+2,B=z.subarray(G,G+z[G-1]),K=Buffer.alloc(32),E=Buffer.alloc(32);H.copy(K,32-H.length),B.copy(E,32-B.length);let V=Buffer.concat([K,E]);return JSON.stringify({protected:W,payload:U,signature:this.base64UrlEncode(V)})}async acmeRequest($,J){let _=await this.signPayload($,J),Y=await fetch($,{method:"POST",headers:{"Content-Type":"application/jose+json"},body:_}),Q=Y.headers.get("replay-nonce");if(Q)this.nonce=Q;let W,U=Y.headers.get("content-type");if(U?.includes("application/json")||U?.includes("application/problem+json"))W=await Y.json();else W=await Y.text();if(!Y.ok)throw Error(`ACME request failed: ${JSON.stringify(W)}`);return{body:W,headers:Y.headers}}async registerAccount(){let $=await this.getDirectory(),{body:J,headers:_}=await this.acmeRequest($.newAccount,{termsOfServiceAgreed:!0,contact:[`mailto:${this.email}`]}),Y=_.get("location");if(!Y)throw Error("No account URL returned");return this.accountUrl=Y,Y}async createOrder($){if(!this.accountUrl)await this.registerAccount();let J=await this.getDirectory(),{body:_,headers:Y}=await this.acmeRequest(J.newOrder,{identifiers:$.map((W)=>({type:"dns",value:W}))}),Q=Y.get("location");if(!Q)throw Error("No order URL returned");return{orderUrl:Q,authorizations:_.authorizations,finalize:_.finalize}}async getAuthorization($){let{body:J}=await this.acmeRequest($,""),_=J.identifier.value,Y=this.getJwkThumbprint(),Q=J.challenges.filter((W)=>W.type==="http-01"||W.type==="dns-01").map((W)=>{let U=`${W.token}.${Y}`;if(W.type==="http-01")return{type:"http-01",token:W.token,keyAuthorization:U,identifier:`/.well-known/acme-challenge/${W.token}`};else{let Z=this.base64UrlEncode(M5("sha256").update(U).digest());return{type:"dns-01",token:W.token,keyAuthorization:U,identifier:`_acme-challenge.${_}`,dnsValue:Z}}});return{domain:_,challenges:Q}}async respondToChallenge($){await this.acmeRequest($,{})}async waitForAuthorization($,J=30){for(let _=0;_<J;_++){let{body:Y}=await this.acmeRequest($,"");if(Y.status==="valid")return;if(Y.status==="invalid")throw Error(`Authorization failed: ${JSON.stringify(Y)}`);await new Promise((Q)=>setTimeout(Q,2000))}throw Error("Authorization timed out")}generateCsr($){let{privateKey:J,publicKey:_}=j5("rsa",{modulusLength:2048}),Y=J.export({type:"pkcs8",format:"pem"});return{csr:this.createSimpleCsr($,J),privateKey:Y}}createSimpleCsr($,J){throw Error("CSR generation requires additional implementation. Consider using the shell-based certbot approach instead.")}async finalizeOrder($,J){let{csr:_,privateKey:Y}=this.generateCsr(J),{body:Q}=await this.acmeRequest($,{csr:this.base64UrlEncode(Buffer.from(_,"base64"))}),W=Q.certificate;if(!W)throw Error("Certificate not immediately available - polling not implemented");let Z=await(await fetch(W)).text(),O=Z.split(/(?=-----BEGIN CERTIFICATE-----)/g),z=O[0],H=O.slice(1).join("");return{certificate:z,privateKey:Y,chain:H,fullchain:Z,expiresAt:new Date(Date.now()+7776000000)}}getAccountKey(){return this.accountKey}}Q9();l2();M$();export{hG as xrayManager,HH as withTimeout,Gz as withSecurity,Ez as withQueue,Hz as withMonitoring,Bz as withDatabase,Kz as withCache,Xz as withCDN,tY as validateTemplateSize,mY as validateTemplate,iY as validateResourceLimits,fz as validateCredentials,Iz as validateConfiguration,J4 as validateCommand,wH as validateAgainstSchema,c4 as validateAccountStructure,n2 as uploadStaticFiles,t6 as templateCache,IY as syntheticsManager,S4 as suggestRegions,D4 as suggestRegionPairs,pz as suggestQuotaIncrease,uz as suggestIAMPolicy,oH as suggestFlags,v7 as suggestCommand,dY as storageAdvancedManager,xK as staticSiteManager,j4 as stackDependencyManager,f9 as signRequestAsync,K0 as signRequest,hq as setupDns01Challenge,yY as serviceMeshManager,zH as sequence,DB as senderReputationManager,oG as securityScanningManager,DY as securityHubManager,nG as secretsRotationManager,vY as secretsManager,sH as searchCommands,bW as sanitizeName,fY as route53RoutingManager,TB as route53ResolverManager,fK as resourceManagementManager,x6 as resolveRegion,x$ as resolveCredentials,EH as requiresReplacement,hY as replicaManager,M4 as regionPairManager,YH as quickHash,RK as queueManagementManager,xY as progressiveDeploymentManager,GH as processInChunks,WY as previewNotifications,JY as previewManager,mG as performanceManager,z$ as parseXMLResponse,F6 as parseJSONResponse,OH as parallelWithRetry,ZH as parallelMap,t9 as parallel,b4 as organizationManager,bK as networkSecurityManager,bq as needsRenewal,K4 as multiRegionManager,v4 as multiAccountManager,uG as migrationManager,bG as metricsManager,D$ as mergeInfrastructure,j6 as makeAWSRequestOnce,q6 as makeAWSRequestAsync,J$ as makeAWSRequest,kY as logsManager,SW as loadCloudConfig,OB as lambdaVersionsManager,XB as lambdaVPCManager,UB as lambdaLayersManager,BB as lambdaDestinationsManager,VB as lambdaDLQManager,HB as lambdaConcurrencyManager,R6 as isWebCryptoAvailable,R4 as isValidRegion,L6 as isNodeCryptoAvailable,RH as isLocalDevelopment,tH as isLikelyTypo,t2 as invalidateCache,$B as imageScanningManager,hK as healthCheckManager,D7 as hashString,_H as hashManifest,S7 as hashFile,JH as hashDirectory,$H as hashBuffer,SY as guardDutyManager,V4 as globalResourceManager,vW as getTimestamp,w6 as getSigningKeyCacheSize,n6 as getRequiredPermissions,L4 as getRegionsByPricingTier,T4 as getRegionsByLocation,w4 as getRegionsByCompliance,P4 as getRegionStats,i$ as getRegion,u4 as getRecommendedStructure,lz as getQuotaUsageSummary,DH as getLocalEnvVars,AH as getLocalEndpoint,SH as getLocalCredentials,i9 as getLocalConfig,r6 as getErrorDetails,XH as getDiffSummary,jH as getDiffStats,MH as getDeploymentStrategy,t$ as getCredentials,iH as getContextualHelp,D_ as getConfig,$4 as getCommandUsage,A4 as getClosestRegion,F4 as getAllRegions,F7 as getAccountId,p2 as generateStaticSiteTemplate,a4 as generateScheduledWorkflow,YG as generateScheduledPipeline,OG as generateScheduledConfig,w as generateResourceName,_Y as generatePreviewWorkflow,_G as generatePreviewPipeline,HG as generateParallelConfig,s4 as generatePRPreviewWorkflow,i4 as generateMultiEnvWorkflow,JG as generateMultiEnvPipeline,ZG as generateMultiEnvConfig,o4 as generateMatrixWorkflow,QG as generateManualPipeline,j as generateLogicalId,kq as generateLetsEncryptUserData,Iq as generateHttpsServerCode,F5 as generateExternalDnsStaticSiteTemplate,t4 as generateDeploymentWorkflow,$G as generateDeploymentPipeline,UG as generateDeploymentConfig,d4 as generateCrossAccountRoleCF,QY as generateCostReportWorkflow,YY as generateCleanupWorkflow,zG as generateApprovalConfig,N6 as fromWebIdentity,S6 as fromSharedCredentials,A6 as fromEnvironment,P6 as fromECSMetadata,C6 as fromEC2Metadata,gH as formatTree,fH as formatTable,nH as formatSuggestion,C4 as formatRegionList,FY as formatRegion,uH as formatProgressBar,mH as formatList,lH as formatKeyValue,W4 as formatHistoryStats,Q4 as formatHistory,eH as formatFlagSuggestions,cH as formatDuration,uW as formatDiff,dH as formatBytes,m4 as formatAccountStructure,QH as findChangedFiles,jK as fifoQueueManager,O7 as extendPreset,PB as emailTemplateManager,AB as emailAnalyticsManager,LY as drManager,qB as dnssecManager,fQ as dnsProviders,FK as dlqMonitoringManager,KH as diffTemplates,y9 as detectServiceRegion,hz as detectMisconfigurations,yQ as detectDnsProvider,iQ as deployStaticSiteWithExternalDnsFull,W9 as deployStaticSiteWithExternalDns,w5 as deployStaticSiteFull,r2 as deployStaticSite,T5 as deleteStaticSite,P7 as defaultLocalConfig,y8 as defaultConfig,pG as databaseUserManager,E4 as crossRegionReferenceManager,tO as createWordPressPreset,Uz as createTraditionalWebAppPreset,fO as createStaticSitePreset,d6 as createS3Client,tJ as createRoute53Validator,$z as createRealtimeAppPreset,M6 as createPresignedUrlAsync,g9 as createPresignedUrl,zz as createPreset,rJ as createPorkbunValidator,cO as createNodeJsServerlessPreset,uO as createNodeJsServerPreset,PH as createMockAWS,oO as createMicroservicesPreset,Qz as createMLApiPreset,sO as createJamstackPreset,nJ as createGoDaddyValidator,lO as createFullStackAppPreset,w7 as createError,j0 as createDnsProvider,_z as createDataPipelinePreset,Fz as createCredentialProvider,rO as createApiBackendPreset,bY as containerRegistryManager,DW as config,Oz as composePresets,AY as cloudTrailManager,$Y as cloudConfigSchema,T6 as clearSigningKeyCache,vq as cleanupDns01Challenge,a6 as chunk,mz as checkServiceQuotas,gz as checkIAMPermissions,sG as certificateManager,VH as categorizeChanges,PY as canaryManager,_B as buildOptimizationManager,bO as buildCloudFormationTemplate,LB as bounceComplaintHandler,CY as blueGreenManager,wK as batchProcessingManager,UH as batch,wY as backupManager,RY as awsConfigManager,aH as autocomplete,gW as analyzeStackDiff,NY as abTestManager,m7 as XRayManager,b_ as Workflow,V5 as VoiceClient,L7 as ValidationError,W$ as UnifiedDnsValidator,H5 as TranslateClient,_9 as TranscribeClient,f2 as TextractClient,r9 as TemplateCache,C9 as TemplateBuilder,GY as TaskList,G$ as SyntheticsManager,u2 as SupportClient,A2 as StorageAdvancedManager,y0 as Storage,qJ as StaticSiteManager,LU as StacksIntegration,u7 as StackDependencyManager,HY as Spinner,c8 as SmsHandlers,E5 as SmsClient,XJ as SmsAdvanced,G2 as ServiceMeshManager,zJ as SenderReputationManager,s7 as SecurityScanningManager,H$ as SecurityHubManager,U0 as Security,t7 as SecretsRotationManager,eJ as SecretsManagerClient,z2 as SecretsManager,d$ as Secrets,c$ as Search,Y9 as SchedulerClient,aJ as STSClient,oJ as SSMClient,$5 as SQSClient,Z1 as SNSClient,w0 as SMS,U1 as SESClient,S0 as S3Error,o as S3Client,B2 as Route53RoutingManager,UJ as Route53ResolverManager,Q1 as Route53Provider,pJ as Route53DomainsClient,$0 as Route53Client,wJ as ResourceManagementManager,O2 as ReplicaManager,y2 as RekognitionClient,n0 as Registry,g7 as RegionPairManager,v1 as Redirects,NW as RealtimePresets,s6 as RateLimiter,EY as REPLContext,VY as REPLCommandBuilder,XY as REPL,f4 as RECOMMENDED_SCPS,TY as RECOMMENDED_ACCOUNT_STRUCTURES,W5 as RDSClient,PW as QueuePresets,jJ as QueueManagementManager,T0 as Queue,C_ as Pseudo,U2 as ProgressiveDeploymentManager,OY as ProgressBar,a9 as PreviewNotificationService,s9 as PreviewEnvironmentManager,_1 as PorkbunProvider,z5 as PollyClient,g8 as PhoneHandlers,KJ as PhoneAdvanced,t0 as Phone,G5 as PersonalizeClient,k0 as Permissions,r7 as PerformanceManager,Y0 as ParameterStore,c7 as OrganizationManager,U5 as OpenSearchClient,TJ as NetworkSecurityManager,a as Network,zY as MultiStepProgress,b7 as MultiRegionManager,d7 as MultiAccountManager,k1 as Monitoring,x7 as MockS3,k7 as MockDynamoDB,N7 as MockCloudFormation,p7 as MigrationManager,l7 as MetricsManager,I0 as Messaging,Z2 as LogsManager,$J as LambdaVersionsManager,YJ as LambdaVPCManager,e7 as LambdaLayersManager,_J as LambdaDestinationsManager,QJ as LambdaDLQManager,JJ as LambdaConcurrencyManager,_5 as LambdaClient,g2 as KendraClient,$$ as JobLoader,cY as InfrastructureGenerator,a7 as ImageScanningManager,$9 as IAMClient,FJ as HealthCheckManager,i6 as HashCache,Y2 as GuardDutyManager,Y1 as GoDaddyProvider,f7 as GlobalResourceManager,X as Fn,g$ as FileSystem,p9 as FileCache,EJ as FIFOQueueManager,B5 as EventBridgeClient,p6 as ErrorCodes,HJ as EmailTemplateManager,BJ as EmailHandlers,b2 as EmailClient,OJ as EmailAnalyticsManager,GJ as EmailAdvanced,_0 as Email,K5 as ElastiCacheClient,Q5 as ELBv2Client,sJ as ECSClient,iJ as ECRClient,cJ as EC2Client,U$ as DynamoDBClient,v2 as DnsProviderFactory,$2 as DisasterRecoveryManager,m6 as DeploymentError,R0 as Deployment,P_ as DependencyGraph,V0 as DebugLogger,n7 as DatabaseUserManager,O$ as Database,WJ as DNSSECManager,F0 as DNS,VJ as DLQMonitoringManager,D0 as DEFAULT_SERVICE_LIMITS,y7 as CrossRegionReferenceManager,_$ as CredentialError,H2 as ContainerRegistryManager,J9 as ConnectClient,c1 as ConfigurationError,g as Compute,O5 as ComprehendClient,A0 as Communication,MY as CommandHistory,Y5 as CloudWatchLogsClient,_2 as CloudTrailManager,c6 as CloudFrontClient,k6 as CloudFormationClient,Z7 as CloudFormationBuilder,i0 as CloudError,i7 as CertificateManager,a$ as CanaryManager,v_ as Cache,g4 as COMMON_CROSS_ACCOUNT_ROLES,x0 as CDN,o7 as BuildOptimizationManager,ZJ as BounceComplaintHandler,Q2 as BlueGreenManager,Z5 as BedrockRuntimeClient,MJ as BatchProcessingManager,e9 as BackupManager,L0 as Auth,z0 as AssetHasher,S$ as Arn,X5 as ApplicationAutoScalingClient,x9 as ApiGateway,tQ as AcmeClient,f0 as AWS_REGIONS,aZ as AWS_PSEUDO_PARAMETERS,J2 as AWSConfigManager,u0 as AWSCloudFrontClient,E$ as AWSCloudFormationClient,I as AWSClient,l6 as AWSAPIError,x1 as AI,q5 as ACME_DIRECTORIES,e1 as ACMDnsValidator,a0 as ACMClient,W2 as ABTestManager};
|
|
7881
|
+
`).filter((W)=>!W.startsWith("-----")).join(""),J=Buffer.from($,"base64"),_=J.length-65,Y=J.subarray(_+1,_+33),Q=J.subarray(_+33,_+65);return{kty:"EC",crv:"P-256",x:this.base64UrlEncode(Y),y:this.base64UrlEncode(Q)}}getJwkThumbprint(){let $=this.getJwk(),J=JSON.stringify({crv:$.crv,kty:$.kty,x:$.x,y:$.y}),_=M5("sha256").update(J).digest();return this.base64UrlEncode(_)}base64UrlEncode($){return(typeof $==="string"?Buffer.from($):$).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async signPayload($,J){let _=await this.getNonce(),Y=this.getJwk(),Q={alg:"ES256",nonce:_,url:$};if(this.accountUrl)Q.kid=this.accountUrl;else Q.jwk=Y;let W=this.base64UrlEncode(JSON.stringify(Q)),U=J===""?"":this.base64UrlEncode(JSON.stringify(J)),Z=`${W}.${U}`,O=nQ("SHA256");O.update(Z);let z=O.sign(this.accountKey),H=z.subarray(4,4+z[3]),G=4+z[3]+2,B=z.subarray(G,G+z[G-1]),K=Buffer.alloc(32),E=Buffer.alloc(32);H.copy(K,32-H.length),B.copy(E,32-B.length);let V=Buffer.concat([K,E]);return JSON.stringify({protected:W,payload:U,signature:this.base64UrlEncode(V)})}async acmeRequest($,J){let _=await this.signPayload($,J),Y=await fetch($,{method:"POST",headers:{"Content-Type":"application/jose+json"},body:_}),Q=Y.headers.get("replay-nonce");if(Q)this.nonce=Q;let W,U=Y.headers.get("content-type");if(U?.includes("application/json")||U?.includes("application/problem+json"))W=await Y.json();else W=await Y.text();if(!Y.ok)throw Error(`ACME request failed: ${JSON.stringify(W)}`);return{body:W,headers:Y.headers}}async registerAccount(){let $=await this.getDirectory(),{body:J,headers:_}=await this.acmeRequest($.newAccount,{termsOfServiceAgreed:!0,contact:[`mailto:${this.email}`]}),Y=_.get("location");if(!Y)throw Error("No account URL returned");return this.accountUrl=Y,Y}async createOrder($){if(!this.accountUrl)await this.registerAccount();let J=await this.getDirectory(),{body:_,headers:Y}=await this.acmeRequest(J.newOrder,{identifiers:$.map((W)=>({type:"dns",value:W}))}),Q=Y.get("location");if(!Q)throw Error("No order URL returned");return{orderUrl:Q,authorizations:_.authorizations,finalize:_.finalize}}async getAuthorization($){let{body:J}=await this.acmeRequest($,""),_=J.identifier.value,Y=this.getJwkThumbprint(),Q=J.challenges.filter((W)=>W.type==="http-01"||W.type==="dns-01").map((W)=>{let U=`${W.token}.${Y}`;if(W.type==="http-01")return{type:"http-01",token:W.token,keyAuthorization:U,identifier:`/.well-known/acme-challenge/${W.token}`};else{let Z=this.base64UrlEncode(M5("sha256").update(U).digest());return{type:"dns-01",token:W.token,keyAuthorization:U,identifier:`_acme-challenge.${_}`,dnsValue:Z}}});return{domain:_,challenges:Q}}async respondToChallenge($){await this.acmeRequest($,{})}async waitForAuthorization($,J=30){for(let _=0;_<J;_++){let{body:Y}=await this.acmeRequest($,"");if(Y.status==="valid")return;if(Y.status==="invalid")throw Error(`Authorization failed: ${JSON.stringify(Y)}`);await new Promise((Q)=>setTimeout(Q,2000))}throw Error("Authorization timed out")}generateCsr($){let{privateKey:J}=j5("rsa",{modulusLength:2048}),_=J.export({type:"pkcs8",format:"pem"});return{csr:this.createSimpleCsr($,J),privateKey:_}}createSimpleCsr($,J){throw Error("CSR generation requires additional implementation. Consider using the shell-based certbot approach instead.")}async finalizeOrder($,J){let{csr:_,privateKey:Y}=this.generateCsr(J),{body:Q}=await this.acmeRequest($,{csr:this.base64UrlEncode(Buffer.from(_,"base64"))}),W=Q.certificate;if(!W)throw Error("Certificate not immediately available - polling not implemented");let Z=await(await fetch(W)).text(),O=Z.split(/(?=-----BEGIN CERTIFICATE-----)/g),z=O[0],H=O.slice(1).join("");return{certificate:z,privateKey:Y,chain:H,fullchain:Z,expiresAt:new Date(Date.now()+7776000000)}}getAccountKey(){return this.accountKey}}Q9();l2();M$();export{hG as xrayManager,HH as withTimeout,Gz as withSecurity,Ez as withQueue,Hz as withMonitoring,Bz as withDatabase,Kz as withCache,Xz as withCDN,tY as validateTemplateSize,mY as validateTemplate,iY as validateResourceLimits,fz as validateCredentials,Iz as validateConfiguration,J4 as validateCommand,wH as validateAgainstSchema,c4 as validateAccountStructure,n2 as uploadStaticFiles,t6 as templateCache,IY as syntheticsManager,S4 as suggestRegions,D4 as suggestRegionPairs,pz as suggestQuotaIncrease,uz as suggestIAMPolicy,oH as suggestFlags,v7 as suggestCommand,dY as storageAdvancedManager,xK as staticSiteManager,j4 as stackDependencyManager,f9 as signRequestAsync,K0 as signRequest,hq as setupDns01Challenge,yY as serviceMeshManager,zH as sequence,DB as senderReputationManager,oG as securityScanningManager,DY as securityHubManager,nG as secretsRotationManager,vY as secretsManager,sH as searchCommands,bW as sanitizeName,fY as route53RoutingManager,TB as route53ResolverManager,fK as resourceManagementManager,x6 as resolveRegion,x$ as resolveCredentials,EH as requiresReplacement,hY as replicaManager,M4 as regionPairManager,YH as quickHash,RK as queueManagementManager,xY as progressiveDeploymentManager,GH as processInChunks,WY as previewNotifications,JY as previewManager,mG as performanceManager,z$ as parseXMLResponse,F6 as parseJSONResponse,OH as parallelWithRetry,ZH as parallelMap,t9 as parallel,b4 as organizationManager,bK as networkSecurityManager,bq as needsRenewal,K4 as multiRegionManager,v4 as multiAccountManager,uG as migrationManager,bG as metricsManager,D$ as mergeInfrastructure,j6 as makeAWSRequestOnce,q6 as makeAWSRequestAsync,J$ as makeAWSRequest,kY as logsManager,SW as loadCloudConfig,OB as lambdaVersionsManager,XB as lambdaVPCManager,UB as lambdaLayersManager,BB as lambdaDestinationsManager,VB as lambdaDLQManager,HB as lambdaConcurrencyManager,R6 as isWebCryptoAvailable,R4 as isValidRegion,L6 as isNodeCryptoAvailable,RH as isLocalDevelopment,tH as isLikelyTypo,t2 as invalidateCache,$B as imageScanningManager,hK as healthCheckManager,D7 as hashString,_H as hashManifest,S7 as hashFile,JH as hashDirectory,$H as hashBuffer,SY as guardDutyManager,V4 as globalResourceManager,vW as getTimestamp,w6 as getSigningKeyCacheSize,n6 as getRequiredPermissions,L4 as getRegionsByPricingTier,T4 as getRegionsByLocation,w4 as getRegionsByCompliance,P4 as getRegionStats,i$ as getRegion,u4 as getRecommendedStructure,lz as getQuotaUsageSummary,DH as getLocalEnvVars,AH as getLocalEndpoint,SH as getLocalCredentials,i9 as getLocalConfig,r6 as getErrorDetails,XH as getDiffSummary,jH as getDiffStats,MH as getDeploymentStrategy,t$ as getCredentials,iH as getContextualHelp,D_ as getConfig,$4 as getCommandUsage,A4 as getClosestRegion,F4 as getAllRegions,F7 as getAccountId,p2 as generateStaticSiteTemplate,a4 as generateScheduledWorkflow,YG as generateScheduledPipeline,OG as generateScheduledConfig,w as generateResourceName,_Y as generatePreviewWorkflow,_G as generatePreviewPipeline,HG as generateParallelConfig,s4 as generatePRPreviewWorkflow,i4 as generateMultiEnvWorkflow,JG as generateMultiEnvPipeline,ZG as generateMultiEnvConfig,o4 as generateMatrixWorkflow,QG as generateManualPipeline,j as generateLogicalId,kq as generateLetsEncryptUserData,Iq as generateHttpsServerCode,F5 as generateExternalDnsStaticSiteTemplate,t4 as generateDeploymentWorkflow,$G as generateDeploymentPipeline,UG as generateDeploymentConfig,d4 as generateCrossAccountRoleCF,QY as generateCostReportWorkflow,YY as generateCleanupWorkflow,zG as generateApprovalConfig,N6 as fromWebIdentity,S6 as fromSharedCredentials,A6 as fromEnvironment,P6 as fromECSMetadata,C6 as fromEC2Metadata,gH as formatTree,fH as formatTable,nH as formatSuggestion,C4 as formatRegionList,FY as formatRegion,uH as formatProgressBar,mH as formatList,lH as formatKeyValue,W4 as formatHistoryStats,Q4 as formatHistory,eH as formatFlagSuggestions,cH as formatDuration,uW as formatDiff,dH as formatBytes,m4 as formatAccountStructure,QH as findChangedFiles,jK as fifoQueueManager,O7 as extendPreset,PB as emailTemplateManager,AB as emailAnalyticsManager,LY as drManager,qB as dnssecManager,fQ as dnsProviders,FK as dlqMonitoringManager,KH as diffTemplates,y9 as detectServiceRegion,hz as detectMisconfigurations,yQ as detectDnsProvider,iQ as deployStaticSiteWithExternalDnsFull,W9 as deployStaticSiteWithExternalDns,w5 as deployStaticSiteFull,r2 as deployStaticSite,T5 as deleteStaticSite,P7 as defaultLocalConfig,y8 as defaultConfig,pG as databaseUserManager,E4 as crossRegionReferenceManager,tO as createWordPressPreset,Uz as createTraditionalWebAppPreset,fO as createStaticSitePreset,d6 as createS3Client,tJ as createRoute53Validator,$z as createRealtimeAppPreset,M6 as createPresignedUrlAsync,g9 as createPresignedUrl,zz as createPreset,rJ as createPorkbunValidator,cO as createNodeJsServerlessPreset,uO as createNodeJsServerPreset,PH as createMockAWS,oO as createMicroservicesPreset,Qz as createMLApiPreset,sO as createJamstackPreset,nJ as createGoDaddyValidator,lO as createFullStackAppPreset,w7 as createError,j0 as createDnsProvider,_z as createDataPipelinePreset,Fz as createCredentialProvider,rO as createApiBackendPreset,bY as containerRegistryManager,DW as config,Oz as composePresets,AY as cloudTrailManager,$Y as cloudConfigSchema,T6 as clearSigningKeyCache,vq as cleanupDns01Challenge,a6 as chunk,mz as checkServiceQuotas,gz as checkIAMPermissions,sG as certificateManager,VH as categorizeChanges,PY as canaryManager,_B as buildOptimizationManager,bO as buildCloudFormationTemplate,LB as bounceComplaintHandler,CY as blueGreenManager,wK as batchProcessingManager,UH as batch,wY as backupManager,RY as awsConfigManager,aH as autocomplete,gW as analyzeStackDiff,NY as abTestManager,m7 as XRayManager,b_ as Workflow,V5 as VoiceClient,L7 as ValidationError,W$ as UnifiedDnsValidator,H5 as TranslateClient,_9 as TranscribeClient,f2 as TextractClient,r9 as TemplateCache,C9 as TemplateBuilder,GY as TaskList,G$ as SyntheticsManager,u2 as SupportClient,A2 as StorageAdvancedManager,y0 as Storage,qJ as StaticSiteManager,LU as StacksIntegration,u7 as StackDependencyManager,HY as Spinner,c8 as SmsHandlers,E5 as SmsClient,XJ as SmsAdvanced,G2 as ServiceMeshManager,zJ as SenderReputationManager,s7 as SecurityScanningManager,H$ as SecurityHubManager,U0 as Security,t7 as SecretsRotationManager,eJ as SecretsManagerClient,z2 as SecretsManager,d$ as Secrets,c$ as Search,Y9 as SchedulerClient,aJ as STSClient,oJ as SSMClient,$5 as SQSClient,Z1 as SNSClient,w0 as SMS,U1 as SESClient,S0 as S3Error,o as S3Client,B2 as Route53RoutingManager,UJ as Route53ResolverManager,Q1 as Route53Provider,pJ as Route53DomainsClient,$0 as Route53Client,wJ as ResourceManagementManager,O2 as ReplicaManager,y2 as RekognitionClient,n0 as Registry,g7 as RegionPairManager,v1 as Redirects,NW as RealtimePresets,s6 as RateLimiter,EY as REPLContext,VY as REPLCommandBuilder,XY as REPL,f4 as RECOMMENDED_SCPS,TY as RECOMMENDED_ACCOUNT_STRUCTURES,W5 as RDSClient,PW as QueuePresets,jJ as QueueManagementManager,T0 as Queue,C_ as Pseudo,U2 as ProgressiveDeploymentManager,OY as ProgressBar,a9 as PreviewNotificationService,s9 as PreviewEnvironmentManager,_1 as PorkbunProvider,z5 as PollyClient,g8 as PhoneHandlers,KJ as PhoneAdvanced,t0 as Phone,G5 as PersonalizeClient,k0 as Permissions,r7 as PerformanceManager,Y0 as ParameterStore,c7 as OrganizationManager,U5 as OpenSearchClient,TJ as NetworkSecurityManager,a as Network,zY as MultiStepProgress,b7 as MultiRegionManager,d7 as MultiAccountManager,k1 as Monitoring,x7 as MockS3,k7 as MockDynamoDB,N7 as MockCloudFormation,p7 as MigrationManager,l7 as MetricsManager,I0 as Messaging,Z2 as LogsManager,$J as LambdaVersionsManager,YJ as LambdaVPCManager,e7 as LambdaLayersManager,_J as LambdaDestinationsManager,QJ as LambdaDLQManager,JJ as LambdaConcurrencyManager,_5 as LambdaClient,g2 as KendraClient,$$ as JobLoader,cY as InfrastructureGenerator,a7 as ImageScanningManager,$9 as IAMClient,FJ as HealthCheckManager,i6 as HashCache,Y2 as GuardDutyManager,Y1 as GoDaddyProvider,f7 as GlobalResourceManager,X as Fn,g$ as FileSystem,p9 as FileCache,EJ as FIFOQueueManager,B5 as EventBridgeClient,p6 as ErrorCodes,HJ as EmailTemplateManager,BJ as EmailHandlers,b2 as EmailClient,OJ as EmailAnalyticsManager,GJ as EmailAdvanced,_0 as Email,K5 as ElastiCacheClient,Q5 as ELBv2Client,sJ as ECSClient,iJ as ECRClient,cJ as EC2Client,U$ as DynamoDBClient,v2 as DnsProviderFactory,$2 as DisasterRecoveryManager,m6 as DeploymentError,R0 as Deployment,P_ as DependencyGraph,V0 as DebugLogger,n7 as DatabaseUserManager,O$ as Database,WJ as DNSSECManager,F0 as DNS,VJ as DLQMonitoringManager,D0 as DEFAULT_SERVICE_LIMITS,y7 as CrossRegionReferenceManager,_$ as CredentialError,H2 as ContainerRegistryManager,J9 as ConnectClient,c1 as ConfigurationError,g as Compute,O5 as ComprehendClient,A0 as Communication,MY as CommandHistory,Y5 as CloudWatchLogsClient,_2 as CloudTrailManager,c6 as CloudFrontClient,k6 as CloudFormationClient,Z7 as CloudFormationBuilder,i0 as CloudError,i7 as CertificateManager,a$ as CanaryManager,v_ as Cache,g4 as COMMON_CROSS_ACCOUNT_ROLES,x0 as CDN,o7 as BuildOptimizationManager,ZJ as BounceComplaintHandler,Q2 as BlueGreenManager,Z5 as BedrockRuntimeClient,MJ as BatchProcessingManager,e9 as BackupManager,L0 as Auth,z0 as AssetHasher,S$ as Arn,X5 as ApplicationAutoScalingClient,x9 as ApiGateway,tQ as AcmeClient,f0 as AWS_REGIONS,aZ as AWS_PSEUDO_PARAMETERS,J2 as AWSConfigManager,u0 as AWSCloudFrontClient,E$ as AWSCloudFormationClient,I as AWSClient,l6 as AWSAPIError,x1 as AI,q5 as ACME_DIRECTORIES,e1 as ACMDnsValidator,a0 as ACMClient,W2 as ABTestManager};
|