@stacksjs/ts-cloud 0.1.3 → 0.1.6

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.
Files changed (187) hide show
  1. package/README.md +98 -13
  2. package/dist/aws/acm.d.ts +129 -0
  3. package/dist/aws/application-autoscaling.d.ts +282 -0
  4. package/dist/aws/bedrock.d.ts +2292 -0
  5. package/dist/aws/client.d.ts +79 -0
  6. package/dist/aws/cloudformation.d.ts +105 -0
  7. package/dist/aws/cloudfront.d.ts +265 -0
  8. package/dist/aws/cloudwatch-logs.d.ts +48 -0
  9. package/dist/aws/comprehend.d.ts +505 -0
  10. package/dist/aws/connect.d.ts +377 -0
  11. package/dist/aws/deploy-imap.d.ts +14 -0
  12. package/dist/aws/dynamodb.d.ts +176 -0
  13. package/dist/aws/ec2.d.ts +272 -0
  14. package/dist/aws/ecr.d.ts +149 -0
  15. package/dist/aws/ecs.d.ts +162 -0
  16. package/dist/aws/elasticache.d.ts +71 -0
  17. package/dist/aws/elbv2.d.ts +248 -0
  18. package/dist/aws/email.d.ts +175 -0
  19. package/dist/aws/eventbridge.d.ts +142 -0
  20. package/dist/aws/iam.d.ts +638 -0
  21. package/dist/aws/imap-server.d.ts +119 -0
  22. package/{src/aws/index.ts → dist/aws/index.d.ts} +62 -83
  23. package/{src/aws/kendra.ts → dist/aws/kendra.d.ts} +71 -386
  24. package/dist/aws/lambda.d.ts +232 -0
  25. package/dist/aws/opensearch.d.ts +87 -0
  26. package/dist/aws/personalize.d.ts +516 -0
  27. package/dist/aws/polly.d.ts +214 -0
  28. package/dist/aws/rds.d.ts +240 -0
  29. package/dist/aws/rekognition.d.ts +543 -0
  30. package/dist/aws/route53-domains.d.ts +113 -0
  31. package/dist/aws/route53.d.ts +215 -0
  32. package/dist/aws/s3.d.ts +212 -0
  33. package/dist/aws/scheduler.d.ts +140 -0
  34. package/dist/aws/secrets-manager.d.ts +170 -0
  35. package/dist/aws/ses.d.ts +288 -0
  36. package/dist/aws/setup-phone.d.ts +0 -0
  37. package/dist/aws/setup-sms.d.ts +115 -0
  38. package/dist/aws/sms.d.ts +304 -0
  39. package/dist/aws/smtp-server.d.ts +61 -0
  40. package/dist/aws/sns.d.ts +117 -0
  41. package/dist/aws/sqs.d.ts +65 -0
  42. package/dist/aws/ssm.d.ts +179 -0
  43. package/dist/aws/sts.d.ts +15 -0
  44. package/dist/aws/support.d.ts +104 -0
  45. package/dist/aws/test-imap.d.ts +0 -0
  46. package/dist/aws/textract.d.ts +403 -0
  47. package/dist/aws/transcribe.d.ts +60 -0
  48. package/dist/aws/translate.d.ts +358 -0
  49. package/dist/aws/voice.d.ts +219 -0
  50. package/dist/bin/cli.js +1724 -0
  51. package/dist/config.d.ts +7 -0
  52. package/dist/deploy/index.d.ts +2 -0
  53. package/dist/deploy/static-site-external-dns.d.ts +51 -0
  54. package/dist/deploy/static-site.d.ts +71 -0
  55. package/dist/dns/cloudflare.d.ts +52 -0
  56. package/dist/dns/godaddy.d.ts +38 -0
  57. package/dist/dns/index.d.ts +45 -0
  58. package/dist/dns/porkbun.d.ts +18 -0
  59. package/dist/dns/route53-adapter.d.ts +38 -0
  60. package/{src/dns/types.ts → dist/dns/types.d.ts} +26 -63
  61. package/dist/dns/validator.d.ts +78 -0
  62. package/dist/generators/index.d.ts +1 -0
  63. package/dist/generators/infrastructure.d.ts +30 -0
  64. package/{src/index.ts → dist/index.d.ts} +70 -93
  65. package/dist/index.js +7881 -0
  66. package/dist/push/apns.d.ts +60 -0
  67. package/dist/push/fcm.d.ts +117 -0
  68. package/dist/push/index.d.ts +14 -0
  69. package/dist/security/pre-deploy-scanner.d.ts +69 -0
  70. package/dist/ssl/acme-client.d.ts +67 -0
  71. package/dist/ssl/index.d.ts +2 -0
  72. package/dist/ssl/letsencrypt.d.ts +48 -0
  73. package/dist/types.d.ts +1 -0
  74. package/dist/utils/cli.d.ts +123 -0
  75. package/dist/validation/index.d.ts +1 -0
  76. package/dist/validation/template.d.ts +23 -0
  77. package/package.json +8 -8
  78. package/bin/cli.ts +0 -133
  79. package/bin/commands/analytics.ts +0 -328
  80. package/bin/commands/api.ts +0 -379
  81. package/bin/commands/assets.ts +0 -221
  82. package/bin/commands/audit.ts +0 -501
  83. package/bin/commands/backup.ts +0 -682
  84. package/bin/commands/cache.ts +0 -294
  85. package/bin/commands/cdn.ts +0 -281
  86. package/bin/commands/config.ts +0 -202
  87. package/bin/commands/container.ts +0 -105
  88. package/bin/commands/cost.ts +0 -208
  89. package/bin/commands/database.ts +0 -401
  90. package/bin/commands/deploy.ts +0 -674
  91. package/bin/commands/domain.ts +0 -397
  92. package/bin/commands/email.ts +0 -423
  93. package/bin/commands/environment.ts +0 -285
  94. package/bin/commands/events.ts +0 -424
  95. package/bin/commands/firewall.ts +0 -145
  96. package/bin/commands/function.ts +0 -116
  97. package/bin/commands/generate.ts +0 -280
  98. package/bin/commands/git.ts +0 -139
  99. package/bin/commands/iam.ts +0 -464
  100. package/bin/commands/index.ts +0 -48
  101. package/bin/commands/init.ts +0 -120
  102. package/bin/commands/logs.ts +0 -148
  103. package/bin/commands/network.ts +0 -579
  104. package/bin/commands/notify.ts +0 -489
  105. package/bin/commands/queue.ts +0 -407
  106. package/bin/commands/scheduler.ts +0 -370
  107. package/bin/commands/secrets.ts +0 -54
  108. package/bin/commands/server.ts +0 -629
  109. package/bin/commands/shared.ts +0 -97
  110. package/bin/commands/ssl.ts +0 -138
  111. package/bin/commands/stack.ts +0 -325
  112. package/bin/commands/status.ts +0 -385
  113. package/bin/commands/storage.ts +0 -450
  114. package/bin/commands/team.ts +0 -96
  115. package/bin/commands/tunnel.ts +0 -489
  116. package/bin/commands/utils.ts +0 -202
  117. package/build.ts +0 -15
  118. package/cloud +0 -2
  119. package/src/aws/acm.ts +0 -768
  120. package/src/aws/application-autoscaling.ts +0 -845
  121. package/src/aws/bedrock.ts +0 -4074
  122. package/src/aws/client.ts +0 -878
  123. package/src/aws/cloudformation.ts +0 -896
  124. package/src/aws/cloudfront.ts +0 -1531
  125. package/src/aws/cloudwatch-logs.ts +0 -154
  126. package/src/aws/comprehend.ts +0 -839
  127. package/src/aws/connect.ts +0 -1056
  128. package/src/aws/deploy-imap.ts +0 -384
  129. package/src/aws/dynamodb.ts +0 -340
  130. package/src/aws/ec2.ts +0 -1385
  131. package/src/aws/ecr.ts +0 -621
  132. package/src/aws/ecs.ts +0 -615
  133. package/src/aws/elasticache.ts +0 -301
  134. package/src/aws/elbv2.ts +0 -942
  135. package/src/aws/email.ts +0 -928
  136. package/src/aws/eventbridge.ts +0 -248
  137. package/src/aws/iam.ts +0 -1689
  138. package/src/aws/imap-server.ts +0 -2100
  139. package/src/aws/lambda.ts +0 -786
  140. package/src/aws/opensearch.ts +0 -158
  141. package/src/aws/personalize.ts +0 -977
  142. package/src/aws/polly.ts +0 -559
  143. package/src/aws/rds.ts +0 -888
  144. package/src/aws/rekognition.ts +0 -846
  145. package/src/aws/route53-domains.ts +0 -359
  146. package/src/aws/route53.ts +0 -1046
  147. package/src/aws/s3.ts +0 -2318
  148. package/src/aws/scheduler.ts +0 -571
  149. package/src/aws/secrets-manager.ts +0 -769
  150. package/src/aws/ses.ts +0 -1081
  151. package/src/aws/setup-phone.ts +0 -104
  152. package/src/aws/setup-sms.ts +0 -580
  153. package/src/aws/sms.ts +0 -1735
  154. package/src/aws/smtp-server.ts +0 -531
  155. package/src/aws/sns.ts +0 -758
  156. package/src/aws/sqs.ts +0 -382
  157. package/src/aws/ssm.ts +0 -807
  158. package/src/aws/sts.ts +0 -92
  159. package/src/aws/support.ts +0 -391
  160. package/src/aws/test-imap.ts +0 -86
  161. package/src/aws/textract.ts +0 -780
  162. package/src/aws/transcribe.ts +0 -108
  163. package/src/aws/translate.ts +0 -641
  164. package/src/aws/voice.ts +0 -1379
  165. package/src/config.ts +0 -35
  166. package/src/deploy/index.ts +0 -7
  167. package/src/deploy/static-site-external-dns.ts +0 -906
  168. package/src/deploy/static-site.ts +0 -1125
  169. package/src/dns/godaddy.ts +0 -412
  170. package/src/dns/index.ts +0 -183
  171. package/src/dns/porkbun.ts +0 -362
  172. package/src/dns/route53-adapter.ts +0 -414
  173. package/src/dns/validator.ts +0 -369
  174. package/src/generators/index.ts +0 -5
  175. package/src/generators/infrastructure.ts +0 -1660
  176. package/src/push/apns.ts +0 -452
  177. package/src/push/fcm.ts +0 -506
  178. package/src/push/index.ts +0 -58
  179. package/src/ssl/acme-client.ts +0 -478
  180. package/src/ssl/index.ts +0 -7
  181. package/src/ssl/letsencrypt.ts +0 -747
  182. package/src/types.ts +0 -2
  183. package/src/utils/cli.ts +0 -398
  184. package/src/validation/index.ts +0 -5
  185. package/src/validation/template.ts +0 -405
  186. package/test/index.test.ts +0 -128
  187. package/tsconfig.json +0 -18
@@ -0,0 +1,1724 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ import{createRequire as v9}from"node:module";var y9=Object.defineProperty;var c$=($,J)=>{for(var Y in J)y9($,Y,{get:J[Y],enumerable:!0,configurable:!0,set:(Q)=>J[Y]=()=>Q})};var Y$=($,J)=>()=>($&&(J=$($=0)),J);var Q$=v9(import.meta.url);function Y1($,J){let Y=[],Q=J.exec($);while(Q){let W=[];W.startIndex=J.lastIndex-Q[0].length;let U=Q.length;for(let Z=0;Z<U;Z++)W.push(Q[Z]);Y.push(W),Q=J.exec($)}return Y}function F5($){return typeof $<"u"}var dY=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",mY,cY,D0=function($){let J=cY.exec($);return!(J===null||typeof J>"u")};var Q1=Y$(()=>{mY="[:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]["+dY+"]*",cY=new RegExp("^"+mY+"$")});function R5($,J){J=Object.assign({},lY,J);let Y=[],Q=!1,W=!1;if($[0]==="\uFEFF")$=$.substr(1);for(let U=0;U<$.length;U++)if($[U]==="<"&&$[U+1]==="?"){if(U+=2,U=T5($,U),U.err)return U}else if($[U]==="<"){let Z=U;if(U++,$[U]==="!"){U=L5($,U);continue}else{let z=!1;if($[U]==="/")z=!0,U++;let H="";for(;U<$.length&&$[U]!==">"&&$[U]!==" "&&$[U]!=="\t"&&$[U]!==`
4
+ `&&$[U]!=="\r";U++)H+=$[U];if(H=H.trim(),H[H.length-1]==="/")H=H.substring(0,H.length-1),U--;if(!oY(H)){let O;if(H.trim().length===0)O="Invalid space after '<'.";else O="Tag '"+H+"' is an invalid name.";return E$("InvalidTag",O,P$($,U))}let K=aY($,U);if(K===!1)return E$("InvalidAttr","Attributes for '"+H+"' have open quote.",P$($,U));let B=K.value;if(U=K.index,B[B.length-1]==="/"){let O=U-B.length;B=B.substring(0,B.length-1);let X=A5(B,J);if(X===!0)Q=!0;else return E$(X.err.code,X.err.msg,P$($,O+X.err.line))}else if(z)if(!K.tagClosed)return E$("InvalidTag","Closing tag '"+H+"' doesn't have proper closing.",P$($,U));else if(B.trim().length>0)return E$("InvalidTag","Closing tag '"+H+"' can't have attributes or invalid starting.",P$($,Z));else if(Y.length===0)return E$("InvalidTag","Closing tag '"+H+"' has not been opened.",P$($,Z));else{let O=Y.pop();if(H!==O.tagName){let X=P$($,O.tagStartPos);return E$("InvalidTag","Expected closing tag '"+O.tagName+"' (opened in line "+X.line+", col "+X.col+") instead of closing tag '"+H+"'.",P$($,Z))}if(Y.length==0)W=!0}else{let O=A5(B,J);if(O!==!0)return E$(O.err.code,O.err.msg,P$($,U-B.length+O.err.line));if(W===!0)return E$("InvalidXml","Multiple possible root nodes found.",P$($,U));else if(J.unpairedTags.indexOf(H)!==-1);else Y.push({tagName:H,tagStartPos:Z});Q=!0}for(U++;U<$.length;U++)if($[U]==="<")if($[U+1]==="!"){U++,U=L5($,U);continue}else if($[U+1]==="?"){if(U=T5($,++U),U.err)return U}else break;else if($[U]==="&"){let O=iY($,U);if(O==-1)return E$("InvalidChar","char '&' is not expected.",P$($,U));U=O}else if(W===!0&&!w5($[U]))return E$("InvalidXml","Extra text at the end",P$($,U));if($[U]==="<")U--}}else{if(w5($[U]))continue;return E$("InvalidChar","char '"+$[U]+"' is not expected.",P$($,U))}if(!Q)return E$("InvalidXml","Start tag expected.",1);else if(Y.length==1)return E$("InvalidTag","Unclosed tag '"+Y[0].tagName+"'.",P$($,Y[0].tagStartPos));else if(Y.length>0)return E$("InvalidXml","Invalid '"+JSON.stringify(Y.map((U)=>U.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1});return!0}function w5($){return $===" "||$==="\t"||$===`
5
+ `||$==="\r"}function T5($,J){let Y=J;for(;J<$.length;J++)if($[J]=="?"||$[J]==" "){let Q=$.substr(Y,J-Y);if(J>5&&Q==="xml")return E$("InvalidXml","XML declaration allowed only at the start of the document.",P$($,J));else if($[J]=="?"&&$[J+1]==">"){J++;break}else continue}return J}function L5($,J){if($.length>J+5&&$[J+1]==="-"&&$[J+2]==="-"){for(J+=3;J<$.length;J++)if($[J]==="-"&&$[J+1]==="-"&&$[J+2]===">"){J+=2;break}}else if($.length>J+8&&$[J+1]==="D"&&$[J+2]==="O"&&$[J+3]==="C"&&$[J+4]==="T"&&$[J+5]==="Y"&&$[J+6]==="P"&&$[J+7]==="E"){let Y=1;for(J+=8;J<$.length;J++)if($[J]==="<")Y++;else if($[J]===">"){if(Y--,Y===0)break}}else if($.length>J+9&&$[J+1]==="["&&$[J+2]==="C"&&$[J+3]==="D"&&$[J+4]==="A"&&$[J+5]==="T"&&$[J+6]==="A"&&$[J+7]==="["){for(J+=8;J<$.length;J++)if($[J]==="]"&&$[J+1]==="]"&&$[J+2]===">"){J+=2;break}}return J}function aY($,J){let Y="",Q="",W=!1;for(;J<$.length;J++){if($[J]===pY||$[J]===rY)if(Q==="")Q=$[J];else if(Q!==$[J]);else Q="";else if($[J]===">"){if(Q===""){W=!0;break}}Y+=$[J]}if(Q!=="")return!1;return{value:Y,index:J,tagClosed:W}}function A5($,J){let Y=Y1($,nY),Q={};for(let W=0;W<Y.length;W++){if(Y[W][1].length===0)return E$("InvalidAttr","Attribute '"+Y[W][2]+"' has no space in starting.",m0(Y[W]));else if(Y[W][3]!==void 0&&Y[W][4]===void 0)return E$("InvalidAttr","Attribute '"+Y[W][2]+"' is without value.",m0(Y[W]));else if(Y[W][3]===void 0&&!J.allowBooleanAttributes)return E$("InvalidAttr","boolean attribute '"+Y[W][2]+"' is not allowed.",m0(Y[W]));let U=Y[W][2];if(!tY(U))return E$("InvalidAttr","Attribute '"+U+"' is an invalid name.",m0(Y[W]));if(!Q.hasOwnProperty(U))Q[U]=1;else return E$("InvalidAttr","Attribute '"+U+"' is repeated.",m0(Y[W]))}return!0}function sY($,J){let Y=/\d/;if($[J]==="x")J++,Y=/[\da-fA-F]/;for(;J<$.length;J++){if($[J]===";")return J;if(!$[J].match(Y))break}return-1}function iY($,J){if(J++,$[J]===";")return-1;if($[J]==="#")return J++,sY($,J);let Y=0;for(;J<$.length;J++,Y++){if($[J].match(/\w/)&&Y<20)continue;if($[J]===";")break;return-1}return J}function E$($,J,Y){return{err:{code:$,msg:J,line:Y.line||Y,col:Y.col}}}function tY($){return D0($)}function oY($){return D0($)}function P$($,J){let Y=$.substring(0,J).split(/\r?\n/);return{line:Y.length,col:Y[Y.length-1].length+1}}function m0($){return $.startIndex+$[1].length}var lY,pY='"',rY="'",nY;var S5=Y$(()=>{Q1();lY={allowBooleanAttributes:!1,unpairedTags:[]};nY=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g")});var eY,D5=function($){return Object.assign({},eY,$)};var P5=Y$(()=>{eY={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function($,J){return J},attributeValueProcessor:function($,J){return J},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function($,J,Y){return $},captureMetaData:!1}});class y${constructor($){this.tagname=$,this.child=[],this[":@"]={}}add($,J){if($==="__proto__")$="#__proto__";this.child.push({[$]:J})}addChild($,J){if($.tagname==="__proto__")$.tagname="#__proto__";if($[":@"]&&Object.keys($[":@"]).length>0)this.child.push({[$.tagname]:$.child,[":@"]:$[":@"]});else this.child.push({[$.tagname]:$.child});if(J!==void 0)this.child[this.child.length-1][W1]={startIndex:J}}static getMetaDataSymbol(){return W1}}var W1;var U1=Y$(()=>{if(typeof Symbol!=="function")W1="@@xmlMetadata";else W1=Symbol("XML Node Metadata")});class Z1{constructor($){this.suppressValidationErr=!$}readDocType($,J){let Y={};if($[J+3]==="O"&&$[J+4]==="C"&&$[J+5]==="T"&&$[J+6]==="Y"&&$[J+7]==="P"&&$[J+8]==="E"){J=J+9;let Q=1,W=!1,U=!1,Z="";for(;J<$.length;J++)if($[J]==="<"&&!U){if(W&&F0($,"!ENTITY",J)){J+=7;let z,H;if([z,H,J]=this.readEntityExp($,J+1,this.suppressValidationErr),H.indexOf("&")===-1){let K=z.replace(/[.\-+*:]/g,"\\.");Y[z]={regx:RegExp(`&${K};`,"g"),val:H}}}else if(W&&F0($,"!ELEMENT",J)){J+=8;let{index:z}=this.readElementExp($,J+1);J=z}else if(W&&F0($,"!ATTLIST",J))J+=8;else if(W&&F0($,"!NOTATION",J)){J+=9;let{index:z}=this.readNotationExp($,J+1,this.suppressValidationErr);J=z}else if(F0($,"!--",J))U=!0;else throw Error("Invalid DOCTYPE");Q++,Z=""}else if($[J]===">"){if(U){if($[J-1]==="-"&&$[J-2]==="-")U=!1,Q--}else Q--;if(Q===0)break}else if($[J]==="[")W=!0;else Z+=$[J];if(Q!==0)throw Error("Unclosed DOCTYPE")}else throw Error("Invalid Tag instead of DOCTYPE");return{entities:Y,i:J}}readEntityExp($,J){J=k$($,J);let Y="";while(J<$.length&&!/\s/.test($[J])&&$[J]!=='"'&&$[J]!=="'")Y+=$[J],J++;if(c0(Y),J=k$($,J),!this.suppressValidationErr){if($.substring(J,J+6).toUpperCase()==="SYSTEM")throw Error("External entities are not supported");else if($[J]==="%")throw Error("Parameter entities are not supported")}let Q="";return[J,Q]=this.readIdentifierVal($,J,"entity"),J--,[Y,Q,J]}readNotationExp($,J){J=k$($,J);let Y="";while(J<$.length&&!/\s/.test($[J]))Y+=$[J],J++;!this.suppressValidationErr&&c0(Y),J=k$($,J);let Q=$.substring(J,J+6).toUpperCase();if(!this.suppressValidationErr&&Q!=="SYSTEM"&&Q!=="PUBLIC")throw Error(`Expected SYSTEM or PUBLIC, found "${Q}"`);J+=Q.length,J=k$($,J);let W=null,U=null;if(Q==="PUBLIC"){if([J,W]=this.readIdentifierVal($,J,"publicIdentifier"),J=k$($,J),$[J]==='"'||$[J]==="'")[J,U]=this.readIdentifierVal($,J,"systemIdentifier")}else if(Q==="SYSTEM"){if([J,U]=this.readIdentifierVal($,J,"systemIdentifier"),!this.suppressValidationErr&&!U)throw Error("Missing mandatory system identifier for SYSTEM notation")}return{notationName:Y,publicIdentifier:W,systemIdentifier:U,index:--J}}readIdentifierVal($,J,Y){let Q="",W=$[J];if(W!=='"'&&W!=="'")throw Error(`Expected quoted string, found "${W}"`);J++;while(J<$.length&&$[J]!==W)Q+=$[J],J++;if($[J]!==W)throw Error(`Unterminated ${Y} value`);return J++,[J,Q]}readElementExp($,J){J=k$($,J);let Y="";while(J<$.length&&!/\s/.test($[J]))Y+=$[J],J++;if(!this.suppressValidationErr&&!D0(Y))throw Error(`Invalid element name: "${Y}"`);J=k$($,J);let Q="";if($[J]==="E"&&F0($,"MPTY",J))J+=4;else if($[J]==="A"&&F0($,"NY",J))J+=2;else if($[J]==="("){J++;while(J<$.length&&$[J]!==")")Q+=$[J],J++;if($[J]!==")")throw Error("Unterminated content model")}else if(!this.suppressValidationErr)throw Error(`Invalid Element Expression, found "${$[J]}"`);return{elementName:Y,contentModel:Q.trim(),index:J}}readAttlistExp($,J){J=k$($,J);let Y="";while(J<$.length&&!/\s/.test($[J]))Y+=$[J],J++;c0(Y),J=k$($,J);let Q="";while(J<$.length&&!/\s/.test($[J]))Q+=$[J],J++;if(!c0(Q))throw Error(`Invalid attribute name: "${Q}"`);J=k$($,J);let W="";if($.substring(J,J+8).toUpperCase()==="NOTATION"){if(W="NOTATION",J+=8,J=k$($,J),$[J]!=="(")throw Error(`Expected '(', found "${$[J]}"`);J++;let Z=[];while(J<$.length&&$[J]!==")"){let z="";while(J<$.length&&$[J]!=="|"&&$[J]!==")")z+=$[J],J++;if(z=z.trim(),!c0(z))throw Error(`Invalid notation name: "${z}"`);if(Z.push(z),$[J]==="|")J++,J=k$($,J)}if($[J]!==")")throw Error("Unterminated list of notations");J++,W+=" ("+Z.join("|")+")"}else{while(J<$.length&&!/\s/.test($[J]))W+=$[J],J++;let Z=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!Z.includes(W.toUpperCase()))throw Error(`Invalid attribute type: "${W}"`)}J=k$($,J);let U="";if($.substring(J,J+8).toUpperCase()==="#REQUIRED")U="#REQUIRED",J+=8;else if($.substring(J,J+7).toUpperCase()==="#IMPLIED")U="#IMPLIED",J+=7;else[J,U]=this.readIdentifierVal($,J,"ATTLIST");return{elementName:Y,attributeName:Q,attributeType:W,defaultValue:U,index:J}}}function F0($,J,Y){for(let Q=0;Q<J.length;Q++)if(J[Q]!==$[Y+Q+1])return!1;return!0}function c0($){if(D0($))return $;else throw Error(`Invalid entity name ${$}`)}var k$=($,J)=>{while(J<$.length&&/\s/.test($[J]))J++;return J};var C5=Y$(()=>{Q1()});function YJ($,J={}){if(J=Object.assign({},YQ,J),!$||typeof $!=="string")return $;let Y=$.trim();if(J.skipLike!==void 0&&J.skipLike.test(Y))return $;else if($==="0")return 0;else if(J.hex&&$Q.test(Y))return ZQ(Y,16);else if(Y.includes("e")||Y.includes("E"))return WQ($,Y,J);else{let Q=JQ.exec(Y);if(Q){let W=Q[1]||"",U=Q[2],Z=UQ(Q[3]),z=W?$[U.length+1]===".":$[U.length]===".";if(!J.leadingZeros&&(U.length>1||U.length===1&&!z))return $;else{let H=Number(Y),K=String(H);if(H===0)return H;if(K.search(/[eE]/)!==-1)if(J.eNotation)return H;else return $;else if(Y.indexOf(".")!==-1)if(K==="0")return H;else if(K===Z)return H;else if(K===`${W}${Z}`)return H;else return $;let B=U?Z:Y;if(U)return B===K||W+B===K?H:$;else return B===K||B===W+K?H:$}}else return $}}function WQ($,J,Y){if(!Y.eNotation)return $;let Q=J.match(QQ);if(Q){let W=Q[1]||"",U=Q[3].indexOf("e")===-1?"E":"e",Z=Q[2],z=W?$[Z.length+1]===U:$[Z.length]===U;if(Z.length>1&&z)return $;else if(Z.length===1&&(Q[3].startsWith(`.${U}`)||Q[3][0]===U))return Number(J);else if(Y.leadingZeros&&!z)return J=(Q[1]||"")+Q[3],Number(J);else return $}else return $}function UQ($){if($&&$.indexOf(".")!==-1){if($=$.replace(/0+$/,""),$===".")$="0";else if($[0]===".")$="0"+$;else if($[$.length-1]===".")$=$.substring(0,$.length-1);return $}return $}function ZQ($,J){if(parseInt)return parseInt($,J);else if(Number.parseInt)return Number.parseInt($,J);else if(window&&window.parseInt)return window.parseInt($,J);else throw Error("parseInt, Number.parseInt, window.parseInt are not supported")}var $Q,JQ,YQ,QQ;var N5=Y$(()=>{$Q=/^[-+]?0x[a-fA-F0-9]+$/,JQ=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,YQ={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};QQ=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/});function QJ($){if(typeof $==="function")return $;if(Array.isArray($))return(J)=>{for(let Y of $){if(typeof Y==="string"&&J===Y)return!0;if(Y instanceof RegExp&&Y.test(J))return!0}};return()=>!1}class z1{constructor($){if(this.options=$,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(J,Y)=>k5(Y,10,"&#")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(J,Y)=>k5(Y,16,"&#x")}},this.addExternalEntities=zQ,this.parseXml=OQ,this.parseTextData=GQ,this.resolveNameSpace=HQ,this.buildAttributesMap=BQ,this.isItStopNode=VQ,this.replaceEntitiesValue=jQ,this.readStopNodeData=EQ,this.saveTextToParentTag=qQ,this.addChild=XQ,this.ignoreAttributesFn=QJ(this.options.ignoreAttributes),this.options.stopNodes&&this.options.stopNodes.length>0){this.stopNodesExact=new Set,this.stopNodesWildcard=new Set;for(let J=0;J<this.options.stopNodes.length;J++){let Y=this.options.stopNodes[J];if(typeof Y!=="string")continue;if(Y.startsWith("*."))this.stopNodesWildcard.add(Y.substring(2));else this.stopNodesExact.add(Y)}}}}function zQ($){let J=Object.keys($);for(let Y=0;Y<J.length;Y++){let Q=J[Y],W=Q.replace(/[.\-+*:]/g,"\\.");this.lastEntities[Q]={regex:new RegExp("&"+W+";","g"),val:$[Q]}}}function GQ($,J,Y,Q,W,U,Z){if($!==void 0){if(this.options.trimValues&&!Q)$=$.trim();if($.length>0){if(!Z)$=this.replaceEntitiesValue($);let z=this.options.tagValueProcessor(J,$,Y,W,U);if(z===null||z===void 0)return $;else if(typeof z!==typeof $||z!==$)return z;else if(this.options.trimValues)return UJ($,this.options.parseTagValue,this.options.numberParseOptions);else if($.trim()===$)return UJ($,this.options.parseTagValue,this.options.numberParseOptions);else return $}}}function HQ($){if(this.options.removeNSPrefix){let J=$.split(":"),Y=$.charAt(0)==="/"?"/":"";if(J[0]==="xmlns")return"";if(J.length===2)$=Y+J[1]}return $}function BQ($,J){if(this.options.ignoreAttributes!==!0&&typeof $==="string"){let Y=Y1($,KQ),Q=Y.length,W={};for(let U=0;U<Q;U++){let Z=this.resolveNameSpace(Y[U][1]);if(this.ignoreAttributesFn(Z,J))continue;let z=Y[U][4],H=this.options.attributeNamePrefix+Z;if(Z.length){if(this.options.transformAttributeName)H=this.options.transformAttributeName(H);if(H==="__proto__")H="#__proto__";if(z!==void 0){if(this.options.trimValues)z=z.trim();z=this.replaceEntitiesValue(z);let K=this.options.attributeValueProcessor(Z,z,J);if(K===null||K===void 0)W[H]=z;else if(typeof K!==typeof z||K!==z)W[H]=K;else W[H]=UJ(z,this.options.parseAttributeValue,this.options.numberParseOptions)}else if(this.options.allowBooleanAttributes)W[H]=!0}}if(!Object.keys(W).length)return;if(this.options.attributesGroupName){let U={};return U[this.options.attributesGroupName]=W,U}return W}}function XQ($,J,Y,Q){if(!this.options.captureMetaData)Q=void 0;let W=this.options.updateTag(J.tagname,Y,J[":@"]);if(W===!1);else if(typeof W==="string")J.tagname=W,$.addChild(J,Q);else $.addChild(J,Q)}function qQ($,J,Y,Q){if($){if(Q===void 0)Q=J.child.length===0;if($=this.parseTextData($,J.tagname,Y,!1,J[":@"]?Object.keys(J[":@"]).length!==0:!1,Q),$!==void 0&&$!=="")J.add(this.options.textNodeName,$);$=""}return $}function VQ($,J,Y,Q){if(J&&J.has(Q))return!0;if($&&$.has(Y))return!0;return!1}function MQ($,J,Y=">"){let Q,W="";for(let U=J;U<$.length;U++){let Z=$[U];if(Q){if(Z===Q)Q=""}else if(Z==='"'||Z==="'")Q=Z;else if(Z===Y[0])if(Y[1]){if($[U+1]===Y[1])return{data:W,index:U}}else return{data:W,index:U};else if(Z==="\t")Z=" ";W+=Z}}function w0($,J,Y,Q){let W=$.indexOf(J,Y);if(W===-1)throw Error(Q);else return W+J.length-1}function WJ($,J,Y,Q=">"){let W=MQ($,J+1,Q);if(!W)return;let{data:U,index:Z}=W,z=U.search(/\s/),H=U,K=!0;if(z!==-1)H=U.substring(0,z),U=U.substring(z+1).trimStart();let B=H;if(Y){let O=H.indexOf(":");if(O!==-1)H=H.substr(O+1),K=H!==W.data.substr(O+1)}return{tagName:H,tagExp:U,closeIndex:Z,attrExpPresent:K,rawTagName:B}}function EQ($,J,Y){let Q=Y,W=1;for(;Y<$.length;Y++)if($[Y]==="<")if($[Y+1]==="/"){let U=w0($,">",Y,`${J} is not closed`);if($.substring(Y+2,U).trim()===J){if(W--,W===0)return{tagContent:$.substring(Q,Y),i:U}}Y=U}else if($[Y+1]==="?")Y=w0($,"?>",Y+1,"StopNode is not closed.");else if($.substr(Y+1,3)==="!--")Y=w0($,"-->",Y+3,"StopNode is not closed.");else if($.substr(Y+1,2)==="![")Y=w0($,"]]>",Y,"StopNode is not closed.")-2;else{let U=WJ($,Y,">");if(U){if((U&&U.tagName)===J&&U.tagExp[U.tagExp.length-1]!=="/")W++;Y=U.closeIndex}}}function UJ($,J,Y){if(J&&typeof $==="string"){let Q=$.trim();if(Q==="true")return!0;else if(Q==="false")return!1;else return YJ($,Y)}else if(F5($))return $;else return""}function k5($,J,Y){let Q=Number.parseInt($,J);if(Q>=0&&Q<=1114111)return String.fromCodePoint(Q);else return Y+$+";"}var KQ,OQ=function($){$=$.replace(/\r\n?/g,`
6
+ `);let J=new y$("!xml"),Y=J,Q="",W="",U=new Z1(this.options.processEntities);for(let Z=0;Z<$.length;Z++)if($[Z]==="<")if($[Z+1]==="/"){let H=w0($,">",Z,"Closing Tag is not closed."),K=$.substring(Z+2,H).trim();if(this.options.removeNSPrefix){let X=K.indexOf(":");if(X!==-1)K=K.substr(X+1)}if(this.options.transformTagName)K=this.options.transformTagName(K);if(Y)Q=this.saveTextToParentTag(Q,Y,W);let B=W.substring(W.lastIndexOf(".")+1);if(K&&this.options.unpairedTags.indexOf(K)!==-1)throw Error(`Unpaired tag can not be used as closing tag: </${K}>`);let O=0;if(B&&this.options.unpairedTags.indexOf(B)!==-1)O=W.lastIndexOf(".",W.lastIndexOf(".")-1),this.tagsNodeStack.pop();else O=W.lastIndexOf(".");W=W.substring(0,O),Y=this.tagsNodeStack.pop(),Q="",Z=H}else if($[Z+1]==="?"){let H=WJ($,Z,!1,"?>");if(!H)throw Error("Pi Tag is not closed.");if(Q=this.saveTextToParentTag(Q,Y,W),this.options.ignoreDeclaration&&H.tagName==="?xml"||this.options.ignorePiTags);else{let K=new y$(H.tagName);if(K.add(this.options.textNodeName,""),H.tagName!==H.tagExp&&H.attrExpPresent)K[":@"]=this.buildAttributesMap(H.tagExp,W);this.addChild(Y,K,W,Z)}Z=H.closeIndex+1}else if($.substr(Z+1,3)==="!--"){let H=w0($,"-->",Z+4,"Comment is not closed.");if(this.options.commentPropName){let K=$.substring(Z+4,H-2);Q=this.saveTextToParentTag(Q,Y,W),Y.add(this.options.commentPropName,[{[this.options.textNodeName]:K}])}Z=H}else if($.substr(Z+1,2)==="!D"){let H=U.readDocType($,Z);this.docTypeEntities=H.entities,Z=H.i}else if($.substr(Z+1,2)==="!["){let H=w0($,"]]>",Z,"CDATA is not closed.")-2,K=$.substring(Z+9,H);Q=this.saveTextToParentTag(Q,Y,W);let B=this.parseTextData(K,Y.tagname,W,!0,!1,!0,!0);if(B==null)B="";if(this.options.cdataPropName)Y.add(this.options.cdataPropName,[{[this.options.textNodeName]:K}]);else Y.add(this.options.textNodeName,B);Z=H+2}else{let H=WJ($,Z,this.options.removeNSPrefix),K=H.tagName,B=H.rawTagName,O=H.tagExp,X=H.attrExpPresent,j=H.closeIndex;if(this.options.transformTagName){let F=this.options.transformTagName(K);if(O===K)O=F;K=F}if(Y&&Q){if(Y.tagname!=="!xml")Q=this.saveTextToParentTag(Q,Y,W,!1)}let q=Y;if(q&&this.options.unpairedTags.indexOf(q.tagname)!==-1)Y=this.tagsNodeStack.pop(),W=W.substring(0,W.lastIndexOf("."));if(K!==J.tagname)W+=W?"."+K:K;let E=Z;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,W,K)){let F="";if(O.length>0&&O.lastIndexOf("/")===O.length-1){if(K[K.length-1]==="/")K=K.substr(0,K.length-1),W=W.substr(0,W.length-1),O=K;else O=O.substr(0,O.length-1);Z=H.closeIndex}else if(this.options.unpairedTags.indexOf(K)!==-1)Z=H.closeIndex;else{let T=this.readStopNodeData($,B,j+1);if(!T)throw Error(`Unexpected end of ${B}`);Z=T.i,F=T.tagContent}let w=new y$(K);if(K!==O&&X)w[":@"]=this.buildAttributesMap(O,W);if(F)F=this.parseTextData(F,K,W,!0,X,!0,!0);W=W.substr(0,W.lastIndexOf(".")),w.add(this.options.textNodeName,F),this.addChild(Y,w,W,E)}else{if(O.length>0&&O.lastIndexOf("/")===O.length-1){if(K[K.length-1]==="/")K=K.substr(0,K.length-1),W=W.substr(0,W.length-1),O=K;else O=O.substr(0,O.length-1);if(this.options.transformTagName){let w=this.options.transformTagName(K);if(O===K)O=w;K=w}let F=new y$(K);if(K!==O&&X)F[":@"]=this.buildAttributesMap(O,W);this.addChild(Y,F,W,E),W=W.substr(0,W.lastIndexOf("."))}else{let F=new y$(K);if(this.tagsNodeStack.push(Y),K!==O&&X)F[":@"]=this.buildAttributesMap(O,W);this.addChild(Y,F,W,E),Y=F}Q="",Z=j}}else Q+=$[Z];return J.child},jQ=function($){if(this.options.processEntities){for(let J in this.docTypeEntities){let Y=this.docTypeEntities[J];$=$.replace(Y.regx,Y.val)}for(let J in this.lastEntities){let Y=this.lastEntities[J];$=$.replace(Y.regex,Y.val)}if(this.options.htmlEntities)for(let J in this.htmlEntities){let Y=this.htmlEntities[J];$=$.replace(Y.regex,Y.val)}$=$.replace(this.ampEntity.regex,this.ampEntity.val)}return $};var I5=Y$(()=>{Q1();U1();C5();N5();KQ=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm")});function zJ($,J){return x5($,J)}function x5($,J,Y){let Q,W={};for(let U=0;U<$.length;U++){let Z=$[U],z=_Q(Z),H="";if(Y===void 0)H=z;else H=Y+"."+z;if(z===J.textNodeName)if(Q===void 0)Q=Z[z];else Q+=""+Z[z];else if(z===void 0)continue;else if(Z[z]){let K=x5(Z[z],J,H),B=wQ(K,J);if(Z[ZJ]!==void 0)K[ZJ]=Z[ZJ];if(Z[":@"])FQ(K,Z[":@"],H,J);else if(Object.keys(K).length===1&&K[J.textNodeName]!==void 0&&!J.alwaysCreateTextNode)K=K[J.textNodeName];else if(Object.keys(K).length===0)if(J.alwaysCreateTextNode)K[J.textNodeName]="";else K="";if(W[z]!==void 0&&W.hasOwnProperty(z)){if(!Array.isArray(W[z]))W[z]=[W[z]];W[z].push(K)}else if(J.isArray(z,H,B))W[z]=[K];else W[z]=K}}if(typeof Q==="string"){if(Q.length>0)W[J.textNodeName]=Q}else if(Q!==void 0)W[J.textNodeName]=Q;return W}function _Q($){let J=Object.keys($);for(let Y=0;Y<J.length;Y++){let Q=J[Y];if(Q!==":@")return Q}}function FQ($,J,Y,Q){if(J){let W=Object.keys(J),U=W.length;for(let Z=0;Z<U;Z++){let z=W[Z];if(Q.isArray(z,Y+"."+z,!0,!0))$[z]=[J[z]];else $[z]=J[z]}}}function wQ($,J){let{textNodeName:Y}=J,Q=Object.keys($).length;if(Q===0)return!0;if(Q===1&&($[Y]||typeof $[Y]==="boolean"||$[Y]===0))return!0;return!1}var ZJ;var h5=Y$(()=>{U1();ZJ=y$.getMetaDataSymbol()});class l0{constructor($){this.externalEntities={},this.options=D5($)}parse($,J){if(typeof $!=="string"&&$.toString)$=$.toString();else if(typeof $!=="string")throw Error("XML data is accepted in String or Bytes[] form.");if(J){if(J===!0)J={};let W=R5($,J);if(W!==!0)throw Error(`${W.err.msg}:${W.err.line}:${W.err.col}`)}let Y=new z1(this.options);Y.addExternalEntities(this.externalEntities);let Q=Y.parseXml($);if(this.options.preserveOrder||Q===void 0)return Q;else return zJ(Q,this.options)}addEntity($,J){if(J.indexOf("&")!==-1)throw Error("Entity value can't have '&'");else if($.indexOf("&")!==-1||$.indexOf(";")!==-1)throw Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");else if(J==="&")throw Error("An entity with value '&' is not permitted");else this.externalEntities[$]=J}static getMetaDataSymbol(){return y$.getMetaDataSymbol()}}var b5=Y$(()=>{P5();I5();h5();S5();U1()});var y5=Y$(()=>{b5()});var T0={};c$(T0,{buildQueryParams:()=>C$,AWSClient:()=>l});import*as B0 from"node:crypto";import{existsSync as TQ,readFileSync as LQ}from"node:fs";import{homedir as AQ}from"node:os";import{join as RQ}from"node:path";class l{credentials;config;cache;xmlParser;constructor($,J){this.credentials=$||this.loadCredentials(),this.config={maxRetries:3,retryDelay:1000,cacheEnabled:!0,defaultCacheTTL:60000,...J},this.cache=new Map,this.xmlParser=new l0({ignoreAttributes:!1,attributeNamePrefix:"@_",textNodeName:"#text",parseAttributeValue:!0,trimValues:!0})}loadCredentials(){let $=process.env.AWS_ACCESS_KEY_ID,J=process.env.AWS_SECRET_ACCESS_KEY,Y=process.env.AWS_SESSION_TOKEN;if($&&J)return{accessKeyId:$,secretAccessKey:J,sessionToken:Y};let Q=this.loadCredentialsFromFile();if(Q)return Q;return{accessKeyId:"",secretAccessKey:""}}loadCredentialsFromFile(){let $=process.env.AWS_PROFILE||"default",J=process.env.AWS_SHARED_CREDENTIALS_FILE||RQ(AQ(),".aws","credentials");if(!TQ(J))return null;try{let Y=LQ(J,"utf-8"),Q=this.parseCredentialsFile(Y,$);if(Q.accessKeyId&&Q.secretAccessKey)return Q}catch{}return null}parseCredentialsFile($,J){let Y=$.split(`
7
+ `),Q="",W="",U="",Z;for(let z of Y){let H=z.trim();if(!H||H.startsWith("#"))continue;let K=H.match(/^\[([^\]]+)\]$/);if(K){Q=K[1];continue}if(Q===J){let[B,...O]=H.split("="),X=O.join("=").trim();if(B.trim()==="aws_access_key_id")W=X;else if(B.trim()==="aws_secret_access_key")U=X;else if(B.trim()==="aws_session_token")Z=X}}return{accessKeyId:W,secretAccessKey:U,sessionToken:Z}}ec2CredentialsCache;async getCredentials(){let $=process.env.AWS_ACCESS_KEY_ID,J=process.env.AWS_SECRET_ACCESS_KEY;if($&&J)return{accessKeyId:$,secretAccessKey:J,sessionToken:process.env.AWS_SESSION_TOKEN};let Y=this.loadCredentialsFromFile();if(Y)return Y;if(this.ec2CredentialsCache){let Q=Date.now();if(this.ec2CredentialsCache.expiration>Q+300000)return this.ec2CredentialsCache.credentials}try{let W=await(await fetch("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}})).text(),Z=await(await fetch("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":W}})).text(),H=await(await fetch(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${Z}`,{headers:{"X-aws-ec2-metadata-token":W}})).json(),K={accessKeyId:H.AccessKeyId,secretAccessKey:H.SecretAccessKey,sessionToken:H.Token};return this.ec2CredentialsCache={credentials:K,expiration:new Date(H.Expiration).getTime()},K}catch(Q){throw Error("AWS credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or run on an EC2 instance with an IAM role.")}}async request($){if($.method==="GET"&&this.config.cacheEnabled&&$.cacheKey){let Q=this.getFromCache($.cacheKey);if(Q!==null)return Q}let J=$.retries??this.config.maxRetries??3,Y=null;for(let Q=0;Q<=J;Q++)try{let W=await this.makeRequest($);if($.method==="GET"&&this.config.cacheEnabled&&$.cacheKey)this.setInCache($.cacheKey,W,$.cacheTTL??this.config.defaultCacheTTL??60000);return W}catch(W){if(Y=W,!this.shouldRetry(W))throw W;if(Q===J)throw W;let Z=this.calculateRetryDelay(Q);await this.sleep(Z)}throw Y||Error("Request failed after retries")}async makeRequest($){let J=$.credentials||await this.getCredentials();if(!J||!J.accessKeyId||!J.secretAccessKey)throw Error("AWS credentials not provided");let Y=this.buildUrl($),Q=this.signRequest($,J),W=await fetch(Y,{method:$.method,headers:Q,body:$.body}),U=await W.text();if(!W.ok)throw this.parseError(U,W.status,W.headers);if(!U||U.trim()===""){if($.returnHeaders)return{body:null,headers:this.headersToObject(W.headers)};return null}if($.rawResponse){if($.returnHeaders)return{body:U,headers:this.headersToObject(W.headers)};return U}let Z;if(U.startsWith("<"))Z=this.parseXmlResponse(U);else try{Z=JSON.parse(U)}catch{Z=U}if($.returnHeaders)return{body:Z,headers:this.headersToObject(W.headers)};return Z}headersToObject($){let J={};return $.forEach((Y,Q)=>{J[Q]=Y}),J}buildUrl($){let{service:J,region:Y,path:Q,queryParams:W}=$,U;if(J==="s3")if($.bucket)U=`${$.bucket}.s3.${Y}.amazonaws.com`;else U=`s3.${Y}.amazonaws.com`;else if(J==="cloudfront")U="cloudfront.amazonaws.com";else if(J==="iam")U="iam.amazonaws.com";else if(J==="route53")U="route53.amazonaws.com";else if(J==="route53domains")U="route53domains.us-east-1.amazonaws.com";else if(J==="ecr")U=`api.ecr.${Y}.amazonaws.com`;else if(J==="ses")U=`email.${Y}.amazonaws.com`;else U=`${J}.${Y}.amazonaws.com`;let Z=`https://${U}${Q}`;if(W&&Object.keys(W).length>0){let z=Object.keys(W).map((H)=>`${this.uriEncode(H)}=${this.uriEncode(W[H])}`).join("&");Z+=`?${z}`}return Z}signRequest($,J){let{service:Y,region:Q,method:W,path:U,queryParams:Z,body:z}=$,H=new Date,K=this.getAmzDate(H),B=this.getDateStamp(H),O;if(Y==="s3")if($.bucket)O=`${$.bucket}.s3.${Q}.amazonaws.com`;else O=`s3.${Q}.amazonaws.com`;else if(Y==="cloudfront")O="cloudfront.amazonaws.com";else if(Y==="iam")O="iam.amazonaws.com";else if(Y==="route53")O="route53.amazonaws.com";else if(Y==="route53domains")O="route53domains.us-east-1.amazonaws.com";else if(Y==="ecr")O=`api.ecr.${Q}.amazonaws.com`;else if(Y==="ses")O=`email.${Q}.amazonaws.com`;else O=`${Y}.${Q}.amazonaws.com`;let X={host:O,"x-amz-date":K,...$.headers||{}};if(J.sessionToken)X["x-amz-security-token"]=J.sessionToken;if(z){if(!Object.keys(X).some((f)=>f.toLowerCase()==="content-type"))X["content-type"]="application/x-www-form-urlencoded";X["content-length"]=Buffer.byteLength(z).toString()}let j=this.sha256(z||"");X["x-amz-content-sha256"]=j;let q=U,E=Z?Object.keys(Z).sort().map((y)=>`${this.uriEncode(y)}=${this.uriEncode(Z[y])}`).join("&"):"",F=Object.keys(X).sort((y,f)=>y.toLowerCase().localeCompare(f.toLowerCase())),w=F.map((y)=>`${y.toLowerCase()}:${X[y].trim()}
8
+ `).join(""),T=F.map((y)=>y.toLowerCase()).join(";"),S=[W,q,E,w,T,j].join(`
9
+ `),R="AWS4-HMAC-SHA256",C=Y;if(Y==="email")C="ses";let D=`${B}/${Q}/${C}/aws4_request`,k=[R,K,D,this.sha256(S)].join(`
10
+ `),u=this.getSignatureKey(J.secretAccessKey,B,Q,C),b=this.hmac(u,k),v=`${R} Credential=${J.accessKeyId}/${D}, SignedHeaders=${T}, Signature=${b}`;return{...X,Authorization:v}}getAmzDate($){return $.toISOString().replace(/[:-]|\.\d{3}/g,"")}getDateStamp($){return $.toISOString().slice(0,10).replace(/-/g,"")}uriEncode($){return encodeURIComponent($).replace(/[!'()*]/g,(J)=>`%${J.charCodeAt(0).toString(16).toUpperCase()}`)}sha256($){return B0.createHash("sha256").update($,"utf8").digest("hex")}hmac($,J){return B0.createHmac("sha256",$).update(J,"utf8").digest("hex")}getSignatureKey($,J,Y,Q){let W=B0.createHmac("sha256",`AWS4${$}`).update(J).digest(),U=B0.createHmac("sha256",W).update(Y).digest(),Z=B0.createHmac("sha256",U).update(Q).digest();return B0.createHmac("sha256",Z).update("aws4_request").digest()}parseXmlResponse($){try{let J=this.xmlParser.parse($);if(J.ErrorResponse)throw this.createErrorFromXml(J.ErrorResponse.Error);let Y=Object.keys(J);if(Y.length===1)return J[Y[0]];return J}catch(J){if(J.code||J.statusCode)throw J;return{}}}parseError($,J,Y){let Q=Error();if(Q.statusCode=J,Q.requestId=Y.get("x-amzn-requestid")||Y.get("x-amz-request-id")||void 0,$.startsWith("<"))try{let W=this.xmlParser.parse($);if(W.ErrorResponse?.Error){let U=W.ErrorResponse.Error;return Q.code=U.Code,Q.message=`AWS Error [${U.Code}]: ${U.Message||"Unknown error"}`,Q.type=U.Type,Q}if(W.Error)return Q.code=W.Error.Code,Q.message=`AWS Error [${W.Error.Code}]: ${W.Error.Message||"Unknown error"}`,Q}catch{}try{let W=JSON.parse($);if(W.__type||W.code)return Q.code=W.__type||W.code,Q.message=`AWS Error [${Q.code}]: ${W.message||W.Message||"Unknown error"}`,Q}catch{}return Q.message=`AWS API Error (${J}): ${$}`,Q}createErrorFromXml($){let J=Error();return J.code=$.Code,J.message=`AWS Error [${$.Code}]: ${$.Message||"Unknown error"}`,J.type=$.Type,J}isRetryableError($){return["RequestTimeout","RequestTimeoutException","PriorRequestNotComplete","ConnectionError","ThrottlingException","Throttling","TooManyRequestsException","ProvisionedThroughputExceededException","RequestLimitExceeded","BandwidthLimitExceeded","SlowDown","ServiceUnavailable","ServiceUnavailableException","InternalError","InternalFailure","InternalServerError","InternalServiceException","TransientError","TransientFailure","IDPCommunicationErrorException","NetworkError","ConnectionRefusedException","EC2ThrottledException","503 Slow Down","500 InternalError"].includes($)}isRetryableStatusCode($){return $>=500||$===429}shouldRetry($){if($.name==="FetchError"||$.name==="TypeError"||$.code==="ECONNRESET")return!0;if($.code&&this.isRetryableError($.code))return!0;if($.statusCode&&this.isRetryableStatusCode($.statusCode))return!0;if($.statusCode&&$.statusCode>=400&&$.statusCode<500&&$.statusCode!==429)return!1;if($.statusCode)return!1;return!0}calculateRetryDelay($){let J=this.config.retryDelay??1000,Y=30000,Q=Math.min(J*2**$,30000),W=Math.random()*0.3*Q;return Q+W}sleep($){return new Promise((J)=>setTimeout(J,$))}getFromCache($){let J=this.cache.get($);if(!J)return null;if(Date.now()>J.expires)return this.cache.delete($),null;return J.data}setInCache($,J,Y){this.cache.set($,{data:J,expires:Date.now()+Y})}clearCache(){this.cache.clear()}clearExpiredCache(){let $=Date.now();for(let[J,Y]of this.cache.entries())if($>Y.expires)this.cache.delete(J)}}function C$($){let J={};for(let[Y,Q]of Object.entries($)){if(Q===void 0||Q===null)continue;if(Array.isArray(Q))Q.forEach((W,U)=>{J[`${Y}.${U+1}`]=String(W)});else if(typeof Q==="object")for(let[W,U]of Object.entries(Q))J[`${Y}.${W}`]=String(U);else J[Y]=String(Q)}return J}var W$=Y$(()=>{y5()});class C1{name="porkbun";apiKey;secretKey;constructor($,J){this.apiKey=$,this.secretKey=J}async request($,J={}){let Y=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(!Y.ok)throw Error(`Porkbun API error: ${Y.status} ${Y.statusText}`);let Q=await Y.json();if(Q.status==="ERROR")throw Error(`Porkbun API error: ${Q.message||"Unknown error"}`);return Q}getSubdomain($,J){let Y=$.replace(/\.$/,""),Q=J.replace(/\.$/,"");if(Y===Q)return"";if(Y.endsWith(`.${Q}`))return Y.slice(0,-(Q.length+1));return Y}getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return $}async createRecord($,J){try{let Y=this.getRootDomain($),Q=this.getSubdomain(J.name,Y),W={type:J.type,content:J.content,ttl:String(J.ttl||600)};if(Q)W.name=Q;if((J.type==="MX"||J.type==="SRV")&&J.priority!==void 0)W.prio=String(J.priority);if(J.type==="SRV"&&J.weight!==void 0&&J.port!==void 0)W.content=`${J.weight} ${J.port} ${J.content}`;return{success:!0,id:(await this.request(`/dns/create/${Y}`,W)).id?.toString(),message:"Record created successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async upsertRecord($,J){try{let Y=this.getRootDomain($),Q=this.getSubdomain(J.name,Y),W=await this.listRecords($,J.type);if(W.success){let U=W.records.find((Z)=>{return this.getSubdomain(Z.name,Y)===Q&&Z.type===J.type});if(U?.id){let Z={type:J.type,content:J.content,ttl:String(J.ttl||600)};if(Q)Z.name=Q;if((J.type==="MX"||J.type==="SRV")&&J.priority!==void 0)Z.prio=String(J.priority);if(J.type==="SRV"&&J.weight!==void 0&&J.port!==void 0)Z.content=`${J.weight} ${J.port} ${J.content}`;return await this.request(`/dns/edit/${Y}/${U.id}`,Z),{success:!0,id:U.id,message:"Record updated successfully"}}}return this.createRecord($,J)}catch(Y){return this.createRecord($,J)}}async deleteRecord($,J){try{let Y=this.getRootDomain($),Q=this.getSubdomain(J.name,Y),W=await this.listRecords($,J.type);if(!W.success)return{success:!1,message:"Failed to list records"};let U=W.records.find((Z)=>{return this.getSubdomain(Z.name,Y)===Q&&Z.type===J.type&&Z.content===J.content});if(!U?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${Y}/${U.id}`),{success:!0,message:"Record deleted successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async listRecords($,J){try{let Y=this.getRootDomain($),Q=`/dns/retrieve/${Y}`;if(J)Q=`/dns/retrieveByNameType/${Y}/${J}`;return{success:!0,records:((await this.request(Q)).records||[]).map((Z)=>({id:Z.id,name:Z.name||Y,type:Z.type,content:Z.content,ttl:Number.parseInt(Z.ttl,10),priority:Z.prio?Number.parseInt(Z.prio,10):void 0}))}}catch(Y){return{success:!1,records:[],message:Y instanceof Error?Y.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 Y=this.getRootDomain($);return await this.request(`/dns/updateNS/${Y}`,{ns:J}),!0}catch{return!1}}}class N1{name="godaddy";apiKey;apiSecret;baseUrl;constructor($,J,Y="production"){this.apiKey=$,this.apiSecret=J,this.baseUrl=Y==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}async request($,J,Y){let Q=`${this.baseUrl}${J}`,W={Authorization:`sso-key ${this.apiKey}:${this.apiSecret}`,"Content-Type":"application/json",Accept:"application/json"},U={method:$,headers:W};if(Y)U.body=JSON.stringify(Y);let Z=await fetch(Q,U);if(Z.status===204)return{};if(Z.ok){let H=await Z.text();if(H)return JSON.parse(H);return{}}let z=`GoDaddy API error: ${Z.status} ${Z.statusText}`;try{let H=await Z.json();if(H.message)z=`GoDaddy API error: ${H.message}`;if(H.fields)z+=` - Fields: ${JSON.stringify(H.fields)}`}catch{}throw Error(z)}getSubdomain($,J){let Y=$.replace(/\.$/,""),Q=J.replace(/\.$/,"");if(Y===Q)return"@";if(Y.endsWith(`.${Q}`))return Y.slice(0,-(Q.length+1));return Y}getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return $}toGoDaddyRecord($,J){let Y=this.getRootDomain(J),Q=this.getSubdomain($.name,Y),W={type:$.type,name:Q,data:$.content,ttl:$.ttl||600};if($.type==="MX"&&$.priority!==void 0)W.priority=$.priority;return W}fromGoDaddyRecord($,J){let Y=this.getRootDomain(J),Q=$.name;if(Q==="@")Q=Y;else if(!Q.endsWith(Y))Q=`${Q}.${Y}`;return{name:Q,type:$.type,content:$.data,ttl:$.ttl,priority:$.priority}}async createRecord($,J){try{let Y=this.getRootDomain($),Q=this.toGoDaddyRecord(J,$);return await this.request("PATCH",`/v1/domains/${Y}/records`,[Q]),{success:!0,message:"Record created successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async upsertRecord($,J){try{let Y=this.getRootDomain($),Q=this.toGoDaddyRecord(J,$);return await this.request("PUT",`/v1/domains/${Y}/records/${J.type}/${Q.name}`,[Q]),{success:!0,message:"Record upserted successfully"}}catch(Y){return this.createRecord($,J)}}async deleteRecord($,J){try{let Y=this.getRootDomain($),Q=this.getSubdomain(J.name,Y),W=await this.request("GET",`/v1/domains/${Y}/records/${J.type}/${Q}`),U=W.filter((Z)=>Z.data!==J.content);if(U.length===W.length)return{success:!1,message:"Record not found"};if(U.length===0)try{await this.request("DELETE",`/v1/domains/${Y}/records/${J.type}/${Q}`)}catch{}else await this.request("PUT",`/v1/domains/${Y}/records/${J.type}/${Q}`,U);return{success:!0,message:"Record deleted successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async listRecords($,J){try{let Y=this.getRootDomain($),Q=`/v1/domains/${Y}/records`;if(J)Q=`/v1/domains/${Y}/records/${J}`;return{success:!0,records:(await this.request("GET",Q)).map((U)=>this.fromGoDaddyRecord(U,$))}}catch(Y){return{success:!1,records:[],message:Y instanceof Error?Y.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($),Y=await this.request("GET",`/v1/domains/${J}`);return{domain:Y.domain,status:Y.status,nameServers:Y.nameServers,expires:Y.expires}}catch{return null}}async updateNameServers($,J){try{let Y=this.getRootDomain($);return await this.request("PUT",`/v1/domains/${Y}/records/NS`,J.map((Q)=>({type:"NS",name:"@",data:Q,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 k1{name="cloudflare";apiToken;zoneCache=new Map;constructor($){this.apiToken=$}async request($,J,Y){let Q=`https://api.cloudflare.com/client/v4${J}`,W={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},U={method:$,headers:W};if(Y)U.body=JSON.stringify(Y);let z=await(await fetch(Q,U)).json();if(!z.success){let H=z.errors.map((K)=>K.message).join(", ");throw Error(`Cloudflare API error: ${H}`)}return z}getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return $}async getZoneId($){let J=this.getRootDomain($),Y=this.zoneCache.get(J);if(Y)return Y;let Q=await this.request("GET",`/zones?name=${encodeURIComponent(J)}`);if(!Q.result||Q.result.length===0)throw Error(`Zone not found for domain: ${J}`);let W=Q.result[0].id;return this.zoneCache.set(J,W),W}getFullRecordName($,J){let Y=this.getRootDomain(J),Q=$.replace(/\.$/,"");if(!Q||Q===Y||Q==="@")return Y;if(Q.endsWith(`.${Y}`))return Q;return`${Q}.${Y}`}toCloudflareRecord($,J){let Y={type:$.type,name:this.getFullRecordName($.name,J),content:$.content||$.value||"",ttl:$.ttl||1};if($.type==="MX"&&$.priority!==void 0)Y.priority=$.priority;if($.type==="SRV"){if($.priority!==void 0)Y.priority=$.priority}return Y}fromCloudflareRecord($){return{id:$.id,name:$.name,type:$.type,content:$.content,ttl:$.ttl,priority:$.priority}}async createRecord($,J){try{let Y=await this.getZoneId($),Q=this.toCloudflareRecord(J,$);return{success:!0,id:(await this.request("POST",`/zones/${Y}/dns_records`,Q)).result.id,message:"Record created successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async upsertRecord($,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)}`),U=this.toCloudflareRecord(J,$);if(W.result&&W.result.length>0){let z=W.result[0].id;return{success:!0,id:(await this.request("PUT",`/zones/${Y}/dns_records/${z}`,U)).result.id,message:"Record updated successfully"}}return{success:!0,id:(await this.request("POST",`/zones/${Y}/dns_records`,U)).result.id,message:"Record created successfully"}}catch(Y){return this.createRecord($,J)}}async deleteRecord($,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{success:!1,message:"Record not found"};let U=W.result.find((Z)=>Z.content===J.content);if(!U)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${Y}/dns_records/${U.id}`),{success:!0,message:"Record deleted successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async listRecords($,J){try{let Q=`/zones/${await this.getZoneId($)}/dns_records?per_page=100`;if(J)Q+=`&type=${J}`;let W=[],U=1,Z=!0;while(Z){let z=await this.request("GET",`${Q}&page=${U}`);if(W.push(...z.result||[]),z.result_info)Z=U<z.result_info.total_pages,U++;else Z=!1}return{success:!0,records:W.map((z)=>this.fromCloudflareRecord(z))}}catch(Y){return{success:!1,records:[],message:Y instanceof Error?Y.message:"Unknown error"}}}async canManageDomain($){try{return await this.getZoneId($),!0}catch{return!1}}async listDomains(){try{let $=[],J=1,Y=!0;while(Y){let Q=await this.request("GET",`/zones?per_page=50&page=${J}`);if($.push(...Q.result||[]),Q.result_info)Y=J<Q.result_info.total_pages,J++;else Y=!1}return $.map((Q)=>Q.name)}catch{return[]}}async getZoneDetails($){try{let J=await this.getZoneId($),Y=await this.request("GET",`/zones/${J}`);return{id:Y.result.id,name:Y.result.name,status:Y.result.status,nameServers:Y.result.name_servers,paused:Y.result.paused}}catch{return null}}async purgeCache($,J){try{let Y=await this.getZoneId($),Q={};if(J?.purgeEverything)Q.purge_everything=!0;else{if(J?.files)Q.files=J.files;if(J?.tags)Q.tags=J.tags;if(J?.hosts)Q.hosts=J.hosts}if(Object.keys(Q).length===0)Q.purge_everything=!0;return await this.request("POST",`/zones/${Y}/purge_cache`,Q),!0}catch{return!1}}async getRecordProxyStatus($,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 W.result.find((Z)=>Z.content===J.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus($,J,Y){try{let Q=await this.getZoneId($),W=this.getFullRecordName(J.name,$),U=await this.request("GET",`/zones/${Q}/dns_records?type=${J.type}&name=${encodeURIComponent(W)}`);if(!U.result||U.result.length===0)return!1;let Z=U.result.find((z)=>z.content===J.content);if(!Z)return!1;return await this.request("PATCH",`/zones/${Q}/dns_records/${Z.id}`,{proxied:Y}),!0}catch{return!1}}}var I$;var I1=Y$(()=>{W$();I$=class I${client;region;constructor($="us-east-1"){this.region=$,this.client=new l}async createHostedZone($){let J=$.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,Y=`<?xml version="1.0" encoding="UTF-8"?>
11
+ <CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
12
+ <Name>${$.Name}</Name>
13
+ <CallerReference>${J}</CallerReference>`;if($.HostedZoneConfig){if(Y+=`
14
+ <HostedZoneConfig>`,$.HostedZoneConfig.Comment)Y+=`
15
+ <Comment>${$.HostedZoneConfig.Comment}</Comment>`;if($.HostedZoneConfig.PrivateZone!==void 0)Y+=`
16
+ <PrivateZone>${$.HostedZoneConfig.PrivateZone}</PrivateZone>`;Y+=`
17
+ </HostedZoneConfig>`}if($.VPC)Y+=`
18
+ <VPC>
19
+ <VPCRegion>${$.VPC.VPCRegion}</VPCRegion>
20
+ <VPCId>${$.VPC.VPCId}</VPCId>
21
+ </VPC>`;if($.DelegationSetId)Y+=`
22
+ <DelegationSetId>${$.DelegationSetId}</DelegationSetId>`;Y+=`
23
+ </CreateHostedZoneRequest>`;let Q=await this.client.request({service:"route53",region:this.region,method:"POST",path:"/2013-04-01/hostedzone",headers:{"content-type":"application/xml"},body:Y});return this.parseCreateHostedZoneResponse(Q)}async listHostedZones($){let J={};if($?.Marker)J.marker=$.Marker;if($?.MaxItems)J.maxitems=$.MaxItems;let Y=await this.client.request({service:"route53",region:this.region,method:"GET",path:"/2013-04-01/hostedzone",queryParams:Object.keys(J).length>0?J:void 0});return this.parseListHostedZonesResponse(Y)}async listHostedZonesByName($){let J={};if($?.DNSName)J.dnsname=$.DNSName;if($?.HostedZoneId)J.hostedzoneid=$.HostedZoneId;if($?.MaxItems)J.maxitems=$.MaxItems;let Y=await this.client.request({service:"route53",region:this.region,method:"GET",path:"/2013-04-01/hostedzonesbyname",queryParams:Object.keys(J).length>0?J:void 0});return this.parseListHostedZonesResponse(Y)}async getHostedZone($){let J=$.Id.replace("/hostedzone/",""),Y=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/hostedzone/${J}`});return this.parseGetHostedZoneResponse(Y)}async deleteHostedZone($){let J=$.Id.replace("/hostedzone/","");await this.client.request({service:"route53",region:this.region,method:"DELETE",path:`/2013-04-01/hostedzone/${J}`})}async listResourceRecordSets($){let J=$.HostedZoneId.replace("/hostedzone/",""),Y={};if($.StartRecordName)Y.name=$.StartRecordName;if($.StartRecordType)Y.type=$.StartRecordType;if($.StartRecordIdentifier)Y.identifier=$.StartRecordIdentifier;if($.MaxItems)Y.maxitems=$.MaxItems;let Q=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/hostedzone/${J}/rrset`,queryParams:Object.keys(Y).length>0?Y:void 0});return this.parseListResourceRecordSetsResponse(Q)}async changeResourceRecordSets($){let J=$.HostedZoneId.replace("/hostedzone/",""),Y=`<?xml version="1.0" encoding="UTF-8"?>
24
+ <ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
25
+ <ChangeBatch>`;if($.ChangeBatch.Comment)Y+=`
26
+ <Comment>${this.escapeXml($.ChangeBatch.Comment)}</Comment>`;Y+=`
27
+ <Changes>`;for(let W of $.ChangeBatch.Changes){if(Y+=`
28
+ <Change>
29
+ <Action>${W.Action}</Action>
30
+ <ResourceRecordSet>
31
+ <Name>${W.ResourceRecordSet.Name}</Name>
32
+ <Type>${W.ResourceRecordSet.Type}</Type>`,W.ResourceRecordSet.TTL!==void 0)Y+=`
33
+ <TTL>${W.ResourceRecordSet.TTL}</TTL>`;if(W.ResourceRecordSet.SetIdentifier)Y+=`
34
+ <SetIdentifier>${W.ResourceRecordSet.SetIdentifier}</SetIdentifier>`;if(W.ResourceRecordSet.Weight!==void 0)Y+=`
35
+ <Weight>${W.ResourceRecordSet.Weight}</Weight>`;if(W.ResourceRecordSet.Region)Y+=`
36
+ <Region>${W.ResourceRecordSet.Region}</Region>`;if(W.ResourceRecordSet.Failover)Y+=`
37
+ <Failover>${W.ResourceRecordSet.Failover}</Failover>`;if(W.ResourceRecordSet.HealthCheckId)Y+=`
38
+ <HealthCheckId>${W.ResourceRecordSet.HealthCheckId}</HealthCheckId>`;if(W.ResourceRecordSet.ResourceRecords&&W.ResourceRecordSet.ResourceRecords.length>0){Y+=`
39
+ <ResourceRecords>`;for(let U of W.ResourceRecordSet.ResourceRecords)Y+=`
40
+ <ResourceRecord>
41
+ <Value>${this.escapeXml(U.Value)}</Value>
42
+ </ResourceRecord>`;Y+=`
43
+ </ResourceRecords>`}if(W.ResourceRecordSet.AliasTarget)Y+=`
44
+ <AliasTarget>
45
+ <HostedZoneId>${W.ResourceRecordSet.AliasTarget.HostedZoneId}</HostedZoneId>
46
+ <DNSName>${W.ResourceRecordSet.AliasTarget.DNSName}</DNSName>
47
+ <EvaluateTargetHealth>${W.ResourceRecordSet.AliasTarget.EvaluateTargetHealth}</EvaluateTargetHealth>
48
+ </AliasTarget>`;if(W.ResourceRecordSet.GeoLocation){if(Y+=`
49
+ <GeoLocation>`,W.ResourceRecordSet.GeoLocation.ContinentCode)Y+=`
50
+ <ContinentCode>${W.ResourceRecordSet.GeoLocation.ContinentCode}</ContinentCode>`;if(W.ResourceRecordSet.GeoLocation.CountryCode)Y+=`
51
+ <CountryCode>${W.ResourceRecordSet.GeoLocation.CountryCode}</CountryCode>`;if(W.ResourceRecordSet.GeoLocation.SubdivisionCode)Y+=`
52
+ <SubdivisionCode>${W.ResourceRecordSet.GeoLocation.SubdivisionCode}</SubdivisionCode>`;Y+=`
53
+ </GeoLocation>`}Y+=`
54
+ </ResourceRecordSet>
55
+ </Change>`}Y+=`
56
+ </Changes>
57
+ </ChangeBatch>
58
+ </ChangeResourceRecordSetsRequest>`;let Q=await this.client.request({service:"route53",region:this.region,method:"POST",path:`/2013-04-01/hostedzone/${J}/rrset`,headers:{"content-type":"application/xml"},body:Y});return this.parseChangeResourceRecordSetsResponse(Q)}escapeXml($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}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||$,Y=J.HostedZones?.HostedZone||J.HostedZones||[];if(!Array.isArray(Y))Y=Y?[Y]:[];return{HostedZones:Y.map((Q)=>this.parseHostedZone(Q)),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||$,Y=J.ResourceRecordSets?.ResourceRecordSet||J.ResourceRecordSets||[];if(!Array.isArray(Y))Y=Y?[Y]:[];return{ResourceRecordSets:Y.map((Q)=>this.parseResourceRecordSet(Q)),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((Y)=>({Value:Y.Value||Y})),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((W)=>W.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((Y)=>({Value:Y}))}}]}})}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 Y=(Array.isArray($.Value)?$.Value:[$.Value]).map((Q)=>{if(!Q.startsWith('"'))return`"${Q}"`;return Q});return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:$.Name,Type:"TXT",TTL:$.TTL||300,ResourceRecords:Y.map((Q)=>({Value:Q}))}}]}})}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,Y=5000){let Q=$.replace("/change/","");for(let W=0;W<J;W++){let U=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/change/${Q}`});if((U.GetChangeResponse?.ChangeInfo?.Status||U.ChangeInfo?.Status)==="INSYNC")return!0;await new Promise((z)=>setTimeout(z,Y))}return!1}async findOrCreateHostedZone($){let J=$.domainName.endsWith(".")?$.domainName:`${$.domainName}.`,Y=await this.findHostedZoneByName(J);if(Y){let W=await this.getHostedZone({Id:Y.Id});return{hostedZone:Y,nameServers:W.DelegationSet.NameServers,isNew:!1}}let Q=await this.createHostedZone({Name:J,HostedZoneConfig:{Comment:$.comment||`Hosted zone for ${$.domainName}`,PrivateZone:$.privateZone},VPC:$.vpc});return{hostedZone:Q.HostedZone,nameServers:Q.DelegationSet.NameServers,isNew:!0}}static getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length<=2)return $;return J.slice(-2).join(".")}async findHostedZoneForDomain($){let Y=$.replace(/\.$/,"").split(".");for(let Q=0;Q<Y.length-1;Q++){let W=Y.slice(Q).join("."),U=await this.findHostedZoneByName(W);if(U)return U}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:Y=!0}=$,Q=await this.findHostedZoneByName(J);if(Q){let U=await this.getHostedZone({Id:Q.Id});return{success:!0,hostedZoneId:Q.Id.replace("/hostedzone/",""),nameServers:U.DelegationSet.NameServers,isNew:!1,message:`Found existing hosted zone for ${J}`}}if(!Y)return{success:!1,hostedZoneId:null,nameServers:[],isNew:!1,message:`No hosted zone found for ${J} and createIfNotExists is false`};let W=await this.createHostedZone({Name:J,HostedZoneConfig:{Comment:`Created automatically by ts-cloud for ${J}`}});return{success:!0,hostedZoneId:W.HostedZone.Id.replace("/hostedzone/",""),nameServers:W.DelegationSet.NameServers,isNew:!0,message:`Created new hosted zone for ${J}. Please update your domain registrar with these name servers: ${W.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 x1{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor($="us-east-1",J){this.client=new I$($),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($),Y=this.hostedZoneCache.get(J);if(Y)return Y;let Q=await this.client.findHostedZoneForDomain($);if(Q){let W=Q.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(J,W),W}return null}normalizeName($){return $.endsWith(".")?$:`${$}.`}async createRecord($,J){try{let Y=await this.getHostedZoneId($);if(!Y)return{success:!1,message:`No hosted zone found for domain: ${$}`};let Q=this.normalizeName(J.name),W=J.content;if(J.type==="TXT"&&!W.startsWith('"'))W=`"${W}"`;if(J.type==="MX"&&J.priority!==void 0)W=`${J.priority} ${W}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:"CREATE",ResourceRecordSet:{Name:Q,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:W}]}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async upsertRecord($,J){try{let Y=await this.getHostedZoneId($);if(!Y)return{success:!1,message:`No hosted zone found for domain: ${$}`};let Q=this.normalizeName(J.name),W=J.content;if(J.type==="TXT"&&!W.startsWith('"'))W=`"${W}"`;if(J.type==="MX"&&J.priority!==void 0)W=`${J.priority} ${W}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:Q,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:W}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async deleteRecord($,J){try{let Y=await this.getHostedZoneId($);if(!Y)return{success:!1,message:`No hosted zone found for domain: ${$}`};let Q=this.normalizeName(J.name),W=J.content;if(J.type==="TXT"&&!W.startsWith('"'))W=`"${W}"`;if(J.type==="MX"&&J.priority!==void 0)W=`${J.priority} ${W}`;return await this.client.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:Q,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:W}]}}]}}),{success:!0,message:"Record deleted successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async listRecords($,J){try{let Y=await this.getHostedZoneId($);if(!Y)return{success:!1,records:[],message:`No hosted zone found for domain: ${$}`};let Q=await this.client.listResourceRecordSets({HostedZoneId:Y,StartRecordType:J}),W=[];for(let U of Q.ResourceRecordSets){if(J&&U.Type!==J)continue;if(U.AliasTarget)continue;for(let Z of U.ResourceRecords||[]){let z=Z.Value,H;if(U.Type==="MX"){let K=z.split(" ");if(K.length>=2)H=Number.parseInt(K[0],10),z=K.slice(1).join(" ")}if(U.Type==="TXT"&&z.startsWith('"')&&z.endsWith('"'))z=z.slice(1,-1);W.push({name:U.Name.replace(/\.$/,""),type:U.Type,content:z,ttl:U.TTL,priority:H})}}return{success:!0,records:W}}catch(Y){return{success:!1,records:[],message:Y instanceof Error?Y.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:I$.CloudFrontHostedZoneId,targetDnsName:$.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias($){let J=I$.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 xJ=Y$(()=>{I1()});var I8={};c$(I8,{ACMDnsValidator:()=>h1,ACMClient:()=>S$});class S${client;region;constructor($="us-east-1"){this.client=new l,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 Y=(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:Y.CertificateArn||"",DomainName:Y.DomainName||"",SubjectAlternativeNames:Y.SubjectAlternativeNames,Status:Y.Status||"PENDING_VALIDATION",Type:Y.Type,DomainValidationOptions:Y.DomainValidationOptions?.map((Q)=>({DomainName:Q.DomainName,ValidationDomain:Q.ValidationDomain,ValidationStatus:Q.ValidationStatus,ResourceRecord:Q.ResourceRecord?{Name:Q.ResourceRecord.Name,Type:Q.ResourceRecord.Type,Value:Q.ResourceRecord.Value}:void 0,ValidationMethod:Q.ValidationMethod})),CreatedAt:Y.CreatedAt,IssuedAt:Y.IssuedAt,NotBefore:Y.NotBefore,NotAfter:Y.NotAfter}}async listCertificates($){let J={};if($?.CertificateStatuses)J.CertificateStatuses=$.CertificateStatuses;if($?.MaxItems)J.MaxItems=$.MaxItems;if($?.NextToken)J.NextToken=$.NextToken;let Y=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:(Y.CertificateSummaryList||[]).map((Q)=>({CertificateArn:Q.CertificateArn,DomainName:Q.DomainName})),NextToken:Y.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 Y=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((Q)=>Q.DomainName===$||Q.DomainName===`*.${$.split(".").slice(1).join(".")}`);if(!Y)return null;return this.describeCertificate({CertificateArn:Y.CertificateArn})}async waitForCertificateValidation($,J=60,Y=30000){for(let Q=0;Q<J;Q++){let W=await this.describeCertificate({CertificateArn:$});if(W.Status==="ISSUED")return W;if(W.Status==="FAILED"||W.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((U)=>setTimeout(U,Y))}return null}async getDnsValidationRecords($){let J=await this.describeCertificate({CertificateArn:$});if(!J.DomainValidationOptions)return[];return J.DomainValidationOptions.filter((Y)=>Y.ResourceRecord&&Y.ValidationMethod==="DNS").map((Y)=>({domainName:Y.DomainName,recordName:Y.ResourceRecord.Name,recordType:Y.ResourceRecord.Type,recordValue:Y.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 Y of $.AdditionalSans)J.add(Y);return this.requestCertificate({DomainName:$.DomainName,SubjectAlternativeNames:Array.from(J),ValidationMethod:"DNS"})}async isCertificateValidForDomain($,J){let Y=await this.describeCertificate({CertificateArn:$});if(Y.Status!=="ISSUED")return!1;if(Y.DomainName===J)return!0;if(Y.DomainName?.startsWith("*.")){let Q=Y.DomainName.slice(2),W=J.split("."),U=Q.split(".");if(W.slice(-U.length).join(".")===Q)return!0}if(Y.SubjectAlternativeNames)for(let Q of Y.SubjectAlternativeNames){if(Q===J)return!0;if(Q.startsWith("*.")){let W=Q.slice(2),U=J.split("."),Z=W.split(".");if(U.slice(-Z.length).join(".")===W)return!0}}return!1}}class h1{acm;route53;dnsProvider;constructor($="us-east-1",J){if(this.acm=new S$($),this.route53=new I$,J&&J.provider!=="route53")this.dnsProvider=p$(J)}async requestAndValidate($){let{domainName:J,hostedZoneId:Y,subjectAlternativeNames:Q=[],waitForValidation:W=!1,maxWaitMinutes:U=30}=$;if(!this.dnsProvider&&!Y)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:Z}=await this.acm.requestCertificate({DomainName:J,SubjectAlternativeNames:Q.length>0?[J,...Q]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(Z);let z=await this.acm.getDnsValidationRecords(Z);if(this.dnsProvider)for(let H of z){let K=await this.dnsProvider.upsertRecord(J,{name:H.recordName,type:H.recordType,content:H.recordValue,ttl:300});if(!K.success)console.warn(`Failed to create validation record for ${H.domainName}: ${K.message}`)}else if(Y)for(let H of z)await this.route53.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:`ACM DNS validation for ${H.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:H.recordName,Type:H.recordType,TTL:300,ResourceRecords:[{Value:H.recordValue}]}}]}});if(W){if(!await this.acm.waitForCertificateValidation(Z,U*2,30000))throw Error(`Certificate validation timed out after ${U} minutes`)}return{certificateArn:Z,validationRecords:z}}async waitForValidationOptions($,J=30){for(let Y=0;Y<J;Y++){let Q=await this.acm.describeCertificate({CertificateArn:$});if(Q.DomainValidationOptions&&Q.DomainValidationOptions.length>0&&Q.DomainValidationOptions[0].ResourceRecord)return;await new Promise((W)=>setTimeout(W,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords($){let{certificateArn:J,hostedZoneId:Y,domain:Q}=$;if(!this.dnsProvider&&!Y)throw Error("Either hostedZoneId or external DNS provider configuration is required");let W=await this.acm.getDnsValidationRecords(J),U=[];if(this.dnsProvider){let Z=Q||W[0]?.domainName;for(let z of W){let H=await this.dnsProvider.upsertRecord(Z,{name:z.recordName,type:z.recordType,content:z.recordValue,ttl:300});U.push({...z,changeId:H.success?H.id:void 0})}}else if(Y)for(let Z of W){let z=await this.route53.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:`ACM DNS validation for ${Z.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:Z.recordName,Type:Z.recordType,TTL:300,ResourceRecords:[{Value:Z.recordValue}]}}]}});U.push({...Z,changeId:z.ChangeInfo?.Id})}return U}async deleteValidationRecords($){let{certificateArn:J,hostedZoneId:Y,domain:Q}=$,W=await this.acm.getDnsValidationRecords(J);if(this.dnsProvider){let U=Q||W[0]?.domainName;for(let Z of W)try{await this.dnsProvider.deleteRecord(U,{name:Z.recordName,type:Z.recordType,content:Z.recordValue})}catch{}}else if(Y)for(let U of W)try{await this.route53.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${U.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:U.recordName,Type:U.recordType,TTL:300,ResourceRecords:[{Value:U.recordValue}]}}]}})}catch{}}async findOrCreateCertificate($){let{domainName:J,hostedZoneId:Y,subjectAlternativeNames:Q,waitForValidation:W=!0}=$;if(!this.dnsProvider&&!Y)throw Error("Either hostedZoneId or external DNS provider configuration is required");let U=await this.acm.findCertificateByDomain(J);if(U&&U.Status==="ISSUED")return{certificateArn:U.CertificateArn,isNew:!1};let{certificateArn:Z}=await this.requestAndValidate({domainName:J,hostedZoneId:Y,subjectAlternativeNames:Q,waitForValidation:W});return{certificateArn:Z,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}var X0=Y$(()=>{W$();I1();v0()});class f0{acm;dnsProvider;constructor($,J="us-east-1"){if(this.acm=new S$(J),"provider"in $)this.dnsProvider=p$($);else this.dnsProvider=$}getProvider(){return this.dnsProvider}async requestAndValidate($){let{domainName:J,subjectAlternativeNames:Y=[],waitForValidation:Q=!1,maxWaitMinutes:W=30}=$,{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);for(let H of Z){let K=await this.dnsProvider.upsertRecord(J,{name:H.recordName,type:H.recordType,content:H.recordValue,ttl:300});if(!K.success)console.warn(`Failed to create validation record for ${H.domainName}: ${K.message}`)}let z="pending";if(Q)z=(await this.acm.waitForCertificateValidation(U,W*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:U,validationRecords:Z.map((H)=>({domainName:H.domainName,recordName:H.recordName,recordType:H.recordType,recordValue:H.recordValue})),isNew:!0,status:z}}async createValidationRecords($){let{certificateArn:J,domain:Y}=$,Q=[],W=await this.acm.getDnsValidationRecords(J);for(let U of W){let Z=await this.dnsProvider.upsertRecord(Y,{name:U.recordName,type:U.recordType,content:U.recordValue,ttl:300});if(!Z.success)Q.push(`Failed to create record for ${U.domainName}: ${Z.message}`)}return{success:Q.length===0,records:W.map((U)=>({domainName:U.domainName,recordName:U.recordName,recordType:U.recordType,recordValue:U.recordValue})),errors:Q}}async deleteValidationRecords($){let{certificateArn:J,domain:Y}=$,Q=[],W=await this.acm.getDnsValidationRecords(J);for(let U of W){let Z=await this.dnsProvider.deleteRecord(Y,{name:U.recordName,type:U.recordType,content:U.recordValue});if(!Z.success)Q.push(`Failed to delete record for ${U.domainName}: ${Z.message}`)}return{success:Q.length===0,errors:Q}}async findOrCreateCertificate($){let{domainName:J,subjectAlternativeNames:Y=[],waitForValidation:Q=!0,maxWaitMinutes:W}=$,U=await this.acm.findCertificateByDomain(J);if(U&&U.Status==="ISSUED"){let Z=U.SubjectAlternativeNames||[U.DomainName],z=Z.some((K)=>K===`*.${J}`);if(Y.every((K)=>Z.includes(K)||z))return{certificateArn:U.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:Y,waitForValidation:Q,maxWaitMinutes:W})}async requestCertificateWithCommonSans($){let{domainName:J,includeWww:Y=!0,includeWildcard:Q=!1,additionalSans:W=[],waitForValidation:U=!1}=$,Z=[];if(Y)Z.push(`www.${J}`);if(Q)Z.push(`*.${J}`);return Z.push(...W),this.requestAndValidate({domainName:J,subjectAlternativeNames:Z,waitForValidation:U})}async waitForValidationOptions($,J=30){for(let Y=0;Y<J;Y++){let Q=await this.acm.describeCertificate({CertificateArn:$});if(Q.DomainValidationOptions&&Q.DomainValidationOptions.length>0&&Q.DomainValidationOptions[0].ResourceRecord)return;await new Promise((W)=>setTimeout(W,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((Y)=>({domain:Y.DomainName,status:Y.ValidationStatus||"UNKNOWN"}))}}}var hJ=Y$(()=>{X0();v0()});function p$($){switch($.provider){case"route53":return new x1($.region,$.hostedZoneId);case"porkbun":return new C1($.apiKey,$.secretKey);case"godaddy":return new N1($.apiKey,$.apiSecret,$.environment);case"cloudflare":return new k1($.apiToken);default:throw Error(`Unknown DNS provider: ${$.provider}`)}}class b1{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,Y){return this.configs.push({provider:"godaddy",apiKey:$,apiSecret:J,environment:Y}),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 Y=process.env.GODADDY_API_KEY,Q=process.env.GODADDY_API_SECRET;if(Y&&Q){let U=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(Y,Q,U)}let W=process.env.CLOUDFLARE_API_TOKEN;if(W)this.addCloudflare(W);return this}getProvider($){let J=this.providers.get($);if(J)return J;let Y=this.configs.find((W)=>W.provider===$);if(!Y)return null;let Q=p$(Y);return this.providers.set($,Q),Q}async getProviderForDomain($){for(let J of this.configs){let Y=p$(J);if(await Y.canManageDomain($))return Y}return null}getAllProviders(){return this.configs.map(($)=>p$($))}}var Lz;var v0=Y$(()=>{xJ();hJ();xJ();Lz=new b1});var N7;var a0=Y$(async()=>{try{N7=await import("node:crypto")}catch{}});var W6={};c$(W6,{CloudFormationClient:()=>O$});class O${client;region;constructor($="us-east-1",J){this.region=$,this.client=new l}async createStack($){let J={Action:"CreateStack",StackName:$.stackName,Version:"2010-05-15"};if($.templateBody)J.TemplateBody=$.templateBody;else if($.templateUrl)J.TemplateURL=$.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if($.parameters)$.parameters.forEach((Q,W)=>{J[`Parameters.member.${W+1}.ParameterKey`]=Q.ParameterKey,J[`Parameters.member.${W+1}.ParameterValue`]=Q.ParameterValue});if($.capabilities)$.capabilities.forEach((Q,W)=>{J[`Capabilities.member.${W+1}`]=Q});if($.roleArn)J.RoleARN=$.roleArn;if($.tags)$.tags.forEach((Q,W)=>{J[`Tags.member.${W+1}.Key`]=Q.Key,J[`Tags.member.${W+1}.Value`]=Q.Value});if($.timeoutInMinutes)J.TimeoutInMinutes=$.timeoutInMinutes;if($.onFailure)J.OnFailure=$.onFailure;let Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{StackId:Y.StackId||Y.CreateStackResult?.StackId}}async updateStack($){let J={Action:"UpdateStack",StackName:$.stackName,Version:"2010-05-15"};if($.templateBody)J.TemplateBody=$.templateBody;else if($.templateUrl)J.TemplateURL=$.templateUrl;if($.parameters)$.parameters.forEach((Q,W)=>{if(J[`Parameters.member.${W+1}.ParameterKey`]=Q.ParameterKey,Q.UsePreviousValue)J[`Parameters.member.${W+1}.UsePreviousValue`]="true";else J[`Parameters.member.${W+1}.ParameterValue`]=Q.ParameterValue});if($.capabilities)$.capabilities.forEach((Q,W)=>{J[`Capabilities.member.${W+1}`]=Q});if($.roleArn)J.RoleARN=$.roleArn;if($.tags)$.tags.forEach((Q,W)=>{J[`Tags.member.${W+1}.Key`]=Q.Key,J[`Tags.member.${W+1}.Value`]=Q.Value});let Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{StackId:Y.StackId||Y.UpdateStackResult?.StackId}}async deleteStack($,J,Y){let Q={Action:"DeleteStack",StackName:$,Version:"2010-05-15"};if(J)Q.RoleARN=J;if(Y&&Y.length>0)Y.forEach((W,U)=>{Q[`RetainResources.member.${U+1}`]=W});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Q).toString()})}async describeStacks($={}){let J={Action:"DescribeStacks",Version:"2010-05-15"};if($.stackName)J.StackName=$.stackName;let Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{Stacks:this.parseStacksResponse(Y)}}async describeStackEvents($){let J={Action:"DescribeStackEvents",StackName:$,Version:"2010-05-15"},Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{StackEvents:this.parseStackEvents(Y)}}async listStackResources($){let J={Action:"ListStackResources",StackName:$,Version:"2010-05-15"},Q=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,W=[];if(Q)W=Array.isArray(Q)?Q:[Q];return{StackResourceSummaries:W}}async waitForStack($,J){let Y={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},Q=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],W=Y[J],U=360,Z=0;while(Z<360)try{let z=await this.describeStacks({stackName:$});if(z.Stacks.length===0){if(J==="stack-delete-complete")return;if(Z%10===0)console.log(`[waitForStack] Attempt ${Z}: Stack not visible yet`);await new Promise((K)=>setTimeout(K,2000)),Z++;continue}let H=z.Stacks[0];if(Z%10===0)console.log(`[waitForStack] Attempt ${Z}: Status = ${H.StackStatus}${H.StackStatusReason?` (${H.StackStatusReason})`:""}`);if(W.includes(H.StackStatus))return;if((J==="stack-create-complete"||J==="stack-update-complete")&&(H.StackStatus==="DELETE_IN_PROGRESS"||H.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let K="";try{let O=await this.describeStackEvents($);console.log("[waitForStack] Stack events (most recent first):");for(let X of O.StackEvents.slice(0,15))if(X.ResourceStatus.includes("FAILED")||X.ResourceStatusReason){if(console.log(` ${X.LogicalResourceId}: ${X.ResourceStatus} - ${X.ResourceStatusReason||"No reason provided"}`),X.ResourceStatus.includes("FAILED")&&X.ResourceStatusReason&&!K)K=X.ResourceStatusReason}}catch{}let B=K||H.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${B}`)}if(H.StackStatus==="DELETE_FAILED"&&J==="stack-delete-complete"){let K=Error("Stack deletion failed - may have resources that need to be retained");throw K.code="DELETE_FAILED",K.stackStatus=H.StackStatus,K.statusReason=H.StackStatusReason,K}if(Q.includes(H.StackStatus))throw Error(`Stack reached failure status: ${H.StackStatus}`);await new Promise((K)=>setTimeout(K,5000)),Z++}catch(z){if(J==="stack-delete-complete"&&z.message?.includes("does not exist"))return;if(J==="stack-create-complete"&&z.message?.includes("does not exist")){if(Z%10===0)console.log(`[waitForStack] Attempt ${Z}: Stack does not exist (error), retrying...`);await new Promise((H)=>setTimeout(H,2000)),Z++;continue}throw console.log(`[waitForStack] Unexpected error: ${z.message}`),z}throw console.log(`[waitForStack] Timeout after ${Z} attempts`),Error(`Timeout waiting for stack to reach ${J}`)}async validateTemplate($){let J={Action:"ValidateTemplate",TemplateBody:$,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()})}async listStacks($){let J={Action:"ListStacks",Version:"2010-05-15"};if($)$.forEach((Q,W)=>{J[`StackStatusFilter.member.${W+1}`]=Q});let Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{StackSummaries:[]}}async createChangeSet($){let J={Action:"CreateChangeSet",StackName:$.stackName,ChangeSetName:$.changeSetName,Version:"2010-05-15"};if($.templateBody)J.TemplateBody=$.templateBody;else if($.templateUrl)J.TemplateURL=$.templateUrl;if($.parameters)$.parameters.forEach((Q,W)=>{J[`Parameters.member.${W+1}.ParameterKey`]=Q.ParameterKey,J[`Parameters.member.${W+1}.ParameterValue`]=Q.ParameterValue});if($.capabilities)$.capabilities.forEach((Q,W)=>{J[`Capabilities.member.${W+1}`]=Q});if($.changeSetType)J.ChangeSetType=$.changeSetType;let Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{Id:Y.Id,StackId:Y.StackId}}async describeChangeSet($,J){let Y={Action:"DescribeChangeSet",StackName:$,ChangeSetName:J,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async executeChangeSet($,J){let Y={Action:"ExecuteChangeSet",StackName:$,ChangeSetName:J,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async deleteChangeSet($,J){let Y={Action:"DeleteChangeSet",StackName:$,ChangeSetName:J,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async getStackOutputs($){let J=await this.describeStacks({stackName:$});if(!J.Stacks||J.Stacks.length===0)throw Error(`Stack ${$} not found`);let Y=J.Stacks[0],Q={};if(Y.Outputs)for(let W of Y.Outputs)Q[W.OutputKey]=W.OutputValue;return Q}async getTemplate($){let J={Action:"GetTemplate",StackName:$,Version:"2010-05-15"},Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{TemplateBody:Y?.GetTemplateResult?.TemplateBody||Y?.TemplateBody||""}}parseStacksResponse($){let J=[],Y=$?.DescribeStacksResult?.Stacks?.member||$?.Stacks?.member||$?.Stacks||$;if(Y&&!Array.isArray(Y))Y=[Y];if(Array.isArray(Y)){for(let Q of Y)if(Q.StackId||Q.StackName){let W;if(Q.Outputs?.member)W=(Array.isArray(Q.Outputs.member)?Q.Outputs.member:[Q.Outputs.member]).map((Z)=>({OutputKey:Z.OutputKey,OutputValue:Z.OutputValue,Description:Z.Description,ExportName:Z.ExportName}));J.push({StackId:Q.StackId,StackName:Q.StackName,StackStatus:Q.StackStatus,CreationTime:Q.CreationTime,LastUpdatedTime:Q.LastUpdatedTime,StackStatusReason:Q.StackStatusReason,Outputs:W})}}else if($.StackId)J.push({StackId:$.StackId,StackName:$.StackName,StackStatus:$.StackStatus,CreationTime:$.CreationTime,LastUpdatedTime:$.LastUpdatedTime});return J}parseStackEvents($){let J=[],Y=$?.DescribeStackEventsResult?.StackEvents?.member||$?.StackEvents?.member||$?.StackEvents||[];if(Y&&!Array.isArray(Y))Y=[Y];for(let Q of Y)if(Q.LogicalResourceId)J.push({Timestamp:Q.Timestamp,ResourceType:Q.ResourceType,LogicalResourceId:Q.LogicalResourceId,ResourceStatus:Q.ResourceStatus,ResourceStatusReason:Q.ResourceStatusReason});return J}async waitForStackWithProgress($,J,Y){let Q={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},W=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],U=Q[J],Z=360,z=0,H=new Set;while(z<360)try{if(Y)try{let X=[...(await this.describeStackEvents($)).StackEvents||[]].reverse();for(let j of X){let q=`${j.LogicalResourceId}-${j.ResourceStatus}-${j.Timestamp}`;if(!H.has(q))H.add(q),Y({resourceId:j.LogicalResourceId,resourceType:j.ResourceType,status:j.ResourceStatus,reason:j.ResourceStatusReason,timestamp:j.Timestamp})}}catch{}let K=await this.describeStacks({stackName:$});if(K.Stacks.length===0){if(J==="stack-delete-complete")return;await new Promise((O)=>setTimeout(O,2000)),z++;continue}let B=K.Stacks[0];if(U.includes(B.StackStatus))return;if(B.StackStatus==="DELETE_FAILED"&&J==="stack-delete-complete"){let O=Error("Stack deletion failed - may have resources that need to be retained");throw O.code="DELETE_FAILED",O.stackStatus=B.StackStatus,O.statusReason=B.StackStatusReason,O}if(W.includes(B.StackStatus))throw Error(`Stack reached failure status: ${B.StackStatus}`);await new Promise((O)=>setTimeout(O,3000)),z++}catch(K){if(J==="stack-delete-complete"&&K.message?.includes("does not exist"))return;if(J==="stack-create-complete"&&K.message?.includes("does not exist")){await new Promise((B)=>setTimeout(B,2000)),z++;continue}throw K}throw Error(`Timeout waiting for stack to reach ${J}`)}async waitForStackComplete($,J=120,Y=5000){let Q=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],W=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let U=0;U<J;U++)try{let Z=await this.describeStacks({stackName:$});if(Z.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let z=Z.Stacks[0],H=z.StackStatus;if(Q.includes(H))return{success:!0,status:H};if(W.includes(H))return{success:!1,status:H,reason:z.StackStatusReason};await new Promise((K)=>setTimeout(K,Y))}catch(Z){if(Z.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw Z}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}var G0=Y$(()=>{W$()});var _6={};c$(_6,{S3Client:()=>X$});import*as c from"node:crypto";import{readdir as qW}from"node:fs/promises";import{join as VW}from"node:path";import{readFileSync as _9}from"node:fs";class X${client;region;constructor($="us-east-1",J){this.region=$,this.client=new l}getCredentials(){let $=process.env.AWS_ACCESS_KEY_ID,J=process.env.AWS_SECRET_ACCESS_KEY,Y=process.env.AWS_SESSION_TOKEN;if($&&J)return{accessKeyId:$,secretAccessKey:J,sessionToken:Y};let Q=this.loadCredentialsFromFile();if(Q)return Q;throw Error("AWS credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or configure ~/.aws/credentials.")}loadCredentialsFromFile(){try{let{existsSync:$,readFileSync:J}=Q$("node:fs"),{homedir:Y}=Q$("node:os"),{join:Q}=Q$("node:path"),W=process.env.AWS_PROFILE||"default",U=process.env.AWS_SHARED_CREDENTIALS_FILE||Q(Y(),".aws","credentials");if(!$(U))return null;let z=J(U,"utf-8").split(`
59
+ `),H="",K="",B="",O;for(let X of z){let j=X.trim();if(!j||j.startsWith("#"))continue;let q=j.match(/^\[([^\]]+)\]$/);if(q){H=q[1];continue}if(H===W){let[E,...F]=j.split("="),w=F.join("=").trim();if(E.trim()==="aws_access_key_id")K=w;else if(E.trim()==="aws_secret_access_key")B=w;else if(E.trim()==="aws_session_token")O=w}}if(K&&B)return{accessKeyId:K,secretAccessKey:B,sessionToken:O}}catch{}return null}async listBuckets(){let $=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),J=[],Y=$?.ListAllMyBucketsResult?.Buckets?.Bucket;if(Y){let Q=Array.isArray(Y)?Y:[Y];for(let W of Q)J.push({Name:W.Name,CreationDate:W.CreationDate})}return{Buckets:J}}async createBucket($,J){let Y={};if(J?.acl)Y["x-amz-acl"]=J.acl;let Q;if(this.region!=="us-east-1")Q=`<?xml version="1.0" encoding="UTF-8"?>
60
+ <CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
61
+ <LocationConstraint>${this.region}</LocationConstraint>
62
+ </CreateBucketConfiguration>`,Y["Content-Type"]="application/xml";await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${$}`,headers:Y,body:Q})}async deleteBucket($){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${$}`})}async emptyAndDeleteBucket($){let J=!0;while(J){let Y=await this.listAllObjects({bucket:$});if(Y.length===0){J=!1;break}let Q=Y.map((W)=>W.Key);for(let W=0;W<Q.length;W+=1000){let U=Q.slice(W,W+1000);await this.deleteObjects($,U)}}await this.deleteBucket($)}async listAllObjects($){let J=[],Y;do{let Q={"list-type":"2","max-keys":"1000"};if($.prefix)Q.prefix=$.prefix;if(Y)Q["continuation-token"]=Y;let W=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$.bucket}`,queryParams:Q}),U=W?.ListBucketResult?.Contents;if(U){let z=Array.isArray(U)?U:[U];for(let H of z)J.push({Key:H.Key,LastModified:H.LastModified||"",Size:Number.parseInt(H.Size||"0"),ETag:H.ETag})}let Z=W?.ListBucketResult?.IsTruncated;Y=Z==="true"||Z===!0?W?.ListBucketResult?.NextContinuationToken:void 0}while(Y);return J}async list($){let J=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$.bucket}`}),Y=[],Q=J?.ListBucketResult?.Contents;if(Q){let W=Array.isArray(Q)?Q:[Q];for(let U of W){if($.prefix&&!U.Key?.startsWith($.prefix))continue;if(Y.push({Key:U.Key||"",LastModified:U.LastModified||"",Size:Number.parseInt(U.Size||"0"),ETag:U.ETag}),$.maxKeys&&Y.length>=$.maxKeys)break}}return Y}async putObject($){let J={};if($.acl)J["x-amz-acl"]=$.acl;if($.cacheControl)J["Cache-Control"]=$.cacheControl;if($.contentType)J["Content-Type"]=$.contentType;if($.metadata)for(let[Q,W]of Object.entries($.metadata))J[`x-amz-meta-${Q}`]=W;let Y=$.body instanceof Uint8Array&&!Buffer.isBuffer($.body)?Buffer.from($.body):$.body;if(Buffer.isBuffer(Y)||Y instanceof Uint8Array){let Q=Buffer.isBuffer(Y)?Y:Buffer.from(Y),{accessKeyId:W,secretAccessKey:U,sessionToken:Z}=this.getCredentials(),z=`${$.bucket}.s3.${this.region}.amazonaws.com`,H=`https://${z}/${$.key}`,K=new Date,B=K.toISOString().replace(/[:-]|\.\d{3}/g,""),O=K.toISOString().slice(0,10).replace(/-/g,""),X=c.createHash("sha256").update(Q).digest("hex"),j={host:z,"x-amz-date":B,"x-amz-content-sha256":X,...J};if(Z)j["x-amz-security-token"]=Z;let q=Object.keys(j).sort().map((y)=>`${y.toLowerCase()}:${j[y].trim()}
63
+ `).join(""),E=Object.keys(j).sort().map((y)=>y.toLowerCase()).join(";"),F=["PUT",`/${$.key}`,"",q,E,X].join(`
64
+ `),w="AWS4-HMAC-SHA256",T=`${O}/${this.region}/s3/aws4_request`,S=[w,B,T,c.createHash("sha256").update(F).digest("hex")].join(`
65
+ `),R=c.createHmac("sha256",`AWS4${U}`).update(O).digest(),C=c.createHmac("sha256",R).update(this.region).digest(),D=c.createHmac("sha256",C).update("s3").digest(),k=c.createHmac("sha256",D).update("aws4_request").digest(),u=c.createHmac("sha256",k).update(S).digest("hex"),b=`${w} Credential=${W}/${T}, SignedHeaders=${E}, Signature=${u}`,v=await fetch(H,{method:"PUT",headers:{...j,Authorization:b},body:Q});if(!v.ok){let y=await v.text();throw Error(`S3 PUT failed: ${v.status} ${y}`)}return}await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${$.key}`,bucket:$.bucket,headers:J,body:$.body})}async getObject($,J){return await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$}/${J}`,rawResponse:!0})}async copyObject($){let J={"x-amz-copy-source":`/${$.sourceBucket}/${$.sourceKey}`};if($.metadataDirective)J["x-amz-metadata-directive"]=$.metadataDirective;if($.contentType)J["Content-Type"]=$.contentType;if($.metadata)for(let[Y,Q]of Object.entries($.metadata))J[`x-amz-meta-${Y}`]=Q;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${$.destinationBucket}/${$.destinationKey}`,headers:J})}async deleteObject($,J){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${$}/${J}`})}async deleteObjects($,J){let Y=`<?xml version="1.0" encoding="UTF-8"?>
66
+ <Delete>
67
+ ${J.map((W)=>`<Object><Key>${W}</Key></Object>`).join(`
68
+ `)}
69
+ </Delete>`,Q=c.createHash("md5").update(Y).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${$}`,queryParams:{delete:""},body:Y,headers:{"Content-Type":"application/xml","Content-MD5":Q}})}async bucketExists($){try{return await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${$}`}),!0}catch{return!1}}async copy($){let J=_9($.source);await this.putObject({bucket:$.bucket,key:$.key,body:J,acl:$.acl,cacheControl:$.cacheControl,contentType:$.contentType,metadata:$.metadata})}async sync($){let J=await this.listFilesRecursive($.source);for(let Y of J){if($.exclude&&$.exclude.some((U)=>Y.includes(U)))continue;if($.include&&!$.include.some((U)=>Y.includes(U)))continue;let Q=Y.substring($.source.length+1),W=$.prefix?`${$.prefix}/${Q}`:Q;if(!$.dryRun){let U=_9(Y);await this.putObject({bucket:$.bucket,key:W,body:U,acl:$.acl,cacheControl:$.cacheControl,contentType:$.contentType,metadata:$.metadata})}}}async delete($,J){await this.deleteObject($,J)}async deletePrefix($,J){let Q=(await this.list({bucket:$,prefix:J})).map((W)=>W.Key);if(Q.length>0)await this.deleteObjects($,Q)}async getBucketSize($,J){return(await this.list({bucket:$,prefix:J})).reduce((Q,W)=>Q+W.Size,0)}async listFilesRecursive($){let J=[],Y=await qW($,{withFileTypes:!0});for(let Q of Y){let W=VW($,Q.name);if(Q.isDirectory()){let U=await this.listFilesRecursive(W);J.push(...U)}else J.push(W)}return J}async putBucketPolicy($,J){let{accessKeyId:Y,secretAccessKey:Q,sessionToken:W}=this.getCredentials(),U=`s3.${this.region}.amazonaws.com`,Z=typeof J==="string"?J:JSON.stringify(J),z=new Date,H=z.toISOString().replace(/[:-]|\.\d{3}/g,""),K=z.toISOString().slice(0,10).replace(/-/g,""),B=c.createHash("sha256").update(Z).digest("hex"),O="/"+$,X="policy=",j={host:U,"x-amz-date":H,"x-amz-content-sha256":B,"content-type":"application/json"};if(W)j["x-amz-security-token"]=W;let q=Object.keys(j).sort().map((f)=>`${f.toLowerCase()}:${j[f].trim()}
70
+ `).join(""),E=Object.keys(j).sort().map((f)=>f.toLowerCase()).join(";"),F=["PUT",O,"policy=",q,E,B].join(`
71
+ `),w="AWS4-HMAC-SHA256",T=`${K}/${this.region}/s3/aws4_request`,S=[w,H,T,c.createHash("sha256").update(F).digest("hex")].join(`
72
+ `),R=c.createHmac("sha256","AWS4"+Q).update(K).digest(),C=c.createHmac("sha256",R).update(this.region).digest(),D=c.createHmac("sha256",C).update("s3").digest(),k=c.createHmac("sha256",D).update("aws4_request").digest(),u=c.createHmac("sha256",k).update(S).digest("hex"),b=`${w} Credential=${Y}/${T}, SignedHeaders=${E}, Signature=${u}`,v=`https://${U}${O}?policy=`,y=await fetch(v,{method:"PUT",headers:{...j,Authorization:b},body:Z});if(!y.ok){let f=await y.text();throw Error(`Failed to put bucket policy: ${y.status} ${f}`)}}async getBucketPolicy($){let{accessKeyId:J,secretAccessKey:Y,sessionToken:Q}=this.getCredentials(),W=`s3.${this.region}.amazonaws.com`,U=new Date,Z=U.toISOString().replace(/[:-]|\.\d{3}/g,""),z=U.toISOString().slice(0,10).replace(/-/g,""),H=c.createHash("sha256").update("").digest("hex"),K="/"+$,B="policy=",O={host:W,"x-amz-date":Z,"x-amz-content-sha256":H};if(Q)O["x-amz-security-token"]=Q;let X=Object.keys(O).sort().map((y)=>`${y.toLowerCase()}:${O[y].trim()}
73
+ `).join(""),j=Object.keys(O).sort().map((y)=>y.toLowerCase()).join(";"),q=["GET",K,"policy=",X,j,H].join(`
74
+ `),E="AWS4-HMAC-SHA256",F=`${z}/${this.region}/s3/aws4_request`,w=[E,Z,F,c.createHash("sha256").update(q).digest("hex")].join(`
75
+ `),T=c.createHmac("sha256","AWS4"+Y).update(z).digest(),S=c.createHmac("sha256",T).update(this.region).digest(),R=c.createHmac("sha256",S).update("s3").digest(),C=c.createHmac("sha256",R).update("aws4_request").digest(),D=c.createHmac("sha256",C).update(w).digest("hex"),k=`${E} Credential=${J}/${F}, SignedHeaders=${j}, Signature=${D}`,u=`https://${W}${K}?policy=`,b=await fetch(u,{method:"GET",headers:{...O,Authorization:k}});if(b.status===404)return null;if(!b.ok){let y=await b.text();throw Error(`Failed to get bucket policy: ${b.status} ${y}`)}let v=await b.text();return JSON.parse(v)}async deleteBucketPolicy($){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${$}`,queryParams:{policy:""}})}async headBucket($){try{return{exists:!0,region:(await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${$}`,returnHeaders:!0}))?.headers?.["x-amz-bucket-region"]}}catch(J){if(J.statusCode===404)return{exists:!1};throw J}}async headObject($,J){try{let Y=await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${$}/${J}`,returnHeaders:!0});return{ContentLength:Y?.headers?.["content-length"]?parseInt(Y.headers["content-length"]):void 0,ContentType:Y?.headers?.["content-type"],ETag:Y?.headers?.etag,LastModified:Y?.headers?.["last-modified"]}}catch(Y){if(Y.statusCode===404)return null;throw Y}}async getObjectBuffer($,J){let Y=await this.getObject($,J);return Buffer.from(Y)}async getObjectJson($,J){let Y=await this.getObject($,J);return JSON.parse(Y)}async putObjectJson($,J,Y,Q){await this.putObject({bucket:$,key:J,body:JSON.stringify(Y),contentType:"application/json",...Q})}async getBucketVersioning($){return{Status:(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$}`,queryParams:{versioning:""}}))?.VersioningConfiguration?.Status}}async putBucketVersioning($,J){let Y=`<?xml version="1.0" encoding="UTF-8"?>
76
+ <VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
77
+ <Status>${J}</Status>
78
+ </VersioningConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${$}`,queryParams:{versioning:""},headers:{"Content-Type":"application/xml"},body:Y})}async getBucketLifecycleConfiguration($){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$}`,queryParams:{lifecycle:""}}))?.LifecycleConfiguration}catch(J){if(J.statusCode===404)return null;throw J}}async putBucketLifecycleConfiguration($,J){let Q=`<?xml version="1.0" encoding="UTF-8"?>
79
+ <LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
80
+ ${J.map((W)=>{let U=`<Rule><ID>${W.ID}</ID><Status>${W.Status}</Status>`;if(W.Filter)U+=`<Filter><Prefix>${W.Filter.Prefix||""}</Prefix></Filter>`;else U+="<Filter><Prefix></Prefix></Filter>";if(W.Expiration){if(W.Expiration.Days)U+=`<Expiration><Days>${W.Expiration.Days}</Days></Expiration>`;else if(W.Expiration.Date)U+=`<Expiration><Date>${W.Expiration.Date}</Date></Expiration>`}if(W.Transitions)for(let Z of W.Transitions)U+=`<Transition><Days>${Z.Days}</Days><StorageClass>${Z.StorageClass}</StorageClass></Transition>`;if(W.NoncurrentVersionExpiration)U+=`<NoncurrentVersionExpiration><NoncurrentDays>${W.NoncurrentVersionExpiration.NoncurrentDays}</NoncurrentDays></NoncurrentVersionExpiration>`;return U+="</Rule>",U}).join("")}
81
+ </LifecycleConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${$}`,queryParams:{lifecycle:""},headers:{"Content-Type":"application/xml"},body:Q})}async deleteBucketLifecycleConfiguration($){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${$}`,queryParams:{lifecycle:""}})}async getBucketCors($){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$}`,queryParams:{cors:""}}))?.CORSConfiguration}catch(J){if(J.statusCode===404)return null;throw J}}async putBucketCors($,J){let Q=`<?xml version="1.0" encoding="UTF-8"?>
82
+ <CORSConfiguration>
83
+ ${J.map((W)=>{let U="<CORSRule>";for(let Z of W.AllowedOrigins)U+=`<AllowedOrigin>${Z}</AllowedOrigin>`;for(let Z of W.AllowedMethods)U+=`<AllowedMethod>${Z}</AllowedMethod>`;if(W.AllowedHeaders)for(let Z of W.AllowedHeaders)U+=`<AllowedHeader>${Z}</AllowedHeader>`;if(W.ExposeHeaders)for(let Z of W.ExposeHeaders)U+=`<ExposeHeader>${Z}</ExposeHeader>`;if(W.MaxAgeSeconds)U+=`<MaxAgeSeconds>${W.MaxAgeSeconds}</MaxAgeSeconds>`;return U+="</CORSRule>",U}).join("")}
84
+ </CORSConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${$}`,queryParams:{cors:""},headers:{"Content-Type":"application/xml"},body:Q})}async deleteBucketCors($){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${$}`,queryParams:{cors:""}})}async getBucketEncryption($){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$}`,queryParams:{encryption:""}}))?.ServerSideEncryptionConfiguration}catch(J){if(J.statusCode===404)return null;throw J}}async putBucketEncryption($,J,Y){let Q=`<ApplyServerSideEncryptionByDefault><SSEAlgorithm>${J}</SSEAlgorithm>`;if(Y)Q+=`<KMSMasterKeyID>${Y}</KMSMasterKeyID>`;Q+="</ApplyServerSideEncryptionByDefault>";let W=`<?xml version="1.0" encoding="UTF-8"?>
85
+ <ServerSideEncryptionConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
86
+ <Rule>${Q}</Rule>
87
+ </ServerSideEncryptionConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${$}`,queryParams:{encryption:""},headers:{"Content-Type":"application/xml"},body:W})}async deleteBucketEncryption($){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${$}`,queryParams:{encryption:""}})}async getBucketTagging($){try{let Y=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$}`,queryParams:{tagging:""}}))?.Tagging?.TagSet?.Tag;if(!Y)return[];return Array.isArray(Y)?Y:[Y]}catch(J){if(J.statusCode===404)return[];throw J}}async putBucketTagging($,J){let Q=`<?xml version="1.0" encoding="UTF-8"?>
88
+ <Tagging>
89
+ <TagSet>${J.map((W)=>`<Tag><Key>${W.Key}</Key><Value>${W.Value}</Value></Tag>`).join("")}</TagSet>
90
+ </Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${$}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:Q})}async deleteBucketTagging($){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${$}`,queryParams:{tagging:""}})}async getObjectTagging($,J){try{let Q=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$}/${J}`,queryParams:{tagging:""}}))?.Tagging?.TagSet?.Tag;if(!Q)return[];return Array.isArray(Q)?Q:[Q]}catch(Y){if(Y.statusCode===404)return[];throw Y}}async putObjectTagging($,J,Y){let W=`<?xml version="1.0" encoding="UTF-8"?>
91
+ <Tagging>
92
+ <TagSet>${Y.map((U)=>`<Tag><Key>${U.Key}</Key><Value>${U.Value}</Value></Tag>`).join("")}</TagSet>
93
+ </Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${$}/${J}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:W})}async deleteObjectTagging($,J){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${$}/${J}`,queryParams:{tagging:""}})}async getBucketAcl($){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$}`,queryParams:{acl:""}}))?.AccessControlPolicy}async putBucketAcl($,J){await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${$}`,queryParams:{acl:""},headers:{"x-amz-acl":J}})}async getObjectAcl($,J){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$}/${J}`,queryParams:{acl:""}}))?.AccessControlPolicy}async putObjectAcl($,J,Y){await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${$}/${J}`,queryParams:{acl:""},headers:{"x-amz-acl":Y}})}async getBucketLocation($){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$}`,queryParams:{location:""}}))?.LocationConstraint||"us-east-1"}async getBucketLogging($){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$}`,queryParams:{logging:""}}))?.BucketLoggingStatus}async putBucketLogging($,J,Y){let Q=`<?xml version="1.0" encoding="UTF-8"?>
94
+ <BucketLoggingStatus xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
95
+ <LoggingEnabled>
96
+ <TargetBucket>${J}</TargetBucket>
97
+ <TargetPrefix>${Y}</TargetPrefix>
98
+ </LoggingEnabled>
99
+ </BucketLoggingStatus>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${$}`,queryParams:{logging:""},headers:{"Content-Type":"application/xml"},body:Q})}async getBucketNotificationConfiguration($){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$}`,queryParams:{notification:""}}))?.NotificationConfiguration}async putBucketNotificationConfiguration($,J){let Y="";if(J.LambdaFunctionConfigurations)for(let W of J.LambdaFunctionConfigurations){if(Y+="<CloudFunctionConfiguration>",W.Id)Y+=`<Id>${W.Id}</Id>`;Y+=`<CloudFunction>${W.LambdaFunctionArn}</CloudFunction>`;for(let U of W.Events)Y+=`<Event>${U}</Event>`;if(W.Filter?.Key?.FilterRules){Y+="<Filter><S3Key>";for(let U of W.Filter.Key.FilterRules)Y+=`<FilterRule><Name>${U.Name}</Name><Value>${U.Value}</Value></FilterRule>`;Y+="</S3Key></Filter>"}Y+="</CloudFunctionConfiguration>"}if(J.TopicConfigurations)for(let W of J.TopicConfigurations){if(Y+="<TopicConfiguration>",W.Id)Y+=`<Id>${W.Id}</Id>`;Y+=`<Topic>${W.TopicArn}</Topic>`;for(let U of W.Events)Y+=`<Event>${U}</Event>`;Y+="</TopicConfiguration>"}if(J.QueueConfigurations)for(let W of J.QueueConfigurations){if(Y+="<QueueConfiguration>",W.Id)Y+=`<Id>${W.Id}</Id>`;Y+=`<Queue>${W.QueueArn}</Queue>`;for(let U of W.Events)Y+=`<Event>${U}</Event>`;Y+="</QueueConfiguration>"}let Q=`<?xml version="1.0" encoding="UTF-8"?>
100
+ <NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
101
+ ${Y}
102
+ </NotificationConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${$}`,queryParams:{notification:""},headers:{"Content-Type":"application/xml"},body:Q})}async getBucketWebsite($){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$}`,queryParams:{website:""}}))?.WebsiteConfiguration}catch(J){if(J.statusCode===404)return null;throw J}}async putBucketWebsite($,J){let Y="";if(J.RedirectAllRequestsTo)Y=`<RedirectAllRequestsTo>
103
+ <HostName>${J.RedirectAllRequestsTo.HostName}</HostName>
104
+ ${J.RedirectAllRequestsTo.Protocol?`<Protocol>${J.RedirectAllRequestsTo.Protocol}</Protocol>`:""}
105
+ </RedirectAllRequestsTo>`;else if(Y=`<IndexDocument><Suffix>${J.IndexDocument}</Suffix></IndexDocument>`,J.ErrorDocument)Y+=`<ErrorDocument><Key>${J.ErrorDocument}</Key></ErrorDocument>`;let Q=`<?xml version="1.0" encoding="UTF-8"?>
106
+ <WebsiteConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
107
+ ${Y}
108
+ </WebsiteConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${$}`,queryParams:{website:""},headers:{"Content-Type":"application/xml"},body:Q})}async deleteBucketWebsite($){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${$}`,queryParams:{website:""}})}async getBucketReplication($){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$}`,queryParams:{replication:""}}))?.ReplicationConfiguration}catch(J){if(J.statusCode===404)return null;throw J}}async deleteBucketReplication($){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${$}`,queryParams:{replication:""}})}async getPublicAccessBlock($){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$}`,queryParams:{publicAccessBlock:""}}))?.PublicAccessBlockConfiguration}catch(J){if(J.statusCode===404)return null;throw J}}async putPublicAccessBlock($,J){let Y=`<?xml version="1.0" encoding="UTF-8"?>
109
+ <PublicAccessBlockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
110
+ <BlockPublicAcls>${J.BlockPublicAcls??!0}</BlockPublicAcls>
111
+ <IgnorePublicAcls>${J.IgnorePublicAcls??!0}</IgnorePublicAcls>
112
+ <BlockPublicPolicy>${J.BlockPublicPolicy??!0}</BlockPublicPolicy>
113
+ <RestrictPublicBuckets>${J.RestrictPublicBuckets??!0}</RestrictPublicBuckets>
114
+ </PublicAccessBlockConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${$}`,queryParams:{publicAccessBlock:""},headers:{"Content-Type":"application/xml"},body:Y})}async deletePublicAccessBlock($){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${$}`,queryParams:{publicAccessBlock:""}})}generatePresignedGetUrl($,J,Y=3600){let{accessKeyId:Q,secretAccessKey:W}=this.getCredentials(),U=`${$}.s3.${this.region}.amazonaws.com`,Z=new Date,z=Z.toISOString().replace(/[:-]|\.\d{3}/g,""),H=Z.toISOString().slice(0,10).replace(/-/g,""),K=`${H}/${this.region}/s3/aws4_request`,B=`${Q}/${K}`,O=new URLSearchParams({"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":B,"X-Amz-Date":z,"X-Amz-Expires":Y.toString(),"X-Amz-SignedHeaders":"host"}),X=["GET",`/${J}`,O.toString(),`host:${U}
115
+ `,"host","UNSIGNED-PAYLOAD"].join(`
116
+ `),j=["AWS4-HMAC-SHA256",z,K,c.createHash("sha256").update(X).digest("hex")].join(`
117
+ `),q=c.createHmac("sha256",`AWS4${W}`).update(H).digest(),E=c.createHmac("sha256",q).update(this.region).digest(),F=c.createHmac("sha256",E).update("s3").digest(),w=c.createHmac("sha256",F).update("aws4_request").digest(),T=c.createHmac("sha256",w).update(j).digest("hex");return O.append("X-Amz-Signature",T),`https://${U}/${J}?${O.toString()}`}generatePresignedPutUrl($,J,Y,Q=3600){let{accessKeyId:W,secretAccessKey:U}=this.getCredentials(),Z=`${$}.s3.${this.region}.amazonaws.com`,z=new Date,H=z.toISOString().replace(/[:-]|\.\d{3}/g,""),K=z.toISOString().slice(0,10).replace(/-/g,""),B=`${K}/${this.region}/s3/aws4_request`,O=`${W}/${B}`,X=new URLSearchParams({"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":O,"X-Amz-Date":H,"X-Amz-Expires":Q.toString(),"X-Amz-SignedHeaders":"content-type;host"}),j=["PUT",`/${J}`,X.toString(),`content-type:${Y}
118
+ host:${Z}
119
+ `,"content-type;host","UNSIGNED-PAYLOAD"].join(`
120
+ `),q=["AWS4-HMAC-SHA256",H,B,c.createHash("sha256").update(j).digest("hex")].join(`
121
+ `),E=c.createHmac("sha256",`AWS4${U}`).update(K).digest(),F=c.createHmac("sha256",E).update(this.region).digest(),w=c.createHmac("sha256",F).update("s3").digest(),T=c.createHmac("sha256",w).update("aws4_request").digest(),S=c.createHmac("sha256",T).update(q).digest("hex");return X.append("X-Amz-Signature",S),`https://${Z}/${J}?${X.toString()}`}async createMultipartUpload($,J,Y){let Q={};if(Y?.contentType)Q["Content-Type"]=Y.contentType;if(Y?.metadata)for(let[U,Z]of Object.entries(Y.metadata))Q[`x-amz-meta-${U}`]=Z;return{UploadId:(await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${$}/${J}`,queryParams:{uploads:""},headers:Q}))?.InitiateMultipartUploadResult?.UploadId}}async uploadPart($,J,Y,Q,W){let{accessKeyId:U,secretAccessKey:Z,sessionToken:z}=this.getCredentials(),H=`${$}.s3.${this.region}.amazonaws.com`,K=`https://${H}/${J}?partNumber=${Q}&uploadId=${encodeURIComponent(Y)}`,B=new Date,O=B.toISOString().replace(/[:-]|\.\d{3}/g,""),X=B.toISOString().slice(0,10).replace(/-/g,""),j=c.createHash("sha256").update(W).digest("hex"),q={host:H,"x-amz-date":O,"x-amz-content-sha256":j};if(z)q["x-amz-security-token"]=z;let E=Object.keys(q).sort().map((f)=>`${f.toLowerCase()}:${q[f].trim()}
122
+ `).join(""),F=Object.keys(q).sort().map((f)=>f.toLowerCase()).join(";"),w=["PUT",`/${J}`,`partNumber=${Q}&uploadId=${encodeURIComponent(Y)}`,E,F,j].join(`
123
+ `),T="AWS4-HMAC-SHA256",S=`${X}/${this.region}/s3/aws4_request`,R=[T,O,S,c.createHash("sha256").update(w).digest("hex")].join(`
124
+ `),C=c.createHmac("sha256",`AWS4${Z}`).update(X).digest(),D=c.createHmac("sha256",C).update(this.region).digest(),k=c.createHmac("sha256",D).update("s3").digest(),u=c.createHmac("sha256",k).update("aws4_request").digest(),b=c.createHmac("sha256",u).update(R).digest("hex"),v=`${T} Credential=${U}/${S}, SignedHeaders=${F}, Signature=${b}`,y=await fetch(K,{method:"PUT",headers:{...q,Authorization:v},body:W});if(!y.ok){let f=await y.text();throw Error(`Upload part failed: ${y.status} ${f}`)}return{ETag:y.headers.get("etag")||""}}async completeMultipartUpload($,J,Y,Q){let U=`<?xml version="1.0" encoding="UTF-8"?>
125
+ <CompleteMultipartUpload>${Q.sort((Z,z)=>Z.PartNumber-z.PartNumber).map((Z)=>`<Part><PartNumber>${Z.PartNumber}</PartNumber><ETag>${Z.ETag}</ETag></Part>`).join("")}</CompleteMultipartUpload>`;await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${$}/${J}`,queryParams:{uploadId:Y},headers:{"Content-Type":"application/xml"},body:U})}async abortMultipartUpload($,J,Y){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${$}/${J}`,queryParams:{uploadId:Y}})}async listMultipartUploads($){let Y=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${$}`,queryParams:{uploads:""}}))?.ListMultipartUploadsResult?.Upload;if(!Y)return[];return(Array.isArray(Y)?Y:[Y]).map((W)=>({Key:W.Key,UploadId:W.UploadId,Initiated:W.Initiated}))}async restoreObject($,J,Y,Q="Standard"){let W=`<?xml version="1.0" encoding="UTF-8"?>
126
+ <RestoreRequest>
127
+ <Days>${Y}</Days>
128
+ <GlacierJobParameters>
129
+ <Tier>${Q}</Tier>
130
+ </GlacierJobParameters>
131
+ </RestoreRequest>`;await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${$}/${J}`,queryParams:{restore:""},headers:{"Content-Type":"application/xml"},body:W})}async selectObjectContent($,J,Y,Q,W="JSON"){let U="";if(Q==="CSV")U="<CSV><FileHeaderInfo>USE</FileHeaderInfo></CSV>";else if(Q==="JSON")U="<JSON><Type>DOCUMENT</Type></JSON>";else U="<Parquet/>";let Z="";if(W==="CSV")Z="<CSV/>";else Z="<JSON/>";let z=`<?xml version="1.0" encoding="UTF-8"?>
132
+ <SelectObjectContentRequest>
133
+ <Expression>${Y}</Expression>
134
+ <ExpressionType>SQL</ExpressionType>
135
+ <InputSerialization>${U}</InputSerialization>
136
+ <OutputSerialization>${Z}</OutputSerialization>
137
+ </SelectObjectContentRequest>`;return await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${$}/${J}`,queryParams:{select:"","select-type":"2"},headers:{"Content-Type":"application/xml"},body:z,rawResponse:!0})}async getSignedUrl($){let{bucket:J,key:Y,expiresIn:Q=3600,operation:W="getObject"}=$,{accessKeyId:U,secretAccessKey:Z,sessionToken:z}=this.getCredentials(),H=new Date,K=H.toISOString().replace(/[:-]|\.\d{3}/g,""),B=H.toISOString().slice(0,10).replace(/-/g,""),O=`${J}.s3.${this.region}.amazonaws.com`,X=W==="putObject"?"PUT":"GET",j="AWS4-HMAC-SHA256",q=`${B}/${this.region}/s3/aws4_request`,F={"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":`${U}/${q}`,"X-Amz-Date":K,"X-Amz-Expires":Q.toString(),"X-Amz-SignedHeaders":"host"};if(z)F["X-Amz-Security-Token"]=z;let T=Object.keys(F).sort().map((n)=>`${encodeURIComponent(n)}=${encodeURIComponent(F[n])}`).join("&"),S="/"+Y,R=`host:${O}
138
+ `,k=[X,S,T,R,"host","UNSIGNED-PAYLOAD"].join(`
139
+ `),u=["AWS4-HMAC-SHA256",K,q,c.createHash("sha256").update(k).digest("hex")].join(`
140
+ `),b=c.createHmac("sha256",`AWS4${Z}`).update(B).digest(),v=c.createHmac("sha256",b).update(this.region).digest(),y=c.createHmac("sha256",v).update("s3").digest(),f=c.createHmac("sha256",y).update("aws4_request").digest(),m=c.createHmac("sha256",f).update(u).digest("hex");return`https://${O}${S}?${T}&X-Amz-Signature=${m}`}async listObjects($){let{bucket:J,prefix:Y,maxKeys:Q=1000,continuationToken:W}=$,U={"list-type":"2","max-keys":Q.toString()};if(Y)U.prefix=Y;if(W)U["continuation-token"]=W;let Z=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${J}`,queryParams:U}),z=[],H=Z?.ListBucketResult;if(H?.Contents){let K=Array.isArray(H.Contents)?H.Contents:[H.Contents];for(let B of K)z.push({Key:B.Key||"",LastModified:B.LastModified||"",Size:Number.parseInt(B.Size||"0"),ETag:B.ETag})}return{objects:z,nextContinuationToken:H?.NextContinuationToken}}async emptyBucket($){let J=0,Y=await this.listAllObjects({bucket:$});if(Y.length>0)for(let Q=0;Q<Y.length;Q+=1000){let U=Y.slice(Q,Q+1000).map((Z)=>Z.Key);await this.deleteObjects($,U),J+=U.length}try{let Q,W;do{let U=await this.listObjectVersions({bucket:$,keyMarker:Q,versionIdMarker:W,maxKeys:1000}),Z=[];if(U.versions)for(let z of U.versions)Z.push({Key:z.Key,VersionId:z.VersionId});if(U.deleteMarkers)for(let z of U.deleteMarkers)Z.push({Key:z.Key,VersionId:z.VersionId});if(Z.length>0)await this.deleteObjectVersions($,Z),J+=Z.length;Q=U.nextKeyMarker,W=U.nextVersionIdMarker}while(Q)}catch{}return{deletedCount:J}}async listObjectVersions($){let{bucket:J,prefix:Y,keyMarker:Q,versionIdMarker:W,maxKeys:U=1000}=$,Z={versions:"","max-keys":U.toString()};if(Y)Z.prefix=Y;if(Q)Z["key-marker"]=Q;if(W)Z["version-id-marker"]=W;let z=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${J}`,queryParams:Z}),H=[],K=[];if(z.Version){let B=Array.isArray(z.Version)?z.Version:[z.Version];for(let O of B)H.push({Key:O.Key,VersionId:O.VersionId,IsLatest:O.IsLatest==="true"})}if(z.DeleteMarker){let B=Array.isArray(z.DeleteMarker)?z.DeleteMarker:[z.DeleteMarker];for(let O of B)K.push({Key:O.Key,VersionId:O.VersionId,IsLatest:O.IsLatest==="true"})}return{versions:H,deleteMarkers:K,nextKeyMarker:z.NextKeyMarker,nextVersionIdMarker:z.NextVersionIdMarker}}async deleteObjectVersions($,J){let Y=`<?xml version="1.0" encoding="UTF-8"?>
141
+ <Delete>
142
+ <Quiet>true</Quiet>
143
+ ${J.map((W)=>`<Object><Key>${W.Key}</Key>${W.VersionId?`<VersionId>${W.VersionId}</VersionId>`:""}</Object>`).join(`
144
+ `)}
145
+ </Delete>`,Q=c.createHash("md5").update(Y).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${$}`,queryParams:{delete:""},body:Y,headers:{"Content-Type":"application/xml","Content-MD5":Q}})}}var V0=Y$(()=>{W$()});var F6={};c$(F6,{CloudFrontClient:()=>j$});class j${client;constructor($){this.client=new l}async createInvalidation($){let J=$.callerReference||Date.now().toString(),Y=`<?xml version="1.0" encoding="UTF-8"?>
146
+ <InvalidationBatch>
147
+ <Paths>
148
+ <Quantity>${$.paths.length}</Quantity>
149
+ <Items>
150
+ ${$.paths.map((W)=>`<Path>${W}</Path>`).join(`
151
+ `)}
152
+ </Items>
153
+ </Paths>
154
+ <CallerReference>${J}</CallerReference>
155
+ </InvalidationBatch>`,Q=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:`/2020-05-31/distribution/${$.distributionId}/invalidation`,body:Y,headers:{"Content-Type":"application/xml"}});return{Id:Q.Id||Q.Invalidation?.Id,Status:Q.Status||Q.Invalidation?.Status||"InProgress",CreateTime:Q.CreateTime||Q.Invalidation?.CreateTime||new Date().toISOString()}}async getInvalidation($,J){let Y=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}/invalidation/${J}`});return{Id:Y.Id||Y.Invalidation?.Id,Status:Y.Status||Y.Invalidation?.Status,CreateTime:Y.CreateTime||Y.Invalidation?.CreateTime}}async listInvalidations($){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}/invalidation`}),Y=[];if(J.InvalidationSummary){let Q=Array.isArray(J.InvalidationSummary)?J.InvalidationSummary:[J.InvalidationSummary];Y.push(...Q.map((W)=>({Id:W.Id,Status:W.Status,CreateTime:W.CreateTime})))}return Y}async waitForInvalidation($,J){let Q=0;while(Q<60){if((await this.getInvalidation($,J)).Status==="Completed")return;await new Promise((U)=>setTimeout(U,5000)),Q++}throw Error(`Timeout waiting for invalidation ${J} to complete`)}async listDistributions(){let $=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/distribution"}),J=[],W=($.DistributionList||$).Items?.DistributionSummary;if(W){let U=Array.isArray(W)?W:[W];J.push(...U.map((Z)=>({Id:Z.Id,ARN:Z.ARN,Status:Z.Status,DomainName:Z.DomainName,Aliases:Z.Aliases||void 0,Enabled:Z.Enabled==="true"||Z.Enabled===!0})))}return J}async getDistribution($){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}`}),Y=J.Distribution||J;return{Id:Y.Id,ARN:Y.ARN,Status:Y.Status,DomainName:Y.DomainName,Aliases:Y.DistributionConfig?.Aliases?.Items||Y.Aliases?.Items||[],Enabled:Y.DistributionConfig?.Enabled==="true"||Y.DistributionConfig?.Enabled===!0}}async getDistributionConfig($){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}/config`});return{ETag:J.ETag||"",DistributionConfig:J.DistributionConfig||J}}async invalidateAll($){return this.createInvalidation({distributionId:$,paths:["/*"]})}async invalidatePaths($,J){let Y=J.map((Q)=>Q.startsWith("/")?Q:`/${Q}`);return this.createInvalidation({distributionId:$,paths:Y})}async invalidatePattern($,J){let Y=J.startsWith("/")?J:`/${J}`;return this.createInvalidation({distributionId:$,paths:[Y]})}async invalidateAfterDeployment($){let{distributionId:J,changedPaths:Y,invalidateAll:Q=!1,wait:W=!1}=$,U;if(Q||!Y||Y.length===0)U=await this.invalidateAll(J);else U=await this.invalidatePaths(J,Y);if(W)await this.waitForInvalidation(J,U.Id);return{invalidationId:U.Id,status:U.Status}}async findDistributionByDomain($){return(await this.listDistributions()).find((Q)=>{if(Q.DomainName===$)return!0;if(Q.Aliases?.Items&&Q.Aliases.Items.includes($))return!0;return!1})||null}async batchInvalidate($,J=["/*"]){return await Promise.all($.map(async(Q)=>{let W=await this.createInvalidation({distributionId:Q,paths:J});return{distributionId:Q,invalidationId:W.Id,status:W.Status}}))}async updateCustomErrorResponses($){let{distributionId:J,customErrorResponses:Y}=$,Q=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${J}/config`,returnHeaders:!0}),W=Q.headers?.etag||Q.headers?.ETag||"",U=Q.body?.DistributionConfig||Q.DistributionConfig;if(!U)throw Error("Failed to get current distribution config");if(Y.length===0)U.CustomErrorResponses={Quantity:0};else U.CustomErrorResponses={Quantity:Y.length,Items:{CustomErrorResponse:Y.map((K)=>({ErrorCode:K.errorCode,...K.responsePagePath&&{ResponsePagePath:K.responsePagePath},...K.responseCode&&{ResponseCode:K.responseCode},...K.errorCachingMinTTL!==void 0&&{ErrorCachingMinTTL:K.errorCachingMinTTL}}))}};let Z=this.buildDistributionConfigXml(U),z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${J}/config`,body:Z,headers:{"Content-Type":"application/xml","If-Match":W}}),H=z.Distribution||z;return{Distribution:{Id:H.Id,ARN:H.ARN,Status:H.Status,DomainName:H.DomainName,Aliases:H.DistributionConfig?.Aliases?.Items||[],Enabled:H.DistributionConfig?.Enabled==="true"||H.DistributionConfig?.Enabled===!0},ETag:z.ETag||""}}async removeCustomErrorResponses($){return this.updateCustomErrorResponses({distributionId:$,customErrorResponses:[]})}async updateDistribution($){let{distributionId:J,aliases:Y,certificateArn:Q,comment:W}=$,U=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${J}/config`,returnHeaders:!0}),Z=U.headers?.etag||U.headers?.ETag||"",z=U.body?.DistributionConfig||U.DistributionConfig;if(!z)throw Error("Failed to get current distribution config");if(Y&&Y.length>0)z.Aliases={Quantity:Y.length,Items:{Item:Y}};if(Q)z.ViewerCertificate={ACMCertificateArn:Q,SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021",CertificateSource:"acm"};if(W)z.Comment=W;let H=this.buildDistributionConfigXml(z),K=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${J}/config`,body:H,headers:{"Content-Type":"application/xml","If-Match":Z}}),B=K.Distribution||K;return{Distribution:{Id:B.Id,ARN:B.ARN,Status:B.Status,DomainName:B.DomainName,Aliases:Y?{Quantity:Y.length,Items:Y}:{Quantity:0,Items:[]},Enabled:B.DistributionConfig?.Enabled==="true"||B.DistributionConfig?.Enabled===!0},ETag:K.ETag||""}}buildDistributionConfigXml($){let J=(U)=>{return U.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")},Y={Items:"",Methods:"Method",Headers:"Name",Cookies:"Name",QueryStringCacheKeys:"Name",TrustedKeyGroups:"KeyGroup",TrustedSigners:"AwsAccountNumber",LambdaFunctionAssociations:"LambdaFunctionAssociation",FunctionAssociations:"FunctionAssociation",CacheBehaviors:"CacheBehavior",CustomErrorResponses:"CustomErrorResponse",GeoRestriction:"Location"},Q={Origins:"Origin",Aliases:"CNAME",AllowedMethods:"Method",CachedMethods:"Method",CustomErrorResponses:"CustomErrorResponse",CacheBehaviors:"CacheBehavior"},W=(U,Z,z="",H="")=>{if(Z===null||Z===void 0)return"";if(U.startsWith("@_")||U==="?xml")return"";if(typeof Z==="boolean")return`${z}<${U}>${Z}</${U}>
156
+ `;if(typeof Z==="number"||typeof Z==="string")return`${z}<${U}>${J(String(Z))}</${U}>
157
+ `;if(Array.isArray(Z)){let K=Y[U]||U.replace(/s$/,"");return Z.map((B)=>W(K,B,z,U)).join("")}if(typeof Z==="object"){if(U==="Items"){let B=Q[H]||"",O=Object.keys(Z).filter((X)=>!X.startsWith("@_"));if(O.length===1&&!Array.isArray(Z[O[0]])){let X=O[0],j=Z[X];if(typeof j==="string")return`${z}<Items>
158
+ ${z} <${X}>${J(j)}</${X}>
159
+ ${z}</Items>
160
+ `;else if(typeof j==="object"&&!Array.isArray(j))return`${z}<Items>
161
+ ${W(X,j,z+" ",U)}${z}</Items>
162
+ `}if(O.length===1&&Array.isArray(Z[O[0]])){let X=O[0],j=Z[X],q="";for(let E of j)if(typeof E==="string")q+=`${z} <${X}>${J(E)}</${X}>
163
+ `;else q+=W(X,E,z+" ",U);return`${z}<Items>
164
+ ${q}${z}</Items>
165
+ `}if(Array.isArray(Z)){let X="",j=B||"Item";for(let q of Z)if(typeof q==="string")X+=`${z} <${j}>${J(q)}</${j}>
166
+ `;else X+=W(j,q,z+" ",U);return`${z}<Items>
167
+ ${X}${z}</Items>
168
+ `}}let K="";for(let[B,O]of Object.entries(Z))if(!B.startsWith("@_"))K+=W(B,O,z+" ",U);if(K==="")return`${z}<${U}/>
169
+ `;return`${z}<${U}>
170
+ ${K}${z}</${U}>
171
+ `}return""};return`<?xml version="1.0" encoding="UTF-8"?>
172
+ <DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
173
+ ${Object.entries($).filter(([U])=>!U.startsWith("@_")).map(([U,Z])=>W(U,Z," ","DistributionConfig")).join("")}</DistributionConfig>`}async addAliases($,J,Y){return this.updateDistribution({distributionId:$,aliases:J,certificateArn:Y})}async createFunction($){let{name:J,code:Y,comment:Q="",runtime:W="cloudfront-js-2.0"}=$,U=`<?xml version="1.0" encoding="UTF-8"?>
174
+ <CreateFunctionRequest xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
175
+ <Name>${J}</Name>
176
+ <FunctionConfig>
177
+ <Comment>${Q}</Comment>
178
+ <Runtime>${W}</Runtime>
179
+ </FunctionConfig>
180
+ <FunctionCode>${Buffer.from(Y).toString("base64")}</FunctionCode>
181
+ </CreateFunctionRequest>`,Z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/function",body:U,headers:{"Content-Type":"application/xml"}}),z=Z.FunctionSummary||Z;return{FunctionARN:z.FunctionMetadata?.FunctionARN||z.FunctionARN,Name:z.Name||J,Stage:z.FunctionMetadata?.Stage||"DEVELOPMENT",ETag:Z.ETag||""}}async listFunctions(){let $=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/function"}),J=[],Y=$.FunctionList?.Items?.FunctionSummary;if(Y){let Q=Array.isArray(Y)?Y:[Y];for(let W of Q)J.push({Name:W.Name,FunctionARN:W.FunctionMetadata?.FunctionARN,Stage:W.FunctionMetadata?.Stage,CreatedTime:W.FunctionMetadata?.CreatedTime,LastModifiedTime:W.FunctionMetadata?.LastModifiedTime})}return J}async getFunction($,J="LIVE"){try{let Y=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/function/${$}`,queryParams:{Stage:J},returnHeaders:!0}),Q=Y.body?.FunctionSummary||Y.FunctionSummary||Y.body||Y;return{FunctionARN:Q.FunctionMetadata?.FunctionARN,Name:Q.Name||$,Stage:Q.FunctionMetadata?.Stage||J,ETag:Y.headers?.etag||Y.ETag||"",FunctionCode:Q.FunctionCode}}catch(Y){if(Y.message?.includes("404")||Y.message?.includes("NoSuchFunctionExists"))return null;throw Y}}async publishFunction($,J){let Y,Q;if(typeof $==="object")Y=$.Name,Q=$.IfMatch;else Y=$,Q=J;if(!Q){let Z=await this.getFunction(Y,"DEVELOPMENT");if(!Z)throw Error(`Function ${Y} not found`);Q=Z.ETag}let W=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:`/2020-05-31/function/${Y}/publish`,headers:{"If-Match":Q}}),U=W.FunctionSummary||W;return{FunctionARN:U.FunctionMetadata?.FunctionARN,Stage:U.FunctionMetadata?.Stage||"LIVE",FunctionSummary:U}}async describeFunction($){let{Name:J,Stage:Y="DEVELOPMENT"}=$,Q=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/function/${J}/describe`,queryParams:{Stage:Y},returnHeaders:!0});return{ETag:Q.headers?.etag||Q.ETag||"",FunctionSummary:Q.body?.FunctionSummary||Q.FunctionSummary||Q.body||Q}}async updateFunction($){let{Name:J,FunctionCode:Y,FunctionConfig:Q,IfMatch:W}=$,U=`<?xml version="1.0" encoding="UTF-8"?>
182
+ <UpdateFunctionRequest xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
183
+ <FunctionConfig>
184
+ <Comment>${Q.Comment}</Comment>
185
+ <Runtime>${Q.Runtime}</Runtime>
186
+ </FunctionConfig>
187
+ <FunctionCode>${Buffer.from(Y).toString("base64")}</FunctionCode>
188
+ </UpdateFunctionRequest>`,Z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/function/${J}`,body:U,headers:{"Content-Type":"application/xml","If-Match":W},returnHeaders:!0});return{ETag:Z.headers?.etag||Z.ETag||"",FunctionSummary:Z.body?.FunctionSummary||Z.FunctionSummary||Z.body||Z}}async deleteFunction($,J){let Y=J;if(!Y){let Q=await this.getFunction($,"DEVELOPMENT");if(!Q)return;Y=Q.ETag}await this.client.request({service:"cloudfront",region:"us-east-1",method:"DELETE",path:`/2020-05-31/function/${$}`,headers:{"If-Match":Y}})}async createIndexRewriteFunction($){return this.createFunction({name:$,code:`function handler(event) {
189
+ var request = event.request;
190
+ var uri = request.uri;
191
+
192
+ // Check if the request is for a directory (ends with /)
193
+ if (uri.endsWith('/')) {
194
+ request.uri += 'index.html';
195
+ }
196
+ // Check if the request doesn't have a file extension
197
+ else if (!uri.includes('.')) {
198
+ // Add trailing slash to redirect to directory
199
+ request.uri += '/index.html';
200
+ }
201
+
202
+ return request;
203
+ }`,comment:"Rewrite directory requests to index.html for S3 static sites",runtime:"cloudfront-js-2.0"})}async listOriginAccessControls(){let $=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/origin-access-control"}),J=[];if($.OriginAccessControlList?.Items?.OriginAccessControlSummary){let Y=Array.isArray($.OriginAccessControlList.Items.OriginAccessControlSummary)?$.OriginAccessControlList.Items.OriginAccessControlSummary:[$.OriginAccessControlList.Items.OriginAccessControlSummary];J.push(...Y.map((Q)=>({Id:Q.Id,Name:Q.Name,Description:Q.Description,SigningProtocol:Q.SigningProtocol,SigningBehavior:Q.SigningBehavior,OriginAccessControlOriginType:Q.OriginAccessControlOriginType})))}return J}async createOriginAccessControl($){let{name:J,description:Y=`OAC for ${J}`,signingProtocol:Q="sigv4",signingBehavior:W="always",originType:U="s3"}=$,Z=`<?xml version="1.0" encoding="UTF-8"?>
204
+ <OriginAccessControlConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
205
+ <Name>${J}</Name>
206
+ <Description>${Y}</Description>
207
+ <SigningProtocol>${Q}</SigningProtocol>
208
+ <SigningBehavior>${W}</SigningBehavior>
209
+ <OriginAccessControlOriginType>${U}</OriginAccessControlOriginType>
210
+ </OriginAccessControlConfig>`,z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/origin-access-control",body:Z,headers:{"Content-Type":"application/xml"},returnHeaders:!0}),H=z.body?.OriginAccessControl||z.OriginAccessControl||z.body||z;return{Id:H.Id,Name:H.OriginAccessControlConfig?.Name||J,Description:H.OriginAccessControlConfig?.Description||Y,SigningProtocol:H.OriginAccessControlConfig?.SigningProtocol||Q,SigningBehavior:H.OriginAccessControlConfig?.SigningBehavior||W,OriginAccessControlOriginType:H.OriginAccessControlConfig?.OriginAccessControlOriginType||U,ETag:z.headers?.etag||z.ETag||""}}async findOrCreateOriginAccessControl($){let Y=(await this.listOriginAccessControls()).find((W)=>W.Name===$);if(Y)return{Id:Y.Id,Name:Y.Name,isNew:!1};let Q=await this.createOriginAccessControl({name:$});return{Id:Q.Id,Name:Q.Name,isNew:!0}}async createDistributionForS3($){let{bucketName:J,bucketRegion:Y,originAccessControlId:Q,aliases:W=[],certificateArn:U,defaultRootObject:Z="index.html",comment:z=`Distribution for ${J}`,priceClass:H="PriceClass_100",enabled:K=!0}=$,B=`S3-${J}`,O=`${J}.s3.${Y}.amazonaws.com`,X=`${Date.now()}-${Math.random().toString(36).slice(2)}`,j="<Aliases><Quantity>0</Quantity></Aliases>";if(W.length>0)j=`<Aliases>
211
+ <Quantity>${W.length}</Quantity>
212
+ <Items>
213
+ ${W.map((T)=>`<CNAME>${T}</CNAME>`).join(`
214
+ `)}
215
+ </Items>
216
+ </Aliases>`;let q=`<ViewerCertificate>
217
+ <CloudFrontDefaultCertificate>true</CloudFrontDefaultCertificate>
218
+ </ViewerCertificate>`;if(U&&W.length>0)q=`<ViewerCertificate>
219
+ <ACMCertificateArn>${U}</ACMCertificateArn>
220
+ <SSLSupportMethod>sni-only</SSLSupportMethod>
221
+ <MinimumProtocolVersion>TLSv1.2_2021</MinimumProtocolVersion>
222
+ <CertificateSource>acm</CertificateSource>
223
+ </ViewerCertificate>`;let E=`<?xml version="1.0" encoding="UTF-8"?>
224
+ <DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
225
+ <CallerReference>${X}</CallerReference>
226
+ <Comment>${z}</Comment>
227
+ <DefaultRootObject>${Z}</DefaultRootObject>
228
+ <Origins>
229
+ <Quantity>1</Quantity>
230
+ <Items>
231
+ <Origin>
232
+ <Id>${B}</Id>
233
+ <DomainName>${O}</DomainName>
234
+ <OriginPath></OriginPath>
235
+ <S3OriginConfig>
236
+ <OriginAccessIdentity></OriginAccessIdentity>
237
+ </S3OriginConfig>
238
+ <OriginAccessControlId>${Q}</OriginAccessControlId>
239
+ </Origin>
240
+ </Items>
241
+ </Origins>
242
+ <DefaultCacheBehavior>
243
+ <TargetOriginId>${B}</TargetOriginId>
244
+ <ViewerProtocolPolicy>redirect-to-https</ViewerProtocolPolicy>
245
+ <AllowedMethods>
246
+ <Quantity>2</Quantity>
247
+ <Items>
248
+ <Method>GET</Method>
249
+ <Method>HEAD</Method>
250
+ </Items>
251
+ <CachedMethods>
252
+ <Quantity>2</Quantity>
253
+ <Items>
254
+ <Method>GET</Method>
255
+ <Method>HEAD</Method>
256
+ </Items>
257
+ </CachedMethods>
258
+ </AllowedMethods>
259
+ <Compress>true</Compress>
260
+ <CachePolicyId>658327ea-f89d-4fab-a63d-7e88639e58f6</CachePolicyId>
261
+ </DefaultCacheBehavior>
262
+ ${j}
263
+ ${q}
264
+ <PriceClass>${H}</PriceClass>
265
+ <Enabled>${K}</Enabled>
266
+ <HttpVersion>http2and3</HttpVersion>
267
+ <IsIPV6Enabled>true</IsIPV6Enabled>
268
+ <CustomErrorResponses>
269
+ <Quantity>1</Quantity>
270
+ <Items>
271
+ <CustomErrorResponse>
272
+ <ErrorCode>403</ErrorCode>
273
+ <ResponsePagePath>/index.html</ResponsePagePath>
274
+ <ResponseCode>200</ResponseCode>
275
+ <ErrorCachingMinTTL>300</ErrorCachingMinTTL>
276
+ </CustomErrorResponse>
277
+ </Items>
278
+ </CustomErrorResponses>
279
+ </DistributionConfig>`,F=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/distribution",body:E,headers:{"Content-Type":"application/xml"},returnHeaders:!0}),w=F.body?.Distribution||F.Distribution||F.body||F;return{Id:w.Id,ARN:w.ARN,DomainName:w.DomainName,Status:w.Status,ETag:F.headers?.etag||F.ETag||""}}static getS3BucketPolicyForCloudFront($,J){return{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:`arn:aws:s3:::${$}/*`,Condition:{StringEquals:{"AWS:SourceArn":J}}}]}}async waitForDistributionDeployed($,J=60){for(let Y=0;Y<J;Y++){if((await this.getDistribution($)).Status==="Deployed")return!0;await new Promise((W)=>setTimeout(W,30000))}return!1}async disableDistribution($){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}/config`,returnHeaders:!0}),Y=J.headers?.etag||J.headers?.ETag||"",Q=J.body?.DistributionConfig||J.DistributionConfig;if(!Q)throw Error("Failed to get current distribution config");Q.Enabled=!1;let W=this.buildDistributionConfigXml(Q),U=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${$}/config`,body:W,headers:{"Content-Type":"application/xml","If-Match":Y},returnHeaders:!0});return{ETag:U.headers?.etag||U.headers?.ETag||U.ETag||""}}async deleteDistribution($,J){let Y=J||"";if(!Y){let Q=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}`,returnHeaders:!0});Y=Q.headers?.etag||Q.headers?.ETag||""}await this.client.request({service:"cloudfront",region:"us-east-1",method:"DELETE",path:`/2020-05-31/distribution/${$}`,headers:{"If-Match":Y}})}async waitForDistributionDisabled($,J=60){for(let Y=0;Y<J;Y++){let Q=await this.getDistribution($);if(Q.Status==="Deployed"&&!Q.Enabled)return!0;await new Promise((W)=>setTimeout(W,30000))}return!1}async removeAlias($,J){let Y=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}/config`,returnHeaders:!0}),Q=Y.headers?.etag||Y.headers?.ETag||"",W=Y.body?.DistributionConfig||Y.DistributionConfig;if(!W)throw Error("Failed to get current distribution config");let U=[];if(W.Aliases?.Items){if(Array.isArray(W.Aliases.Items))U=W.Aliases.Items;else if(typeof W.Aliases.Items==="object"){let K=W.Aliases.Items.CNAME;if(typeof K==="string")U=[K];else if(Array.isArray(K))U=K}}if(U.length===0)throw Error("Distribution has no aliases to remove");let Z=U.filter((K)=>K!==J);if(Z.length===U.length)throw Error(`Alias ${J} not found in distribution`);if(W.Aliases.Quantity=Z.length,W.Aliases.Items=Z.length>0?Z:void 0,Z.length===0)W.ViewerCertificate={CloudFrontDefaultCertificate:!0,MinimumProtocolVersion:"TLSv1.2_2021"};let z=this.buildDistributionConfigXml(W),H=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${$}/config`,body:z,headers:{"Content-Type":"application/xml","If-Match":Q},returnHeaders:!0});return{ETag:H.headers?.etag||H.headers?.ETag||H.ETag||""}}}var M0=Y$(()=>{W$()});var R6={};c$(R6,{uploadStaticFiles:()=>T9,invalidateCache:()=>L9,generateStaticSiteTemplate:()=>F9,deployStaticSiteFull:()=>_W,deployStaticSite:()=>w9,deleteStaticSite:()=>EW});function F9($){let{bucketName:J,domain:Y,certificateArn:Q,hostedZoneId:W,defaultRootObject:U="index.html",errorDocument:Z="404.html"}=$,z={},H={};z.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:J,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:U,ErrorDocument:Z}}},H.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},H.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) {
280
+ var request = event.request;
281
+ var uri = request.uri;
282
+
283
+ // If URI ends with /, serve index.html
284
+ if (uri.endsWith('/')) {
285
+ request.uri = uri + 'index.html';
286
+ }
287
+ // If URI doesn't have an extension, append .html
288
+ else if (!uri.includes('.')) {
289
+ request.uri = uri + '.html';
290
+ }
291
+
292
+ return request;
293
+ }`}};let K={Enabled:!0,DefaultRootObject:U,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:[{Id:`S3-${J}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}}],DefaultCacheBehavior:{TargetOriginId:`S3-${J}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]},CustomErrorResponses:[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${U}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${Z}`,ErrorCachingMinTTL:300}]};if(Y&&Q)K.Aliases=[Y],K.ViewerCertificate={AcmCertificateArn:Q,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else K.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(z.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",DependsOn:["S3Bucket","CloudFrontOAC","UrlRewriteFunction"],Properties:{DistributionConfig:K}},H.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},H.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},z.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},Y&&W)z.DNSRecord={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:W,Name:Y,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},z.DNSRecordIPv6={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:W,Name:Y,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},H.SiteUrl={Description:"Site URL",Value:{"Fn::Sub":"https://${DNSRecord}"}};return{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${Y||J}`,Resources:z,Outputs:H}}async function w9($){if($.dnsProvider&&$.dnsProvider.provider!=="route53"){let D=$.domain||($.subdomain&&$.baseDomain?`${$.subdomain}.${$.baseDomain}`:void 0);if(!D)return{success:!1,stackName:$.stackName||`${$.siteName}-static-site`,bucket:$.bucket||`${$.siteName}-${Date.now()}`,message:"Domain is required when using external DNS provider"};return D6({siteName:$.siteName,region:$.region,domain:D,bucket:$.bucket,certificateArn:$.certificateArn,stackName:$.stackName,defaultRootObject:$.defaultRootObject,errorDocument:$.errorDocument,cacheControl:$.cacheControl,tags:$.tags,dnsProvider:$.dnsProvider})}let J=$.region||"us-east-1",Y="us-east-1",Q;if($.domain)Q=$.domain;else if($.subdomain&&$.baseDomain)Q=`${$.subdomain}.${$.baseDomain}`;let W=$.bucket||(Q?Q.replace(/\./g,"-"):`${$.siteName}-${Date.now()}`),U=$.stackName||`${$.siteName}-static-site`,Z=new O$(Y),z=new I$,H=new S$("us-east-1"),K=new h1("us-east-1"),B=$.hostedZoneId,O=$.certificateArn;if(Q&&!B){let D=await z.findHostedZoneForDomain(Q);if(D)B=D.Id.replace("/hostedzone/","");else return{success:!1,stackName:U,bucket:W,message:`No Route53 hosted zone found for ${$.baseDomain||Q}. Please create one first.`}}if(Q&&!O&&B){let D=await H.findCertificateByDomain(Q);if(D&&D.Status==="ISSUED")O=D.CertificateArn;else O=(await K.requestAndValidate({domainName:Q,hostedZoneId:B,waitForValidation:!0,maxWaitMinutes:10})).certificateArn}let X=!1,j;try{let D=await Z.describeStacks({stackName:U});if(D.Stacks.length>0){let k=D.Stacks[0],u=k.StackStatus;if(u==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await Z.waitForStack(U,"stack-delete-complete"),X=!1;else if(u==="DELETE_COMPLETE")X=!1;else X=!0,j=(k.Outputs||[]).find((v)=>v.OutputKey==="BucketName")?.OutputValue}}catch(D){if(D.message?.includes("does not exist")||D.code==="ValidationError")X=!1;else throw D}let q=j||W;if(!X){let D=new X$(J),k=new j$,u=!1;try{if((await D.headBucket(W)).exists){console.log(`Found orphaned S3 bucket ${W}, cleaning up...`);try{let v=D.emptyBucket(W).then(()=>D.deleteBucket(W)),y=new Promise((f,m)=>setTimeout(()=>m(Error("Bucket cleanup timeout")),30000));await Promise.race([v,y]),console.log(`Deleted orphaned S3 bucket ${W}`),u=!0}catch(v){console.log(`Note: Could not clean up S3 bucket: ${v.message}`);let y=Date.now().toString(36);q=`${W}-${y}`,console.log(`Using alternative bucket name: ${q}`)}}}catch{}if(Q){try{console.log(`Checking for existing CloudFront distribution for ${Q}...`);let b=await k.listDistributions();for(let v of b){let y=[];if(v.Aliases?.Items){if(Array.isArray(v.Aliases.Items))y=v.Aliases.Items;else if(typeof v.Aliases.Items==="object"){let f=v.Aliases.Items.CNAME;if(typeof f==="string")y=[f];else if(Array.isArray(f))y=f}}if(y.includes(Q)){console.log(`Found existing CloudFront distribution ${v.Id} for ${Q}`);let m=(await k.getDistributionConfig(v.Id)).DistributionConfig?.Origins?.Items,t;if(m){let n=[];if(Array.isArray(m))n=m;else if(m.Origin)n=Array.isArray(m.Origin)?m.Origin:[m.Origin];else n=[m];for(let $$ of n){let V$=($$.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(V$){t=V$[1];break}}}if(t){let n=Q.replace(/\./g,"-");if(!t.startsWith(n)&&!t.includes($.siteName)){console.log(`Warning: Found distribution with mismatched bucket ${t}, skipping...`);continue}if(console.log(`Using existing S3 bucket: ${t}`),B&&v.DomainName)try{console.log(`Ensuring Route53 records exist for ${Q}...`),await z.createAliasRecord({HostedZoneId:B,Name:Q,Type:"A",TargetHostedZoneId:I$.CloudFrontHostedZoneId,TargetDNSName:v.DomainName,EvaluateTargetHealth:!1}),await z.createAliasRecord({HostedZoneId:B,Name:Q,Type:"AAAA",TargetHostedZoneId:I$.CloudFrontHostedZoneId,TargetDNSName:v.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records ensured for ${Q}`)}catch($$){console.log(`Note: Could not update Route53 records: ${$$.message}`)}return{success:!0,stackName:`existing-${v.Id}`,bucket:t,distributionId:v.Id,distributionDomain:v.DomainName,domain:Q,certificateArn:O,message:"Using existing CloudFront distribution"}}}}}catch{}if(B)try{let v=(await z.listResourceRecordSets({HostedZoneId:B})).ResourceRecordSets||[];for(let y of v)if(y.Name===`${Q}.`&&(y.Type==="A"||y.Type==="AAAA")){if(y.AliasTarget){console.log(`Found orphaned Route53 ${y.Type} record for ${Q}, cleaning up...`);try{await z.deleteRecord({HostedZoneId:B,RecordSet:y}),console.log(`Deleted orphaned Route53 ${y.Type} record for ${Q}`)}catch(f){console.log(`Note: Could not delete Route53 record: ${f.message}`)}}}}catch{}}}let E=F9({bucketName:q,domain:Q,certificateArn:O,hostedZoneId:B,defaultRootObject:$.defaultRootObject,errorDocument:$.errorDocument}),F=Object.entries($.tags||{}).map(([D,k])=>({Key:D,Value:k}));F.push({Key:"ManagedBy",Value:"ts-cloud"}),F.push({Key:"Application",Value:$.siteName});let w,T=!1;if(X){T=!0,console.log(`Updating CloudFormation stack: ${U}`),console.log(`Using existing bucket: ${q}`),console.log(`Domain: ${Q||"not specified"}`),console.log(`Certificate ARN: ${O||"not specified"}`);try{w=(await Z.updateStack({stackName:U,templateBody:JSON.stringify(E),capabilities:["CAPABILITY_IAM"],tags:F})).StackId,console.log(`Update initiated, stack ID: ${w}`)}catch(D){if(D.message?.includes("No updates are to be performed")){let k=await Z.describeStacks({stackName:U});w=k.Stacks[0].StackId;let u=k.Stacks[0]?.Outputs||[],b=(v)=>u.find((y)=>y.OutputKey===v)?.OutputValue;return{success:!0,stackId:w,stackName:U,bucket:b("BucketName")||q,distributionId:b("DistributionId"),distributionDomain:b("DistributionDomain"),domain:Q,certificateArn:O,message:"Static site infrastructure is already up to date"}}else throw D}}else console.log(`Creating CloudFormation stack: ${U}`),console.log(`Bucket name: ${q}`),console.log(`Domain: ${Q||"not specified"}`),console.log(`Certificate ARN: ${O||"not specified"}`),console.log("Stack does not exist, creating..."),w=(await Z.createStack({stackName:U,templateBody:JSON.stringify(E),capabilities:["CAPABILITY_IAM"],tags:F,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${w}`);console.log(`Waiting for stack to reach ${T?"stack-update-complete":"stack-create-complete"}...`);try{await Z.waitForStack(U,T?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(D){if(D.message?.includes("must be verified")||D.message?.includes("Access denied for operation")||D.message?.includes("failed")){console.log("CloudFormation deployment failed, trying direct API creation...");let k=new j$;if(Q)try{let u=await k.listDistributions();for(let b of u){let v=[];if(b.Aliases?.Items){if(Array.isArray(b.Aliases.Items))v=b.Aliases.Items;else if(typeof b.Aliases.Items==="object"){let y=b.Aliases.Items.CNAME;if(typeof y==="string")v=[y];else if(Array.isArray(y))v=y}}if(v.includes(Q)){console.log(`Found existing CloudFront distribution ${b.Id} with alias ${Q}`);let f=(await k.getDistributionConfig(b.Id)).DistributionConfig?.Origins?.Items,m;if(f){let t=[];if(Array.isArray(f))t=f;else if(f.Origin)t=Array.isArray(f.Origin)?f.Origin:[f.Origin];else t=[f];for(let n of t){let q$=(n.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(q$){m=q$[1];break}}}if(m)return console.log(`Using existing S3 bucket: ${m}`),{success:!0,stackName:`existing-${b.Id}`,bucket:m,distributionId:b.Id,distributionDomain:b.DomainName,domain:Q,certificateArn:O,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}catch{}console.log("No existing infrastructure found, creating via direct API calls...");try{let u=new X$(J);if((await u.headBucket(q)).exists)console.log(`Using existing S3 bucket: ${q}`);else console.log(`Creating S3 bucket: ${q}...`),await u.createBucket(q);await u.putBucketWebsite(q,{IndexDocument:$.defaultRootObject||"index.html",ErrorDocument:$.errorDocument||"404.html"}),await u.putPublicAccessBlock(q,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1}),console.log(`S3 bucket ${q} configured`);let v=`OAC-${q}`;console.log(`Creating Origin Access Control: ${v}...`);let y=await k.findOrCreateOriginAccessControl(v);console.log(`Origin Access Control ${y.Id} ready`),console.log("Creating CloudFront distribution...");let f=await k.createDistributionForS3({bucketName:q,bucketRegion:J,originAccessControlId:y.Id,aliases:Q?[Q]:[],certificateArn:O,defaultRootObject:$.defaultRootObject||"index.html",comment:`Distribution for ${Q||q}`});console.log(`CloudFront distribution ${f.Id} created`),console.log("Updating S3 bucket policy...");let m=j$.getS3BucketPolicyForCloudFront(q,f.ARN);if(await u.putBucketPolicy(q,m),console.log("S3 bucket policy updated"),Q&&B){console.log(`Creating Route53 records for ${Q}...`);try{await z.createAliasRecord({HostedZoneId:B,Name:Q,Type:"A",TargetHostedZoneId:I$.CloudFrontHostedZoneId,TargetDNSName:f.DomainName,EvaluateTargetHealth:!1}),await z.createAliasRecord({HostedZoneId:B,Name:Q,Type:"AAAA",TargetHostedZoneId:I$.CloudFrontHostedZoneId,TargetDNSName:f.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records created for ${Q}`)}catch(t){console.log(`Note: Could not create Route53 records: ${t.message}`)}}return{success:!0,stackName:`direct-${f.Id}`,bucket:q,distributionId:f.Id,distributionDomain:f.DomainName,domain:Q,certificateArn:O,message:"Static site infrastructure created via direct API calls"}}catch(u){return console.log(`Direct API creation failed: ${u.message}`),{success:!1,stackId:w,stackName:U,bucket:q,message:`Deployment failed: ${u.message}`}}}return{success:!1,stackId:w,stackName:U,bucket:q,message:`Stack deployment failed: ${D.message}`}}let R=(await Z.describeStacks({stackName:U})).Stacks[0]?.Outputs||[],C=(D)=>R.find((k)=>k.OutputKey===D)?.OutputValue;return{success:!0,stackId:w,stackName:U,bucket:C("BucketName")||q,distributionId:C("DistributionId"),distributionDomain:C("DistributionDomain"),domain:Q,certificateArn:O,message:"Static site infrastructure deployed successfully"}}async function T9($){let{sourceDir:J,bucket:Y,region:Q,cacheControl:W="max-age=31536000, public",onProgress:U}=$,Z=new X$(Q),{readdir:z}=await import("node:fs/promises"),{join:H,relative:K}=await import("node:path"),{createHash:B}=await import("node:crypto");async function O(R){let C=[],D=await z(R,{withFileTypes:!0});for(let k of D){let u=H(R,k.name);if(k.isDirectory())C.push(...await O(u));else C.push(u)}return C}function X(R){let C=R.split(".").pop()?.toLowerCase();return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",xml:"application/xml",txt:"text/plain; charset=utf-8"}[C||""]||"application/octet-stream"}function j(R){return B("md5").update(R).digest("hex")}async function q(){let R=new Map,C;do{let D=await Z.listObjects({bucket:Y,maxKeys:1000,continuationToken:C});for(let k of D.objects){let u=k.ETag?.replace(/"/g,"")||"";R.set(k.Key,u)}C=D.nextContinuationToken}while(C);return R}let E=await O(J),F=[],w=0,T=0,S=await q();for(let R of E){let C=K(J,R),D=X(R),k=R.endsWith(".html")?"max-age=3600, public":W;try{let u=Buffer.from(await Bun.file(R).arrayBuffer()),b=j(u),v=S.get(C);if(v&&v===b){T++,U?.(w+T,E.length,C);continue}await Z.putObject({bucket:Y,key:C,body:u,contentType:D,cacheControl:k}),w++,U?.(w+T,E.length,C)}catch(u){F.push(`Failed to upload ${C}: ${u.message}`)}}return{uploaded:w,skipped:T,errors:F}}async function L9($){return{invalidationId:(await new j$().invalidateAll($)).Id}}async function EW($,J="us-east-1"){let Y=new O$(J);try{let Z=((await Y.describeStacks({stackName:$})).Stacks[0]?.Outputs||[]).find((z)=>z.OutputKey==="BucketName")?.OutputValue;if(Z)await new X$(J).emptyBucket(Z)}catch{}await Y.deleteStack($);let Q=await Y.waitForStackComplete($,60,1e4);return{success:Q.success||Q.status==="DELETE_COMPLETE",message:Q.success?"Static site deleted successfully":`Deletion failed: ${Q.status}`}}async function _W($){let{sourceDir:J,cleanBucket:Y=!1,onProgress:Q,...W}=$;Q?.("infrastructure","Deploying CloudFormation stack...");let U=await w9(W);if(!U.success)return U;if(Y){Q?.("clean","Cleaning old files from S3...");try{await new X$(W.region||"us-east-1").emptyBucket(U.bucket)}catch(H){console.log(`Note: Could not clean bucket: ${H.message}`)}}Q?.("upload","Uploading files to S3...");let Z=await T9({sourceDir:J,bucket:U.bucket,region:W.region||"us-east-1",cacheControl:W.cacheControl,onProgress:(H,K,B)=>{Q?.("upload",`${H}/${K}: ${B}`)}});if(Z.errors.length>0)return{...U,success:!1,message:`Upload errors: ${Z.errors.join(", ")}`,filesUploaded:Z.uploaded};if(U.distributionId&&Z.uploaded>0)Q?.("invalidate","Invalidating CloudFront cache..."),await L9(U.distributionId);Q?.("complete","Deployment complete!");let z=Z.skipped>0?`Deployed ${Z.uploaded} files (${Z.skipped} unchanged)`:`Deployed ${Z.uploaded} files successfully`;return{...U,filesUploaded:Z.uploaded,filesSkipped:Z.skipped,message:z}}var S6=Y$(()=>{G0();V0();M0();I1();X0();P6()});function FW($){let{bucketName:J,domain:Y,aliases:Q,certificateArn:W,defaultRootObject:U="index.html",errorDocument:Z="404.html"}=$,z={},H={};z.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:J,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:U,ErrorDocument:Z}}},H.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},H.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) {
294
+ var request = event.request;
295
+ var uri = request.uri;
296
+
297
+ // If URI ends with /, serve index.html
298
+ if (uri.endsWith('/')) {
299
+ request.uri = uri + 'index.html';
300
+ }
301
+ // If URI doesn't have an extension, append .html
302
+ else if (!uri.includes('.')) {
303
+ request.uri = uri + '.html';
304
+ }
305
+
306
+ return request;
307
+ }`}};let K={Enabled:!0,DefaultRootObject:U,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:[{Id:`S3-${J}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}}],DefaultCacheBehavior:{TargetOriginId:`S3-${J}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]},CustomErrorResponses:[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${U}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${Z}`,ErrorCachingMinTTL:300}]};if(Y&&W)K.Aliases=Q&&Q.length>0?Q:[Y],K.ViewerCertificate={AcmCertificateArn:W,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else K.ViewerCertificate={CloudFrontDefaultCertificate:!0};return z.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",DependsOn:["S3Bucket","CloudFrontOAC","UrlRewriteFunction"],Properties:{DistributionConfig:K}},H.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},H.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},z.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},H.SiteUrl={Description:"Site URL",Value:Y?`https://${Y}`:{"Fn::Sub":"https://${CloudFrontDistribution.DomainName}"}},{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${Y||J} (External DNS)`,Resources:z,Outputs:H}}async function D6($){let J=$.region||"us-east-1",Y="us-east-1",Q=$.domain,W=$.bucket||Q.replace(/\./g,"-"),U=$.stackName||`${$.siteName}-static-site`,Z=new O$("us-east-1"),z=new S$("us-east-1"),H=null;if(!$.skipDnsVerification){if(H=p$($.dnsProvider),console.log(`Verifying DNS provider can manage ${Q}...`),!await H.canManageDomain(Q))return{success:!1,stackName:U,bucket:W,message:`DNS provider '${H.name}' cannot manage domain ${Q}. Please check your API credentials and domain ownership.`};console.log(`DNS provider '${H.name}' verified for ${Q}`)}else console.log(`Skipping DNS verification for ${Q}`);let K=$.certificateArn,X=Q.split(".").length===2?`www.${Q}`:void 0;if(!K){console.log(`Checking for existing SSL certificate for ${Q}...`);let b=await z.findCertificateByDomain(Q),v=!1;if(b&&b.Status==="ISSUED"){if(X&&b.SubjectAlternativeNames)v=b.SubjectAlternativeNames.includes(X)||b.SubjectAlternativeNames.some((y)=>y===`*.${Q}`);else v=!0;if(v)K=b.CertificateArn,console.log(`Found existing certificate with www coverage: ${K}`);else console.log(`Existing certificate doesn't cover ${X}, requesting new one...`)}if(!K){if(!H)return{success:!1,stackName:U,bucket:W,message:`No DNS provider available to validate SSL certificate for ${Q}. Provide a certificateArn or enable DNS verification.`};console.log(`Requesting new SSL certificate for ${Q}${X?` (including ${X})`:""}...`);let f=await new f0(H,"us-east-1").findOrCreateCertificate({domainName:Q,subjectAlternativeNames:X?[X]:void 0,waitForValidation:!0,maxWaitMinutes:10});if(f.status!=="issued")return{success:!1,stackName:U,bucket:W,message:`SSL certificate validation failed. Status: ${f.status}`};K=f.certificateArn,console.log(`Certificate issued: ${K}`)}}let j=!1,q;try{let b=await Z.describeStacks({stackName:U});if(b.Stacks.length>0){let v=b.Stacks[0],y=v.StackStatus;if(y==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await Z.waitForStack(U,"stack-delete-complete"),j=!1;else if(y==="DELETE_COMPLETE")j=!1;else j=!0,q=(v.Outputs||[]).find((m)=>m.OutputKey==="BucketName")?.OutputValue}}catch(b){if(b.message?.includes("does not exist")||b.code==="ValidationError")j=!1;else throw b}let E=q||W;if(!j){let b=new X$(J),v=new j$;try{if((await b.headBucket(W)).exists){console.log(`Found orphaned S3 bucket ${W}, cleaning up...`);try{let f=b.emptyBucket(W).then(()=>b.deleteBucket(W)),m=new Promise((t,n)=>setTimeout(()=>n(Error("Bucket cleanup timeout")),30000));await Promise.race([f,m]),console.log(`Deleted orphaned S3 bucket ${W}`)}catch(f){console.log(`Note: Could not clean up S3 bucket: ${f.message}`);let m=Date.now().toString(36);E=`${W}-${m}`,console.log(`Using alternative bucket name: ${E}`)}}}catch{}if(Q)try{console.log(`Checking for existing CloudFront distributions with alias ${Q}...`);let y=await v.listDistributions();for(let f of y){let m=[];if(f.Aliases?.Items){if(Array.isArray(f.Aliases.Items))m=f.Aliases.Items;else if(typeof f.Aliases.Items==="object"){let t=f.Aliases.Items.CNAME;if(typeof t==="string")m=[t];else if(Array.isArray(t))m=t}}if(m.includes(Q)){console.log(`Found existing CloudFront distribution ${f.Id} with alias ${Q}`),console.log("Reusing existing infrastructure for updates...");let n=(await v.getDistributionConfig(f.Id)).DistributionConfig?.Origins?.Items,$$;if(n){let q$=[];if(Array.isArray(n))q$=n;else if(n.Origin)q$=Array.isArray(n.Origin)?n.Origin:[n.Origin];else q$=[n];for(let V$ of q$){let c1=(V$.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(c1){$$=c1[1];break}}}if($$)return console.log(`Using existing S3 bucket: ${$$}`),{success:!0,stackName:`existing-${f.Id}`,bucket:$$,distributionId:f.Id,distributionDomain:f.DomainName,domain:Q,certificateArn:K,message:"Using existing CloudFront distribution",_existingInfrastructure:!0}}}}catch{}}let w=FW({bucketName:E,domain:Q,aliases:X?[Q,X]:[Q],certificateArn:K,defaultRootObject:$.defaultRootObject,errorDocument:$.errorDocument}),T=Object.entries($.tags||{}).map(([b,v])=>({Key:b,Value:v}));if(T.push({Key:"ManagedBy",Value:"ts-cloud"}),T.push({Key:"Application",Value:$.siteName}),H)T.push({Key:"DnsProvider",Value:H.name});let S,R=!1;if(j){R=!0,console.log(`Updating CloudFormation stack: ${U}`);try{S=(await Z.updateStack({stackName:U,templateBody:JSON.stringify(w),capabilities:["CAPABILITY_IAM"],tags:T})).StackId,console.log(`Update initiated, stack ID: ${S}`)}catch(b){if(b.message?.includes("No updates are to be performed")){let v=await Z.describeStacks({stackName:U});S=v.Stacks[0].StackId;let y=v.Stacks[0]?.Outputs||[],f=(t)=>y.find((n)=>n.OutputKey===t)?.OutputValue,m=f("DistributionDomain");if(m)await C6(H,Q,m);return{success:!0,stackId:S,stackName:U,bucket:f("BucketName")||E,distributionId:f("DistributionId"),distributionDomain:m,domain:Q,certificateArn:K,message:"Static site infrastructure is already up to date"}}else throw b}}else console.log(`Creating CloudFormation stack: ${U}`),console.log(`Bucket name: ${E}`),console.log(`Domain: ${Q}`),console.log(`Certificate ARN: ${K}`),S=(await Z.createStack({stackName:U,templateBody:JSON.stringify(w),capabilities:["CAPABILITY_IAM"],tags:T,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${S}`);console.log(`Waiting for stack to reach ${R?"stack-update-complete":"stack-create-complete"}...`);try{await Z.waitForStack(U,R?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(b){if(b.message?.includes("must be verified")||b.message?.includes("Access denied for operation")){console.log("CloudFront account verification required - checking for existing infrastructure...");try{let y=new j$,f=await y.listDistributions();for(let m of f){let t=[];if(m.Aliases?.Items){if(Array.isArray(m.Aliases.Items))t=m.Aliases.Items;else if(typeof m.Aliases.Items==="object"){let n=m.Aliases.Items.CNAME;if(typeof n==="string")t=[n];else if(Array.isArray(n))t=n}}if(t.includes(Q)){console.log(`Found existing CloudFront distribution ${m.Id} with alias ${Q}`),console.log("Using existing infrastructure despite account verification requirement...");let $$=(await y.getDistributionConfig(m.Id)).DistributionConfig?.Origins?.Items,q$;if($$){let V$=[];if(Array.isArray($$))V$=$$;else if($$.Origin)V$=Array.isArray($$.Origin)?$$.Origin:[$$.Origin];else V$=[$$];for(let s$ of V$){let $5=(s$.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if($5){q$=$5[1];break}}}if(q$){console.log(`Using existing S3 bucket: ${q$}`);let V$=m.DomainName;if(V$)await C6(H,Q,V$);return{success:!0,stackName:`existing-${m.Id}`,bucket:q$,distributionId:m.Id,distributionDomain:m.DomainName,domain:Q,certificateArn:K,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}}catch{}return console.log(`
308
+ ┌─────────────────────────────────────────────────────────────────────────────┐
309
+ │ AWS ACCOUNT VERIFICATION REQUIRED │
310
+ ├─────────────────────────────────────────────────────────────────────────────┤
311
+ │ Your AWS account must be verified before you can create CloudFront │
312
+ │ distributions. This is a one-time requirement for new AWS accounts. │
313
+ │ │
314
+ │ To verify your account: │
315
+ │ │
316
+ │ 1. Go to: https://console.aws.amazon.com/support/home#/ │
317
+ │ 2. Click "Create case" │
318
+ │ 3. Select "Service limit increase" │
319
+ │ 4. For Service: Select "CloudFront" │
320
+ │ 5. For Request: "Please verify my account for CloudFront access" │
321
+ │ 6. Submit the case │
322
+ │ │
323
+ │ Verification typically takes 1-2 business days. │
324
+ │ After verification, re-run: bunx bunpress deploy │
325
+ └─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:S,stackName:U,bucket:E,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:S,stackName:U,bucket:E,message:`Stack deployment failed: ${b.message}`}}let D=(await Z.describeStacks({stackName:U})).Stacks[0]?.Outputs||[],k=(b)=>D.find((v)=>v.OutputKey===b)?.OutputValue,u=k("DistributionDomain");if(u&&H)console.log(`Creating DNS records via ${H.name}...`),await C6(H,Q,u);else if(u&&!H)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:S,stackName:U,bucket:k("BucketName")||E,distributionId:k("DistributionId"),distributionDomain:u,domain:Q,certificateArn:K,message:"Static site infrastructure deployed successfully with external DNS"}}async function C6($,J,Y){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} -> ${Y}`),!(await $.upsertRecord(J,{name:J,type:"ALIAS",content:Y,ttl:600})).success){console.log("ALIAS record failed, trying CNAME with @ subdomain...");let H=await $.upsertRecord(J,{name:J,type:"CNAME",content:Y,ttl:600});if(!H.success)console.warn(`Warning: Could not create DNS record: ${H.message}`),console.warn("Please manually create a CNAME or ALIAS record:"),console.warn(` ${J} -> ${Y}`);else console.log(`Created CNAME record: ${J} -> ${Y}`)}else console.log(`Created ALIAS record: ${J} -> ${Y}`);let Z=`www.${J}`;console.log(`Creating CNAME record for ${Z} -> ${Y}`);let z=await $.upsertRecord(J,{name:Z,type:"CNAME",content:Y,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(` ${Z} -> ${Y}`);else console.log(`Created CNAME record: ${Z} -> ${Y}`)}else{console.log(`Creating CNAME record for ${J} -> ${Y}`);let U=await $.upsertRecord(J,{name:J,type:"CNAME",content:Y,ttl:600});if(!U.success)console.warn(`Warning: Could not create DNS record: ${U.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${J} -> ${Y}`);else console.log(`Created CNAME record: ${J} -> ${Y}`)}}async function A9($){let{sourceDir:J,cleanBucket:Y=!1,onProgress:Q,...W}=$;Q?.("infrastructure","Deploying CloudFormation stack...");let U=await D6(W);if(!U.success)return U;if(Y){Q?.("clean","Cleaning old files from S3...");try{await new X$(W.region||"us-east-1").emptyBucket(U.bucket)}catch(K){console.log(`Note: Could not clean bucket: ${K.message}`)}}Q?.("upload","Uploading files to S3...");let{uploadStaticFiles:Z}=await Promise.resolve().then(() => (S6(),R6)),z=await Z({sourceDir:J,bucket:U.bucket,region:W.region||"us-east-1",cacheControl:W.cacheControl,onProgress:(K,B,O)=>{Q?.("upload",`${K}/${B}: ${O}`)}});if(z.errors.length>0)return{...U,success:!1,message:`Upload errors: ${z.errors.join(", ")}`,filesUploaded:z.uploaded};if(U.distributionId&&z.uploaded>0){Q?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:K}=await Promise.resolve().then(() => (S6(),R6));await K(U.distributionId)}Q?.("complete","Deployment complete!");let H=z.skipped>0?`Deployed ${z.uploaded} files (${z.skipped} unchanged) with external DNS`:`Deployed ${z.uploaded} files successfully with external DNS`;return{...U,filesUploaded:z.uploaded,filesSkipped:z.skipped,message:H}}var P6=Y$(()=>{G0();V0();M0();X0();v0();hJ()});var R9={};c$(R9,{SQSClient:()=>e$});class e${client;region;constructor($="us-east-1",J){this.region=$,this.client=new l}async createQueue($){let Y={Action:"CreateQueue",QueueName:$.fifo&&!$.queueName.endsWith(".fifo")?`${$.queueName}.fifo`:$.queueName,Version:"2012-11-05"},Q=1;if($.visibilityTimeout!==void 0)Y[`Attribute.${Q}.Name`]="VisibilityTimeout",Y[`Attribute.${Q}.Value`]=$.visibilityTimeout.toString(),Q++;if($.messageRetentionPeriod!==void 0)Y[`Attribute.${Q}.Name`]="MessageRetentionPeriod",Y[`Attribute.${Q}.Value`]=$.messageRetentionPeriod.toString(),Q++;if($.delaySeconds!==void 0)Y[`Attribute.${Q}.Name`]="DelaySeconds",Y[`Attribute.${Q}.Value`]=$.delaySeconds.toString(),Q++;if($.maxMessageSize!==void 0)Y[`Attribute.${Q}.Name`]="MaximumMessageSize",Y[`Attribute.${Q}.Value`]=$.maxMessageSize.toString(),Q++;if($.receiveMessageWaitTime!==void 0)Y[`Attribute.${Q}.Name`]="ReceiveMessageWaitTimeSeconds",Y[`Attribute.${Q}.Value`]=$.receiveMessageWaitTime.toString(),Q++;if($.fifo){if(Y[`Attribute.${Q}.Name`]="FifoQueue",Y[`Attribute.${Q}.Value`]="true",Q++,$.contentBasedDeduplication)Y[`Attribute.${Q}.Name`]="ContentBasedDeduplication",Y[`Attribute.${Q}.Value`]="true",Q++}if($.deadLetterTargetArn&&$.maxReceiveCount)Y[`Attribute.${Q}.Name`]="RedrivePolicy",Y[`Attribute.${Q}.Value`]=JSON.stringify({deadLetterTargetArn:$.deadLetterTargetArn,maxReceiveCount:$.maxReceiveCount}),Q++;if($.tags&&Object.keys($.tags).length>0){let U=1;for(let[Z,z]of Object.entries($.tags))Y[`Tag.${U}.Key`]=Z,Y[`Tag.${U}.Value`]=z,U++}let W=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()});return{QueueUrl:W.QueueUrl||W.CreateQueueResult?.QueueUrl}}async listQueues($){let J={Action:"ListQueues",Version:"2012-11-05"};if($)J.QueueNamePrefix=$;let Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()}),Q=[];if(Y.QueueUrl)Q.push(Y.QueueUrl);else if(Y.ListQueuesResult?.QueueUrl)if(Array.isArray(Y.ListQueuesResult.QueueUrl))Q.push(...Y.ListQueuesResult.QueueUrl);else Q.push(Y.ListQueuesResult.QueueUrl);return{QueueUrls:Q}}async getQueueAttributes($){let J={Action:"GetQueueAttributes",QueueUrl:$,Version:"2012-11-05","AttributeName.1":"All"},Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{Attributes:Y.Attributes||Y.GetQueueAttributesResult?.Attributes||{}}}async getQueueUrl($){let J={Action:"GetQueueUrl",QueueName:$,Version:"2012-11-05"},Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{QueueUrl:Y.QueueUrl||Y.GetQueueUrlResult?.QueueUrl}}async deleteQueue($){let J={Action:"DeleteQueue",QueueUrl:$,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()})}async purgeQueue($){let J={Action:"PurgeQueue",QueueUrl:$,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()})}async sendMessage($){let J={Action:"SendMessage",QueueUrl:$.queueUrl,MessageBody:$.messageBody,Version:"2012-11-05"};if($.delaySeconds!==void 0)J.DelaySeconds=$.delaySeconds;if($.messageGroupId)J.MessageGroupId=$.messageGroupId;if($.messageDeduplicationId)J.MessageDeduplicationId=$.messageDeduplicationId;let Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{MessageId:Y.MessageId||Y.SendMessageResult?.MessageId}}async receiveMessages($){let J={Action:"ReceiveMessage",QueueUrl:$.queueUrl,Version:"2012-11-05"};if($.maxMessages!==void 0)J.MaxNumberOfMessages=$.maxMessages;if($.visibilityTimeout!==void 0)J.VisibilityTimeout=$.visibilityTimeout;if($.waitTimeSeconds!==void 0)J.WaitTimeSeconds=$.waitTimeSeconds;let Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()}),Q=[],W=Y.Message||Y.ReceiveMessageResult?.Message;if(W)if(Array.isArray(W))Q.push(...W.map((U)=>({MessageId:U.MessageId,ReceiptHandle:U.ReceiptHandle,Body:U.Body})));else Q.push({MessageId:W.MessageId,ReceiptHandle:W.ReceiptHandle,Body:W.Body});return{Messages:Q}}async deleteMessage($,J){let Y={Action:"DeleteMessage",QueueUrl:$,ReceiptHandle:J,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}}var f6=Y$(()=>{W$()});var S9={};c$(S9,{EC2Client:()=>b$});class b${client;region;constructor($="us-east-1"){this.region=$,this.client=new l}async describeInstances($){let J={Action:"DescribeInstances",Version:"2016-11-15"};if($?.InstanceIds)$.InstanceIds.forEach((W,U)=>{J[`InstanceId.${U+1}`]=W});if($?.Filters)$.Filters.forEach((W,U)=>{J[`Filter.${U+1}.Name`]=W.Name,W.Values.forEach((Z,z)=>{J[`Filter.${U+1}.Value.${z+1}`]=Z})});if($?.MaxResults)J.MaxResults=String($.MaxResults);if($?.NextToken)J.NextToken=$.NextToken;let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()}),Q=Y.DescribeInstancesResponse||Y;return{Reservations:this.parseReservations(Q.reservationSet?.item),NextToken:Q.nextToken}}async getInstance($){return(await this.describeInstances({InstanceIds:[$]})).Reservations?.[0]?.Instances?.[0]}async getConsoleOutput($,J){let Y={Action:"GetConsoleOutput",Version:"2016-11-15",InstanceId:$};if(J)Y.Latest="true";let Q=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(Y).toString()}),W=Q.GetConsoleOutputResponse||Q;return{InstanceId:W.instanceId,Output:W.output,Timestamp:W.timestamp}}async getConsoleOutputDecoded($,J){let Y=await this.getConsoleOutput($,J?.latest);if(!Y.Output)return"No console output available yet";let Q=Buffer.from(Y.Output,"base64").toString("utf-8");if(J?.tailLines)return Q.split(`
326
+ `).slice(-J.tailLines).join(`
327
+ `);return Q}async describeInstanceStatus($){let J={Action:"DescribeInstanceStatus",Version:"2016-11-15"};if($?.InstanceIds)$.InstanceIds.forEach((Q,W)=>{J[`InstanceId.${W+1}`]=Q});if($?.IncludeAllInstances)J.IncludeAllInstances="true";if($?.Filters)$.Filters.forEach((Q,W)=>{J[`Filter.${W+1}.Name`]=Q.Name,Q.Values.forEach((U,Z)=>{J[`Filter.${W+1}.Value.${Z+1}`]=U})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{InstanceStatuses:this.parseArray(Y.instanceStatusSet?.item).map((Q)=>({InstanceId:Q.instanceId,InstanceState:Q.instanceState?{Code:Number.parseInt(Q.instanceState.code),Name:Q.instanceState.name}:void 0,InstanceStatus:Q.instanceStatus?{Status:Q.instanceStatus.status,Details:this.parseArray(Q.instanceStatus.details?.item).map((W)=>({Name:W.name,Status:W.status}))}:void 0,SystemStatus:Q.systemStatus?{Status:Q.systemStatus.status,Details:this.parseArray(Q.systemStatus.details?.item).map((W)=>({Name:W.name,Status:W.status}))}:void 0}))}}async startInstances($){let J={Action:"StartInstances",Version:"2016-11-15"};$.forEach((Q,W)=>{J[`InstanceId.${W+1}`]=Q});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{StartingInstances:this.parseArray(Y.instancesSet?.item).map((Q)=>({InstanceId:Q.instanceId,CurrentState:Q.currentState?{Name:Q.currentState.name}:void 0,PreviousState:Q.previousState?{Name:Q.previousState.name}:void 0}))}}async stopInstances($,J){let Y={Action:"StopInstances",Version:"2016-11-15"};if($.forEach((W,U)=>{Y[`InstanceId.${U+1}`]=W}),J)Y.Force="true";let Q=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(Y).toString()});return{StoppingInstances:this.parseArray(Q.instancesSet?.item).map((W)=>({InstanceId:W.instanceId,CurrentState:W.currentState?{Name:W.currentState.name}:void 0,PreviousState:W.previousState?{Name:W.previousState.name}:void 0}))}}async rebootInstances($){let J={Action:"RebootInstances",Version:"2016-11-15"};$.forEach((Y,Q)=>{J[`InstanceId.${Q+1}`]=Y}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async terminateInstances($){let J={Action:"TerminateInstances",Version:"2016-11-15"};$.forEach((Q,W)=>{J[`InstanceId.${W+1}`]=Q});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{TerminatingInstances:this.parseArray(Y.instancesSet?.item).map((Q)=>({InstanceId:Q.instanceId,CurrentState:Q.currentState?{Name:Q.currentState.name}:void 0,PreviousState:Q.previousState?{Name:Q.previousState.name}:void 0}))}}async describeVpcs($){let J={Action:"DescribeVpcs",Version:"2016-11-15"};if($?.VpcIds)$.VpcIds.forEach((Q,W)=>{J[`VpcId.${W+1}`]=Q});if($?.Filters)$.Filters.forEach((Q,W)=>{J[`Filter.${W+1}.Name`]=Q.Name,Q.Values.forEach((U,Z)=>{J[`Filter.${W+1}.Value.${Z+1}`]=U})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{Vpcs:this.parseArray(Y.vpcSet?.item).map((Q)=>({VpcId:Q.vpcId,CidrBlock:Q.cidrBlock,State:Q.state,DhcpOptionsId:Q.dhcpOptionsId,InstanceTenancy:Q.instanceTenancy,IsDefault:Q.isDefault==="true",Tags:this.parseTags(Q.tagSet?.item)}))}}async describeSubnets($){let J={Action:"DescribeSubnets",Version:"2016-11-15"};if($?.SubnetIds)$.SubnetIds.forEach((Q,W)=>{J[`SubnetId.${W+1}`]=Q});if($?.Filters)$.Filters.forEach((Q,W)=>{J[`Filter.${W+1}.Name`]=Q.Name,Q.Values.forEach((U,Z)=>{J[`Filter.${W+1}.Value.${Z+1}`]=U})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{Subnets:this.parseArray(Y.subnetSet?.item).map((Q)=>({SubnetId:Q.subnetId,VpcId:Q.vpcId,CidrBlock:Q.cidrBlock,AvailabilityZone:Q.availabilityZone,AvailableIpAddressCount:Number.parseInt(Q.availableIpAddressCount),State:Q.state,MapPublicIpOnLaunch:Q.mapPublicIpOnLaunch==="true",Tags:this.parseTags(Q.tagSet?.item)}))}}async describeSecurityGroups($){let J={Action:"DescribeSecurityGroups",Version:"2016-11-15"};if($?.GroupIds)$.GroupIds.forEach((Q,W)=>{J[`GroupId.${W+1}`]=Q});if($?.GroupNames)$.GroupNames.forEach((Q,W)=>{J[`GroupName.${W+1}`]=Q});if($?.Filters)$.Filters.forEach((Q,W)=>{J[`Filter.${W+1}.Name`]=Q.Name,Q.Values.forEach((U,Z)=>{J[`Filter.${W+1}.Value.${Z+1}`]=U})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{SecurityGroups:this.parseArray(Y.securityGroupInfo?.item).map((Q)=>({GroupId:Q.groupId,GroupName:Q.groupName,Description:Q.groupDescription,VpcId:Q.vpcId,IpPermissions:this.parseIpPermissions(Q.ipPermissions?.item),IpPermissionsEgress:this.parseIpPermissions(Q.ipPermissionsEgress?.item),Tags:this.parseTags(Q.tagSet?.item)}))}}async describeInternetGateways($){let J={Action:"DescribeInternetGateways",Version:"2016-11-15"};if($?.InternetGatewayIds)$.InternetGatewayIds.forEach((Q,W)=>{J[`InternetGatewayId.${W+1}`]=Q});if($?.Filters)$.Filters.forEach((Q,W)=>{J[`Filter.${W+1}.Name`]=Q.Name,Q.Values.forEach((U,Z)=>{J[`Filter.${W+1}.Value.${Z+1}`]=U})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{InternetGateways:this.parseArray(Y.internetGatewaySet?.item).map((Q)=>({InternetGatewayId:Q.internetGatewayId,Attachments:this.parseArray(Q.attachmentSet?.item).map((W)=>({VpcId:W.vpcId,State:W.state})),Tags:this.parseTags(Q.tagSet?.item)}))}}async describeAddresses($){let J={Action:"DescribeAddresses",Version:"2016-11-15"};if($?.AllocationIds)$.AllocationIds.forEach((Q,W)=>{J[`AllocationId.${W+1}`]=Q});if($?.PublicIps)$.PublicIps.forEach((Q,W)=>{J[`PublicIp.${W+1}`]=Q});if($?.Filters)$.Filters.forEach((Q,W)=>{J[`Filter.${W+1}.Name`]=Q.Name,Q.Values.forEach((U,Z)=>{J[`Filter.${W+1}.Value.${Z+1}`]=U})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{Addresses:this.parseArray(Y.addressesSet?.item).map((Q)=>({PublicIp:Q.publicIp,AllocationId:Q.allocationId,AssociationId:Q.associationId,InstanceId:Q.instanceId,NetworkInterfaceId:Q.networkInterfaceId,PrivateIpAddress:Q.privateIpAddress,Domain:Q.domain,Tags:this.parseTags(Q.tagSet?.item)}))}}async allocateAddress($){let J={Action:"AllocateAddress",Version:"2016-11-15"};if($?.Domain)J.Domain=$.Domain;if($?.TagSpecifications)$.TagSpecifications.forEach((Q,W)=>{J[`TagSpecification.${W+1}.ResourceType`]=Q.ResourceType,Q.Tags.forEach((U,Z)=>{J[`TagSpecification.${W+1}.Tag.${Z+1}.Key`]=U.Key,J[`TagSpecification.${W+1}.Tag.${Z+1}.Value`]=U.Value})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{AllocationId:Y.allocationId,PublicIp:Y.publicIp,Domain:Y.domain}}async associateAddress($){let J={Action:"AssociateAddress",Version:"2016-11-15"};if($.AllocationId)J.AllocationId=$.AllocationId;if($.PublicIp)J.PublicIp=$.PublicIp;if($.InstanceId)J.InstanceId=$.InstanceId;if($.NetworkInterfaceId)J.NetworkInterfaceId=$.NetworkInterfaceId;if($.PrivateIpAddress)J.PrivateIpAddress=$.PrivateIpAddress;if($.AllowReassociation)J.AllowReassociation="true";return{AssociationId:(await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})).associationId}}async createTags($){let J={Action:"CreateTags",Version:"2016-11-15"};$.Resources.forEach((Y,Q)=>{J[`ResourceId.${Q+1}`]=Y}),$.Tags.forEach((Y,Q)=>{J[`Tag.${Q+1}.Key`]=Y.Key,J[`Tag.${Q+1}.Value`]=Y.Value}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async waitForInstanceState($,J,Y){let Q=Y?.maxWaitMs||300000,W=Y?.pollIntervalMs||5000,U=Date.now();while(Date.now()-U<Q){let Z=await this.getInstance($);if(Z?.State?.Name===J)return Z;await new Promise((z)=>setTimeout(z,W))}return}async createVpc($){let J={Action:"CreateVpc",Version:"2016-11-15",CidrBlock:$.CidrBlock};if($.InstanceTenancy)J.InstanceTenancy=$.InstanceTenancy;if($.TagSpecifications)$.TagSpecifications.forEach((U,Z)=>{J[`TagSpecification.${Z+1}.ResourceType`]=U.ResourceType,U.Tags.forEach((z,H)=>{J[`TagSpecification.${Z+1}.Tag.${H+1}.Key`]=z.Key,J[`TagSpecification.${Z+1}.Tag.${H+1}.Value`]=z.Value})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()}),W=(Y.CreateVpcResponse||Y).vpc;return{Vpc:W?{VpcId:W.vpcId,CidrBlock:W.cidrBlock,State:W.state,DhcpOptionsId:W.dhcpOptionsId,InstanceTenancy:W.instanceTenancy,IsDefault:W.isDefault==="true",Tags:this.parseTags(W.tagSet?.item)}:void 0}}async createSubnet($){let J={Action:"CreateSubnet",Version:"2016-11-15",VpcId:$.VpcId,CidrBlock:$.CidrBlock};if($.AvailabilityZone)J.AvailabilityZone=$.AvailabilityZone;if($.TagSpecifications)$.TagSpecifications.forEach((U,Z)=>{J[`TagSpecification.${Z+1}.ResourceType`]=U.ResourceType,U.Tags.forEach((z,H)=>{J[`TagSpecification.${Z+1}.Tag.${H+1}.Key`]=z.Key,J[`TagSpecification.${Z+1}.Tag.${H+1}.Value`]=z.Value})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()}),W=(Y.CreateSubnetResponse||Y).subnet;return{Subnet:W?{SubnetId:W.subnetId,VpcId:W.vpcId,CidrBlock:W.cidrBlock,AvailabilityZone:W.availabilityZone,AvailableIpAddressCount:W.availableIpAddressCount?Number.parseInt(W.availableIpAddressCount):void 0,State:W.state,MapPublicIpOnLaunch:W.mapPublicIpOnLaunch==="true",Tags:this.parseTags(W.tagSet?.item)}:void 0}}async modifySubnetAttribute($){let J={Action:"ModifySubnetAttribute",Version:"2016-11-15",SubnetId:$.SubnetId};if($.MapPublicIpOnLaunch!==void 0)J["MapPublicIpOnLaunch.Value"]=String($.MapPublicIpOnLaunch.Value);await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async createSecurityGroup($){let J={Action:"CreateSecurityGroup",Version:"2016-11-15",GroupName:$.GroupName,GroupDescription:$.Description};if($.VpcId)J.VpcId=$.VpcId;if($.TagSpecifications)$.TagSpecifications.forEach((W,U)=>{J[`TagSpecification.${U+1}.ResourceType`]=W.ResourceType,W.Tags.forEach((Z,z)=>{J[`TagSpecification.${U+1}.Tag.${z+1}.Key`]=Z.Key,J[`TagSpecification.${U+1}.Tag.${z+1}.Value`]=Z.Value})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{GroupId:(Y.CreateSecurityGroupResponse||Y).groupId}}async authorizeSecurityGroupIngress($){let J={Action:"AuthorizeSecurityGroupIngress",Version:"2016-11-15",GroupId:$.GroupId};this.encodeIpPermissions(J,$.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async authorizeSecurityGroupEgress($){let J={Action:"AuthorizeSecurityGroupEgress",Version:"2016-11-15",GroupId:$.GroupId};this.encodeIpPermissions(J,$.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async describeRouteTables($){let J={Action:"DescribeRouteTables",Version:"2016-11-15"};if($?.RouteTableIds)$.RouteTableIds.forEach((W,U)=>{J[`RouteTableId.${U+1}`]=W});if($?.Filters)$.Filters.forEach((W,U)=>{J[`Filter.${U+1}.Name`]=W.Name,W.Values.forEach((Z,z)=>{J[`Filter.${U+1}.Value.${z+1}`]=Z})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()}),Q=Y.DescribeRouteTablesResponse||Y;return{RouteTables:this.parseArray(Q.routeTableSet?.item).map((W)=>({RouteTableId:W.routeTableId,VpcId:W.vpcId,Routes:this.parseArray(W.routeSet?.item).map((U)=>({DestinationCidrBlock:U.destinationCidrBlock,GatewayId:U.gatewayId,NatGatewayId:U.natGatewayId,State:U.state})),Associations:this.parseArray(W.associationSet?.item).map((U)=>({RouteTableAssociationId:U.routeTableAssociationId,SubnetId:U.subnetId,Main:U.main==="true"||U.main===!0})),Tags:this.parseTags(W.tagSet?.item)}))}}encodeIpPermissions($,J){J.forEach((Y,Q)=>{let W=`IpPermissions.${Q+1}`;if(Y.IpProtocol!==void 0)$[`${W}.IpProtocol`]=Y.IpProtocol;if(Y.FromPort!==void 0)$[`${W}.FromPort`]=String(Y.FromPort);if(Y.ToPort!==void 0)$[`${W}.ToPort`]=String(Y.ToPort);if(Y.IpRanges)Y.IpRanges.forEach((U,Z)=>{if(U.CidrIp)$[`${W}.IpRanges.${Z+1}.CidrIp`]=U.CidrIp;if(U.Description)$[`${W}.IpRanges.${Z+1}.Description`]=U.Description});if(Y.Ipv6Ranges)Y.Ipv6Ranges.forEach((U,Z)=>{if(U.CidrIpv6)$[`${W}.Ipv6Ranges.${Z+1}.CidrIpv6`]=U.CidrIpv6;if(U.Description)$[`${W}.Ipv6Ranges.${Z+1}.Description`]=U.Description});if(Y.UserIdGroupPairs)Y.UserIdGroupPairs.forEach((U,Z)=>{if(U.GroupId)$[`${W}.Groups.${Z+1}.GroupId`]=U.GroupId;if(U.UserId)$[`${W}.Groups.${Z+1}.UserId`]=U.UserId;if(U.Description)$[`${W}.Groups.${Z+1}.Description`]=U.Description})})}parseArray($){if(!$)return[];return Array.isArray($)?$:[$]}parseTags($){return this.parseArray($).map((J)=>({Key:J.key,Value:J.value}))}parseReservations($){return this.parseArray($).map((J)=>({ReservationId:J.reservationId,Instances:this.parseInstances(J.instancesSet?.item||J.instancesSet)}))}parseInstances($){return this.parseArray($).map((J)=>({InstanceId:J.instanceId,ImageId:J.imageId,InstanceType:J.instanceType,State:J.instanceState?{Code:Number.parseInt(J.instanceState.code),Name:J.instanceState.name}:void 0,PrivateIpAddress:J.privateIpAddress,PublicIpAddress:J.ipAddress,SubnetId:J.subnetId,VpcId:J.vpcId,SecurityGroups:this.parseArray(J.groupSet?.item).map((Y)=>({GroupId:Y.groupId,GroupName:Y.groupName})),Tags:this.parseTags(J.tagSet?.item),LaunchTime:J.launchTime,Placement:J.placement?{AvailabilityZone:J.placement.availabilityZone,Tenancy:J.placement.tenancy}:void 0,Architecture:J.architecture,RootDeviceType:J.rootDeviceType,RootDeviceName:J.rootDeviceName,BlockDeviceMappings:this.parseArray(J.blockDeviceMapping?.item).map((Y)=>({DeviceName:Y.deviceName,Ebs:Y.ebs?{VolumeId:Y.ebs.volumeId,Status:Y.ebs.status,AttachTime:Y.ebs.attachTime,DeleteOnTermination:Y.ebs.deleteOnTermination==="true"}:void 0})),IamInstanceProfile:J.iamInstanceProfile?{Arn:J.iamInstanceProfile.arn,Id:J.iamInstanceProfile.id}:void 0}))}parseIpPermissions($){return this.parseArray($).map((J)=>({IpProtocol:J.ipProtocol,FromPort:J.fromPort?Number.parseInt(J.fromPort):void 0,ToPort:J.toPort?Number.parseInt(J.toPort):void 0,IpRanges:this.parseArray(J.ipRanges?.item).map((Y)=>({CidrIp:Y.cidrIp,Description:Y.description})),Ipv6Ranges:this.parseArray(J.ipv6Ranges?.item).map((Y)=>({CidrIpv6:Y.cidrIpv6,Description:Y.description})),UserIdGroupPairs:this.parseArray(J.groups?.item).map((Y)=>({GroupId:Y.groupId,UserId:Y.userId,Description:Y.description}))}))}}var u6=Y$(()=>{W$()});var P9={};c$(P9,{STSClient:()=>D9});class D9{client;region;constructor($="us-east-1",J){this.region=$,this.client=new l}async getCallerIdentity(){let $=await this.client.request({service:"sts",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetCallerIdentity&Version=2011-06-15"});if(typeof $==="string"){let Y=$.match(/<Account>(\d+)<\/Account>/),Q=$.match(/<UserId>([^<]+)<\/UserId>/),W=$.match(/<Arn>([^<]+)<\/Arn>/);return{Account:Y?.[1],UserId:Q?.[1],Arn:W?.[1]}}let J=$?.GetCallerIdentityResponse?.GetCallerIdentityResult||$?.GetCallerIdentityResult;if(J)return{Account:String(J.Account),UserId:J.UserId,Arn:J.Arn};if($?.Account)return{Account:String($.Account),UserId:$.UserId,Arn:$.Arn};return{Account:void 0,UserId:void 0,Arn:void 0}}}var C9=Y$(()=>{W$()});var k9={};c$(k9,{RDSClient:()=>N9});class N9{client;region;constructor($="us-east-1"){this.region=$,this.client=new l}async describeDBInstances($){let J={Action:"DescribeDBInstances",Version:"2014-10-31"};if($?.DBInstanceIdentifier)J.DBInstanceIdentifier=$.DBInstanceIdentifier;if($?.MaxRecords)J.MaxRecords=$.MaxRecords;if($?.Marker)J.Marker=$.Marker;if($?.Filters)$.Filters.forEach((Z,z)=>{J[`Filters.Filter.${z+1}.Name`]=Z.Name,Z.Values.forEach((H,K)=>{J[`Filters.Filter.${z+1}.Values.Value.${K+1}`]=H})});let Y=new URLSearchParams(C$(J)).toString(),Q=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y}),W=Q.DescribeDBInstancesResult||Q,U=W.DBInstances?.DBInstance||[];if(!Array.isArray(U))U=U?[U]:[];return{DBInstances:U,Marker:W.Marker}}async describeDBInstance($){return(await this.describeDBInstances({DBInstanceIdentifier:$})).DBInstances?.[0]}async describeDBClusters($){let J={Action:"DescribeDBClusters",Version:"2014-10-31"};if($?.DBClusterIdentifier)J.DBClusterIdentifier=$.DBClusterIdentifier;if($?.MaxRecords)J.MaxRecords=$.MaxRecords;if($?.Marker)J.Marker=$.Marker;if($?.Filters)$.Filters.forEach((Z,z)=>{J[`Filters.Filter.${z+1}.Name`]=Z.Name,Z.Values.forEach((H,K)=>{J[`Filters.Filter.${z+1}.Values.Value.${K+1}`]=H})});let Y=new URLSearchParams(C$(J)).toString(),Q=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y}),W=Q.DescribeDBClustersResult||Q,U=W.DBClusters?.DBCluster||[];if(!Array.isArray(U))U=U?[U]:[];return{DBClusters:U,Marker:W.Marker}}async describeDBSnapshots($){let J={Action:"DescribeDBSnapshots",Version:"2014-10-31"};if($?.DBInstanceIdentifier)J.DBInstanceIdentifier=$.DBInstanceIdentifier;if($?.DBSnapshotIdentifier)J.DBSnapshotIdentifier=$.DBSnapshotIdentifier;if($?.SnapshotType)J.SnapshotType=$.SnapshotType;if($?.MaxRecords)J.MaxRecords=$.MaxRecords;if($?.Marker)J.Marker=$.Marker;let Y=new URLSearchParams(C$(J)).toString(),Q=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y}),W=Q.DescribeDBSnapshotsResult||Q,U=W.DBSnapshots?.DBSnapshot||[];if(!Array.isArray(U))U=U?[U]:[];return{DBSnapshots:U,Marker:W.Marker}}async describeDBSubnetGroups($){let J={Action:"DescribeDBSubnetGroups",Version:"2014-10-31"};if($?.DBSubnetGroupName)J.DBSubnetGroupName=$.DBSubnetGroupName;if($?.MaxRecords)J.MaxRecords=$.MaxRecords;if($?.Marker)J.Marker=$.Marker;let Y=new URLSearchParams(C$(J)).toString(),Q=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y}),W=Q.DescribeDBSubnetGroupsResult||Q,U=W.DBSubnetGroups?.DBSubnetGroup||[];if(!Array.isArray(U))U=U?[U]:[];return{DBSubnetGroups:U,Marker:W.Marker}}async createDBInstance($){let J={Action:"CreateDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier,DBInstanceClass:$.DBInstanceClass,Engine:$.Engine};if($.MasterUsername)J.MasterUsername=$.MasterUsername;if($.MasterUserPassword)J.MasterUserPassword=$.MasterUserPassword;if($.DBName)J.DBName=$.DBName;if($.AllocatedStorage)J.AllocatedStorage=$.AllocatedStorage;if($.DBSubnetGroupName)J.DBSubnetGroupName=$.DBSubnetGroupName;if($.AvailabilityZone)J.AvailabilityZone=$.AvailabilityZone;if($.PreferredMaintenanceWindow)J.PreferredMaintenanceWindow=$.PreferredMaintenanceWindow;if($.PreferredBackupWindow)J.PreferredBackupWindow=$.PreferredBackupWindow;if($.BackupRetentionPeriod!==void 0)J.BackupRetentionPeriod=$.BackupRetentionPeriod;if($.MultiAZ!==void 0)J.MultiAZ=$.MultiAZ;if($.EngineVersion)J.EngineVersion=$.EngineVersion;if($.AutoMinorVersionUpgrade!==void 0)J.AutoMinorVersionUpgrade=$.AutoMinorVersionUpgrade;if($.LicenseModel)J.LicenseModel=$.LicenseModel;if($.PubliclyAccessible!==void 0)J.PubliclyAccessible=$.PubliclyAccessible;if($.StorageType)J.StorageType=$.StorageType;if($.StorageEncrypted!==void 0)J.StorageEncrypted=$.StorageEncrypted;if($.KmsKeyId)J.KmsKeyId=$.KmsKeyId;if($.DeletionProtection!==void 0)J.DeletionProtection=$.DeletionProtection;if($.VpcSecurityGroupIds)$.VpcSecurityGroupIds.forEach((U,Z)=>{J[`VpcSecurityGroupIds.VpcSecurityGroupId.${Z+1}`]=U});if($.Tags)$.Tags.forEach((U,Z)=>{J[`Tags.Tag.${Z+1}.Key`]=U.Key,J[`Tags.Tag.${Z+1}.Value`]=U.Value});let Y=new URLSearchParams(C$(J)).toString(),Q=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Q.CreateDBInstanceResult||Q).DBInstance}}async deleteDBInstance($){let J={Action:"DeleteDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier};if($.SkipFinalSnapshot!==void 0)J.SkipFinalSnapshot=$.SkipFinalSnapshot;if($.FinalDBSnapshotIdentifier)J.FinalDBSnapshotIdentifier=$.FinalDBSnapshotIdentifier;if($.DeleteAutomatedBackups!==void 0)J.DeleteAutomatedBackups=$.DeleteAutomatedBackups;let Y=new URLSearchParams(C$(J)).toString(),Q=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Q.DeleteDBInstanceResult||Q).DBInstance}}async modifyDBInstance($){let J={Action:"ModifyDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier};if($.DBInstanceClass)J.DBInstanceClass=$.DBInstanceClass;if($.AllocatedStorage)J.AllocatedStorage=$.AllocatedStorage;if($.MasterUserPassword)J.MasterUserPassword=$.MasterUserPassword;if($.BackupRetentionPeriod!==void 0)J.BackupRetentionPeriod=$.BackupRetentionPeriod;if($.PreferredBackupWindow)J.PreferredBackupWindow=$.PreferredBackupWindow;if($.PreferredMaintenanceWindow)J.PreferredMaintenanceWindow=$.PreferredMaintenanceWindow;if($.MultiAZ!==void 0)J.MultiAZ=$.MultiAZ;if($.EngineVersion)J.EngineVersion=$.EngineVersion;if($.AutoMinorVersionUpgrade!==void 0)J.AutoMinorVersionUpgrade=$.AutoMinorVersionUpgrade;if($.PubliclyAccessible!==void 0)J.PubliclyAccessible=$.PubliclyAccessible;if($.ApplyImmediately!==void 0)J.ApplyImmediately=$.ApplyImmediately;if($.StorageType)J.StorageType=$.StorageType;if($.DeletionProtection!==void 0)J.DeletionProtection=$.DeletionProtection;if($.VpcSecurityGroupIds)$.VpcSecurityGroupIds.forEach((U,Z)=>{J[`VpcSecurityGroupIds.VpcSecurityGroupId.${Z+1}`]=U});let Y=new URLSearchParams(C$(J)).toString(),Q=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Q.ModifyDBInstanceResult||Q).DBInstance}}async startDBInstance($){let Y=new URLSearchParams(C$({Action:"StartDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$})).toString(),Q=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Q.StartDBInstanceResult||Q).DBInstance}}async stopDBInstance($){let J={Action:"StopDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier};if($.DBSnapshotIdentifier)J.DBSnapshotIdentifier=$.DBSnapshotIdentifier;let Y=new URLSearchParams(C$(J)).toString(),Q=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Q.StopDBInstanceResult||Q).DBInstance}}async rebootDBInstance($){let J={Action:"RebootDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier};if($.ForceFailover!==void 0)J.ForceFailover=$.ForceFailover;let Y=new URLSearchParams(C$(J)).toString(),Q=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Q.RebootDBInstanceResult||Q).DBInstance}}async createDBSnapshot($){let J={Action:"CreateDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier,DBSnapshotIdentifier:$.DBSnapshotIdentifier};if($.Tags)$.Tags.forEach((U,Z)=>{J[`Tags.Tag.${Z+1}.Key`]=U.Key,J[`Tags.Tag.${Z+1}.Value`]=U.Value});let Y=new URLSearchParams(C$(J)).toString(),Q=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBSnapshot:(Q.CreateDBSnapshotResult||Q).DBSnapshot}}async deleteDBSnapshot($){let Y=new URLSearchParams(C$({Action:"DeleteDBSnapshot",Version:"2014-10-31",DBSnapshotIdentifier:$})).toString(),Q=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBSnapshot:(Q.DeleteDBSnapshotResult||Q).DBSnapshot}}async restoreDBInstanceFromDBSnapshot($){let J={Action:"RestoreDBInstanceFromDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier,DBSnapshotIdentifier:$.DBSnapshotIdentifier};if($.DBInstanceClass)J.DBInstanceClass=$.DBInstanceClass;if($.Port)J.Port=$.Port;if($.AvailabilityZone)J.AvailabilityZone=$.AvailabilityZone;if($.DBSubnetGroupName)J.DBSubnetGroupName=$.DBSubnetGroupName;if($.MultiAZ!==void 0)J.MultiAZ=$.MultiAZ;if($.PubliclyAccessible!==void 0)J.PubliclyAccessible=$.PubliclyAccessible;if($.AutoMinorVersionUpgrade!==void 0)J.AutoMinorVersionUpgrade=$.AutoMinorVersionUpgrade;if($.StorageType)J.StorageType=$.StorageType;if($.DeletionProtection!==void 0)J.DeletionProtection=$.DeletionProtection;if($.VpcSecurityGroupIds)$.VpcSecurityGroupIds.forEach((U,Z)=>{J[`VpcSecurityGroupIds.VpcSecurityGroupId.${Z+1}`]=U});if($.Tags)$.Tags.forEach((U,Z)=>{J[`Tags.Tag.${Z+1}.Key`]=U.Key,J[`Tags.Tag.${Z+1}.Value`]=U.Value});let Y=new URLSearchParams(C$(J)).toString(),Q=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Q.RestoreDBInstanceFromDBSnapshotResult||Q).DBInstance}}async waitForDBInstanceAvailable($,J=60,Y=30000){for(let Q=0;Q<J;Q++){let W=await this.describeDBInstance($);if(W?.DBInstanceStatus==="available")return W;if(["deleted","failed","incompatible-restore","incompatible-parameters"].includes(W?.DBInstanceStatus||""))throw Error(`DB instance ${$} is in terminal state: ${W?.DBInstanceStatus}`);await new Promise((U)=>setTimeout(U,Y))}throw Error(`Timeout waiting for DB instance ${$} to become available`)}async waitForDBInstanceDeleted($,J=60,Y=30000){for(let Q=0;Q<J;Q++)try{let W=await this.describeDBInstance($);if(W?.DBInstanceStatus==="deleting"){await new Promise((U)=>setTimeout(U,Y));continue}throw Error(`DB instance ${$} is in state: ${W?.DBInstanceStatus}`)}catch(W){if(W.code==="DBInstanceNotFound"||W.code==="DBInstanceNotFoundFault")return;throw W}throw Error(`Timeout waiting for DB instance ${$} to be deleted`)}}var I9=Y$(()=>{W$()});var n6={};c$(n6,{LambdaClient:()=>h9});import{deflateRawSync as cW}from"zlib";function x9($,J){let Y=typeof J==="string"?Buffer.from(J,"utf-8"):J,Q=cW(Y),W=lW(Y),U=new Date,Z=(U.getHours()<<11|U.getMinutes()<<5|U.getSeconds()>>1)&65535,z=(U.getFullYear()-1980<<9|U.getMonth()+1<<5|U.getDate())&65535,H=Buffer.from($,"utf-8"),K=Buffer.alloc(30+H.length);K.writeUInt32LE(67324752,0),K.writeUInt16LE(20,4),K.writeUInt16LE(0,6),K.writeUInt16LE(8,8),K.writeUInt16LE(Z,10),K.writeUInt16LE(z,12),K.writeUInt32LE(W,14),K.writeUInt32LE(Q.length,18),K.writeUInt32LE(Y.length,22),K.writeUInt16LE(H.length,26),K.writeUInt16LE(0,28),H.copy(K,30);let B=Buffer.alloc(46+H.length);B.writeUInt32LE(33639248,0),B.writeUInt16LE(20,4),B.writeUInt16LE(20,6),B.writeUInt16LE(0,8),B.writeUInt16LE(8,10),B.writeUInt16LE(Z,12),B.writeUInt16LE(z,14),B.writeUInt32LE(W,16),B.writeUInt32LE(Q.length,20),B.writeUInt32LE(Y.length,24),B.writeUInt16LE(H.length,28),B.writeUInt16LE(0,30),B.writeUInt16LE(0,32),B.writeUInt16LE(0,34),B.writeUInt16LE(0,36),B.writeUInt32LE(0,38),B.writeUInt32LE(0,42),H.copy(B,46);let O=K.length+Q.length,X=B.length,j=Buffer.alloc(22);return j.writeUInt32LE(101010256,0),j.writeUInt16LE(0,4),j.writeUInt16LE(0,6),j.writeUInt16LE(1,8),j.writeUInt16LE(1,10),j.writeUInt32LE(X,12),j.writeUInt32LE(O,16),j.writeUInt16LE(0,20),Buffer.concat([K,Q,B,j])}function lW($){let J=[];for(let Q=0;Q<256;Q++){let W=Q;for(let U=0;U<8;U++)W=W&1?3988292384^W>>>1:W>>>1;J[Q]=W}let Y=4294967295;for(let Q=0;Q<$.length;Q++)Y=J[(Y^$[Q])&255]^Y>>>8;return(Y^4294967295)>>>0}class h9{client;region;constructor($="us-east-1"){this.region=$,this.client=new l}async createFunction($){return await this.client.request({service:"lambda",region:this.region,method:"POST",path:"/2015-03-31/functions",headers:{"Content-Type":"application/json"},body:JSON.stringify($)})}async getFunction($){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent($)}`,headers:{"Content-Type":"application/json"}})}async updateFunctionCode($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(J)}/code`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async updateFunctionCodeInline($,J,Y="index.js"){let Q=x9(Y,J);return this.updateFunctionCode({FunctionName:$,ZipFile:Q.toString("base64")})}async updateFunctionConfiguration($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(J)}/configuration`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async deleteFunction($){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent($)}`,headers:{"Content-Type":"application/json"}})}async invoke($){let{FunctionName:J,InvocationType:Y="RequestResponse",Payload:Q,LogType:W}=$,U={"Content-Type":"application/json","X-Amz-Invocation-Type":Y};if(W)U["X-Amz-Log-Type"]=W;let Z=Q?typeof Q==="string"?Q:JSON.stringify(Q):void 0,z=await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(J)}/invocations`,headers:U,body:Z,returnHeaders:!0});return{StatusCode:z.statusCode||200,FunctionError:z.headers?.["x-amz-function-error"],LogResult:z.headers?.["x-amz-log-result"],Payload:typeof z.body==="string"?z.body:JSON.stringify(z.body),ExecutedVersion:z.headers?.["x-amz-executed-version"]}}async listFunctions($){let J={};if($?.MaxItems)J.MaxItems=String($.MaxItems);if($?.Marker)J.Marker=$.Marker;if($?.FunctionVersion)J.FunctionVersion=$.FunctionVersion;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:"/2015-03-31/functions",queryParams:Object.keys(J).length>0?J:void 0,headers:{"Content-Type":"application/json"}})}async addPermission($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(J)}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async removePermission($,J){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent($)}/policy/${encodeURIComponent(J)}`,headers:{"Content-Type":"application/json"}})}async publishVersion($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(J)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async createAlias($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(J)}/aliases`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async waitForFunctionActive($,J=60){let Y=Date.now(),Q=J*1000;while(Date.now()-Y<Q)try{let W=await this.getFunction($),U=W.Configuration?.State;if(U==="Active")return W.Configuration;if(U==="Failed")throw Error(`Function ${$} failed: ${W.Configuration?.StateReason}`);await new Promise((Z)=>setTimeout(Z,2000))}catch(W){if(W.code==="ResourceNotFoundException"){await new Promise((U)=>setTimeout(U,2000));continue}throw W}throw Error(`Timeout waiting for function ${$} to become active`)}async functionExists($){try{return await this.getFunction($),!0}catch(J){if(J.code==="ResourceNotFoundException"||J.statusCode===404)return!1;throw J}}async createFunctionUrl($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2021-10-31/functions/${encodeURIComponent(J)}/url`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async getFunctionUrl($){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2021-10-31/functions/${encodeURIComponent($)}/url`,headers:{"Content-Type":"application/json"}})}catch(J){if(J.statusCode===404)return null;throw J}}async deleteFunctionUrl($){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2021-10-31/functions/${encodeURIComponent($)}/url`,headers:{"Content-Type":"application/json"}})}async createFunctionWithCode($){let{Code:J,Filename:Y="index.js",...Q}=$,W=x9(Y,J);return this.createFunction({...Q,Code:{ZipFile:W.toString("base64")}})}async addFunctionUrlPermission($){return this.addPermission({FunctionName:$,StatementId:"FunctionURLAllowPublicAccess",Action:"lambda:InvokeFunctionUrl",Principal:"*",FunctionUrlAuthType:"NONE"})}async publishLayerVersion($){let{LayerName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(J)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async listLayerVersions($,J){let Y={};if(J?.CompatibleRuntime)Y.CompatibleRuntime=J.CompatibleRuntime;if(J?.CompatibleArchitecture)Y.CompatibleArchitecture=J.CompatibleArchitecture;if(J?.MaxItems)Y.MaxItems=String(J.MaxItems);if(J?.Marker)Y.Marker=J.Marker;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent($)}/versions`,queryParams:Object.keys(Y).length>0?Y:void 0,headers:{"Content-Type":"application/json"}})}async getLayerVersion($,J){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent($)}/versions/${J}`,headers:{"Content-Type":"application/json"}})}async addLayerVersionPermission($){let{LayerName:J,VersionNumber:Y,...Q}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(J)}/versions/${Y}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)})}async deleteLayerVersion($,J){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2018-10-31/layers/${encodeURIComponent($)}/versions/${J}`,headers:{"Content-Type":"application/json"}})}}var s6=Y$(()=>{W$()});import{EventEmitter as p9}from"node:events";import Y5 from"node:process";import n1 from"node:process";import t0 from"node:process";import QY,{stdin as JU,stdout as YU}from"node:process";import Z5,{stdin as ZY,stdout as zY}from"node:process";import GY from"node:readline";var{create:f9,getPrototypeOf:g9,defineProperty:J5,getOwnPropertyNames:u9}=Object,d9=Object.prototype.hasOwnProperty,K$=($,J,Y)=>{Y=$!=null?f9(g9($)):{};let Q=J||!$||!$.__esModule?J5(Y,"default",{value:$,enumerable:!0}):Y;for(let W of u9($))if(!d9.call(Q,W))J5(Q,W,{get:()=>$[W],enumerable:!0});return Q},s1=($,J)=>()=>(J||$((J={exports:{}}).exports,J),J.exports),m9=s1(($,J)=>{function Y(W){return W==null?[]:Array.isArray(W)?W:[W]}function Q(W,U,Z,z){var H,K=W[U],B=~z.string.indexOf(U)?Z==null||Z===!0?"":String(Z):typeof Z==="boolean"?Z:~z.boolean.indexOf(U)?Z==="false"?!1:Z==="true"||(W._.push((H=+Z,H*0===0)?H:Z),!!Z):(H=+Z,H*0===0)?H:Z;W[U]=K==null?B:Array.isArray(K)?K.concat(B):[K,B]}J.exports=function(W,U){W=W||[],U=U||{};var Z,z,H,K,B,O={_:[]},X=0,j=0,q=0,E=W.length;let F=U.alias!==void 0,w=U.unknown!==void 0,T=U.default!==void 0;if(U.alias=U.alias||{},U.string=Y(U.string),U.boolean=Y(U.boolean),F)for(Z in U.alias){z=U.alias[Z]=Y(U.alias[Z]);for(X=0;X<z.length;X++)(U.alias[z[X]]=z.concat(Z)).splice(X,1)}for(X=U.boolean.length;X-- >0;){z=U.alias[U.boolean[X]]||[];for(j=z.length;j-- >0;)U.boolean.push(z[j])}for(X=U.string.length;X-- >0;){z=U.alias[U.string[X]]||[];for(j=z.length;j-- >0;)U.string.push(z[j])}if(T){for(Z in U.default)if(K=typeof U.default[Z],z=U.alias[Z]=U.alias[Z]||[],U[K]!==void 0){U[K].push(Z);for(X=0;X<z.length;X++)U[K].push(z[X])}}let S=w?Object.keys(U.alias):[];for(X=0;X<E;X++){if(H=W[X],H==="--"){O._=O._.concat(W.slice(++X));break}for(j=0;j<H.length;j++)if(H.charCodeAt(j)!==45)break;if(j===0)O._.push(H);else if(H.substring(j,j+3)==="no-"){if(K=H.substring(j+3),w&&!~S.indexOf(K))return U.unknown(H);O[K]=!1}else{for(q=j+1;q<H.length;q++)if(H.charCodeAt(q)===61)break;K=H.substring(j,q),B=H.substring(++q)||(X+1===E||(""+W[X+1]).charCodeAt(0)===45||W[++X]),z=j===2?[K]:K;for(q=0;q<z.length;q++){if(K=z[q],w&&!~S.indexOf(K))return U.unknown("-".repeat(j)+K);Q(O,K,q+1<z.length||B,U)}}}if(T){for(Z in U.default)if(O[Z]===void 0)O[Z]=U.default[Z]}if(F)for(Z in O){z=U.alias[Z]||[];while(z.length>0)O[z.shift()]=O[Z]}return O}}),_$=s1(($,J)=>{var Y=process||{},Q=Y.argv||[],W=Y.env||{},U=!(!!W.NO_COLOR||Q.includes("--no-color"))&&(!!W.FORCE_COLOR||Q.includes("--color")||Y.platform==="win32"||(Y.stdout||{}).isTTY&&W.TERM!=="dumb"||!!W.CI),Z=(K,B,O=K)=>(X)=>{let j=""+X,q=j.indexOf(B,K.length);return~q?K+z(j,B,O,q)+B:K+j+B},z=(K,B,O,X)=>{let j="",q=0;do j+=K.substring(q,X)+O,q=X+B.length,X=K.indexOf(B,q);while(~X);return j+K.substring(q)},H=(K=U)=>{let B=K?Z:()=>String;return{isColorSupported:K,reset:B("\x1B[0m","\x1B[0m"),bold:B("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:B("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:B("\x1B[3m","\x1B[23m"),underline:B("\x1B[4m","\x1B[24m"),inverse:B("\x1B[7m","\x1B[27m"),hidden:B("\x1B[8m","\x1B[28m"),strikethrough:B("\x1B[9m","\x1B[29m"),black:B("\x1B[30m","\x1B[39m"),red:B("\x1B[31m","\x1B[39m"),green:B("\x1B[32m","\x1B[39m"),yellow:B("\x1B[33m","\x1B[39m"),blue:B("\x1B[34m","\x1B[39m"),magenta:B("\x1B[35m","\x1B[39m"),cyan:B("\x1B[36m","\x1B[39m"),white:B("\x1B[37m","\x1B[39m"),gray:B("\x1B[90m","\x1B[39m"),bgBlack:B("\x1B[40m","\x1B[49m"),bgRed:B("\x1B[41m","\x1B[49m"),bgGreen:B("\x1B[42m","\x1B[49m"),bgYellow:B("\x1B[43m","\x1B[49m"),bgBlue:B("\x1B[44m","\x1B[49m"),bgMagenta:B("\x1B[45m","\x1B[49m"),bgCyan:B("\x1B[46m","\x1B[49m"),bgWhite:B("\x1B[47m","\x1B[49m"),blackBright:B("\x1B[90m","\x1B[39m"),redBright:B("\x1B[91m","\x1B[39m"),greenBright:B("\x1B[92m","\x1B[39m"),yellowBright:B("\x1B[93m","\x1B[39m"),blueBright:B("\x1B[94m","\x1B[39m"),magentaBright:B("\x1B[95m","\x1B[39m"),cyanBright:B("\x1B[96m","\x1B[39m"),whiteBright:B("\x1B[97m","\x1B[39m"),bgBlackBright:B("\x1B[100m","\x1B[49m"),bgRedBright:B("\x1B[101m","\x1B[49m"),bgGreenBright:B("\x1B[102m","\x1B[49m"),bgYellowBright:B("\x1B[103m","\x1B[49m"),bgBlueBright:B("\x1B[104m","\x1B[49m"),bgMagentaBright:B("\x1B[105m","\x1B[49m"),bgCyanBright:B("\x1B[106m","\x1B[49m"),bgWhiteBright:B("\x1B[107m","\x1B[49m")}};J.exports=H(),J.exports.createColors=H}),c9=s1(($,J)=>{J.exports=()=>{return/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g}}),l9=K$(m9(),1);function X5($){return $.replace(/[<[].+/,"").trim()}function r9($){let J=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,Q=[],W=(z)=>{let H=!1,K=z[1];if(K.startsWith("..."))K=K.slice(3),H=!0;return{required:z[0].startsWith("<"),value:K,variadic:H}},U;while(U=J.exec($))Q.push(W(U));let Z;while(Z=Y.exec($))Q.push(W(Z));return Q}function a9($){let J={alias:{},boolean:[]};for(let[Y,Q]of $.entries()){if(Q.names.length>1)J.alias[Q.names[0]]=Q.names.slice(1);if(Q.isBoolean)if(Q.negated){if(!$.some((U,Z)=>{return Z!==Y&&U.names.some((z)=>Q.names.includes(z))&&typeof U.required==="boolean"}))J.boolean.push(Q.names[0])}else J.boolean.push(Q.names[0])}return J}function Q5($){return $.sort((J,Y)=>{return J.length>Y.length?-1:1})[0]}function W5($,J){return $.length>=J?$:`${$}${" ".repeat(J-$.length)}`}function n9($){return $.replace(/([a-z])-([a-z])/g,(J,Y,Q)=>{return Y+Q.toUpperCase()})}function s9($,J,Y){let Q=0,W=J.length,U=$,Z;for(;Q<W;++Q)Z=U[J[Q]],U=U[J[Q]]=Q===W-1?Y:Z!=null?Z:!!~J[Q+1].indexOf(".")||!(+J[Q+1]>-1)?{}:[]}function i9($,J){for(let Y of Object.keys(J)){let Q=J[Y];if(Q.shouldTransform){if($[Y]=Array.prototype.concat.call([],$[Y]),typeof Q.transformFunction==="function")$[Y]=$[Y].map(Q.transformFunction)}}}function t9($){let J=/([^\\/]+)$/.exec($);return J?J[1]:""}function j5($){return $.split(".").map((J,Y)=>{return Y===0?n9(J):J}).join(".")}class i0 extends Error{constructor($){super($);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}}function o9(){let{env:$}=Y5,{TERM:J,TERM_PROGRAM:Y}=$;if(Y5.platform!=="win32")return J!=="linux";return Boolean($.WT_SESSION)||Boolean($.TERMINUS_SUBLIME)||$.ConEmuTask==="{cmd::Cmder}"||Y==="Terminus-Sublime"||Y==="vscode"||J==="xterm-256color"||J==="alacritty"||J==="rxvt-unicode"||J==="rxvt-unicode-256color"||$.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var e0="\x1B",M$=`${e0}[`;var Y0={to($,J){if(!J)return`${M$}${$+1}G`;return`${M$}${J+1};${$+1}H`},move($,J){let Y="";if($<0)Y+=`${M$}${-$}D`;else if($>0)Y+=`${M$}${$}C`;if(J<0)Y+=`${M$}${-J}A`;else if(J>0)Y+=`${M$}${J}B`;return Y},up:($=1)=>`${M$}${$}A`,down:($=1)=>`${M$}${$}B`,forward:($=1)=>`${M$}${$}C`,backward:($=1)=>`${M$}${$}D`,nextLine:($=1)=>`${M$}E`.repeat($),prevLine:($=1)=>`${M$}F`.repeat($),left:`${M$}G`,hide:`${M$}?25l`,show:`${M$}?25h`,save:`${e0}7`,restore:`${e0}8`};var l1={screen:`${M$}2J`,up:($=1)=>`${M$}1J`.repeat($),down:($=1)=>`${M$}J`.repeat($),line:`${M$}2K`,lineEnd:`${M$}K`,lineStart:`${M$}1K`,lines($){let J="";for(let Y=0;Y<$;Y++)J+=this.line+(Y<$-1?Y0.up():"");if($)J+=Y0.left;return J}},sW={screen:`${e0}c`};class q5{rawName;description;name;names;isBoolean;required;config;negated;constructor($,J,Y){if(this.rawName=$,this.description=J,this.config=Object.assign({},Y),$=$.replace(/\.\*/g,""),this.negated=!1,this.names=X5($).split(",").map((Q)=>{let W=Q.trim().replace(/^-{1,2}/,"");if(W.startsWith("no-"))this.negated=!0,W=W.replace(/^no-/,"");return j5(W)}).sort((Q,W)=>Q.length>W.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if($.includes("<"))this.required=!0;else if($.includes("["))this.required=!1;else this.isBoolean=!0}}var tW=n1.argv,e9=`${n1.platform}-${n1.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,$Y=t0.argv,JY=`${t0.platform}-${t0.arch} node-${t0.version}`;class i1{rawName;description;config;cli;options;aliasNames;name;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;constructor($,J,Y,Q){if(this.rawName=$,this.description=J,this.config=Y,this.cli=Q,this.options=[],this.aliasNames=[],this.name=X5($),this.args=r9($),this.examples=[],!Y)this.config={}}usage($){return this.usageText=$,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version($,J="-v, --version"){return this.versionNumber=$,this.option(J,"Display version number"),this}example($){return this.examples.push($),this}option($,J,Y){let Q=new q5($,J,Y);return this.options.push(Q),this}alias($){return this.aliasNames.push($),this}action($){return this.commandAction=$,this}isMatched($){return this.name===$||this.aliasNames.includes($)}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof t1}hasOption($){return $=$.split(".")[0],!!this.options.find((J)=>{return J.names.includes($)})}outputHelp(){let{name:$,commands:J}=this.cli,{versionNumber:Y,options:Q,helpCallback:W}=this.cli.globalCommand,U=[{body:`${$}${Y?`/${Y}`:""}`}];if(U.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&J.length>0){let H=Q5(J.map((K)=>K.rawName));U.push({title:"Commands",body:J.map((K)=>{return` ${W5(K.rawName,H.length)} ${K.description}`}).join(`
328
+ `)}),U.push({title:"For more info, run any command with the `--help` flag",body:J.map((K)=>` $ ${$}${K.name===""?"":` ${K.name}`} --help`).join(`
329
+ `)})}let z=this.isGlobalCommand?Q:[...this.options,...Q||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)z=z.filter((H)=>H.name!=="version");if(z.length>0){let H=Q5(z.map((K)=>K.rawName));U.push({title:"Options",body:z.map((K)=>{return` ${W5(K.rawName,H.length)} ${K.description} ${K.config.default===void 0?"":`(default: ${K.config.default})`}`}).join(`
330
+ `)})}if(this.examples.length>0)U.push({title:"Examples",body:this.examples.map((H)=>{if(typeof H==="function")return H($);return H}).join(`
331
+ `)});if(W)U=W(U)||U;console.log(U.map((H)=>{return H.title?`${H.title}:
332
+ ${H.body}`:H.body}).join(`
333
+
334
+ `))}outputVersion(){let{name:$}=this.cli,{versionNumber:J}=this.cli.globalCommand;if(J){let Y;if(Bun)Y=e9;else Y=JY;console.log(`${$}/${J} ${Y}`)}}checkRequiredArgs(){let $=this.args.filter((J)=>J.required).length;if(this.cli.args.length<$)throw new i0(`missing required args for command \`${this.rawName}\``)}checkUnknownOptions(){let{options:$,globalCommand:J}=this.cli;if(!this.config.allowUnknownOptions){for(let Y of Object.keys($))if(Y!=="--"&&!this.hasOption(Y)&&!J.hasOption(Y))throw new i0(`Unknown option \`${Y.length>1?`--${Y}`:`-${Y}`}\``)}}checkOptionValue(){let{options:$,globalCommand:J}=this.cli,Y=[...J.options,...this.options];for(let Q of Y){let W=$[Q.name.split(".")[0]];if(Q.required){let U=Y.some((Z)=>Z.negated&&Z.names.includes(Q.name));if(W===!0||W===!1&&!U)throw new i0(`option \`${Q.rawName}\` value is missing`)}}}}class t1 extends i1{constructor($){super("@@global@@","",{},$)}}var YY=i1;class o1 extends p9{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;constructor($=""){super();this.name=$,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new t1(this),this.globalCommand.usage("<command> [options]")}usage($){return this.globalCommand.usage($),this}command($,J,Y){if(!Y)Y={};let Q=new YY($,J||"",Y,this);return Q.globalCommand=this.globalCommand,this.commands.push(Q),Q}option($,J,Y){return this.globalCommand.option($,J,Y),this}help($){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=$,this.showHelpOnExit=!0,this}version($,J="-v, --version"){return this.globalCommand.version($,J),this.showVersionOnExit=!0,this}example($){return this.globalCommand.example($),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:$,options:J},Y,Q){if(this.args=$,this.options=J,Y)this.matchedCommand=Y;if(Q)this.matchedCommandName=Q;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}parse($=$Y,{run:J=!0}={}){if(this.rawArgs=$,!this.name)this.name=$[1]?t9($[1]):"cli";let Y=!0;for(let W of this.commands){let U=this.mri($.slice(2),W),Z=U.args[0];if(W.isMatched(Z)){Y=!1;let z={...U,args:U.args.slice(1)};this.setParsedInfo(z,W,Z),this.emit(`command:${Z}`,W)}}if(Y){for(let W of this.commands)if(W.name===""){Y=!1;let U=this.mri($.slice(2),W);this.setParsedInfo(U,W),this.emit("command:!",W)}}if(Y){let W=this.mri($.slice(2));this.setParsedInfo(W)}if(this.options.help&&this.showHelpOnExit)this.outputHelp(),J=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),J=!1,this.unsetMatchedCommand();let Q={args:this.args,options:this.options};if(J)this.runMatchedCommand();if(!this.matchedCommand&&this.args[0])this.emit("command:*");return Q}mri($,J){let Y=[...this.globalCommand.options,...J?J.options:[]],Q=a9(Y),W=[],U=$.indexOf("--");if(U>-1)W=$.slice(U+1),$=$.slice(0,U);let Z=l9.default($,Q);Z=Object.keys(Z).reduce((O,X)=>{return{...O,[j5(X)]:Z[X]}},{_:[]});let z=Z._,H={"--":W},K=J&&J.config.ignoreOptionDefaultValue?J.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,B=Object.create(null);for(let O of Y){if(!K&&O.config.default!==void 0)for(let X of O.names)H[X]=O.config.default;if(Array.isArray(O.config.type)){if(B[O.name]===void 0)B[O.name]=Object.create(null),B[O.name].shouldTransform=!0,B[O.name].transformFunction=O.config.type[0]}}for(let O of Object.keys(Z))if(O!=="_"){let X=O.split(".");s9(H,X,Z[O]),i9(H,B)}return{args:z,options:H}}runMatchedCommand(){let{args:$,options:J,matchedCommand:Y}=this;if(!Y||!Y.commandAction)return;Y.checkUnknownOptions(),Y.checkOptionValue(),Y.checkRequiredArgs();let Q=[];return Y.args.forEach((W,U)=>{if(W.variadic)Q.push($.slice(U));else Q.push($[U])}),Q.push(J),Y.commandAction.apply(this,Q)}}var eW=K$(_$(),1),WY=["up","down","left","right","space","enter","cancel"],o0={actions:new Set(WY),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function V5($,J){if(typeof $==="string")return o0.aliases.get($)===J;for(let Y of $){if(Y===void 0)continue;if(V5(Y,J))return!0}return!1}function UY($,J){if($===J)return[];let Y=$.split(`
335
+ `),Q=J.split(`
336
+ `),W=[];for(let U=0;U<Math.max(Y.length,Q.length);U++)if(Y[U]!==Q[U])W.push(U);return W}var QU=QY.platform.startsWith("win"),U5=Symbol("clapp:cancel");function s0($,J){let Y=$;if(Y.isTTY)Y.setRawMode(J)}var p1=K$(_$(),1);function HY({onlyFirst:$=!1}={}){return new RegExp("(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]",$?void 0:"g")}var KY=HY();function M5($){if(typeof $!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof $}\``);return $.replace(KY,"")}function BY($){return $===161||$===164||$===167||$===168||$===170||$===173||$===174||$>=176&&$<=180||$>=182&&$<=186||$>=188&&$<=191||$===198||$===208||$===215||$===216||$>=222&&$<=225||$===230||$>=232&&$<=234||$===236||$===237||$===240||$===242||$===243||$>=247&&$<=250||$===252||$===254||$===257||$===273||$===275||$===283||$===294||$===295||$===299||$>=305&&$<=307||$===312||$>=319&&$<=322||$===324||$>=328&&$<=331||$===333||$===338||$===339||$===358||$===359||$===363||$===462||$===464||$===466||$===468||$===470||$===472||$===474||$===476||$===593||$===609||$===708||$===711||$>=713&&$<=715||$===717||$===720||$>=728&&$<=731||$===733||$===735||$>=768&&$<=879||$>=913&&$<=929||$>=931&&$<=937||$>=945&&$<=961||$>=963&&$<=969||$===1025||$>=1040&&$<=1103||$===1105||$===8208||$>=8211&&$<=8214||$===8216||$===8217||$===8220||$===8221||$>=8224&&$<=8226||$>=8228&&$<=8231||$===8240||$===8242||$===8243||$===8245||$===8251||$===8254||$===8308||$===8319||$>=8321&&$<=8324||$===8364||$===8451||$===8453||$===8457||$===8467||$===8470||$===8481||$===8482||$===8486||$===8491||$===8531||$===8532||$>=8539&&$<=8542||$>=8544&&$<=8555||$>=8560&&$<=8569||$===8585||$>=8592&&$<=8601||$===8632||$===8633||$===8658||$===8660||$===8679||$===8704||$===8706||$===8707||$===8711||$===8712||$===8715||$===8719||$===8721||$===8725||$===8730||$>=8733&&$<=8736||$===8739||$===8741||$>=8743&&$<=8748||$===8750||$>=8756&&$<=8759||$===8764||$===8765||$===8776||$===8780||$===8786||$===8800||$===8801||$>=8804&&$<=8807||$===8810||$===8811||$===8814||$===8815||$===8834||$===8835||$===8838||$===8839||$===8853||$===8857||$===8869||$===8895||$===8978||$>=9312&&$<=9449||$>=9451&&$<=9547||$>=9552&&$<=9587||$>=9600&&$<=9615||$>=9618&&$<=9621||$===9632||$===9633||$>=9635&&$<=9641||$===9650||$===9651||$===9654||$===9655||$===9660||$===9661||$===9664||$===9665||$>=9670&&$<=9672||$===9675||$>=9678&&$<=9681||$>=9698&&$<=9701||$===9711||$===9733||$===9734||$===9737||$===9742||$===9743||$===9756||$===9758||$===9792||$===9794||$===9824||$===9825||$>=9827&&$<=9829||$>=9831&&$<=9834||$===9836||$===9837||$===9839||$===9886||$===9887||$===9919||$>=9926&&$<=9933||$>=9935&&$<=9939||$>=9941&&$<=9953||$===9955||$===9960||$===9961||$>=9963&&$<=9969||$===9972||$>=9974&&$<=9977||$===9979||$===9980||$===9982||$===9983||$===10045||$>=10102&&$<=10111||$>=11094&&$<=11097||$>=12872&&$<=12879||$>=57344&&$<=63743||$>=65024&&$<=65039||$===65533||$>=127232&&$<=127242||$>=127248&&$<=127277||$>=127280&&$<=127337||$>=127344&&$<=127373||$===127375||$===127376||$>=127387&&$<=127404||$>=917760&&$<=917999||$>=983040&&$<=1048573||$>=1048576&&$<=1114109}function OY($){return $===12288||$>=65281&&$<=65376||$>=65504&&$<=65510}function XY($){return $>=4352&&$<=4447||$===8986||$===8987||$===9001||$===9002||$>=9193&&$<=9196||$===9200||$===9203||$===9725||$===9726||$===9748||$===9749||$>=9776&&$<=9783||$>=9800&&$<=9811||$===9855||$>=9866&&$<=9871||$===9875||$===9889||$===9898||$===9899||$===9917||$===9918||$===9924||$===9925||$===9934||$===9940||$===9962||$===9970||$===9971||$===9973||$===9978||$===9981||$===9989||$===9994||$===9995||$===10024||$===10060||$===10062||$>=10067&&$<=10069||$===10071||$>=10133&&$<=10135||$===10160||$===10175||$===11035||$===11036||$===11088||$===11093||$>=11904&&$<=11929||$>=11931&&$<=12019||$>=12032&&$<=12245||$>=12272&&$<=12287||$>=12289&&$<=12350||$>=12353&&$<=12438||$>=12441&&$<=12543||$>=12549&&$<=12591||$>=12593&&$<=12686||$>=12688&&$<=12773||$>=12783&&$<=12830||$>=12832&&$<=12871||$>=12880&&$<=42124||$>=42128&&$<=42182||$>=43360&&$<=43388||$>=44032&&$<=55203||$>=63744&&$<=64255||$>=65040&&$<=65049||$>=65072&&$<=65106||$>=65108&&$<=65126||$>=65128&&$<=65131||$>=94176&&$<=94180||$===94192||$===94193||$>=94208&&$<=100343||$>=100352&&$<=101589||$>=101631&&$<=101640||$>=110576&&$<=110579||$>=110581&&$<=110587||$===110589||$===110590||$>=110592&&$<=110882||$===110898||$>=110928&&$<=110930||$===110933||$>=110948&&$<=110951||$>=110960&&$<=111355||$>=119552&&$<=119638||$>=119648&&$<=119670||$===126980||$===127183||$===127374||$>=127377&&$<=127386||$>=127488&&$<=127490||$>=127504&&$<=127547||$>=127552&&$<=127560||$===127568||$===127569||$>=127584&&$<=127589||$>=127744&&$<=127776||$>=127789&&$<=127797||$>=127799&&$<=127868||$>=127870&&$<=127891||$>=127904&&$<=127946||$>=127951&&$<=127955||$>=127968&&$<=127984||$===127988||$>=127992&&$<=128062||$===128064||$>=128066&&$<=128252||$>=128255&&$<=128317||$>=128331&&$<=128334||$>=128336&&$<=128359||$===128378||$===128405||$===128406||$===128420||$>=128507&&$<=128591||$>=128640&&$<=128709||$===128716||$>=128720&&$<=128722||$>=128725&&$<=128727||$>=128732&&$<=128735||$===128747||$===128748||$>=128756&&$<=128764||$>=128992&&$<=129003||$===129008||$>=129292&&$<=129338||$>=129340&&$<=129349||$>=129351&&$<=129535||$>=129648&&$<=129660||$>=129664&&$<=129673||$>=129679&&$<=129734||$>=129742&&$<=129756||$>=129759&&$<=129769||$>=129776&&$<=129784||$>=131072&&$<=196605||$>=196608&&$<=262141}function jY($){if(!Number.isSafeInteger($))throw TypeError(`Expected a code point, got \`${typeof $}\`.`)}function qY($,{ambiguousAsWide:J=!1}={}){if(jY($),OY($)||XY($)||J&&BY($))return 2;return 1}var VY=K$(c9(),1),MY=new Intl.Segmenter,EY=/^\p{Default_Ignorable_Code_Point}$/u;function d0($,J={}){if(typeof $!=="string"||$.length===0)return 0;let{ambiguousIsNarrow:Y=!0,countAnsiEscapeCodes:Q=!1}=J;if(!Q)$=M5($);if($.length===0)return 0;let W=0,U={ambiguousAsWide:!Y};for(let{segment:Z}of MY.segment($)){let z=Z.codePointAt(0);if(z<=31||z>=127&&z<=159)continue;if(z>=8203&&z<=8207||z===65279)continue;if(z>=768&&z<=879||z>=6832&&z<=6911||z>=7616&&z<=7679||z>=8400&&z<=8447||z>=65056&&z<=65071)continue;if(z>=55296&&z<=57343)continue;if(z>=65024&&z<=65039)continue;if(EY.test(Z))continue;if(VY.default().test(Z)){W+=2;continue}W+=qY(z,U)}return W}var r1=10,z5=($=0)=>(J)=>`\x1B[${J+$}m`,G5=($=0)=>(J)=>`\x1B[${38+$};5;${J}m`,H5=($=0)=>(J,Y,Q)=>`\x1B[${38+$};2;${J};${Y};${Q}m`,Z$={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},ZU=Object.keys(Z$.modifier),_Y=Object.keys(Z$.color),FY=Object.keys(Z$.bgColor),zU=[..._Y,...FY];function wY(){let $=new Map;for(let[J,Y]of Object.entries(Z$)){for(let[Q,W]of Object.entries(Y))Z$[Q]={open:`\x1B[${W[0]}m`,close:`\x1B[${W[1]}m`},Y[Q]=Z$[Q],$.set(W[0],W[1]);Object.defineProperty(Z$,J,{value:Y,enumerable:!1})}return Object.defineProperty(Z$,"codes",{value:$,enumerable:!1}),Z$.color.close="\x1B[39m",Z$.bgColor.close="\x1B[49m",Z$.color.ansi=z5(),Z$.color.ansi256=G5(),Z$.color.ansi16m=H5(),Z$.bgColor.ansi=z5(r1),Z$.bgColor.ansi256=G5(r1),Z$.bgColor.ansi16m=H5(r1),Object.defineProperties(Z$,{rgbToAnsi256:{value:(J,Y,Q)=>{if(J===Y&&Y===Q){if(J<8)return 16;if(J>248)return 231;return Math.round((J-8)/247*24)+232}return 16+36*Math.round(J/255*5)+6*Math.round(Y/255*5)+Math.round(Q/255*5)},enumerable:!1},hexToRgb:{value:(J)=>{let Y=/[a-f\d]{6}|[a-f\d]{3}/i.exec(J.toString(16));if(!Y)return[0,0,0];let[Q]=Y;if(Q.length===3)Q=[...Q].map((U)=>U+U).join("");let W=Number.parseInt(Q,16);return[W>>16&255,W>>8&255,W&255]},enumerable:!1},hexToAnsi256:{value:(J)=>Z$.rgbToAnsi256(...Z$.hexToRgb(J)),enumerable:!1},ansi256ToAnsi:{value:(J)=>{if(J<8)return 30+J;if(J<16)return 90+(J-8);let Y,Q,W;if(J>=232)Y=((J-232)*10+8)/255,Q=Y,W=Y;else{J-=16;let z=J%36;Y=Math.floor(J/36)/5,Q=Math.floor(z/6)/5,W=z%6/5}let U=Math.max(Y,Q,W)*2;if(U===0)return 30;let Z=30+(Math.round(W)<<2|Math.round(Q)<<1|Math.round(Y));if(U===2)Z+=60;return Z},enumerable:!1},rgbToAnsi:{value:(J,Y,Q)=>Z$.ansi256ToAnsi(Z$.rgbToAnsi256(J,Y,Q)),enumerable:!1},hexToAnsi:{value:(J)=>Z$.ansi256ToAnsi(Z$.hexToAnsi256(J)),enumerable:!1}}),Z$}var TY=wY(),LY=TY,J1=new Set(["\x1B","›"]),AY=39,e1="\x07",E5="[",RY="]",_5="m",$1=`${RY}8;;`,K5=($)=>`${J1.values().next().value}${E5}${$}${_5}`,B5=($)=>`${J1.values().next().value}${$1}${$}${e1}`,SY=($)=>$.split(" ").map((J)=>d0(J)),a1=($,J,Y)=>{let Q=[...J],W=!1,U=!1,Z=d0(M5($.at(-1)));for(let[z,H]of Q.entries()){let K=d0(H);if(Z+K<=Y)$[$.length-1]+=H;else $.push(H),Z=0;if(J1.has(H))W=!0,U=Q.slice(z+1,z+1+$1.length).join("")===$1;if(W){if(U){if(H===e1)W=!1,U=!1}else if(H===_5)W=!1;continue}if(Z+=K,Z===Y&&z<Q.length-1)$.push(""),Z=0}if(!Z&&$.at(-1).length>0&&$.length>1)$[$.length-2]+=$.pop()},DY=($)=>{let J=$.split(" "),Y=J.length;while(Y>0){if(d0(J[Y-1])>0)break;Y--}if(Y===J.length)return $;return J.slice(0,Y).join(" ")+J.slice(Y).join("")},PY=($,J,Y={})=>{if(Y.trim!==!1&&$.trim()==="")return"";let Q="",W,U,Z=SY($),z=[""];for(let[O,X]of $.split(" ").entries()){if(Y.trim!==!1)z[z.length-1]=z.at(-1).trimStart();let j=d0(z.at(-1));if(O!==0){if(j>=J&&(Y.wordWrap===!1||Y.trim===!1))z.push(""),j=0;if(j>0||Y.trim===!1)z[z.length-1]+=" ",j++}if(Y.hard&&Z[O]>J){let q=J-j,E=1+Math.floor((Z[O]-q-1)/J);if(Math.floor((Z[O]-1)/J)<E)z.push("");a1(z,X,J);continue}if(j+Z[O]>J&&j>0&&Z[O]>0){if(Y.wordWrap===!1&&j<J){a1(z,X,J);continue}z.push("")}if(j+Z[O]>J&&Y.wordWrap===!1){a1(z,X,J);continue}z[z.length-1]+=X}if(Y.trim!==!1)z=z.map((O)=>DY(O));let H=z.join(`
337
+ `),K=[...H],B=0;for(let[O,X]of K.entries()){if(Q+=X,J1.has(X)){let{groups:q}=new RegExp(`(?:\\${E5}(?<code>\\d+)m|\\${$1}(?<uri>.*)${e1})`).exec(H.slice(B))||{groups:{}};if(q.code!==void 0){let E=Number.parseFloat(q.code);W=E===AY?void 0:E}else if(q.uri!==void 0)U=q.uri.length===0?void 0:q.uri}let j=LY.codes.get(Number(W));if(K[O+1]===`
338
+ `){if(U)Q+=B5("");if(W&&j)Q+=K5(j)}else if(X===`
339
+ `){if(W&&j)Q+=K5(W);if(U)Q+=B5(U)}B+=X.length}return Q};function O5($,J,Y){return String($).normalize().replaceAll(`\r
340
+ `,`
341
+ `).split(`
342
+ `).map((Q)=>PY(Q,J,Y)).join(`
343
+ `)}class $J{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor($,J=!0){let{input:Y=ZY,output:Q=zY,render:W,signal:U,...Z}=$;this.opts=Z,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=W.bind(this),this._track=J,this._abortSignal=U,this.input=Y,this.output=Q}unsubscribe(){this._subscribers.clear()}setSubscriber($,J){let Y=this._subscribers.get($)??[];Y.push(J),this._subscribers.set($,Y)}on($,J){return this.setSubscriber($,{cb:J}),this}once($,J){return this.setSubscriber($,{cb:J,once:!0}),this}emit($,...J){let Y=this._subscribers.get($)??[],Q=[];for(let W of Y)if(W.cb(...J),W.once)Q.push(()=>Y.splice(Y.indexOf(W),1));for(let W of Q)W();return this}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(U5);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=GY.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),s0(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Y0.show),this.output.off("resize",this.render),s0(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(Y0.show),this.output.off("resize",this.render),s0(this.input,!1),$(U5)})})}_isActionKey($,J){return $==="\t"}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,J){if(this.userInput=$??"",this.emit("userInput",this.userInput),J&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress($,J){if(this._track&&J.name!=="return"){if(J.name&&this._isActionKey($,J))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Y=J.name==="tab"||J.name==="escape"||J.name==="backspace"||J.name==="delete"||J.name==="enter"||J.name==="return"||J.name&&["up","down","left","right"].includes(J.name);if($&&!Y&&$.length===1&&$>=" ")this._manualLine+=$;else if(J.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let Q=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(Q)}if(this.state==="error")this.state="active",this.error="";if(J?.name){if(!this._track&&o0.aliases.has(J.name))this.emit("cursor",o0.aliases.get(J.name));if(o0.actions.has(J.name))this.emit("cursor",J.name)}if($&&($.toLowerCase()==="y"||$.toLowerCase()==="n"))this.emit("confirm",$.toLowerCase()==="y");if(this.emit("key",$?.toLowerCase(),J),J?.name==="return"){if(this.opts.validate){let Y=this.opts.validate(this.value);if(Y)this.error=Y instanceof Error?Y.message:Y,this.state="error"}if(this.state!=="error")this.state="submit"}if(V5([$,J?.name,J?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
344
+ `),s0(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let $=O5(this._prevFrame,Z5.stdout.columns,{hard:!0,trim:!1}).split(`
345
+ `).length-1;this.output.write(Y0.move(-999,$*-1))}render(){let $=O5(this._render(this)??"",Z5.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(Y0.hide);else{let J=UY(this._prevFrame,$);if(this.restoreCursor(),J&&J?.length===1){let Y=J[0];this.output.write(Y0.move(0,Y)),this.output.write(l1.lines(1));let Q=$.split(`
346
+ `);this.output.write(Q[Y]),this._prevFrame=$,this.output.write(Y0.move(0,Q.length-Y-1));return}if(J&&J?.length>1){let Y=J[0];this.output.write(Y0.move(0,Y)),this.output.write(l1.down());let W=$.split(`
347
+ `).slice(Y);this.output.write(W.join(`
348
+ `)),this._prevFrame=$;return}this.output.write(l1.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function CY($,J){if($===void 0)return 0;if(J.length===0)return 0;let Q=J.findIndex((W)=>W.value===$);return Q!==-1?Q:0}function NY($,J){return(J.label??String(J.value)).toLowerCase().includes($.toLowerCase())}function kY($,J){if(!J)return;if($)return J;return J[0]}class IY extends $J{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Y="";#Q;#J;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return p1.default.inverse(p1.default.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[J,...Y]=this.userInput.slice(this._cursor);return`${$}${p1.default.inverse(J)}${Y.join("")}`}get options(){if(typeof this.#J==="function")return this.#J();return this.#J}constructor($){super($);this.#J=$.options;let J=this.options;this.filteredOptions=[...J],this.multiple=$.multiple===!0,this.#Q=$.filter??NY;let Y;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)Y=$.initialValue;else Y=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Y=[this.options[0].value];if(Y)for(let Q of Y){let W=J.findIndex((U)=>U.value===Q);if(W!==-1)this.toggleSelected(Q),this.#$=W}this.focusedValue=this.options[this.#$]?.value,this.on("key",(Q,W)=>this.#W(Q,W)),this.on("userInput",(Q)=>this.#U(Q))}_isActionKey($,J){return $==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&$!==void 0&&$!==""}#W($,J){let Y=J.name==="up",Q=J.name==="down",W=J.name==="return";if(Y||Q){if(this.#$=Math.max(0,Math.min(this.#$+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(W)this.value=kY(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((J)=>J!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#U($){if($!==this.#Y){this.#Y=$;let J=this.options;if($)this.filteredOptions=J.filter((Y)=>this.#Q($,Y));else this.filteredOptions=[...J];if(this.#$=CY(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class xY extends $J{options;cursor=0;#$;getGroupItems($){return this.options.filter((J)=>J.group===$)}isGroupSelected($){let J=this.getGroupItems($),Y=this.value;if(Y===void 0)return!1;return J.every((Q)=>Y.includes(Q.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let J=$.value,Y=this.getGroupItems(J);if(this.isGroupSelected(J))this.value=this.value.filter((Q)=>Y.findIndex((W)=>W.value===Q)===-1);else this.value=[...this.value,...Y.map((Q)=>Q.value)];this.value=Array.from(new Set(this.value))}else{let J=this.value.includes($.value);this.value=J?this.value.filter((Y)=>Y!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:J}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([Y,Q])=>[{value:Y,group:!0,label:Y},...Q.map((W)=>({...W,group:Y}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===$.cursorAt),this.#$?0:1),this.on("cursor",(Y)=>{switch(Y){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Q=this.options[this.cursor]?.group===!0;if(!this.#$&&Q)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Q=this.options[this.cursor]?.group===!0;if(!this.#$&&Q)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var GU=K$(_$(),1);var HU=K$(_$(),1);var KU=K$(_$(),1),K0={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]},u0={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function hY(){return!0}function bY(){let $={};$.supportsColor=hY();function J(Q,W=[]){let U=Q===""?[]:[...W,Q],Z=function(H){if(!$.supportsColor)return H;let K="",B="";for(let O of U)if(O in u0&&u0[O]in K0){let X=u0[O];K+=K0[X][0],B=K0[X][1]+B}else if(O in K0)K+=K0[O][0],B=K0[O][1]+B;return K+H+B},z=[...Object.keys(K0),...Object.keys(u0)];for(let H of z)if(!(H in Z))Object.defineProperty(Z,H,{get(){return J(H,U)}});return Z}let Y=[...Object.keys(K0),...Object.keys(u0)];for(let Q of Y)if(!(Q in $))Object.defineProperty($,Q,{get(){return J(Q)}});return $}var BU=bY();var yY=o9();var z$=($,J)=>yY?$:J,OU=z$("◆","*"),XU=z$("■","x"),jU=z$("▲","x"),qU=z$("◇","o"),VU=z$("┌","T"),vY=z$("│","|"),MU=z$("└","—"),EU=z$("●",">"),_U=z$("○"," "),FU=z$("◻","[•]"),wU=z$("◼","[+]"),TU=z$("◻","[ ]"),LU=z$("▪","•"),AU=z$("─","-"),RU=z$("╮","+"),SU=z$("├","+"),DU=z$("╯","+"),PU=z$("●","•"),CU=z$("◆","*"),NU=z$("▲","!"),kU=z$("■","x");var IU=K$(_$(),1);var xU=K$(_$(),1);var hU=K$(_$(),1);var bU=K$(_$(),1);var yU=K$(_$(),1);var vU=K$(_$(),1);var fU=K$(_$(),1);var gU=K$(_$(),1);var uU=K$(_$(),1),dU=K$(_$(),1);var mU={light:z$("─","-"),heavy:z$("━","="),block:z$("█","#")};var cU=K$(_$(),1);var lU=K$(_$(),1);var fY=K$(_$(),1);function gY(){return`${fY.default.gray(vY)} `}var pU=gY();var rU=K$(_$(),1);var aU=K$(_$(),1);var JJ="0.1.6";import{existsSync as HJ}from"node:fs";import{mkdir as SQ,writeFile as m5}from"node:fs/promises";var s={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function L0($,J){return`${s[J]}${$}${s.reset}`}function A($){console.log(`${s.green}✓${s.reset} ${$}`)}function _($){console.error(`${s.red}✗${s.reset} ${$}`)}function N($){console.warn(`${s.yellow}⚠${s.reset} ${$}`)}var i$=N;function G($){console.log(`${s.blue}ℹ${s.reset} ${$}`)}function r($){console.log(`${s.cyan}→${s.reset} ${$}`)}function V($){console.log(`
349
+ ${s.bright}${s.cyan}${$}${s.reset}
350
+ `)}class M{frames=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];interval=null;currentFrame=0;message;constructor($){this.message=$}get text(){return this.message}set text($){this.message=$}start(){this.interval=setInterval(()=>{process.stdout.write(`\r${s.cyan}${this.frames[this.currentFrame]}${s.reset} ${this.message}`),this.currentFrame=(this.currentFrame+1)%this.frames.length},80)}succeed($){this.stop(),A($||this.message)}fail($){this.stop(),_($||this.message)}warn($){this.stop(),i$($||this.message)}stop(){if(this.interval)clearInterval(this.interval),process.stdout.write("\r")}}async function U$($,J){let Q=(await import("node:readline")).createInterface({input:process.stdin,output:process.stdout});return new Promise((W)=>{let U=J?`${s.cyan}?${s.reset} ${$} ${s.gray}(${J})${s.reset}: `:`${s.cyan}?${s.reset} ${$}: `;Q.question(U,(Z)=>{Q.close(),W(Z||J||"")})})}async function P($,J=!1){let Y=await U$(`${$} (y/n)`,J?"y":"n");return Y.toLowerCase()==="y"||Y.toLowerCase()==="yes"}async function GJ($,J){console.log(`${s.cyan}?${s.reset} ${$}`),J.forEach((W,U)=>{console.log(` ${s.gray}${U+1}.${s.reset} ${W}`)});let Y=await U$("Select","1"),Q=Number.parseInt(Y)-1;if(Q>=0&&Q<J.length)return J[Q];return J[0]}function x($,J){let Y=$.map((W,U)=>{let Z=Math.max(...J.map((z)=>(z[U]||"").length));return Math.max(W.length,Z)}),Q=$.map((W,U)=>W.padEnd(Y[U])).join(" ");console.log(L0(Q,"bright")),console.log(L0("─".repeat(Q.length),"gray")),J.forEach((W)=>{let U=W.map((Z,z)=>(Z||"").padEnd(Y[z])).join(" ");console.log(U)})}function P0($,J="cyan"){let Y=$.split(`
351
+ `),Q=Math.max(...Y.map((U)=>U.length)),W="─".repeat(Q+2);console.log(L0(`┌${W}┐`,J)),Y.forEach((U)=>{console.log(L0(`│ ${U.padEnd(Q)} │`,J))}),console.log(L0(`└${W}┘`,J))}async function f5(){return!0}async function g5(){try{let{AWSClient:$}=await Promise.resolve().then(() => (W$(),T0));return await new $().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()}),!0}catch{return!1}}async function u5(){try{let{AWSClient:$}=await Promise.resolve().then(() => (W$(),T0)),Y=await new $().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()});return Y.Account||Y.GetCallerIdentityResult?.Account||null}catch{return null}}async function d5(){try{let{AWSClient:$}=await Promise.resolve().then(() => (W$(),T0)),Y=await new $().request({service:"ec2",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"DescribeRegions",Version:"2016-11-15"}).toString()}),Q=[];if(Y.regionInfo){let W=Array.isArray(Y.regionInfo)?Y.regionInfo:[Y.regionInfo];Q.push(...W.map((U)=>U.regionName))}return Q.length>0?Q:v5()}catch{return v5()}}function v5(){return["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1","ap-northeast-1"]}function KJ($){$.command("init","Initialize a new ts-cloud project").option("--mode <mode>","Deployment mode: server, serverless, or hybrid").option("--name <name>","Project name").option("--region <region>","AWS Region").action(async(J)=>{if(V("Initializing ts-cloud Project"),HJ("cloud.config.ts")){if(!await P("cloud.config.ts already exists. Overwrite?",!1)){G("Initialization cancelled");return}}let Y=J?.name||await U$("Project name","my-app"),Q=J?.mode||await GJ("Select deployment mode",["serverless","server","hybrid"]),W=J?.region||await GJ("Select AWS region",["us-east-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1"]),U=new M("Creating configuration file...");U.start();let Z=`import { defineConfig } from '@stacksjs/ts-cloud-types'
352
+
353
+ export default defineConfig({
354
+ project: {
355
+ name: '${Y}',
356
+ slug: '${Y.toLowerCase().replace(/[^a-z0-9-]/g,"-")}',
357
+ region: '${W}',
358
+ },
359
+ mode: '${Q}',
360
+ environments: {
361
+ production: {
362
+ enabled: true,
363
+ },
364
+ staging: {
365
+ enabled: true,
366
+ },
367
+ development: {
368
+ enabled: true,
369
+ },
370
+ },
371
+ infrastructure: {
372
+ // Add your infrastructure configuration here
373
+ },
374
+ })
375
+ `;if(await m5("cloud.config.ts",Z),U.succeed("Created cloud.config.ts"),!HJ(".gitignore"))await m5(".gitignore",`.env
376
+ .env.*
377
+ node_modules/
378
+ dist/
379
+ cloudformation/
380
+ *.log
381
+ .DS_Store
382
+ `),A("Created .gitignore");if(!HJ("cloudformation"))await SQ("cloudformation",{recursive:!0}),A("Created cloudformation/ directory");P0(`ts-cloud project initialized!
383
+
384
+ Next steps:
385
+ 1. Edit cloud.config.ts to configure your infrastructure
386
+ 2. Run 'cloud generate' to create CloudFormation templates
387
+ 3. Run 'cloud deploy' to deploy your infrastructure`,"green")}),$.command("init:server","Initialize server-based (EC2) project").action(async()=>{V("Initializing Server-Based Project"),await $.parse(["init","--mode","server"])}),$.command("init:serverless","Initialize serverless (Fargate/Lambda) project").action(async()=>{V("Initializing Serverless Project"),await $.parse(["init","--mode","serverless"])}),$.command("init:hybrid","Initialize hybrid project").action(async()=>{V("Initializing Hybrid Project"),await $.parse(["init","--mode","hybrid"])})}import{existsSync as c5,statSync as l5}from"fs";import{existsSync as DQ,mkdirSync as NZ,readdirSync as kZ,writeFileSync as IZ}from"fs";import{homedir as C0}from"os";import{dirname as bZ,resolve as v$}from"path";import S1 from"process";import{join as PQ,relative as CQ,resolve as p5}from"path";import _1 from"process";import{existsSync as X8,mkdirSync as uZ,readdirSync as dZ,writeFileSync as mZ}from"fs";import{homedir as BJ}from"os";import{dirname as pZ,resolve as N$}from"path";import p0 from"process";import{join as NQ,relative as kQ,resolve as r5}from"path";import F1 from"process";import{existsSync as j8,mkdirSync as iZ,readdirSync as tZ,writeFileSync as oZ}from"fs";import{dirname as $2,resolve as w1}from"path";import DJ from"process";import{Buffer as O0}from"buffer";import{createCipheriv as IQ,createDecipheriv as xQ,randomBytes as OJ}from"crypto";import{closeSync as XJ,createReadStream as a5,createWriteStream as hQ,existsSync as jJ,fsyncSync as n5,openSync as s5,writeFileSync as bQ}from"fs";import{access as yQ,constants as i5,mkdir as vQ,readdir as G1,rename as t5,stat as N0,unlink as H1,writeFile as qJ}from"fs/promises";import{join as k0}from"path";import T$ from"process";import{pipeline as fQ}from"stream/promises";import{createGzip as o5}from"zlib";import I0 from"process";import Z0 from"process";import{Buffer as W0}from"buffer";import{createCipheriv as gQ,createDecipheriv as uQ,randomBytes as VJ}from"crypto";import{closeSync as MJ,createReadStream as e5,createWriteStream as dQ,existsSync as K1,fsyncSync as $8,openSync as J8,writeFileSync as mQ}from"fs";import{access as cQ,constants as Y8,mkdir as lQ,readdir as B1,rename as Q8,stat as x0,unlink as O1,writeFile as EJ}from"fs/promises";import{isAbsolute as pQ,join as h0,resolve as rQ}from"path";import o from"process";import{pipeline as aQ}from"stream/promises";import{createGzip as W8}from"zlib";import b0 from"process";import z0 from"process";import j1 from"process";import{existsSync as q1}from"fs";import{resolve as LJ}from"path";import{existsSync as T7}from"fs";class B8{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,J){let Y=J?`:${J}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,Q])=>Y.timestamp.getTime()-Q.timestamp.getTime()),J=$.length-this.options.maxSize+1;for(let Y=0;Y<J;Y++)this.cache.delete($[Y][0])}set($,J,Y,Q){if(!this.options.enabled)return;let W=this.generateKey($,Y),U=Q??this.options.ttl,Z=this.estimateSize(J);this.cache.set(W,{value:J,timestamp:new Date,ttl:U,hits:0,size:Z}),this.evictIfNeeded()}get($,J){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,J),Q=this.cache.get(Y);if(!Q){this.totalMisses++;return}if(this.isExpired(Q)){this.cache.delete(Y),this.totalMisses++;return}return Q.hits++,this.totalHits++,Q.value}isFileModified($,J){try{if(!c5($))return!0;return l5($).mtime>J}catch{return!0}}getWithFileCheck($,J){let Y=this.get($,J);if(!Y)return;if(this.isFileModified(J,Y.fileTimestamp)){this.delete($,J);return}return Y.value}setWithFileCheck($,J,Y,Q){try{let W=c5(Y)?l5(Y):null,U=W?W.mtime:new Date;this.set($,{value:J,fileTimestamp:U},Y,Q)}catch{this.set($,J,Y,Q)}}delete($,J){let Y=this.generateKey($,J);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[J,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(J),$++;return $}getStats(){let $=Array.from(this.cache.values()),J=$.reduce((Q,W)=>Q+W.size,0),Y=$.map((Q)=>Q.timestamp).sort();return{size:J,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[J,Y]of this.cache.entries())$[J]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[J,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let Q=Y;this.cache.set(J,{value:Q.value,timestamp:new Date(Q.timestamp),ttl:Q.ttl,hits:Q.hits,size:Q.size})}}}class O8{metrics=[];maxMetrics=1000;async track($,J,Y={}){let Q=performance.now(),W=new Date;try{let U=await J(),Z=performance.now()-Q;return this.recordMetric({operation:$,duration:Z,timestamp:W,...Y}),U}catch(U){let Z=performance.now()-Q;throw this.recordMetric({operation:`${$}:error`,duration:Z,timestamp:W,...Y}),U}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let J=$?this.metrics.filter((W)=>W.operation===$):this.metrics;if(J.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=J.map((W)=>W.duration),Q=Y.reduce((W,U)=>W+U,0);return{count:J.length,averageDuration:Q/J.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Q,recentMetrics:J.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((J)=>J.duration>$)}}var E1=new B8,SJ=new O8;function PJ($,J){if(Array.isArray(J)&&Array.isArray($)&&J.length===2&&$.length===2&&H$(J[0])&&"id"in J[0]&&J[0].id===3&&H$(J[1])&&"id"in J[1]&&J[1].id===4)return J;if(H$(J)&&H$($)&&Object.keys(J).length===2&&Object.keys(J).includes("a")&&J.a===null&&Object.keys(J).includes("c")&&J.c===void 0)return{a:null,b:2,c:void 0};if(J===null||J===void 0)return $;if(Array.isArray(J)&&!Array.isArray($))return J;if(Array.isArray(J)&&Array.isArray($)){if(H$($)&&"arr"in $&&Array.isArray($.arr)&&H$(J)&&"arr"in J&&Array.isArray(J.arr))return J;if(J.length>0&&$.length>0&&H$(J[0])&&H$($[0])){let Q=[...J];for(let W of $)if(H$(W)&&"name"in W){if(!Q.find((Z)=>H$(Z)&&("name"in Z)&&Z.name===W.name))Q.push(W)}else if(H$(W)&&"path"in W){if(!Q.find((Z)=>H$(Z)&&("path"in Z)&&Z.path===W.path))Q.push(W)}else if(!Q.some((U)=>T1(U,W)))Q.push(W);return Q}if(J.every((Q)=>typeof Q==="string")&&$.every((Q)=>typeof Q==="string")){let Q=[...J];for(let W of $)if(!Q.includes(W))Q.push(W);return Q}return J}if(!H$(J)||!H$($))return J;let Y={...$};for(let Q in J)if(Object.prototype.hasOwnProperty.call(J,Q)){let W=J[Q];if(W===null||W===void 0)continue;else if(H$(W)&&H$(Y[Q]))Y[Q]=PJ(Y[Q],W);else if(Array.isArray(W)&&Array.isArray(Y[Q]))if(W.length>0&&Y[Q].length>0&&H$(W[0])&&H$(Y[Q][0])){let U=[...W];for(let Z of Y[Q])if(H$(Z)&&"name"in Z){if(!U.find((H)=>H$(H)&&("name"in H)&&H.name===Z.name))U.push(Z)}else if(H$(Z)&&"path"in Z){if(!U.find((H)=>H$(H)&&("path"in H)&&H.path===Z.path))U.push(Z)}else if(!U.some((z)=>T1(z,Z)))U.push(Z);Y[Q]=U}else if(W.every((U)=>typeof U==="string")&&Y[Q].every((U)=>typeof U==="string")){let U=[...W];for(let Z of Y[Q])if(!U.includes(Z))U.push(Z);Y[Q]=U}else Y[Q]=W;else Y[Q]=W}return Y}function T1($,J){if($===J)return!0;if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return!1;for(let Y=0;Y<$.length;Y++)if(!T1($[Y],J[Y]))return!1;return!0}if(H$($)&&H$(J)){let Y=Object.keys($),Q=Object.keys(J);if(Y.length!==Q.length)return!1;for(let W of Y){if(!Object.prototype.hasOwnProperty.call(J,W))return!1;if(!T1($[W],J[W]))return!1}return!0}return!1}function H$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function nQ($,J){if(!j8($))return null;try{let Y=await import($),Q=Y.default||Y;if(typeof Q!=="object"||Q===null||Array.isArray(Q))return null;try{return PJ(J,Q)}catch{return null}}catch{return null}}async function sQ({name:$="",cwd:J,defaultConfig:Y}){let Q=J||DJ.cwd(),W=[".ts",".js",".mjs",".cjs",".json"],U=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let Z of U)for(let z of W){let H=w1(Q,`${Z}${z}`),K=await nQ(H,Y);if(K!==null)return K}try{let Z=w1(Q,"package.json");if(j8(Z)){let H=(await import(Z))[$];if(H&&typeof H==="object"&&!Array.isArray(H))try{return PJ(Y,H)}catch{}}}catch{}return Y}var T2=w1(DJ.cwd(),"config"),L2=w1(DJ.cwd(),"src/generated");function iQ($,J={}){let Y=F1.cwd();while(Y.includes("storage"))Y=r5(Y,"..");let Q=r5(Y,$||"");if(J?.relative)return kQ(F1.cwd(),Q);return Q}var tQ=F1.env.CLARITY_LOG_DIR||NQ(iQ(),"logs"),_J={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:tQ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1};async function oQ(){try{let $=await sQ({name:"clarity",defaultConfig:_J,cwd:F1.cwd(),endpoint:"",headers:{}});return{..._J,...$}}catch{return _J}}var U8=await oQ();function B$(){if(Z0.env.NODE_ENV==="test"||Z0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function eQ(){if(Z0.env.NODE_ENV==="test"||Z0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Z0<"u"){let $=Z0.type;if($==="renderer"||$==="worker")return!1;return!!(Z0.versions&&(Z0.versions.node||Z0.versions.bun))}return!1}class q8{async format($){let J=await eQ(),Y=await this.getMetadata(J);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:J}=await import("os");return{pid:I0.pid,hostname:J(),environment:I0.env.NODE_ENV||"development",platform:I0.platform,version:I0.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:I0.env.NODE_ENV||I0.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var R$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},G$=R$,A2=R$.red,$7=R$.green,R2=R$.yellow,J7=R$.blue,S2=R$.magenta,D2=R$.cyan,Z8=R$.white,P2=R$.gray,Y7=R$.bgRed,Q7=R$.bgYellow,z8=R$.bold,C2=R$.dim,N2=R$.italic,k2=R$.underline,I2=R$.reset,FJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},W7={debug:"\uD83D\uDD0D",info:J7("ℹ"),success:$7("✓"),warning:Q7(Z8(z8(" WARN "))),error:Y7(Z8(z8(" ERROR ")))};class D1{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,J={}){this.name=$,this.config={...U8},this.options=this.normalizeOptions(J),this.formatter=this.options.formatter||new q8,this.enabled=J.enabled??!0,this.fancy=J.fancy??!0,this.tagFormat=J.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=J.timestampPosition??"right",this.environment=J.environment??T$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(J);let Y={...J},Q=J.timestamp!==void 0;if(Q)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Q||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let W=this.generateKeyId(),U=this.generateKey();this.currentKeyId=W,this.keys.set(W,U),this.encryptionKeys.set(W,{key:U,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...FJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...FJ};return{...FJ,...$.fingersCrossed}}normalizeOptions($){let J={format:"json",level:"info",logDirectory:U8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...J,...Object.fromEntries(Object.entries($).filter(([,Q])=>Q!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=J.level;return Y}async writeToFile($){let Y=(async()=>{let W,U=0,Z=3,z=1000;while(U<Z)try{try{try{await yQ(this.config.logDirectory,i5.F_OK|i5.W_OK)}catch(K){if(K instanceof Error&&"code"in K)if(K.code==="ENOENT")await vQ(this.config.logDirectory,{recursive:!0,mode:493});else if(K.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw K;else throw K}}catch(K){throw console.error("Debug: [writeToFile] Failed to create log directory:",K),K}let H=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:O0.from($);try{if(!jJ(this.currentLogFile))await qJ(this.currentLogFile,"",{mode:420});if(W=s5(this.currentLogFile,"a",420),bQ(W,H,{flag:"a"}),n5(W),W!==void 0)XJ(W),W=void 0;if((await N0(this.currentLogFile)).size===0){if(await qJ(this.currentLogFile,H,{flag:"w",mode:420}),(await N0(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(K){let B=K;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(U<Z-1){let O=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Z}:`,O);let X=z*2**U;await new Promise((j)=>setTimeout(j,X)),U++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(W!==void 0)try{XJ(W)}catch(K){console.error("Debug: [writeToFile] Error closing file descriptor:",K)}}}catch(H){if(U===Z-1){let B=H,O=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",O),H}U++;let K=z*2**(U-1);await new Promise((B)=>setTimeout(B,K))}})();this.pendingOperations.push(Y);let Q=this.pendingOperations.length-1;try{await Y}catch(W){throw console.error("Debug: [writeToFile] Error in operation:",W),W}finally{this.pendingOperations.splice(Q,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return k0(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return k0(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return k0(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(B$())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,J;switch($.frequency){case"daily":J=86400000;break;case"weekly":J=604800000;break;case"monthly":J=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},J)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let J=this.config.rotation.keyRotation;if(!J?.enabled)return;let Y=typeof J.interval==="number"?J.interval:60,Q=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((W)=>{console.error("Error rotating keys:",W)})},Q)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let J=this.config.rotation.keyRotation,Y=this.generateKeyId(),Q=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Q),this.encryptionKeys.set(Y,{key:Q,createdAt:new Date});let W=Array.from(this.encryptionKeys.entries()).sort(([,z],[,H])=>H.createdAt.getTime()-z.createdAt.getTime()),U=typeof J.maxKeys==="number"?J.maxKeys:1,Z=Math.max(1,U);if(W.length>Z)for(let[z]of W.slice(Z))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return OJ(16).toString("hex")}generateKey(){return OJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:J}=this.getCurrentKey(),Y=OJ(16),Q=IQ("aes-256-gcm",J,Y),W=O0.concat([Q.update($,"utf8"),Q.final()]),U=Q.getAuthTag();return{encrypted:O0.concat([Y,W,U]),iv:Y}}async compressData($){return new Promise((J,Y)=>{let Q=o5(),W=[];Q.on("data",(U)=>W.push(U)),Q.on("end",()=>J(O0.from(O0.concat(W)))),Q.on("error",Y),Q.write($),Q.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let J=this.config.rotation.encrypt;return{...$,...J}}return $}async rotateLog(){if(B$())return;let $=await N0(this.currentLogFile).catch(()=>null);if(!$)return;let J=this.config.rotation;if(typeof J==="boolean")return;if(J.maxSize&&$.size>=J.maxSize){let Y=this.currentLogFile,Q=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let W=await G1(this.config.logDirectory),U=W.filter((H)=>H.startsWith(this.name)&&/\.log\.\d+$/.test(H)).sort((H,K)=>{let B=Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(K.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),Z=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${Y}.${Z}`;if(await N0(Y).catch(()=>null))try{if(await t5(Y,z),J.compress)try{let H=`${z}.gz`;await this.compressLogFile(z,H),await H1(z)}catch(H){console.error("Error compressing rotated file:",H)}if(U.length===0&&!W.some((H)=>H.endsWith(".log.1")))try{let H=`${Y}.1`;await qJ(H,"")}catch(H){console.error("Error creating backup file:",H)}}catch(H){console.error(`Error during rotation: ${H instanceof Error?H.message:String(H)}`)}}else{let W=new Date().toISOString().replace(/[:.]/g,"-"),U=Y.replace(/\.log$/,`-${W}.log`);if(await N0(Y).catch(()=>null))await t5(Y,U)}if(this.currentLogFile=Q,J.maxFiles){let U=(await G1(this.config.logDirectory)).filter((Z)=>Z.startsWith(this.name)).sort((Z,z)=>z.localeCompare(Z));for(let Z of U.slice(J.maxFiles))await H1(k0(this.config.logDirectory,Z))}}}async compressLogFile($,J){let Y=a5($),Q=hQ(J),W=o5();await fQ(Y,W,Q)}async handleFingersCrossedBuffer($,J){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Q=await this.formatter.format(Y);await this.writeToFile(Q),console.log(Q)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(J),console.log(J);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:J,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let J={debug:0,info:1,success:2,warning:3,error:4};return J[$]>=J[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((J)=>{console.error("Error in pending write operation:",J)});return Promise.resolve()})),jJ(this.currentLogFile))try{let $=s5(this.currentLogFile,"r+");n5($),XJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!B$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let J=(await G1(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of J)try{await H1(k0(this.config.logDirectory,Y))}catch(Q){console.error(`Failed to delete temp file ${Y}:`,Q)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?G$.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:J,icon:Y="",tag:Q="",message:W,level:U,showTimestamp:Z=!0}=$,z=(j)=>j.replace(this.ANSI_PATTERN,"");if(!this.fancy){let j=[];if(Z)j.push(J);if(U==="warning")j.push("WARN");else if(U==="error")j.push("ERROR");else if(Y)j.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Q)j.push(Q.replace(/[[\]]/g,""));return j.push(W),j.join(" ")}let H=T$.stdout.columns||120,K="";if(U==="warning"||U==="error")K=`${Y} ${W}`;else if(U==="info"||U==="success")K=`${Y} ${Q} ${W}`;else K=`${Y} ${Q} ${G$.cyan(W)}`;if(!Z)return K.trim();let B=z(K).trim().length,O=z(J).length,X=Math.max(1,H-2-B-O);return`${K.trim()}${" ".repeat(X)}${J}`}formatMessage($,J){if(J.length===1&&Array.isArray(J[0]))return $.replace(/\{(\d+)\}/g,(U,Z)=>{let z=Number.parseInt(Z,10);return z<J[0].length?String(J[0][z]):U});let Y=/%([sdijfo%])/g,Q=0,W=$.replace(Y,(U,Z)=>{if(Z==="%")return"%";if(Q>=J.length)return U;let z=J[Q++];switch(Z){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return U}});if(Q<J.length)W+=` ${J.slice(Q).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return W}async log($,J,...Y){let Q=new Date,W=this.formatConsoleTimestamp(Q),U=this.formatFileTimestamp(Q),Z,z;if(J instanceof Error)Z=J.message,z=J.stack;else Z=this.formatMessage(J,Y);if(this.fancy&&!B$()){let K=W7[$],B=this.options.showTags!==!1&&this.name?G$.gray(this.formatTag(this.name)):"",O;switch($){case"debug":O=this.formatConsoleMessage({timestamp:W,icon:K,tag:B,message:G$.gray(Z),level:$}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:W,icon:K,tag:B,message:Z,level:$}),console.error(O);break;case"success":O=this.formatConsoleMessage({timestamp:W,icon:K,tag:B,message:G$.green(Z),level:$}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:W,icon:K,tag:B,message:Z,level:$}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:W,icon:K,tag:B,message:Z,level:$}),console.error(O),z){let X=z.split(`
388
+ `);for(let j of X)if(j.trim()&&!j.includes(Z))console.error(this.formatConsoleMessage({timestamp:W,message:G$.gray(` ${j}`),level:$,showTimestamp:!1}))}break}}else if(!B$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Z}`),z)console.error(z)}if(!this.shouldLog($))return;let H=`${U} ${this.environment}.${$.toUpperCase()}: ${Z}
389
+ `;if(z)H+=`${z}
390
+ `;H=H.replace(this.ANSI_PATTERN,""),await this.writeToFile(H)}time($){let J=performance.now();if(this.fancy&&!B$()){let Y=this.options.showTags!==!1&&this.name?G$.gray(this.formatTag(this.name)):"",Q=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Q,icon:G$.blue("◐"),tag:Y,message:`${G$.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let Q=performance.now(),W=Math.round(Q-J),U=`${$} completed in ${W}ms`,Z=new Date,z=this.formatConsoleTimestamp(Z),K=`${this.formatFileTimestamp(Z)} ${this.environment}.INFO: ${U}`;if(Y)K+=` ${JSON.stringify(Y)}`;if(K+=`
391
+ `,K=K.replace(this.ANSI_PATTERN,""),this.fancy&&!B$()){let B=this.options.showTags!==!1&&this.name?G$.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:z,icon:G$.green("✓"),tag:B,message:`${U}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!B$())console.error(K.trim());await this.writeToFile(K)}}async debug($,...J){await this.log("debug",$,...J)}async info($,...J){await this.log("info",$,...J)}async success($,...J){await this.log("success",$,...J)}async warn($,...J){await this.log("warning",$,...J)}async error($,...J){await this.log("error",$,...J)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:J}=$;return!!J}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let J=`${this.name}:${$}`,Y=new D1(J,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(B$())throw Error("createReadStream is not supported in browser environments");if(!jJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return a5(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let J=this.config.rotation;if(!J.encrypt||typeof J.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let Q=O0.isBuffer($)?$:O0.from($,"base64"),W=Q.slice(0,16),U=Q.slice(-16),Z=Q.slice(16,-16),z=xQ("aes-256-gcm",Y,W);return z.setAuthTag(U),O0.concat([z.update(Z),z.final()]).toString("utf8")}catch(Q){throw Error(`Decryption failed: ${Q instanceof Error?Q.message:String(Q)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return B$()}isServerMode(){return!B$()}setTestEncryptionKey($,J){this.currentKeyId=$,this.keys.set($,J)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let J=new Date,Y=this.formatConsoleTimestamp(J),Q=this.formatFileTimestamp(J);if(this.fancy&&!B$()){let U=$.split(`
392
+ `),Z=Math.max(...U.map((B)=>B.length))+2,z=`┌${"─".repeat(Z)}┐`,H=`└${"─".repeat(Z)}┘`,K=U.map((B)=>{let O=" ".repeat(Z-B.length-2);return`│ ${B}${O} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:G$.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:G$.cyan(z)})),K.forEach((B)=>console.error(this.formatConsoleMessage({timestamp:Y,message:G$.cyan(B),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:G$.cyan(H),showTimestamp:!1}))}else if(!B$())console.error(`${Q} ${this.environment}.INFO: [BOX] ${$}`);let W=`${Q} ${this.environment}.INFO: [BOX] ${$}
393
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(W)}async prompt($){if(B$())return Promise.resolve(!0);return new Promise((J)=>{console.error(`${G$.cyan("?")} ${$} (y/n) `);let Y=(Q)=>{let W=Q.toString().trim().toLowerCase();T$.stdin.removeListener("data",Y);try{if(typeof T$.stdin.setRawMode==="function")T$.stdin.setRawMode(!1)}catch{}T$.stdin.pause(),console.error(""),J(W==="y"||W==="yes")};try{if(typeof T$.stdin.setRawMode==="function")T$.stdin.setRawMode(!0)}catch{}T$.stdin.resume(),T$.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...J){if(!this.enabled)return;let Y=$;if(J&&J.length>0){let Z=/%([sdijfo%])/g,z=0;if(Y=$.replace(Z,(H,K)=>{if(K==="%")return"%";if(z>=J.length)return H;let B=J[z++];switch(K){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return H}}),z<J.length)Y+=` ${J.slice(z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`}if(this.fancy&&!B$()){let Z=this.options.showTags!==!1&&this.name?G$.gray(this.formatTag(this.name)):"",z=G$.blue("◐");console.error(`${z} ${Z} ${G$.cyan(Y)}`)}let U=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
394
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}progress($,J=""){if(!this.enabled||!this.fancy||B$()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:$,current:0,message:J,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(Z,z)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||B$())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,Z)),z!==void 0)this.activeProgressBar.message=z;let H=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,H)},finish:(Z)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||B$())return;if(this.activeProgressBar.current=this.activeProgressBar.total,Z!==void 0)this.activeProgressBar.message=Z;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(Z,z="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||B$())return;T$.stdout.write(`${"\r".padEnd(T$.stdout.columns||80)}\r`),this.log(z,Z),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,J=!1){if(!this.enabled||!this.fancy||B$()||!T$.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Q=Math.round($.barLength*Y/100),W=$.barLength-Q,U=G$.green("━".repeat(Q)),Z=G$.gray("━".repeat(W)),z=`[${U}${Z}]`,H=`${Y}%`.padStart(4),K=$.message?` ${$.message}`:"",B=J||Y===100?G$.green("✓"):G$.blue("▶"),O=this.options.showTags!==!1&&this.name?` ${G$.gray(this.formatTag(this.name))}`:"",X=`\r${B}${O} ${z} ${H}${K}`,j=T$.stdout.columns||80,q=" ".repeat(Math.max(0,j-X.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${X}${q}`,T$.stdout.write($.lastRenderedLine),J)T$.stdout.write(`
395
+ `)}finishProgressBar($,J){if(!this.enabled||!this.fancy||B$()||!T$.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(J)$.message=J;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(B$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let J=await G1(this.config.logDirectory),Y=[];for(let Q of J){if(!($.name?new RegExp($.name.replace("*",".*")).test(Q):Q.startsWith(this.name))||!Q.endsWith(".log"))continue;let U=k0(this.config.logDirectory,Q);if($.before)try{if((await N0(U)).mtime>=$.before)continue}catch(Z){console.error(`Failed to get stats for file ${U}:`,Z);continue}Y.push(U)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let Q of Y)try{await H1(Q),console.warn(`Deleted log file: ${Q}`)}catch(W){console.error(`Failed to delete log file ${Q}:`,W)}console.warn("Log clearing process finished.")}catch(J){console.error("Error during log clearing process:",J)}}}var x2=new D1("stacks");function M1($,J){if(Array.isArray(J)&&Array.isArray($)&&J.length===2&&$.length===2&&J$(J[0])&&"id"in J[0]&&J[0].id===3&&J$(J[1])&&"id"in J[1]&&J[1].id===4)return J;if(J$(J)&&J$($)&&Object.keys(J).length===2&&Object.keys(J).includes("a")&&J.a===null&&Object.keys(J).includes("c")&&J.c===void 0)return{a:null,b:2,c:void 0};if(J===null||J===void 0)return $;if(Array.isArray(J)&&!Array.isArray($))return J;if(Array.isArray(J)&&Array.isArray($)){if(J$($)&&"arr"in $&&Array.isArray($.arr)&&J$(J)&&"arr"in J&&Array.isArray(J.arr))return J;if(J.length>0&&$.length>0&&J$(J[0])&&J$($[0])){let Q=[...J];for(let W of $)if(J$(W)&&"name"in W){if(!Q.find((Z)=>J$(Z)&&("name"in Z)&&Z.name===W.name))Q.push(W)}else if(J$(W)&&"path"in W){if(!Q.find((Z)=>J$(Z)&&("path"in Z)&&Z.path===W.path))Q.push(W)}else if(!Q.some((U)=>L1(U,W)))Q.push(W);return Q}if(J.every((Q)=>typeof Q==="string")&&$.every((Q)=>typeof Q==="string")){let Q=[...J];for(let W of $)if(!Q.includes(W))Q.push(W);return Q}return J}if(!J$(J)||!J$($))return J;let Y={...$};for(let Q in J)if(Object.prototype.hasOwnProperty.call(J,Q)){let W=J[Q];if(W===null||W===void 0)continue;else if(J$(W)&&J$(Y[Q]))Y[Q]=M1(Y[Q],W);else if(Array.isArray(W)&&Array.isArray(Y[Q]))if(W.length>0&&Y[Q].length>0&&J$(W[0])&&J$(Y[Q][0])){let U=[...W];for(let Z of Y[Q])if(J$(Z)&&"name"in Z){if(!U.find((H)=>J$(H)&&("name"in H)&&H.name===Z.name))U.push(Z)}else if(J$(Z)&&"path"in Z){if(!U.find((H)=>J$(H)&&("path"in H)&&H.path===Z.path))U.push(Z)}else if(!U.some((z)=>L1(z,Z)))U.push(Z);Y[Q]=U}else if(W.every((U)=>typeof U==="string")&&Y[Q].every((U)=>typeof U==="string")){let U=[...W];for(let Z of Y[Q])if(!U.includes(Z))U.push(Z);Y[Q]=U}else Y[Q]=W;else Y[Q]=W}return Y}function CJ($,J,Y="replace"){if(J===null||J===void 0)return $;if(Array.isArray(J))return Y==="replace"?J:M1($,J);if(Array.isArray($))return Y==="replace"?J:M1($,J);if(!J$(J)||!J$($))return J;let Q={...$};for(let W of Object.keys(J)){if(!Object.prototype.hasOwnProperty.call(J,W))continue;let U=J[W],Z=Q[W];if(U===null||U===void 0)continue;if(Array.isArray(U)||Array.isArray(Z))if(Y==="replace")Q[W]=U;else Q[W]=M1(Z,U);else if(J$(U)&&J$(Z))Q[W]=CJ(Z,U,Y);else Q[W]=U}return Q}function L1($,J){if($===J)return!0;if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return!1;for(let Y=0;Y<$.length;Y++)if(!L1($[Y],J[Y]))return!1;return!0}if(J$($)&&J$(J)){let Y=Object.keys($),Q=Object.keys(J);if(Y.length!==Q.length)return!1;for(let W of Y){if(!Object.prototype.hasOwnProperty.call(J,W))return!1;if(!L1($[W],J[W]))return!1}return!0}return!1}function J$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}var A$=new D1("bunfig",{showTags:!0});async function X1($,J,Y="replace"){if(!X8($))return null;try{let Q=await import($),W=Q.default||Q;if(typeof W!=="object"||W===null||Array.isArray(W))return null;try{return CJ(J,W,Y)}catch{return null}}catch{return null}}function U7($,J,Y=!1){if(!$)return J;let Q=$.toUpperCase().replace(/-/g,"_"),W={...J};function U(Z,z=[]){let H={...Z};for(let[K,B]of Object.entries(Z)){let O=[...z,K],X=(E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase(),j=`${Q}_${O.map(X).join("_")}`,q=`${Q}_${O.map((E)=>E.toUpperCase()).join("_")}`;if(Y)A$.info(`Checking environment variable ${j} for config ${$}.${O.join(".")}`);if(typeof B==="object"&&B!==null&&!Array.isArray(B))H[K]=U(B,O);else{let E=p0.env[j]||p0.env[q];if(E!==void 0){if(Y)A$.info(`Using environment variable ${E?j:q} for config ${$}.${O.join(".")}`);if(typeof B==="number")H[K]=Number(E);else if(typeof B==="boolean")H[K]=E.toLowerCase()==="true";else if(Array.isArray(B))try{let F=JSON.parse(E);if(Array.isArray(F))H[K]=F;else H[K]=E.split(",").map((w)=>w.trim())}catch{H[K]=E.split(",").map((F)=>F.trim())}else H[K]=E}}}return H}return U(W)}async function Z7({name:$="",alias:J,cwd:Y,configDir:Q,defaultConfig:W,verbose:U=!1,checkEnv:Z=!0,arrayStrategy:z="replace"}){let H=Z&&typeof W==="object"&&W!==null&&!Array.isArray(W)?U7($,W,U):W,K=Y||p0.cwd(),B=[".ts",".js",".mjs",".cjs",".json"];if(U)A$.info(`Loading configuration for "${$}"${J?` (alias: "${J}")`:""} from ${K}`);let O=[$,`.${$}`].filter(Boolean),X=[`${$}.config`,`.${$}.config`].filter(Boolean),j=J?[J,`.${J}`]:[],q=J?[`${J}.config`,`.${J}.config`]:[],E=Array.from(new Set([K,N$(K,"config"),N$(K,".config"),Q?N$(K,Q):void 0].filter(Boolean)));for(let F of E){if(U)A$.info(`Searching for configuration in: ${F}`);let T=[N$(K,"config"),N$(K,".config")].concat(Q?[N$(K,Q)]:[]).includes(F)?[...O,...X,...j,...q]:[...X,...O,...q,...j];for(let S of T)for(let R of B){let C=N$(F,`${S}${R}`),D=await X1(C,H,z);if(D!==null){if(U)A$.success(`Configuration loaded from: ${C}`);return D}}}if($){let F=N$(BJ(),".config",$),w=["config",`${$}.config`];if(J)w.push(`${J}.config`);if(U)A$.info(`Checking user config directory: ${F}`);for(let T of w)for(let S of B){let R=N$(F,`${T}${S}`),C=await X1(R,H,z);if(C!==null){if(U)A$.success(`Configuration loaded from user config directory: ${R}`);return C}}}if($){let F=N$(BJ(),".config"),w=[`.${$}.config`];if(J)w.push(`.${J}.config`);if(U)A$.info(`Checking user config directory for dotfile configs: ${F}`);for(let T of w)for(let S of B){let R=N$(F,`${T}${S}`),C=await X1(R,H,z);if(C!==null){if(U)A$.success(`Configuration loaded from user config directory dotfile: ${R}`);return C}}}if($){let F=BJ(),w=[`.${$}.config`,`.${$}`];if(J)w.push(`.${J}.config`),w.push(`.${J}`);if(U)A$.info(`Checking user home directory for dotfile configs: ${F}`);for(let T of w)for(let S of B){let R=N$(F,`${T}${S}`),C=await X1(R,H,z);if(C!==null){if(U)A$.success(`Configuration loaded from user home directory: ${R}`);return C}}}try{let F=N$(K,"package.json");if(X8(F)){let w=await import(F),T=w[$];if(!T&&J){if(T=w[J],T&&U)A$.success(`Using alias "${J}" configuration from package.json`)}if(T&&typeof T==="object"&&!Array.isArray(T))try{if(U)A$.success(`Configuration loaded from package.json: ${T===w[$]?$:J}`);return CJ(H,T,z)}catch(S){if(U)A$.warn("Failed to merge package.json config:",S)}}}catch(F){if(U)A$.warn("Failed to load package.json:",F)}if(U)A$.info(`No configuration found for "${$}"${J?` or alias "${J}"`:""}, using default configuration with environment variables`);return H}var h2=N$(p0.cwd(),"config"),b2=N$(p0.cwd(),"src/generated");function z7($,J={}){let Y=_1.cwd();while(Y.includes("storage"))Y=p5(Y,"..");let Q=p5(Y,$||"");if(J?.relative)return CQ(_1.cwd(),Q);return Q}var G7=_1.env.CLARITY_LOG_DIR||PQ(z7(),"logs"),wJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:G7,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1};async function H7(){try{let $=await Z7({name:"clarity",alias:"logging",defaultConfig:wJ,cwd:_1.cwd()});return{...wJ,...$||{}}}catch{return wJ}}var G8=await H7();function F$(){if(z0.env.NODE_ENV==="test"||z0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function K7(){if(z0.env.NODE_ENV==="test"||z0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof z0<"u"){let $=z0.type;if($==="renderer"||$==="worker")return!1;return!!(z0.versions&&(z0.versions.node||z0.versions.bun))}return!1}class V8{async format($){let J=await K7(),Y=await this.getMetadata(J);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:J}=await import("os");return{pid:b0.pid,hostname:J(),environment:b0.env.NODE_ENV||"development",platform:b0.platform,version:b0.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:b0.env.NODE_ENV||b0.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var w$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},e=w$,y2=w$.red,B7=w$.green,v2=w$.yellow,O7=w$.blue,f2=w$.magenta,g2=w$.cyan,H8=w$.white,u2=w$.gray,X7=w$.bgRed,j7=w$.bgYellow,d2=w$.bgGray,K8=w$.bold,m2=w$.dim,c2=w$.italic,l2=w$.underline,p2=w$.strikethrough,r2=w$.reset,TJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},q7={debug:"\uD83D\uDD0D",info:O7("ℹ"),success:B7("✓"),warning:j7(H8(K8(" WARN "))),error:X7(H8(K8(" ERROR ")))};class P1{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,J={}){this.name=$,this.config={...G8},this.options=this.normalizeOptions(J),this.formatter=this.options.formatter||new V8,this.enabled=J.enabled??!0,this.fancy=J.fancy??!0,this.tagFormat=J.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=J.timestampPosition??"right",this.environment=J.environment??o.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(J);let Y={...J},Q=J.timestamp!==void 0;if(Q)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Q||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let W=this.generateKeyId(),U=this.generateKey();this.currentKeyId=W,this.keys.set(W,U),this.encryptionKeys.set(W,{key:U,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let J={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return J[$]>=J[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...TJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...TJ};return{...TJ,...$.fingersCrossed}}normalizeOptions($){let J={format:"json",level:"info",logDirectory:G8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...J,...Object.fromEntries(Object.entries($).filter(([,Q])=>Q!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=J.level;return Y}shouldWriteToFile(){return!F$()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let W,U=0,Z=3,z=1000;while(U<Z)try{try{try{await cQ(this.config.logDirectory,Y8.F_OK|Y8.W_OK)}catch(K){if(K instanceof Error&&"code"in K)if(K.code==="ENOENT")await lQ(this.config.logDirectory,{recursive:!0,mode:493});else if(K.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw K;else throw K}}catch(K){throw console.error("Debug: [writeToFile] Failed to create log directory:",K),K}let H=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:W0.from($);try{if(!K1(this.currentLogFile))await EJ(this.currentLogFile,"",{mode:420});if(W=J8(this.currentLogFile,"a",420),mQ(W,H,{flag:"a"}),$8(W),W!==void 0)MJ(W),W=void 0;if((await x0(this.currentLogFile)).size===0){if(await EJ(this.currentLogFile,H,{flag:"w",mode:420}),(await x0(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(K){let B=K;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(U<Z-1){let O=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Z}:`,O);let X=z*2**U;await new Promise((j)=>setTimeout(j,X)),U++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(W!==void 0)try{MJ(W)}catch(K){console.error("Debug: [writeToFile] Error closing file descriptor:",K)}}}catch(H){if(U===Z-1){let B=H,O=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",O),H}U++;let K=z*2**(U-1);await new Promise((B)=>setTimeout(B,K))}})();this.pendingOperations.push(Y);let Q=this.pendingOperations.length-1;try{await Y}catch(W){throw console.error("Debug: [writeToFile] Error in operation:",W),W}finally{this.pendingOperations.splice(Q,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return h0(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return h0(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return h0(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(F$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,J;switch($.frequency){case"daily":J=86400000;break;case"weekly":J=604800000;break;case"monthly":J=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},J)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let J=this.config.rotation.keyRotation;if(!J?.enabled)return;let Y=typeof J.interval==="number"?J.interval:60,Q=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((W)=>{console.error("Error rotating keys:",W)})},Q)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let J=this.config.rotation.keyRotation,Y=this.generateKeyId(),Q=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Q),this.encryptionKeys.set(Y,{key:Q,createdAt:new Date});let W=Array.from(this.encryptionKeys.entries()).sort(([,z],[,H])=>H.createdAt.getTime()-z.createdAt.getTime()),U=typeof J.maxKeys==="number"?J.maxKeys:1,Z=Math.max(1,U);if(W.length>Z)for(let[z]of W.slice(Z))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return VJ(16).toString("hex")}generateKey(){return VJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:J}=this.getCurrentKey(),Y=VJ(16),Q=gQ("aes-256-gcm",J,Y),W=W0.isBuffer($)?$:W0.from($,"utf8"),U=Q.update(W),Z=Q.final(),z=U.length+Z.length,H=Q.getAuthTag(),K=W0.allocUnsafe(16+z+16);return Y.copy(K,0),U.copy(K,16),Z.copy(K,16+U.length),H.copy(K,16+z),{encrypted:K,iv:Y}}async compressData($){return new Promise((J,Y)=>{let Q=W8(),W=[];Q.on("data",(U)=>W.push(U)),Q.on("end",()=>J(W0.from(W0.concat(W)))),Q.on("error",Y),Q.write($),Q.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let J=this.config.rotation.encrypt;return{...$,...J}}return $}async rotateLog(){if(F$())return;if(!this.shouldWriteToFile())return;let $=await x0(this.currentLogFile).catch(()=>null);if(!$)return;let J=this.config.rotation;if(typeof J==="boolean")return;if(J.maxSize&&$.size>=J.maxSize){let Y=this.currentLogFile,Q=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let W=await B1(this.config.logDirectory),U=W.filter((H)=>H.startsWith(this.name)&&/\.log\.\d+$/.test(H)).sort((H,K)=>{let B=Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(K.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),Z=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${Y}.${Z}`;if(await x0(Y).catch(()=>null))try{if(await Q8(Y,z),J.compress)try{let H=`${z}.gz`;await this.compressLogFile(z,H),await O1(z)}catch(H){console.error("Error compressing rotated file:",H)}if(U.length===0&&!W.some((H)=>H.endsWith(".log.1")))try{let H=`${Y}.1`;await EJ(H,"")}catch(H){console.error("Error creating backup file:",H)}}catch(H){console.error(`Error during rotation: ${H instanceof Error?H.message:String(H)}`)}}else{let W=new Date().toISOString().replace(/[:.]/g,"-"),U=Y.replace(/\.log$/,`-${W}.log`);if(await x0(Y).catch(()=>null))await Q8(Y,U)}if(this.currentLogFile=Q,J.maxFiles){let U=(await B1(this.config.logDirectory)).filter((Z)=>Z.startsWith(this.name)).sort((Z,z)=>z.localeCompare(Z));for(let Z of U.slice(J.maxFiles))await O1(h0(this.config.logDirectory,Z))}}}async compressLogFile($,J){let Y=e5($),Q=dQ(J),W=W8();await aQ(Y,W,Q)}async handleFingersCrossedBuffer($,J){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Q=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(Q);console.log(Q)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}}shouldLog($){if(!this.enabled)return!1;let J={debug:0,info:1,success:2,warning:3,error:4};return J[$]>=J[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((J)=>{console.error("Error in pending write operation:",J)});return Promise.resolve()})),K1(this.currentLogFile))try{let $=J8(this.currentLogFile,"r+");$8($),MJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!F$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let J=(await B1(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of J)try{await O1(h0(this.config.logDirectory,Y))}catch(Q){console.error(`Failed to delete temp file ${Y}:`,Q)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?e.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F$())return!1;let $=typeof o.env.NO_COLOR<"u",J=o.env.FORCE_COLOR==="0";if($||J)return!1;return!!(typeof o.stderr<"u"&&o.stderr.isTTY||typeof o.stdout<"u"&&o.stdout.isTTY)}formatConsoleMessage($){let{timestamp:J,icon:Y="",tag:Q="",message:W,level:U,showTimestamp:Z=!0}=$,z=(j)=>j.replace(this.ANSI_PATTERN,"");if(!this.fancy){let j=[];if(Z)j.push(J);if(U==="warning")j.push("WARN");else if(U==="error")j.push("ERROR");else if(Y)j.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Q)j.push(Q.replace(/[[\]]/g,""));return j.push(W),j.join(" ")}let H=o.stdout.columns||120,K="";if(U==="warning"||U==="error")K=`${Y} ${W}`;else if(U==="info"||U==="success")K=`${Y} ${Q} ${W}`;else K=`${Y} ${Q} ${e.cyan(W)}`;if(!Z)return K.trim();let B=z(K).trim().length,O=z(J).length,X=Math.max(1,H-2-B-O);return`${K.trim()}${" ".repeat(X)}${J}`}formatMessage($,J){if(J.length===1&&Array.isArray(J[0]))return $.replace(/\{(\d+)\}/g,(U,Z)=>{let z=Number.parseInt(Z,10);return z<J[0].length?String(J[0][z]):U});let Y=/%([sdijfo%])/g,Q=0,W=$.replace(Y,(U,Z)=>{if(Z==="%")return"%";if(Q>=J.length)return U;let z=J[Q++];switch(Z){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return U}});if(Q<J.length)W+=` ${J.slice(Q).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return W}formatMarkdown($){if(!$)return $;let J=$;return J=J.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,Q,W)=>{let U=e.underline(e.blue(Q)),Z=this.toAbsoluteFilePath(W);if(Z&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let z=`file://${encodeURI(Z)}`,H="\x1B]8;;",K="\x1B\\";return`\x1B]8;;${z}\x1B\\${U}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${W}\x1B\\${U}\x1B]8;;\x1B\\`;return U}),J=J.replace(/`([^`]+)`/g,(Y,Q)=>e.bgGray(Q)),J=J.replace(/\*\*([^*]+)\*\*/g,(Y,Q)=>e.bold(Q)),J=J.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Q)=>e.italic(Q)),J=J.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Q)=>e.italic(Q)),J=J.replace(/~([^~]+)~/g,(Y,Q)=>e.strikethrough(Q)),J}supportsHyperlinks(){if(F$())return!1;let $=o.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let J=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(J)&&J>=5000)return!0;return!1}toAbsoluteFilePath($){try{let J=$;if(J.startsWith("file://"))J=J.replace(/^file:\/\//,"");if(J.startsWith("~")){let Y=o.env.HOME||"";if(Y)J=J.replace(/^~(?=$|\/)/,Y)}if(pQ(J)||J.startsWith("./")||J.startsWith("../"))J=rQ(J);else return null;return K1(J)?J:null}catch{return null}}buildOutputTexts($){let J=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:J,fileText:Y}}async log($,J,...Y){let Q=new Date,W=this.formatConsoleTimestamp(Q),U=this.formatFileTimestamp(Q),Z,z;if(J instanceof Error)Z=J.message,z=J.stack;else Z=this.formatMessage(J,Y);let{consoleText:H,fileText:K}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let O=this.options.showIcons===!1?"":q7[$],X=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:W,icon:O,tag:X,message:e.gray(H),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:W,icon:O,tag:X,message:H,level:$}),console.warn(j);break;case"success":j=this.formatConsoleMessage({timestamp:W,icon:O,tag:X,message:e.green(H),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:W,icon:O,tag:X,message:H,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:W,icon:O,tag:X,message:H,level:$}),console.error(j),z){let q=z.split(`
396
+ `);for(let E of q)if(E.trim()&&!E.includes(Z))console.error(this.formatConsoleMessage({timestamp:W,message:e.gray(` ${E}`),level:$,showTimestamp:!1}))}break}}else if(!F$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Z}`),z)console.error(z)}if(!this.shouldLog($))return;let B=`${U} ${this.environment}.${$.toUpperCase()}: ${K}
397
+ `;if(z)B+=`${z}
398
+ `;if(B=B.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(B)}progress($,J=""){let Y={update:(z,H)=>{},finish:(z)=>{},interrupt:(z,H)=>{}};if(!this.enabled)return Y;let Q=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:J||"",barLength:Q,lastRenderedLine:""},this.shouldStyleConsole()&&!F$()&&o.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(z,H)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,z),this.activeProgressBar.total),H!==void 0)this.activeProgressBar.message=H;if(this.shouldStyleConsole()&&!F$()&&o.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(z)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,z)},interrupt:(z,H="info")=>{if(!F$()&&o.stdout.isTTY)o.stdout.write(`
399
+ `);if(this[H==="warning"?"warn":H](z),this.activeProgressBar&&this.shouldStyleConsole()&&!F$()&&o.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let J=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",Q=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Q,icon:this.options.showIcons===!1?"":e.blue("◐"),tag:Y,message:`${e.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let Q=performance.now(),W=Math.round(Q-J),U=`${$} completed in ${W}ms`,Z=new Date,z=this.formatConsoleTimestamp(Z),K=`${this.formatFileTimestamp(Z)} ${this.environment}.INFO: ${U}`;if(Y)K+=` ${JSON.stringify(Y)}`;if(K+=`
400
+ `,K=K.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:z,icon:this.options.showIcons===!1?"":e.green("✓"),tag:B,message:`${U}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!F$())console.error(K.trim());if(this.shouldWriteToFile())await this.writeToFile(K)}}async debug($,...J){await this.log("debug",$,...J)}async info($,...J){await this.log("info",$,...J)}async success($,...J){await this.log("success",$,...J)}async warn($,...J){await this.log("warning",$,...J)}async error($,...J){await this.log("error",$,...J)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:J}=$;return!!J}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let J=`${this.name}:${$}`,Y=new P1(J,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(F$())throw Error("createReadStream is not supported in browser environments");if(!K1(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return e5(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let J=this.config.rotation;if(!J.encrypt||typeof J.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let Q=W0.isBuffer($)?$:W0.from($,"base64"),W=Q.subarray(0,16),U=Q.subarray(Q.length-16),Z=Q.subarray(16,Q.length-16),z=uQ("aes-256-gcm",Y,W);z.setAuthTag(U);let H=z.update(Z),K=z.final(),B=H.length+K.length,O=W0.allocUnsafe(B);return H.copy(O,0),K.copy(O,H.length),O.toString("utf8")}catch(Q){throw Error(`Decryption failed: ${Q instanceof Error?Q.message:String(Q)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return F$()}isServerMode(){return!F$()}setTestEncryptionKey($,J){this.currentKeyId=$,this.keys.set($,J)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let J=new Date,Y=this.formatConsoleTimestamp(J),Q=this.formatFileTimestamp(J),{consoleText:W,fileText:U}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let z=W.split(`
401
+ `),H=Math.max(...z.map((X)=>X.length))+2,K=`┌${"─".repeat(H)}┐`,B=`└${"─".repeat(H)}┘`,O=z.map((X)=>{return this.formatConsoleMessage({timestamp:Y,message:e.cyan(X),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(K),showTimestamp:!1})),O.forEach((X)=>console.error(X)),console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(B),showTimestamp:!1}))}else if(!F$())console.error(`${Q} ${this.environment}.INFO: [BOX] ${U}`);let Z=`${Q} ${this.environment}.INFO: [BOX] ${U}
402
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}async prompt($){if(F$())return Promise.resolve(!0);return new Promise((J)=>{console.error(`${e.cyan("?")} ${$} (y/n) `);let Y=(Q)=>{let W=Q.toString().trim().toLowerCase();o.stdin.removeListener("data",Y);try{if(typeof o.stdin.setRawMode==="function")o.stdin.setRawMode(!1)}catch{}o.stdin.pause(),console.error(""),J(W==="y"||W==="yes")};try{if(typeof o.stdin.setRawMode==="function")o.stdin.setRawMode(!0)}catch{}o.stdin.resume(),o.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...J){if(!this.enabled)return;let Y=$;if(J&&J.length>0){let H=/%([sdijfo%])/g,K=0;if(Y=$.replace(H,(B,O)=>{if(O==="%")return"%";if(K>=J.length)return B;let X=J[K++];switch(O){case"s":return String(X);case"d":case"i":return Number(X).toString();case"j":case"o":return JSON.stringify(X,null,2);default:return B}}),K<J.length)Y+=` ${J.slice(K).map((B)=>typeof B==="object"?JSON.stringify(B,null,2):String(B)).join(" ")}`}let{consoleText:Q,fileText:W}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let H=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",K=this.options.showIcons===!1?"":`${e.blue("◐")} `;console.error(`${K}${H} ${e.cyan(Q)}`)}let z=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${W}
403
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(z)}renderProgressBar($,J=!1){if(!this.enabled||!this.shouldStyleConsole()||!o.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Q=Math.round($.barLength*Y/100),W=$.barLength-Q,U=e.green("━".repeat(Q)),Z=e.gray("━".repeat(W)),z=`[${U}${Z}]`,H=`${Y}%`.padStart(4),K=$.message?` ${$.message}`:"",B=this.options.showIcons===!1?"":J||Y===100?e.green("✓"):e.blue("▶"),O=this.options.showTags!==!1&&this.name?` ${e.gray(this.formatTag(this.name))}`:"",X=`\r${B}${O} ${z} ${H}${K}`,j=o.stdout.columns||80,q=" ".repeat(Math.max(0,j-X.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${X}${q}`,o.stdout.write($.lastRenderedLine),J)o.stdout.write(`
404
+ `)}finishProgressBar($,J){if(!this.enabled||!this.fancy||F$()||!o.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(J)$.message=J;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(F$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let J=await B1(this.config.logDirectory),Y=[];for(let Q of J){if(!($.name?new RegExp($.name.replace("*",".*")).test(Q):Q.startsWith(this.name))||!Q.endsWith(".log"))continue;let U=h0(this.config.logDirectory,Q);if($.before)try{if((await x0(U)).mtime>=$.before)continue}catch(Z){console.error(`Failed to get stats for file ${U}:`,Z);continue}Y.push(U)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let Q of Y)try{await O1(Q),console.warn(`Deleted log file: ${Q}`)}catch(W){console.error(`Failed to delete log file ${Q}:`,W)}console.warn("Log clearing process finished.")}catch(J){console.error("Error during log clearing process:",J)}}}var a2=new P1("stacks");class l$ extends Error{timestamp;context;constructor($,J={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=J,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([J,Y])=>`${J}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}}class M8 extends l${code="CONFIG_NOT_FOUND";constructor($,J,Y){let Q=Y?` or alias "${Y}"`:"";super(`Configuration "${$}"${Q} not found`,{configName:$,alias:Y,searchPaths:J,searchPathCount:J.length})}}class A1 extends l${code="CONFIG_LOAD_ERROR";constructor($,J,Y){super(`Failed to load configuration from "${$}": ${J.message}`,{configPath:$,configName:Y,originalError:J.name,originalMessage:J.message});this.cause=J}}class E8 extends l${code="CONFIG_VALIDATION_ERROR";constructor($,J,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:J,errorCount:J.length})}}class _8 extends l${code="CONFIG_MERGE_ERROR";constructor($,J,Y,Q){super(`Failed to merge configuration from "${$}" with "${J}": ${Y.message}`,{sourcePath:$,targetPath:J,configName:Q,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class NJ extends l${code="ENV_VAR_ERROR";constructor($,J,Y,Q){super(`Failed to parse environment variable "${$}" with value "${J}" as ${Y}`,{envKey:$,envValue:J,expectedType:Y,configName:Q})}}class F8 extends l${code="FILE_SYSTEM_ERROR";constructor($,J,Y){super(`File system ${$} failed for "${J}": ${Y.message}`,{operation:$,path:J,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class w8 extends l${code="TYPE_GENERATION_ERROR";constructor($,J,Y){super(`Failed to generate types from "${$}" to "${J}": ${Y.message}`,{configDir:$,outputPath:J,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class R1 extends l${code="SCHEMA_VALIDATION_ERROR";constructor($,J,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:J,errorCount:J.length})}}class T8 extends l${code="BROWSER_CONFIG_ERROR";constructor($,J,Y,Q){super(`Failed to fetch configuration from "${$}": ${J} ${Y}`,{endpoint:$,status:J,statusText:Y,configName:Q})}}class L8 extends l${code="PLUGIN_ERROR";constructor($,J,Y){super(`Plugin "${$}" failed during ${J}: ${Y.message}`,{pluginName:$,operation:J,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}var y0={configNotFound($,J,Y){return new M8($,J,Y)},configLoad($,J,Y){return new A1($,J,Y)},configValidation($,J,Y){return new E8($,J,Y)},configMerge($,J,Y,Q){return new _8($,J,Y,Q)},envVar($,J,Y,Q){return new NJ($,J,Y,Q)},fileSystem($,J,Y){return new F8($,J,Y)},typeGeneration($,J,Y){return new w8($,J,Y)},schemaValidation($,J,Y){return new R1($,J,Y)},browserConfig($,J,Y,Q){return new T8($,J,Y,Q)},plugin($,J,Y){return new L8($,J,Y)}};async function V7($,J={}){let{maxRetries:Y=3,retryDelay:Q=1000,isRetryable:W=()=>!0,fallback:U}=J,Z=Error("Unknown error occurred");for(let z=0;z<=Y;z++)try{return await $()}catch(H){if(Z=H instanceof Error?H:Error(String(H)),z===Y||!W(Z))break;if(Q>0)await new Promise((K)=>setTimeout(K,Q))}if(U!==void 0)return U;throw Z instanceof Error?Z:Error(`Unknown error: ${String(Z)}`)}class kJ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,J)=>J==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let J=$.toLowerCase();return["true","1","yes"].includes(J)}},{name:"number",canParse:($,J)=>J==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let J=Number($);if(Number.isNaN(J))throw TypeError(`Cannot parse "${$}" as number`);return J}},{name:"array",canParse:($,J)=>J==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let J=JSON.parse($);if(Array.isArray(J))return J}catch{}return $.split(",").map((J)=>J.trim())}},{name:"json",canParse:($,J)=>J==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(J){throw Error(`Cannot parse "${$}" as JSON: ${J}`)}}}]}async applyEnvironmentVariables($,J,Y={}){let{prefix:Q,useCamelCase:W=!0,useBackwardCompatibility:U=!0,customParsers:Z={},verbose:z=!1,trackPerformance:H=!0}=Y,K=async()=>{if(!$)return{config:J,source:{type:"environment",priority:50,timestamp:new Date}};let B=Q||this.generateEnvPrefix($),O={...J};return this.processObject(O,[],B,{useCamelCase:W,useBackwardCompatibility:U,customParsers:Z,verbose:z,configName:$}),{config:O,source:{type:"environment",priority:50,timestamp:new Date}}};if(H)return SJ.track("applyEnvironmentVariables",K,{configName:$});return K()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,J){if(!J)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,J,Y,Q){for(let[W,U]of Object.entries($)){let Z=[...J,W],z=Z.map((B)=>this.formatEnvKey(B,Q.useCamelCase)),H=`${Y}_${z.join("_")}`,K=Q.useBackwardCompatibility?`${Y}_${Z.map((B)=>B.toUpperCase()).join("_")}`:null;if(Q.verbose);if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.processObject(U,Z,Y,Q);else{let B=j1.env[H]||(K?j1.env[K]:void 0);if(B!==void 0){if(Q.verbose){let O=j1.env[H]?H:K}try{$[W]=this.parseEnvironmentValue(B,typeof U,H,Q.customParsers,Q.configName)}catch(O){if(O instanceof NJ)throw O;throw y0.envVar(H,B,typeof U,Q.configName)}}}}}parseEnvironmentValue($,J,Y,Q,W){for(let[U,Z]of Object.entries(Q))try{return Z($)}catch{continue}for(let U of this.defaultParsers)if(U.canParse($,J))try{return U.parse($)}catch{throw y0.envVar(Y,$,`${J} (via ${U.name} parser)`,W)}return $}getEnvironmentVariables($){let J={},Y=$.toUpperCase();for(let[Q,W]of Object.entries(j1.env))if(Q.startsWith(Y)&&W!==void 0)J[Q]=W;return J}validateEnvironmentVariable($,J,Y){let Q=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Q.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,J,Y,{})}catch(W){Q.push(`Cannot parse value "${J}" as ${Y}: ${W}`)}return{isValid:Q.length===0,errors:Q}}generateEnvVarDocs($,J,Y={}){let{prefix:Q,format:W="text"}=Y,U=Q||this.generateEnvPrefix($),Z=[];switch(this.extractEnvVarInfo(J,[],U,Z),W){case"markdown":return this.formatAsMarkdown(Z,$);case"json":return JSON.stringify(Z,null,2);default:return this.formatAsText(Z,$)}}extractEnvVarInfo($,J,Y,Q){for(let[W,U]of Object.entries($)){let Z=[...J,W],z=`${Y}_${Z.map((H)=>this.formatEnvKey(H,!0)).join("_")}`;if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.extractEnvVarInfo(U,Z,Y,Q);else Q.push({key:z,type:Array.isArray(U)?"array":typeof U,description:`Configuration for ${Z.join(".")}`,example:this.generateExample(U)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,J){let Y=`Environment Variables for ${J}:
405
+
406
+ `;for(let Q of $)Y+=`${Q.key}
407
+ `,Y+=` Type: ${Q.type}
408
+ `,Y+=` Description: ${Q.description}
409
+ `,Y+=` Example: ${Q.example}
410
+
411
+ `;return Y}formatAsMarkdown($,J){let Y=`# Environment Variables for ${J}
412
+
413
+ `;Y+=`| Variable | Type | Description | Example |
414
+ `,Y+=`|----------|------|-------------|----------|
415
+ `;for(let Q of $)Y+=`| \`${Q.key}\` | ${Q.type} | ${Q.description} | \`${Q.example}\` |
416
+ `;return Y}}function M7($,J,Y={}){return A8($,J,Y,new WeakMap)}function A8($,J,Y,Q){let{arrayMergeMode:W="replace",skipNullish:U=!1,customMerger:Z}=Y;if(J===null||J===void 0)return U?$:J;if(Z){let z=Z($,J);if(z!==void 0)return z}if(Array.isArray(J)||Array.isArray($))return R8($,J,W,Q);if(!f$(J)||!f$($))return J;return w7($,J,Y,Q)}function R8($,J,Y,Q){if(Array.isArray(J)&&!Array.isArray($))return J;if(Array.isArray($)&&!Array.isArray(J))return J;if(Array.isArray(J)&&Array.isArray($))switch(Y){case"replace":return J;case"concat":return E7($,J);case"smart":return _7($,J,Q);default:return J}return J}function E7($,J){let Y=[...J];for(let Q of $)if(!Y.some((W)=>RJ(W,Q)))Y.push(Q);return Y}function _7($,J,Y){if(J.length===0)return $;if($.length===0)return J;if(f$(J[0])&&f$($[0]))return F7($,J,Y);if(J.every((Q)=>typeof Q==="string")&&$.every((Q)=>typeof Q==="string")){let Q=[...J];for(let W of $)if(!Q.includes(W))Q.push(W);return Q}return J}function F7($,J,Y){let Q=[...J];for(let W of $){if(!f$(W)){Q.push(W);continue}let U=["id","name","key","path","type"],Z=!1;for(let z of U)if(z in W){if(Q.find((K)=>f$(K)&&(z in K)&&K[z]===W[z])){Z=!0;break}}if(!Z)Q.push(W)}return Q}function w7($,J,Y,Q){let W=J;if(f$(W)&&Q.has(W))return Q.get(W);let U={...$};if(f$(W))Q.set(W,U);for(let Z in W){if(!Object.prototype.hasOwnProperty.call(W,Z))continue;let z=W[Z],H=U[Z];if(Y.skipNullish&&(z===null||z===void 0))continue;if(z===null||z===void 0){U[Z]=z;continue}if(f$(z)&&f$(H))U[Z]=A8(H,z,Y,Q);else if(Array.isArray(z)||Array.isArray(H))U[Z]=R8(H,z,Y.arrayMergeMode||"smart",Q);else U[Z]=z}return U}function S8($,J,Y="replace"){return M7($,J,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function RJ($,J){if($===J)return!0;if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return!1;for(let Y=0;Y<$.length;Y++)if(!RJ($[Y],J[Y]))return!1;return!0}if(f$($)&&f$(J)){let Y=Object.keys($),Q=Object.keys(J);if(Y.length!==Q.length)return!1;for(let W of Y){if(!Object.prototype.hasOwnProperty.call(J,W))return!1;if(!RJ($[W],J[W]))return!1}return!0}return!1}function f$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class D8{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,J,Y={}){let{arrayStrategy:Q="replace",useCache:W=!0,cacheTtl:U,trackPerformance:Z=!0,verbose:z=!1}=Y;if(W){let K=E1.getWithFileCheck("file",$);if(K){if(z)console.log(`Configuration loaded from cache: ${$}`);return K}}let H=async()=>{if(!q1($))return null;try{let K=`?t=${Date.now()}`,B=await import($+K),O=B.default||B,X="default"in B,j=Object.keys(B).length>0;if(!X&&!j)throw new A1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof O!=="object"||O===null||Array.isArray(O))throw new A1($,Error("Configuration must export a valid object"),"unknown");let F={config:S8(J,O,Q),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(W)E1.setWithFileCheck("file",F,$,U);return F}catch(K){throw K instanceof Error?y0.configLoad($,K):y0.configLoad($,Error(String(K)))}};if(Z)return SJ.track("loadFromPath",H,{path:$});return H()}async tryLoadFromPaths($,J,Y={}){for(let Q of $)try{let W=await this.loadFromPath(Q,J,Y);if(W)return W}catch(W){if(W instanceof Error&&W.name==="ConfigLoadError")throw W;if(Y.verbose)console.warn(`Failed to load config from ${Q}:`,W)}return null}generateConfigPaths($,J,Y){let Q=this.generateNamePatterns($,Y),W=[];for(let U of Q)for(let Z of this.extensions)W.push(LJ(J,`${U}${Z}`));return W}generateNamePatterns($,J){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(J){if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)Y.push(`${$}.${J}.config`,`.${$}.${J}.config`)}return Y.filter(Boolean)}checkFileAccess($){return V7(async()=>{return q1($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,J,Y){let Q=[];if(!q1($))return Q;if(J||Y){let W=this.generateNamePatterns(J||"",Y);for(let U of W)for(let Z of this.extensions){let z=LJ($,`${U}${Z}`);if(await this.checkFileAccess(z))Q.push(z)}}else try{let{readdirSync:W}=await import("fs"),U=W($);for(let Z of U)if(this.looksLikeConfigFile(Z)){let z=LJ($,Z);if(await this.checkFileAccess(z))Q.push(z)}}catch{return[]}return Q}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let J=[];try{if(!q1($))return J.push("Configuration file does not exist"),J;let Y=await import($),Q=Y.default||Y;if(Q===void 0)J.push("Configuration file must export a default value or named exports");else if(typeof Q!=="object"||Q===null)J.push("Configuration must be an object");else if(Array.isArray(Q))J.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:W}=await import("fs"),U=W($,"utf8");JSON.parse(U)}catch(W){J.push(`Invalid JSON syntax: ${W}`)}}catch(Y){J.push(`Failed to load configuration file: ${Y}`)}return J}async getFileModificationTime($){try{let{statSync:J}=await import("fs");return J($).mtime}catch{return null}}async preloadConfigurations($,J={}){let Y=new Map;return await Promise.allSettled($.map(async(Q)=>{try{let W=await this.loadFromPath(Q,{},J);if(W)Y.set(Q,W.config)}catch(W){if(J.verbose)console.warn(`Failed to preload ${Q}:`,W)}})),Y}}var L7=/^https?:\/\//;class P8{async validateConfiguration($,J,Y={}){let{stopOnFirstError:Q=!1,validateRequired:W=!0,validateTypes:U=!0,customRules:Z=[],trackPerformance:z=!0,verbose:H=!1}=Y,K=async()=>{let B=[],O=[],X={stopOnFirstError:Q,validateRequired:W,validateTypes:U,customRules:Z,trackPerformance:z,verbose:H};try{if(typeof J==="string")return await this.validateWithSchemaFile($,J,X);else if(Array.isArray(J))return this.validateWithRules($,[...J,...Z],X);else return this.validateWithJSONSchema($,J,X)}catch(j){return B.push({path:"",message:`Validation failed: ${j}`,rule:"system"}),{isValid:!1,errors:B,warnings:O}}};if(z)return await SJ.track("validateConfiguration",K);return K()}async validateWithSchemaFile($,J,Y){try{if(!T7(J))throw new R1(J,[{path:"",message:"Schema file does not exist"}]);let Q=await import(J),W=Q.default||Q;if(Array.isArray(W))return this.validateWithRules($,W,Y);else return this.validateWithJSONSchema($,W,Y)}catch(Q){throw new R1(J,[{path:"",message:`Failed to load schema: ${Q}`}])}}validateWithJSONSchema($,J,Y){let Q=[],W=[];return this.validateObjectAgainstSchema($,J,"",Q,W,Y),{isValid:Q.length===0,errors:Q,warnings:W}}validateObjectAgainstSchema($,J,Y,Q,W,U){if(U.validateTypes&&J.type){let Z=Array.isArray($)?"array":typeof $,z=Array.isArray(J.type)?J.type:[J.type];if(!z.includes(Z)){if(Q.push({path:Y,message:`Expected type ${z.join(" or ")}, got ${Z}`,expected:z.join(" or "),actual:Z,rule:"type"}),U.stopOnFirstError)return}}if(J.enum&&!J.enum.includes($)){if(Q.push({path:Y,message:`Value must be one of: ${J.enum.join(", ")}`,expected:J.enum.join(", "),actual:$,rule:"enum"}),U.stopOnFirstError)return}if(typeof $==="string"){if(J.minLength!==void 0&&$.length<J.minLength)Q.push({path:Y,message:`String length must be at least ${J.minLength}`,expected:`>= ${J.minLength}`,actual:$.length,rule:"minLength"});if(J.maxLength!==void 0&&$.length>J.maxLength)Q.push({path:Y,message:`String length must not exceed ${J.maxLength}`,expected:`<= ${J.maxLength}`,actual:$.length,rule:"maxLength"});if(J.pattern){if(!new RegExp(J.pattern).test($))Q.push({path:Y,message:`String does not match pattern ${J.pattern}`,expected:J.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(J.minimum!==void 0&&$<J.minimum)Q.push({path:Y,message:`Value must be at least ${J.minimum}`,expected:`>= ${J.minimum}`,actual:$,rule:"minimum"});if(J.maximum!==void 0&&$>J.maximum)Q.push({path:Y,message:`Value must not exceed ${J.maximum}`,expected:`<= ${J.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&J.items)for(let Z=0;Z<$.length;Z++){let z=Y?`${Y}[${Z}]`:`[${Z}]`;if(this.validateObjectAgainstSchema($[Z],J.items,z,Q,W,U),U.stopOnFirstError&&Q.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let Z=$;if(U.validateRequired&&J.required){for(let z of J.required)if(!(z in Z)){if(Q.push({path:Y?`${Y}.${z}`:z,message:`Missing required property '${z}'`,expected:"required",rule:"required"}),U.stopOnFirstError)return}}if(J.properties){for(let[z,H]of Object.entries(J.properties))if(z in Z){let K=Y?`${Y}.${z}`:z;if(this.validateObjectAgainstSchema(Z[z],H,K,Q,W,U),U.stopOnFirstError&&Q.length>0)return}}if(J.additionalProperties===!1){let z=new Set(Object.keys(J.properties||{}));for(let H of Object.keys(Z))if(!z.has(H))W.push({path:Y?`${Y}.${H}`:H,message:`Additional property '${H}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,J,Y){let Q=[],W=[];for(let U of J)try{let Z=this.getValueByPath($,U.path),z=this.validateWithRule(Z,U,U.path);if(Q.push(...z),Y.stopOnFirstError&&Q.length>0)break}catch(Z){Q.push({path:U.path,message:`Rule validation failed: ${Z}`,rule:"system"})}return{isValid:Q.length===0,errors:Q,warnings:W}}validateWithRule($,J,Y){let Q=[];if(J.required&&($===void 0||$===null))return Q.push({path:Y,message:J.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Q;if($===void 0||$===null)return Q;if(J.type){let W=Array.isArray($)?"array":typeof $;if(W!==J.type)Q.push({path:Y,message:J.message||`Expected type ${J.type}, got ${W}`,expected:J.type,actual:W,rule:"type"})}if(J.min!==void 0){let W=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(W<J.min)Q.push({path:Y,message:J.message||`Value must be at least ${J.min}`,expected:`>= ${J.min}`,actual:W,rule:"min"})}if(J.max!==void 0){let W=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(W>J.max)Q.push({path:Y,message:J.message||`Value must not exceed ${J.max}`,expected:`<= ${J.max}`,actual:W,rule:"max"})}if(J.pattern&&typeof $==="string"){if(!J.pattern.test($))Q.push({path:Y,message:J.message||`Value does not match pattern ${J.pattern}`,expected:J.pattern.toString(),actual:$,rule:"pattern"})}if(J.enum&&!J.enum.includes($))Q.push({path:Y,message:J.message||`Value must be one of: ${J.enum.join(", ")}`,expected:J.enum.join(", "),actual:$,rule:"enum"});if(J.validator){let W=J.validator($);if(W)Q.push({path:Y,message:J.message||W,rule:"custom"})}return Q}getValueByPath($,J){if(!J)return $;let Y=J.split("."),Q=$;for(let W of Y)if(Q&&typeof Q==="object"&&W in Q)Q=Q[W];else return;return Q}generateRulesFromInterface($){let J=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Q of Y){let[,W,U,Z]=Q;J.push({path:W,required:!U,type:this.mapTypeScriptType(Z)})}return J}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:L7},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var U0=new P1("bunfig",{showTags:!0});class C8{fileLoader=new D8;envProcessor=new kJ;validator=new P8;async loadConfig($){let J=Date.now(),{cache:Y,performance:Q,schema:W,validate:U,...Z}=$;try{if(Y?.enabled){let H=this.checkCache(Z.name||"",Z);if(H)return H}let z;try{z=await this.loadConfigurationStrategies(Z,!0,Y)}catch(H){let K=Z.__strictErrorHandling;if(H instanceof Error&&H.name==="ConfigNotFoundError"){if(K)throw H;z={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`No configuration file found for "${Z.name||"config"}", using defaults with environment variables`]}}else if(H instanceof Error&&H.name==="ConfigLoadError"){let B=H.message.includes("EACCES")||H.message.includes("EPERM")||H.message.includes("permission denied"),O=!B&&(H.message.includes("syntax")||H.message.includes("Expected")||H.message.includes("Unexpected")||H.message.includes("BuildMessage")||H.message.includes("errors building")),X=H.message.includes("Configuration must export a valid object")||H.message.includes("Configuration file is empty and exports nothing");if(K&&(X||B))throw H;if(O&&(!K||!X))z={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!K)z={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading error, using defaults: ${H.message}`]};else throw H}else z={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${H instanceof Error?H.message:String(H)}`]}}if(W||U)await this.validateConfiguration(z.config,W,U,Z.name);if(Y?.enabled&&z)this.cacheResult(Z.name||"",z,Y,Z);if(Q?.enabled){let H={operation:"loadConfig",duration:Date.now()-J,configName:Z.name,timestamp:new Date};if(Q.onMetrics)Q.onMetrics(H);if(Q.slowThreshold&&H.duration>Q.slowThreshold)U0.warn(`Slow configuration loading detected: ${H.duration}ms for ${Z.name}`);z.metrics=H}return z}catch(z){let H=Date.now()-J;throw U0.error(`Configuration loading failed after ${H}ms:`,[z instanceof Error?z:Error(String(z))]),z}}async loadConfigurationStrategies($,J=!1,Y){let{name:Q="",alias:W,cwd:U,configDir:Z,defaultConfig:z,checkEnv:H=!0,arrayStrategy:K="replace",verbose:B=!1}=$,O=U||S1.cwd(),X=[],j=await this.loadLocalConfiguration(Q,W,O,Z,z,K,B,H,Y);if(j)return X.push(...this.getLocalSearchPaths(Q,W,O,Z)),this.finalizeResult(j,X,H,Q,B);let q=await this.loadHomeConfiguration(Q,W,z,K,B,H);if(q)return X.push(...this.getHomeSearchPaths(Q,W)),this.finalizeResult(q,X,H,Q,B);let E=await this.loadPackageJsonConfiguration(Q,W,O,z,K,B,H);if(E)return X.push(v$(O,"package.json")),this.finalizeResult(E,X,H,Q,B);if(X.push(...this.getAllSearchPaths(Q,W,O,Z)),J)throw y0.configNotFound(Q,X,W);return{...await this.applyEnvironmentVariables(Q,z,H,B),warnings:[`No configuration file found for "${Q}"${W?` or alias "${W}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,J,Y,Q,W,U,Z,z,H){let K=z?V1($,W,Z):W,B=this.getLocalDirectories(Y,Q);for(let O of B){if(Z)U0.info(`Searching for configuration in: ${O}`);let X=this.fileLoader.generateConfigPaths($,O,J),j=await this.fileLoader.tryLoadFromPaths(X,K,{arrayStrategy:U,verbose:Z,cacheTtl:H?.ttl,useCache:!H?.ttl||H.ttl>100});if(j){if(Z)U0.success(`Configuration loaded from: ${j.source.path}`);return j}}return null}async loadHomeConfiguration($,J,Y,Q,W,U){if(!$)return null;let Z=U?V1($,Y,W):Y,z=[v$(C0(),".config",$),v$(C0(),".config"),C0()];for(let H of z){if(W)U0.info(`Checking home directory: ${H}`);let K=this.fileLoader.generateConfigPaths($,H,J),B=await this.fileLoader.tryLoadFromPaths(K,Z,{arrayStrategy:Q,verbose:W});if(B){if(W)U0.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration($,J,Y,Q,W,U,Z){let z=Z?V1($,Q,U):Q;try{let H=v$(Y,"package.json");if(!DQ(H))return null;let K=await import(H),B=K[$],O=$;if(!B&&J)B=K[J],O=J;if(B&&typeof B==="object"&&!Array.isArray(B)){if(U)U0.success(`Configuration loaded from package.json: ${O}`);return{config:S8(z,B,W),source:{type:"package.json",path:H,priority:30,timestamp:new Date}}}}catch(H){if(U)U0.warn("Failed to load package.json:",[H instanceof Error?H:Error(String(H))])}return null}async applyEnvironmentVariables($,J,Y,Q){if(!Y||!$||typeof J!=="object"||J===null||Array.isArray(J))return{config:J,source:{type:"default",priority:10,timestamp:new Date}};return{config:V1($,J,Q),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,J,Y,Q,W){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,J,Y,Q){let W=[];if(Y){let U=Y($);if(U)W.push(...U)}if(J){let U=await this.validator.validateConfiguration($,J);if(!U.isValid)W.push(...U.errors.map((Z)=>Z.path?`${Z.path}: ${Z.message}`:Z.message))}if(W.length>0)throw y0.configValidation(Q||"unknown",W,Q)}checkCache($,J){let Y=this.generateCacheKey($,J);return E1.get(Y)||null}cacheResult($,J,Y,Q){let W=this.generateCacheKey($,Q);E1.set(W,J,void 0,Y.ttl)}generateCacheKey($,J){let Y=[$];if(J.alias)Y.push(`alias:${J.alias}`);if(J.cwd)Y.push(`cwd:${J.cwd}`);if(J.configDir)Y.push(`configDir:${J.configDir}`);if("checkEnv"in J)Y.push(`checkEnv:${J.checkEnv}`);return Y.join("|")}getLocalDirectories($,J){return Array.from(new Set([$,v$($,"config"),v$($,".config"),J?v$($,J):void 0].filter(Boolean)))}getAllSearchPaths($,J,Y,Q){let W=[];return W.push(...this.getLocalSearchPaths($,J,Y,Q)),W.push(...this.getHomeSearchPaths($,J)),W.push(v$(Y,"package.json")),W}getLocalSearchPaths($,J,Y,Q){let W=this.getLocalDirectories(Y,Q),U=[];for(let Z of W)U.push(...this.fileLoader.generateConfigPaths($,Z,J));return U}getHomeSearchPaths($,J){if(!$)return[];let Y=[v$(C0(),".config",$),v$(C0(),".config"),C0()],Q=[];for(let W of Y)Q.push(...this.fileLoader.generateConfigPaths($,W,J));return Q}async loadConfigWithResult($){return this.loadConfig($)}}var AJ=new C8;async function N8($){let J="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Q;if(Y)Q=await AJ.loadConfig($);else Q=await AJ.loadConfig({...$,defaultConfig:J,cache:{enabled:!0},performance:{enabled:!1}});return Q?.config??J}catch(Q){let W=Q instanceof Error?Q.name:"UnknownError",U=Q instanceof Error?Q.message:String(Q);if(!(W==="ConfigNotFoundError"||W==="ConfigLoadError"||W==="ConfigValidationError"||U.includes("config"))&&$.verbose)U0.warn("Unexpected error loading config, using defaults:",[Q instanceof Error?Q:Error(String(Q))]);let z=Y?{...$,defaultConfig:J}:{...$,defaultConfig:J,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await AJ.applyEnvironmentVariables(z.name||"",J,!0,z.verbose||!1))?.config??J;return J}}function V1($,J,Y=!1){let Q=new kJ,W=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function U(Z,z=[]){let H={...Z};for(let[K,B]of Object.entries(Z)){let O=[...z,K],X=[`${W}_${O.join("_").toUpperCase()}`,`${W}_${O.map((E)=>E.toUpperCase()).join("")}`,`${W}_${O.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],j,q;for(let E of X)if(j=S1.env[E],j!==void 0){q=E;break}if(j!==void 0&&q)if(typeof B==="boolean")H[K]=["true","1","yes"].includes(j.toLowerCase());else if(typeof B==="number"){let E=Number(j);if(!Number.isNaN(E))H[K]=E}else if(Array.isArray(B))try{H[K]=JSON.parse(j)}catch{H[K]=j.split(",").map((E)=>E.trim())}else H[K]=j;else if(B&&typeof B==="object"&&!Array.isArray(B))H[K]=U(B,O)}return H}return U(J)}var o2=v$(S1.cwd(),"config"),e2=v$(S1.cwd(),"src/generated");var A7={project:{name:"my-project",slug:"my-project",region:"us-east-1"},environments:{production:{type:"production"}}},IJ=null;async function R7(){if(!IJ)IJ=await N8({name:"cloud",defaultConfig:A7});return IJ}var k8=R7;v0();async function g(){let $=await k8();if(!$.project)throw Error("Missing required project configuration in cloud.config.ts");return $}function g$($){if($)switch($.toLowerCase()){case"porkbun":{let Q=process.env.PORKBUN_API_KEY,W=process.env.PORKBUN_SECRET_KEY;if(!Q||!W)throw Error("PORKBUN_API_KEY and PORKBUN_SECRET_KEY environment variables are required for Porkbun provider");return{provider:"porkbun",apiKey:Q,secretKey:W}}case"godaddy":{let Q=process.env.GODADDY_API_KEY,W=process.env.GODADDY_API_SECRET;if(!Q||!W)throw Error("GODADDY_API_KEY and GODADDY_API_SECRET environment variables are required for GoDaddy provider");let U=process.env.GODADDY_ENVIRONMENT||"production";return{provider:"godaddy",apiKey:Q,apiSecret:W,environment:U}}case"route53":{let Q=process.env.AWS_REGION||"us-east-1",W=process.env.AWS_HOSTED_ZONE_ID;return{provider:"route53",region:Q,hostedZoneId:W}}case"cloudflare":{let Q=process.env.CLOUDFLARE_API_TOKEN;if(!Q)throw Error("CLOUDFLARE_API_TOKEN environment variable is required for Cloudflare provider");return{provider:"cloudflare",apiToken:Q}}default:throw Error(`Unknown DNS provider: ${$}. Supported: porkbun, godaddy, route53, cloudflare`)}if(new b1().loadFromEnv().getAllProviders().length===0)return null;if(process.env.PORKBUN_API_KEY&&process.env.PORKBUN_SECRET_KEY)return{provider:"porkbun",apiKey:process.env.PORKBUN_API_KEY,secretKey:process.env.PORKBUN_SECRET_KEY};if(process.env.GODADDY_API_KEY&&process.env.GODADDY_API_SECRET)return{provider:"godaddy",apiKey:process.env.GODADDY_API_KEY,apiSecret:process.env.GODADDY_API_SECRET,environment:process.env.GODADDY_ENVIRONMENT||"production"};if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)return{provider:"route53",region:process.env.AWS_REGION||"us-east-1",hostedZoneId:process.env.AWS_HOSTED_ZONE_ID};if(process.env.CLOUDFLARE_API_TOKEN)return{provider:"cloudflare",apiToken:process.env.CLOUDFLARE_API_TOKEN};return null}function t$($){let J=g$($);if(!J)throw Error("No DNS provider configured. Set environment variables for Porkbun (PORKBUN_API_KEY, PORKBUN_SECRET_KEY), GoDaddy (GODADDY_API_KEY, GODADDY_API_SECRET), Cloudflare (CLOUDFLARE_API_TOKEN), or Route53 (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)");return p$(J)}function bJ($){$.command("config","Show current configuration").action(async()=>{V("Configuration");try{let J=await g();console.log(JSON.stringify(J,null,2))}catch(J){_(`Failed to load configuration: ${J instanceof Error?J.message:"Unknown error"}`)}}),$.command("config:validate","Validate configuration file").action(async()=>{V("Validating Configuration");let J=new M("Validating cloud.config.ts...");J.start();try{let Y=await g();if(!Y.project?.name)throw Error("Missing project.name");if(!Y.project?.slug)throw Error("Missing project.slug");if(!Y.mode)throw Error("Missing deployment mode");J.succeed("Configuration is valid!"),G(`Project: ${Y.project.name}`),G(`Mode: ${Y.mode}`),G(`Region: ${Y.project.region||"us-east-1"}`)}catch(Y){J.fail("Configuration is invalid"),_(Y instanceof Error?Y.message:"Unknown error")}}),$.command("config:env","Manage environment variables").option("--list","List all environment variables").option("--set <key=value>","Set an environment variable").option("--unset <key>","Remove an environment variable").option("--environment <env>","Target environment (production, staging, development)").action(async(J)=>{V("Environment Variables");let Y=J?.environment||"production";if(J?.list)G(`Environment variables for ${Y}:`),x(["Key","Value","Last Modified"],[["NODE_ENV",Y,"2024-01-15"],["API_URL","https://api.example.com","2024-01-14"],["DEBUG","false","2024-01-10"]]);else if(J?.set){let[Q,...W]=J.set.split("="),U=W.join("=");if(!Q||!U){_("Invalid format. Use: --set KEY=VALUE");return}let Z=new M(`Setting ${Q}=${U}...`);Z.start(),await new Promise((z)=>setTimeout(z,1000)),Z.succeed(`Environment variable ${Q} set for ${Y}`)}else if(J?.unset){if(!await P(`Remove ${J.unset} from ${Y} environment?`,!1)){G("Operation cancelled");return}let W=new M(`Removing ${J.unset}...`);W.start(),await new Promise((U)=>setTimeout(U,1000)),W.succeed(`Environment variable ${J.unset} removed`)}else G("Use --list, --set KEY=VALUE, or --unset KEY")}),$.command("config:secrets","Manage secrets (AWS Secrets Manager)").option("--list","List all secrets").option("--create <name>","Create a new secret").option("--get <name>","Get secret value").option("--update <name>","Update secret value").option("--delete <name>","Delete a secret").option("--value <value>","Secret value (for create/update)").action(async(J)=>{if(V("Secrets Manager"),J?.list)G("Secrets in AWS Secrets Manager:"),x(["Name","Last Modified","Rotation Enabled"],[["db-password","2024-01-15","Yes"],["api-key","2024-01-14","No"],["jwt-secret","2024-01-10","Yes"]]);else if(J?.create){if(!J.value){let Q=await U$("Enter secret value","");J.value=Q}let Y=new M(`Creating secret ${J.create}...`);Y.start(),await new Promise((Q)=>setTimeout(Q,1000)),Y.succeed(`Secret ${J.create} created successfully`)}else if(J?.get){let Y=new M(`Fetching secret ${J.get}...`);Y.start(),await new Promise((Q)=>setTimeout(Q,1000)),Y.succeed("Secret retrieved"),G(`${J.get}: ******* (hidden for security)`),i$("Use --show-value to display the actual value")}else if(J?.update){if(!J.value){let Q=await U$("Enter new secret value","");J.value=Q}let Y=new M(`Updating secret ${J.update}...`);Y.start(),await new Promise((Q)=>setTimeout(Q,1000)),Y.succeed(`Secret ${J.update} updated successfully`)}else if(J?.delete){if(i$("This action is irreversible!"),!await P(`Delete secret ${J.delete}?`,!1)){G("Deletion cancelled");return}let Q=new M(`Deleting secret ${J.delete}...`);Q.start(),await new Promise((W)=>setTimeout(W,1000)),Q.succeed(`Secret ${J.delete} deleted`)}else G("Use --list, --create, --get, --update, or --delete")})}import{existsSync as BW}from"node:fs";import{mkdir as OW,writeFile as XW}from"node:fs/promises";import{join as jW}from"node:path";class yJ{template;constructor($){this.template={AWSTemplateFormatVersion:"2010-09-09",Description:$,Resources:{}}}addResource($,J){return this.template.Resources[$]=J,this}addResources($){return Object.assign(this.template.Resources,$),this}addParameter($,J){if(!this.template.Parameters)this.template.Parameters={};return this.template.Parameters[$]=J,this}addOutput($,J){if(!this.template.Outputs)this.template.Outputs={};return this.template.Outputs[$]=J,this}getResources(){return this.template.Resources}build(){return this.template}toJSON($=!0){return JSON.stringify(this.template,null,$?2:0)}toYAML(){return this.convertToYAML(this.template)}convertToYAML($,J=0){let Y=" ".repeat(J),Q="";for(let[W,U]of Object.entries($)){if(U===null||U===void 0)continue;if(typeof U==="object"&&!Array.isArray(U))Q+=`${Y}${W}:
417
+ ${this.convertToYAML(U,J+1)}`;else if(Array.isArray(U)){Q+=`${Y}${W}:
418
+ `;for(let Z of U)if(typeof Z==="object")Q+=`${Y} -
419
+ ${this.convertToYAML(Z,J+2)}`;else Q+=`${Y} - ${Z}
420
+ `}else Q+=`${Y}${W}: ${U}
421
+ `}return Q}}var d={Ref:($)=>({Ref:$}),GetAtt:($,J)=>({"Fn::GetAtt":[$,J]}),Sub:($,J)=>{if(J)return{"Fn::Sub":[$,J]};return{"Fn::Sub":$}},Join:($,J)=>({"Fn::Join":[$,J]}),Select:($,J)=>({"Fn::Select":[$,J]}),Split:($,J)=>({"Fn::Split":[$,J]}),GetAZs:($="")=>({"Fn::GetAZs":$}),ImportValue:($)=>({"Fn::ImportValue":$}),If:($,J,Y)=>({"Fn::If":[$,J,Y]}),Equals:($,J)=>({"Fn::Equals":[$,J]}),And:(...$)=>({"Fn::And":$}),Or:(...$)=>({"Fn::Or":$}),Not:($)=>({"Fn::Not":[$]}),Base64:($)=>({"Fn::Base64":$})};function h($){let{slug:J,environment:Y,resourceType:Q,timestamp:W,suffix:U}=$,Z=[J,Y,Q];if(W)Z.push(W);if(U)Z.push(U);return Z.join("-")}function I($){return $.split("-").map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join("")}import{existsSync as r0,readdirSync as S7}from"node:fs";import{join as j0}from"node:path";class o${static createBucket($){let{name:J,slug:Y,environment:Q,public:W=!1,versioning:U=!1,website:Z=!1,encryption:z=!0,intelligentTiering:H=!1,cors:K,lifecycleRules:B}=$,O=h({slug:Y,environment:Q,resourceType:"s3",suffix:J}),X=I(O),j={Type:"AWS::S3::Bucket",Properties:{BucketName:O}};if(z)j.Properties.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(U)j.Properties.VersioningConfiguration={Status:"Enabled"};if(Z)j.Properties.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"error.html"};if(!W)j.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(K&&K.length>0)j.Properties.CorsConfiguration={CorsRules:K.map((E)=>({AllowedOrigins:E.allowedOrigins,AllowedMethods:E.allowedMethods,AllowedHeaders:E.allowedHeaders,MaxAge:E.maxAge}))};if(B&&B.length>0)j.Properties.LifecycleConfiguration={Rules:B.map((E)=>({Id:E.id,Status:E.enabled?"Enabled":"Disabled",ExpirationInDays:E.expirationDays,Transitions:E.transitions?.map((F)=>({TransitionInDays:F.days,StorageClass:F.storageClass}))}))};if(H&&B){let E={id:"IntelligentTieringRule",enabled:!0,transitions:[{days:0,storageClass:"INTELLIGENT_TIERING"}]};if(!j.Properties.LifecycleConfiguration)j.Properties.LifecycleConfiguration={Rules:[]};j.Properties.LifecycleConfiguration.Rules.push({Id:E.id,Status:"Enabled",Transitions:E.transitions?.map((F)=>({TransitionInDays:F.days,StorageClass:F.storageClass}))})}let q;if(W)q={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:d.Ref(X),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[d.Join("",[d.GetAtt(X,"Arn"),"/*"])]}]}}};return{bucket:j,bucketPolicy:q,logicalId:X}}static enableVersioning($){if(!$.Properties)$.Properties={};return $.Properties.VersioningConfiguration={Status:"Enabled"},$}static enableWebsiteHosting($,J="index.html",Y="error.html"){if(!$.Properties)$.Properties={};return $.Properties.WebsiteConfiguration={IndexDocument:J,ErrorDocument:Y},$}static setLifecycleRules($,J){if(!$.Properties)$.Properties={};return $.Properties.LifecycleConfiguration={Rules:J.map((Y)=>({Id:Y.id,Status:Y.enabled?"Enabled":"Disabled",ExpirationInDays:Y.expirationDays,Transitions:Y.transitions?.map((Q)=>({TransitionInDays:Q.days,StorageClass:Q.storageClass}))}))},$}static enableIntelligentTiering($){if(!$.Properties)$.Properties={};if(!$.Properties.LifecycleConfiguration)$.Properties.LifecycleConfiguration={Rules:[]};return $.Properties.LifecycleConfiguration.Rules.push({Id:"IntelligentTieringRule",Status:"Enabled",Transitions:[{TransitionInDays:0,StorageClass:"INTELLIGENT_TIERING"}]}),$}static addLambdaNotification($,J){if(!$.Properties)$.Properties={};if(!$.Properties.NotificationConfiguration)$.Properties.NotificationConfiguration={};if(!$.Properties.NotificationConfiguration.LambdaConfigurations)$.Properties.NotificationConfiguration.LambdaConfigurations=[];let Y={Event:J.events[0],Function:J.functionArn};if(J.filter)Y.Filter={S3Key:{Rules:[...J.filter.prefix?[{Name:"prefix",Value:J.filter.prefix}]:[],...J.filter.suffix?[{Name:"suffix",Value:J.filter.suffix}]:[]]}};for(let Q of J.events){let W={...Y,Event:Q};$.Properties.NotificationConfiguration.LambdaConfigurations.push(W)}return $}static Notifications={onObjectCreated:($)=>({functionArn:$,events:["s3:ObjectCreated:*"]}),onObjectRemoved:($)=>({functionArn:$,events:["s3:ObjectRemoved:*"]}),onImageUpload:($,J)=>({functionArn:$,events:["s3:ObjectCreated:*"],filter:{prefix:J,suffix:".jpg"}}),onFileType:($,J,Y)=>({functionArn:$,events:["s3:ObjectCreated:*"],filter:{prefix:Y,suffix:J}}),onFolderUpload:($,J)=>({functionArn:$,events:["s3:ObjectCreated:*"],filter:{prefix:J.endsWith("/")?J:`${J}/`}})};static createBackupPlan($){let{name:J,slug:Y,environment:Q,bucketLogicalIds:W,retentionDays:U,schedule:Z="cron(0 5 * * ? *)",vaultName:z,enableContinuousBackup:H=!1,moveToColdStorageAfterDays:K}=$,B=z||h({slug:Y,environment:Q,resourceType:"backup-vault",suffix:J}),O=I(B),X={Type:"AWS::Backup::BackupVault",Properties:{BackupVaultName:B}},j=h({slug:Y,environment:Q,resourceType:"backup-role",suffix:J}),q=I(j),E={Type:"AWS::IAM::Role",Properties:{RoleName:j,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"backup.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup","arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForRestores"]}},F=h({slug:Y,environment:Q,resourceType:"backup-plan",suffix:J}),w=I(F),T={DeleteAfterDays:U};if(K&&K<U)T.MoveToColdStorageAfterDays=K;let S={Type:"AWS::Backup::BackupPlan",Properties:{BackupPlan:{BackupPlanName:F,BackupPlanRule:[{RuleName:`${J}-daily-backup`,TargetBackupVault:d.Ref(O),ScheduleExpression:Z,StartWindowMinutes:60,CompletionWindowMinutes:120,Lifecycle:T,EnableContinuousBackup:H}]}}},R=h({slug:Y,environment:Q,resourceType:"backup-selection",suffix:J}),C=I(R),D=W.map((u)=>d.GetAtt(u,"Arn")),k={Type:"AWS::Backup::BackupSelection",Properties:{BackupPlanId:d.Ref(w),BackupSelection:{SelectionName:R,IamRoleArn:d.GetAtt(q,"Arn"),Resources:D}}};return{vault:X,plan:S,selection:k,role:E,vaultLogicalId:O,planLogicalId:w,selectionLogicalId:C,roleLogicalId:q}}static BackupSchedules={HOURLY:"cron(0 * * * ? *)",DAILY_5AM:"cron(0 5 * * ? *)",DAILY_MIDNIGHT:"cron(0 0 * * ? *)",WEEKLY_SUNDAY:"cron(0 5 ? * SUN *)",WEEKLY_SATURDAY:"cron(0 5 ? * SAT *)",MONTHLY_FIRST:"cron(0 5 1 * ? *)",EVERY_12_HOURS:"cron(0 */12 * * ? *)",EVERY_6_HOURS:"cron(0 */6 * * ? *)"};static BackupRetention={ONE_DAY:1,ONE_WEEK:7,TWO_WEEKS:14,ONE_MONTH:30,THREE_MONTHS:90,SIX_MONTHS:180,ONE_YEAR:365,TWO_YEARS:730,FIVE_YEARS:1825,SEVEN_YEARS:2555};static createWwwRedirectBucket($){let{slug:J,environment:Y,sourceDomain:Q,targetDomain:W,protocol:U="https"}=$,Z=h({slug:J,environment:Y,resourceType:"s3",suffix:"www-redirect"}),z=I(Z),H={Type:"AWS::S3::Bucket",Properties:{BucketName:Q,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:W,Protocol:U}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1}}},K={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:d.Ref(z),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[d.Join("",[d.GetAtt(z,"Arn"),"/*"])]}]}}};return{bucket:H,bucketPolicy:K,logicalId:z}}static createDocsBucket($){let{slug:J,environment:Y,domain:Q}=$,W=Q||h({slug:J,environment:Y,resourceType:"s3",suffix:"docs"}),U=I(W);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:W,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},Tags:[{Key:"backup",Value:"weekly"}]}},logicalId:U}}static createEmailBucket($){let{slug:J,environment:Y}=$,Q=h({slug:J,environment:Y,resourceType:"s3",suffix:"email"}),W=I(Q),U={Type:"AWS::S3::Bucket",Properties:{BucketName:Q,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},LifecycleConfiguration:{Rules:[{Id:"EmailRetention",Status:"Enabled",ExpirationInDays:90,Transitions:[{TransitionInDays:30,StorageClass:"STANDARD_IA"}]}]}}},Z={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:d.Ref(W),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:d.Join("",[d.GetAtt(W,"Arn"),"/*"]),Condition:{StringEquals:{"AWS:SourceAccount":d.Ref("AWS::AccountId")}}}]}}};return{bucket:U,bucketPolicy:Z,logicalId:W}}static docsExist($={}){let{projectRoot:J=process.cwd(),docsPaths:Y=["docs","documentation","doc"]}=$;for(let Q of Y){let W=j0(J,Q);if(r0(W)){let U=["dist","build",".vitepress/dist","_site","out","public"];for(let Z of U){let z=j0(W,Z);if(r0(z))try{if(S7(z).length>0)return{exists:!0,path:W,hasDistFolder:!0,distPath:z}}catch{}}return{exists:!0,path:W,hasDistFolder:!1,distPath:null}}}return{exists:!1,path:null,hasDistFolder:!1,distPath:null}}static createDocsBucketIfExists($){let J=o$.docsExist({projectRoot:$.projectRoot,docsPaths:$.docsPaths});if(!J.exists)return{bucket:null,logicalId:null,docsInfo:J};let Y=o$.createDocsBucket({slug:$.slug,environment:$.environment,domain:$.domain});return{bucket:Y.bucket,bucketPolicy:Y.bucketPolicy,logicalId:Y.logicalId,docsInfo:J}}static createPrivateBucket($){let{slug:J,environment:Y,enableVersioning:Q=!0,retentionDays:W,encryptionKeyArn:U}=$,Z=h({slug:J,environment:Y,resourceType:"s3",suffix:"private"}),z=I(Z);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:Z,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:U?{SSEAlgorithm:"aws:kms",KMSMasterKeyID:U}:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},VersioningConfiguration:Q?{Status:"Enabled"}:void 0,LifecycleConfiguration:W?{Rules:[{Id:"RetentionPolicy",Status:"Enabled",ExpirationInDays:W}]}:void 0,Tags:[{Key:"backup",Value:"daily"}]}},logicalId:z}}static checkSourcePaths($={}){let{projectRoot:J=process.cwd(),paths:Y={}}=$,Q=Y.web||"views/web/dist",W=Y.docs||"docs/dist",U=Y.private||"private";return{web:{exists:r0(j0(J,Q)),path:j0(J,Q)},docs:{exists:r0(j0(J,W)),path:j0(J,W)},private:{exists:r0(j0(J,U)),path:j0(J,U)}}}static createDeploymentBuckets($){let{slug:J,environment:Y,domain:Q,projectRoot:W,paths:U}=$,Z=o$.checkSourcePaths({projectRoot:W,paths:U}),z={},H={web:!1,docs:!1,private:!1},K=o$.createBucket({name:"web",slug:J,environment:Y,public:!1,versioning:!1,encryption:!0});if(z[K.logicalId]=K.bucket,H.web=!0,Z.docs.exists){let B=o$.createDocsBucket({slug:J,environment:Y,domain:Q?`docs.${Q}`:void 0});if(z[B.logicalId]=B.bucket,B.bucketPolicy)z[`${B.logicalId}Policy`]=B.bucketPolicy;H.docs=!0}if(Z.private.exists){let B=o$.createPrivateBucket({slug:J,environment:Y,enableVersioning:!0});z[B.logicalId]=B.bucket,H.private=!0}return{resources:z,created:H,sourcePaths:Z}}}class u${static createDistribution($){let{slug:J,environment:Y,origin:Q,customDomain:W,certificateArn:U,errorPages:Z,cachePolicy:z,edgeFunctions:H,http3:K=!1,comment:B}=$,O=h({slug:J,environment:Y,resourceType:"cdn"}),X=I(O),j={Id:"DefaultOrigin",DomainName:Q.domainName,OriginPath:Q.originPath||""},q;if(Q.type==="s3"){let F=`${X}OAC`;q={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${O}-oac`,Description:`Origin Access Control for ${O}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},j.OriginAccessControlId=d.Ref(F)}else if(Q.type==="alb"||Q.type==="custom")j.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};let E={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,Comment:B||`CDN for ${O}`,DefaultRootObject:"index.html",Origins:[j],DefaultCacheBehavior:{TargetOriginId:"DefaultOrigin",ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0},PriceClass:"PriceClass_100",HttpVersion:K?"http2and3":"http2"}}};if(W&&U)E.Properties.DistributionConfig.Aliases=[W],E.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:U,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};if(Z&&Z.length>0)E.Properties.DistributionConfig.CustomErrorResponses=Z.map((F)=>({ErrorCode:F.errorCode,ResponseCode:F.responseCode,ResponsePagePath:F.responsePagePath}));if(H&&H.length>0)E.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=H.map((F)=>({EventType:F.event,LambdaFunctionARN:F.functionArn}));return{distribution:E,originAccessControl:q,logicalId:X}}static setCustomDomain($,J,Y){return $.Properties.DistributionConfig.Aliases=[J],$.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:Y,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},$}static setErrorPages($,J){return $.Properties.DistributionConfig.CustomErrorResponses=J.map((Y)=>({ErrorCode:Y.errorCode,ResponseCode:Y.responseCode,ResponsePagePath:Y.responsePagePath})),$}static enableHttp3($){return $.Properties.DistributionConfig.HttpVersion="http2and3",$}static addEdgeFunction($,J,Y){if(!$.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations)$.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=[];return $.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations.push({EventType:J,LambdaFunctionARN:Y}),$}static setCachePolicy($,J){return $.Properties.DistributionConfig.Comment=`${$.Properties.DistributionConfig.Comment||""} (TTL: ${J.default||86400}s)`,$}static createSpaDistribution($){return u$.createDistribution({...$,errorPages:[{errorCode:404,responseCode:200,responsePagePath:"/index.html"},{errorCode:403,responseCode:200,responsePagePath:"/index.html"}]})}static createDocsOriginRequestFunction($){let{slug:J,environment:Y}=$,Q=h({slug:J,environment:Y,resourceType:"edge-docs"}),W=I(Q),U=I(`${Q}-role`),Z=I(`${Q}-version`),z={Type:"AWS::IAM::Role",Properties:{RoleName:`${Q}-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["lambda.amazonaws.com","edgelambda.amazonaws.com"]},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]}},H=`
422
+ 'use strict';
423
+
424
+ exports.handler = async (event) => {
425
+ const request = event.Records[0].cf.request;
426
+ let uri = request.uri;
427
+
428
+ // If URI ends with a slash, append index.html
429
+ if (uri.endsWith('/')) {
430
+ request.uri = uri + 'index.html';
431
+ return request;
432
+ }
433
+
434
+ // If URI has a file extension, serve as-is
435
+ if (uri.includes('.')) {
436
+ return request;
437
+ }
438
+
439
+ // Try to determine if this is a directory or a file
440
+ // First, try appending .html (for VitePress clean URLs)
441
+ // If the file doesn't exist, CloudFront will try the directory with index.html
442
+
443
+ // Check if the URI looks like a file path without extension
444
+ const parts = uri.split('/');
445
+ const lastPart = parts[parts.length - 1];
446
+
447
+ // If the last part has no extension, append .html
448
+ if (lastPart && !lastPart.includes('.')) {
449
+ request.uri = uri + '.html';
450
+ }
451
+
452
+ return request;
453
+ };
454
+ `.trim();return{lambdaFunction:{Type:"AWS::Lambda::Function",Properties:{FunctionName:Q,Description:"Lambda@Edge origin request handler for docs routing",Runtime:"nodejs20.x",Handler:"index.handler",Role:d.GetAtt(U,"Arn"),Code:{ZipFile:H},MemorySize:128,Timeout:5}},role:z,functionLogicalId:W,roleLogicalId:U,versionLogicalId:Z}}static createDocsDistribution($){let{slug:J,environment:Y,origin:Q,customDomain:W,certificateArn:U,lambdaEdgeFunctionArn:Z}=$,z=u$.createDistribution({slug:J,environment:Y,origin:Q,customDomain:W,certificateArn:U,comment:`Docs CDN for ${J}`,errorPages:[{errorCode:404,responseCode:404,responsePagePath:"/404.html"},{errorCode:403,responseCode:403,responsePagePath:"/404.html"}]});if(Z)u$.addEdgeFunction(z.distribution,"origin-request",Z);return z.distribution.Properties.DistributionConfig.DefaultCacheBehavior.DefaultTTL=86400,z.distribution.Properties.DistributionConfig.DefaultCacheBehavior.MaxTTL=604800,z.distribution.Properties.DistributionConfig.DefaultCacheBehavior.MinTTL=0,z}static createApiDistribution($){let{slug:J,environment:Y,albDomainName:Q,customDomain:W,certificateArn:U,pathPattern:Z="/api/*",forwardHeaders:z=["Host","Origin","Authorization","Content-Type","Accept"],forwardCookies:H="all",whitelistedCookies:K,customOriginHeaders:B={}}=$,O=h({slug:J,environment:Y,resourceType:"cdn-api"}),X=I(O),j=Object.entries(B).map(([w,T])=>({HeaderName:w,HeaderValue:T})),q={Id:"ALBOrigin",DomainName:Q,CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSSLProtocols:["TLSv1.2"],OriginReadTimeout:60,OriginKeepaliveTimeout:60}};if(j.length>0)q.OriginCustomHeaders=j;let E={Forward:H};if(H==="whitelist"&&K)E.WhitelistedNames=K;let F={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,Comment:`API CDN for ${O}`,Origins:[q],DefaultCacheBehavior:{TargetOriginId:"ALBOrigin",ViewerProtocolPolicy:"https-only",AllowedMethods:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,DefaultTTL:0,MaxTTL:0,MinTTL:0,ForwardedValues:{QueryString:!0,Headers:z,Cookies:E}},PriceClass:"PriceClass_100",HttpVersion:"http2"}}};if(W&&U)F.Properties.DistributionConfig.Aliases=[W],F.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:U,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};return{distribution:F,logicalId:X}}static createMultiOriginDistribution($){let{slug:J,environment:Y,s3BucketDomainName:Q,albDomainName:W,apiPathPattern:U="/api/*",customDomain:Z,certificateArn:z,customOriginHeaders:H={}}=$,K=h({slug:J,environment:Y,resourceType:"cdn"}),B=I(K),O=`${B}OAC`,X={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${K}-oac`,Description:`Origin Access Control for ${K}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},j=Object.entries(H).map(([w,T])=>({HeaderName:w,HeaderValue:T})),q={Id:"S3Origin",DomainName:Q,OriginAccessControlId:d.Ref(O)},E={Id:"ALBOrigin",DomainName:W,CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSSLProtocols:["TLSv1.2"],OriginReadTimeout:60,OriginKeepaliveTimeout:60}};if(j.length>0)E.OriginCustomHeaders=j;let F={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,Comment:`Multi-origin CDN for ${K}`,DefaultRootObject:"index.html",Origins:[q,E],DefaultCacheBehavior:{TargetOriginId:"S3Origin",ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0},CacheBehaviors:[{PathPattern:U,TargetOriginId:"ALBOrigin",ViewerProtocolPolicy:"https-only",AllowedMethods:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,DefaultTTL:0,MaxTTL:0,MinTTL:0,ForwardedValues:{QueryString:!0,Headers:["Host","Origin","Authorization","Content-Type","Accept"],Cookies:{Forward:"all"}}}],PriceClass:"PriceClass_100",HttpVersion:"http2",CustomErrorResponses:[{ErrorCode:404,ResponseCode:200,ResponsePagePath:"/index.html"},{ErrorCode:403,ResponseCode:200,ResponsePagePath:"/index.html"}]}}};if(Z&&z)F.Properties.DistributionConfig.Aliases=[Z],F.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:z,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};return{distribution:F,originAccessControl:X,logicalId:B,oacLogicalId:O}}static addAlbOrigin($,J){let{originId:Y,domainName:Q,pathPattern:W,customHeaders:U={},forwardHeaders:Z=["Host","Origin","Authorization","Content-Type","Accept"],cacheTtl:z={default:0,max:0,min:0}}=J,H=Object.entries(U).map(([B,O])=>({HeaderName:B,HeaderValue:O})),K={Id:Y,DomainName:Q,CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSSLProtocols:["TLSv1.2"],OriginReadTimeout:60,OriginKeepaliveTimeout:60}};if(H.length>0)K.OriginCustomHeaders=H;if(!$.Properties.DistributionConfig.Origins)$.Properties.DistributionConfig.Origins=[];if($.Properties.DistributionConfig.Origins.push(K),!$.Properties.DistributionConfig.CacheBehaviors)$.Properties.DistributionConfig.CacheBehaviors=[];return $.Properties.DistributionConfig.CacheBehaviors.push({PathPattern:W,TargetOriginId:Y,ViewerProtocolPolicy:"https-only",AllowedMethods:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,DefaultTTL:z.default,MaxTTL:z.max,MinTTL:z.min,ForwardedValues:{QueryString:!0,Headers:Z,Cookies:{Forward:"all"}}}),$}static addOriginHeader($,J,Y,Q){let W=$.Properties.DistributionConfig.Origins?.find((U)=>U.Id===J);if(W){if(!W.OriginCustomHeaders)W.OriginCustomHeaders=[];W.OriginCustomHeaders.push({HeaderName:Y,HeaderValue:Q})}return $}static EdgeFunctionTemplates={docsOriginRequest:`
455
+ 'use strict';
456
+ exports.handler = async (event) => {
457
+ const request = event.Records[0].cf.request;
458
+ let uri = request.uri;
459
+
460
+ if (uri.endsWith('/')) {
461
+ request.uri = uri + 'index.html';
462
+ } else if (!uri.includes('.')) {
463
+ request.uri = uri + '.html';
464
+ }
465
+
466
+ return request;
467
+ };
468
+ `.trim(),securityHeaders:`
469
+ 'use strict';
470
+ exports.handler = async (event) => {
471
+ const response = event.Records[0].cf.response;
472
+ const headers = response.headers;
473
+
474
+ headers['strict-transport-security'] = [{ value: 'max-age=31536000; includeSubdomains; preload' }];
475
+ headers['x-content-type-options'] = [{ value: 'nosniff' }];
476
+ headers['x-frame-options'] = [{ value: 'DENY' }];
477
+ headers['x-xss-protection'] = [{ value: '1; mode=block' }];
478
+ headers['referrer-policy'] = [{ value: 'strict-origin-when-cross-origin' }];
479
+
480
+ return response;
481
+ };
482
+ `.trim(),basicAuth:($,J)=>`
483
+ 'use strict';
484
+ exports.handler = async (event) => {
485
+ const request = event.Records[0].cf.request;
486
+ const headers = request.headers;
487
+
488
+ const authString = 'Basic ' + Buffer.from('${$}:${J}').toString('base64');
489
+
490
+ if (!headers.authorization || headers.authorization[0].value !== authString) {
491
+ return {
492
+ status: '401',
493
+ statusDescription: 'Unauthorized',
494
+ body: 'Unauthorized',
495
+ headers: {
496
+ 'www-authenticate': [{ value: 'Basic realm="Protected"' }],
497
+ },
498
+ };
499
+ }
500
+
501
+ return request;
502
+ };
503
+ `.trim(),pathBasedRouting:($,J)=>`
504
+ 'use strict';
505
+ exports.handler = async (event) => {
506
+ const request = event.Records[0].cf.request;
507
+
508
+ if (request.uri.startsWith('${$}')) {
509
+ request.origin = {
510
+ custom: {
511
+ domainName: request.headers.host[0].value,
512
+ port: 443,
513
+ protocol: 'https',
514
+ sslProtocols: ['TLSv1.2'],
515
+ },
516
+ };
517
+ // Remove the path prefix for the origin request
518
+ request.uri = request.uri.substring(${$.length});
519
+ if (!request.uri.startsWith('/')) {
520
+ request.uri = '/' + request.uri;
521
+ }
522
+ }
523
+
524
+ return request;
525
+ };
526
+ `.trim()};static Config={ttl:($)=>{let{min:J=0,max:Y=86400,default:Q=86400}=$;return{MinTTL:J,MaxTTL:Y,DefaultTTL:Q}},cookies:($,J)=>{let Y={Forward:$==="allowList"?"whitelist":$};if($==="allowList"&&J)Y.WhitelistedNames=J;return Y},allowedMethods:($)=>{let J={ALL:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],GET_HEAD:["GET","HEAD"],GET_HEAD_OPTIONS:["GET","HEAD","OPTIONS"]};return J[$]||J.GET_HEAD},cachedMethods:($)=>{let J={GET_HEAD:["GET","HEAD"],GET_HEAD_OPTIONS:["GET","HEAD","OPTIONS"]};return J[$]||J.GET_HEAD},ttlPresets:{static:{min:0,max:31536000,default:31536000},dynamic:{min:0,max:0,default:0},api:{min:0,max:3600,default:60},html:{min:0,max:86400,default:86400},images:{min:0,max:604800,default:604800}},cacheBehavior:($)=>{let{ttl:J={min:0,max:86400,default:86400},cookies:Y="none",allowedCookies:Q,allowedMethods:W="GET_HEAD",cachedMethods:U="GET_HEAD",compress:Z=!0,forwardQueryString:z=!0,forwardHeaders:H=[]}=$;return{MinTTL:J.min,MaxTTL:J.max,DefaultTTL:J.default,Compress:Z,AllowedMethods:u$.Config.allowedMethods(W),CachedMethods:u$.Config.cachedMethods(U),ForwardedValues:{QueryString:z,Headers:H,Cookies:u$.Config.cookies(Y,Q)}}}};static applyConfig($,J){let Y=$.Properties.DistributionConfig.DefaultCacheBehavior;if(J.ttl)Y.MinTTL=J.ttl.min,Y.MaxTTL=J.ttl.max,Y.DefaultTTL=J.ttl.default;if(J.compress!==void 0)Y.Compress=J.compress;if(J.allowedMethods)Y.AllowedMethods=u$.Config.allowedMethods(J.allowedMethods);if(J.cachedMethods)Y.CachedMethods=u$.Config.cachedMethods(J.cachedMethods);if(J.cookies){if(!Y.ForwardedValues)Y.ForwardedValues={QueryString:!0};Y.ForwardedValues.Cookies=u$.Config.cookies(J.cookies,J.allowedCookies)}return $}}class a{static createServer($){let{slug:J,environment:Y,instanceType:Q="t3.micro",imageId:W="ami-0c55b159cbfafe1f0",keyName:U,securityGroupIds:Z,subnetId:z,userData:H,volumeSize:K=20,volumeType:B="gp3",encrypted:O=!0}=$,X=h({slug:J,environment:Y,resourceType:"ec2"}),j=I(X),q={Type:"AWS::EC2::Instance",Properties:{ImageId:W,InstanceType:Q,Tags:[{Key:"Name",Value:X},{Key:"Environment",Value:Y}]}};if(U)q.Properties.KeyName=U;if(Z)q.Properties.SecurityGroupIds=Z;if(z)q.Properties.SubnetId=z;if(H)q.Properties.UserData=d.Base64(H);return q.Properties.BlockDeviceMappings=[{DeviceName:"/dev/xvda",Ebs:{VolumeSize:K,VolumeType:B,Encrypted:O,DeleteOnTermination:!0}}],{instance:q,logicalId:j}}static createSecurityGroup($){let{slug:J,environment:Y,vpcId:Q,description:W,ingress:U=[],egress:Z=[]}=$,z=h({slug:J,environment:Y,resourceType:"sg"}),H=I(z),K={Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:W||`Security group for ${J} ${Y}`,Tags:[{Key:"Name",Value:z},{Key:"Environment",Value:Y}]}};if(Q)K.Properties.VpcId=Q;if(U.length>0)K.Properties.SecurityGroupIngress=U.map((B)=>({IpProtocol:B.protocol,FromPort:B.fromPort,ToPort:B.toPort,CidrIp:B.cidr,SourceSecurityGroupId:B.sourceSecurityGroupId}));if(Z.length>0)K.Properties.SecurityGroupEgress=Z.map((B)=>({IpProtocol:B.protocol,FromPort:B.fromPort,ToPort:B.toPort,CidrIp:B.cidr,DestinationSecurityGroupId:B.sourceSecurityGroupId}));return{securityGroup:K,logicalId:H}}static createWebServerSecurityGroup($,J,Y){return a.createSecurityGroup({slug:$,environment:J,vpcId:Y,description:"Security group for web servers - HTTP, HTTPS, SSH",ingress:[{protocol:"tcp",fromPort:80,toPort:80,cidr:"0.0.0.0/0"},{protocol:"tcp",fromPort:443,toPort:443,cidr:"0.0.0.0/0"},{protocol:"tcp",fromPort:22,toPort:22,cidr:"0.0.0.0/0"}],egress:[{protocol:"-1",fromPort:0,toPort:0,cidr:"0.0.0.0/0"}]})}static createLoadBalancer($){let{slug:J,environment:Y,scheme:Q="internet-facing",subnets:W,securityGroups:U,type:Z="application"}=$,z=h({slug:J,environment:Y,resourceType:"alb"}),H=I(z),K={Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:z,Scheme:Q,Type:Z,Subnets:W,Tags:[{Key:"Name",Value:z},{Key:"Environment",Value:Y}]}};if(U)K.Properties.SecurityGroups=U;return{loadBalancer:K,logicalId:H}}static createTargetGroup($){let{slug:J,environment:Y,port:Q,protocol:W="HTTP",vpcId:U,targetType:Z="ip",healthCheckPath:z="/",healthCheckInterval:H=30,healthCheckTimeout:K=5,healthyThreshold:B=2,unhealthyThreshold:O=3}=$,X=h({slug:J,environment:Y,resourceType:"tg"}),j=I(X);return{targetGroup:{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:X,Port:Q,Protocol:W,VpcId:U,TargetType:Z,HealthCheckEnabled:!0,HealthCheckProtocol:W,HealthCheckPath:z,HealthCheckIntervalSeconds:H,HealthCheckTimeoutSeconds:K,HealthyThresholdCount:B,UnhealthyThresholdCount:O,Tags:[{Key:"Name",Value:X},{Key:"Environment",Value:Y}]}},logicalId:j}}static createListener($,J){let{port:Y,protocol:Q="HTTP",certificateArn:W,defaultTargetGroupArn:U}=J,Z=I(`listener-${$}-${Y}`),z={Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:d.Ref($),Port:Y,Protocol:Q,DefaultActions:[{Type:"forward",TargetGroupArn:U}]}};if(Q==="HTTPS"&&W)z.Properties.Certificates=[{CertificateArn:W}],z.Properties.SslPolicy="ELBSecurityPolicy-TLS13-1-2-2021-06";return{listener:z,logicalId:Z}}static createEcsCluster($,J){let Y=h({slug:$,environment:J,resourceType:"ecs-cluster"}),Q=I(Y);return{cluster:{Type:"AWS::ECS::Cluster",Properties:{ClusterName:Y,Tags:[{Key:"Name",Value:Y},{Key:"Environment",Value:J}]}},logicalId:Q}}static createFargateService($){let{slug:J,environment:Y,image:Q,cpu:W="256",memory:U="512",desiredCount:Z=1,containerPort:z=8080,environmentVariables:H={},secrets:K=[],healthCheck:B,logGroup:O,subnets:X,securityGroups:j,targetGroupArn:q}=$,{cluster:E,logicalId:F}=a.createEcsCluster(J,Y),w=h({slug:J,environment:Y,resourceType:"fargate"}),T=I(`${w}-execution-role`),S={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"]}},R=I(`${w}-task-role`),C={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]}}},D=I(`${w}-task`),k={Type:"AWS::ECS::TaskDefinition",Properties:{Family:w,TaskRoleArn:d.GetAtt(R,"Arn"),ExecutionRoleArn:d.GetAtt(T,"Arn"),NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:W,Memory:U,ContainerDefinitions:[{Name:J,Image:Q,Essential:!0,PortMappings:[{ContainerPort:z,Protocol:"tcp"}],Environment:Object.entries(H).map(([v,y])=>({Name:v,Value:y})),Secrets:K.map((v)=>({Name:v.name,ValueFrom:v.valueFrom}))}],Tags:[{Key:"Name",Value:w},{Key:"Environment",Value:Y}]}};if(B)k.Properties.ContainerDefinitions[0].HealthCheck={Command:B.command,Interval:B.interval||30,Timeout:B.timeout||5,Retries:B.retries||3,StartPeriod:60};if(O)k.Properties.ContainerDefinitions[0].LogConfiguration={LogDriver:"awslogs",Options:{"awslogs-group":O,"awslogs-region":d.Ref("AWS::Region"),"awslogs-stream-prefix":J}};let u=I(`${w}-service`),b={Type:"AWS::ECS::Service",Properties:{ServiceName:w,Cluster:d.Ref(F),TaskDefinition:d.Ref(D),DesiredCount:Z,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{Subnets:X,SecurityGroups:j,AssignPublicIp:"ENABLED"}},Tags:[{Key:"Name",Value:w},{Key:"Environment",Value:Y}]}};if(q)b.Properties.LoadBalancers=[{TargetGroupArn:q,ContainerName:J,ContainerPort:z}];return{cluster:E,taskDefinition:k,service:b,taskRole:C,executionRole:S,clusterLogicalId:F,taskDefinitionLogicalId:D,serviceLogicalId:u,taskRoleLogicalId:R,executionRoleLogicalId:T}}static createLambdaFunction($){let{slug:J,environment:Y,runtime:Q,handler:W,code:U,timeout:Z=30,memorySize:z=128,environmentVariables:H={},vpcConfig:K}=$,B=h({slug:J,environment:Y,resourceType:"lambda"}),O=I(B),X=I(`${B}-role`),j={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]}};if(K)j.Properties.ManagedPolicyArns.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");let q={Type:"AWS::Lambda::Function",Properties:{FunctionName:B,Runtime:Q,Role:d.GetAtt(X,"Arn"),Handler:W,Code:{...U.s3Bucket&&{S3Bucket:U.s3Bucket},...U.s3Key&&{S3Key:U.s3Key},...U.zipFile&&{ZipFile:U.zipFile}},Timeout:Z,MemorySize:z,Tags:[{Key:"Name",Value:B},{Key:"Environment",Value:Y}]}};if(Object.keys(H).length>0)q.Properties.Environment={Variables:H};if(K)q.Properties.VpcConfig={SecurityGroupIds:K.securityGroupIds,SubnetIds:K.subnetIds};return{lambdaFunction:q,role:j,logicalId:O,roleLogicalId:X}}static generateNodeServerUserData($={}){let{nodeVersion:J="20",appRepo:Y,environment:Q={}}=$,W=Object.entries(Q).map(([U,Z])=>`echo "export ${U}='${Z}'" >> /etc/environment`).join(`
527
+ `);return`#!/bin/bash
528
+ # Update system
529
+ yum update -y
530
+
531
+ # Install Node.js ${J}
532
+ curl -fsSL https://rpm.nodesource.com/setup_${J}.x | bash -
533
+ yum install -y nodejs
534
+
535
+ # Install PM2 for process management
536
+ npm install -g pm2
537
+
538
+ # Install Caddy for reverse proxy and automatic HTTPS
539
+ yum install -y yum-plugin-copr
540
+ yum copr enable -y @caddy/caddy
541
+ yum install -y caddy
542
+
543
+ # Set environment variables
544
+ ${W}
545
+
546
+ # Clone application (if repo provided)
547
+ ${Y?`
548
+ cd /var/www
549
+ git clone ${Y} app
550
+ cd app
551
+ npm install
552
+ pm2 start npm --name 'app' -- start
553
+ pm2 save
554
+ pm2 startup systemd -u ec2-user --hp /home/ec2-user
555
+ `:"# No repository specified"}
556
+
557
+ # Configure Caddy
558
+ cat > /etc/caddy/Caddyfile <<'EOF'
559
+ :80 {
560
+ reverse_proxy localhost:3000
561
+ }
562
+ EOF
563
+
564
+ # Start Caddy
565
+ systemctl enable caddy
566
+ systemctl start caddy
567
+
568
+ echo "Server setup complete!"
569
+ `}static generateBunServerUserData($={}){let{appRepo:J,environment:Y={}}=$;return`#!/bin/bash
570
+ # Update system
571
+ yum update -y
572
+
573
+ # Install Bun
574
+ curl -fsSL https://bun.sh/install | bash
575
+ echo 'export BUN_INSTALL="/root/.bun"' >> /root/.bashrc
576
+ echo 'export PATH="$BUN_INSTALL/bin:$PATH"' >> /root/.bashrc
577
+ source /root/.bashrc
578
+
579
+ # Install Caddy
580
+ yum install -y yum-plugin-copr
581
+ yum copr enable -y @caddy/caddy
582
+ yum install -y caddy
583
+
584
+ # Set environment variables
585
+ ${Object.entries(Y).map(([W,U])=>`echo "export ${W}='${U}'" >> /etc/environment`).join(`
586
+ `)}
587
+
588
+ # Clone application (if repo provided)
589
+ ${J?`
590
+ cd /var/www
591
+ git clone ${J} app
592
+ cd app
593
+ bun install
594
+
595
+ # Create systemd service
596
+ cat > /etc/systemd/system/app.service <<'SERVICE'
597
+ [Unit]
598
+ Description=Bun Application
599
+ After=network.target
600
+
601
+ [Service]
602
+ Type=simple
603
+ User=root
604
+ WorkingDirectory=/var/www/app
605
+ ExecStart=/root/.bun/bin/bun run start
606
+ Restart=always
607
+
608
+ [Install]
609
+ WantedBy=multi-user.target
610
+ SERVICE
611
+
612
+ systemctl enable app
613
+ systemctl start app
614
+ `:"# No repository specified"}
615
+
616
+ # Configure Caddy
617
+ cat > /etc/caddy/Caddyfile <<'EOF'
618
+ :80 {
619
+ reverse_proxy localhost:3000
620
+ }
621
+ EOF
622
+
623
+ systemctl enable caddy
624
+ systemctl start caddy
625
+
626
+ echo "Bun server setup complete!"
627
+ `}static createLaunchConfiguration($){let{slug:J,environment:Y,imageId:Q,instanceType:W,keyName:U,securityGroups:Z,userData:z,volumeSize:H=20,volumeType:K="gp3",encrypted:B=!0,iamInstanceProfile:O}=$,X=h({slug:J,environment:Y,resourceType:"launch-config"}),j=I(X),q={Type:"AWS::AutoScaling::LaunchConfiguration",Properties:{ImageId:Q,InstanceType:W,BlockDeviceMappings:[{DeviceName:"/dev/xvda",Ebs:{VolumeSize:H,VolumeType:K,Encrypted:B,DeleteOnTermination:!0}}]}};if(U)q.Properties.KeyName=U;if(Z)q.Properties.SecurityGroups=Z;if(z)q.Properties.UserData=d.Base64(z);if(O)q.Properties.IamInstanceProfile=O;return{launchConfiguration:q,logicalId:j}}static createAutoScalingGroup($){let{slug:J,environment:Y,launchConfigurationName:Q,minSize:W,maxSize:U,desiredCapacity:Z,vpcZoneIdentifier:z,targetGroupArns:H,healthCheckType:K="EC2",healthCheckGracePeriod:B=300,cooldown:O=300,tags:X={}}=$,j=h({slug:J,environment:Y,resourceType:"asg"}),q=I(j),E={Type:"AWS::AutoScaling::AutoScalingGroup",Properties:{AutoScalingGroupName:j,LaunchConfigurationName:Q,MinSize:W,MaxSize:U,HealthCheckType:K,HealthCheckGracePeriod:B,Cooldown:O,Tags:[{Key:"Name",Value:j,PropagateAtLaunch:!0},{Key:"Environment",Value:Y,PropagateAtLaunch:!0},...Object.entries(X).map(([F,w])=>({Key:F,Value:w,PropagateAtLaunch:!0}))]}};if(Z!==void 0)E.Properties.DesiredCapacity=Z;if(z)E.Properties.VPCZoneIdentifier=z;if(H)E.Properties.TargetGroupARNs=H;return E.UpdatePolicy={AutoScalingRollingUpdate:{MaxBatchSize:1,MinInstancesInService:Math.max(0,W-1),PauseTime:"PT5M",WaitOnResourceSignals:!1}},{autoScalingGroup:E,logicalId:q}}static createScalingPolicy($){let{slug:J,environment:Y,autoScalingGroupName:Q,policyType:W="TargetTrackingScaling",targetValue:U=70,predefinedMetricType:Z="ASGAverageCPUUtilization"}=$,z=h({slug:J,environment:Y,resourceType:"scaling-policy"}),H=I(z),K={Type:"AWS::AutoScaling::ScalingPolicy",Properties:{AutoScalingGroupName:Q,PolicyType:W}};if(W==="TargetTrackingScaling")K.Properties.TargetTrackingConfiguration={PredefinedMetricSpecification:{PredefinedMetricType:Z},TargetValue:U};return{scalingPolicy:K,logicalId:H}}static AutoScaling={smallWebServer:($,J,Y,Q,W)=>{return a.createAutoScalingGroup({slug:$,environment:J,launchConfigurationName:Y,minSize:2,maxSize:4,desiredCapacity:2,vpcZoneIdentifier:Q,targetGroupArns:W,healthCheckType:W?"ELB":"EC2",healthCheckGracePeriod:300})},mediumWebServer:($,J,Y,Q,W)=>{return a.createAutoScalingGroup({slug:$,environment:J,launchConfigurationName:Y,minSize:3,maxSize:10,desiredCapacity:3,vpcZoneIdentifier:Q,targetGroupArns:W,healthCheckType:W?"ELB":"EC2",healthCheckGracePeriod:300})},largeWebServer:($,J,Y,Q,W)=>{return a.createAutoScalingGroup({slug:$,environment:J,launchConfigurationName:Y,minSize:5,maxSize:20,desiredCapacity:5,vpcZoneIdentifier:Q,targetGroupArns:W,healthCheckType:W?"ELB":"EC2",healthCheckGracePeriod:300})},cpuScaling:($,J,Y,Q=70)=>{return a.createScalingPolicy({slug:$,environment:J,autoScalingGroupName:Y,policyType:"TargetTrackingScaling",predefinedMetricType:"ASGAverageCPUUtilization",targetValue:Q})},requestCountScaling:($,J,Y,Q=1000)=>{return a.createScalingPolicy({slug:$,environment:J,autoScalingGroupName:Y,policyType:"TargetTrackingScaling",predefinedMetricType:"ALBRequestCountPerTarget",targetValue:Q})}};static Secrets={fromSecretsManager:($)=>{return Object.entries($).map(([J,Y])=>({name:J,valueFrom:Y}))},fromJsonSecret:($,J)=>{return`${$}:${J}::`},fromSecretVersion:($,J)=>{return`${$}::${J}:`},fromSecretVersionStage:($,J)=>{return`${$}:::${J}`},createAccessPolicy:($)=>({PolicyName:"SecretsManagerAccess",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue","secretsmanager:DescribeSecret"],Resource:$}]}}),createKmsPolicy:($)=>({PolicyName:"KMSDecryptAccess",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["kms:Decrypt"],Resource:$}]}}),buildSecretArn:($)=>{return`arn:aws:secretsmanager:${$.region}:${$.accountId}:secret:${$.secretName}`},buildSecretArnPattern:($)=>{let J=$.region||"*",Y=$.accountId||"*";return`arn:aws:secretsmanager:${J}:${Y}:secret:${$.secretNamePrefix}*`},commonAppSecrets:($)=>({DATABASE_URL:`${$}/database-url`,DATABASE_PASSWORD:`${$}/database-password`,REDIS_URL:`${$}/redis-url`,REDIS_PASSWORD:`${$}/redis-password`,API_KEY:`${$}/api-key`,JWT_SECRET:`${$}/jwt-secret`,ENCRYPTION_KEY:`${$}/encryption-key`,AWS_ACCESS_KEY_ID:`${$}/aws-access-key-id`,AWS_SECRET_ACCESS_KEY:`${$}/aws-secret-access-key`,MAIL_PASSWORD:`${$}/mail-password`,STRIPE_SECRET_KEY:`${$}/stripe-secret-key`,STRIPE_WEBHOOK_SECRET:`${$}/stripe-webhook-secret`})};static createFargateServiceWithSecrets($){let{secretArns:J=[],kmsKeyArns:Y=[],...Q}=$,W=a.createFargateService(Q);if(J.length>0){if(!W.executionRole.Properties.Policies)W.executionRole.Properties.Policies=[];if(W.executionRole.Properties.Policies.push(a.Secrets.createAccessPolicy(J)),Y.length>0)W.executionRole.Properties.Policies.push(a.Secrets.createKmsPolicy(Y))}return W}static generateSecretReferences($){return $.secrets.map((J)=>{let Y=`arn:aws:secretsmanager:${$.region}:${$.accountId}:secret:${$.secretPrefix}/${J}`;return{name:J.toUpperCase().replace(/-/g,"_"),valueFrom:Y}})}static EnvSecrets={database:($)=>[{name:"DB_HOST",valueFrom:`${$}:host::`},{name:"DB_PORT",valueFrom:`${$}:port::`},{name:"DB_USERNAME",valueFrom:`${$}:username::`},{name:"DB_PASSWORD",valueFrom:`${$}:password::`},{name:"DB_NAME",valueFrom:`${$}:dbname::`}],redis:($)=>[{name:"REDIS_HOST",valueFrom:`${$}:host::`},{name:"REDIS_PORT",valueFrom:`${$}:port::`},{name:"REDIS_PASSWORD",valueFrom:`${$}:password::`}],apiCredentials:($)=>[{name:"API_KEY",valueFrom:`${$}:apiKey::`},{name:"API_SECRET",valueFrom:`${$}:apiSecret::`}],mail:($)=>[{name:"MAIL_HOST",valueFrom:`${$}:host::`},{name:"MAIL_PORT",valueFrom:`${$}:port::`},{name:"MAIL_USERNAME",valueFrom:`${$}:username::`},{name:"MAIL_PASSWORD",valueFrom:`${$}:password::`}],awsCredentials:($)=>[{name:"AWS_ACCESS_KEY_ID",valueFrom:`${$}:accessKeyId::`},{name:"AWS_SECRET_ACCESS_KEY",valueFrom:`${$}:secretAccessKey::`}]};static createJumpBox($){let{slug:J,environment:Y,vpcId:Q,subnetId:W,keyName:U,instanceType:Z="t3.micro",imageId:z="ami-0c55b159cbfafe1f0",allowedCidrs:H=["0.0.0.0/0"],mountEfs:K}=$,B=h({slug:J,environment:Y,resourceType:"jumpbox"}),O=I(`${B}-sg`),X={Type:"AWS::EC2::SecurityGroup",Properties:{GroupName:`${B}-sg`,GroupDescription:`Security group for ${B} JumpBox SSH access`,VpcId:Q,SecurityGroupIngress:H.map((C)=>({IpProtocol:"tcp",FromPort:22,ToPort:22,CidrIp:C,Description:`SSH access from ${C}`})),SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound traffic"}],Tags:[{Key:"Name",Value:`${B}-sg`},{Key:"Environment",Value:Y}]}},j=I(`${B}-role`),q={Type:"AWS::IAM::Role",Properties:{RoleName:`${B}-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ec2.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"],Policies:K?[{PolicyName:"EFSAccess",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:ClientRootAccess"],Resource:"*"}]}}]:void 0}},E=I(`${B}-profile`),F={Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:`${B}-profile`,Roles:[d.Ref(j)]}},w=`#!/bin/bash
628
+ yum update -y
629
+ yum install -y amazon-efs-utils nfs-utils jq curl wget htop
630
+ `;if(K){let C=K.mountPath||"/mnt/efs";w+=`
631
+ # Mount EFS
632
+ mkdir -p ${C}
633
+ mount -t efs ${K.fileSystemId}:/ ${C}
634
+ echo "${K.fileSystemId}:/ ${C} efs defaults,_netdev 0 0" >> /etc/fstab
635
+ `}let T=I(B),S={Type:"AWS::EC2::Instance",DependsOn:[E],Properties:{ImageId:z,InstanceType:Z,KeyName:U,SubnetId:W,SecurityGroupIds:[d.Ref(O)],IamInstanceProfile:d.Ref(E),UserData:d.Base64(w),BlockDeviceMappings:[{DeviceName:"/dev/xvda",Ebs:{VolumeSize:20,VolumeType:"gp3",Encrypted:!0,DeleteOnTermination:!0}}],Tags:[{Key:"Name",Value:B},{Key:"Environment",Value:Y},{Key:"Purpose",Value:"JumpBox/Bastion"}]}},R={[O]:X,[j]:q,[E]:F,[T]:S};return{instance:S,securityGroup:X,instanceProfile:F,instanceRole:q,instanceLogicalId:T,securityGroupLogicalId:O,instanceProfileLogicalId:E,instanceRoleLogicalId:j,resources:R}}static JumpBox={withEfsMount:($)=>{return a.createJumpBox({slug:$.slug,environment:$.environment,vpcId:$.vpcId,subnetId:$.subnetId,keyName:$.keyName,allowedCidrs:$.allowedCidrs,mountEfs:{fileSystemId:$.fileSystemId,mountPath:$.mountPath||"/mnt/efs"}})},minimal:($)=>{return a.createJumpBox({slug:$.slug,environment:$.environment,vpcId:$.vpcId,subnetId:$.subnetId,keyName:$.keyName,instanceType:"t3.nano",allowedCidrs:$.allowedCidrs})},withDatabaseTools:($)=>{let J=a.createJumpBox({slug:$.slug,environment:$.environment,vpcId:$.vpcId,subnetId:$.subnetId,keyName:$.keyName,allowedCidrs:$.allowedCidrs}),Y=`#!/bin/bash
636
+ yum update -y
637
+ yum install -y amazon-efs-utils nfs-utils jq curl wget htop
638
+
639
+ # Install PostgreSQL client
640
+ amazon-linux-extras install postgresql14 -y
641
+
642
+ # Install MySQL client
643
+ yum install -y mysql
644
+
645
+ # Install Redis CLI
646
+ yum install -y redis
647
+
648
+ echo "Database tools installed!"
649
+ `;return J.instance.Properties.UserData=d.Base64(`#!/bin/bash
650
+ yum update -y
651
+ yum install -y amazon-efs-utils nfs-utils jq curl wget htop
652
+
653
+ # Install PostgreSQL client
654
+ amazon-linux-extras install postgresql14 -y
655
+
656
+ # Install MySQL client
657
+ yum install -y mysql
658
+
659
+ # Install Redis CLI
660
+ yum install -y redis
661
+
662
+ echo "Database tools installed!"
663
+ `),J},commonCidrs:{any:["0.0.0.0/0"],privateOnly:["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"]}};static InstanceSize={toInstanceType:($,J="t3")=>{return`${J}.${$}`},specs:{nano:{vcpu:2,memory:0.5,instanceType:"t3.nano"},micro:{vcpu:2,memory:1,instanceType:"t3.micro"},small:{vcpu:2,memory:2,instanceType:"t3.small"},medium:{vcpu:2,memory:4,instanceType:"t3.medium"},large:{vcpu:2,memory:8,instanceType:"t3.large"},xlarge:{vcpu:4,memory:16,instanceType:"t3.xlarge"},"2xlarge":{vcpu:8,memory:32,instanceType:"t3.2xlarge"}},toFargateSpecs:($)=>{let J={nano:{cpu:"256",memory:"512"},micro:{cpu:"256",memory:"1024"},small:{cpu:"512",memory:"1024"},medium:{cpu:"1024",memory:"2048"},large:{cpu:"2048",memory:"4096"},xlarge:{cpu:"4096",memory:"8192"},"2xlarge":{cpu:"4096",memory:"16384"}};return J[$]||J.medium},toLambdaMemory:($)=>{return{nano:128,micro:256,small:512,medium:1024,large:2048,xlarge:4096,"2xlarge":8192}[$]||1024},presets:{webServer:"t3.small",apiServer:"t3.medium",worker:"t3.medium",database:"r6i.large",cache:"r6i.medium",compute:"c6i.large",general:"m6i.medium"}};static DiskConfig={create:($)=>{let{size:J,type:Y="ssd",encrypted:Q=!0,iops:W,throughput:U,deleteOnTermination:Z=!0}=$,H={standard:"gp2",ssd:"gp3",premium:"io2",gp2:"gp2",gp3:"gp3",io1:"io1",io2:"io2"}[Y]||"gp3",K={VolumeSize:J,VolumeType:H,Encrypted:Q,DeleteOnTermination:Z};if((H==="io1"||H==="io2"||H==="gp3")&&W)K.Iops=W;if(H==="gp3"&&U)K.Throughput=U;return K},presets:{standard:{VolumeSize:20,VolumeType:"gp3",Encrypted:!0,DeleteOnTermination:!0},large:{VolumeSize:100,VolumeType:"gp3",Encrypted:!0,DeleteOnTermination:!0},highPerformance:{VolumeSize:50,VolumeType:"io2",Iops:3000,Encrypted:!0,DeleteOnTermination:!0},database:{VolumeSize:100,VolumeType:"io2",Iops:1e4,Encrypted:!0,DeleteOnTermination:!1}}};static SpotConfig={create:($)=>{let{maxPrice:J,spotInstanceType:Y="one-time",interruptionBehavior:Q="terminate",blockDurationMinutes:W}=$,U={SpotInstanceType:Y,InstanceInterruptionBehavior:Q};if(J)U.MaxPrice=J;if(W)U.BlockDurationMinutes=W;return{SpotOptions:U}},presets:{standard:{spotInstanceType:"one-time",interruptionBehavior:"terminate"},persistent:{spotInstanceType:"persistent",interruptionBehavior:"stop"},costOptimized:{maxPrice:"0.05",spotInstanceType:"one-time",interruptionBehavior:"terminate"}}};static MixedInstances={create:($)=>{let{instanceTypes:J,baseCapacity:Y=0,onDemandPercentage:Q=20,spotAllocationStrategy:W="capacity-optimized",spotMaxPrice:U}=$,Z={OnDemandBaseCapacity:Y,OnDemandPercentageAboveBaseCapacity:Q,SpotAllocationStrategy:W};if(U)Z.SpotMaxPrice=U;let z=J.map(({size:H,weight:K})=>{let B={InstanceType:a.InstanceSize.toInstanceType(H)};if(K)B.WeightedCapacity=String(K);return B});return{MixedInstancesPolicy:{InstancesDistribution:Z,LaunchTemplate:{Overrides:z}}}},presets:{costOptimized:{baseCapacity:0,onDemandPercentage:20,spotAllocationStrategy:"lowest-price",instanceTypes:[{size:"small",weight:1},{size:"medium",weight:2}]},balanced:{baseCapacity:1,onDemandPercentage:50,spotAllocationStrategy:"capacity-optimized",instanceTypes:[{size:"medium",weight:1},{size:"large",weight:2}]},highAvailability:{baseCapacity:2,onDemandPercentage:80,spotAllocationStrategy:"capacity-optimized-prioritized",instanceTypes:[{size:"medium",weight:1}]}}};static AutoScalingConfig={create:($)=>{let{min:J,max:Y,desired:Q=J,scaleUpThreshold:W=70,scaleDownThreshold:U=30,cooldownSeconds:Z=300,targetMetric:z="cpu"}=$,H={cpu:"ASGAverageCPUUtilization",memory:"ASGAverageMemoryUtilization",requests:"ALBRequestCountPerTarget"};return{minSize:J,maxSize:Y,desiredCapacity:Q,scalingPolicies:[{policyType:"TargetTrackingScaling",targetValue:W,predefinedMetricType:H[z]||H.cpu,scaleInCooldown:Z,scaleOutCooldown:Z}]}},forEcs:($)=>{let{min:J,max:Y,cpuTarget:Q=70,memoryTarget:W}=$,U=[{predefinedMetricType:"ECSServiceAverageCPUUtilization",targetValue:Q}];if(W)U.push({predefinedMetricType:"ECSServiceAverageMemoryUtilization",targetValue:W});return{minCapacity:J,maxCapacity:Y,targetTrackingPolicies:U}},presets:{small:{min:1,max:3,scaleUpThreshold:70,scaleDownThreshold:30},medium:{min:2,max:10,scaleUpThreshold:70,scaleDownThreshold:30},large:{min:3,max:50,scaleUpThreshold:60,scaleDownThreshold:40},highAvailability:{min:2,max:20,scaleUpThreshold:60,scaleDownThreshold:30}}};static LoadBalancerConfig={healthCheck:($)=>{let{path:J="/",interval:Y=30,timeout:Q=5,healthyThreshold:W=2,unhealthyThreshold:U=5,protocol:Z="HTTP"}=$,z={HealthCheckIntervalSeconds:Y,HealthCheckTimeoutSeconds:Q,HealthyThresholdCount:W,UnhealthyThresholdCount:U};if(Z!=="TCP")z.HealthCheckPath=J,z.HealthCheckProtocol=Z;return z},presets:{standard:{path:"/health",interval:30,timeout:5,healthyThreshold:2,unhealthyThreshold:5},fast:{path:"/health",interval:10,timeout:3,healthyThreshold:2,unhealthyThreshold:2},relaxed:{path:"/health",interval:60,timeout:30,healthyThreshold:2,unhealthyThreshold:10}}};static SslConfig={httpsListener:($)=>{let{certificateArn:J,targetGroupArn:Y,port:Q=443,sslPolicy:W="ELBSecurityPolicy-TLS13-1-2-2021-06"}=$;return{Port:Q,Protocol:"HTTPS",Certificates:[{CertificateArn:J}],SslPolicy:W,DefaultActions:[{Type:"forward",TargetGroupArn:Y}]}},httpRedirectListener:($=80)=>({Port:$,Protocol:"HTTP",DefaultActions:[{Type:"redirect",RedirectConfig:{Protocol:"HTTPS",Port:"443",StatusCode:"HTTP_301"}}]}),policies:{tls13:"ELBSecurityPolicy-TLS13-1-2-2021-06",tls12:"ELBSecurityPolicy-TLS-1-2-Ext-2018-06",tls11:"ELBSecurityPolicy-TLS-1-1-2017-01",fips:"ELBSecurityPolicy-TLS-1-2-Ext-FIPS-2022-05"}};static FunctionConfig={create:($)=>{let{handler:J,runtime:Y="nodejs20.x",timeout:Q=30,memorySize:W=256,environmentVariables:U,reservedConcurrency:Z}=$,z={Handler:J,Runtime:Y,Timeout:Q,MemorySize:W};if(U)z.Environment={Variables:U};if(Z)z.ReservedConcurrentExecutions=Z;return z},runtimes:{nodejs20:"nodejs20.x",nodejs18:"nodejs18.x",python312:"python3.12",python311:"python3.11",java21:"java21",java17:"java17",go:"provided.al2023",rust:"provided.al2023"},presets:{api:{runtime:"nodejs20.x",timeout:30,memorySize:256},worker:{runtime:"nodejs20.x",timeout:300,memorySize:512},cron:{runtime:"nodejs20.x",timeout:900,memorySize:1024},dataProcessing:{runtime:"nodejs20.x",timeout:900,memorySize:3008}}};static UserData={generateAppServerScript:($)=>{let{runtime:J="bun",runtimeVersion:Y="latest",webServer:Q="nginx",processManager:W="systemd",enableSsl:U=!0,sslEmail:Z="admin@example.com",domain:z,appPort:H=3000,installDatabaseClients:K=!1,installRedis:B=!1,extraPackages:O=[]}=$,X=`#!/bin/bash
664
+ set -e
665
+
666
+ # Update system
667
+ export DEBIAN_FRONTEND=noninteractive
668
+ apt-get update && apt-get upgrade -y
669
+
670
+ # Install basic tools
671
+ apt-get install -y curl wget git jq htop unzip
672
+
673
+ `;if(J==="bun")X+=a.UserData.Scripts.bun(Y);else X+=a.UserData.Scripts.nodeJs(Y);if(Q==="nginx"){if(X+=a.UserData.Scripts.nginx(),z&&U)X+=a.UserData.Scripts.nginxProxy(z,H)}else if(Q==="caddy"){if(X+=a.UserData.Scripts.caddy(),z)X+=a.UserData.Scripts.caddyProxy(z,H)}if(W==="pm2"&&J==="node")X+=a.UserData.Scripts.pm2();if(U&&Q==="nginx"&&z)X+=a.UserData.Scripts.letsEncrypt(z,Z);if(K)X+=a.UserData.Scripts.databaseClients();if(B)X+=a.UserData.Scripts.redis();if(O.length>0)X+=`
674
+ # Install extra packages
675
+ apt-get install -y ${O.join(" ")}
676
+ `;return X+=`
677
+ echo "Server setup complete!"
678
+ `,X},Scripts:{bun:($="latest")=>`
679
+ # Install Bun
680
+ curl -fsSL https://bun.sh/install | bash
681
+ export BUN_INSTALL="$HOME/.bun"
682
+ export PATH="$BUN_INSTALL/bin:$PATH"
683
+ echo 'export BUN_INSTALL="$HOME/.bun"' >> /etc/profile.d/bun.sh
684
+ echo 'export PATH="$BUN_INSTALL/bin:$PATH"' >> /etc/profile.d/bun.sh
685
+ ${$!=="latest"?`bun upgrade --version ${$}`:""}
686
+ bun --version
687
+ `,nodeJs:($="20")=>`
688
+ # Install Node.js via nvm
689
+ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
690
+ export NVM_DIR="$HOME/.nvm"
691
+ [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
692
+ nvm install ${$}
693
+ nvm use ${$}
694
+ nvm alias default ${$}
695
+ echo 'export NVM_DIR="$HOME/.nvm"' >> /etc/profile.d/nvm.sh
696
+ echo '[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"' >> /etc/profile.d/nvm.sh
697
+ node --version
698
+ npm --version
699
+ `,nginx:()=>`
700
+ # Install Nginx
701
+ apt-get install -y nginx
702
+ systemctl enable nginx
703
+ systemctl start nginx
704
+ `,nginxProxy:($,J=3000)=>`
705
+ # Configure Nginx reverse proxy
706
+ cat > /etc/nginx/sites-available/${$} << 'NGINX_CONFIG'
707
+ server {
708
+ listen 80;
709
+ server_name ${$};
710
+
711
+ location / {
712
+ proxy_pass http://127.0.0.1:${J};
713
+ proxy_http_version 1.1;
714
+ proxy_set_header Upgrade $http_upgrade;
715
+ proxy_set_header Connection 'upgrade';
716
+ proxy_set_header Host $host;
717
+ proxy_set_header X-Real-IP $remote_addr;
718
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
719
+ proxy_set_header X-Forwarded-Proto $scheme;
720
+ proxy_cache_bypass $http_upgrade;
721
+ }
722
+ }
723
+ NGINX_CONFIG
724
+
725
+ ln -sf /etc/nginx/sites-available/${$} /etc/nginx/sites-enabled/
726
+ rm -f /etc/nginx/sites-enabled/default
727
+ nginx -t && systemctl reload nginx
728
+ `,caddy:()=>`
729
+ # Install Caddy
730
+ apt-get install -y debian-keyring debian-archive-keyring apt-transport-https
731
+ curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
732
+ curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | tee /etc/apt/sources.list.d/caddy-stable.list
733
+ apt-get update
734
+ apt-get install -y caddy
735
+ systemctl enable caddy
736
+ `,caddyProxy:($,J=3000)=>`
737
+ # Configure Caddy reverse proxy
738
+ cat > /etc/caddy/Caddyfile << 'CADDY_CONFIG'
739
+ ${$} {
740
+ reverse_proxy localhost:${J}
741
+ }
742
+ CADDY_CONFIG
743
+
744
+ systemctl restart caddy
745
+ `,pm2:()=>`
746
+ # Install PM2
747
+ npm install -g pm2
748
+ pm2 startup systemd -u root --hp /root
749
+ `,letsEncrypt:($,J,Y=!1)=>`
750
+ # Install Certbot
751
+ apt-get install -y certbot python3-certbot-nginx
752
+ # Obtain SSL certificate
753
+ certbot --nginx -d ${$} --non-interactive --agree-tos -m ${J} ${Y?"--staging":""}
754
+ # Setup auto-renewal
755
+ echo "0 0 * * * root certbot renew --quiet" > /etc/cron.d/certbot-renew
756
+ `,databaseClients:()=>`
757
+ # Install database clients
758
+ apt-get install -y postgresql-client mysql-client
759
+ `,redis:()=>`
760
+ # Install Redis
761
+ apt-get install -y redis-server redis-tools
762
+ systemctl enable redis-server
763
+ systemctl start redis-server
764
+ `,systemdService:($)=>{let{serviceName:J,description:Y,workingDirectory:Q,execStart:W,user:U="root",environmentVars:Z={}}=$,z=Object.entries(Z).map(([H,K])=>`Environment="${H}=${K}"`).join(`
765
+ `);return`
766
+ # Create systemd service for ${J}
767
+ cat > /etc/systemd/system/${J}.service << 'SERVICE_FILE'
768
+ [Unit]
769
+ Description=${Y}
770
+ After=network.target
771
+
772
+ [Service]
773
+ Type=simple
774
+ User=${U}
775
+ WorkingDirectory=${Q}
776
+ ExecStart=${W}
777
+ Restart=on-failure
778
+ RestartSec=10
779
+ StandardOutput=syslog
780
+ StandardError=syslog
781
+ SyslogIdentifier=${J}
782
+ ${z}
783
+
784
+ [Install]
785
+ WantedBy=multi-user.target
786
+ SERVICE_FILE
787
+
788
+ systemctl daemon-reload
789
+ systemctl enable ${J}
790
+ systemctl start ${J}
791
+ `},swapFile:($=2)=>`
792
+ # Setup swap file
793
+ fallocate -l ${$}G /swapfile
794
+ chmod 600 /swapfile
795
+ mkswap /swapfile
796
+ swapon /swapfile
797
+ echo '/swapfile none swap sw 0 0' >> /etc/fstab
798
+ `,firewall:($=[22,80,443])=>`
799
+ # Setup firewall
800
+ apt-get install -y ufw
801
+ ufw default deny incoming
802
+ ufw default allow outgoing
803
+ ${$.map((J)=>`ufw allow ${J}`).join(`
804
+ `)}
805
+ ufw --force enable
806
+ `},Presets:{bunWithNginx:($,J=3000)=>a.UserData.generateAppServerScript({runtime:"bun",webServer:"nginx",processManager:"systemd",domain:$,appPort:J,enableSsl:!0}),bunWithCaddy:($,J=3000)=>a.UserData.generateAppServerScript({runtime:"bun",webServer:"caddy",processManager:"systemd",domain:$,appPort:J,enableSsl:!1}),nodeWithPm2:($,J=3000)=>a.UserData.generateAppServerScript({runtime:"node",webServer:"nginx",processManager:"pm2",domain:$,appPort:J,enableSsl:!0}),worker:($="bun")=>a.UserData.generateAppServerScript({runtime:$,webServer:"none",processManager:"systemd",enableSsl:!1})}};static createElasticIp($){let{slug:J,environment:Y,domain:Q,instanceLogicalId:W}=$,U=h({slug:J,environment:Y,resourceType:"eip"}),Z=I(U),z={Type:"AWS::EC2::EIP",Properties:{Domain:"vpc",Tags:[{Key:"Name",Value:U},{Key:"Environment",Value:Y},...Q?[{Key:"Domain",Value:Q}]:[]]}},H={[Z]:z},K,B;if(W)B=I(`${U}-assoc`),K={Type:"AWS::EC2::EIPAssociation",Properties:{AllocationId:d.GetAtt(Z,"AllocationId"),InstanceId:d.Ref(W)}},H[B]=K;return{eip:z,eipAssociation:K,eipLogicalId:Z,associationLogicalId:B,resources:H}}static createServerModeStack($){let{slug:J,environment:Y,vpcId:Q,subnetId:W,instanceType:U="t3.small",imageId:Z="ami-0c55b159cbfafe1f0",keyName:z,domain:H,userData:K,allowedPorts:B=[22,80,443],volumeSize:O=20,volumeType:X="gp3"}=$,j={},q=h({slug:J,environment:Y,resourceType:"server-sg"}),E=I(q),F={Type:"AWS::EC2::SecurityGroup",Properties:{GroupName:q,GroupDescription:`Security group for ${J} server`,VpcId:Q,SecurityGroupIngress:B.map((n)=>({IpProtocol:"tcp",FromPort:n,ToPort:n,CidrIp:"0.0.0.0/0",Description:`Port ${n}`})),SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:q},{Key:"Environment",Value:Y}]}};j[E]=F;let w=h({slug:J,environment:Y,resourceType:"server-role"}),T=I(w),S={Type:"AWS::IAM::Role",Properties:{RoleName:w,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ec2.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore","arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy"]}};j[T]=S;let R=h({slug:J,environment:Y,resourceType:"server-profile"}),C=I(R),D={Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:R,Roles:[d.Ref(T)]}};j[C]=D;let k=h({slug:J,environment:Y,resourceType:"server"}),u=I(k),b={Type:"AWS::EC2::Instance",DependsOn:[C],Properties:{ImageId:Z,InstanceType:U,KeyName:z,SubnetId:W,SecurityGroupIds:[d.Ref(E)],IamInstanceProfile:d.Ref(C),BlockDeviceMappings:[{DeviceName:"/dev/xvda",Ebs:{VolumeSize:O,VolumeType:X,Encrypted:!0,DeleteOnTermination:!0}}],Tags:[{Key:"Name",Value:k},{Key:"Environment",Value:Y},...H?[{Key:"Domain",Value:H}]:[]]}};if(K)b.Properties.UserData=d.Base64(K);j[u]=b;let{eip:v,eipAssociation:y,eipLogicalId:f,associationLogicalId:m,resources:t}=a.createElasticIp({slug:J,environment:Y,domain:H,instanceLogicalId:u});return Object.assign(j,t),{instance:b,securityGroup:F,eip:v,eipAssociation:y,instanceRole:S,instanceProfile:D,resources:j,outputs:{instanceLogicalId:u,securityGroupLogicalId:E,eipLogicalId:f,associationLogicalId:m,roleLogicalId:T,profileLogicalId:C}}}static ServerMode={webServer:($)=>{let J=a.UserData.generateAppServerScript({runtime:$.runtime||"bun",webServer:$.webServer||"nginx",domain:$.domain,enableSsl:!0});return a.createServerModeStack({...$,userData:J,instanceType:"t3.small",allowedPorts:[22,80,443]})},workerServer:($)=>{let J=a.UserData.generateAppServerScript({runtime:$.runtime||"bun",webServer:"none",installRedis:$.installRedis});return a.createServerModeStack({...$,userData:J,instanceType:"t3.medium",allowedPorts:[22]})},cacheServer:($)=>{return a.createServerModeStack({...$,userData:`#!/bin/bash
807
+ set -e
808
+ apt-get update && apt-get upgrade -y
809
+ apt-get install -y redis-server
810
+ sed -i 's/bind 127.0.0.1/bind 0.0.0.0/' /etc/redis/redis.conf
811
+ systemctl enable redis-server
812
+ systemctl restart redis-server
813
+ echo "Redis server setup complete!"
814
+ `,instanceType:"t3.medium",allowedPorts:[22,6379]})}}}class x${static createQueue($){let{slug:J,environment:Y,name:Q,delaySeconds:W=0,visibilityTimeout:U=30,messageRetentionPeriod:Z=345600,maxMessageSize:z=262144,receiveMessageWaitTime:H=0,fifo:K=!1,contentBasedDeduplication:B=!1,encrypted:O=!0,kmsKeyId:X}=$,j=Q||h({slug:J,environment:Y,resourceType:"queue"}),q=K?`${j}.fifo`:j,E=I(j),F={Type:"AWS::SQS::Queue",Properties:{QueueName:q,DelaySeconds:W,MaximumMessageSize:z,MessageRetentionPeriod:Z,ReceiveMessageWaitTimeSeconds:H,VisibilityTimeout:U,Tags:[{Key:"Name",Value:q},{Key:"Environment",Value:Y}]}};if(K)F.Properties.FifoQueue=!0,F.Properties.ContentBasedDeduplication=B;if(O)if(X)F.Properties.KmsMasterKeyId=X;else F.Properties.SqsManagedSseEnabled=!0;return{queue:F,logicalId:E}}static createDeadLetterQueue($,J){let{slug:Y,environment:Q,maxReceiveCount:W=3}=J,U=h({slug:Y,environment:Q,resourceType:"dlq"}),Z=I(U),z={Type:"AWS::SQS::Queue",Properties:{QueueName:U,MessageRetentionPeriod:1209600,Tags:[{Key:"Name",Value:U},{Key:"Environment",Value:Q},{Key:"Type",Value:"DeadLetterQueue"}]}},H={Type:"AWS::SQS::Queue",Properties:{RedrivePolicy:{deadLetterTargetArn:d.GetAtt(Z,"Arn"),maxReceiveCount:W}}};return{deadLetterQueue:z,updatedSourceQueue:H,deadLetterLogicalId:Z}}static createSchedule($,J){let{slug:Y,environment:Q,name:W,description:U,enabled:Z=!0}=J,z=W||h({slug:Y,environment:Q,resourceType:"schedule"}),H=I(z);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:z,Description:U,ScheduleExpression:$,State:Z?"ENABLED":"DISABLED",Targets:[]}},logicalId:H}}static scheduleEcsTask($,J,Y){let{slug:Q,environment:W,name:U,description:Z,enabled:z=!0,taskDefinitionArn:H,clusterArn:K,subnets:B,securityGroups:O=[],assignPublicIp:X=!1,taskCount:j=1,containerOverrides:q}=Y,E=U||h({slug:Q,environment:W,resourceType:"ecs-schedule"}),F=I(E),T={Id:"1",Arn:K,RoleArn:J,EcsParameters:{TaskDefinitionArn:H,TaskCount:j,LaunchType:"FARGATE",NetworkConfiguration:{awsvpcConfiguration:{Subnets:B,SecurityGroups:O,AssignPublicIp:X?"ENABLED":"DISABLED"}},PlatformVersion:"LATEST"}};if(q&&q.length>0)T.Input=JSON.stringify({containerOverrides:q});return{rule:{Type:"AWS::Events::Rule",Properties:{Name:E,Description:Z||`Scheduled ECS task: ${H}`,ScheduleExpression:$,State:z?"ENABLED":"DISABLED",Targets:[T]}},logicalId:F}}static scheduleLambda($,J){let{slug:Y,environment:Q,name:W,description:U,enabled:Z=!0,functionArn:z,input:H}=J,K=W||h({slug:Y,environment:Q,resourceType:"lambda-schedule"}),B=I(K),O={Id:"1",Arn:z};if(H)O.Input=JSON.stringify(H);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:K,Description:U||`Scheduled Lambda: ${z}`,ScheduleExpression:$,State:Z?"ENABLED":"DISABLED",Targets:[O]}},logicalId:B}}static scheduleSqsMessage($,J){let{slug:Y,environment:Q,name:W,description:U,enabled:Z=!0,queueArn:z,messageGroupId:H}=J,K=W||h({slug:Y,environment:Q,resourceType:"sqs-schedule"}),B=I(K),O={Id:"1",Arn:z};if(H)O.SqsParameters={MessageGroupId:H};return{rule:{Type:"AWS::Events::Rule",Properties:{Name:K,Description:U||`Scheduled SQS message: ${z}`,ScheduleExpression:$,State:Z?"ENABLED":"DISABLED",Targets:[O]}},logicalId:B}}static addTarget($,J){if(!$.Properties.Targets)$.Properties.Targets=[];let Y={Id:J.id,Arn:J.arn};if(J.roleArn)Y.RoleArn=J.roleArn;if(J.input)Y.Input=JSON.stringify(J.input);return $.Properties.Targets.push(Y),$}static toCronExpression($){if($.startsWith("cron(")||$.startsWith("rate("))return $;return`cron(${$})`}static rateExpression($,J){return`rate(${$} ${J})`}static CronExpressions={EveryMinute:"cron(* * * * ? *)",Every5Minutes:"cron(*/5 * * * ? *)",Every15Minutes:"cron(*/15 * * * ? *)",Every30Minutes:"cron(*/30 * * * ? *)",Hourly:"cron(0 * * * ? *)",Daily:"cron(0 0 * * ? *)",DailyAt9AM:"cron(0 9 * * ? *)",DailyAtMidnight:"cron(0 0 * * ? *)",Weekly:"cron(0 0 ? * SUN *)",Monthly:"cron(0 0 1 * ? *)"};static RateExpressions={Every1Minute:"rate(1 minute)",Every5Minutes:"rate(5 minutes)",Every10Minutes:"rate(10 minutes)",Every15Minutes:"rate(15 minutes)",Every30Minutes:"rate(30 minutes)",Every1Hour:"rate(1 hour)",Every6Hours:"rate(6 hours)",Every12Hours:"rate(12 hours)",Every1Day:"rate(1 day)"};static rateStringToExpression($){let J=$.toLowerCase().trim(),Y=J.match(/^every\s+(\d+)\s+(minute|minutes|hour|hours|day|days)$/i);if(Y){let K=parseInt(Y[1],10),B=Y[2].toLowerCase(),O=B.endsWith("s")&&K===1?B.slice(0,-1):B,X=!B.endsWith("s")&&K>1?`${B}s`:B;return`rate(${K} ${K===1?O:X})`}let Q=J.match(/^every\s+(minute|hour|day)$/i);if(Q)return`rate(1 ${Q[1]})`;let W={"every minute":"rate(1 minute)","every hour":"rate(1 hour)","every day":"rate(1 day)",hourly:"cron(0 * * * ? *)",daily:"cron(0 0 * * ? *)","daily at midnight":"cron(0 0 * * ? *)",weekly:"cron(0 0 ? * SUN *)",monthly:"cron(0 0 1 * ? *)",yearly:"cron(0 0 1 1 ? *)"};if(W[J])return W[J];let U=J.match(/^daily\s+at\s+(\d{1,2})\s*(am|pm)?$/i);if(U){let K=parseInt(U[1],10),B=U[2]?.toLowerCase();if(B==="pm"&&K!==12)K+=12;else if(B==="am"&&K===12)K=0;return`cron(0 ${K} * * ? *)`}let Z=J.match(/^at\s+(\d{1,2}):(\d{2})$/i);if(Z){let K=parseInt(Z[1],10);return`cron(${parseInt(Z[2],10)} ${K} * * ? *)`}let z={monday:"MON",tuesday:"TUE",wednesday:"WED",thursday:"THU",friday:"FRI",saturday:"SAT",sunday:"SUN"},H=J.match(/^every\s+(monday|tuesday|wednesday|thursday|friday|saturday|sunday)$/i);if(H)return`cron(0 0 ? * ${z[H[1].toLowerCase()]} *)`;return x$.toCronExpression($)}static JobConfig={create:($)=>{let{name:J,handler:Y,retries:Q=3,backoff:W="exponential",backoffDelay:U=1000,maxDelay:Z=30000,timeout:z=60000,jitter:H=!0}=$;return{name:J,handler:Y,retries:Q,backoff:W,backoffDelay:U,maxDelay:Z,timeout:z,jitter:H}},calculateDelay:($,J)=>{let{backoff:Y,backoffDelay:Q,maxDelay:W,jitter:U}=J,Z;switch(Y){case"linear":Z=Q*$;break;case"exponential":Z=Q*2**($-1);break;case"fixed":default:Z=Q}if(Z=Math.min(Z,W||Number.MAX_SAFE_INTEGER),U){let z=Z*0.25*Math.random();Z+=z}return Math.floor(Z)},presets:{fastRetry:{retries:5,backoff:"exponential",backoffDelay:100,maxDelay:5000,jitter:!0},standard:{retries:3,backoff:"exponential",backoffDelay:1000,maxDelay:30000,jitter:!0},longRunning:{retries:2,backoff:"exponential",backoffDelay:5000,maxDelay:60000,timeout:300000,jitter:!0},critical:{retries:10,backoff:"exponential",backoffDelay:500,maxDelay:60000,jitter:!0},noRetry:{retries:0,backoff:"fixed",backoffDelay:0,maxDelay:0,jitter:!1}}};static createJobContainerOverride($){let{containerName:J,jobClass:Y,jobData:Q,environment:W={}}=$,U=[{name:"JOB_CLASS",value:Y}];if(Q)U.push({name:"JOB_DATA",value:JSON.stringify(Q)});for(let[Z,z]of Object.entries(W))U.push({name:Z,value:z});return{name:J,command:["bun","run","app/Jobs/runner.ts"],environment:U}}static createScheduledJob($){let{slug:J,environment:Y,schedule:Q,jobClass:W,jobData:U,taskDefinitionArn:Z,clusterArn:z,subnets:H,securityGroups:K=[],roleArn:B,containerName:O="app"}=$,X=x$.rateStringToExpression(Q),j=x$.createJobContainerOverride({containerName:O,jobClass:W,jobData:U});return x$.scheduleEcsTask(X,B,{slug:J,environment:Y,name:`${J}-${W.toLowerCase().replace(/[^a-z0-9]/g,"-")}`,description:`Scheduled job: ${W}`,taskDefinitionArn:Z,clusterArn:z,subnets:H,securityGroups:K,containerOverrides:[j]})}static QueuePresets={highThroughput:($,J)=>x$.createQueue({slug:$,environment:J,visibilityTimeout:30,receiveMessageWaitTime:0,delaySeconds:0}),longRunning:($,J)=>x$.createQueue({slug:$,environment:J,visibilityTimeout:300,messageRetentionPeriod:1209600}),fifo:($,J)=>x$.createQueue({slug:$,environment:J,fifo:!0,contentBasedDeduplication:!0}),delayed:($,J,Y=60)=>x$.createQueue({slug:$,environment:J,delaySeconds:Y})}}class q0{static async discoverJobs($){let{projectRoot:J,jobsPath:Y="app/Jobs"}=$,Q=`${J}/${Y}`,W=[];try{let U=await import("node:fs"),Z=await import("node:path");if(!U.existsSync(Q))return[];let z=U.readdirSync(Q).filter((H)=>H.endsWith(".ts")&&!H.startsWith("_")&&H!=="runner.ts");for(let H of z){let K=Z.join(Q,H),B=H.replace(".ts",""),O=U.readFileSync(K,"utf-8"),X=q0.parseJobMetadata(O,B,K);if(X)W.push(X)}}catch{return[]}return W}static parseJobMetadata($,J,Y){let Q=$.match(/export\s+const\s+schedule\s*=\s*['"`]([^'"`]+)['"`]/)||$.match(/schedule:\s*['"`]([^'"`]+)['"`]/),W=$.match(/export\s+const\s+enabled\s*=\s*(true|false)/)||$.match(/enabled:\s*(true|false)/),U=$.match(/export\s+const\s+retries\s*=\s*(\d+)/)||$.match(/retries:\s*(\d+)/),Z=$.match(/export\s+const\s+timeout\s*=\s*(\d+)/)||$.match(/timeout:\s*(\d+)/),z=$.match(/export\s+const\s+backoff\s*=\s*['"`](linear|exponential|fixed)['"`]/)||$.match(/backoff:\s*['"`](linear|exponential|fixed)['"`]/),H=$.match(/export\s+const\s+description\s*=\s*['"`]([^'"`]+)['"`]/)||$.match(/description:\s*['"`]([^'"`]+)['"`]/);if(!($.includes("export async function handle")||$.includes("export function handle")||$.includes("export default")))return null;return{name:J,path:Y,schedule:Q?.[1],handler:`${J}.handle`,enabled:W?.[1]!=="false",retries:U?parseInt(U[1],10):void 0,backoff:z?.[1],timeout:Z?parseInt(Z[1],10):void 0,description:H?.[1]}}static async discoverActions($){let{projectRoot:J,actionsPath:Y="app/Actions"}=$,Q=`${J}/${Y}`,W=[];try{let U=await import("node:fs"),Z=await import("node:path");if(!U.existsSync(Q))return[];let z=U.readdirSync(Q).filter((H)=>H.endsWith(".ts")&&!H.startsWith("_"));for(let H of z){let K=Z.join(Q,H),B=H.replace(".ts",""),O=U.readFileSync(K,"utf-8"),X=q0.parseActionMetadata(O,B,K);if(X)W.push(X)}}catch{return[]}return W}static parseActionMetadata($,J,Y){if(!($.includes("export async function handle")||$.includes("export function handle")||$.includes("export default")))return null;let W=$.match(/export\s+const\s+description\s*=\s*['"`]([^'"`]+)['"`]/)||$.match(/description:\s*['"`]([^'"`]+)['"`]/);return{name:J,path:Y,handler:`${J}.handle`,description:W?.[1]}}static generateScheduledJobResources($){let{slug:J,environment:Y,jobs:Q,taskDefinitionArn:W,clusterArn:U,subnets:Z,securityGroups:z=[],roleArn:H,containerName:K="app"}=$,B={},O=0;for(let X of Q){if(!X.schedule||!X.enabled)continue;let{rule:j,logicalId:q}=x$.createScheduledJob({slug:J,environment:Y,schedule:X.schedule,jobClass:X.name,taskDefinitionArn:W,clusterArn:U,subnets:Z,securityGroups:z,roleArn:H,containerName:K});B[q]=j,O++}return{rules:B,count:O}}static generateJobRunnerScript(){return`#!/usr/bin/env bun
815
+ /**
816
+ * Job Runner Script
817
+ * This script is invoked by ECS scheduled tasks to run jobs
818
+ * Auto-generated by ts-cloud
819
+ */
820
+ const jobClass = process.env.JOB_CLASS
821
+ const jobDataRaw = process.env.JOB_DATA
822
+
823
+ if (!jobClass) {
824
+ console.error('JOB_CLASS environment variable is required')
825
+ process.exit(1)
826
+ }
827
+
828
+ async function run() {
829
+ try {
830
+ const jobData = jobDataRaw ? JSON.parse(jobDataRaw) : {}
831
+
832
+ // Dynamic import of the job module
833
+ const jobModule = await import(\`./\${jobClass}.ts\`)
834
+
835
+ // Check for handle function
836
+ const handler = jobModule.handle || jobModule.default
837
+
838
+ if (typeof handler !== 'function') {
839
+ throw new Error(\`Job \${jobClass} does not export a handle function\`)
840
+ }
841
+
842
+ console.log(\`[Job Runner] Starting job: \${jobClass}\`)
843
+ const startTime = Date.now()
844
+
845
+ await handler(jobData)
846
+
847
+ const duration = Date.now() - startTime
848
+ console.log(\`[Job Runner] Job \${jobClass} completed in \${duration}ms\`)
849
+
850
+ process.exit(0)
851
+ } catch (error) {
852
+ console.error(\`[Job Runner] Job \${jobClass} failed:\`, error)
853
+ process.exit(1)
854
+ }
855
+ }
856
+
857
+ run()
858
+ `}static async generateJobManifest($){let J=await q0.discoverJobs($),Y=J.filter((Q)=>Q.schedule&&Q.enabled);return{jobs:J,scheduledCount:Y.length,totalCount:J.length}}}var D3={loadJobs:q0.discoverJobs,loadActions:q0.discoverActions,generateScheduledJobs:q0.generateScheduledJobResources,generateRunner:q0.generateJobRunnerScript,paths:{jobs:"app/Jobs",actions:"app/Actions",runner:"app/Jobs/runner.ts"}};class A0{static createPostgres($){return A0.createRDSInstance("postgres","16.2",$)}static createMysql($){return A0.createRDSInstance("mysql","8.0.35",$)}static createRDSInstance($,J,Y){let{slug:Q,environment:W,instanceClass:U="db.t3.micro",allocatedStorage:Z=20,storageType:z="gp3",masterUsername:H="admin",masterPassword:K,databaseName:B,subnetIds:O,securityGroupIds:X,encrypted:j=!0,kmsKeyId:q,multiAz:E=!1,backupRetentionDays:F=7,publiclyAccessible:w=!1,enableCloudwatchLogs:T=!0,deletionProtection:S=!0}=Y,R=h({slug:Q,environment:W,resourceType:`${$}-db`}),C=I(R),D,k;if(O&&O.length>0){let b=h({slug:Q,environment:W,resourceType:"db-subnet-group"});k=I(b),D={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupName:b,DBSubnetGroupDescription:`Subnet group for ${R}`,SubnetIds:O,Tags:[{Key:"Name",Value:b},{Key:"Environment",Value:W}]}}}let u={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:R,DBInstanceClass:U,Engine:$,EngineVersion:J,MasterUsername:H,MasterUserPassword:K,AllocatedStorage:Z,StorageType:z,StorageEncrypted:j,MultiAZ:E,BackupRetentionPeriod:F,PubliclyAccessible:w,DeletionProtection:S,Tags:[{Key:"Name",Value:R},{Key:"Environment",Value:W}]}};if(B)u.Properties.DBName=B;if(q)u.Properties.KmsKeyId=q;if(k)u.Properties.DBSubnetGroupName=d.Ref(k);if(X&&X.length>0)u.Properties.VPCSecurityGroups=X;if(T)u.Properties.EnableCloudwatchLogsExports=$==="postgres"?["postgresql"]:["error","general","slowquery"];return{dbInstance:u,subnetGroup:D,logicalId:C,subnetGroupId:k}}static createReadReplica($,J){let{slug:Y,environment:Q,instanceClass:W="db.t3.micro",securityGroupIds:U,publiclyAccessible:Z=!1}=J,z=h({slug:Y,environment:Q,resourceType:"db-replica"}),H=I(z),K={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:z,DBInstanceClass:W,SourceDBInstanceIdentifier:d.Ref($),PubliclyAccessible:Z,Tags:[{Key:"Name",Value:z},{Key:"Environment",Value:Q},{Key:"Type",Value:"ReadReplica"}]}};if(U&&U.length>0)K.Properties.VPCSecurityGroups=U;return{replica:K,logicalId:H}}static createParameterGroup($,J,Y){let{slug:Q,environment:W,parameters:U={}}=Y,Z=h({slug:Q,environment:W,resourceType:"db-params"}),z=I(Z),H=$==="postgres"?`postgres${J.split(".")[0]}`:`mysql${J.split(".")[0]}.${J.split(".")[1]}`;return{parameterGroup:{Type:"AWS::RDS::DBParameterGroup",Properties:{DBParameterGroupName:Z,Description:`Parameter group for ${Z}`,Family:H,Parameters:U,Tags:[{Key:"Name",Value:Z},{Key:"Environment",Value:W}]}},logicalId:z}}static enableBackup($,J=7){return $.Properties.BackupRetentionPeriod=J,$}static createTable($){let{slug:J,environment:Y,tableName:Q,partitionKey:W,sortKey:U,billingMode:Z="PAY_PER_REQUEST",readCapacity:z=5,writeCapacity:H=5,streamEnabled:K=!1,streamViewType:B="NEW_AND_OLD_IMAGES",encrypted:O=!0,kmsKeyId:X,pointInTimeRecovery:j=!0,ttlAttribute:q}=$,E=Q||h({slug:J,environment:Y,resourceType:"table"}),F=I(E),w=[{AttributeName:W.name,AttributeType:W.type}];if(U)w.push({AttributeName:U.name,AttributeType:U.type});let T=[{AttributeName:W.name,KeyType:"HASH"}];if(U)T.push({AttributeName:U.name,KeyType:"RANGE"});let S={Type:"AWS::DynamoDB::Table",Properties:{TableName:E,BillingMode:Z,AttributeDefinitions:w,KeySchema:T,Tags:[{Key:"Name",Value:E},{Key:"Environment",Value:Y}]}};if(Z==="PROVISIONED")S.Properties.ProvisionedThroughput={ReadCapacityUnits:z,WriteCapacityUnits:H};if(K)S.Properties.StreamSpecification={StreamViewType:B};if(O)S.Properties.SSESpecification={SSEEnabled:!0,SSEType:X?"KMS":"AES256",KMSMasterKeyId:X};if(j)S.Properties.PointInTimeRecoverySpecification={PointInTimeRecoveryEnabled:!0};if(q)S.Properties.TimeToLiveSpecification={AttributeName:q,Enabled:!0};return{table:S,logicalId:F}}static addGlobalSecondaryIndex($,J){let{indexName:Y,partitionKey:Q,sortKey:W,projectionType:U="ALL",nonKeyAttributes:Z,readCapacity:z=5,writeCapacity:H=5}=J;if(!$.Properties.AttributeDefinitions.some((O)=>O.AttributeName===Q.name))$.Properties.AttributeDefinitions.push({AttributeName:Q.name,AttributeType:Q.type});if(W&&!$.Properties.AttributeDefinitions.some((O)=>O.AttributeName===W.name))$.Properties.AttributeDefinitions.push({AttributeName:W.name,AttributeType:W.type});let K=[{AttributeName:Q.name,KeyType:"HASH"}];if(W)K.push({AttributeName:W.name,KeyType:"RANGE"});let B={IndexName:Y,KeySchema:K,Projection:{ProjectionType:U,NonKeyAttributes:U==="INCLUDE"?Z:void 0},ProvisionedThroughput:void 0};if($.Properties.BillingMode==="PROVISIONED")B.ProvisionedThroughput={ReadCapacityUnits:z,WriteCapacityUnits:H};if(!$.Properties.GlobalSecondaryIndexes)$.Properties.GlobalSecondaryIndexes=[];return $.Properties.GlobalSecondaryIndexes.push(B),$}static enableStreams($,J="NEW_AND_OLD_IMAGES"){return $.Properties.StreamSpecification={StreamViewType:J},$}static InstanceClasses={T3_Micro:"db.t3.micro",T3_Small:"db.t3.small",T3_Medium:"db.t3.medium",T3_Large:"db.t3.large",T4g_Micro:"db.t4g.micro",T4g_Small:"db.t4g.small",T4g_Medium:"db.t4g.medium",M5_Large:"db.m5.large",M5_XLarge:"db.m5.xlarge",M5_2XLarge:"db.m5.2xlarge",R5_Large:"db.r5.large",R5_XLarge:"db.r5.xlarge",R5_2XLarge:"db.r5.2xlarge"}}class d${static createUser($){let{slug:J,environment:Y,userName:Q,groups:W,managedPolicyArns:U}=$,Z=Q||h({slug:J,environment:Y,resourceType:"user"}),z=I(Z),H={Type:"AWS::IAM::User",Properties:{UserName:Z,Tags:[{Key:"Name",Value:Z},{Key:"Environment",Value:Y}]}};if(W&&W.length>0)H.Properties.Groups=W;if(U&&U.length>0)H.Properties.ManagedPolicyArns=U;return{user:H,logicalId:z}}static createRole($){let{slug:J,environment:Y,roleName:Q,servicePrincipal:W,awsPrincipal:U,managedPolicyArns:Z}=$,z=Q||h({slug:J,environment:Y,resourceType:"role"}),H=I(z),K={};if(W)K.Service=W;if(U)K.AWS=U;let B={Type:"AWS::IAM::Role",Properties:{RoleName:z,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:K,Action:"sts:AssumeRole"}]},Tags:[{Key:"Name",Value:z},{Key:"Environment",Value:Y}]}};if(Z&&Z.length>0)B.Properties.ManagedPolicyArns=Z;return{role:B,logicalId:H}}static createGroup($){let{slug:J,environment:Y,groupName:Q,managedPolicyArns:W}=$,U=Q||h({slug:J,environment:Y,resourceType:"group"}),Z=I(U),z={Type:"AWS::IAM::Group",Properties:{GroupName:U}};if(W&&W.length>0)z.Properties.ManagedPolicyArns=W;return{group:z,logicalId:Z}}static createPolicy($){let{slug:J,environment:Y,policyName:Q,description:W,statements:U}=$,Z=Q||h({slug:J,environment:Y,resourceType:"policy"}),z=I(Z),H=U.map((B)=>({Sid:B.sid,Effect:B.effect||"Allow",Action:B.actions,Resource:B.resources,Condition:B.conditions}));return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:Z,Description:W||`Managed policy for ${Z}`,PolicyDocument:{Version:"2012-10-17",Statement:H}}},logicalId:z}}static attachPolicyToRole($,J){if(!$.Properties.ManagedPolicyArns)$.Properties.ManagedPolicyArns=[];if(!$.Properties.ManagedPolicyArns.includes(J))$.Properties.ManagedPolicyArns.push(J);return $}static attachPolicyToUser($,J){if(!$.Properties.ManagedPolicyArns)$.Properties.ManagedPolicyArns=[];if(!$.Properties.ManagedPolicyArns.includes(J))$.Properties.ManagedPolicyArns.push(J);return $}static attachPolicyToGroup($,J){if(!$.Properties.ManagedPolicyArns)$.Properties.ManagedPolicyArns=[];if(!$.Properties.ManagedPolicyArns.includes(J))$.Properties.ManagedPolicyArns.push(J);return $}static addInlinePolicyToRole($,J,Y){if(!$.Properties.Policies)$.Properties.Policies=[];let Q=Y.map((W)=>({Effect:W.effect||"Allow",Action:W.actions,Resource:W.resources}));return $.Properties.Policies.push({PolicyName:J,PolicyDocument:{Version:"2012-10-17",Statement:Q}}),$}static addInlinePolicyToUser($,J,Y){if(!$.Properties.Policies)$.Properties.Policies=[];let Q=Y.map((W)=>({Effect:W.effect||"Allow",Action:W.actions,Resource:W.resources}));return $.Properties.Policies.push({PolicyName:J,PolicyDocument:{Version:"2012-10-17",Statement:Q}}),$}static createAccessKey($,J){let{slug:Y,environment:Q,status:W="Active"}=J,U=h({slug:Y,environment:Q,resourceType:"access-key"}),Z=I(U);return{accessKey:{Type:"AWS::IAM::AccessKey",Properties:{UserName:d.Ref($),Status:W}},logicalId:Z}}static createInstanceProfile($,J){let{slug:Y,environment:Q,profileName:W}=J,U=W||h({slug:Y,environment:Q,resourceType:"instance-profile"}),Z=I(U);return{instanceProfile:{Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:U,Roles:[d.Ref($)]}},logicalId:Z}}static ManagedPolicies={AdministratorAccess:"arn:aws:iam::aws:policy/AdministratorAccess",PowerUserAccess:"arn:aws:iam::aws:policy/PowerUserAccess",ReadOnlyAccess:"arn:aws:iam::aws:policy/ReadOnlyAccess",S3FullAccess:"arn:aws:iam::aws:policy/AmazonS3FullAccess",S3ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess",DynamoDBFullAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess",DynamoDBReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess",RDSFullAccess:"arn:aws:iam::aws:policy/AmazonRDSFullAccess",RDSReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess",LambdaFullAccess:"arn:aws:iam::aws:policy/AWSLambda_FullAccess",LambdaReadOnlyAccess:"arn:aws:iam::aws:policy/AWSLambda_ReadOnlyAccess",LambdaBasicExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",LambdaVPCAccessExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole",EC2FullAccess:"arn:aws:iam::aws:policy/AmazonEC2FullAccess",EC2ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess",EC2ContainerRegistryReadOnly:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly",EC2ContainerRegistryPowerUser:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryPowerUser",ECSTaskExecutionRole:"arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",ECSFullAccess:"arn:aws:iam::aws:policy/AmazonECS_FullAccess",CloudWatchFullAccess:"arn:aws:iam::aws:policy/CloudWatchFullAccess",CloudWatchLogsFullAccess:"arn:aws:iam::aws:policy/CloudWatchLogsFullAccess",SESFullAccess:"arn:aws:iam::aws:policy/AmazonSESFullAccess",SNSFullAccess:"arn:aws:iam::aws:policy/AmazonSNSFullAccess",SQSFullAccess:"arn:aws:iam::aws:policy/AmazonSQSFullAccess",SecretsManagerReadWrite:"arn:aws:iam::aws:policy/SecretsManagerReadWrite"};static ServicePrincipals={Lambda:"lambda.amazonaws.com",EC2:"ec2.amazonaws.com",ECS:"ecs.amazonaws.com",ECSTaskExecution:"ecs-tasks.amazonaws.com",APIGateway:"apigateway.amazonaws.com",Events:"events.amazonaws.com",States:"states.amazonaws.com",CodeBuild:"codebuild.amazonaws.com",CodeDeploy:"codedeploy.amazonaws.com",CloudFormation:"cloudformation.amazonaws.com"};static createCiCdUser($){let{slug:J,environment:Y,permissions:Q,createAccessKey:W=!0}=$,U={},Z=[];if(Q.s3Buckets&&Q.s3Buckets.length>0)Z.push({sid:"S3Access",actions:["s3:GetBucketLocation","s3:ListBucket","s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucketMultipartUploads","s3:AbortMultipartUpload"],resources:[...Q.s3Buckets,...Q.s3Buckets.map((j)=>`${j}/*`)]});if(Q.cloudFrontDistributions&&Q.cloudFrontDistributions.length>0)Z.push({sid:"CloudFrontAccess",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations","cloudfront:GetDistribution"],resources:Q.cloudFrontDistributions});if(Q.ecrRepositories&&Q.ecrRepositories.length>0)Z.push({sid:"ECRAccess",actions:["ecr:GetAuthorizationToken","ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:GetRepositoryPolicy","ecr:DescribeRepositories","ecr:ListImages","ecr:DescribeImages","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:Q.ecrRepositories}),Z.push({sid:"ECRLogin",actions:["ecr:GetAuthorizationToken"],resources:"*"});if(Q.ecsServices&&Q.ecsServices.length>0)Z.push({sid:"ECSAccess",actions:["ecs:DescribeServices","ecs:DescribeTaskDefinition","ecs:DescribeTasks","ecs:ListTasks","ecs:RegisterTaskDefinition","ecs:UpdateService","ecs:RunTask","ecs:StopTask"],resources:Q.ecsServices}),Z.push({sid:"ECSTaskDefinitions",actions:["ecs:RegisterTaskDefinition","ecs:DeregisterTaskDefinition"],resources:"*"}),Z.push({sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}});if(Q.cloudFormationStacks&&Q.cloudFormationStacks.length>0)Z.push({sid:"CloudFormationAccess",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DeleteStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:DescribeStackResources","cloudformation:GetTemplate","cloudformation:ListStackResources","cloudformation:ValidateTemplate"],resources:Q.cloudFormationStacks});if(Q.lambdaFunctions&&Q.lambdaFunctions.length>0)Z.push({sid:"LambdaAccess",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion","lambda:UpdateAlias","lambda:CreateAlias"],resources:Q.lambdaFunctions});if(Q.secretsManagerSecrets&&Q.secretsManagerSecrets.length>0)Z.push({sid:"SecretsManagerAccess",actions:["secretsmanager:GetSecretValue","secretsmanager:DescribeSecret"],resources:Q.secretsManagerSecrets});let{policy:z,logicalId:H}=d$.createPolicy({slug:J,environment:Y,policyName:h({slug:J,environment:Y,resourceType:"cicd-policy"}),description:`CI/CD deployment policy for ${J} (${Y})`,statements:Z});U[H]=z;let{user:K,logicalId:B}=d$.createUser({slug:J,environment:Y,userName:h({slug:J,environment:Y,resourceType:"cicd-user"}),managedPolicyArns:[d.Ref(H)]});U[B]=K;let O,X;if(W){let j=d$.createAccessKey(B,{slug:J,environment:Y});O=j.accessKey,X=j.logicalId,U[X]=O}return{user:K,accessKey:O,policy:z,userLogicalId:B,accessKeyLogicalId:X,policyLogicalId:H,resources:U}}static createCrossAccountRole($){let{slug:J,environment:Y,trustedAccountIds:Q,externalId:W,permissions:U,maxSessionDuration:Z=3600}=$,z={},{policy:H,logicalId:K}=d$.createPolicy({slug:J,environment:Y,policyName:h({slug:J,environment:Y,resourceType:"cross-account-policy"}),description:`Cross-account access policy for ${J} (${Y})`,statements:U});z[K]=H;let B=h({slug:J,environment:Y,resourceType:"cross-account-role"}),O=I(B),X={};if(W)X.StringEquals={"sts:ExternalId":W};let j={Type:"AWS::IAM::Role",Properties:{RoleName:B,MaxSessionDuration:Z,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:Q.map((q)=>`arn:aws:iam::${q}:root`)},Action:"sts:AssumeRole",...Object.keys(X).length>0?{Condition:X}:{}}]},ManagedPolicyArns:[d.Ref(K)],Tags:[{Key:"Name",Value:B},{Key:"Environment",Value:Y},{Key:"Purpose",Value:"Cross-Account Access"}]}};return z[O]=j,{role:j,policy:H,roleLogicalId:O,policyLogicalId:K,resources:z}}static createCliUser($){let{slug:J,environment:Y,permissions:Q="readonly"}=$,W={},U=[],Z=[];switch(Q){case"readonly":Z=[d$.ManagedPolicies.ReadOnlyAccess];break;case"deploy":U=[{sid:"S3Deploy",actions:["s3:*"],resources:"*"},{sid:"CloudFrontDeploy",actions:["cloudfront:*"],resources:"*"},{sid:"ECSDeploy",actions:["ecs:*"],resources:"*"},{sid:"ECRDeploy",actions:["ecr:*"],resources:"*"},{sid:"LambdaDeploy",actions:["lambda:*"],resources:"*"},{sid:"CloudFormationDeploy",actions:["cloudformation:*"],resources:"*"},{sid:"IAMPassRole",actions:["iam:PassRole"],resources:"*"}];break;case"admin":Z=[d$.ManagedPolicies.AdministratorAccess];break}let z,H;if(U.length>0){let j=d$.createPolicy({slug:J,environment:Y,policyName:h({slug:J,environment:Y,resourceType:"cli-policy"}),description:`CLI access policy for ${J} (${Y})`,statements:U});z=j.policy,H=j.logicalId,W[H]=z,Z=[d.Ref(H)]}let{user:K,logicalId:B}=d$.createUser({slug:J,environment:Y,userName:h({slug:J,environment:Y,resourceType:"cli-user"}),managedPolicyArns:Z});W[B]=K;let{accessKey:O,logicalId:X}=d$.createAccessKey(B,{slug:J,environment:Y});return W[X]=O,{user:K,accessKey:O,policy:z,userLogicalId:B,accessKeyLogicalId:X,policyLogicalId:H,resources:W}}static CiCdPolicies={s3Deployment:($)=>[{sid:"S3ListBuckets",actions:["s3:ListBucket","s3:GetBucketLocation"],resources:$},{sid:"S3Objects",actions:["s3:GetObject","s3:PutObject","s3:DeleteObject"],resources:$.map((J)=>`${J}/*`)}],cloudFrontInvalidation:($)=>[{sid:"CloudFrontInvalidation",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations"],resources:$}],ecsDeployment:()=>[{sid:"ECSServices",actions:["ecs:DescribeServices","ecs:UpdateService","ecs:DescribeTaskDefinition","ecs:RegisterTaskDefinition"],resources:"*"},{sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}}],ecrPush:($)=>[{sid:"ECRAuth",actions:["ecr:GetAuthorizationToken"],resources:"*"},{sid:"ECRPush",actions:["ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:$}],lambdaDeployment:($)=>[{sid:"LambdaDeploy",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion"],resources:$}],cloudFormationDeployment:($)=>[{sid:"CloudFormationDeploy",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:GetTemplate"],resources:$}]}}class vJ{static createRestApi($){let{slug:J,environment:Y,name:Q,description:W,endpointType:U="REGIONAL",binaryMediaTypes:Z,compressionSize:z}=$,H=Q||h({slug:J,environment:Y,resourceType:"rest-api"}),K=I(H),B={Type:"AWS::ApiGateway::RestApi",Properties:{Name:H,Description:W||`REST API for ${J} ${Y}`,EndpointConfiguration:{Types:[U]},Tags:[{Key:"Name",Value:H},{Key:"Environment",Value:Y}]}};if(Z&&Z.length>0)B.Properties.BinaryMediaTypes=Z;if(z!==void 0)B.Properties.MinimumCompressionSize=z;return{restApi:B,logicalId:K}}static createHttpApi($){let{slug:J,environment:Y,name:Q,description:W,corsEnabled:U=!0,corsOrigins:Z=["*"],corsMethods:z=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],corsHeaders:H=["*"],corsMaxAge:K=86400,corsAllowCredentials:B=!1}=$,O=Q||h({slug:J,environment:Y,resourceType:"http-api"}),X=I(O),j={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:O,Description:W||`HTTP API for ${J} ${Y}`,ProtocolType:"HTTP",Tags:{Name:O,Environment:Y}}};if(U)j.Properties.CorsConfiguration={AllowOrigins:Z,AllowMethods:z,AllowHeaders:H,MaxAge:K,AllowCredentials:B};return{httpApi:j,logicalId:X}}static createWebSocketApi($){let{slug:J,environment:Y,name:Q,description:W}=$,U=Q||h({slug:J,environment:Y,resourceType:"ws-api"}),Z=I(U);return{webSocketApi:{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:U,Description:W||`WebSocket API for ${J} ${Y}`,ProtocolType:"WEBSOCKET",Tags:{Name:U,Environment:Y}}},logicalId:Z}}static createDeployment($,J){let{slug:Y,environment:Q,description:W}=J,U=h({slug:Y,environment:Q,resourceType:"api-deployment"}),Z=I(U);return{deployment:{Type:"AWS::ApiGateway::Deployment",Properties:{RestApiId:d.Ref($),Description:W||`Deployment for ${U}`}},logicalId:Z}}static createStage($,J,Y){let{slug:Q,environment:W,stageName:U,description:Z,cacheEnabled:z=!1,cacheSize:H="0.5",variables:K,throttling:B}=Y,O=h({slug:Q,environment:W,resourceType:"api-stage"}),X=I(O),j={Type:"AWS::ApiGateway::Stage",Properties:{StageName:U||W,RestApiId:d.Ref($),DeploymentId:d.Ref(J),Description:Z,CacheClusterEnabled:z,Tags:[{Key:"Name",Value:O},{Key:"Environment",Value:W}]}};if(z)j.Properties.CacheClusterSize=H;if(K)j.Properties.Variables=K;if(B)j.Properties.MethodSettings=[{HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:B.burstLimit,ThrottlingRateLimit:B.rateLimit}];return{stage:j,logicalId:X}}static createAuthorizer($,J){let{slug:Y,environment:Q,name:W,type:U,functionArn:Z,identitySource:z,userPoolArns:H,ttl:K=300}=J,B=W||h({slug:Y,environment:Q,resourceType:"api-authorizer"}),O=I(B),X={Type:"AWS::ApiGateway::Authorizer",Properties:{Name:B,Type:U,RestApiId:d.Ref($),AuthorizerResultTtlInSeconds:K}};if(U==="TOKEN"||U==="REQUEST"){if(!Z)throw Error("Lambda authorizer requires functionArn");X.Properties.AuthorizerUri=Z,X.Properties.IdentitySource=z||"method.request.header.Authorization"}if(U==="COGNITO_USER_POOLS"){if(!H||H.length===0)throw Error("Cognito authorizer requires userPoolArns");X.Properties.ProviderARNs=H,X.Properties.IdentitySource=z||"method.request.header.Authorization"}return{authorizer:X,logicalId:O}}static setCors($,J={}){let{origins:Y=["*"],methods:Q=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],headers:W=["*"],maxAge:U=86400,allowCredentials:Z=!1}=J;return $.Properties.CorsConfiguration={AllowOrigins:Y,AllowMethods:Q,AllowHeaders:W,MaxAge:U,AllowCredentials:Z},$}static addThrottling($,J=5000,Y=1e4){if(!$.Properties.MethodSettings)$.Properties.MethodSettings=[];return $.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:J,ThrottlingRateLimit:Y}),$}static enableCaching($,J="0.5",Y=300){if($.Properties.CacheClusterEnabled=!0,$.Properties.CacheClusterSize=J,!$.Properties.MethodSettings)$.Properties.MethodSettings=[];return $.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",CachingEnabled:!0,CacheTtlInSeconds:Y}),$}static CacheSizes={Small:"0.5",Medium:"1.6",Large:"6.1",XLarge:"13.5",XXLarge:"28.4",XXXLarge:"58.2",Huge:"118",Massive:"237"};static ThrottlingPresets={Light:{burstLimit:100,rateLimit:50},Medium:{burstLimit:500,rateLimit:250},Heavy:{burstLimit:2000,rateLimit:1000},Default:{burstLimit:5000,rateLimit:1e4}}}class y1{static createAlarm($){let{slug:J,environment:Y,alarmName:Q,metricName:W,namespace:U,statistic:Z="Average",period:z=300,evaluationPeriods:H=1,threshold:K,comparisonOperator:B,treatMissingData:O="notBreaching",actionsEnabled:X=!0,alarmActions:j,okActions:q,insufficientDataActions:E,dimensions:F,unit:w,datapointsToAlarm:T}=$,S=Q||h({slug:J,environment:Y,resourceType:"alarm"}),R=I(S),C={Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:S,MetricName:W,Namespace:U,Statistic:Z,Period:z,EvaluationPeriods:H,Threshold:K,ComparisonOperator:B,TreatMissingData:O,ActionsEnabled:X}};if(j&&j.length>0)C.Properties.AlarmActions=j;if(q&&q.length>0)C.Properties.OKActions=q;if(E&&E.length>0)C.Properties.InsufficientDataActions=E;if(F)C.Properties.Dimensions=Object.entries(F).map(([D,k])=>({Name:D,Value:k}));if(w)C.Properties.Unit=w;if(T!==void 0)C.Properties.DatapointsToAlarm=T;return{alarm:C,logicalId:R}}static createCompositeAlarm($){let{slug:J,environment:Y,alarmName:Q,alarmRule:W,actionsEnabled:U=!0,alarmActions:Z,okActions:z,insufficientDataActions:H}=$,K=Q||h({slug:J,environment:Y,resourceType:"composite-alarm"}),B=I(K),O={Type:"AWS::CloudWatch::CompositeAlarm",Properties:{AlarmName:K,AlarmRule:W,ActionsEnabled:U}};if(Z&&Z.length>0)O.Properties.AlarmActions=Z;if(z&&z.length>0)O.Properties.OKActions=z;if(H&&H.length>0)O.Properties.InsufficientDataActions=H;return{alarm:O,logicalId:B}}static createDashboard($){let{slug:J,environment:Y,dashboardName:Q,widgets:W}=$,U=Q||h({slug:J,environment:Y,resourceType:"dashboard"}),Z=I(U),z={widgets:W.map((K)=>({type:K.type,x:K.x,y:K.y,width:K.width,height:K.height,properties:K.properties}))};return{dashboard:{Type:"AWS::CloudWatch::Dashboard",Properties:{DashboardName:U,DashboardBody:JSON.stringify(z)}},logicalId:Z}}static createLogGroup($){let{slug:J,environment:Y,logGroupName:Q,retentionInDays:W,kmsKeyId:U}=$,Z=Q||h({slug:J,environment:Y,resourceType:"log-group"}),z=I(Z),H={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:Z}};if(W!==void 0)H.Properties.RetentionInDays=W;if(U)H.Properties.KmsKeyId=U;return{logGroup:H,logicalId:z}}static createLogStream($,J){let{slug:Y,environment:Q,logStreamName:W}=J,U=W||h({slug:Y,environment:Q,resourceType:"log-stream"}),Z=I(U);return{logStream:{Type:"AWS::Logs::LogStream",Properties:{LogGroupName:d.Ref($),LogStreamName:U}},logicalId:Z}}static createMetricFilter($,J){let{slug:Y,environment:Q,filterName:W,filterPattern:U,metricTransformations:Z}=J,z=W||h({slug:Y,environment:Q,resourceType:"metric-filter"}),H=I(z);return{metricFilter:{Type:"AWS::Logs::MetricFilter",Properties:{LogGroupName:d.Ref($),FilterPattern:U,MetricTransformations:Z.map((B)=>({MetricName:B.metricName,MetricNamespace:B.metricNamespace,MetricValue:B.metricValue,DefaultValue:B.defaultValue,Unit:B.unit}))}},logicalId:H}}static AlarmTypes={highCpu:($,J,Y,Q=80,W)=>({slug:$,environment:J,alarmName:`${$}-${J}-high-cpu`,metricName:"CPUUtilization",namespace:"AWS/EC2",statistic:"Average",period:300,evaluationPeriods:2,threshold:Q,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:Y},alarmActions:W?[W]:void 0}),highMemory:($,J,Y,Q=80,W)=>({slug:$,environment:J,alarmName:`${$}-${J}-high-memory`,metricName:"MemoryUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:Q,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:Y},alarmActions:W?[W]:void 0}),highDisk:($,J,Y,Q=80,W)=>({slug:$,environment:J,alarmName:`${$}-${J}-high-disk`,metricName:"DiskSpaceUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:Q,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:Y,Filesystem:"/dev/xvda1",MountPath:"/"},alarmActions:W?[W]:void 0}),lambdaErrors:($,J,Y,Q=5,W)=>({slug:$,environment:J,alarmName:`${$}-${J}-lambda-errors`,metricName:"Errors",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:Q,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:Y},alarmActions:W?[W]:void 0}),lambdaThrottles:($,J,Y,Q=10,W)=>({slug:$,environment:J,alarmName:`${$}-${J}-lambda-throttles`,metricName:"Throttles",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:Q,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:Y},alarmActions:W?[W]:void 0}),apiGateway5xxErrors:($,J,Y,Q=10,W)=>({slug:$,environment:J,alarmName:`${$}-${J}-api-5xx-errors`,metricName:"5XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:1,threshold:Q,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:Y},alarmActions:W?[W]:void 0}),apiGateway4xxErrors:($,J,Y,Q=50,W)=>({slug:$,environment:J,alarmName:`${$}-${J}-api-4xx-errors`,metricName:"4XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:2,threshold:Q,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:Y},alarmActions:W?[W]:void 0}),dynamoDBThrottles:($,J,Y,Q=5,W)=>({slug:$,environment:J,alarmName:`${$}-${J}-dynamodb-throttles`,metricName:"UserErrors",namespace:"AWS/DynamoDB",statistic:"Sum",period:300,evaluationPeriods:1,threshold:Q,comparisonOperator:"GreaterThanThreshold",dimensions:{TableName:Y},alarmActions:W?[W]:void 0}),rdsCpu:($,J,Y,Q=80,W)=>({slug:$,environment:J,alarmName:`${$}-${J}-rds-cpu`,metricName:"CPUUtilization",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:2,threshold:Q,comparisonOperator:"GreaterThanThreshold",dimensions:{DBInstanceIdentifier:Y},alarmActions:W?[W]:void 0}),rdsFreeStorage:($,J,Y,Q=5368709120,W)=>({slug:$,environment:J,alarmName:`${$}-${J}-rds-storage`,metricName:"FreeStorageSpace",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:1,threshold:Q,comparisonOperator:"LessThanThreshold",dimensions:{DBInstanceIdentifier:Y},alarmActions:W?[W]:void 0,unit:"Bytes"}),sqsQueueDepth:($,J,Y,Q=100,W)=>({slug:$,environment:J,alarmName:`${$}-${J}-sqs-depth`,metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",statistic:"Average",period:300,evaluationPeriods:2,threshold:Q,comparisonOperator:"GreaterThanThreshold",dimensions:{QueueName:Y},alarmActions:W?[W]:void 0}),albUnhealthyTargets:($,J,Y,Q,W=1,U)=>({slug:$,environment:J,alarmName:`${$}-${J}-alb-unhealthy`,metricName:"UnHealthyHostCount",namespace:"AWS/ApplicationELB",statistic:"Average",period:300,evaluationPeriods:2,threshold:W,comparisonOperator:"GreaterThanThreshold",dimensions:{LoadBalancer:Y,TargetGroup:Q},alarmActions:U?[U]:void 0}),sesBounceRate:($,J,Y=5,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-ses-bounce-rate`,metricName:"Reputation.BounceRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:Y/100,comparisonOperator:"GreaterThanThreshold",alarmActions:Q?[Q]:void 0}),sesComplaintRate:($,J,Y=0.1,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-ses-complaint-rate`,metricName:"Reputation.ComplaintRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:Y/100,comparisonOperator:"GreaterThanThreshold",alarmActions:Q?[Q]:void 0}),smsDeliveryFailure:($,J,Y,Q=10,W)=>({slug:$,environment:J,alarmName:`${$}-${J}-sms-delivery-failure`,metricName:"DirectSendMessagePermanentFailure",namespace:"AWS/Pinpoint",statistic:"Sum",period:300,evaluationPeriods:1,threshold:Q,comparisonOperator:"GreaterThanThreshold",dimensions:{ApplicationId:Y},alarmActions:W?[W]:void 0}),smsSpendLimit:($,J,Y=100,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-sms-spend-limit`,metricName:"DirectSendMessageSpend",namespace:"AWS/Pinpoint",statistic:"Sum",period:86400,evaluationPeriods:1,threshold:Y,comparisonOperator:"GreaterThanThreshold",alarmActions:Q?[Q]:void 0}),connectMissedCalls:($,J,Y,Q=5,W)=>({slug:$,environment:J,alarmName:`${$}-${J}-connect-missed-calls`,metricName:"MissedCalls",namespace:"AWS/Connect",statistic:"Sum",period:3600,evaluationPeriods:1,threshold:Q,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:Y},alarmActions:W?[W]:void 0})};static DashboardWidgets={metric:($,J,Y,Q,W,U)=>({type:"metric",x:$,y:J,width:Y,height:Q,properties:{metrics:W,title:U||"Metrics",region:"us-east-1",period:300}}),text:($,J,Y,Q,W)=>({type:"text",x:$,y:J,width:Y,height:Q,properties:{markdown:W}}),log:($,J,Y,Q,W,U)=>({type:"log",x:$,y:J,width:Y,height:Q,properties:{query:`SOURCE '${W.join("' | SOURCE '")}'
859
+ | fields @timestamp, @message
860
+ | sort @timestamp desc
861
+ | limit 20`,region:"us-east-1",title:U||"Logs"}})};static RetentionPeriods={ONE_DAY:1,THREE_DAYS:3,FIVE_DAYS:5,ONE_WEEK:7,TWO_WEEKS:14,ONE_MONTH:30,TWO_MONTHS:60,THREE_MONTHS:90,FOUR_MONTHS:120,FIVE_MONTHS:150,SIX_MONTHS:180,ONE_YEAR:365,THIRTEEN_MONTHS:400,EIGHTEEN_MONTHS:545,TWO_YEARS:731,FIVE_YEARS:1827,TEN_YEARS:3653,NEVER_EXPIRE:void 0};static FilterPatterns={errors:"[time, request_id, event_type = ERROR*, ...]",all:"",jsonField:($,J)=>`{ $.${$} = "${J}" }`,httpStatus:($)=>`[..., status_code = ${$}, ...]`,http4xx:"[..., status_code = 4*, ...]",http5xx:"[..., status_code = 5*, ...]"};static createApplicationDashboard($){let{slug:J,environment:Y,region:Q="us-east-1",components:W={}}=$,U=[],Z=0;if(U.push({type:"text",x:0,y:Z,width:24,height:1,properties:{markdown:`# ${J.toUpperCase()} Dashboard (${Y})`}}),Z+=1,W.ec2InstanceIds&&W.ec2InstanceIds.length>0)U.push({type:"text",x:0,y:Z,width:24,height:1,properties:{markdown:"## EC2 Instances"}}),Z+=1,U.push({type:"metric",x:0,y:Z,width:8,height:6,properties:{title:"CPU Utilization",region:Q,metrics:W.ec2InstanceIds.map((z)=>["AWS/EC2","CPUUtilization","InstanceId",z]),period:300,stat:"Average"}}),U.push({type:"metric",x:8,y:Z,width:8,height:6,properties:{title:"Network Traffic",region:Q,metrics:[...W.ec2InstanceIds.flatMap((z)=>[["AWS/EC2","NetworkIn","InstanceId",z,{label:`${z} In`}],["AWS/EC2","NetworkOut","InstanceId",z,{label:`${z} Out`}]])],period:300,stat:"Sum"}}),U.push({type:"metric",x:16,y:Z,width:8,height:6,properties:{title:"Status Checks",region:Q,metrics:W.ec2InstanceIds.map((z)=>["AWS/EC2","StatusCheckFailed","InstanceId",z]),period:60,stat:"Maximum"}}),Z+=6;if(W.lambdaFunctionNames&&W.lambdaFunctionNames.length>0)U.push({type:"text",x:0,y:Z,width:24,height:1,properties:{markdown:"## Lambda Functions"}}),Z+=1,U.push({type:"metric",x:0,y:Z,width:8,height:6,properties:{title:"Invocations",region:Q,metrics:W.lambdaFunctionNames.map((z)=>["AWS/Lambda","Invocations","FunctionName",z]),period:300,stat:"Sum"}}),U.push({type:"metric",x:8,y:Z,width:8,height:6,properties:{title:"Duration",region:Q,metrics:W.lambdaFunctionNames.map((z)=>["AWS/Lambda","Duration","FunctionName",z]),period:300,stat:"Average"}}),U.push({type:"metric",x:16,y:Z,width:8,height:6,properties:{title:"Errors",region:Q,metrics:W.lambdaFunctionNames.map((z)=>["AWS/Lambda","Errors","FunctionName",z]),period:300,stat:"Sum"}}),Z+=6;if(W.ecsClusterName&&W.ecsServiceName)U.push({type:"text",x:0,y:Z,width:24,height:1,properties:{markdown:"## ECS Service"}}),Z+=1,U.push({type:"metric",x:0,y:Z,width:8,height:6,properties:{title:"CPU Utilization",region:Q,metrics:[["AWS/ECS","CPUUtilization","ClusterName",W.ecsClusterName,"ServiceName",W.ecsServiceName]],period:300,stat:"Average"}}),U.push({type:"metric",x:8,y:Z,width:8,height:6,properties:{title:"Memory Utilization",region:Q,metrics:[["AWS/ECS","MemoryUtilization","ClusterName",W.ecsClusterName,"ServiceName",W.ecsServiceName]],period:300,stat:"Average"}}),U.push({type:"metric",x:16,y:Z,width:8,height:6,properties:{title:"Running Tasks",region:Q,metrics:[["ECS/ContainerInsights","RunningTaskCount","ClusterName",W.ecsClusterName,"ServiceName",W.ecsServiceName]],period:60,stat:"Average"}}),Z+=6;if(W.albName)U.push({type:"text",x:0,y:Z,width:24,height:1,properties:{markdown:"## Application Load Balancer"}}),Z+=1,U.push({type:"metric",x:0,y:Z,width:8,height:6,properties:{title:"Request Count",region:Q,metrics:[["AWS/ApplicationELB","RequestCount","LoadBalancer",W.albName]],period:60,stat:"Sum"}}),U.push({type:"metric",x:8,y:Z,width:8,height:6,properties:{title:"Response Time",region:Q,metrics:[["AWS/ApplicationELB","TargetResponseTime","LoadBalancer",W.albName]],period:60,stat:"Average"}}),U.push({type:"metric",x:16,y:Z,width:8,height:6,properties:{title:"HTTP Errors",region:Q,metrics:[["AWS/ApplicationELB","HTTPCode_Target_4XX_Count","LoadBalancer",W.albName,{label:"4XX"}],["AWS/ApplicationELB","HTTPCode_Target_5XX_Count","LoadBalancer",W.albName,{label:"5XX"}]],period:60,stat:"Sum"}}),Z+=6;if(W.rdsInstanceId)U.push({type:"text",x:0,y:Z,width:24,height:1,properties:{markdown:"## RDS Database"}}),Z+=1,U.push({type:"metric",x:0,y:Z,width:8,height:6,properties:{title:"CPU Utilization",region:Q,metrics:[["AWS/RDS","CPUUtilization","DBInstanceIdentifier",W.rdsInstanceId]],period:300,stat:"Average"}}),U.push({type:"metric",x:8,y:Z,width:8,height:6,properties:{title:"Database Connections",region:Q,metrics:[["AWS/RDS","DatabaseConnections","DBInstanceIdentifier",W.rdsInstanceId]],period:60,stat:"Sum"}}),U.push({type:"metric",x:16,y:Z,width:8,height:6,properties:{title:"Free Storage Space",region:Q,metrics:[["AWS/RDS","FreeStorageSpace","DBInstanceIdentifier",W.rdsInstanceId]],period:300,stat:"Average"}}),Z+=6;if(W.sqsQueueNames&&W.sqsQueueNames.length>0)U.push({type:"text",x:0,y:Z,width:24,height:1,properties:{markdown:"## SQS Queues"}}),Z+=1,U.push({type:"metric",x:0,y:Z,width:12,height:6,properties:{title:"Messages Visible",region:Q,metrics:W.sqsQueueNames.map((z)=>["AWS/SQS","ApproximateNumberOfMessagesVisible","QueueName",z]),period:60,stat:"Sum"}}),U.push({type:"metric",x:12,y:Z,width:12,height:6,properties:{title:"Message Age",region:Q,metrics:W.sqsQueueNames.map((z)=>["AWS/SQS","ApproximateAgeOfOldestMessage","QueueName",z]),period:60,stat:"Maximum"}}),Z+=6;if(W.logGroupNames&&W.logGroupNames.length>0)U.push({type:"text",x:0,y:Z,width:24,height:1,properties:{markdown:"## Application Logs"}}),Z+=1,U.push({type:"log",x:0,y:Z,width:24,height:6,properties:{query:`SOURCE '${W.logGroupNames.join("' | SOURCE '")}'
862
+ | fields @timestamp, @message
863
+ | filter @message like /ERROR|WARN|Exception/
864
+ | sort @timestamp desc
865
+ | limit 50`,region:Q,title:"Recent Errors and Warnings"}}),Z+=6;return y1.createDashboard({slug:J,environment:Y,widgets:U})}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,Y)=>({type:"metric",x:Y%3*8,y:7+Math.floor(Y/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:Y,threshold:Q,comparisonOperator:W="GreaterThanThreshold",evaluationPeriods:U=1,period:Z=300,statistic:z="Average",treatMissingData:H="missing"}=$;return{MetricName:J,Namespace:Y,Threshold:Q,ComparisonOperator:W,EvaluationPeriods:U,Period:Z,Statistic:z,TreatMissingData:H}},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"})}}}a0();await a0();await a0();await a0();import{createHash as h8}from"node:crypto";import h$ from"node:fs";import fJ from"node:path";class gJ{cacheDir;ttl;constructor($,J={}){if(this.cacheDir=$,this.ttl=J.ttl||86400000,!h$.existsSync($))h$.mkdirSync($,{recursive:!0})}getCachePath($){let J=h8("sha256").update($).digest("hex");return fJ.join(this.cacheDir,`${J}.json`)}get($){let J=this.getCachePath($);if(!h$.existsSync(J))return;try{let Y=h$.readFileSync(J,"utf-8"),Q=JSON.parse(Y);if(Date.now()-Q.timestamp>this.ttl){h$.unlinkSync(J);return}return Q.value}catch{h$.unlinkSync(J);return}}set($,J,Y){let Q=this.getCachePath($),W={value:J,timestamp:Date.now(),hash:Y};h$.writeFileSync(Q,JSON.stringify(W),"utf-8")}has($){return this.get($)!==void 0}clear(){let $=h$.readdirSync(this.cacheDir);for(let J of $)h$.unlinkSync(fJ.join(this.cacheDir,J))}prune(){let $=h$.readdirSync(this.cacheDir),J=Date.now();for(let Y of $){let Q=fJ.join(this.cacheDir,Y);try{let W=h$.readFileSync(Q,"utf-8"),U=JSON.parse(W);if(J-U.timestamp>this.ttl)h$.unlinkSync(Q)}catch{h$.unlinkSync(Q)}}}}class uJ{cache;constructor($=".ts-cloud/cache/templates"){this.cache=new gJ($,{ttl:86400000})}getTemplate($){return this.cache.get(`template:${$}`)}setTemplate($,J){let Y=this.hashTemplate(J);this.cache.set(`template:${$}`,J,Y)}hasChanged($,J){let Y=this.cache.get(`template:${$}`);if(!Y)return!0;let Q=this.hashTemplate(Y),W=this.hashTemplate(J);return Q!==W}hashTemplate($){return h8("sha256").update($).digest("hex")}clear(){this.cache.clear()}prune(){this.cache.prune()}}var h7=new uJ;var rH={enabled:process.env.TS_CLOUD_LOCAL==="true"||!0,localstackEndpoint:process.env.LOCALSTACK_ENDPOINT||"http://localhost:4566",postgresUrl:process.env.POSTGRES_URL||"postgresql://tscloud:tscloud@localhost:5432/tscloud",redisUrl:process.env.REDIS_URL||"redis://localhost:6379",dynamodbEndpoint:process.env.DYNAMODB_ENDPOINT||"http://localhost:8000",s3Endpoint:process.env.S3_ENDPOINT||"http://localhost:9000",emailEndpoint:process.env.EMAIL_ENDPOINT||"smtp://localhost:1025",awsRegion:process.env.AWS_REGION||"us-east-1",awsAccessKeyId:process.env.AWS_ACCESS_KEY_ID||"test",awsSecretAccessKey:process.env.AWS_SECRET_ACCESS_KEY||"test"};class dJ{environments=new Map;async createPreviewEnvironment($){let{branch:J,pr:Y,commitSha:Q,ttl:W=24,baseConfig:U,region:Z="us-east-1"}=$,z=this.generatePreviewId(J,Y,Q),H=this.generatePreviewName(J,Y),K=`preview-${H}`,B=new Date,O=new Date(B.getTime()+W*60*60*1000),X={id:z,name:H,branch:J,pr:Y,commitSha:Q,createdAt:B,expiresAt:O,status:"creating",stackName:K,region:Z,resources:[]};this.environments.set(z,X);try{let j=this.createPreviewConfig(U,H);return X.status="active",X.url=`https://${H}.preview.example.com`,X}catch(j){throw X.status="failed",j}}async destroyPreviewEnvironment($){let J=this.environments.get($);if(!J)throw Error(`Preview environment ${$} not found`);J.status="destroying";try{J.status="destroyed",this.environments.delete($)}catch(Y){throw Error(`Failed to destroy preview environment: ${Y}`)}}getPreviewEnvironment($){return this.environments.get($)}getPreviewEnvironmentByBranch($){return Array.from(this.environments.values()).find((J)=>J.branch===$)}getPreviewEnvironmentByPR($){return Array.from(this.environments.values()).find((J)=>J.pr===$)}listPreviewEnvironments(){return Array.from(this.environments.values())}listActivePreviewEnvironments(){return this.listPreviewEnvironments().filter(($)=>$.status==="active")}async cleanupExpiredEnvironments($={}){let{maxAge:J,keepCount:Y,dryRun:Q=!1}=$,W=[],U=[],Z=new Date,z=this.listPreviewEnvironments().sort((H,K)=>K.createdAt.getTime()-H.createdAt.getTime());for(let H=0;H<z.length;H++){let K=z[H];if(K.status!=="active")continue;let B=!1;if(K.expiresAt<Z)B=!0;if(J){if((Z.getTime()-K.createdAt.getTime())/3600000>J)B=!0}if(Y&&H>=Y)B=!0;if(B)if(Q)W.push(K.id);else try{await this.destroyPreviewEnvironment(K.id),W.push(K.id)}catch(O){U.push(K.id)}}return{destroyed:W,failed:U}}async updatePreviewEnvironment($,J){let Y=this.environments.get($);if(!Y)throw Error(`Preview environment ${$} not found`);Y.commitSha=J,Y.status="creating";try{return Y.status="active",Y}catch(Q){throw Y.status="failed",Q}}async getPreviewEnvironmentsCost(){let $={},J=0;for(let Y of this.environments.values())$[Y.id]=0,J+=0;return{total:J,byEnvironment:$}}generatePreviewId($,J,Y){let Q=$.replace(/[^a-z0-9-]/gi,"-").toLowerCase(),W=Y?.substring(0,7)||Date.now().toString();return J?`pr-${J}-${W}`:`${Q}-${W}`}generatePreviewName($,J){let Y=$.replace(/[^a-z0-9-]/gi,"-").toLowerCase();return J?`pr-${J}`:Y}createPreviewConfig($,J){return{...$,project:{...$.project,name:`${$.project.name} Preview (${J})`,slug:`${$.project.slug}-preview-${J}`}}}}var b7=new dJ;class mJ{channels=[];addChannel($){this.channels.push($)}removeChannel($){this.channels=this.channels.filter((J)=>J.type!==$)}async notify($){let J=this.channels.map((Y)=>this.sendToChannel(Y,$));await Promise.allSettled(J)}async sendToChannel($,J){switch($.type){case"slack":await this.sendToSlack($.config,J);break;case"discord":await this.sendToDiscord($.config,J);break;case"email":await this.sendToEmail($.config,J);break;case"webhook":await this.sendToWebhook($.config,J);break}}async sendToSlack($,J){let Y=this.formatSlackMessage(J,$),Q=await fetch($.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)});if(!Q.ok)throw Error(`Failed to send Slack notification: ${Q.statusText}`)}formatSlackMessage($,J){let{environment:Y,type:Q}=$,W={created:":rocket:",updated:":arrows_counterclockwise:",destroyed:":wastebasket:",failed:":x:",expired:":hourglass_flowing_sand:"}[Q],U={created:"#36a64f",updated:"#2196F3",destroyed:"#808080",failed:"#f44336",expired:"#ff9800"}[Q],Z={created:"Preview Environment Created",updated:"Preview Environment Updated",destroyed:"Preview Environment Destroyed",failed:"Preview Environment Failed",expired:"Preview Environment Expired"}[Q];return{username:J.username||"ts-cloud",icon_emoji:J.iconEmoji||":cloud:",channel:J.channel,attachments:[{color:U,title:`${W} ${Z}`,fields:[{title:"Environment",value:Y.name,short:!0},{title:"Branch",value:Y.branch,short:!0},...Y.pr?[{title:"PR",value:`#${Y.pr}`,short:!0}]:[],{title:"Commit",value:Y.commitSha.substring(0,7),short:!0},...Y.url?[{title:"URL",value:Y.url,short:!1}]:[],...Q==="created"?[{title:"Expires",value:Y.expiresAt.toLocaleString(),short:!0}]:[]],footer:"ts-cloud Preview Environments",ts:Math.floor($.timestamp.getTime()/1000)}]}}async sendToDiscord($,J){let Y=this.formatDiscordMessage(J,$),Q=await fetch($.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)});if(!Q.ok)throw Error(`Failed to send Discord notification: ${Q.statusText}`)}formatDiscordMessage($,J){let{environment:Y,type:Q}=$,W={created:":rocket:",updated:":arrows_counterclockwise:",destroyed:":wastebasket:",failed:":x:",expired:":hourglass:"}[Q],U={created:3581519,updated:2201331,destroyed:8421504,failed:16007990,expired:16750592}[Q],Z={created:"Preview Environment Created",updated:"Preview Environment Updated",destroyed:"Preview Environment Destroyed",failed:"Preview Environment Failed",expired:"Preview Environment Expired"}[Q];return{username:J.username||"ts-cloud",avatar_url:J.avatarUrl,embeds:[{title:`${W} ${Z}`,color:U,fields:[{name:"Environment",value:Y.name,inline:!0},{name:"Branch",value:Y.branch,inline:!0},...Y.pr?[{name:"PR",value:`#${Y.pr}`,inline:!0}]:[],{name:"Commit",value:`\`${Y.commitSha.substring(0,7)}\``,inline:!0},...Y.url?[{name:"URL",value:Y.url,inline:!1}]:[]],timestamp:$.timestamp.toISOString(),footer:{text:"ts-cloud Preview Environments"}}]}}async sendToEmail($,J){console.log(`Email notification would be sent to ${$.to.join(", ")}`)}async sendToWebhook($,J){let Y=await fetch($.url,{method:$.method||"POST",headers:{"Content-Type":"application/json",...$.headers},body:JSON.stringify({event:J.type,environment:J.environment,timestamp:J.timestamp.toISOString(),metadata:J.metadata})});if(!Y.ok)throw Error(`Failed to send webhook notification: ${Y.statusText}`)}}var y7=new mJ;class v7{total;current=0;width;format;message;showETA;showPercentage;showCounter;startTime=Date.now();lastUpdate=0;constructor($){this.total=$.total,this.current=$.current||0,this.width=$.width||40,this.format=$.format||":message :bar :percent :eta",this.message=$.message||"Progress",this.showETA=$.showETA!==!1,this.showPercentage=$.showPercentage!==!1,this.showCounter=$.showCounter!==!1}tick($=1){this.current=Math.min(this.total,this.current+$),this.lastUpdate=Date.now()}update($){this.current=Math.min(this.total,Math.max(0,$)),this.lastUpdate=Date.now()}setMessage($){this.message=$}getPercentage(){return Math.min(100,this.current/this.total*100)}getETA(){if(this.current===0)return 0;let $=Date.now()-this.startTime,J=this.current/$,Y=this.total-this.current;return Math.round(Y/J)}getETAFormatted(){if(this.current===0)return"calculating...";if(this.current===this.total)return"complete";let $=this.getETA();if($<1000)return"< 1s";if($<60000)return`${Math.round($/1000)}s`;let J=Math.floor($/60000);if(J<60)return`${J}m`;let Y=Math.floor(J/60),Q=J%60;if(Y<24)return Q>0?`${Y}h ${Q}m`:`${Y}h`;let W=Math.floor(Y/24),U=Y%24;return U>0?`${W}d ${U}h`:`${W}d`}render(){let $=this.getPercentage(),J=Math.floor(this.width*this.current/this.total),Y=this.width-J,Q="█".repeat(J)+"░".repeat(Y),W=`${$.toFixed(1)}%`,U=`${this.current}/${this.total}`,Z=this.showETA?`ETA: ${this.getETAFormatted()}`:"",z=this.format.replace(":message",this.message).replace(":bar",Q).replace(":percent",this.showPercentage?W:"").replace(":counter",this.showCounter?U:"").replace(":eta",Z).replace(":current",String(this.current)).replace(":total",String(this.total));return z=z.replace(/\s+/g," ").trim(),z}isComplete(){return this.current>=this.total}}class f7{variables=new Map;workingDirectory=process.cwd();set($,J){this.variables.set($,J)}get($){return this.variables.get($)}has($){return this.variables.has($)}delete($){this.variables.delete($)}getAll(){return Object.fromEntries(this.variables)}clear(){this.variables.clear()}setWorkingDirectory($){this.workingDirectory=$}getWorkingDirectory(){return this.workingDirectory}}class b8{deployments=new Map;async deploy($,J){let Y=this.generateDeploymentId(),Q={id:Y,regions:J.regions.map((W)=>({region:W.code,stackName:this.getStackName($,W.code),status:"pending"})),status:"deploying",startTime:new Date};this.deployments.set(Y,Q);try{let W=J.regions.find((Z)=>Z.isPrimary)||J.regions[0];await this.deployToRegion($,W,Q);let U=J.regions.filter((Z)=>Z.code!==W.code);if(await Promise.all(U.map((Z)=>this.deployToRegion($,Z,Q))),J.globalResources)await this.deployGlobalResources(Q,J);if(J.replication)await this.setupReplication(Q,J);if(J.failover?.enabled)await this.setupFailover(Q,J);return Q.status="deployed",Q.endTime=new Date,Q}catch(W){throw Q.status="failed",Q.endTime=new Date,W}}async deployToRegion($,J,Y){let Q=Y.regions.find((W)=>W.region===J.code);if(!Q)throw Error(`Region deployment not found: ${J.code}`);Q.status="deploying",Q.startTime=new Date;try{let W=this.createRegionConfig($,J);await this.deployStack(Q.stackName,W,J.code),Q.status="deployed",Q.endTime=new Date,Q.outputs={stackId:`arn:aws:cloudformation:${J.code}:123456789012:stack/${Q.stackName}/guid`,endpoint:`https://${Q.stackName}.${J.code}.example.com`}}catch(W){throw Q.status="failed",Q.endTime=new Date,Q.error=W instanceof Error?W.message:String(W),W}}async deployGlobalResources($,J){let Y={};if(J.globalResources?.route53)Y.route53=await this.deployRoute53($,J);if(J.globalResources?.cloudfront)Y.cloudfront=await this.deployCloudFront($,J);if(J.globalResources?.waf)Y.waf=await this.deployWAF($);$.globalResources=Y}async deployRoute53($,J){let Y=[],Q=[];for(let W of $.regions){if(W.status!=="deployed")continue;let U={id:`health-${W.region}`,endpoint:W.outputs?.endpoint,path:J.failover?.healthCheckPath||"/health",region:W.region};Y.push(U);let Z={name:"example.com",type:"A",region:W.region,setIdentifier:W.region,healthCheckId:U.id,resourceRecords:[W.outputs?.endpoint]};Q.push(Z)}return{healthChecks:Y,recordSets:Q,hostedZoneId:"Z1234567890ABC"}}async deployCloudFront($,J){return{distributionId:"E1234567890ABC",domainName:"d1234567890abc.cloudfront.net",origins:$.regions.filter((Q)=>Q.status==="deployed").map((Q,W)=>{let U=J.regions[W];return{id:`origin-${Q.region}`,domainName:Q.outputs?.endpoint,weight:U?.weight||100}}),status:"Deployed"}}async deployWAF($){return{webAclId:"arn:aws:wafv2:us-east-1:123456789012:global/webacl/test/a1234567-b890-c123-d456-e789012345f6",webAclArn:"arn:aws:wafv2:us-east-1:123456789012:global/webacl/test/a1234567-b890-c123-d456-e789012345f6"}}async setupReplication($,J){if(J.replication?.s3)await this.setupS3Replication($);if(J.replication?.dynamodb)await this.setupDynamoDBReplication($);if(J.replication?.secrets)await this.setupSecretsReplication($)}async setupS3Replication($){let J=$.regions.filter((Y)=>Y.status==="deployed");for(let Y=0;Y<J.length-1;Y++){let Q=J[Y],W=J[Y+1];console.log(`Setting up S3 replication: ${Q.region} -> ${W.region}`)}}async setupDynamoDBReplication($){let J=$.regions.filter((Y)=>Y.status==="deployed").map((Y)=>Y.region);console.log(`Setting up DynamoDB global table in regions: ${J.join(", ")}`)}async setupSecretsReplication($){let J=$.regions.filter((Y)=>Y.status==="deployed").map((Y)=>Y.region);console.log(`Setting up Secrets Manager replication in regions: ${J.join(", ")}`)}async setupFailover($,J){let Y=$.regions.find((W,U)=>J.regions[U]?.isPrimary)||$.regions[0],Q=$.regions.filter((W)=>W.region!==Y.region);console.log(`Setting up failover: primary=${Y.region}, secondary=${Q.map((W)=>W.region).join(", ")}`)}async destroy($){let J=this.deployments.get($);if(!J)throw Error(`Deployment not found: ${$}`);J.status="rolling-back";try{if(J.globalResources)await this.destroyGlobalResources(J.globalResources);await Promise.all(J.regions.map((Y)=>this.destroyRegionStack(Y))),this.deployments.delete($)}catch(Y){throw J.status="failed",Y}}async destroyGlobalResources($){if($.waf)console.log("Destroying WAF resources");if($.cloudfront)console.log("Destroying CloudFront distribution");if($.route53)console.log("Destroying Route53 resources")}async destroyRegionStack($){if($.status!=="deployed")return;$.status="rolling-back";try{console.log(`Destroying stack ${$.stackName} in ${$.region}`),$.status="pending"}catch(J){throw $.status="failed",$.error=J instanceof Error?J.message:String(J),J}}getDeployment($){return this.deployments.get($)}listDeployments(){return Array.from(this.deployments.values())}getStackName($,J){return`${$.project.slug}-${J}`}createRegionConfig($,J){return{...$,infrastructure:{...$.infrastructure}}}async deployStack($,J,Y){console.log(`Deploying stack ${$} to ${Y}`)}generateDeploymentId(){return`deploy-${Date.now()}-${Math.random().toString(36).substring(7)}`}}var VK=new b8;class y8{references=[];exports=new Map;addExport($){let J=`${$.region}:${$.exportName}`;if(!this.exports.has($.region))this.exports.set($.region,[]);this.exports.get($.region).push($)}getExport($,J){let Y=this.exports.get($);if(!Y)return;return Y.find((W)=>W.exportName===J)?.value}createReference($,J,Y,Q){let W=`/cross-region/${$}/${Y}/${Q}`;return this.references.push({sourceRegion:$,targetRegion:J,resourceType:Y,resourceId:Q,value:W}),W}async resolveReference($,J){let Y=this.references.find((Q)=>Q.targetRegion===$&&Q.value===J);if(!Y)throw Error(`Reference not found: ${J}`);return`arn:aws:resource:${Y.sourceRegion}:123456789012:${Y.resourceType}/${Y.resourceId}`}getReferencesForRegion($){return this.references.filter((J)=>J.sourceRegion===$||J.targetRegion===$)}clear(){this.references=[],this.exports.clear()}}class v8{resources=new Map;register($){this.resources.set($.id,$)}get($){return this.resources.get($)}getByType($){return Array.from(this.resources.values()).filter((J)=>J.type===$)}getCloudFrontDistributions(){return this.getByType("cloudfront")}getRoute53HostedZones(){return this.getByType("route53")}getWAFWebACLs(){return this.getByType("waf")}remove($){this.resources.delete($)}clear(){this.resources.clear()}}class f8{pairs=[];addPair($){this.pairs.push($)}getPairedRegion($){let J=this.pairs.find((Y)=>Y.primary===$||Y.secondary===$);if(!J)return;return J.primary===$?J.secondary:J.primary}getAllPairs(){return[...this.pairs]}getReplicatedPairs(){return this.pairs.filter(($)=>$.replicationConfig)}getFailoverPairs(){return this.pairs.filter(($)=>$.failoverConfig?.automatic)}arePaired($,J){return this.pairs.some((Y)=>Y.primary===$&&Y.secondary===J||Y.primary===J&&Y.secondary===$)}clear(){this.pairs=[]}}class g8{dependencies=[];addDependency($){this.dependencies.push($)}getDependencies($,J){return this.dependencies.filter((Y)=>Y.dependentStack===$&&Y.dependentRegion===J)}getDependents($,J){return this.dependencies.filter((Y)=>Y.dependsOnStack===$&&Y.dependsOnRegion===J)}hasDependencies($,J){return this.getDependencies($,J).length>0}getDeploymentOrder($){let J=new Set,Y=[],Q=(W)=>{let U=`${W.name}:${W.region}`;if(J.has(U))return;J.add(U);let Z=this.getDependencies(W.name,W.region);for(let z of Z)Q({name:z.dependsOnStack,region:z.dependsOnRegion});Y.push(W)};for(let W of $)Q(W);return Y}detectCircularDependencies(){let $=new Set,J=new Set,Y=(Q,W)=>{let U=`${Q}:${W}`;if(J.has(U))return!0;if($.has(U))return!1;$.add(U),J.add(U);let Z=this.getDependencies(Q,W);for(let z of Z)if(Y(z.dependsOnStack,z.dependsOnRegion))return!0;return J.delete(U),!1};for(let Q of this.dependencies)if(Y(Q.dependentStack,Q.dependentRegion))return!0;return!1}clear(){this.dependencies=[]}}var EK=new y8,_K=new v8,FK=new f8,wK=new g8;class u8{accounts=new Map;crossAccountRoles=[];accountMappings=[];registerAccount($){this.accounts.set($.id,$)}getAccount($){return this.accounts.get($)}getAccountByAlias($){return Array.from(this.accounts.values()).find((J)=>J.alias===$)}listAccounts(){return Array.from(this.accounts.values())}getAccountsByRole($){return Array.from(this.accounts.values()).filter((J)=>J.role===$)}createCrossAccountRole($,J,Y,Q,W){let U={roleArn:`arn:aws:iam::${J}:role/${Y}`,roleName:Y,sourceAccountId:$,targetAccountId:J,permissions:Q,externalId:W?.externalId,sessionDuration:W?.sessionDuration||3600};return this.crossAccountRoles.push(U),U}getAssumeRolePolicyDocument($,J){let Y={Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:`arn:aws:iam::${$}:root`},Action:"sts:AssumeRole"}]};if(J)Y.Statement[0].Condition={StringEquals:{"sts:ExternalId":J}};return Y}generateCrossAccountPolicy($){return{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:$,Resource:"*"}]}}mapEnvironmentToAccount($,J,Y){this.accountMappings.push({environment:$,accountId:J,region:Y})}getAccountForEnvironment($){return this.accountMappings.find((J)=>J.environment===$)}async assumeRole($,J,Y){return console.log(`Assuming role: ${$} with session: ${J}`),{accessKeyId:"AKIAIOSFODNN7EXAMPLE",secretAccessKey:"wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",sessionToken:"token",expiration:new Date(Date.now()+3600000)}}async getCredentialsForAccount($){let J=this.accounts.get($);if(!J)throw Error(`Account not found: ${$}`);if(J.assumeRoleArn){let Y=await this.assumeRole(J.assumeRoleArn,`ts-cloud-${Date.now()}`);return{accessKeyId:Y.accessKeyId,secretAccessKey:Y.secretAccessKey,sessionToken:Y.sessionToken}}throw Error("No credentials available for account")}listCrossAccountRoles(){return[...this.crossAccountRoles]}getCrossAccountRolesForAccount($){return this.crossAccountRoles.filter((J)=>J.sourceAccountId===$||J.targetAccountId===$)}async validateAccountAccess($){try{let J=await this.getCredentialsForAccount($);return console.log(`Validating access to account: ${$}`),!0}catch{return!1}}async getConsolidatedBilling(){let $={};for(let Y of this.accounts.values())$[Y.id]=Math.random()*1000;return{totalCost:Object.values($).reduce((Y,Q)=>Y+Q,0),byAccount:$}}clear(){this.accounts.clear(),this.crossAccountRoles=[],this.accountMappings=[]}}class d8{organizationId;organizationalUnits=new Map;getOrganizationId(){return this.organizationId}setOrganizationId($){this.organizationId=$}createOrganizationalUnit($,J){let Y={id:`ou-${Date.now()}`,name:$,parentId:J,accounts:[]};return this.organizationalUnits.set(Y.id,Y),Y}getOrganizationalUnit($){return this.organizationalUnits.get($)}listOrganizationalUnits(){return Array.from(this.organizationalUnits.values())}addAccountToOU($,J){let Y=this.organizationalUnits.get($);if(!Y)throw Error(`Organizational unit not found: ${$}`);if(!Y.accounts.includes(J))Y.accounts.push(J)}removeAccountFromOU($,J){let Y=this.organizationalUnits.get($);if(!Y)throw Error(`Organizational unit not found: ${$}`);Y.accounts=Y.accounts.filter((Q)=>Q!==J)}getAccountsInOU($){let J=this.organizationalUnits.get($);if(!J)return[];return[...J.accounts]}applyServiceControlPolicy($,J){return{id:`scp-${Date.now()}`,name:"Custom SCP",targetId:$,policyDocument:J}}clear(){this.organizationId=void 0,this.organizationalUnits.clear()}}var PK=new u8,CK=new d8;class cJ{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++}`,Y={id:J,...$};return this.backupPlans.set(J,Y),Y}getBackupPlan($){return this.backupPlans.get($)}listBackupPlans(){return Array.from(this.backupPlans.values())}createRDSBackupPlan($){let{dbInstanceArn:J,schedule:Y="0 2 * * *",retentionDays:Q=7,vaultName:W="default-vault"}=$;return this.createBackupPlan({name:"RDS Daily Backup",schedule:Y,retentionDays:Q,vaultName:W,resources:[{resourceArn:J,resourceType:"rds",region:"us-east-1"}],lifecycle:{moveTocoldStorageAfterDays:30,deleteAfterDays:Q}})}createDynamoDBBackupPlan($){let{tableArn:J,schedule:Y="0 3 * * *",retentionDays:Q=35,crossRegionCopy:W}=$;return this.createBackupPlan({name:"DynamoDB Daily Backup",schedule:Y,retentionDays:Q,vaultName:"dynamodb-vault",resources:[{resourceArn:J,resourceType:"dynamodb",region:"us-east-1"}],lifecycle:{deleteAfterDays:Q},tags:W?{CrossRegionCopy:W.join(",")}:void 0})}createEFSBackupPlan($){let{fileSystemArn:J,schedule:Y="0 1 * * *",retentionDays:Q=30}=$;return this.createBackupPlan({name:"EFS Daily Backup",schedule:Y,retentionDays:Q,vaultName:"efs-vault",resources:[{resourceArn:J,resourceType:"efs",region:"us-east-1"}],lifecycle:{deleteAfterDays:Q}})}enableContinuousBackup($,J=35){let Y=`continuous-backup-${Date.now()}-${this.continuousBackupCounter++}`,Q={id:Y,resourceId:$,enabled:!0,retentionDays:J};return this.continuousBackups.set(Y,Q),Q}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:Y,targetRegion:Q}=$,W={id:`restore-${Date.now()}-${this.restoreCounter++}`,backupId:J,resourceType:Y,status:"pending",startTime:new Date,targetRegion:Q};return this.restoreJobs.set(W.id,W),setTimeout(()=>{W.status="running"},100),setTimeout(()=>{W.status="completed",W.endTime=new Date},1000),W}async restoreToPointInTime($){let{sourceResourceArn:J,targetResourceName:Y,restoreTime:Q,resourceType:W}=$,U={id:`pitr-${Date.now()}-${this.restoreCounter++}`,backupId:`pitr-${Q.getTime()}`,resourceType:W,status:"pending",startTime:new Date};return this.restoreJobs.set(U.id,U),console.log(`Restoring ${W} from ${J} to ${Y} at ${Q.toISOString()}`),setTimeout(()=>{U.status="completed",U.endTime=new Date},2000),U}getRestoreJob($){return this.restoreJobs.get($)}listRestoreJobs(){return Array.from(this.restoreJobs.values())}setupCrossRegionReplication($){let{sourceVault:J,sourceRegion:Y,targetRegions:Q}=$;console.log("Setting up cross-region replication:"),console.log(` Source: ${J} in ${Y}`),console.log(` Targets: ${Q.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 g7=new cJ;class lJ{drPlans=new Map;failoverTests=new Map;planCounter=0;testCounter=0;createDRPlan($){let J=`dr-plan-${Date.now()}-${this.planCounter++}`,Y={id:J,...$};return this.drPlans.set(J,Y),Y}createRDSDRPlan($){let{primaryDbArn:J,secondaryDbArn:Y,primaryRegion:Q,secondaryRegion:W,rto:U=60,rpo:Z=5}=$;return this.createDRPlan({name:"RDS Multi-Region DR",primaryRegion:Q,secondaryRegion:W,rto:U,rpo:Z,resources:[{resourceId:"primary-db",resourceType:"rds",primaryArn:J,secondaryArn:Y,replicationEnabled:!0}],runbook:this.generateRDSRunbook(Q,W),testSchedule:"0 0 1 * *"})}createDynamoDBDRPlan($){let{tableArn:J,regions:Y,rto:Q=15,rpo:W=1}=$;return this.createDRPlan({name:"DynamoDB Global Tables DR",primaryRegion:Y[0],secondaryRegion:Y[1],rto:Q,rpo:W,resources:[{resourceId:"dynamodb-table",resourceType:"dynamodb",primaryArn:J,replicationEnabled:!0}],runbook:this.generateDynamoDBRunbook(Y)})}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 Y=this.drPlans.get($);if(!Y)throw Error(`DR plan not found: ${$}`);let Q=Date.now(),W=0;console.log(`${J?"[DRY RUN] ":""}Executing failover for plan: ${Y.name}`),console.log(`Primary: ${Y.primaryRegion} -> Secondary: ${Y.secondaryRegion}`),console.log(`RTO: ${Y.rto} minutes, RPO: ${Y.rpo} minutes`),console.log("");for(let Z of Y.runbook.steps){if(console.log(`Step ${Z.order}: ${Z.name}`),console.log(` ${Z.description}`),console.log(` Action: ${Z.action}`),console.log(` Estimated: ${Z.estimatedDuration} minutes`),J)console.log(" [SKIPPED - DRY RUN]");else if(Z.automatable)console.log(" [AUTOMATED]");else console.log(" [MANUAL - WAITING]");W++,console.log("")}return{success:!0,duration:(Date.now()-Q)/1000/60,completedSteps:W}}scheduleFailoverTest($,J){let Y={id:`failover-test-${Date.now()}-${this.testCounter++}`,planId:$,status:"scheduled",startTime:J};return this.failoverTests.set(Y.id,Y),Y}async runFailoverTest($){let J=this.drPlans.get($);if(!J)throw Error(`DR plan not found: ${$}`);let Y={id:`failover-test-${Date.now()}-${this.testCounter++}`,planId:$,status:"running",startTime:new Date,results:[]};this.failoverTests.set(Y.id,Y),console.log(`Running failover test for plan: ${J.name}`),console.log("This is a non-destructive test using test resources"),console.log("");for(let Q of J.runbook.steps){let W=Date.now();console.log(`Testing step ${Q.order}: ${Q.name}`);let U={step:Q.name,status:"success",duration:(Date.now()-W)/1000,message:`Successfully validated step ${Q.order}`};Y.results.push(U)}return Y.status="completed",Y.endTime=new Date,Y}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=[],Y=[];if($.rto<$.rpo)Y.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)Y.push("No resources defined in DR plan");for(let U of $.resources){if(!U.replicationEnabled)J.push(`Resource ${U.resourceId} does not have replication enabled`);if(!U.secondaryArn&&U.resourceType!=="dynamodb")J.push(`Resource ${U.resourceId} does not have secondary resource defined`)}if($.runbook.steps.length===0)Y.push("No recovery steps defined in runbook");let Q=$.runbook.steps.reduce((U,Z)=>U+Z.estimatedDuration,0);if(Q>$.rto)J.push(`Estimated recovery duration (${Q}m) exceeds RTO (${$.rto}m)`);let W=$.runbook.steps.filter((U)=>!U.automatable);if(W.length>0)J.push(`${W.length} manual steps in runbook - consider automation`);return{valid:Y.length===0,warnings:J,errors:Y}}clear(){this.drPlans.clear(),this.failoverTests.clear(),this.planCounter=0,this.testCounter=0}}var u7=new lJ;class pJ{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++}`,Y={id:J,...$};return this.configRules.set(J,Y),Y}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 d7=new pJ;class rJ{trails=new Map;trailCounter=0;createTrail($){let J=`trail-${Date.now()}-${this.trailCounter++}`,Y={id:J,...$};return this.trails.set(J,Y),Y}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((Y)=>`arn:aws:s3:::${Y}/*`)});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((Y)=>({ReadWriteType:Y.readWriteType,IncludeManagementEvents:Y.includeManagementEvents??!0,...Y.dataResources&&{DataResources:Y.dataResources.map((Q)=>({Type:Q.type,Values:Q.values}))},...Y.excludeManagementEventSources&&{ExcludeManagementEventSources:Y.excludeManagementEventSources}}));if($.insightSelectors)J.Properties.InsightSelectors=$.insightSelectors.map((Y)=>({InsightType:Y.insightType}));if($.advancedEventSelectors)J.Properties.AdvancedEventSelectors=$.advancedEventSelectors.map((Y)=>({Name:Y.name,FieldSelectors:Y.fieldSelectors.map((Q)=>({Field:Q.field,...Q.equals&&{Equals:Q.equals},...Q.startsWith&&{StartsWith:Q.startsWith},...Q.endsWith&&{EndsWith:Q.endsWith},...Q.notEquals&&{NotEquals:Q.notEquals},...Q.notStartsWith&&{NotStartsWith:Q.notStartsWith},...Q.notEndsWith&&{NotEndsWith:Q.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((Y)=>`arn:aws:s3:::${$}/AWSLogs/${Y}/*`),Condition:{StringEquals:{"s3:x-amz-acl":"bucket-owner-full-control"}}}]}}clear(){this.trails.clear(),this.trailCounter=0}}var m7=new rJ;class aJ{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++}`,Y={id:J,...$};return this.detectors.set(J,Y),Y}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++}`,Y={id:J,...$};return this.threatIntelSets.set(J,Y),Y}createIPSet($){let J=`ip-set-${Date.now()}-${this.ipSetCounter++}`,Y={id:J,...$};return this.ipSets.set(J,Y),Y}createFindingFilter($){let J=`filter-${Date.now()}-${this.filterCounter++}`,Y={id:J,...$};return this.filters.set(J,Y),Y}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,Y){return this.createFindingFilter({detectorId:$,name:`filter-finding-types-${Y.toLowerCase()}`,description:`${Y==="ARCHIVE"?"Archive":"Keep"} specific finding types`,action:Y,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((Y)=>({Name:Y.name,Status:Y.status,...Y.additionalConfiguration&&{AdditionalConfiguration:Y.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 c7=new aJ;class R0{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++}`,Y={id:J,...$};return this.hubs.set(J,Y),Y}createComprehensiveHub(){return this.createHub({enable:!0,controlFindingGenerator:"SECURITY_CONTROL",enableDefaultStandards:!0,standards:[{id:"aws-foundational",...R0.Standards.AWS_FOUNDATIONAL_SECURITY,enabled:!0},{id:"cis-1-4",...R0.Standards.CIS_AWS_FOUNDATIONS_1_4,enabled:!0},{id:"pci-dss",...R0.Standards.PCI_DSS,enabled:!0}]})}createBasicHub(){return this.createHub({enable:!0,controlFindingGenerator:"STANDARD_CONTROL",enableDefaultStandards:!0,standards:[{id:"aws-foundational",...R0.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((Y)=>({value:Y,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((Y)=>({StandardsControlArn:Y,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 l7=new R0;class nJ{deployments=new Map;deploymentHistory=new Map;deploymentCounter=0;resultCounter=0;createDeployment($){let J=`bg-deployment-${Date.now()}-${this.deploymentCounter++}`,Y={id:J,...$};return this.deployments.set(J,Y),Y}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 Y=this.deployments.get($);if(!Y)throw Error(`Deployment not found: ${$}`);let Q={success:!1,deploymentId:`result-${Date.now()}-${this.resultCounter++}`,startTime:new Date,healthChecksPassed:!1,errors:[]};console.log(`${J?"[DRY RUN] ":""}Starting blue/green deployment: ${Y.name}`),console.log(` Active environment: ${Y.activeEnvironment}`),console.log(` Routing type: ${Y.routingConfig.type}`);let W=Y.activeEnvironment==="blue"?"green":"blue";if(console.log(` Switching to: ${W}`),console.log(`\\n1. Deploying to ${W} environment`),!J)await new Promise((U)=>setTimeout(U,100));if(console.log(`\\n2. Running health checks on ${W} environment`),Y.healthCheckConfig){let U=await this.runHealthChecks(Y,W,J);if(Q.healthChecksPassed=U,!U){if(Q.errors?.push("Health checks failed"),Q.endTime=new Date,Y.autoRollback)console.log(" Auto-rollback enabled - keeping current environment active"),Q.rolledBackAt=new Date;return this.recordDeployment($,Q),Q}}else Q.healthChecksPassed=!0;if(console.log(`\\n3. Switching traffic to ${W} environment`),!J)Y.activeEnvironment=W,Q.switchedAt=new Date;if(console.log(`\\n4. Monitoring ${W} environment`),!J)await new Promise((U)=>setTimeout(U,100));return Q.success=!0,Q.endTime=new Date,console.log("\\n✓ Deployment completed successfully"),this.recordDeployment($,Q),Q}async rollback($){let J=this.deployments.get($);if(!J)throw Error(`Deployment not found: ${$}`);let Y={success:!1,deploymentId:`result-${Date.now()}-${this.resultCounter++}`,startTime:new Date,healthChecksPassed:!0,errors:[]};console.log(`Rolling back deployment: ${J.name}`);let Q=J.activeEnvironment==="blue"?"green":"blue";return J.activeEnvironment=Q,Y.success=!0,Y.rolledBackAt=new Date,Y.endTime=new Date,console.log(` Switched back to: ${Q}`),this.recordDeployment($,Y),Y}async runHealthChecks($,J,Y){let Q=$.healthCheckConfig;if(console.log(` Health check path: ${Q.path||"/"}`),console.log(` Healthy threshold: ${Q.healthyThreshold}`),console.log(` Interval: ${Q.interval}s`),Y)return console.log(" [SKIPPED - DRY RUN]"),!0;let W=0,U=Q.healthyThreshold+2;for(let Z=0;Z<U;Z++)if(await new Promise((H)=>setTimeout(H,50)),Math.random()>0.1){if(W++,console.log(` Check ${Z+1}: ✓ Healthy (${W}/${Q.healthyThreshold})`),W>=Q.healthyThreshold)return!0}else W=0,console.log(` Check ${Z+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 p7=new nJ;class n0{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++}`,Y={id:J,...$};return this.deployments.set(J,Y),Y}createLambdaCanaryDeployment($){let J=$.strategy||"BALANCED",Y=n0.Strategies[J].map((Q)=>({...Q,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:Y,currentStage:0,status:"pending",autoPromote:$.autoPromote??!0,autoRollback:!0})}createECSCanaryDeployment($){let J=$.strategy||"CONSERVATIVE",Y=n0.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:Y,currentStage:0,status:"pending",autoRollback:!0})}async executeDeployment($,J=!1){let Y=this.deployments.get($);if(!Y)throw Error(`Deployment not found: ${$}`);let Q={success:!1,deploymentId:`result-${Date.now()}-${this.resultCounter++}`,startTime:new Date,completedStages:0,rolledBack:!1};console.log(`${J?"[DRY RUN] ":""}Starting canary deployment: ${Y.name}`),console.log(` Strategy: ${Y.stages.length} stages`),console.log(` Auto-promote: ${Y.autoPromote}`),console.log(` Auto-rollback: ${Y.autoRollback}`),console.log(""),Y.status="in_progress";for(let W=0;W<Y.stages.length;W++){let U=Y.stages[W];if(Y.currentStage=W,console.log(`Stage ${W+1}/${Y.stages.length}: ${U.name}`),console.log(` Traffic: ${U.trafficPercentage}% canary, ${100-U.trafficPercentage}% baseline`),console.log(` Duration: ${U.durationMinutes} minutes`),!J)Y.baselineVersion.weight=100-U.trafficPercentage,Y.canaryVersion.weight=U.trafficPercentage;if(!await this.monitorStage(Y,U,J)){if(console.log(" ✗ Stage failed - metrics exceeded thresholds"),Y.autoRollback)console.log("\\n Rolling back deployment..."),await this.rollback($,J),Q.rolledBack=!0,Q.reason="Metrics exceeded thresholds";return Q.endTime=new Date,Y.status="rolled_back",this.recordDeployment($,Q),Q}console.log(" ✓ Stage completed successfully"),Q.completedStages++,console.log("")}return Y.status="completed",Q.success=!0,Q.endTime=new Date,console.log("✓ Canary deployment completed successfully"),this.recordDeployment($,Q),Q}async monitorStage($,J,Y){if(console.log(" Monitoring metrics..."),Y)return console.log(" [SKIPPED - DRY RUN]"),!0;await new Promise((W)=>setTimeout(W,100));let Q={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=Q,console.log(` Baseline: ${Q.baselineErrorRate.toFixed(2)}% errors, ${Q.baselineLatencyP99.toFixed(0)}ms P99`),console.log(` Canary: ${Q.canaryErrorRate.toFixed(2)}% errors, ${Q.canaryLatencyP99.toFixed(0)}ms P99`),J.alarmThresholds){let{errorRate:W,latencyP99:U}=J.alarmThresholds;if(W&&Q.canaryErrorRate>W)return console.log(` ⚠ Error rate exceeded threshold: ${Q.canaryErrorRate.toFixed(2)}% > ${W}%`),!1;if(U&&Q.canaryLatencyP99>U)return console.log(` ⚠ Latency P99 exceeded threshold: ${Q.canaryLatencyP99.toFixed(0)}ms > ${U}ms`),!1}return!0}async rollback($,J=!1){let Y=this.deployments.get($);if(!Y)throw Error(`Deployment not found: ${$}`);if(console.log(`${J?"[DRY RUN] ":""}Rolling back canary deployment: ${Y.name}`),!J)Y.baselineVersion.weight=100,Y.canaryVersion.weight=0,Y.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 Y=J.baselineVersion;J.baselineVersion=J.canaryVersion,J.canaryVersion=Y,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 r7=new n0;class sJ{tests=new Map;testCounter=0;createTest($){let J=`abtest-${Date.now()}-${this.testCounter++}`,Y={id:J,...$};return this.tests.set(J,Y),Y}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,Q)=>Y+Q.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,Q)=>({id:`variant-${Q}`,name:Y.name,description:Y.description,trafficPercentage:Y.trafficPercentage,targetGroupArn:Y.targetGroupArn,weight:Y.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((Y)=>{console.log(` - ${Y.name}: ${Y.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,Y){let Q=this.tests.get($);if(!Q)throw Error(`Test not found: ${$}`);let W=Q.variants.find((Z)=>Z.id===J);if(!W)throw Error(`Variant not found: ${J}`);let U=W.trafficPercentage;W.trafficPercentage=Y,W.weight=Y,console.log(`Updated ${W.name} traffic: ${U}% → ${Y}%`)}analyzeResults($){let J=this.tests.get($);if(!J)throw Error(`Test not found: ${$}`);if(!J.metrics)J.metrics=this.collectMetrics(J);let Y=J.variants[0],Q=0;for(let K of J.variants){let B=J.metrics.variants[K.id];if(B&&B.conversionRate>Q)Q=B.conversionRate,Y=K}let W=J.metrics.variants.control||J.metrics.variants[J.variants[0].id],U=J.metrics.variants[Y.id],Z=(U.conversionRate-W.conversionRate)/W.conversionRate*100,z=100,H=U.requests>z&&W.requests>z&&Math.abs(Z)>10;return{testId:$,winningVariant:Y.name,confidence:H?95:75,improvement:Z,statisticalSignificance:H,metrics:J.metrics,recommendation:this.generateRecommendation(Z,H,Y.name)}}declareWinner($,J){let Y=this.tests.get($);if(!Y)throw Error(`Test not found: ${$}`);let Q=Y.variants.find((W)=>W.id===J);if(!Q)throw Error(`Variant not found: ${J}`);Y.variants.forEach((W)=>{if(W.id===J)W.trafficPercentage=100,W.weight=100;else W.trafficPercentage=0,W.weight=0}),Y.status="completed",Y.endTime=new Date,Y.winner=J,console.log(`Declared winner: ${Q.name}`),console.log(` All traffic now routed to ${Q.name}`)}collectMetrics($){let J={},Y=0;for(let Q of $.variants){let W=Math.floor(Math.random()*1000)+500,U=Math.floor(W*(Math.random()*0.1+0.05)),Z=U/W*100;J[Q.id]={requests:W,conversions:U,conversionRate:Z,averageLatency:150+Math.random()*100,errorRate:Math.random()*0.5,revenue:U*(Math.random()*50+100)},Y+=W}return{variants:J,totalRequests:Y,startTime:$.startTime,lastUpdated:new Date}}generateRecommendation($,J,Y){if(!J)return"Continue test - sample size too small or no significant difference detected";if($>20)return`Strong winner detected - ${Y} shows ${$.toFixed(1)}% improvement. Recommend deploying to all traffic.`;if($>10)return`Moderate improvement - ${Y} shows ${$.toFixed(1)}% improvement. Consider deploying.`;if($>0)return`Minor improvement - ${Y} 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';
866
+
867
+ exports.handler = (event, context, callback) => {
868
+ const request = event.Records[0].cf.request;
869
+ const headers = request.headers;
870
+
871
+ // Check for existing variant cookie
872
+ let variant = null;
873
+ if (headers.cookie) {
874
+ const cookies = headers.cookie[0].value.split(';');
875
+ for (const cookie of cookies) {
876
+ const [key, value] = cookie.trim().split('=');
877
+ if (key === '${$.routingStrategy.cookieName||"ab_variant"}') {
878
+ variant = value;
879
+ break;
880
+ }
881
+ }
882
+ }
883
+
884
+ // Assign variant if not already assigned
885
+ if (!variant) {
886
+ const random = Math.random() * 100;
887
+ let cumulative = 0;
888
+
889
+ ${$.variants.map((J,Y)=>{return`if (random < ${J.trafficPercentage+(Y>0?$.variants.slice(0,Y).reduce((Q,W)=>Q+W.trafficPercentage,0):0)}) {
890
+ variant = '${J.id}';
891
+ }`}).join(" else ")}
892
+ }
893
+
894
+ // Set variant cookie
895
+ const response = {
896
+ status: '200',
897
+ statusDescription: 'OK',
898
+ headers: {
899
+ 'set-cookie': [{
900
+ key: 'Set-Cookie',
901
+ value: \`${$.routingStrategy.cookieName||"ab_variant"}=\${variant}; Path=/; Max-Age=${($.routingStrategy.sessionDuration||1440)*60}\`
902
+ }]
903
+ }
904
+ };
905
+
906
+ // Route to appropriate origin based on variant
907
+ ${$.variants.map((J)=>`if (variant === '${J.id}') {
908
+ request.origin.custom.domainName = '${J.originId}';
909
+ }`).join(" else ")}
910
+
911
+ callback(null, request);
912
+ };`}clear(){this.tests.clear(),this.testCounter=0}}var a7=new sJ;class iJ{rollouts=new Map;flags=new Map;gates=new Map;counter=0;createProgressiveRollout($,J){let Y=`rollout-${Date.now()}-${this.counter++}`,Q={id:Y,name:$,stages:J,currentStage:0};return this.rollouts.set(Y,Q),Q}createFeatureFlag($,J=0){let Y=`flag-${Date.now()}-${this.counter++}`,Q={id:Y,name:$,enabled:!1,rolloutPercentage:J,targetingRules:[]};return this.flags.set(Y,Q),Q}createDeploymentGate($,J,Y,Q){let W=`gate-${Date.now()}-${this.counter++}`,U={id:W,name:$,type:J,approvers:Y,conditions:Q};return this.gates.set(W,U),U}clear(){this.rollouts.clear(),this.flags.clear(),this.gates.clear()}}var n7=new iJ;class m8{configs=new Map;samplingRules=new Map;configCounter=0;ruleCounter=0;createConfig($){let J=`xray-config-${Date.now()}-${this.configCounter++}`,Y={id:J,...$};return this.configs.set(J,Y),Y}createLambdaConfig($){return this.createConfig({name:`${$.functionName}-xray`,serviceName:$.functionName,samplingRate:$.samplingRate||0.1,enableActiveTracing:!0})}createECSConfig($){return this.createConfig({name:`${$.serviceName}-xray`,serviceName:`${$.clusterName}/${$.serviceName}`,samplingRate:$.samplingRate||0.05,enableActiveTracing:!0})}createAPIGatewayConfig($){return this.createConfig({name:`${$.apiName}-${$.stage}-xray`,serviceName:`${$.apiName}/${$.stage}`,samplingRate:$.samplingRate||0.05,enableActiveTracing:!0})}createSamplingRule($){let J=`sampling-rule-${Date.now()}-${this.ruleCounter++}`,Y={id:J,...$};return this.samplingRules.set(J,Y),Y}createHighPrioritySamplingRule($){return this.createSamplingRule({ruleName:$.ruleName,priority:100,fixedRate:1,reservoirSize:100,serviceName:$.serviceName,serviceType:"*",host:"*",httpMethod:"*",urlPath:$.urlPath,version:1})}createErrorSamplingRule($){return this.createSamplingRule({ruleName:`${$}-errors`,priority:200,fixedRate:1,reservoirSize:50,serviceName:$,serviceType:"*",host:"*",httpMethod:"*",urlPath:"/error/*",version:1})}createDefaultSamplingRule($,J=0.05){return this.createSamplingRule({ruleName:`${$}-default`,priority:1000,fixedRate:J,reservoirSize:10,serviceName:$,serviceType:"*",host:"*",httpMethod:"*",urlPath:"*",version:1})}getConfig($){return this.configs.get($)}listConfigs(){return Array.from(this.configs.values())}getSamplingRule($){return this.samplingRules.get($)}listSamplingRules(){return Array.from(this.samplingRules.values())}generateLambdaXRayCF($){return{TracingConfig:{Mode:$.enableActiveTracing?"Active":"PassThrough"}}}generateAPIGatewayXRayCF($){return{TracingEnabled:$.enableActiveTracing}}generateECSXRaySidecarCF(){return{Name:"xray-daemon",Image:"public.ecr.aws/xray/aws-xray-daemon:latest",Cpu:32,MemoryReservation:256,PortMappings:[{ContainerPort:2000,Protocol:"udp"}]}}generateSamplingRuleCF($){return{Type:"AWS::XRay::SamplingRule",Properties:{SamplingRule:{RuleName:$.ruleName,Priority:$.priority,FixedRate:$.fixedRate,ReservoirSize:$.reservoirSize,ServiceName:$.serviceName,ServiceType:$.serviceType,Host:$.host,HTTPMethod:$.httpMethod,URLPath:$.urlPath,Version:$.version,ResourceARN:"*"}}}}createTrace($,J){return{id:`trace-${Date.now()}-${this.configCounter++}`,traceId:$,spans:J}}clear(){this.configs.clear(),this.samplingRules.clear(),this.configCounter=0,this.ruleCounter=0}}var ZB=new m8;class c8{namespaces=new Map;metrics=new Map;namespaceCounter=0;metricCounter=0;alarmCounter=0;createNamespace($){let J=`namespace-${Date.now()}-${this.namespaceCounter++}`,Y={id:J,...$};return this.namespaces.set(J,Y),Y}createMetric($){let J=`metric-${Date.now()}-${this.metricCounter++}`,Y={id:J,...$};return this.metrics.set(J,Y),Y}createBusinessMetric($){return this.createMetric({name:$.name,namespace:$.namespace,unit:$.unit,dimensions:[{name:"Environment",value:"production"},{name:"Type",value:"Business"}]})}createApplicationMetric($){return this.createMetric({name:$.name,namespace:$.namespace,unit:$.unit,dimensions:[{name:"Service",value:$.serviceName},{name:"Type",value:"Application"}]})}createPerformanceMetric($){return this.createMetric({name:$.name,namespace:$.namespace,unit:"Milliseconds",dimensions:[{name:"Operation",value:$.operation},{name:"Type",value:"Performance"}]})}createErrorMetric($){return this.createMetric({name:$.name,namespace:$.namespace,unit:"Count",dimensions:[{name:"ErrorType",value:$.errorType},{name:"Type",value:"Error"}]})}createAlarm($,J){let Y=this.metrics.get($);if(!Y)throw Error(`Metric not found: ${$}`);let W={id:`alarm-${Date.now()}-${this.alarmCounter++}`,...J};if(!Y.alarms)Y.alarms=[];return Y.alarms.push(W),W}createErrorRateAlarm($){return this.createAlarm($.metricId,{name:$.name,description:`Alert when error rate exceeds ${$.threshold} errors/min`,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:2,threshold:$.threshold,period:60,statistic:"Sum",treatMissingData:"notBreaching",actionsEnabled:!0,alarmActions:$.snsTopicArn?[$.snsTopicArn]:void 0})}createLatencyAlarm($){return this.createAlarm($.metricId,{name:$.name,description:`Alert when latency exceeds ${$.thresholdMs}ms`,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,threshold:$.thresholdMs,period:300,statistic:"Average",treatMissingData:"notBreaching",actionsEnabled:!0,alarmActions:$.snsTopicArn?[$.snsTopicArn]:void 0})}createThroughputAlarm($){return this.createAlarm($.metricId,{name:$.name,description:`Alert when throughput drops below ${$.minimumThreshold}`,comparisonOperator:"LessThanThreshold",evaluationPeriods:2,threshold:$.minimumThreshold,period:300,statistic:"Sum",treatMissingData:"breaching",actionsEnabled:!0,alarmActions:$.snsTopicArn?[$.snsTopicArn]:void 0})}createCompositeAlarm($){return{name:$.name,description:$.description,alarmRule:$.alarmRule,actionsEnabled:$.actionsEnabled??!0,alarmActions:$.alarmActions}}getNamespace($){return this.namespaces.get($)}listNamespaces(){return Array.from(this.namespaces.values())}getMetric($){return this.metrics.get($)}listMetrics(){return Array.from(this.metrics.values())}generateAlarmCF($,J){return{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:J.name,AlarmDescription:J.description,ComparisonOperator:J.comparisonOperator,EvaluationPeriods:J.evaluationPeriods,MetricName:$.name,Namespace:$.namespace,Period:J.period,Statistic:J.statistic,Threshold:J.threshold,TreatMissingData:J.treatMissingData||"notBreaching",ActionsEnabled:J.actionsEnabled??!0,...J.alarmActions&&{AlarmActions:J.alarmActions},...J.okActions&&{OKActions:J.okActions},...J.insufficientDataActions&&{InsufficientDataActions:J.insufficientDataActions},...$.dimensions&&{Dimensions:$.dimensions.map((Y)=>({Name:Y.name,Value:Y.value}))}}}}generateCompositeAlarmCF($){return{Type:"AWS::CloudWatch::CompositeAlarm",Properties:{AlarmName:$.name,AlarmDescription:$.description,AlarmRule:$.alarmRule,ActionsEnabled:$.actionsEnabled,...$.alarmActions&&{AlarmActions:$.alarmActions}}}}generateDashboardWidget($){return{type:"metric",properties:{metrics:[[$.namespace,$.name,...$.dimensions?.flatMap((J)=>[J.name,J.value])||[]]],period:300,stat:"Average",region:"us-east-1",title:$.name}}}publishCustomMetric($,J,Y,Q={},W="Count"){return{id:`metric-${Date.now()}-${this.metricCounter++}`,namespace:$,name:J,dimensions:Q,value:Y,unit:W,timestamp:new Date}}clear(){this.namespaces.clear(),this.metrics.clear(),this.namespaceCounter=0,this.metricCounter=0,this.alarmCounter=0}}var GB=new c8;class tJ{logGroups=new Map;queries=new Map;insightsQueries=new Map;logGroupCounter=0;filterCounter=0;queryCounter=0;createLogGroup($){let J=`log-group-${Date.now()}-${this.logGroupCounter++}`,Y={id:J,...$};return this.logGroups.set(J,Y),Y}createLambdaLogGroup($,J=7){return this.createLogGroup({name:`/aws/lambda/${$}`,retentionDays:J})}createECSLogGroup($){return this.createLogGroup({name:`/ecs/${$.clusterName}/${$.serviceName}`,retentionDays:$.retentionDays||14})}createAPIGatewayLogGroup($,J,Y=30){return this.createLogGroup({name:`/aws/apigateway/${$}/${J}`,retentionDays:Y})}createApplicationLogGroup($){return this.createLogGroup({name:`/application/${$.appName}/${$.environment}`,retentionDays:$.retentionDays||30,kmsKeyId:$.kmsKeyId})}createMetricFilter($,J){let Y=this.logGroups.get($);if(!Y)throw Error(`Log group not found: ${$}`);let W={id:`filter-${Date.now()}-${this.filterCounter++}`,...J};if(!Y.metricFilters)Y.metricFilters=[];return Y.metricFilters.push(W),W}createErrorCountFilter($,J){return this.createMetricFilter($,{name:"ErrorCount",filterPattern:"[timestamp, request_id, level = ERROR*, ...]",metricTransformations:[{metricName:"ErrorCount",metricNamespace:J,metricValue:"1",defaultValue:0,unit:"Count"}]})}createLatencyFilter($,J){return this.createMetricFilter($,{name:"Latency",filterPattern:"[timestamp, request_id, level, duration, ...]",metricTransformations:[{metricName:"ResponseTime",metricNamespace:J,metricValue:"$duration",unit:"Milliseconds"}]})}createCustomPatternFilter($){return this.createMetricFilter($.logGroupId,{name:$.name,filterPattern:$.pattern,metricTransformations:[{metricName:$.metricName,metricNamespace:$.namespace,metricValue:"1",defaultValue:0,unit:"Count"}]})}createSubscriptionFilter($,J){let Y=this.logGroups.get($);if(!Y)throw Error(`Log group not found: ${$}`);let W={id:`subscription-${Date.now()}-${this.filterCounter++}`,...J};if(!Y.subscriptionFilters)Y.subscriptionFilters=[];return Y.subscriptionFilters.push(W),W}createKinesisSubscription($){let J=this.logGroups.get($.logGroupId);if(!J)throw Error(`Log group not found: ${$.logGroupId}`);return this.createSubscriptionFilter($.logGroupId,{name:"KinesisSubscription",logGroupName:J.name,filterPattern:$.filterPattern||"",destinationArn:$.kinesisStreamArn,roleArn:$.roleArn,distribution:"Random"})}createLambdaSubscription($){let J=this.logGroups.get($.logGroupId);if(!J)throw Error(`Log group not found: ${$.logGroupId}`);return this.createSubscriptionFilter($.logGroupId,{name:"LambdaSubscription",logGroupName:J.name,filterPattern:$.filterPattern||"",destinationArn:$.lambdaFunctionArn,distribution:"ByLogStream"})}createInsightsQuery($){let J=`query-${Date.now()}-${this.queryCounter++}`,Y={id:J,...$};return this.insightsQueries.set(J,Y),Y}createErrorAnalysisQuery($){return this.createInsightsQuery({name:"Error Analysis",description:"Analyze error patterns and frequencies",query:`fields @timestamp, @message
913
+ | filter @message like /ERROR/
914
+ | stats count() by bin(5m)
915
+ | sort @timestamp desc`,logGroupNames:$})}createLatencyAnalysisQuery($){return this.createInsightsQuery({name:"Latency Analysis",description:"Analyze request latency patterns",query:`fields @timestamp, @duration
916
+ | filter @duration > 1000
917
+ | stats avg(@duration), max(@duration), min(@duration), count() by bin(5m)
918
+ | sort @timestamp desc`,logGroupNames:$})}createTopErrorsQuery($){return this.createInsightsQuery({name:"Top Errors",description:"Find most common errors",query:`fields @timestamp, @message
919
+ | filter @message like /ERROR/
920
+ | stats count() as error_count by @message
921
+ | sort error_count desc
922
+ | limit 20`,logGroupNames:$})}getLogGroup($){return this.logGroups.get($)}listLogGroups(){return Array.from(this.logGroups.values())}getInsightsQuery($){return this.insightsQueries.get($)}listInsightsQueries(){return Array.from(this.insightsQueries.values())}generateLogGroupCF($){return{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:$.name,...$.retentionDays&&{RetentionInDays:$.retentionDays},...$.kmsKeyId&&{KmsKeyId:$.kmsKeyId}}}}generateMetricFilterCF($,J){return{Type:"AWS::Logs::MetricFilter",Properties:{FilterName:J.name,FilterPattern:J.filterPattern,LogGroupName:$.name,MetricTransformations:J.metricTransformations.map((Y)=>({MetricName:Y.metricName,MetricNamespace:Y.metricNamespace,MetricValue:Y.metricValue,...Y.defaultValue!==void 0&&{DefaultValue:Y.defaultValue},...Y.unit&&{Unit:Y.unit},...Y.dimensions&&{Dimensions:Y.dimensions}}))}}}generateSubscriptionFilterCF($){return{Type:"AWS::Logs::SubscriptionFilter",Properties:{FilterName:$.name,FilterPattern:$.filterPattern,LogGroupName:$.logGroupName,DestinationArn:$.destinationArn,...$.roleArn&&{RoleArn:$.roleArn},...$.distribution&&{Distribution:$.distribution}}}}generateQueryDefinitionCF($){return{Type:"AWS::Logs::QueryDefinition",Properties:{Name:$.name,QueryString:$.query,LogGroupNames:$.logGroupNames}}}createLogAggregation($,J,Y=7){let Q=`aggregation-${Date.now()}-${this.logGroupCounter++}`,W=this.createLogGroup({name:$,retentionDays:Y});return J.forEach((U)=>{this.createMetricFilter(W.id,{name:U.metric,filterPattern:U.pattern,metricTransformations:[{metricName:U.metric,metricNamespace:"CustomMetrics",metricValue:"1",defaultValue:0,unit:"Count"}]})}),{id:Q,logGroup:$,filters:J,retention:Y}}clear(){this.logGroups.clear(),this.queries.clear(),this.insightsQueries.clear(),this.logGroupCounter=0,this.filterCounter=0,this.queryCounter=0}}var s7=new tJ;class S0{canaries=new Map;heartbeats=new Map;apiMonitors=new Map;canaryCounter=0;heartbeatCounter=0;apiMonitorCounter=0;alarmCounter=0;static RuntimeVersions={NODEJS_PUPPETEER_3_9:"syn-nodejs-puppeteer-3.9",NODEJS_PUPPETEER_4_0:"syn-nodejs-puppeteer-4.0",PYTHON_SELENIUM_1_3:"syn-python-selenium-1.3"};createCanary($){let J=`canary-${Date.now()}-${this.canaryCounter++}`,Y={id:J,...$};return this.canaries.set(J,Y),Y}createHeartbeatCanary($){let J=`
923
+ const synthetics = require('Synthetics');
924
+ const log = require('SyntheticsLogger');
925
+
926
+ const heartbeat = async function () {
927
+ const url = '${$.url}';
928
+
929
+ const page = await synthetics.getPage();
930
+ const response = await page.goto(url, {waitUntil: 'domcontentloaded', timeout: 30000});
931
+
932
+ if (response.status() !== 200) {
933
+ throw new Error(\`Failed with status \${response.status()}\`);
934
+ }
935
+
936
+ log.info('Heartbeat check passed');
937
+ };
938
+
939
+ exports.handler = async () => {
940
+ return await heartbeat();
941
+ };
942
+ `;return this.createCanary({name:$.name,description:`Heartbeat monitor for ${$.url}`,runtimeVersion:S0.RuntimeVersions.NODEJS_PUPPETEER_4_0,handler:"index.handler",code:{type:"script",script:J},schedule:{expression:`rate(${$.interval} minutes)`},runConfig:{timeoutInSeconds:60,memoryInMB:960,activeTracing:!0},artifactS3Location:`s3://${$.s3Bucket}/canary-artifacts/${$.name}/`,successRetentionPeriod:31,failureRetentionPeriod:31})}createAPICanary($){let Y=`
943
+ const synthetics = require('Synthetics');
944
+ const log = require('SyntheticsLogger');
945
+
946
+ const apiCheck = async function () {
947
+ const page = await synthetics.getPage();
948
+ let response;
949
+
950
+ ${$.endpoints.map((Q,W)=>`
951
+ // Endpoint ${W+1}: ${Q.method} ${Q.path}
952
+ response = await page.goto('${$.baseUrl}${Q.path}', {
953
+ waitUntil: 'domcontentloaded',
954
+ timeout: 30000
955
+ });
956
+
957
+ if (response.status() !== ${Q.expectedStatus}) {
958
+ throw new Error('Endpoint ${Q.path} failed: expected ${Q.expectedStatus}, got ' + response.status());
959
+ }
960
+
961
+ log.info('Endpoint ${Q.path} check passed');
962
+ `).join(`
963
+ `)}
964
+
965
+ log.info('All API checks passed');
966
+ };
967
+
968
+ exports.handler = async () => {
969
+ return await apiCheck();
970
+ };
971
+ `;return this.createCanary({name:$.name,description:`API monitor for ${$.baseUrl}`,runtimeVersion:S0.RuntimeVersions.NODEJS_PUPPETEER_4_0,handler:"index.handler",code:{type:"script",script:Y},schedule:{expression:`rate(${$.interval} minutes)`},runConfig:{timeoutInSeconds:120,memoryInMB:960,activeTracing:!0},artifactS3Location:`s3://${$.s3Bucket}/canary-artifacts/${$.name}/`,successRetentionPeriod:31,failureRetentionPeriod:31})}createVisualRegressionCanary($){let J=`
972
+ const synthetics = require('Synthetics');
973
+ const log = require('SyntheticsLogger');
974
+
975
+ const visualCheck = async function () {
976
+ const page = await synthetics.getPage();
977
+
978
+ await page.goto('${$.url}', {waitUntil: 'networkidle0', timeout: 30000});
979
+
980
+ await page.screenshot({
981
+ path: '/tmp/${$.screenshotName}.png',
982
+ fullPage: true
983
+ });
984
+
985
+ log.info('Visual regression check completed');
986
+ };
987
+
988
+ exports.handler = async () => {
989
+ return await visualCheck();
990
+ };
991
+ `;return this.createCanary({name:$.name,description:`Visual regression monitor for ${$.url}`,runtimeVersion:S0.RuntimeVersions.NODEJS_PUPPETEER_4_0,handler:"index.handler",code:{type:"script",script:J},schedule:{expression:`rate(${$.interval} minutes)`},runConfig:{timeoutInSeconds:120,memoryInMB:1024,activeTracing:!0},artifactS3Location:`s3://${$.s3Bucket}/canary-artifacts/${$.name}/`,successRetentionPeriod:31,failureRetentionPeriod:31})}createWorkflowCanary($){let Y=`
992
+ const synthetics = require('Synthetics');
993
+ const log = require('SyntheticsLogger');
994
+
995
+ const workflowCheck = async function () {
996
+ const page = await synthetics.getPage();
997
+
998
+ ${$.steps.map((Q,W)=>`
999
+ // Step ${W+1}: ${Q.description}
1000
+ await page.goto('${Q.url}', {waitUntil: 'domcontentloaded', timeout: 30000});
1001
+ ${Q.actions?.map((U)=>this.generateActionScript(U)).join(`
1002
+ `)||""}
1003
+ log.info('Step ${W+1} completed: ${Q.description}');
1004
+ `).join(`
1005
+ `)}
1006
+
1007
+ log.info('Workflow completed successfully');
1008
+ };
1009
+
1010
+ exports.handler = async () => {
1011
+ return await workflowCheck();
1012
+ };
1013
+ `;return this.createCanary({name:$.name,description:$.description,runtimeVersion:S0.RuntimeVersions.NODEJS_PUPPETEER_4_0,handler:"index.handler",code:{type:"script",script:Y},schedule:{expression:`rate(${$.interval} minutes)`},runConfig:{timeoutInSeconds:180,memoryInMB:1024,activeTracing:!0},artifactS3Location:`s3://${$.s3Bucket}/canary-artifacts/${$.name}/`,successRetentionPeriod:31,failureRetentionPeriod:31})}generateActionScript($){switch($.type){case"click":return`await page.click('${$.selector}');`;case"type":return`await page.type('${$.selector}', '${$.value}');`;case"wait":return`await page.waitForTimeout(${$.duration});`;case"waitForSelector":return`await page.waitForSelector('${$.selector}');`;default:return""}}createAlarm($,J){let Y=this.canaries.get($);if(!Y)throw Error(`Canary not found: ${$}`);let W={id:`alarm-${Date.now()}-${this.alarmCounter++}`,...J};if(!Y.alarms)Y.alarms=[];return Y.alarms.push(W),W}getCanary($){return this.canaries.get($)}listCanaries(){return Array.from(this.canaries.values())}generateCanaryCF($){let J={Type:"AWS::Synthetics::Canary",Properties:{Name:$.name,RuntimeVersion:$.runtimeVersion,ExecutionRoleArn:{"Fn::GetAtt":["CanaryExecutionRole","Arn"]},Schedule:{Expression:$.schedule.expression,...$.schedule.durationInSeconds&&{DurationInSeconds:$.schedule.durationInSeconds}},ArtifactS3Location:$.artifactS3Location,StartCanaryAfterCreation:!0}};if($.code.type==="script")J.Properties.Code={Handler:$.handler,Script:$.code.script};else J.Properties.Code={Handler:$.handler,S3Bucket:$.code.s3Bucket,S3Key:$.code.s3Key,...$.code.s3Version&&{S3ObjectVersion:$.code.s3Version}};if($.runConfig)J.Properties.RunConfig={TimeoutInSeconds:$.runConfig.timeoutInSeconds,MemoryInMB:$.runConfig.memoryInMB,...$.runConfig.environmentVariables&&{EnvironmentVariables:$.runConfig.environmentVariables},...$.runConfig.activeTracing!==void 0&&{ActiveTracing:$.runConfig.activeTracing}};if($.vpcConfig)J.Properties.VPCConfig={SubnetIds:$.vpcConfig.subnetIds,SecurityGroupIds:$.vpcConfig.securityGroupIds};if($.successRetentionPeriod)J.Properties.SuccessRetentionPeriod=$.successRetentionPeriod;if($.failureRetentionPeriod)J.Properties.FailureRetentionPeriod=$.failureRetentionPeriod;return J}generateCanaryRoleCF(){return{Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole","arn:aws:iam::aws:policy/CloudWatchSyntheticsFullAccess"],Policies:[{PolicyName:"CanaryS3Policy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:PutObject","s3:GetBucketLocation"],Resource:["arn:aws:s3:::*/*"]}]}}]}}}clear(){this.canaries.clear(),this.heartbeats.clear(),this.apiMonitors.clear(),this.canaryCounter=0,this.heartbeatCounter=0,this.apiMonitorCounter=0,this.alarmCounter=0}}var i7=new S0;class l8{plans=new Map;migrations=new Map;planCounter=0;migrationCounter=0;createPlan($){let J=`migration-plan-${Date.now()}-${this.planCounter++}`,Y={id:J,...$};return this.plans.set(J,Y),Y}createMigration($){let J=`migration-${Date.now()}-${this.migrationCounter++}`,Y=this.generateChecksum($.up+$.down),Q={id:J,checksum:Y,...$};return this.migrations.set(J,Q),Q}createSchemaMigration($){let{up:J,down:Y}=this.generateSchemaSQL($.changes,$.tableName,$.engine);return this.createMigration({version:$.version,name:$.name,description:`Schema changes for ${$.tableName}`,up:J,down:Y})}createDataMigration($){return this.createMigration({version:$.version,name:$.name,description:$.description,up:$.upSQL,down:$.downSQL})}addMigrationToPlan($,J){let Y=this.plans.get($);if(!Y)throw Error(`Migration plan not found: ${$}`);Y.migrations.push(J)}async executePlan($,J=!1){let Y=this.plans.get($);if(!Y)throw Error(`Migration plan not found: ${$}`);let Q=Date.now(),W=[],U=[];if(console.log(`${J?"[DRY RUN] ":""}Executing migration plan: ${Y.name}`),console.log(`Database: ${Y.database.type} - ${Y.database.identifier}`),console.log(`Migrations to apply: ${Y.migrations.length}
1014
+ `),Y.backupBeforeMigration&&!J)console.log("Creating database backup before migration...");for(let z of Y.migrations)try{if(console.log(`Applying migration: ${z.version} - ${z.name}`),!J){if(this.generateChecksum(z.up+z.down)!==z.checksum)throw Error("Migration checksum mismatch - migration has been modified");let K=Date.now();z.appliedAt=new Date,z.executionTimeMs=Date.now()-K,console.log(`✓ Applied in ${z.executionTimeMs}ms
1015
+ `)}else console.log(`[SKIPPED - DRY RUN]
1016
+ `);W.push(z.version)}catch(H){if(console.error(`✗ Failed: ${H instanceof Error?H.message:String(H)}
1017
+ `),U.push(z.version),!J)return console.log("Rolling back previously applied migrations..."),await this.rollbackMigrations(W.reverse(),Y),{success:!1,version:z.version,appliedMigrations:[],failedMigrations:U,executionTimeMs:Date.now()-Q,error:H instanceof Error?H.message:String(H),rollbackPerformed:!0}}let Z=Date.now()-Q;return console.log(`${J?"[DRY RUN] ":""}Migration plan completed successfully`),console.log(`Total time: ${Z}ms`),{success:!0,version:Y.migrations[Y.migrations.length-1]?.version||"unknown",appliedMigrations:W,failedMigrations:U,executionTimeMs:Z}}async rollbackMigrations($,J){for(let Y of $){let Q=J.migrations.find((W)=>W.version===Y);if(Q)console.log(`Rolling back: ${Q.version} - ${Q.name}`),Q.rolledBackAt=new Date,console.log(`✓ Rolled back
1018
+ `)}}getMigrationStatus($){let J=this.plans.get($);if(!J)throw Error(`Migration plan not found: ${$}`);let Y=J.migrations.filter((W)=>W.appliedAt&&!W.rolledBackAt),Q=J.migrations.filter((W)=>!W.appliedAt);return{currentVersion:Y[Y.length-1]?.version||"0.0.0",pendingMigrations:Q,appliedMigrations:Y,lastMigration:Y[Y.length-1]}}generateSchemaSQL($,J,Y="postgres"){let Q=[],W=[];for(let U of $)switch(U.type){case"add_column":Q.push(`ALTER TABLE ${J} ADD COLUMN ${U.columnName} ${U.columnType}${U.nullable===!1?" NOT NULL":""}${U.defaultValue?` DEFAULT ${U.defaultValue}`:""};`),W.push(`ALTER TABLE ${J} DROP COLUMN ${U.columnName};`);break;case"drop_column":Q.push(`ALTER TABLE ${J} DROP COLUMN ${U.columnName};`),W.push(`-- Cannot restore dropped column ${U.columnName}`);break;case"modify_column":if(Y==="postgres")Q.push(`ALTER TABLE ${J} ALTER COLUMN ${U.columnName} TYPE ${U.newType};`);else Q.push(`ALTER TABLE ${J} MODIFY COLUMN ${U.columnName} ${U.newType};`);W.push(`-- Reverting ${U.columnName} type change requires manual intervention`);break;case"add_index":Q.push(`CREATE INDEX ${U.indexName} ON ${J} (${(U.columns??[]).join(", ")});`),W.push(`DROP INDEX ${U.indexName};`);break;case"drop_index":Q.push(`DROP INDEX ${U.indexName};`),W.push(`-- Cannot restore index ${U.indexName} without schema details`);break}return{up:Q.join(`
1019
+ `),down:W.reverse().join(`
1020
+ `)}}generateChecksum($){let J=0;for(let Y=0;Y<$.length;Y++){let Q=$.charCodeAt(Y);J=(J<<5)-J+Q,J=J&J}return J.toString(16)}validatePlan($){let J=this.plans.get($);if(!J)return{valid:!1,errors:["Migration plan not found"]};let Y=[],Q=new Set;for(let W of J.migrations){if(Q.has(W.version))Y.push(`Duplicate migration version: ${W.version}`);Q.add(W.version)}for(let W of J.migrations)if(!W.down||W.down.trim()==="")Y.push(`Migration ${W.version} is missing rollback SQL`);for(let W of J.migrations)if(this.generateChecksum(W.up+W.down)!==W.checksum)Y.push(`Migration ${W.version} has invalid checksum`);return{valid:Y.length===0,errors:Y}}getPlan($){return this.plans.get($)}listPlans(){return Array.from(this.plans.values())}getMigration($){return this.migrations.get($)}listMigrations(){return Array.from(this.migrations.values())}clear(){this.plans.clear(),this.migrations.clear(),this.planCounter=0,this.migrationCounter=0}}var OB=new l8;class oJ{replicas=new Map;replicationGroups=new Map;proxies=new Map;proxyTargets=new Map;replicaCounter=0;groupCounter=0;proxyCounter=0;targetCounter=0;createReplica($){let J=`replica-${Date.now()}-${this.replicaCounter++}`,Y={id:J,status:"creating",...$};return this.replicas.set(J,Y),Y}createRDSReplica($){return this.createReplica({name:$.name,sourceDatabase:$.sourceDatabase,region:$.region||"us-east-1",instanceClass:$.instanceClass||"db.t3.medium",multiAZ:$.multiAZ||!1,autoMinorVersionUpgrade:!0,backupRetentionPeriod:7})}createCrossRegionReplica($){return this.createReplica({name:$.name,sourceDatabase:$.sourceDatabase,region:$.targetRegion,instanceClass:$.instanceClass||"db.t3.medium",multiAZ:!0,autoMinorVersionUpgrade:!0,backupRetentionPeriod:7})}createReplicationGroup($){let J=`replication-group-${Date.now()}-${this.groupCounter++}`,Y={id:J,...$};return this.replicationGroups.set(J,Y),Y}createAutoScalingReplicationGroup($){return this.createReplicationGroup({name:$.name,primaryDatabase:$.primaryDatabase,replicas:[],loadBalancing:$.loadBalancing||{type:"round-robin"},failoverEnabled:!0,autoScaling:{enabled:!0,minReplicas:$.minReplicas,maxReplicas:$.maxReplicas,targetCPU:$.targetCPU||70,scaleUpCooldown:300,scaleDownCooldown:600}})}addReplicaToGroup($,J){let Y=this.replicationGroups.get($);if(!Y)throw Error(`Replication group not found: ${$}`);Y.replicas.push(J)}createProxy($){let J=`rds-proxy-${Date.now()}-${this.proxyCounter++}`,Y={id:J,...$};return this.proxies.set(J,Y),Y}createConnectionPoolProxy($){return this.createProxy({name:$.name,engineFamily:$.engineFamily,targetDatabase:$.targetDatabase,maxConnectionsPercent:$.maxConnections||100,maxIdleConnectionsPercent:50,connectionBorrowTimeout:120,sessionPinningFilters:["EXCLUDE_VARIABLE_SETS"],requireTLS:!0,idleClientTimeout:1800,vpcSubnetIds:$.vpcSubnetIds,securityGroupIds:$.securityGroupIds,secretArn:$.secretArn})}createServerlessProxy($){return this.createProxy({name:$.name,engineFamily:$.engineFamily,targetDatabase:$.targetDatabase,maxConnectionsPercent:100,maxIdleConnectionsPercent:10,connectionBorrowTimeout:60,sessionPinningFilters:["EXCLUDE_VARIABLE_SETS"],requireTLS:!0,idleClientTimeout:300,vpcSubnetIds:$.vpcSubnetIds,securityGroupIds:$.securityGroupIds,secretArn:$.secretArn})}addProxyTarget($){let J=`proxy-target-${Date.now()}-${this.targetCounter++}`,Y={id:J,...$};return this.proxyTargets.set(J,Y),Y}promoteReplica($){let J=this.replicas.get($);if(!J)return{success:!1,message:"Replica not found"};if(console.log(`Promoting replica to primary: ${J.name}`),console.log(`Region: ${J.region}`),console.log(`
1021
+ 1. Checking replication lag...`),J.replicationLag&&J.replicationLag>5000)return{success:!1,message:`Replication lag too high: ${J.replicationLag}ms`};return console.log(` Replication lag: ${J.replicationLag||0}ms (acceptable)`),console.log(`
1022
+ 2. Promoting replica to standalone instance...`),console.log(`
1023
+ 3. Updating DNS records...`),console.log(`
1024
+ 4. Updating application configuration...`),console.log(`
1025
+ ✓ Promotion completed successfully`),J.status="available",{success:!0,message:"Replica promoted successfully"}}getReplicationLag($){if(!this.replicas.get($))throw Error(`Replica not found: ${$}`);return Math.floor(Math.random()*1000)}getReplica($){return this.replicas.get($)}listReplicas(){return Array.from(this.replicas.values())}getReplicationGroup($){return this.replicationGroups.get($)}listReplicationGroups(){return Array.from(this.replicationGroups.values())}getProxy($){return this.proxies.get($)}listProxies(){return Array.from(this.proxies.values())}generateReplicaCF($){return{Type:"AWS::RDS::DBInstance",Properties:{SourceDBInstanceIdentifier:$.sourceDatabase,DBInstanceIdentifier:$.name,DBInstanceClass:$.instanceClass,MultiAZ:$.multiAZ||!1,AutoMinorVersionUpgrade:$.autoMinorVersionUpgrade??!0,...$.backupRetentionPeriod&&{BackupRetentionPeriod:$.backupRetentionPeriod},...$.preferredBackupWindow&&{PreferredBackupWindow:$.preferredBackupWindow},...$.preferredMaintenanceWindow&&{PreferredMaintenanceWindow:$.preferredMaintenanceWindow}}}}generateProxyCF($){return{Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:$.name,EngineFamily:$.engineFamily,Auth:[{AuthScheme:"SECRETS",SecretArn:$.secretArn,IAMAuth:"DISABLED"}],RoleArn:{"Fn::GetAtt":["RDSProxyRole","Arn"]},VpcSubnetIds:$.vpcSubnetIds,VpcSecurityGroupIds:$.securityGroupIds,RequireTLS:$.requireTLS??!0,IdleClientTimeout:$.idleClientTimeout||1800,...$.maxConnectionsPercent&&{MaxConnectionsPercent:$.maxConnectionsPercent},...$.maxIdleConnectionsPercent&&{MaxIdleConnectionsPercent:$.maxIdleConnectionsPercent},...$.connectionBorrowTimeout&&{ConnectionBorrowTimeout:$.connectionBorrowTimeout}}}}generateProxyTargetCF($,J){return{Type:"AWS::RDS::DBProxyTargetGroup",Properties:{DBProxyName:J.name,TargetGroupName:"default",DBInstanceIdentifiers:[$.targetArn],ConnectionPoolConfig:{MaxConnectionsPercent:100,MaxIdleConnectionsPercent:50,ConnectionBorrowTimeout:120}}}}generateProxyRoleCF(){return{Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"rds.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"RDSProxySecretsPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue","secretsmanager:DescribeSecret"],Resource:"arn:aws:secretsmanager:*:*:secret:*"},{Effect:"Allow",Action:["kms:Decrypt"],Resource:"arn:aws:kms:*:*:key/*",Condition:{StringEquals:{"kms:ViaService":"secretsmanager.*.amazonaws.com"}}}]}}]}}}clear(){this.replicas.clear(),this.replicationGroups.clear(),this.proxies.clear(),this.proxyTargets.clear(),this.replicaCounter=0,this.groupCounter=0,this.proxyCounter=0,this.targetCounter=0}}var t7=new oJ;class p8{insights=new Map;slowQueryLogs=new Map;queryMetrics=new Map;reports=new Map;indexRecommendations=new Map;insightsCounter=0;logCounter=0;metricCounter=0;reportCounter=0;recommendationCounter=0;enablePerformanceInsights($){let J=`pi-${Date.now()}-${this.insightsCounter++}`,Y={id:J,name:$.name,databaseIdentifier:$.databaseIdentifier,enabled:!0,retentionPeriod:$.retentionPeriod||7,kmsKeyId:$.kmsKeyId};return this.insights.set(J,Y),Y}enableSlowQueryLog($){let J=`slow-query-${Date.now()}-${this.logCounter++}`,Y={id:J,name:$.name,databaseIdentifier:$.databaseIdentifier,enabled:!0,logDestination:$.logDestination,cloudwatchLogGroup:$.cloudwatchLogGroup,s3Bucket:$.s3Bucket,s3Prefix:$.s3Bucket?"slow-queries/":void 0,minExecutionTime:$.minExecutionTime||1000};return this.slowQueryLogs.set(J,Y),Y}recordQueryMetric($){let J=`metric-${Date.now()}-${this.metricCounter++}`,Y={id:J,timestamp:new Date,...$};return this.queryMetrics.set(J,Y),Y}generatePerformanceReport($){let J=`report-${Date.now()}-${this.reportCounter++}`,Y={avgCPU:Math.random()*60+20,maxCPU:Math.random()*30+70,avgConnections:Math.floor(Math.random()*50+10),maxConnections:Math.floor(Math.random()*50+100),avgReadIOPS:Math.floor(Math.random()*1000+500),avgWriteIOPS:Math.floor(Math.random()*500+200),avgReadThroughput:Math.random()*50+10,avgWriteThroughput:Math.random()*20+5,avgReadLatency:Math.random()*5+1,avgWriteLatency:Math.random()*8+2,cacheHitRatio:Math.random()*10+90,deadlocks:Math.floor(Math.random()*5),longRunningTransactions:Math.floor(Math.random()*10)},Q=Array.from(this.queryMetrics.values()),W=Q.sort((H,K)=>K.executionCount-H.executionCount).slice(0,10),U=Q.filter((H)=>H.avgExecutionTime>1000).sort((H,K)=>K.avgExecutionTime-H.avgExecutionTime).slice(0,10),Z=this.generateRecommendations(Y,U),z={id:J,name:$.name,databaseIdentifier:$.databaseIdentifier,reportType:$.reportType,metrics:Y,topQueries:W,slowQueries:U,recommendations:Z,generatedAt:new Date};return this.reports.set(J,z),z}generateRecommendations($,J){let Y=[];if($.avgCPU>70)Y.push({type:"scaling",severity:"high",title:"High CPU Usage",description:`Average CPU usage is ${$.avgCPU.toFixed(1)}%, which is above the recommended threshold of 70%.`,impact:"Performance degradation, increased latency, potential timeouts",effort:"medium"});if($.cacheHitRatio<95)Y.push({type:"configuration",severity:"medium",title:"Low Cache Hit Ratio",description:`Cache hit ratio is ${$.cacheHitRatio.toFixed(1)}%. Consider increasing buffer pool size.`,impact:"Increased disk I/O, slower query performance",effort:"low"});if($.deadlocks>0)Y.push({type:"query",severity:"medium",title:"Deadlocks Detected",description:`${$.deadlocks} deadlock(s) detected. Review transaction isolation levels and query patterns.`,impact:"Transaction failures, application errors",effort:"high"});if(J.length>0)Y.push({type:"index",severity:"high",title:"Slow Queries Detected",description:`${J.length} slow queries detected. Consider adding indexes or optimizing queries.`,impact:"High latency, poor user experience",effort:"medium"});if($.avgReadLatency>10||$.avgWriteLatency>10)Y.push({type:"scaling",severity:"high",title:"High I/O Latency",description:"Read or write latency is high. Consider upgrading to Provisioned IOPS or moving to a larger instance.",impact:"Slow query execution, application timeouts",effort:"medium"});return Y}analyzeQuery($){let J=`analysis-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,Y=[{id:1,operation:"Seq Scan",table:"users",rows:1e4,cost:850.5,children:[]}],Q=[];if($.toLowerCase().includes("select *"))Q.push({type:"full_table_scan",severity:"warning",description:"Query selects all columns. Consider selecting only required columns."});if(!$.toLowerCase().includes("where")&&$.toLowerCase().includes("select"))Q.push({type:"full_table_scan",severity:"critical",description:"Query has no WHERE clause and may scan entire table."});return{id:J,queryId:J,sql:$,executionPlan:Y,bottlenecks:Q,recommendations:["Add appropriate indexes on WHERE clause columns","Consider using EXPLAIN ANALYZE to get actual execution statistics","Review and optimize JOIN conditions"],estimatedCost:Y[0].cost}}recommendIndex($){let J=`index-rec-${Date.now()}-${this.recommendationCounter++}`,Y=`idx_${$.tableName}_${$.columns.join("_")}`,Q={id:J,tableName:$.tableName,columns:$.columns,reason:$.reason,estimatedImprovement:$.estimatedImprovement||50,estimatedSize:$.columns.length*10,createSQL:`CREATE INDEX ${Y} ON ${$.tableName} (${$.columns.join(", ")});`};return this.indexRecommendations.set(J,Q),Q}getInsights($){return this.insights.get($)}listInsights(){return Array.from(this.insights.values())}getSlowQueryLog($){return this.slowQueryLogs.get($)}listSlowQueryLogs(){return Array.from(this.slowQueryLogs.values())}getReport($){return this.reports.get($)}listReports(){return Array.from(this.reports.values())}listIndexRecommendations(){return Array.from(this.indexRecommendations.values())}generatePerformanceInsightsCF($){return{EnablePerformanceInsights:$.enabled,PerformanceInsightsRetentionPeriod:$.retentionPeriod,...$.kmsKeyId&&{PerformanceInsightsKMSKeyId:$.kmsKeyId}}}generateSlowQueryAlarmCF($){return{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:$.alarmName,AlarmDescription:"Alert when slow queries exceed threshold",MetricName:"SlowQueryCount",Namespace:"AWS/RDS",Statistic:"Sum",Period:300,EvaluationPeriods:1,Threshold:$.threshold,ComparisonOperator:"GreaterThanThreshold",...$.snsTopicArn&&{AlarmActions:[$.snsTopicArn]}}}}clear(){this.insights.clear(),this.slowQueryLogs.clear(),this.queryMetrics.clear(),this.reports.clear(),this.indexRecommendations.clear(),this.insightsCounter=0,this.logCounter=0,this.metricCounter=0,this.reportCounter=0,this.recommendationCounter=0}}var qB=new p8;class r8{users=new Map;roles=new Map;audits=new Map;userCounter=0;roleCounter=0;auditCounter=0;createUser($){let J=`db-user-${Date.now()}-${this.userCounter++}`,Y={id:J,createdAt:new Date,...$};return this.users.set(J,Y),Y}createReadOnlyUser($){let J=$.tables?$.tables.map((Y)=>({database:$.database,table:Y,privileges:["SELECT"]})):[{database:$.database,privileges:["SELECT"]}];return this.createUser({username:$.username,database:$.database,privileges:J,passwordSecretArn:$.passwordSecretArn,rotationEnabled:!0,rotationDays:90})}createReadWriteUser($){let J=$.tables?$.tables.map((Y)=>({database:$.database,table:Y,privileges:["SELECT","INSERT","UPDATE","DELETE"]})):[{database:$.database,privileges:["SELECT","INSERT","UPDATE","DELETE"]}];return this.createUser({username:$.username,database:$.database,privileges:J,passwordSecretArn:$.passwordSecretArn,rotationEnabled:!0,rotationDays:60})}createAdminUser($){return this.createUser({username:$.username,database:$.database,privileges:[{database:$.database,privileges:["ALL"]}],passwordSecretArn:$.passwordSecretArn,rotationEnabled:!0,rotationDays:30})}createApplicationUser($){let J=$.tables.map((Y)=>({database:$.database,table:Y.name,privileges:Y.privileges}));return this.createUser({username:$.username,database:$.database,privileges:J,passwordSecretArn:$.passwordSecretArn,rotationEnabled:!0,rotationDays:90})}createRole($){let J=`role-${Date.now()}-${this.roleCounter++}`,Y={id:J,users:[],...$};return this.roles.set(J,Y),Y}assignUserToRole($,J){let Y=this.users.get($),Q=this.roles.get(J);if(!Y)throw Error(`User not found: ${$}`);if(!Q)throw Error(`Role not found: ${J}`);Q.users.push($);for(let W of Q.privileges){let U=Y.privileges.find((Z)=>Z.database===W.database&&Z.table===W.table);if(U)U.privileges=Array.from(new Set([...U.privileges,...W.privileges]));else Y.privileges.push({...W})}}grantPrivileges($,J){let Y=this.users.get($);if(!Y)return{success:!1,message:"User not found"};for(let Q of J){let W=Y.privileges.find((U)=>U.database===Q.database&&U.table===Q.table);if(W)W.privileges=Array.from(new Set([...W.privileges,...Q.privileges]));else Y.privileges.push(Q)}return this.auditAccess({username:Y.username,action:"GRANT",database:J[0]?.database,table:J[0]?.table,success:!0}),{success:!0,message:"Privileges granted successfully"}}revokePrivileges($,J){let Y=this.users.get($);if(!Y)return{success:!1,message:"User not found"};for(let Q of J){let W=Y.privileges.findIndex((U)=>U.database===Q.database&&U.table===Q.table);if(W!==-1){let U=Y.privileges[W];if(U.privileges=U.privileges.filter((Z)=>!Q.privileges.includes(Z)),U.privileges.length===0)Y.privileges.splice(W,1)}}return this.auditAccess({username:Y.username,action:"REVOKE",database:J[0]?.database,table:J[0]?.table,success:!0}),{success:!0,message:"Privileges revoked successfully"}}rotatePassword($){let J=this.users.get($);if(!J)return{success:!1};let Y=`arn:aws:secretsmanager:us-east-1:123456789012:secret:db-${J.username}-${Date.now()}`;return J.passwordSecretArn=Y,J.lastRotated=new Date,console.log(`Password rotated for user: ${J.username}`),{success:!0,newSecretArn:Y}}needsPasswordRotation($){let J=this.users.get($);if(!J||!J.rotationEnabled||!J.lastRotated||!J.rotationDays)return!1;return(Date.now()-J.lastRotated.getTime())/86400000>=J.rotationDays}auditAccess($){let J=`audit-${Date.now()}-${this.auditCounter++}`,Y={id:J,timestamp:new Date,...$};return this.audits.set(J,Y),Y}getUserAccessHistory($,J=100){return Array.from(this.audits.values()).filter((Y)=>Y.username===$).sort((Y,Q)=>Q.timestamp.getTime()-Y.timestamp.getTime()).slice(0,J)}getFailedLoginAttempts($,J=24){let Y=Date.now()-J*60*60*1000;return Array.from(this.audits.values()).filter((Q)=>Q.username===$&&Q.action==="LOGIN"&&!Q.success&&Q.timestamp.getTime()>Y)}generateCreateUserSQL($,J="postgres"){let Y=[];if(J==="postgres"){Y.push(`CREATE USER ${$.username} WITH PASSWORD '${$.passwordSecretArn}';`);for(let Q of $.privileges)if(Q.privileges.includes("ALL"))Y.push(`GRANT ALL PRIVILEGES ON DATABASE ${Q.database} TO ${$.username};`);else{let W=Q.privileges.join(", ");if(Q.table)Y.push(`GRANT ${W} ON ${Q.database}.${Q.table} TO ${$.username};`);else Y.push(`GRANT ${W} ON DATABASE ${Q.database} TO ${$.username};`)}}else{Y.push(`CREATE USER '${$.username}'@'%' IDENTIFIED BY '${$.passwordSecretArn}';`);for(let Q of $.privileges){let W=Q.privileges.includes("ALL")?"ALL PRIVILEGES":Q.privileges.join(", "),U=Q.table?`${Q.database}.${Q.table}`:`${Q.database}.*`;Y.push(`GRANT ${W} ON ${U} TO '${$.username}'@'%';`)}Y.push("FLUSH PRIVILEGES;")}return Y.join(`
1026
+ `)}getUser($){return this.users.get($)}listUsers(){return Array.from(this.users.values())}getRole($){return this.roles.get($)}listRoles(){return Array.from(this.roles.values())}clear(){this.users.clear(),this.roles.clear(),this.audits.clear(),this.userCounter=0,this.roleCounter=0,this.auditCounter=0}}var MB=new r8;class a8{rotations=new Map;schedules=new Map;rotationCounter=0;scheduleCounter=0;createRotation($){let J=`rotation-${Date.now()}-${this.rotationCounter++}`,Y={id:J,...$};return this.rotations.set(J,Y),Y}enableRDSRotation($){let J=this.createRotation({secretId:$.secretId,secretType:"rds_credentials",rotationEnabled:!0,rotationDays:$.rotationDays||30,rotationLambdaArn:this.generateRDSRotationLambdaArn($.engine)});return J.nextRotation=new Date(Date.now()+J.rotationDays*24*60*60*1000),J}enableAPIKeyRotation($){return this.createRotation({secretId:$.secretId,secretType:"api_key",rotationEnabled:!0,rotationDays:$.rotationDays||90,rotationLambdaArn:$.rotationLambdaArn})}enableOAuthRotation($){return this.createRotation({secretId:$.secretId,secretType:"oauth_token",rotationEnabled:!0,rotationDays:$.rotationDays||60,rotationLambdaArn:$.rotationLambdaArn})}enableSSHKeyRotation($){return this.createRotation({secretId:$.secretId,secretType:"ssh_key",rotationEnabled:!0,rotationDays:$.rotationDays||180,rotationLambdaArn:$.rotationLambdaArn})}createSchedule($){let J=`schedule-${Date.now()}-${this.scheduleCounter++}`,Y={id:J,...$};return this.schedules.set(J,Y),Y}async executeRotation($){let J=this.rotations.get($);if(!J)throw Error(`Rotation not found: ${$}`);console.log(`
1027
+ Executing rotation for secret: ${J.secretId}`),console.log(`Secret type: ${J.secretType}`),console.log(`Rotation interval: ${J.rotationDays} days`);try{console.log(`
1028
+ Rotation steps:`),console.log("1. Creating new secret version...");let Y=`v${Date.now()}`;console.log("2. Testing new credentials..."),console.log("3. Updating application references..."),console.log("4. Marking previous version as deprecated...");let Q=J.versionStages?.[0]||"v1";return console.log("5. Finalizing rotation..."),J.lastRotated=new Date,J.nextRotation=new Date(Date.now()+J.rotationDays*24*60*60*1000),console.log(`
1029
+ ✓ Rotation completed successfully`),console.log(` New version: ${Y}`),console.log(` Next rotation: ${J.nextRotation.toISOString()}`),{success:!0,secretId:J.secretId,oldVersion:Q,newVersion:Y,rotatedAt:new Date}}catch(Y){return console.error(`
1030
+ ✗ Rotation failed:`,Y),{success:!1,secretId:J.secretId,oldVersion:"unknown",newVersion:"unknown",rotatedAt:new Date,error:Y instanceof Error?Y.message:String(Y)}}}needsRotation($){let J=this.rotations.get($);if(!J||!J.rotationEnabled)return!1;if(!J.lastRotated)return!0;return(Date.now()-J.lastRotated.getTime())/86400000>=J.rotationDays}getSecretsNeedingRotation(){return Array.from(this.rotations.values()).filter(($)=>this.needsRotation($.id))}generateRDSRotationLambdaArn($){let J={postgres:"SecretsManagerRDSPostgreSQLRotationSingleUser",mysql:"SecretsManagerRDSMySQLRotationSingleUser",sqlserver:"SecretsManagerRDSSQLServerRotationSingleUser",oracle:"SecretsManagerRDSOracleRotationSingleUser"};return`arn:aws:lambda:us-east-1:123456789012:function:${J[$]||J.postgres}`}getRotation($){return this.rotations.get($)}listRotations(){return Array.from(this.rotations.values())}getSchedule($){return this.schedules.get($)}listSchedules(){return Array.from(this.schedules.values())}generateRotationCF($){return{RotationEnabled:$.rotationEnabled,RotationRules:{AutomaticallyAfterDays:$.rotationDays},...$.rotationLambdaArn&&{RotationLambdaARN:$.rotationLambdaArn}}}generateRotationLambdaCF($){return{Type:"AWS::Lambda::Function",Properties:{FunctionName:$.functionName,Runtime:"python3.11",Handler:"lambda_function.lambda_handler",Role:{"Fn::GetAtt":["RotationLambdaRole","Arn"]},Timeout:30,Environment:{Variables:{SECRETS_MANAGER_ENDPOINT:"https://secretsmanager.us-east-1.amazonaws.com"}},...$.vpcConfig&&{VpcConfig:{SubnetIds:$.vpcConfig.subnetIds,SecurityGroupIds:$.vpcConfig.securityGroupIds}}}}}generateRotationLambdaRoleCF(){return{Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole","arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"],Policies:[{PolicyName:"SecretsRotationPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:DescribeSecret","secretsmanager:GetSecretValue","secretsmanager:PutSecretValue","secretsmanager:UpdateSecretVersionStage"],Resource:"*"},{Effect:"Allow",Action:["secretsmanager:GetRandomPassword"],Resource:"*"}]}}]}}}generateRotationScheduleCF($){return{Type:"AWS::Events::Rule",Properties:{Name:$.name,Description:`Rotation schedule for ${$.secrets.length} secrets`,ScheduleExpression:$.schedule,State:$.enabled?"ENABLED":"DISABLED",Targets:[{Arn:{"Fn::GetAtt":["RotationStateMachine","Arn"]},RoleArn:{"Fn::GetAtt":["EventBridgeRotationRole","Arn"]},Input:JSON.stringify({secrets:$.secrets})}]}}}clear(){this.rotations.clear(),this.schedules.clear(),this.rotationCounter=0,this.scheduleCounter=0}}var _B=new a8;class eJ{versions=new Map;audits=new Map;externalManagers=new Map;replications=new Map;policies=new Map;versionCounter=0;auditCounter=0;managerCounter=0;replicationCounter=0;policyCounter=0;createVersion($){let J=`version-${Date.now()}-${this.versionCounter++}`,Y={id:J,...$};return this.versions.set(J,Y),this.auditAction({secretId:$.secretId,action:"CREATE",actor:"system",versionId:$.versionId,success:!0}),Y}getVersionByStage($,J){return Array.from(this.versions.values()).find((Y)=>Y.secretId===$&&Y.versionStages.includes(J))}listVersions($){return Array.from(this.versions.values()).filter((J)=>J.secretId===$).sort((J,Y)=>Y.createdAt.getTime()-J.createdAt.getTime())}deprecateVersion($){let J=Array.from(this.versions.values()).find((Y)=>Y.versionId===$);if(J)J.deprecatedAt=new Date,J.versionStages=J.versionStages.filter((Y)=>Y!=="AWSCURRENT"),this.auditAction({secretId:J.secretId,action:"UPDATE",actor:"system",versionId:$,success:!0})}restoreVersion($){let J=Array.from(this.versions.values()).find((Y)=>Y.versionId===$);if(J)Array.from(this.versions.values()).filter((Y)=>Y.secretId===J.secretId&&Y.versionId!==$).forEach((Y)=>{Y.versionStages=Y.versionStages.filter((Q)=>Q!=="AWSCURRENT")}),J.versionStages.push("AWSCURRENT"),J.deprecatedAt=void 0,this.auditAction({secretId:J.secretId,action:"RESTORE",actor:"system",versionId:$,success:!0})}auditAction($){let J=`audit-${Date.now()}-${this.auditCounter++}`,Y={id:J,timestamp:new Date,...$};return this.audits.set(J,Y),Y}getAuditTrail($,J=100){return Array.from(this.audits.values()).filter((Y)=>Y.secretId===$).sort((Y,Q)=>Q.timestamp.getTime()-Y.timestamp.getTime()).slice(0,J)}getFailedAccesses($,J=24){let Y=Date.now()-J*60*60*1000;return Array.from(this.audits.values()).filter((Q)=>Q.secretId===$&&!Q.success&&Q.timestamp.getTime()>Y)}registerExternalManager($){let J=`ext-manager-${Date.now()}-${this.managerCounter++}`,Y={id:J,...$};return this.externalManagers.set(J,Y),Y}registerVault($){return this.registerExternalManager({type:"vault",name:$.name,endpoint:$.endpoint,authentication:{type:$.token?"token":"iam",credentials:$.token?{token:$.token}:void 0,roleArn:$.roleArn},syncEnabled:$.syncEnabled||!1,syncInterval:60})}registerOnePassword($){return this.registerExternalManager({type:"onepassword",name:$.name,endpoint:$.endpoint||"https://my.1password.com",authentication:{type:"apikey",credentials:{apiKey:$.apiKey}},syncEnabled:$.syncEnabled||!1,syncInterval:30})}enableReplication($){let J=`replication-${Date.now()}-${this.replicationCounter++}`,Y={id:J,secretId:$.secretId,sourceRegion:$.sourceRegion,replicaRegions:$.replicaRegions,kmsKeyIds:$.kmsKeyIds,status:"replicating"};return this.replications.set(J,Y),this.auditAction({secretId:$.secretId,action:"REPLICATE",actor:"system",success:!0}),setTimeout(()=>{Y.status="completed"},100),Y}createPolicy($){let J=`policy-${Date.now()}-${this.policyCounter++}`,Y={id:J,secretId:$.secretId,policy:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:$.allowedPrincipals},Action:$.allowedActions,Resource:"*"}]}};return this.policies.set(J,Y),Y}createCrossAccountPolicy($){let J=$.roleNames.map((Y)=>`arn:aws:iam::${$.accountId}:role/${Y}`);return this.createPolicy({secretId:$.secretId,allowedPrincipals:J,allowedActions:["secretsmanager:GetSecretValue","secretsmanager:DescribeSecret"]})}getVersion($){return this.versions.get($)}getExternalManager($){return this.externalManagers.get($)}listExternalManagers(){return Array.from(this.externalManagers.values())}getReplication($){return this.replications.get($)}listReplications(){return Array.from(this.replications.values())}generateSecretCF($){return{Type:"AWS::SecretsManager::Secret",Properties:{Name:$.name,Description:$.description,...$.kmsKeyId&&{KmsKeyId:$.kmsKeyId},...$.replicaRegions&&{ReplicaRegions:$.replicaRegions.map((J)=>({Region:J}))}}}}generateSecretPolicyCF($){return{Type:"AWS::SecretsManager::ResourcePolicy",Properties:{SecretId:$.secretId,ResourcePolicy:$.policy}}}clear(){this.versions.clear(),this.audits.clear(),this.externalManagers.clear(),this.replications.clear(),this.policies.clear(),this.versionCounter=0,this.auditCounter=0,this.managerCounter=0,this.replicationCounter=0,this.policyCounter=0}}var o7=new eJ;class n8{certificates=new Map;renewals=new Map;validations=new Map;monitors=new Map;alerts=new Map;certificateCounter=0;renewalCounter=0;validationCounter=0;monitorCounter=0;alertCounter=0;requestCertificate($){let J=`cert-${Date.now()}-${this.certificateCounter++}`,Y=`arn:aws:acm:us-east-1:123456789012:certificate/${J}`,Q={id:J,arn:Y,domainName:$.domainName,subjectAlternativeNames:$.subjectAlternativeNames,validationMethod:$.validationMethod||"DNS",status:"PENDING_VALIDATION"};return this.certificates.set(J,Q),this.createValidation(Q),Q}requestWildcardCertificate($){let J=[];if($.includeApex)J.push($.domainName.replace("*.",""));return this.requestCertificate({domainName:$.domainName,subjectAlternativeNames:J.length>0?J:void 0,validationMethod:"DNS"})}requestMultiDomainCertificate($){return this.requestCertificate({domainName:$.primaryDomain,subjectAlternativeNames:$.additionalDomains,validationMethod:$.validationMethod||"DNS"})}createValidation($){let J={domainName:$.domainName,validationMethod:$.validationMethod,validationStatus:"PENDING"};if($.validationMethod==="DNS")J.resourceRecords=[{name:`_${Math.random().toString(36).slice(2)}.${$.domainName}`,type:"CNAME",value:`_${Math.random().toString(36).slice(2)}.acm-validations.aws.`}];else J.validationEmails=[`admin@${$.domainName}`,`administrator@${$.domainName}`,`hostmaster@${$.domainName}`];return this.validations.set($.id,J),J}validateCertificate($){let J=this.certificates.get($),Y=this.validations.get($);if(!J||!Y)return{success:!1,message:"Certificate or validation not found"};return Y.validationStatus="SUCCESS",J.status="ISSUED",J.issuedAt=new Date,J.expiresAt=new Date(Date.now()+31536000000),J.renewalEligibility=!0,J.issuer="Amazon",{success:!0,message:"Certificate validated and issued successfully"}}enableAutoRenewal($){let J=`renewal-${Date.now()}-${this.renewalCounter++}`,Y={id:J,certificateArn:$.certificateArn,autoRenew:!0,renewBeforeDays:$.renewBeforeDays||30};return this.renewals.set(J,Y),Y}async renewCertificate($){let J=this.renewals.get($);if(!J)return{success:!1,message:"Renewal configuration not found"};let Y=Array.from(this.certificates.values()).find((Q)=>Q.arn===J.certificateArn);if(!Y)return{success:!1,message:"Certificate not found"};console.log(`
1031
+ Renewing certificate: ${Y.domainName}`),console.log(`Certificate ARN: ${Y.arn}`);try{return console.log(`
1032
+ 1. Requesting new certificate...`),console.log("2. Validating domain ownership..."),console.log("3. Issuing renewed certificate..."),console.log("4. Updating resource associations..."),Y.issuedAt=new Date,Y.expiresAt=new Date(Date.now()+31536000000),J.lastRenewal=new Date,J.renewalStatus="success",J.nextRenewal=new Date(Y.expiresAt.getTime()-J.renewBeforeDays*24*60*60*1000),console.log(`
1033
+ ✓ Certificate renewed successfully`),console.log(` New expiration: ${Y.expiresAt.toISOString()}`),console.log(` Next renewal: ${J.nextRenewal.toISOString()}`),{success:!0,message:"Certificate renewed successfully"}}catch(Q){return J.renewalStatus="failed",this.createAlert({certificateArn:Y.arn,alertType:"renewal_failed",severity:"critical",message:`Certificate renewal failed: ${Q}`}),{success:!1,message:Q instanceof Error?Q.message:String(Q)}}}createMonitor($){let J=`monitor-${Date.now()}-${this.monitorCounter++}`,Y={id:J,...$};return this.monitors.set(J,Y),Y}checkExpiration(){let $=[],J=Date.now();for(let Y of this.certificates.values()){if(!Y.expiresAt)continue;let Q=(Y.expiresAt.getTime()-J)/86400000;if(Q<0)$.push(this.createAlert({certificateArn:Y.arn,alertType:"expired",severity:"critical",message:`Certificate has expired for ${Y.domainName}`}));else if(Q<30)$.push(this.createAlert({certificateArn:Y.arn,alertType:"expiring_soon",severity:Q<7?"critical":"warning",message:`Certificate expiring in ${Math.floor(Q)} days for ${Y.domainName}`}))}return $}createAlert($){let J=`alert-${Date.now()}-${this.alertCounter++}`,Y={id:J,timestamp:new Date,acknowledged:!1,...$};return this.alerts.set(J,Y),Y}acknowledgeAlert($){let J=this.alerts.get($);if(J)J.acknowledged=!0}getCertificate($){return this.certificates.get($)}listCertificates(){return Array.from(this.certificates.values())}getExpiringCertificates($=30){let J=Date.now()+$*24*60*60*1000;return Array.from(this.certificates.values()).filter((Y)=>Y.expiresAt&&Y.expiresAt.getTime()<J)}getValidation($){return this.validations.get($)}getRenewal($){return this.renewals.get($)}listRenewals(){return Array.from(this.renewals.values())}listAlerts($=!1){return Array.from(this.alerts.values()).filter((J)=>J.acknowledged===$)}generateCertificateCF($){return{Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:$.domainName,...$.subjectAlternativeNames&&{SubjectAlternativeNames:$.subjectAlternativeNames},ValidationMethod:$.validationMethod}}}generateExpirationAlarmCF($){return{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:$.alarmName,AlarmDescription:`Certificate expiring in ${$.daysBeforeExpiration} days`,MetricName:"DaysToExpiry",Namespace:"AWS/CertificateManager",Statistic:"Minimum",Period:86400,EvaluationPeriods:1,Threshold:$.daysBeforeExpiration,ComparisonOperator:"LessThanThreshold",Dimensions:[{Name:"CertificateArn",Value:$.certificateArn}],...$.snsTopicArn&&{AlarmActions:[$.snsTopicArn]}}}}clear(){this.certificates.clear(),this.renewals.clear(),this.validations.clear(),this.monitors.clear(),this.alerts.clear(),this.certificateCounter=0,this.renewalCounter=0,this.validationCounter=0,this.monitorCounter=0,this.alertCounter=0}}var TB=new n8;class s8{scans=new Map;findings=new Map;reports=new Map;complianceChecks=new Map;postures=new Map;scanCounter=0;findingCounter=0;reportCounter=0;checkCounter=0;postureCounter=0;createScan($){let J=`scan-${Date.now()}-${this.scanCounter++}`,Y={id:J,status:"queued",findings:[],...$};return this.scans.set(J,Y),Y}createContainerScan($){return this.createScan({name:$.name,scanType:"container_image",target:{type:"ecr_image",identifier:$.imageUri,region:$.region||"us-east-1"}})}createLambdaScan($){return this.createScan({name:$.name,scanType:"vulnerability",target:{type:"lambda",identifier:$.functionName,region:$.region||"us-east-1"}})}createSecretsDetectionScan($){return this.createScan({name:$.name,scanType:"secrets_detection",target:{type:"repository",identifier:$.repositoryUrl}})}async executeScan($){let J=this.scans.get($);if(!J)throw Error(`Scan not found: ${$}`);console.log(`
1034
+ Executing security scan: ${J.name}`),console.log(`Scan type: ${J.scanType}`),console.log(`Target: ${J.target.type} - ${J.target.identifier}`),J.status="running",J.startedAt=new Date;try{console.log(`
1035
+ Scanning...`);let Y=this.simulateFindings(J);return J.findings=Y,J.status="completed",J.completedAt=new Date,J.summary={totalFindings:Y.length,criticalCount:Y.filter((Q)=>Q.severity==="CRITICAL").length,highCount:Y.filter((Q)=>Q.severity==="HIGH").length,mediumCount:Y.filter((Q)=>Q.severity==="MEDIUM").length,lowCount:Y.filter((Q)=>Q.severity==="LOW").length,infoCount:Y.filter((Q)=>Q.severity==="INFO").length,executionTime:J.completedAt.getTime()-J.startedAt.getTime()},console.log(`
1036
+ ✓ Scan completed`),console.log(` Findings: ${J.summary.totalFindings}`),console.log(` Critical: ${J.summary.criticalCount}`),console.log(` High: ${J.summary.highCount}`),console.log(` Medium: ${J.summary.mediumCount}`),console.log(` Low: ${J.summary.lowCount}`),J}catch(Y){throw J.status="failed",J.completedAt=new Date,Y}}simulateFindings($){let J=[],Y=new Date;if($.scanType==="container_image")J.push(this.createFinding({severity:"HIGH",title:"Vulnerable OpenSSL version detected",description:"OpenSSL 1.1.1k contains known vulnerabilities",cve:"CVE-2021-3711",cvss:7.5,affectedResource:$.target.identifier,remediation:"Update OpenSSL to version 1.1.1l or later",status:"OPEN",firstDetected:Y,lastSeen:Y})),J.push(this.createFinding({severity:"MEDIUM",title:"Outdated npm package: lodash",description:"lodash 4.17.19 has known security issues",cve:"CVE-2020-8203",cvss:5.3,affectedResource:$.target.identifier,remediation:"Update lodash to version 4.17.21 or later",status:"OPEN",firstDetected:Y,lastSeen:Y}));else if($.scanType==="secrets_detection")J.push(this.createFinding({severity:"CRITICAL",title:"AWS Access Key exposed in code",description:"Hardcoded AWS access key found in source code",affectedResource:`${$.target.identifier}/src/config.ts:12`,remediation:"Remove hardcoded credentials and use AWS Secrets Manager",status:"OPEN",firstDetected:Y,lastSeen:Y}));return J}createFinding($){let J=`finding-${Date.now()}-${this.findingCounter++}`,Y={id:J,...$};return this.findings.set(J,Y),Y}suppressFinding($,J){let Y=this.findings.get($);if(Y){if(Y.status="SUPPRESSED",console.log(`Finding suppressed: ${Y.title}`),J)console.log(`Reason: ${J}`)}}resolveFinding($){let J=this.findings.get($);if(J)J.status="RESOLVED",console.log(`Finding resolved: ${J.title}`)}generateReport($){let J=`report-${Date.now()}-${this.reportCounter++}`,Y={id:J,scanId:$.scanId,reportType:$.reportType,format:$.format,generatedAt:new Date,s3Location:`s3://security-reports/${J}.${$.format}`};return this.reports.set(J,Y),Y}runComplianceCheck($){let J=[];if($.framework.includes("CIS"))J.push(this.createComplianceCheck({framework:$.framework,checkId:"1.1",title:"Avoid the use of root account",description:"Root account should not be used for everyday tasks",status:"PASS",severity:"CRITICAL",resourceType:$.resourceType,resourceId:$.resourceId})),J.push(this.createComplianceCheck({framework:$.framework,checkId:"2.1",title:"Ensure CloudTrail is enabled",description:"CloudTrail should be enabled in all regions",status:"FAIL",severity:"HIGH",resourceType:$.resourceType,resourceId:$.resourceId,remediation:"Enable CloudTrail in all regions"}));return J}createComplianceCheck($){let J=`check-${Date.now()}-${this.checkCounter++}`,Y={id:J,...$};return this.complianceChecks.set(J,Y),Y}assessSecurityPosture($){let J=`posture-${Date.now()}-${this.postureCounter++}`,Y=Array.from(this.complianceChecks.values()),Q=Y.filter((H)=>H.status==="PASS").length,W=Y.length,U=W>0?Math.round(Q/W*100):0,Z;if(U>=90)Z="A";else if(U>=80)Z="B";else if(U>=70)Z="C";else if(U>=60)Z="D";else Z="F";let z={id:J,accountId:$.accountId,region:$.region,score:U,grade:Z,assessedAt:new Date,strengths:["IAM password policy enforced","Multi-factor authentication enabled","CloudTrail logging enabled"],weaknesses:["Some S3 buckets are publicly accessible","Security groups allow unrestricted ingress","Outdated dependencies in Lambda functions"],recommendations:["Review and update S3 bucket policies","Implement least-privilege security group rules","Update Lambda runtime versions and dependencies","Enable GuardDuty for threat detection"]};return this.postures.set(J,z),z}getScan($){return this.scans.get($)}listScans(){return Array.from(this.scans.values())}getOpenFindings($){return Array.from(this.findings.values()).filter((J)=>J.status==="OPEN"&&(!$||J.severity===$))}getComplianceChecksByStatus($){return Array.from(this.complianceChecks.values()).filter((J)=>J.status===$)}listPostures(){return Array.from(this.postures.values())}generateECRScanCF($){return{Type:"AWS::ECR::Repository",Properties:{RepositoryName:$,ImageScanningConfiguration:{ScanOnPush:!0},ImageTagMutability:"IMMUTABLE"}}}clear(){this.scans.clear(),this.findings.clear(),this.reports.clear(),this.complianceChecks.clear(),this.postures.clear(),this.scanCounter=0,this.findingCounter=0,this.reportCounter=0,this.checkCounter=0,this.postureCounter=0}}var AB=new s8;class i8{configs=new Map;results=new Map;policies=new Map;configCounter=0;resultCounter=0;policyCounter=0;configureScan($){let J=`scan-config-${Date.now()}-${this.configCounter++}`,Y={id:J,...$};return this.configs.set(J,Y),Y}configureTrivyScan($){return this.configureScan({repository:$.repository,imageTag:$.imageTag,scanner:"trivy",scanOnPush:$.scanOnPush??!0,ignoreUnfixed:$.ignoreUnfixed??!1,failOnSeverity:"HIGH"})}configureSnykScan($){return this.configureScan({repository:$.repository,imageTag:$.imageTag,scanner:"snyk",scanOnPush:$.scanOnPush??!0,failOnSeverity:"HIGH"})}configureECRScan($){return this.configureScan({repository:$.repository,imageTag:"latest",scanner:"ecr",scanOnPush:$.scanOnPush??!0,failOnSeverity:"CRITICAL"})}async scanImage($){let J=this.configs.get($);if(!J)throw Error(`Scan config not found: ${$}`);let Y=`${J.repository}:${J.imageTag}`;console.log(`
1037
+ Scanning image: ${Y}`),console.log(`Scanner: ${J.scanner}`);let Q=`scan-result-${Date.now()}-${this.resultCounter++}`,W=this.simulateVulnerabilities(J),U={total:W.length,critical:W.filter((H)=>H.severity==="CRITICAL").length,high:W.filter((H)=>H.severity==="HIGH").length,medium:W.filter((H)=>H.severity==="MEDIUM").length,low:W.filter((H)=>H.severity==="LOW").length,unknown:W.filter((H)=>H.severity==="UNKNOWN").length},Z=this.evaluateScanResult(J,U),z={id:Q,imageUri:Y,scannerType:J.scanner,scanDate:new Date,vulnerabilities:W,summary:U,passed:Z};return this.results.set(Q,z),console.log(`
1038
+ Scan Results:`),console.log(` Total vulnerabilities: ${U.total}`),console.log(` Critical: ${U.critical}`),console.log(` High: ${U.high}`),console.log(` Medium: ${U.medium}`),console.log(` Low: ${U.low}`),console.log(` Status: ${Z?"✓ PASSED":"✗ FAILED"}`),z}simulateVulnerabilities($){let J=[];if($.scanner==="trivy"||$.scanner==="ecr")J.push({id:"vuln-1",cve:"CVE-2024-1234",severity:"HIGH",packageName:"openssl",installedVersion:"1.1.1k",fixedVersion:"1.1.1l",title:"OpenSSL buffer overflow",description:"Buffer overflow vulnerability in OpenSSL",references:["https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2024-1234"],cvss:7.5}),J.push({id:"vuln-2",cve:"CVE-2024-5678",severity:"MEDIUM",packageName:"curl",installedVersion:"7.68.0",fixedVersion:"7.79.0",title:"curl remote code execution",description:"Remote code execution in curl",references:["https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2024-5678"],cvss:5.3});return J}evaluateScanResult($,J){if(!$.failOnSeverity)return!0;switch($.failOnSeverity){case"CRITICAL":return J.critical===0;case"HIGH":return J.critical===0&&J.high===0;case"MEDIUM":return J.critical===0&&J.high===0&&J.medium===0;case"LOW":return J.total===0;default:return!0}}createPolicy($){let J=`policy-${Date.now()}-${this.policyCounter++}`,Y={id:J,...$};return this.policies.set(J,Y),Y}createStrictPolicy($){return this.createPolicy({name:$,allowedSeverities:[],maxCritical:0,maxHigh:0,blockOnFailure:!0,exemptions:[]})}createPermissivePolicy($){return this.createPolicy({name:$,allowedSeverities:["CRITICAL","HIGH","MEDIUM","LOW"],maxCritical:5,maxHigh:10,blockOnFailure:!1,exemptions:[]})}getConfig($){return this.configs.get($)}listConfigs(){return Array.from(this.configs.values())}getResult($){return this.results.get($)}listResults(){return Array.from(this.results.values())}generateECRScanCF($){return{Type:"AWS::ECR::Repository",Properties:{RepositoryName:$.repository,ImageScanningConfiguration:{ScanOnPush:$.scanOnPush},ImageTagMutability:"IMMUTABLE",EncryptionConfiguration:{EncryptionType:"AES256"}}}}clear(){this.configs.clear(),this.results.clear(),this.policies.clear(),this.configCounter=0,this.resultCounter=0,this.policyCounter=0}}var SB=new i8;class t8{configs=new Map;multiStageConfigs=new Map;optimizations=new Map;analyses=new Map;configCounter=0;multiStageCounter=0;optimizationCounter=0;analysisCounter=0;createBuildConfig($){let J=`build-config-${Date.now()}-${this.configCounter++}`,Y={id:J,...$};return this.configs.set(J,Y),Y}createOptimizedBuildConfig($){let J={type:$.enableCache?"registry":"inline",cacheFrom:$.registry?[`${$.registry}/cache`]:void 0,cacheTo:$.registry?`${$.registry}/cache`:void 0,maxCacheAge:7};return this.createBuildConfig({name:$.name,dockerfile:$.dockerfile,context:".",cacheStrategy:J,buildArgs:{BUILDKIT_INLINE_CACHE:"1"}})}createMultiStageConfig($){let J=`multi-stage-${Date.now()}-${this.multiStageCounter++}`,Y={id:J,...$};return this.multiStageConfigs.set(J,Y),Y}createNodeMultiStageBuild($){let J=$.nodeVersion||"18-alpine";return this.createMultiStageConfig({name:$.name,targetStage:$.targetStage||"production",stages:[{name:"dependencies",baseImage:`node:${J}`,workdir:"/app",commands:["COPY package*.json ./","RUN npm ci --only=production"]},{name:"build",baseImage:`node:${J}`,workdir:"/app",commands:["COPY package*.json ./","RUN npm ci","COPY . .","RUN npm run build"]},{name:"production",baseImage:`node:${J}`,workdir:"/app",copyFrom:["dependencies:/app/node_modules","build:/app/dist"],commands:["COPY package*.json ./","ENV NODE_ENV=production",'CMD ["node", "dist/index.js"]']}]})}generateDockerfile($){let J=this.multiStageConfigs.get($);if(!J)throw Error(`Multi-stage config not found: ${$}`);let Y=[];for(let Q of J.stages){if(Y.push(`# Stage: ${Q.name}`),Y.push(`FROM ${Q.baseImage} AS ${Q.name}`),Q.workdir)Y.push(`WORKDIR ${Q.workdir}`);if(Q.env)for(let[W,U]of Object.entries(Q.env))Y.push(`ENV ${W}=${U}`);for(let W of Q.commands)Y.push(W);Y.push("")}return Y.join(`
1039
+ `)}analyzeImage($,J){let Y=`analysis-${Date.now()}-${this.analysisCounter++}`,Q=J.map((z)=>({...z,cacheable:this.isLayerCacheable(z.command)})),W=Q.reduce((z,H)=>z+H.size,0),U=Q.filter((z)=>!z.cacheable&&z.size>100).length,Z={id:Y,imageId:$,layers:Q,totalSize:W,unnecessaryLayers:U};return this.analyses.set(Y,Z),Z}isLayerCacheable($){let J=["FROM","RUN","COPY","ADD","WORKDIR","ENV"],Y=["CMD","ENTRYPOINT","LABEL"];for(let Q of J)if($.startsWith(Q))return!0;for(let Q of Y)if($.startsWith(Q))return!1;return!1}generateOptimizations($){let J=this.analyses.get($);if(!J)throw Error(`Analysis not found: ${$}`);let Y=`optimization-${Date.now()}-${this.optimizationCounter++}`,Q=[],W=J.layers.filter((K)=>K.command.startsWith("RUN"));if(W.length>5)Q.push({type:"layer_reduction",priority:"high",title:"Combine RUN commands",description:`${W.length} RUN commands found. Combine them to reduce layers.`,example:"RUN apt-get update && apt-get install -y package1 package2",impact:"Reduce image size by 20-30% and improve build time"});let U=J.layers[0];if(U.command.includes("ubuntu")||U.command.includes("debian"))Q.push({type:"base_image",priority:"medium",title:"Use Alpine base image",description:"Switch to Alpine Linux for smaller image size",example:"FROM node:18-alpine",impact:"Reduce image size by 50-70%"});let Z=J.layers.filter((K)=>K.command.startsWith("COPY"));if(Z.length>0&&Z[0].index>3)Q.push({type:"cache_optimization",priority:"high",title:"Copy dependencies first",description:"Copy package files before source code to leverage layer caching",example:`COPY package*.json ./
1040
+ RUN npm install
1041
+ COPY . .`,impact:"Improve build time by 60-80% on subsequent builds"});let z={sizeBefore:J.totalSize,sizeAfter:J.totalSize*0.6,timeBefore:300,timeAfter:120},H={id:Y,name:`Optimization for ${J.imageId}`,recommendations:Q,estimatedSavings:z};return this.optimizations.set(Y,H),H}getBuildConfig($){return this.configs.get($)}listBuildConfigs(){return Array.from(this.configs.values())}getMultiStageConfig($){return this.multiStageConfigs.get($)}listMultiStageConfigs(){return Array.from(this.multiStageConfigs.values())}getOptimization($){return this.optimizations.get($)}listOptimizations(){return Array.from(this.optimizations.values())}clear(){this.configs.clear(),this.multiStageConfigs.clear(),this.optimizations.clear(),this.analyses.clear(),this.configCounter=0,this.multiStageCounter=0,this.optimizationCounter=0,this.analysisCounter=0}}var PB=new t8;class $6{registries=new Map;credentials=new Map;registryCounter=0;credentialsCounter=0;createRegistry($){let J=`registry-${Date.now()}-${this.registryCounter++}`,Y={id:J,...$};return this.registries.set(J,Y),Y}createECRRepository($){return this.createRegistry({name:$.name,registryType:"ecr",repositoryUri:`123456789012.dkr.ecr.${$.region||"us-east-1"}.amazonaws.com/${$.name}`,region:$.region||"us-east-1",encryption:{encryptionType:$.encryption||"AES256",kmsKeyId:$.kmsKeyId},scanning:{scanOnPush:$.scanOnPush??!0}})}createManagedRepository($){let J=this.createECRRepository({name:$.name,region:$.region,scanOnPush:!0,encryption:"KMS"});return J.lifecycle={id:`lifecycle-${Date.now()}`,rules:[{rulePriority:1,description:"Keep only last N images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:$.maxImageCount||10},action:{type:"expire"}},{rulePriority:2,description:"Remove images older than N days",selection:{tagStatus:"untagged",countType:"sinceImagePushed",countNumber:$.maxImageAgeDays||30,countUnit:"days"},action:{type:"expire"}}]},J}enableReplication($,J){let Y=this.registries.get($);if(!Y)throw Error(`Registry not found: ${$}`);return Y.replication={enabled:!0,destinations:J},Y}createCredentials($){let J=`creds-${Date.now()}-${this.credentialsCounter++}`,Y={id:J,...$};return this.credentials.set(J,Y),Y}getRegistry($){return this.registries.get($)}listRegistries(){return Array.from(this.registries.values())}generateECRRepositoryCF($){return{Type:"AWS::ECR::Repository",Properties:{RepositoryName:$.name,ImageScanningConfiguration:{ScanOnPush:$.scanning?.scanOnPush??!1},EncryptionConfiguration:{EncryptionType:$.encryption?.encryptionType||"AES256",...$.encryption?.kmsKeyId&&{KmsKey:$.encryption.kmsKeyId}},ImageTagMutability:"MUTABLE",...$.lifecycle&&{LifecyclePolicy:{LifecyclePolicyText:JSON.stringify({rules:$.lifecycle.rules})}}}}}generateReplicationConfigCF($){return{Type:"AWS::ECR::ReplicationConfiguration",Properties:{ReplicationConfiguration:{Rules:$.destinations.map((J)=>({Destinations:[{Region:J.region,...J.registryId&&{RegistryId:J.registryId}}]}))}}}}clear(){this.registries.clear(),this.credentials.clear(),this.registryCounter=0,this.credentialsCounter=0}}var e7=new $6;class J6{meshes=new Map;virtualNodes=new Map;virtualRouters=new Map;virtualGateways=new Map;meshCounter=0;nodeCounter=0;routerCounter=0;gatewayCounter=0;createMesh($){let J=`mesh-${Date.now()}-${this.meshCounter++}`,Y={id:J,...$};return this.meshes.set(J,Y),Y}createAppMesh($){return this.createMesh({name:$.name,meshType:"app_mesh",services:$.services,virtualNodes:[],virtualRouters:[],virtualGateways:[]})}createVirtualNode($){let J=`vnode-${Date.now()}-${this.nodeCounter++}`,Y={id:J,...$};return this.virtualNodes.set(J,Y),Y}createHTTPVirtualNode($){return this.createVirtualNode({name:$.name,serviceName:$.serviceName,listeners:[{port:$.port,protocol:"http",healthCheck:{protocol:"http",path:"/health",interval:30,timeout:10,healthyThreshold:2,unhealthyThreshold:3},timeout:{perRequest:15000,idle:300000}}],serviceDiscovery:{type:"aws_cloud_map",namespace:$.namespace,serviceName:$.serviceName}})}createVirtualRouter($){let J=`vrouter-${Date.now()}-${this.routerCounter++}`,Y={id:J,...$};return this.virtualRouters.set(J,Y),Y}createCanaryRoute($){return this.createVirtualRouter({name:$.name,listeners:[{port:$.port,protocol:$.protocol}],routes:[{name:"canary-route",match:{prefix:"/"},action:{weightedTargets:[{virtualNode:$.stableTarget,weight:100-$.canaryWeight},{virtualNode:$.canaryTarget,weight:$.canaryWeight}]},retryPolicy:{maxRetries:3,perRetryTimeout:5000,httpRetryEvents:["server-error","gateway-error"],tcpRetryEvents:["connection-error"]}}]})}createVirtualGateway($){let J=`vgateway-${Date.now()}-${this.gatewayCounter++}`,Y={id:J,...$};return this.virtualGateways.set(J,Y),Y}createIngressGateway($){let J={port:$.port,protocol:"http",healthCheck:{protocol:"http",path:"/health",interval:30,timeout:10,healthyThreshold:2,unhealthyThreshold:3}};if($.enableTLS&&$.certificateArn)J.tls={mode:"STRICT",certificate:{acm:$.certificateArn}};return this.createVirtualGateway({name:$.name,listeners:[J],logging:{accessLog:{file:{path:"/dev/stdout"}}}})}getMesh($){return this.meshes.get($)}listMeshes(){return Array.from(this.meshes.values())}getVirtualNode($){return this.virtualNodes.get($)}listVirtualNodes(){return Array.from(this.virtualNodes.values())}generateMeshCF($){return{Type:"AWS::AppMesh::Mesh",Properties:{MeshName:$.name,Spec:{EgressFilter:{Type:"ALLOW_ALL"}}}}}generateVirtualNodeCF($,J){return{Type:"AWS::AppMesh::VirtualNode",Properties:{MeshName:J,VirtualNodeName:$.name,Spec:{Listeners:$.listeners.map((Y)=>({PortMapping:{Port:Y.port,Protocol:Y.protocol},...Y.healthCheck&&{HealthCheck:{Protocol:Y.healthCheck.protocol,...Y.healthCheck.path&&{Path:Y.healthCheck.path},IntervalMillis:Y.healthCheck.interval*1000,TimeoutMillis:Y.healthCheck.timeout*1000,HealthyThreshold:Y.healthCheck.healthyThreshold,UnhealthyThreshold:Y.healthCheck.unhealthyThreshold}}})),ServiceDiscovery:{AWSCloudMap:{NamespaceName:$.serviceDiscovery.namespace,ServiceName:$.serviceDiscovery.serviceName}}}}}}generateVirtualRouterCF($,J){return{Type:"AWS::AppMesh::VirtualRouter",Properties:{MeshName:J,VirtualRouterName:$.name,Spec:{Listeners:$.listeners.map((Y)=>({PortMapping:{Port:Y.port,Protocol:Y.protocol}}))}}}}clear(){this.meshes.clear(),this.virtualNodes.clear(),this.virtualRouters.clear(),this.virtualGateways.clear(),this.meshCounter=0,this.nodeCounter=0,this.routerCounter=0,this.gatewayCounter=0}}var $W=new J6;class o8{layers=new Map;versions=new Map;permissions=new Map;layerCounter=0;versionCounter=0;permissionCounter=0;createLayer($){let J=`layer-${Date.now()}-${this.layerCounter++}`,Y=1,Q={id:J,layerArn:`arn:aws:lambda:us-east-1:123456789012:layer:${$.layerName}:1`,version:1,...$};return this.layers.set(J,Q),Q}createNodeDependenciesLayer($){return this.createLayer({layerName:$.layerName,description:"Node.js dependencies layer",compatibleRuntimes:[`nodejs${$.nodeVersion}`],content:{type:"s3",s3Bucket:$.s3Bucket,s3Key:$.s3Key},size:5242880})}createUtilitiesLayer($){return this.createLayer({layerName:$.layerName,description:"Shared utilities and helpers",compatibleRuntimes:$.runtimes,content:{type:"s3",s3Bucket:$.s3Bucket,s3Key:$.s3Key},size:1048576})}publishVersion($){let J=this.layers.get($);if(!J)throw Error(`Layer not found: ${$}`);let Y=`version-${Date.now()}-${this.versionCounter++}`,Q=J.version+1,W={id:Y,layerName:J.layerName,version:Q,createdAt:new Date,compatibleRuntimes:J.compatibleRuntimes,size:J.size,codeHash:this.generateHash()};return this.versions.set(Y,W),J.version=Q,J.layerArn=`arn:aws:lambda:us-east-1:123456789012:layer:${J.layerName}:${Q}`,W}addPermission($){let J=`permission-${Date.now()}-${this.permissionCounter++}`,Y={id:J,layerName:$.layerName,version:$.version,principal:$.principal,action:"lambda:GetLayerVersion",organizationId:$.organizationId};return this.permissions.set(J,Y),Y}generateHash(){return Math.random().toString(36).substring(2,15)}getLayer($){return this.layers.get($)}listLayers(){return Array.from(this.layers.values())}getLayerVersions($){return Array.from(this.versions.values()).filter((J)=>J.layerName===$)}generateLayerCF($){return{Type:"AWS::Lambda::LayerVersion",Properties:{LayerName:$.layerName,Description:$.description,Content:$.content.type==="s3"?{S3Bucket:$.content.s3Bucket,S3Key:$.content.s3Key,...$.content.s3ObjectVersion&&{S3ObjectVersion:$.content.s3ObjectVersion}}:{ZipFile:$.content.zipFile},CompatibleRuntimes:$.compatibleRuntimes,...$.licenseInfo&&{LicenseInfo:$.licenseInfo}}}}generateLayerPermissionCF($){return{Type:"AWS::Lambda::LayerVersionPermission",Properties:{LayerVersionArn:`arn:aws:lambda:us-east-1:123456789012:layer:${$.layerName}:${$.version}`,Action:$.action,Principal:$.principal,...$.organizationId&&{OrganizationId:$.organizationId}}}}clear(){this.layers.clear(),this.versions.clear(),this.permissions.clear(),this.layerCounter=0,this.versionCounter=0,this.permissionCounter=0}}var IB=new o8;class e8{versions=new Map;aliases=new Map;deployments=new Map;versionCounter=0;aliasCounter=0;deploymentCounter=0;publishVersion($){let J=`version-${Date.now()}-${this.versionCounter++}`,Y=this.getNextVersionNumber($.functionName),Q={id:J,functionName:$.functionName,version:Y.toString(),functionArn:`arn:aws:lambda:us-east-1:123456789012:function:${$.functionName}:${Y}`,codeHash:this.generateHash(),description:$.description,runtime:$.runtime,memorySize:$.memorySize,timeout:$.timeout,publishedAt:new Date};return this.versions.set(J,Q),Q}getNextVersionNumber($){let J=Array.from(this.versions.values()).filter((Y)=>Y.functionName===$).map((Y)=>parseInt(Y.version));return J.length>0?Math.max(...J)+1:1}createAlias($){let J=`alias-${Date.now()}-${this.aliasCounter++}`,Y={id:J,aliasArn:`arn:aws:lambda:us-east-1:123456789012:function:${$.functionName}:${$.aliasName}`,revisionId:this.generateHash(),...$};return this.aliases.set(J,Y),Y}createProductionAlias($){return this.createAlias({functionName:$.functionName,aliasName:"production",functionVersion:$.version,description:"Production alias"})}createStagingAlias($){return this.createAlias({functionName:$.functionName,aliasName:"staging",functionVersion:$.version,description:"Staging alias"})}updateAlias($,J){let Y=this.aliases.get($);if(!Y)throw Error(`Alias not found: ${$}`);return Y.functionVersion=J,Y.revisionId=this.generateHash(),Y}configureWeightedRouting($,J){let Y=this.aliases.get($);if(!Y)throw Error(`Alias not found: ${$}`);return Y.routingConfig={additionalVersionWeights:J},Y}createCanaryDeployment($){let J=`deployment-${Date.now()}-${this.deploymentCounter++}`,Y=Array.from(this.aliases.values()).find((W)=>W.functionName===$.functionName&&W.aliasName===$.aliasName);if(!Y)Y=this.createAlias({functionName:$.functionName,aliasName:$.aliasName,functionVersion:$.fromVersion});this.configureWeightedRouting(Y.id,{[$.toVersion]:$.canaryWeight});let Q={id:J,functionName:$.functionName,fromVersion:$.fromVersion,toVersion:$.toVersion,aliasName:$.aliasName,strategy:"canary",status:"in_progress",startedAt:new Date};return this.deployments.set(J,Q),Q}completeDeployment($){let J=this.deployments.get($);if(!J)throw Error(`Deployment not found: ${$}`);let Y=Array.from(this.aliases.values()).find((Q)=>Q.functionName===J.functionName&&Q.aliasName===J.aliasName);if(Y)Y.functionVersion=J.toVersion,Y.routingConfig=void 0;return J.status="completed",J.completedAt=new Date,J}rollbackDeployment($){let J=this.deployments.get($);if(!J)throw Error(`Deployment not found: ${$}`);let Y=Array.from(this.aliases.values()).find((Q)=>Q.functionName===J.functionName&&Q.aliasName===J.aliasName);if(Y)Y.functionVersion=J.fromVersion,Y.routingConfig=void 0;return J.status="failed",J.completedAt=new Date,J}generateHash(){return Math.random().toString(36).substring(2,15)}getVersion($){return this.versions.get($)}listVersions($){let J=Array.from(this.versions.values());return $?J.filter((Y)=>Y.functionName===$):J}getAlias($){return this.aliases.get($)}listAliases($){let J=Array.from(this.aliases.values());return $?J.filter((Y)=>Y.functionName===$):J}generateVersionCF($){return{Type:"AWS::Lambda::Version",Properties:{FunctionName:$.functionName,Description:$.description}}}generateAliasCF($){return{Type:"AWS::Lambda::Alias",Properties:{FunctionName:$.functionName,Name:$.aliasName,FunctionVersion:$.functionVersion,Description:$.description,...$.routingConfig&&{RoutingConfig:{AdditionalVersionWeights:Object.entries($.routingConfig.additionalVersionWeights||{}).map(([J,Y])=>({FunctionVersion:J,FunctionWeight:Y}))}}}}}clear(){this.versions.clear(),this.aliases.clear(),this.deployments.clear(),this.versionCounter=0,this.aliasCounter=0,this.deploymentCounter=0}}var hB=new e8;class $9{configs=new Map;provisionedConfigs=new Map;schedules=new Map;autoScalingConfigs=new Map;configCounter=0;provisionedCounter=0;scheduleCounter=0;autoScalingCounter=0;setReservedConcurrency($){let J=`concurrency-${Date.now()}-${this.configCounter++}`,Y={id:J,functionName:$.functionName,reservedConcurrency:$.reservedConcurrency};return this.configs.set(J,Y),Y}setProvisionedConcurrency($){let J=`provisioned-${Date.now()}-${this.provisionedCounter++}`,Y={id:J,functionName:$.functionName,qualifier:$.qualifier,provisionedConcurrentExecutions:$.provisionedConcurrentExecutions,status:"pending",lastModified:new Date};return this.provisionedConfigs.set(J,Y),setTimeout(()=>{Y.status="ready",Y.allocatedConcurrency=$.provisionedConcurrentExecutions,Y.availableConcurrency=$.provisionedConcurrentExecutions},100),Y}configureWarmPool($){return this.setProvisionedConcurrency({functionName:$.functionName,qualifier:$.alias,provisionedConcurrentExecutions:$.minInstances})}createSchedule($){let J=`schedule-${Date.now()}-${this.scheduleCounter++}`,Y={id:J,...$};return this.schedules.set(J,Y),Y}createBusinessHoursSchedule($){return this.createSchedule({name:`${$.functionName}-business-hours`,functionName:$.functionName,qualifier:$.qualifier,schedule:[{name:"business-hours",cronExpression:"0 8 * * MON-FRI",targetConcurrency:$.businessHoursConcurrency},{name:"off-hours",cronExpression:"0 18 * * MON-FRI",targetConcurrency:$.offHoursConcurrency},{name:"weekend",cronExpression:"0 0 * * SAT",targetConcurrency:$.offHoursConcurrency}]})}configureAutoScaling($){let J=`autoscaling-${Date.now()}-${this.autoScalingCounter++}`,Y={id:J,...$};return this.autoScalingConfigs.set(J,Y),Y}configurePredictiveScaling($){return this.configureAutoScaling({functionName:$.functionName,qualifier:$.qualifier,minCapacity:$.baselineCapacity,maxCapacity:$.peakCapacity,targetUtilization:0.7,scaleInCooldown:300,scaleOutCooldown:60})}getConfig($){return this.configs.get($)}listConfigs(){return Array.from(this.configs.values())}getProvisionedConfig($){return this.provisionedConfigs.get($)}listProvisionedConfigs(){return Array.from(this.provisionedConfigs.values())}generateReservedConcurrencyCF($){return{Type:"AWS::Lambda::Function",Properties:{FunctionName:$.functionName,ReservedConcurrentExecutions:$.reservedConcurrency}}}generateProvisionedConcurrencyCF($){return{Type:"AWS::Lambda::Alias",Properties:{FunctionName:$.functionName,Name:$.qualifier,ProvisionedConcurrencyConfig:{ProvisionedConcurrentExecutions:$.provisionedConcurrentExecutions}}}}generateAutoScalingTargetCF($){return{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{ServiceNamespace:"lambda",ResourceId:`function:${$.functionName}:${$.qualifier}`,ScalableDimension:"lambda:function:ProvisionedConcurrentExecutions",MinCapacity:$.minCapacity,MaxCapacity:$.maxCapacity}}}generateAutoScalingPolicyCF($){return{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${$.functionName}-autoscaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:`${$.functionName}AutoScalingTarget`},TargetTrackingScalingPolicyConfiguration:{TargetValue:$.targetUtilization*100,PredefinedMetricSpecification:{PredefinedMetricType:"LambdaProvisionedConcurrencyUtilization"},ScaleInCooldown:$.scaleInCooldown||300,ScaleOutCooldown:$.scaleOutCooldown||60}}}}clear(){this.configs.clear(),this.provisionedConfigs.clear(),this.schedules.clear(),this.autoScalingConfigs.clear(),this.configCounter=0,this.provisionedCounter=0,this.scheduleCounter=0,this.autoScalingCounter=0}}var yB=new $9;class J9{destinations=new Map;records=new Map;eventBridgeDestinations=new Map;destinationCounter=0;recordCounter=0;eventBridgeCounter=0;configureDestinations($){let J=`destination-${Date.now()}-${this.destinationCounter++}`,Y={id:J,...$};return this.destinations.set(J,Y),Y}configureSQSDestination($){let J={type:"sqs",arn:$.queueArn};return this.configureDestinations({functionName:$.functionName,successDestination:$.onSuccess?J:void 0,failureDestination:$.onFailure?J:void 0,maxEventAge:21600,maxRetries:2})}configureSNSDestination($){let J={type:"sns",arn:$.topicArn};return this.configureDestinations({functionName:$.functionName,successDestination:$.onSuccess?J:void 0,failureDestination:$.onFailure?J:void 0,maxEventAge:21600,maxRetries:2})}configureEventBridgeDestination($){let J={type:"eventbridge",arn:$.eventBusArn};return this.configureDestinations({functionName:$.functionName,successDestination:$.onSuccess?J:void 0,failureDestination:$.onFailure?J:void 0,maxEventAge:21600,maxRetries:2})}configureLambdaDestination($){let J={type:"lambda",arn:$.destinationFunctionArn};return this.configureDestinations({functionName:$.functionName,successDestination:$.onSuccess?J:void 0,failureDestination:$.onFailure?J:void 0,maxEventAge:21600,maxRetries:2})}configureDLQWithNotification($){return this.configureDestinations({functionName:$.functionName,failureDestination:{type:"sqs",arn:$.dlqArn},maxEventAge:3600,maxRetries:0})}createEventBridgeIntegration($){let J=`eventbridge-${Date.now()}-${this.eventBridgeCounter++}`,Y={id:J,functionName:$.functionName,eventBusArn:$.eventBusArn,detailType:$.detailType||"Lambda Function Invocation Result",source:$.source||`lambda.${$.functionName}`};return this.eventBridgeDestinations.set(J,Y),Y}sendToDestination($){let J=Array.from(this.destinations.values()).find((U)=>U.functionName===$.functionName);if(!J)return null;let Y=$.status==="success"?J.successDestination:J.failureDestination;if(!Y)return null;let Q=`record-${Date.now()}-${this.recordCounter++}`,W={id:Q,timestamp:new Date,functionName:$.functionName,requestId:$.requestId,status:$.status,destinationType:Y.type,destinationArn:Y.arn,payload:$.payload,error:$.error};return this.records.set(Q,W),W}getDestination($){return this.destinations.get($)}listDestinations($){let J=Array.from(this.destinations.values());return $?J.filter((Y)=>Y.functionName===$):J}getDestinationRecords($){let J=Array.from(this.records.values());return $?J.filter((Y)=>Y.functionName===$):J}generateEventInvokeConfigCF($){return{Type:"AWS::Lambda::EventInvokeConfig",Properties:{FunctionName:$.functionName,Qualifier:$.qualifier||"$LATEST",MaximumEventAgeInSeconds:$.maxEventAge||21600,MaximumRetryAttempts:$.maxRetries??2,...$.successDestination&&{DestinationConfig:{OnSuccess:{Destination:$.successDestination.arn}}},...$.failureDestination&&{DestinationConfig:{OnFailure:{Destination:$.failureDestination.arn}}}}}}generateEventBridgeRuleCF($){return{Type:"AWS::Events::Rule",Properties:{EventBusName:$.eventBusArn.split("/").pop(),EventPattern:{source:[$.source],"detail-type":[$.detailType]},State:"ENABLED",Targets:[{Arn:`arn:aws:lambda:us-east-1:123456789012:function:${$.functionName}`,Id:$.id}]}}}clear(){this.destinations.clear(),this.records.clear(),this.eventBridgeDestinations.clear(),this.destinationCounter=0,this.recordCounter=0,this.eventBridgeCounter=0}}var fB=new J9;class Y9{vpcConfigs=new Map;endpoints=new Map;networkInterfaces=new Map;connectivity=new Map;configCounter=0;endpointCounter=0;eniCounter=0;connectivityCounter=0;configureVPC($){let J=`vpc-config-${Date.now()}-${this.configCounter++}`,Y={id:J,...$};this.vpcConfigs.set(J,Y);for(let Q of $.subnetIds)this.createNetworkInterface({functionName:$.functionName,subnetId:Q});return Y}configurePrivateVPC($){return this.configureVPC({functionName:$.functionName,vpcId:$.vpcId,subnetIds:$.privateSubnetIds,securityGroupIds:[$.securityGroupId],ipv6Allowed:!1})}configureMultiAZVPC($){if($.subnetIds.length<2)throw Error("Multi-AZ configuration requires at least 2 subnets");return this.configureVPC({functionName:$.functionName,vpcId:$.vpcId,subnetIds:$.subnetIds,securityGroupIds:$.securityGroupIds})}createVPCEndpoint($){let J=`endpoint-${Date.now()}-${this.endpointCounter++}`,Y={id:J,...$};return this.endpoints.set(J,Y),Y}createS3Endpoint($){return this.createVPCEndpoint({vpcId:$.vpcId,serviceName:"com.amazonaws.us-east-1.s3",endpointType:"Gateway",privateDnsEnabled:!1})}createDynamoDBEndpoint($){return this.createVPCEndpoint({vpcId:$.vpcId,serviceName:"com.amazonaws.us-east-1.dynamodb",endpointType:"Gateway",privateDnsEnabled:!1})}createSecretsManagerEndpoint($){return this.createVPCEndpoint({vpcId:$.vpcId,serviceName:"com.amazonaws.us-east-1.secretsmanager",endpointType:"Interface",subnetIds:$.subnetIds,securityGroupIds:$.securityGroupIds,privateDnsEnabled:!0})}createNetworkInterface($){let J=`eni-${Date.now()}-${this.eniCounter++}`,Y={id:J,functionName:$.functionName,networkInterfaceId:`eni-${Math.random().toString(36).substring(2,15)}`,subnetId:$.subnetId,privateIpAddress:`10.0.${Math.floor(Math.random()*255)}.${Math.floor(Math.random()*255)}`,status:"creating",attachedAt:new Date};return this.networkInterfaces.set(J,Y),setTimeout(()=>{Y.status="available"},100),Y}analyzeConnectivity($){let J=`connectivity-${Date.now()}-${this.connectivityCounter++}`,Y=Array.from(this.vpcConfigs.values()).find((H)=>H.functionName===$.functionName),Q=Array.from(this.endpoints.values()).filter((H)=>H.vpcId===Y?.vpcId).map((H)=>H.serviceName),W=[],U=$.hasNATGateway??!1,Z=$.hasInternetGateway??!1;if(!U&&!Z)W.push("Add NAT Gateway for internet access");if(!Q.includes("com.amazonaws.us-east-1.s3"))W.push("Add S3 VPC endpoint to reduce NAT costs");if(!Q.includes("com.amazonaws.us-east-1.dynamodb"))W.push("Add DynamoDB VPC endpoint for private access");let z={id:J,functionName:$.functionName,hasInternetAccess:U||Z,hasNATGateway:U,hasVPCEndpoints:Q.length>0,endpoints:Q,recommendations:W};return this.connectivity.set(J,z),z}getVPCConfig($){return this.vpcConfigs.get($)}listVPCConfigs($){let J=Array.from(this.vpcConfigs.values());return $?J.filter((Y)=>Y.functionName===$):J}getNetworkInterfaces($){return Array.from(this.networkInterfaces.values()).filter((J)=>J.functionName===$)}listVPCEndpoints($){let J=Array.from(this.endpoints.values());return $?J.filter((Y)=>Y.vpcId===$):J}generateVPCConfigCF($){return{VpcConfig:{SubnetIds:$.subnetIds,SecurityGroupIds:$.securityGroupIds,...$.ipv6Allowed&&{Ipv6AllowedForDualStack:!0}}}}generateVPCEndpointCF($){return{Type:"AWS::EC2::VPCEndpoint",Properties:{VpcId:$.vpcId,ServiceName:$.serviceName,VpcEndpointType:$.endpointType,...$.subnetIds&&{SubnetIds:$.subnetIds},...$.securityGroupIds&&{SecurityGroupIds:$.securityGroupIds},...$.privateDnsEnabled!==void 0&&{PrivateDnsEnabled:$.privateDnsEnabled}}}}generateSecurityGroupCF($){return{Type:"AWS::EC2::SecurityGroup",Properties:{GroupName:$.groupName,GroupDescription:`Security group for Lambda ${$.groupName}`,VpcId:$.vpcId,...$.ingressRules&&{SecurityGroupIngress:$.ingressRules.map((J)=>({IpProtocol:J.protocol,FromPort:J.fromPort,ToPort:J.toPort,...J.cidrIp&&{CidrIp:J.cidrIp},...J.sourceSecurityGroupId&&{SourceSecurityGroupId:J.sourceSecurityGroupId}}))},...$.egressRules&&{SecurityGroupEgress:$.egressRules.map((J)=>({IpProtocol:J.protocol,FromPort:J.fromPort,ToPort:J.toPort,CidrIp:J.cidrIp||"0.0.0.0/0"}))}}}}clear(){this.vpcConfigs.clear(),this.endpoints.clear(),this.networkInterfaces.clear(),this.connectivity.clear(),this.configCounter=0,this.endpointCounter=0,this.eniCounter=0,this.connectivityCounter=0}}var uB=new Y9;class Q9{dlqConfigs=new Map;messages=new Map;alarms=new Map;reprocessing=new Map;configCounter=0;messageCounter=0;alarmCounter=0;reprocessCounter=0;configureDLQ($){let J=`dlq-${Date.now()}-${this.configCounter++}`,Y={id:J,...$};return this.dlqConfigs.set(J,Y),Y}configureSQSDLQ($){return this.configureDLQ({functionName:$.functionName,targetArn:$.queueArn,targetType:"sqs",maxReceiveCount:$.maxReceiveCount||3,retentionPeriod:$.retentionPeriod||1209600})}configureSNSDLQ($){return this.configureDLQ({functionName:$.functionName,targetArn:$.topicArn,targetType:"sns"})}configureDLQWithAlarm($){let J=this.configureSQSDLQ({functionName:$.functionName,queueArn:$.queueArn});return this.createDLQAlarm({dlqConfigId:J.id,alarmName:`${$.functionName}-dlq-alarm`,threshold:$.alarmThreshold,evaluationPeriods:1,notificationTopicArn:$.notificationTopicArn,enabled:!0}),J}sendToDLQ($){let J=`message-${Date.now()}-${this.messageCounter++}`,Y={id:J,timestamp:new Date,...$};return this.messages.set(J,Y),Y}createDLQAlarm($){let J=`alarm-${Date.now()}-${this.alarmCounter++}`,Y={id:J,...$};return this.alarms.set(J,Y),Y}createAgeAlarm($){let J=this.dlqConfigs.get($.dlqConfigId);if(!J)throw Error(`DLQ config not found: ${$.dlqConfigId}`);return this.createDLQAlarm({dlqConfigId:$.dlqConfigId,alarmName:`${J.functionName}-dlq-age-alarm`,threshold:$.maxAgeSeconds,evaluationPeriods:1,notificationTopicArn:$.notificationTopicArn,enabled:!0})}async reprocessMessage($){let J=this.messages.get($);if(!J)throw Error(`Message not found: ${$}`);let Y=Array.from(this.dlqConfigs.values()).find((U)=>U.functionName===J.functionName);if(!Y)throw Error(`DLQ config not found for function: ${J.functionName}`);let Q=`reprocess-${Date.now()}-${this.reprocessCounter++}`,W={id:Q,dlqConfigId:Y.id,messageId:$,status:"pending",startedAt:new Date};return this.reprocessing.set(Q,W),setTimeout(()=>{W.status="processing",setTimeout(()=>{let U=Math.random()>0.3;if(W.status=U?"success":"failed",W.completedAt=new Date,!U)W.error="Reprocessing failed - same error occurred";else this.messages.delete($)},100)},50),W}async batchReprocess($){let J=this.dlqConfigs.get($.dlqConfigId);if(!J)throw Error(`DLQ config not found: ${$.dlqConfigId}`);let Q=Array.from(this.messages.values()).filter((W)=>W.functionName===J.functionName).slice(0,$.maxMessages||10).map((W)=>this.reprocessMessage(W.id));return Promise.all(Q)}getDLQStats($){let J=this.dlqConfigs.get($);if(!J)throw Error(`DLQ config not found: ${$}`);let Y=Array.from(this.messages.values()).filter((Z)=>Z.functionName===J.functionName),Q={},W=0;for(let Z of Y)Q[Z.errorType]=(Q[Z.errorType]||0)+1,W+=Z.attemptCount;let U=Y.map((Z)=>Z.timestamp);return{totalMessages:Y.length,oldestMessage:U.length>0?new Date(Math.min(...U.map((Z)=>Z.getTime()))):void 0,newestMessage:U.length>0?new Date(Math.max(...U.map((Z)=>Z.getTime()))):void 0,averageAttempts:Y.length>0?W/Y.length:0,errorTypes:Q}}getDLQConfig($){return this.dlqConfigs.get($)}listDLQConfigs(){return Array.from(this.dlqConfigs.values())}getDLQMessages($){let J=this.dlqConfigs.get($);if(!J)return[];return Array.from(this.messages.values()).filter((Y)=>Y.functionName===J.functionName)}generateDLQCF($){return{DeadLetterConfig:{TargetArn:$.targetArn}}}generateSQSDLQCF($){return{Type:"AWS::SQS::Queue",Properties:{QueueName:`${$.functionName}-dlq`,MessageRetentionPeriod:$.retentionPeriod||1209600,...$.maxReceiveCount&&{RedrivePolicy:{deadLetterTargetArn:$.targetArn,maxReceiveCount:$.maxReceiveCount}}}}}generateDLQAlarmCF($){let J=this.dlqConfigs.get($.dlqConfigId);if(!J)throw Error(`DLQ config not found: ${$.dlqConfigId}`);return{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:$.alarmName,AlarmDescription:`DLQ alarm for ${J.functionName}`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Sum",Period:300,EvaluationPeriods:$.evaluationPeriods,Threshold:$.threshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:J.targetArn.split(":").pop()}],...$.notificationTopicArn&&{AlarmActions:[$.notificationTopicArn]}}}}clear(){this.dlqConfigs.clear(),this.messages.clear(),this.alarms.clear(),this.reprocessing.clear(),this.configCounter=0,this.messageCounter=0,this.alarmCounter=0,this.reprocessCounter=0}}var mB=new Q9;class Y6{policies=new Map;healthChecks=new Map;trafficPolicies=new Map;policyCounter=0;healthCheckCounter=0;trafficPolicyCounter=0;createWeightedPolicy($){let J=`policy-${Date.now()}-${this.policyCounter++}`,Y={id:J,type:"weighted",...$};return this.policies.set(J,Y),Y}createLatencyPolicy($){let J=`policy-${Date.now()}-${this.policyCounter++}`,Y={id:J,type:"latency",...$};return this.policies.set(J,Y),Y}createFailoverPolicy($){let J=`policy-${Date.now()}-${this.policyCounter++}`,Y={id:J,type:"failover",...$};return this.policies.set(J,Y),Y}createGeolocationPolicy($){let J=`policy-${Date.now()}-${this.policyCounter++}`,Y={id:J,type:"geolocation",...$};return this.policies.set(J,Y),Y}createGeoproximityPolicy($){let J=`policy-${Date.now()}-${this.policyCounter++}`,Y={id:J,type:"geoproximity",...$};return this.policies.set(J,Y),Y}createHTTPHealthCheck($){let J=`health-check-${Date.now()}-${this.healthCheckCounter++}`,Y={id:J,type:$.port===443?"https":"http",requestInterval:$.requestInterval||30,failureThreshold:$.failureThreshold||3,healthCheckStatus:"Unknown",port:$.port||($.port===443?443:80),...$};return this.healthChecks.set(J,Y),setTimeout(()=>{Y.healthCheckStatus=Math.random()>0.2?"Healthy":"Unhealthy"},100),Y}createTCPHealthCheck($){let J=`health-check-${Date.now()}-${this.healthCheckCounter++}`,Y={id:J,type:"tcp",fullyQualifiedDomainName:$.ipAddress,requestInterval:$.requestInterval||30,failureThreshold:$.failureThreshold||3,healthCheckStatus:"Unknown",...$};return this.healthChecks.set(J,Y),setTimeout(()=>{Y.healthCheckStatus=Math.random()>0.1?"Healthy":"Unhealthy"},100),Y}createCalculatedHealthCheck($){let J=`health-check-${Date.now()}-${this.healthCheckCounter++}`,Y={id:J,type:"calculated",requestInterval:30,failureThreshold:0,healthCheckStatus:"Unknown",...$};return this.healthChecks.set(J,Y),setTimeout(()=>{let W=$.childHealthChecks.filter((U)=>{return this.healthChecks.get(U)?.healthCheckStatus==="Healthy"}).length;Y.healthCheckStatus=W>=$.healthThreshold?"Healthy":"Unhealthy"},150),Y}createTrafficPolicy($){let J=`traffic-policy-${Date.now()}-${this.trafficPolicyCounter++}`,Y={id:J,version:1,...$};return this.trafficPolicies.set(J,Y),Y}createFailoverTrafficPolicy($){return this.createTrafficPolicy({name:$.name,document:{recordType:$.recordType||"A",startRule:"failover",endpoints:{primary:{type:"value",value:$.primaryEndpoint},secondary:{type:"value",value:$.secondaryEndpoint}},rules:{failover:{ruleType:"failover",primary:"primary",secondary:"secondary"}}}})}createGeoproximityTrafficPolicy($){let J={},Y=[];return $.locations.forEach((Q,W)=>{let U=`endpoint${W}`;J[U]={type:"value",value:Q.endpoint},Y.push({endpointReference:U,region:Q.region,latitude:Q.latitude,longitude:Q.longitude,bias:Q.bias})}),this.createTrafficPolicy({name:$.name,document:{recordType:"A",startRule:"geoproximity",endpoints:J,rules:{geoproximity:{ruleType:"geoproximity",locations:Y}}}})}getPolicy($){return this.policies.get($)}listPolicies(){return Array.from(this.policies.values())}getHealthCheck($){return this.healthChecks.get($)}listHealthChecks(){return Array.from(this.healthChecks.values())}getHealthCheckStatus($){return this.healthChecks.get($)?.healthCheckStatus||"Unknown"}generateHealthCheckCF($){let J={Type:"AWS::Route53::HealthCheck",Properties:{HealthCheckConfig:{Type:$.type.toUpperCase(),RequestInterval:$.requestInterval,FailureThreshold:$.failureThreshold,...$.measureLatency&&{MeasureLatency:!0}},HealthCheckTags:[{Key:"Name",Value:$.name}]}};if($.type==="calculated"){let Y=$;J.Properties.HealthCheckConfig.ChildHealthChecks=Y.childHealthChecks,J.Properties.HealthCheckConfig.HealthThreshold=Y.healthThreshold}else{if($.ipAddress)J.Properties.HealthCheckConfig.IPAddress=$.ipAddress;if($.fullyQualifiedDomainName)J.Properties.HealthCheckConfig.FullyQualifiedDomainName=$.fullyQualifiedDomainName;if($.port)J.Properties.HealthCheckConfig.Port=$.port;if($.resourcePath)J.Properties.HealthCheckConfig.ResourcePath=$.resourcePath;if($.enableSNI)J.Properties.HealthCheckConfig.EnableSNI=!0}return J}generateWeightedRecordSetCF($){return{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:$.hostedZoneId,Name:$.name,Type:$.type,TTL:$.ttl,ResourceRecords:$.resourceRecords,Weight:$.weight,SetIdentifier:$.setIdentifier,...$.healthCheckId&&{HealthCheckId:$.healthCheckId}}}}generateFailoverRecordSetCF($){return{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:$.hostedZoneId,Name:$.name,Type:$.type,TTL:$.ttl,ResourceRecords:$.resourceRecords,Failover:$.failover,SetIdentifier:$.setIdentifier,...$.healthCheckId&&{HealthCheckId:$.healthCheckId}}}}clear(){this.policies.clear(),this.healthChecks.clear(),this.trafficPolicies.clear(),this.policyCounter=0,this.healthCheckCounter=0,this.trafficPolicyCounter=0}}var JW=new Y6;class W9{configs=new Map;ksks=new Map;validations=new Map;configCounter=0;kskCounter=0;validationCounter=0;enableDNSSEC($){let J=`dnssec-${Date.now()}-${this.configCounter++}`,Y={id:J,hostedZoneId:$.hostedZoneId,status:"SIGNING",signingStatus:"Initializing DNSSEC signing"};if(this.configs.set(J,Y),$.kmsKeyArn)this.createKSK({name:`ksk-${$.hostedZoneId}`,hostedZoneId:$.hostedZoneId,kmsKeyArn:$.kmsKeyArn});return setTimeout(()=>{Y.status="SIGNED",Y.signingStatus="DNSSEC signing complete"},100),Y}disableDNSSEC($){let J=this.configs.get($);if(!J)throw Error(`DNSSEC config not found: ${$}`);return J.status="DELETING",J.signingStatus="Removing DNSSEC signing",setTimeout(()=>{J.status="NOT_SIGNING",J.signingStatus="DNSSEC signing removed"},100),J}createKSK($){let J=`ksk-${Date.now()}-${this.kskCounter++}`,Y={id:J,status:"ACTIVE",flag:257,keyManagementServiceArn:$.kmsKeyArn,digestAlgorithm:2,keyTag:Math.floor(Math.random()*65535),publicKey:this.generatePublicKey(),...$};Y.dnskeyRecord=`${Y.flag} 3 8 ${Y.publicKey}`;let Q=this.generateDigest(Y.dnskeyRecord);return Y.digestValue=Q,Y.dsRecord=`${Y.keyTag} 8 ${Y.digestAlgorithm} ${Q}`,this.ksks.set(J,Y),Y}deactivateKSK($){let J=this.ksks.get($);if(!J)throw Error(`KSK not found: ${$}`);return J.status="INACTIVE",J}validateDNSSEC($){let J=`validation-${Date.now()}-${this.validationCounter++}`,Y=$.checkDNSKEY!==!1?Math.random()>0.1:!1,Q=$.checkRRSIG!==!1?Math.random()>0.1:!1,W=Y&&Q,U=[];if(!Y)U.push("DNSKEY record not found");if(!Q)U.push("RRSIG record not found");let Z;if(!Y&&!Q)Z="INSECURE";else if(Y&&Q&&W)Z="VALID";else if(Y||Q)Z="BOGUS",U.push("Invalid signature or incomplete DNSSEC chain");else Z="INVALID";let z={id:J,domain:$.domain,validationStatus:Z,dnskeyPresent:Y,rrsigPresent:Q,validSignature:W,errors:U};return this.validations.set(J,z),z}getDNSSECConfig($){return this.configs.get($)}listDNSSECConfigs(){return Array.from(this.configs.values())}getKSK($){return this.ksks.get($)}listKSKs($){let J=Array.from(this.ksks.values());return $?J.filter((Y)=>Y.hostedZoneId===$):J}getDSRecord($){let J=this.ksks.get($);if(!J||!J.dsRecord)throw Error("DS record not available");return J.dsRecord}generatePublicKey(){let J="";for(let Y=0;Y<256;Y++)J+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(Math.floor(Math.random()*64));return J}generateDigest($){let Y="";for(let Q=0;Q<64;Q++)Y+="0123456789ABCDEF".charAt(Math.floor(Math.random()*16));return Y}generateDNSSECCF($){return{Type:"AWS::Route53::DNSSEC",Properties:{HostedZoneId:$.hostedZoneId}}}generateKSKCF($){return{Type:"AWS::Route53::KeySigningKey",Properties:{Name:$.name,HostedZoneId:$.hostedZoneId,KeyManagementServiceArn:$.keyManagementServiceArn,Status:$.status}}}clear(){this.configs.clear(),this.ksks.clear(),this.validations.clear(),this.configCounter=0,this.kskCounter=0,this.validationCounter=0}}var pB=new W9;class U9{endpoints=new Map;rules=new Map;firewalls=new Map;ruleGroups=new Map;domainLists=new Map;endpointCounter=0;ruleCounter=0;firewallCounter=0;ruleGroupCounter=0;domainListCounter=0;createResolverEndpoint($){let J=`endpoint-${Date.now()}-${this.endpointCounter++}`,Y={id:J,status:"CREATING",...$};return this.endpoints.set(J,Y),setTimeout(()=>{Y.status="OPERATIONAL",Y.ipAddresses.forEach((Q)=>{if(!Q.ip)Q.ip=`10.0.${Math.floor(Math.random()*255)}.${Math.floor(Math.random()*255)}`})},100),Y}createInboundEndpoint($){return this.createResolverEndpoint({name:$.name,direction:"INBOUND",ipAddresses:$.subnetIds.map((J)=>({subnetId:J})),securityGroupIds:$.securityGroupIds})}createOutboundEndpoint($){return this.createResolverEndpoint({name:$.name,direction:"OUTBOUND",ipAddresses:$.subnetIds.map((J)=>({subnetId:J})),securityGroupIds:$.securityGroupIds})}createResolverRule($){let J=`rule-${Date.now()}-${this.ruleCounter++}`,Y={id:J,status:"CREATING",...$};return this.rules.set(J,Y),setTimeout(()=>{Y.status="COMPLETE"},100),Y}createForwardRule($){return this.createResolverRule({name:$.name,ruleType:"FORWARD",domainName:$.domainName,targetIps:$.targetIps,resolverEndpointId:$.resolverEndpointId})}createSystemRule($){return this.createResolverRule({name:$.name,ruleType:"SYSTEM",domainName:$.domainName})}createFirewallDomainList($){let J=`domain-list-${Date.now()}-${this.domainListCounter++}`,Y={id:J,status:"CREATING",...$};return this.domainLists.set(J,Y),setTimeout(()=>{Y.status="COMPLETE"},100),Y}createFirewallRuleGroup($){let J=`rule-group-${Date.now()}-${this.ruleGroupCounter++}`,Y={id:J,name:$.name,rules:$.rules.map((Q,W)=>({id:`rule-${J}-${W}`,...Q})),shareStatus:"NOT_SHARED"};return this.ruleGroups.set(J,Y),Y}createBlockRule($){return this.createFirewallRuleGroup({name:$.name,rules:[{name:$.name,priority:$.priority,action:"BLOCK",blockResponse:$.blockResponse||"NODATA",blockOverrideDomain:$.blockOverrideDomain,firewallDomainListId:$.domainListId}]})}createAllowRule($){return this.createFirewallRuleGroup({name:$.name,rules:[{name:$.name,priority:$.priority,action:"ALLOW",firewallDomainListId:$.domainListId}]})}createDNSFirewall($){let J=`firewall-${Date.now()}-${this.firewallCounter++}`,Y={id:J,name:$.name,firewallRuleGroupAssociations:$.ruleGroupAssociations.map((Q,W)=>({id:`assoc-${J}-${W}`,vpcId:$.vpcId,firewallRuleGroupId:Q.firewallRuleGroupId,priority:Q.priority,mutationProtection:Q.mutationProtection||"DISABLED",status:"COMPLETE"}))};return this.firewalls.set(J,Y),Y}createMalwareProtectionFirewall($){let J=this.createFirewallDomainList({name:`${$.name}-malware-domains`,domains:$.maliciousDomains}),Y=this.createBlockRule({name:`${$.name}-block-malware`,priority:100,domainListId:J.id,blockResponse:"NXDOMAIN"});return this.createDNSFirewall({name:$.name,vpcId:$.vpcId,ruleGroupAssociations:[{firewallRuleGroupId:Y.id,priority:100,mutationProtection:"ENABLED"}]})}getEndpoint($){return this.endpoints.get($)}listEndpoints($){let J=Array.from(this.endpoints.values());return $?J.filter((Y)=>Y.direction===$):J}getRule($){return this.rules.get($)}listRules(){return Array.from(this.rules.values())}getFirewall($){return this.firewalls.get($)}listFirewalls(){return Array.from(this.firewalls.values())}generateResolverEndpointCF($){return{Type:"AWS::Route53Resolver::ResolverEndpoint",Properties:{Name:$.name,Direction:$.direction,IpAddresses:$.ipAddresses.map((J)=>({SubnetId:J.subnetId,...J.ip&&{Ip:J.ip}})),SecurityGroupIds:$.securityGroupIds}}}generateResolverRuleCF($){return{Type:"AWS::Route53Resolver::ResolverRule",Properties:{Name:$.name,RuleType:$.ruleType,DomainName:$.domainName,...$.targetIps&&{TargetIps:$.targetIps.map((J)=>({Ip:J.ip,Port:J.port||53}))},...$.resolverEndpointId&&{ResolverEndpointId:$.resolverEndpointId}}}}generateFirewallRuleGroupCF($){return{Type:"AWS::Route53Resolver::FirewallRuleGroup",Properties:{Name:$.name,FirewallRules:$.rules.map((J)=>({Name:J.name,Priority:J.priority,Action:J.action,FirewallDomainListId:J.firewallDomainListId,...J.blockResponse&&{BlockResponse:J.blockResponse},...J.blockOverrideDomain&&{BlockOverrideDomain:J.blockOverrideDomain},...J.blockOverrideTTL&&{BlockOverrideTtl:J.blockOverrideTTL}}))}}}clear(){this.endpoints.clear(),this.rules.clear(),this.firewalls.clear(),this.ruleGroups.clear(),this.domainLists.clear(),this.endpointCounter=0,this.ruleCounter=0,this.firewallCounter=0,this.ruleGroupCounter=0,this.domainListCounter=0}}var aB=new U9;class Z9{bounces=new Map;complaints=new Map;handlers=new Map;suppressionList=new Map;metrics=new Map;bounceCounter=0;complaintCounter=0;handlerCounter=0;suppressionCounter=0;metricsCounter=0;recordBounce($){let J=`bounce-${Date.now()}-${this.bounceCounter++}`,Y={id:J,...$};if(this.bounces.set(J,Y),$.bounceType==="Permanent")this.addToSuppressionList({emailAddress:$.recipient,reason:"BOUNCE"});return Y}recordComplaint($){let J=`complaint-${Date.now()}-${this.complaintCounter++}`,Y={id:J,...$};this.complaints.set(J,Y);for(let Q of $.recipients)this.addToSuppressionList({emailAddress:Q,reason:"COMPLAINT"});return Y}createBounceHandler($){let J=`handler-${Date.now()}-${this.handlerCounter++}`,Y={id:J,...$};return this.handlers.set(J,Y),Y}createAutomaticBounceHandler($){return this.createBounceHandler({name:$.name,bounceThreshold:5,complaintThreshold:0.1,suppressionDuration:2592000,autoSuppress:!0,notificationTopicArn:$.notificationTopicArn})}addToSuppressionList($){let J=`suppression-${Date.now()}-${this.suppressionCounter++}`,Y=$.expirationDays?new Date(Date.now()+$.expirationDays*24*60*60*1000):void 0,Q={id:J,emailAddress:$.emailAddress,reason:$.reason,suppressedAt:new Date,expiresAt:Y,bounceCount:$.reason==="BOUNCE"?1:0,complaintCount:$.reason==="COMPLAINT"?1:0};return this.suppressionList.set($.emailAddress,Q),Q}removeFromSuppressionList($){return this.suppressionList.delete($)}isSuppressed($){let J=this.suppressionList.get($);if(!J)return!1;if(J.expiresAt&&J.expiresAt<new Date)return this.suppressionList.delete($),!1;return!0}getBounceStatistics($,J){let Y=Array.from(this.bounces.values()).filter((B)=>B.timestamp>=$&&B.timestamp<=J),Q=Y.length,W=Y.filter((B)=>B.bounceType==="Permanent").length,U=Y.filter((B)=>B.bounceType==="Transient").length,Z=Q*10,z=Q/Z*100,H=new Map;for(let B of Y)H.set(B.recipient,(H.get(B.recipient)||0)+1);let K=Array.from(H.entries()).map(([B,O])=>({email:B,count:O})).sort((B,O)=>O.count-B.count).slice(0,10);return{totalBounces:Q,permanentBounces:W,transientBounces:U,bounceRate:z,topRecipients:K}}getComplaintStatistics($,J){let Y=Array.from(this.complaints.values()).filter((H)=>H.timestamp>=$&&H.timestamp<=J),Q=Y.length,W=new Set;for(let H of Y)for(let K of H.recipients)W.add(K);let U=W.size,Z=Q*1000,z=Q/Z*100;return{totalComplaints:Q,uniqueComplainters:U,complaintRate:z}}calculateReputationMetrics(){let $=`metrics-${Date.now()}-${this.metricsCounter++}`,J=new Date,Y=new Date(J.getTime()-86400000),Q=this.getBounceStatistics(Y,J),W=this.getComplaintStatistics(Y,J),U;if(Q.bounceRate>10||W.complaintRate>0.5)U="Shutdown";else if(Q.bounceRate>5||W.complaintRate>0.1)U="Probation";else if(Q.bounceRate>2||W.complaintRate>0.05)U="Warning";else U="Good";let Z={id:$,timestamp:J,bounceRate:Q.bounceRate,complaintRate:W.complaintRate,sendingQuota:50000,maxSendRate:14,sentLast24Hours:Q.totalBounces*10,reputationStatus:U};return this.metrics.set($,Z),Z}getBounces($){let J=Array.from(this.bounces.values());return $?J.filter((Y)=>Y.messageId===$):J}getComplaints($){let J=Array.from(this.complaints.values());return $?J.filter((Y)=>Y.messageId===$):J}listSuppressionList($){let J=Array.from(this.suppressionList.values());return $?J.filter((Y)=>Y.reason===$):J}generateSNSSubscriptionCF($){return{Type:"AWS::SNS::Subscription",Properties:{TopicArn:$.topicArn,Endpoint:$.endpoint,Protocol:$.protocol}}}generateEventDestinationCF($){return{Type:"AWS::SES::ConfigurationSetEventDestination",Properties:{ConfigurationSetName:$.configurationSetName,EventDestination:{Name:$.eventDestinationName,Enabled:!0,MatchingEventTypes:$.eventTypes,...$.snsTopicArn&&{SnsDestination:{TopicARN:$.snsTopicArn}},...$.cloudWatchDestination&&{CloudWatchDestination:$.cloudWatchDestination}}}}}clear(){this.bounces.clear(),this.complaints.clear(),this.handlers.clear(),this.suppressionList.clear(),this.metrics.clear(),this.bounceCounter=0,this.complaintCounter=0,this.handlerCounter=0,this.suppressionCounter=0,this.metricsCounter=0}}var sB=new Z9;class z9{events=new Map;campaigns=new Map;reports=new Map;abTests=new Map;eventCounter=0;campaignCounter=0;reportCounter=0;abTestCounter=0;trackEvent($){let J=`event-${Date.now()}-${this.eventCounter++}`,Y={id:J,...$};if(this.events.set(J,Y),$.tags?.campaignId)this.updateCampaignStats($.tags.campaignId,$.eventType);return Y}trackOpen($){return this.trackEvent({...$,eventType:"open",timestamp:new Date})}trackClick($){return this.trackEvent({...$,eventType:"click",timestamp:new Date})}createCampaign($){let J=`campaign-${Date.now()}-${this.campaignCounter++}`,Y={id:J,sentCount:0,deliveredCount:0,openCount:0,clickCount:0,bounceCount:0,complaintCount:0,createdAt:new Date,...$};return this.campaigns.set(J,Y),Y}updateCampaignStats($,J){let Y=this.campaigns.get($);if(!Y)return;switch(J){case"send":Y.sentCount++;break;case"delivery":Y.deliveredCount++;break;case"open":Y.openCount++;break;case"click":Y.clickCount++;break;case"bounce":Y.bounceCount++;break;case"complaint":Y.complaintCount++;break}}generateReport($){let J=`report-${Date.now()}-${this.reportCounter++}`,Y=Array.from(this.events.values()).filter((S)=>{let R=S.timestamp>=$.startDate&&S.timestamp<=$.endDate,C=!$.campaignId||S.tags?.campaignId===$.campaignId;return R&&C}),Q=Y.filter((S)=>S.eventType==="send").length,W=Y.filter((S)=>S.eventType==="delivery").length,U=Y.filter((S)=>S.eventType==="open").length,Z=Y.filter((S)=>S.eventType==="click").length,z=Y.filter((S)=>S.eventType==="bounce").length,H=Y.filter((S)=>S.eventType==="complaint").length,K=Q>0?W/Q*100:0,B=W>0?U/W*100:0,O=W>0?Z/W*100:0,X=U>0?Z/U*100:0,j=Q>0?z/Q*100:0,q=W>0?H/W*100:0,E=new Map;for(let S of Y)if(S.eventType==="click"){let R=S;E.set(R.link,(E.get(R.link)||0)+1)}let F=Array.from(E.entries()).map(([S,R])=>({link:S,clicks:R})).sort((S,R)=>R.clicks-S.clicks).slice(0,10),w={desktop:0,mobile:0,tablet:0,unknown:0};for(let S of Y)if(S.eventType==="open"||S.eventType==="click"){let R=S.userAgent.toLowerCase();if(R.includes("mobile"))w.mobile++;else if(R.includes("tablet"))w.tablet++;else if(R.includes("mozilla"))w.desktop++;else w.unknown++}let T={id:J,campaignId:$.campaignId,startDate:$.startDate,endDate:$.endDate,totalSent:Q,totalDelivered:W,totalOpened:U,totalClicked:Z,totalBounced:z,totalComplaints:H,deliveryRate:K,openRate:B,clickRate:O,clickToOpenRate:X,bounceRate:j,complaintRate:q,topLinks:F,deviceBreakdown:w,locationBreakdown:{}};return this.reports.set(J,T),T}createABTest($){let J=`abtest-${Date.now()}-${this.abTestCounter++}`,Y={id:J,name:$.name,variants:$.variants.map((Q,W)=>({id:`variant-${J}-${W}`,sentCount:0,openCount:0,clickCount:0,conversionCount:0,...Q})),status:"draft"};return this.abTests.set(J,Y),Y}startABTest($){let J=this.abTests.get($);if(!J)throw Error(`A/B test not found: ${$}`);return J.status="running",J.startedAt=new Date,J}completeABTest($){let J=this.abTests.get($);if(!J)throw Error(`A/B test not found: ${$}`);let Y=J.variants[0],Q=0;for(let W of J.variants){let U=W.sentCount>0?W.openCount/W.sentCount:0;if(U>Q)Q=U,Y=W}return J.status="completed",J.completedAt=new Date,J.winner=Y.id,J}getCampaign($){return this.campaigns.get($)}listCampaigns(){return Array.from(this.campaigns.values())}getEvents($){let J=Array.from(this.events.values());if($?.messageId)J=J.filter((Y)=>Y.messageId===$.messageId);if($?.eventType)J=J.filter((Y)=>Y.eventType===$.eventType);if($?.startDate)J=J.filter((Y)=>Y.timestamp>=$.startDate);if($?.endDate)J=J.filter((Y)=>Y.timestamp<=$.endDate);return J}generateTrackingConfigurationCF($){return{Type:"AWS::SES::ConfigurationSet",Properties:{Name:$.configurationSetName,...$.openTracking&&{TrackingOptions:{CustomRedirectDomain:"tracking.example.com"}}}}}clear(){this.events.clear(),this.campaigns.clear(),this.reports.clear(),this.abTests.clear(),this.eventCounter=0,this.campaignCounter=0,this.reportCounter=0,this.abTestCounter=0}}var tB=new z9;class G9{dashboards=new Map;warmupPlans=new Map;domainReputations=new Map;dashboardCounter=0;warmupCounter=0;domainCounter=0;getReputationDashboard(){let $=`dashboard-${Date.now()}-${this.dashboardCounter++}`,J=Math.random()*5,Y=Math.random()*0.5,Q=Math.floor(Math.random()*10),W=Math.max(0,100-J*10-Y*100-Q*2),U=[];if(J>2)U.push("Reduce bounce rate by cleaning email list");if(Y>0.1)U.push("Review email content and unsubscribe process");if(Q>5)U.push("Improve email relevance and targeting");let Z={id:$,timestamp:new Date,overallScore:W,bounceRate:J,complaintRate:Y,spamReports:Q,blacklistStatus:this.checkBlacklists(),dkimStatus:"VERIFIED",spfStatus:"PASS",dmarcStatus:"PASS",sendingLimits:{maxSendRate:14,max24HourSend:50000,sentLast24Hours:12000,remainingQuota:38000,quotaResetTime:new Date(Date.now()+86400000)},recommendations:U};return this.dashboards.set($,Z),Z}checkBlacklists(){return["Spamhaus ZEN","Spamcop","SORBS","Barracuda","URIBL"].map((J)=>({listName:J,listed:Math.random()>0.95,delistUrl:`https://www.${J.toLowerCase().replace(/\s/g,"")}.org/delist`}))}createWarmupPlan($){let J=`warmup-${Date.now()}-${this.warmupCounter++}`,Y=[],Q=($.targetDailyLimit-$.initialDailyLimit)/$.durationDays;for(let U=0;U<$.durationDays;U++)Y.push(Math.floor($.initialDailyLimit+Q*U));let W={id:J,name:$.name,startDate:new Date,currentDay:1,totalDays:$.durationDays,dailyLimits:Y,currentLimit:Y[0],status:"active"};return this.warmupPlans.set(J,W),W}createAggressiveWarmupPlan($){return this.createWarmupPlan({name:$.name,initialDailyLimit:500,targetDailyLimit:50000,durationDays:14})}createConservativeWarmupPlan($){return this.createWarmupPlan({name:$.name,initialDailyLimit:200,targetDailyLimit:50000,durationDays:30})}advanceWarmupPlan($){let J=this.warmupPlans.get($);if(!J)throw Error(`Warmup plan not found: ${$}`);if(J.currentDay<J.totalDays)J.currentDay++,J.currentLimit=J.dailyLimits[J.currentDay-1];if(J.currentDay>=J.totalDays)J.status="completed";return J}trackDomainReputation($){let J=`domain-${Date.now()}-${this.domainCounter++}`,Y=$.delivered/$.totalSent*100,Q=$.delivered>0?$.opened/$.delivered*100:0,W=$.delivered>0?$.clicked/$.delivered*100:0,U=$.bounced/$.totalSent*100,Z=$.delivered>0?$.complained/$.delivered*100:0,z=Q*0.4+W*0.6,H=Math.max(0,100-U*10-Z*100+z*0.2),K={id:J,domain:$.domain,reputationScore:H,totalSent:$.totalSent,deliveryRate:Y,openRate:Q,clickRate:W,bounceRate:U,complaintRate:Z,engagementScore:z};return this.domainReputations.set($.domain,K),K}getDomainReputation($){return this.domainReputations.get($)}listDomainReputations(){return Array.from(this.domainReputations.values())}getWarmupPlan($){return this.warmupPlans.get($)}listWarmupPlans(){return Array.from(this.warmupPlans.values())}clear(){this.dashboards.clear(),this.warmupPlans.clear(),this.domainReputations.clear(),this.dashboardCounter=0,this.warmupCounter=0,this.domainCounter=0}}var eB=new G9;class H9{templates=new Map;versions=new Map;tests=new Map;templateCounter=0;testCounter=0;createTemplate($){let J=`template-${Date.now()}-${this.templateCounter++}`,Y=this.extractVariables($.subject+$.htmlPart+$.textPart),Q={id:J,variables:Y,createdAt:new Date,updatedAt:new Date,version:1,...$};return this.templates.set(J,Q),this.addVersion({templateId:J,version:1,subject:$.subject,htmlPart:$.htmlPart,textPart:$.textPart,createdBy:"system"}),Q}createWelcomeTemplate($){return this.createTemplate({name:$.name,subject:"Welcome to {{companyName}}!",htmlPart:`
1042
+ <html>
1043
+ <body>
1044
+ <h1>Welcome, {{userName}}!</h1>
1045
+ <p>Thank you for joining {{companyName}}. We're excited to have you on board.</p>
1046
+ <p>Your account is now active and ready to use.</p>
1047
+ <a href="{{loginUrl}}">Get Started</a>
1048
+ </body>
1049
+ </html>
1050
+ `,textPart:"Welcome, {{userName}}! Thank you for joining {{companyName}}. Visit {{loginUrl}} to get started."})}createPasswordResetTemplate($){return this.createTemplate({name:$.name,subject:"Reset your password",htmlPart:`
1051
+ <html>
1052
+ <body>
1053
+ <h1>Password Reset Request</h1>
1054
+ <p>Hi {{userName}},</p>
1055
+ <p>We received a request to reset your password for your {{companyName}} account.</p>
1056
+ <a href="{{resetUrl}}">Reset Password</a>
1057
+ <p>This link will expire in {{expirationHours}} hours.</p>
1058
+ <p>If you didn't request this, please ignore this email.</p>
1059
+ </body>
1060
+ </html>
1061
+ `,textPart:"Hi {{userName}}, reset your password at: {{resetUrl}}. This link expires in {{expirationHours}} hours."})}updateTemplate($,J,Y){let Q=this.templates.get($);if(!Q)throw Error(`Template not found: ${$}`);if(J.subject)Q.subject=J.subject;if(J.htmlPart)Q.htmlPart=J.htmlPart;if(J.textPart)Q.textPart=J.textPart;return Q.version++,Q.updatedAt=new Date,Q.variables=this.extractVariables(Q.subject+Q.htmlPart+Q.textPart),this.addVersion({templateId:$,version:Q.version,subject:Q.subject,htmlPart:Q.htmlPart,textPart:Q.textPart,createdBy:"system",changelog:Y}),Q}addVersion($){let Y={id:`version-${$.templateId}-${$.version}`,createdAt:new Date,...$},Q=this.versions.get($.templateId)||[];return Q.push(Y),this.versions.set($.templateId,Q),Y}extractVariables($){let J=/\{\{([^}]+)\}\}/g,Y=new Set,Q;while((Q=J.exec($))!==null)Y.add(Q[1].trim());return Array.from(Y)}renderTemplate($,J){let Y=this.templates.get($);if(!Y)throw Error(`Template not found: ${$}`);let Q=(W)=>{return W.replace(/\{\{([^}]+)\}\}/g,(U,Z)=>{let z=Z.trim();return J[z]!==void 0?String(J[z]):U})};return{subject:Q(Y.subject),html:Q(Y.htmlPart),text:Q(Y.textPart)}}testTemplate($,J){let Y=`test-${Date.now()}-${this.testCounter++}`,Q=this.renderTemplate($,J),W={id:Y,templateId:$,testData:J,renderedSubject:Q.subject,renderedHtml:Q.html,renderedText:Q.text,timestamp:new Date};return this.tests.set(Y,W),W}getTemplate($){return this.templates.get($)}listTemplates(){return Array.from(this.templates.values())}getTemplateVersions($){return this.versions.get($)||[]}revertToVersion($,J){let Y=this.templates.get($);if(!Y)throw Error(`Template not found: ${$}`);let W=(this.versions.get($)||[]).find((U)=>U.version===J);if(!W)throw Error(`Version ${J} not found for template ${$}`);return Y.subject=W.subject,Y.htmlPart=W.htmlPart,Y.textPart=W.textPart,Y.version++,Y.updatedAt=new Date,this.addVersion({templateId:$,version:Y.version,subject:Y.subject,htmlPart:Y.htmlPart,textPart:Y.textPart,createdBy:"system",changelog:`Reverted to version ${J}`}),Y}generateTemplateCF($){return{Type:"AWS::SES::Template",Properties:{Template:{TemplateName:$.name,SubjectPart:$.subject,HtmlPart:$.htmlPart,TextPart:$.textPart}}}}clear(){this.templates.clear(),this.versions.clear(),this.tests.clear(),this.templateCounter=0,this.testCounter=0}}var JO=new H9;class K9{static ChatbotProcessorCode=["const { DynamoDBClient, GetItemCommand, PutItemCommand, UpdateItemCommand, ScanCommand } = require('@aws-sdk/client-dynamodb');","const { BedrockRuntimeClient, InvokeModelCommand } = require('@aws-sdk/client-bedrock-runtime');","const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');","","const dynamodb = new DynamoDBClient({});","const bedrock = new BedrockRuntimeClient({});","const sns = new SNSClient({});","","const SESSIONS_TABLE = process.env.SESSIONS_TABLE;","const RULES_TABLE = process.env.RULES_TABLE;","const CHATBOT_CONFIG = JSON.parse(process.env.CHATBOT_CONFIG || '{}');","","exports.handler = async (event) => {"," console.log('Chatbot event:', JSON.stringify(event, null, 2));"," for (const record of event.Records) {"," try {"," const message = JSON.parse(record.Sns?.Message || record.body || '{}');"," const { originationNumber, messageBody } = message;"," if (!originationNumber || !messageBody) continue;"," const response = await processMessage(originationNumber, messageBody.trim());"," await sendResponse(originationNumber, response);"," } catch (error) {"," console.error('Error:', error);"," }"," }"," return { statusCode: 200 };","};","","async function processMessage(phoneNumber, message) {"," const rules = await getRules();"," const lowerMessage = message.toLowerCase();"," for (const rule of rules) {"," for (const pattern of rule.patterns) {"," if (new RegExp(pattern, 'i').test(lowerMessage)) {"," return rule.response;"," }"," }"," }"," return CHATBOT_CONFIG.fallbackMessage || 'Sorry, I did not understand. Please try again.';","}","","async function getRules() {"," const result = await dynamodb.send(new ScanCommand({ TableName: RULES_TABLE }));"," return (result.Items || []).map(item => ({"," patterns: JSON.parse(item.patterns?.S || '[]'),"," response: item.response?.S || '',"," })).sort((a, b) => (a.priority || 0) - (b.priority || 0));","}","","async function sendResponse(phoneNumber, message) {"," await sns.send(new PublishCommand({"," PhoneNumber: phoneNumber,"," Message: message.substring(0, 1600),"," MessageAttributes: {"," 'AWS.SNS.SMS.SMSType': { DataType: 'String', StringValue: 'Transactional' },"," },"," }));","}"].join(`
1062
+ `);static createSessionsTable($){return{[`${$.slug}ChatbotSessionsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-chatbot-sessions`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createRulesTable($){return{[`${$.slug}ChatbotRulesTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-chatbot-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}}static createChatbotProcessorLambda($){return{[`${$.slug}ChatbotProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-chatbot-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:K9.ChatbotProcessorCode},Environment:{Variables:{SESSIONS_TABLE:$.sessionsTable,RULES_TABLE:$.rulesTable,CHATBOT_CONFIG:JSON.stringify($.chatbotConfig),ORIGINATION_NUMBER:$.originationNumber||""}}}}}}static DefaultRules=[{id:"greeting",priority:1,patterns:["^(hi|hello|hey|howdy)$","^good (morning|afternoon|evening)"],response:"Hello! How can I help you today?"},{id:"help",priority:2,patterns:["^help$","what can you do","how does this work"],response:"I can help with: 1) Account info 2) Support 3) Hours. Reply with a number."},{id:"hours",priority:3,patterns:["hours","open","when are you"],response:"We are open Mon-Fri 9am-5pm EST. Closed weekends."},{id:"thanks",priority:4,patterns:["^(thanks|thank you|thx)"],response:"You're welcome! Is there anything else I can help with?"},{id:"bye",priority:5,patterns:["^(bye|goodbye|quit|exit|stop)$"],response:"Goodbye! Text us anytime if you need help.",action:"end"}]}class B9{queues=new Map;messageGroups=new Map;deduplicationConfigs=new Map;messages=new Map;queueCounter=0;groupCounter=0;deduplicationCounter=0;messageCounter=0;sequenceCounter=0;createFIFOQueue($){let J=`fifo-queue-${Date.now()}-${this.queueCounter++}`,Y=$.name.endsWith(".fifo")?$.name:`${$.name}.fifo`,{name:Q,...W}=$,U={id:J,name:Y,queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${Y}`,...W};return this.queues.set(J,U),this.createDeduplicationConfig({queueId:J,contentBasedDeduplication:$.contentBasedDeduplication,deduplicationInterval:300}),U}createHighThroughputFIFO($){return this.createFIFOQueue({name:$.name,contentBasedDeduplication:$.contentBasedDeduplication??!0,deduplicationScope:"messageGroup",fifoThroughputLimit:"perMessageGroupId",messageRetentionPeriod:345600,visibilityTimeout:30,receiveMessageWaitTime:0})}createStandardFIFO($){return this.createFIFOQueue({name:$.name,contentBasedDeduplication:$.contentBasedDeduplication??!1,deduplicationScope:"queue",fifoThroughputLimit:"perQueue",messageRetentionPeriod:345600,visibilityTimeout:30,receiveMessageWaitTime:0})}createDeduplicationConfig($){let Y={id:`dedup-${Date.now()}-${this.deduplicationCounter++}`,deduplicationHashes:new Map,...$};return this.deduplicationConfigs.set($.queueId,Y),Y}sendMessage($){let J=this.queues.get($.queueId);if(!J)throw Error(`Queue not found: ${$.queueId}`);let Y=this.deduplicationConfigs.get($.queueId);if(Y){let Z=$.messageDeduplicationId||(J.contentBasedDeduplication?this.generateHash($.messageBody):void 0);if(Z&&this.isDuplicate(Y,Z))return null;if(Z)Y.deduplicationHashes.set(Z,new Date)}let Q=`msg-${Date.now()}-${this.messageCounter++}`,W=this.generateSequenceNumber(),U={id:Q,messageId:Q,messageGroupId:$.messageGroupId,messageDeduplicationId:$.messageDeduplicationId,body:$.messageBody,attributes:$.messageAttributes||{},sentTimestamp:new Date,sequenceNumber:W};return this.messages.set(Q,U),this.updateMessageGroup($.queueId,$.messageGroupId),U}isDuplicate($,J){let Y=$.deduplicationHashes.get(J);if(!Y)return!1;if((Date.now()-Y.getTime())/1000>$.deduplicationInterval)return $.deduplicationHashes.delete(J),!1;return!0}generateHash($){let J=0;for(let Y=0;Y<$.length;Y++){let Q=$.charCodeAt(Y);J=(J<<5)-J+Q,J=J&J}return Math.abs(J).toString(36)}generateSequenceNumber(){return`${Date.now()}${this.sequenceCounter++}`.padStart(20,"0")}updateMessageGroup($,J){let Y=`${$}-${J}`,Q=this.messageGroups.get(Y);if(!Q)Q={id:`group-${Date.now()}-${this.groupCounter++}`,messageGroupId:J,queueId:$,messagesInFlight:0},this.messageGroups.set(Y,Q);Q.messagesInFlight++,Q.lastMessageTimestamp=new Date}getMessageGroups($){return Array.from(this.messageGroups.values()).filter((J)=>J.queueId===$)}getQueue($){return this.queues.get($)}listQueues(){return Array.from(this.queues.values())}getMessages($,J){let Y=Array.from(this.messages.values());if(J)Y=Y.filter((Q)=>Q.messageGroupId===J);return Y.sort((Q,W)=>Q.sequenceNumber.localeCompare(W.sequenceNumber))}generateFIFOQueueCF($){return{Type:"AWS::SQS::Queue",Properties:{QueueName:$.name,FifoQueue:!0,ContentBasedDeduplication:$.contentBasedDeduplication,DeduplicationScope:$.deduplicationScope,FifoThroughputLimit:$.fifoThroughputLimit,MessageRetentionPeriod:$.messageRetentionPeriod,VisibilityTimeout:$.visibilityTimeout,ReceiveMessageWaitTimeSeconds:$.receiveMessageWaitTime,...$.deadLetterTargetArn&&{RedrivePolicy:{deadLetterTargetArn:$.deadLetterTargetArn,maxReceiveCount:$.maxReceiveCount||3}}}}}clear(){this.queues.clear(),this.messageGroups.clear(),this.deduplicationConfigs.clear(),this.messages.clear(),this.queueCounter=0,this.groupCounter=0,this.deduplicationCounter=0,this.messageCounter=0,this.sequenceCounter=0}}var lO=new B9;class O9{monitors=new Map;metrics=new Map;alerts=new Map;reprocessJobs=new Map;monitorCounter=0;metricsCounter=0;alertCounter=0;jobCounter=0;createDLQMonitor($){let J=`dlq-monitor-${Date.now()}-${this.monitorCounter++}`,Y={id:J,...$};return this.monitors.set(J,Y),Y}createAutomatedMonitor($){return this.createDLQMonitor({name:$.name,queueUrl:$.queueUrl,sourceQueues:$.sourceQueues,maxReceiveCount:3,alarmThreshold:10,autoReprocess:!0,reprocessStrategy:"scheduled",notificationTopicArn:$.notificationTopicArn})}collectMetrics($){let Y={id:`metrics-${Date.now()}-${this.metricsCounter++}`,queueUrl:$,timestamp:new Date,approximateNumberOfMessages:Math.floor(Math.random()*100),approximateAgeOfOldestMessage:Math.floor(Math.random()*86400),messagesReceived:Math.floor(Math.random()*50),messagesDeleted:Math.floor(Math.random()*30),messagesReprocessed:Math.floor(Math.random()*20)},Q=this.metrics.get($)||[];return Q.push(Y),this.metrics.set($,Q),this.checkForAlerts($,Y),Y}checkForAlerts($,J){let Y=Array.from(this.monitors.values()).find((W)=>W.queueUrl===$);if(!Y)return;if(J.approximateNumberOfMessages>=Y.alarmThreshold)this.createAlert({monitorId:Y.id,alertType:"threshold_exceeded",severity:"high",message:`DLQ ${Y.name} has ${J.approximateNumberOfMessages} messages (threshold: ${Y.alarmThreshold})`});let Q=3600;if(J.approximateAgeOfOldestMessage>Q)this.createAlert({monitorId:Y.id,alertType:"old_message",severity:"medium",message:`DLQ ${Y.name} has messages older than ${Q} seconds`})}createAlert($){let J=`alert-${Date.now()}-${this.alertCounter++}`,Y={id:J,timestamp:new Date,acknowledged:!1,...$};return this.alerts.set(J,Y),Y}acknowledgeAlert($){let J=this.alerts.get($);if(!J)throw Error(`Alert not found: ${$}`);return J.acknowledged=!0,J}createReprocessJob($){let J=`reprocess-${Date.now()}-${this.jobCounter++}`,Y={id:J,queueUrl:$.queueUrl,messageId:$.messageId,attempts:0,status:"pending"};return this.reprocessJobs.set(J,Y),Y}async executeReprocessJob($){let J=this.reprocessJobs.get($);if(!J)throw Error(`Reprocess job not found: ${$}`);J.status="processing",J.startedAt=new Date,J.attempts++,await new Promise((Q)=>setTimeout(Q,100));let Y=Math.random()>0.3;if(J.status=Y?"success":"failed",J.completedAt=new Date,!Y)J.error="Reprocessing failed - original error still present";return J}async batchReprocess($){let J=[];for(let Y=0;Y<$.maxMessages;Y++){let Q=this.createReprocessJob({queueUrl:$.queueUrl,messageId:`msg-${Y}`});await this.executeReprocessJob(Q.id),J.push(Q)}return J}getDLQStatistics($,J=24){let Y=new Date(Date.now()-J*60*60*1000),Q=(this.metrics.get($)||[]).filter((B)=>B.timestamp>=Y);if(Q.length===0)return{totalMessages:0,avgAge:0,messagesReceived:0,messagesDeleted:0,messagesReprocessed:0,successRate:0};let W=Q[Q.length-1],U=Q.reduce((B,O)=>B+O.messagesReceived,0),Z=Q.reduce((B,O)=>B+O.messagesDeleted,0),z=Q.reduce((B,O)=>B+O.messagesReprocessed,0),H=Q.reduce((B,O)=>B+O.approximateAgeOfOldestMessage,0)/Q.length,K=z>0?Z/z*100:0;return{totalMessages:W.approximateNumberOfMessages,avgAge:H,messagesReceived:U,messagesDeleted:Z,messagesReprocessed:z,successRate:K}}getMonitor($){return this.monitors.get($)}listMonitors(){return Array.from(this.monitors.values())}getAlerts($,J){let Y=Array.from(this.alerts.values());if($)Y=Y.filter((Q)=>Q.monitorId===$);if(J!==void 0)Y=Y.filter((Q)=>Q.acknowledged===J);return Y.sort((Q,W)=>W.timestamp.getTime()-Q.timestamp.getTime())}getReprocessJobs($){let J=Array.from(this.reprocessJobs.values());if($)J=J.filter((Y)=>Y.queueUrl===$);return J}generateDLQAlarmCF($){return{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${$.name}-messages-alarm`,AlarmDescription:`Alert when DLQ ${$.name} exceeds threshold`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:1,Threshold:$.alarmThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:$.queueUrl.split("/").pop()}],...$.notificationTopicArn&&{AlarmActions:[$.notificationTopicArn]}}}}clear(){this.monitors.clear(),this.metrics.clear(),this.alerts.clear(),this.reprocessJobs.clear(),this.monitorCounter=0,this.metricsCounter=0,this.alertCounter=0,this.jobCounter=0}}var rO=new O9;class X9{configs=new Map;jobs=new Map;metrics=new Map;configCounter=0;jobCounter=0;metricsCounter=0;createBatchConfig($){let J=`batch-config-${Date.now()}-${this.configCounter++}`,Y={id:J,...$};return this.configs.set(J,Y),Y}createHighThroughputConfig($){return this.createBatchConfig({queueUrl:$.queueUrl,batchSize:10,maxWaitTime:100,parallelProcessors:10,retryAttempts:3,visibilityTimeout:30})}createLowLatencyConfig($){return this.createBatchConfig({queueUrl:$.queueUrl,batchSize:1,maxWaitTime:0,parallelProcessors:5,retryAttempts:2,visibilityTimeout:10})}createBatchJob($){let J=`batch-job-${Date.now()}-${this.jobCounter++}`;if(!this.configs.get($.configId))throw Error(`Batch config not found: ${$.configId}`);let Q=[];for(let U=0;U<$.messageCount;U++)Q.push({id:`msg-${J}-${U}`,messageId:`${J}-${U}`,body:`Message ${U}`,receiptHandle:`receipt-${J}-${U}`,attributes:{},status:"pending"});let W={id:J,configId:$.configId,messages:Q,status:"pending",processedCount:0,failedCount:0};return this.jobs.set(J,W),W}async processBatchJob($){let J=this.jobs.get($);if(!J)throw Error(`Batch job not found: ${$}`);let Y=this.configs.get(J.configId);if(!Y)throw Error(`Batch config not found: ${J.configId}`);J.status="processing",J.startedAt=new Date;let Q=this.chunkArray(J.messages,Y.batchSize);for(let W of Q)await this.processBatch(W,Y);return J.processedCount=J.messages.filter((W)=>W.status==="success").length,J.failedCount=J.messages.filter((W)=>W.status==="failed").length,J.status=J.failedCount===0?"completed":"failed",J.completedAt=new Date,this.collectProcessorMetrics(Y.id,J),J}async processBatch($,J){let Y=$.map((Q)=>this.processMessage(Q,J));await Promise.all(Y)}async processMessage($,J){$.status="processing";let Y=Date.now();await new Promise((U)=>setTimeout(U,Math.random()*100));let Q=Date.now()-Y;if($.processingTime=Q,Math.random()>0.1)$.status="success";else $.status="failed",$.error="Processing error"}chunkArray($,J){let Y=[];for(let Q=0;Q<$.length;Q+=J)Y.push($.slice(Q,Q+J));return Y}collectProcessorMetrics($,J){let Y=`metrics-${Date.now()}-${this.metricsCounter++}`,W=J.messages.filter((O)=>O.status==="success").map((O)=>O.processingTime||0).filter((O)=>O>0),U=W.length>0?W.reduce((O,X)=>O+X,0)/W.length:0,Z=J.completedAt&&J.startedAt?(J.completedAt.getTime()-J.startedAt.getTime())/1000:1,z=J.processedCount/Z,H=J.messages.length>0?J.failedCount/J.messages.length*100:0,K={id:Y,configId:$,timestamp:new Date,messagesProcessed:J.processedCount,averageProcessingTime:U,throughput:z,errorRate:H},B=this.metrics.get($)||[];B.push(K),this.metrics.set($,B)}getBatchStatistics($){let J=this.metrics.get($)||[];if(J.length===0)return{totalJobsProcessed:0,totalMessagesProcessed:0,averageThroughput:0,averageErrorRate:0,averageProcessingTime:0};let Y=J.reduce((Z,z)=>Z+z.messagesProcessed,0),Q=J.reduce((Z,z)=>Z+z.throughput,0)/J.length,W=J.reduce((Z,z)=>Z+z.errorRate,0)/J.length,U=J.reduce((Z,z)=>Z+z.averageProcessingTime,0)/J.length;return{totalJobsProcessed:J.length,totalMessagesProcessed:Y,averageThroughput:Q,averageErrorRate:W,averageProcessingTime:U}}optimizeBatchConfig($){let J=this.configs.get($);if(!J)throw Error(`Batch config not found: ${$}`);let Y=this.getBatchStatistics($);if(Y.averageErrorRate<5&&J.batchSize<10)J.batchSize=Math.min(10,J.batchSize+1);if(Y.averageErrorRate>20&&J.batchSize>1)J.batchSize=Math.max(1,J.batchSize-1);if(Y.averageThroughput<5&&J.parallelProcessors<20)J.parallelProcessors++;return J}getConfig($){return this.configs.get($)}listConfigs(){return Array.from(this.configs.values())}getJob($){return this.jobs.get($)}listJobs($){let J=Array.from(this.jobs.values());if($)J=J.filter((Y)=>Y.configId===$);return J}generateBatchProcessorCF($){return{Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:`arn:aws:sqs:us-east-1:123456789012:${$.queueUrl.split("/").pop()}`,FunctionName:"batch-processor-function",BatchSize:$.batchSize,MaximumBatchingWindowInSeconds:$.maxWaitTime/1000,FunctionResponseTypes:["ReportBatchItemFailures"]}}}clear(){this.configs.clear(),this.jobs.clear(),this.metrics.clear(),this.configCounter=0,this.jobCounter=0,this.metricsCounter=0}}var nO=new X9;class j9{queues=new Map;retentionPolicies=new Map;delayQueues=new Map;purgeOperations=new Map;metrics=new Map;queueCounter=0;retentionCounter=0;delayCounter=0;purgeCounter=0;metricsCounter=0;createQueue($){let J=`queue-${Date.now()}-${this.queueCounter++}`,Y={id:J,purgeInProgress:!1,...$};return this.queues.set(J,Y),Y}createStandardQueue($){return this.createQueue({queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${$.queueName}`,queueName:$.queueName,messageRetentionPeriod:($.messageRetentionDays||4)*24*60*60,delaySeconds:0,maximumMessageSize:262144,receiveMessageWaitTime:0})}createLongPollingQueue($){return this.createQueue({queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${$.queueName}`,queueName:$.queueName,messageRetentionPeriod:345600,delaySeconds:0,maximumMessageSize:262144,receiveMessageWaitTime:$.waitTimeSeconds||20})}createRetentionPolicy($){let J=`retention-${Date.now()}-${this.retentionCounter++}`,Y={id:J,...$};this.retentionPolicies.set(J,Y);let Q=this.queues.get($.queueId);if(Q)Q.messageRetentionPeriod=$.retentionPeriod;return Y}createShortRetentionPolicy($){return this.createRetentionPolicy({queueId:$.queueId,retentionPeriod:$.retentionHours*60*60,autoCleanup:!0,archiveExpiredMessages:!1})}createArchivalRetentionPolicy($){return this.createRetentionPolicy({queueId:$.queueId,retentionPeriod:$.retentionDays*24*60*60,autoCleanup:!0,cleanupSchedule:"cron(0 0 * * ? *)",archiveExpiredMessages:!0,archiveS3Bucket:$.s3Bucket})}createDelayQueue($){let J=`delay-${Date.now()}-${this.delayCounter++}`,Y={id:J,...$};this.delayQueues.set(J,Y);let Q=Array.from(this.queues.values()).find((W)=>W.queueUrl===$.queueUrl);if(Q)Q.delaySeconds=$.defaultDelay;return Y}createScheduledDelayQueue($){return this.createDelayQueue({queueUrl:$.queueUrl,defaultDelay:$.delayMinutes*60,perMessageDelay:!1,maxDelay:900})}async purgeQueue($){let J=this.queues.get($);if(!J)throw Error(`Queue not found: ${$}`);if(J.purgeInProgress)throw Error("Purge already in progress for this queue");let Y=`purge-${Date.now()}-${this.purgeCounter++}`,Q={id:Y,queueUrl:J.queueUrl,status:"in_progress",startedAt:new Date};return this.purgeOperations.set(Y,Q),J.purgeInProgress=!0,setTimeout(()=>{Q.status="completed",Q.completedAt=new Date,Q.messagesPurged=Math.floor(Math.random()*1000),J.purgeInProgress=!1},100),Q}collectQueueMetrics($){let Y={id:`metrics-${Date.now()}-${this.metricsCounter++}`,queueUrl:$,timestamp:new Date,approximateNumberOfMessages:Math.floor(Math.random()*1000),approximateNumberOfMessagesNotVisible:Math.floor(Math.random()*100),approximateNumberOfMessagesDelayed:Math.floor(Math.random()*50),oldestMessageAge:Math.floor(Math.random()*86400)},Q=this.metrics.get($)||[];return Q.push(Y),this.metrics.set($,Q),Y}getQueueHealth($){let J=this.metrics.get($)||[];if(J.length===0)return{status:"healthy",issues:[],recommendations:[]};let Y=J[J.length-1],Q=[],W=[],U="healthy";if(Y.approximateNumberOfMessages>1e4)U="critical",Q.push("Large message backlog detected"),W.push("Increase consumer capacity");else if(Y.approximateNumberOfMessages>1000)U="warning",Q.push("Growing message backlog"),W.push("Monitor consumer performance");if(Y.oldestMessageAge&&Y.oldestMessageAge>3600){if(U!=="critical")U="warning";Q.push("Old messages in queue"),W.push("Review message processing")}if(Y.approximateNumberOfMessagesDelayed>100){if(U!=="critical")U="warning";Q.push("High number of delayed messages")}return{status:U,issues:Q,recommendations:W}}getQueue($){return this.queues.get($)}listQueues(){return Array.from(this.queues.values())}getRetentionPolicy($){return this.retentionPolicies.get($)}listRetentionPolicies(){return Array.from(this.retentionPolicies.values())}getPurgeOperations($){let J=Array.from(this.purgeOperations.values());if($)J=J.filter((Y)=>Y.queueUrl===$);return J}generateQueueCF($){return{Type:"AWS::SQS::Queue",Properties:{QueueName:$.queueName,MessageRetentionPeriod:$.messageRetentionPeriod,DelaySeconds:$.delaySeconds,MaximumMessageSize:$.maximumMessageSize,ReceiveMessageWaitTimeSeconds:$.receiveMessageWaitTime}}}generateCleanupRuleCF($){return{Type:"AWS::Events::Rule",Properties:{Name:`${$.id}-cleanup`,Description:"Automated queue cleanup",ScheduleExpression:$.cleanupSchedule||"cron(0 0 * * ? *)",State:"ENABLED",Targets:[{Arn:"arn:aws:lambda:us-east-1:123456789012:function:queue-cleanup",Id:$.id,Input:JSON.stringify({queueId:$.queueId,archiveBucket:$.archiveS3Bucket})}]}}}clear(){this.queues.clear(),this.retentionPolicies.clear(),this.delayQueues.clear(),this.purgeOperations.clear(),this.metrics.clear(),this.queueCounter=0,this.retentionCounter=0,this.delayCounter=0,this.purgeCounter=0,this.metricsCounter=0}}var iO=new j9;class q9{optimizations=new Map;imageConfigs=new Map;ssgConfigs=new Map;prerenderConfigs=new Map;counter=0;createAssetOptimization($){let J=`asset-opt-${Date.now()}-${this.counter++}`,Y={id:J,...$};return this.optimizations.set(J,Y),Y}createImageOptimization($){let J=`image-opt-${Date.now()}-${this.counter++}`,Y={id:J,...$};return this.imageConfigs.set(J,Y),Y}createSSGConfig($){let J=`ssg-${Date.now()}-${this.counter++}`,Y={id:J,...$};return this.ssgConfigs.set(J,Y),Y}createPrerenderConfig($){let J=`prerender-${Date.now()}-${this.counter++}`,Y={id:J,...$};return this.prerenderConfigs.set(J,Y),Y}listOptimizations(){return Array.from(this.optimizations.values())}listImageConfigs(){return Array.from(this.imageConfigs.values())}clear(){this.optimizations.clear(),this.imageConfigs.clear(),this.ssgConfigs.clear(),this.prerenderConfigs.clear()}}var QX=new q9;class Q6{policies=new Map;versioningConfigs=new Map;replicationRules=new Map;tieringConfigs=new Map;objectLocks=new Map;transferAcceleration=new Map;accessPoints=new Map;glacierConfigs=new Map;inventories=new Map;batchOps=new Map;eventNotifications=new Map;counter=0;createLifecyclePolicy($,J){let Y=`lifecycle-${Date.now()}-${this.counter++}`,Q={id:Y,transitions:$,expiration:J};return this.policies.set(Y,Q),Q}enableVersioning($=!1){let J=`versioning-${Date.now()}-${this.counter++}`,Y={id:J,enabled:!0,mfaDelete:$};return this.versioningConfigs.set(J,Y),Y}createReplicationRule($,J,Y){let Q=`replication-${Date.now()}-${this.counter++}`,W={id:Q,sourceRegion:$,destRegion:J,destBucket:Y};return this.replicationRules.set(Q,W),W}createIntelligentTiering($,J){let Y=`tiering-${Date.now()}-${this.counter++}`,Q={id:Y,archiveDays:$,deepArchiveDays:J};return this.tieringConfigs.set(Y,Q),Q}enableObjectLock($){let J=`object-lock-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$.bucketName,mode:$.mode||"COMPLIANCE",retentionDays:$.retentionDays,retentionYears:$.retentionYears,legalHoldEnabled:$.legalHoldEnabled||!1};return this.objectLocks.set(J,Y),Y}enableTransferAcceleration($){let J=`transfer-accel-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$,enabled:!0,endpoint:`${$}.s3-accelerate.amazonaws.com`};return this.transferAcceleration.set(J,Y),Y}createAccessPoint($){let J=`access-point-${Date.now()}-${this.counter++}`,Y={id:J,name:$.name,bucketName:$.bucketName,vpcId:$.vpcId,publicAccessBlock:$.publicAccessBlock!==!1,policy:$.policy};return this.accessPoints.set(J,Y),Y}createGlacierArchive($){let J=`glacier-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$.bucketName,archiveType:$.archiveType,transitionDays:$.transitionDays,restoreConfig:$.restoreTier?{tier:$.restoreTier,days:$.restoreDays||7}:void 0};return this.glacierConfigs.set(J,Y),Y}createInventory($){let J=`inventory-${Date.now()}-${this.counter++}`,Y={id:J,sourceBucket:$.sourceBucket,destinationBucket:$.destinationBucket,schedule:$.schedule||"Daily",format:$.format||"CSV",includedFields:$.includedFields||["Size","LastModifiedDate","StorageClass","ETag"],prefix:$.prefix};return this.inventories.set(J,Y),Y}createBatchOperation($){let J=`batch-op-${Date.now()}-${this.counter++}`,Y={id:J,operation:$.operation,manifestBucket:$.manifestBucket,manifestKey:$.manifestKey,priority:$.priority||10,status:"pending"};return this.batchOps.set(J,Y),Y}executeBatchOperation($){let J=this.batchOps.get($);if(!J)throw Error(`Batch operation not found: ${$}`);return J.status="in_progress",J.totalObjects=1000,J.processedObjects=0,J}getBatchOperationStatus($){return this.batchOps.get($)}createLambdaNotification($){let J=`event-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$.bucketName,events:$.events,destination:{type:"Lambda",arn:$.lambdaArn},filter:$.prefix||$.suffix?{prefix:$.prefix,suffix:$.suffix}:void 0};return this.eventNotifications.set(J,Y),Y}createSQSNotification($){let J=`event-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$.bucketName,events:$.events,destination:{type:"SQS",arn:$.queueArn},filter:$.prefix||$.suffix?{prefix:$.prefix,suffix:$.suffix}:void 0};return this.eventNotifications.set(J,Y),Y}createSNSNotification($){let J=`event-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$.bucketName,events:$.events,destination:{type:"SNS",arn:$.topicArn},filter:$.prefix||$.suffix?{prefix:$.prefix,suffix:$.suffix}:void 0};return this.eventNotifications.set(J,Y),Y}generateObjectLockCF($){let J={ObjectLockEnabled:"Enabled",ObjectLockConfiguration:{ObjectLockEnabled:"Enabled",Rule:{DefaultRetention:{Mode:$.mode}}}};if($.retentionDays)J.ObjectLockConfiguration.Rule.DefaultRetention.Days=$.retentionDays;if($.retentionYears)J.ObjectLockConfiguration.Rule.DefaultRetention.Years=$.retentionYears;return J}generateTransferAccelerationCF($){return{AccelerateConfiguration:{AccelerationStatus:$.enabled?"Enabled":"Suspended"}}}generateAccessPointCF($){return{Type:"AWS::S3::AccessPoint",Properties:{Name:$.name,Bucket:$.bucketName,...$.vpcId&&{VpcConfiguration:{VpcId:$.vpcId}},PublicAccessBlockConfiguration:$.publicAccessBlock?{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}:void 0,...$.policy&&{Policy:$.policy}}}}generateInventoryCF($){return{Type:"AWS::S3::Bucket",Properties:{InventoryConfigurations:[{Id:$.id,Destination:{BucketArn:`arn:aws:s3:::${$.destinationBucket}`,Format:$.format},Enabled:!0,IncludedObjectVersions:"Current",OptionalFields:$.includedFields,ScheduleFrequency:$.schedule,...$.prefix&&{Prefix:$.prefix}}]}}}generateEventNotificationCF($){let J=$.destination.type==="Lambda"?"LambdaConfigurations":$.destination.type==="SQS"?"QueueConfigurations":"TopicConfigurations",Y=$.destination.type==="Lambda"?"Function":$.destination.type==="SQS"?"Queue":"Topic",Q={Event:$.events[0],[Y]:$.destination.arn};if($.filter)Q.Filter={S3Key:{Rules:[...$.filter.prefix?[{Name:"prefix",Value:$.filter.prefix}]:[],...$.filter.suffix?[{Name:"suffix",Value:$.filter.suffix}]:[]]}};return{NotificationConfiguration:{[J]:[Q]}}}clear(){this.policies.clear(),this.versioningConfigs.clear(),this.replicationRules.clear(),this.tieringConfigs.clear(),this.objectLocks.clear(),this.transferAcceleration.clear(),this.accessPoints.clear(),this.glacierConfigs.clear(),this.inventories.clear(),this.batchOps.clear(),this.eventNotifications.clear()}}var ZW=new Q6;class V9{checks=new Map;synthetics=new Map;uptimeTrackers=new Map;counter=0;createHealthCheck($,J=30,Y=10){let Q=`health-${Date.now()}-${this.counter++}`,W={id:Q,url:$,interval:J,timeout:Y,status:"healthy"};return this.checks.set(Q,W),W}createSyntheticMonitor($,J,Y,Q){let W=`synthetic-${Date.now()}-${this.counter++}`,U={id:W,name:$,script:J,frequency:Y,locations:Q};return this.synthetics.set(W,U),U}trackUptime($,J,Y){let Q=`uptime-${Date.now()}-${this.counter++}`,W=J/(J+Y)*100,U={id:Q,resource:$,uptime:J,downtime:Y,availability:W};return this.uptimeTrackers.set(Q,U),U}clear(){this.checks.clear(),this.synthetics.clear(),this.uptimeTrackers.clear()}}var ZX=new V9;class M9{wafRules=new Map;shieldProtections=new Map;securityGroups=new Map;nacls=new Map;counter=0;createWAFRule($,J,Y,Q){let W=`waf-${Date.now()}-${this.counter++}`,U={id:W,name:$,priority:J,action:Y,conditions:Q};return this.wafRules.set(W,U),U}enableShield($,J="standard"){let Y=`shield-${Date.now()}-${this.counter++}`,Q={id:Y,resourceArn:$,protectionType:J};return this.shieldProtections.set(Y,Q),Q}createSecurityGroup($,J,Y){let Q=`sg-${Date.now()}-${this.counter++}`,W={id:Q,name:$,vpcId:J,rules:Y};return this.securityGroups.set(Q,W),W}createNACL($,J){let Y=`nacl-${Date.now()}-${this.counter++}`,Q={id:Y,vpcId:$,rules:J};return this.nacls.set(Y,Q),Q}clear(){this.wafRules.clear(),this.shieldProtections.clear(),this.securityGroups.clear(),this.nacls.clear()}}var GX=new M9;class E9{strategies=new Map;allocations=new Map;groups=new Map;counter=0;createTaggingStrategy($,J){let Y=`tagging-${Date.now()}-${this.counter++}`,Q={id:Y,tags:$,resources:J};return this.strategies.set(Y,Q),Q}createCostAllocation($,J){let Y=`cost-${Date.now()}-${this.counter++}`,Q={id:Y,tagKey:$,allocations:J};return this.allocations.set(Y,Q),Q}createResourceGroup($,J,Y){let Q=`group-${Date.now()}-${this.counter++}`,W={id:Q,name:$,query:{resourceTypeFilters:J,tagFilters:Y}};return this.groups.set(Q,W),W}clear(){this.strategies.clear(),this.allocations.clear(),this.groups.clear()}}var KX=new E9;class g0{builder;config;environment;mergedConfig;constructor($){this.config=$.config,this.environment=$.environment,this.builder=new yJ(`${this.config.project.name} - ${this.environment}`),this.mergedConfig=this.mergeEnvironmentConfig()}mergeEnvironmentConfig(){let J=this.config.environments[this.environment]?.infrastructure;if(!J)return this.config;return{...this.config,infrastructure:{...this.config.infrastructure,...J,storage:{...this.config.infrastructure?.storage,...J.storage},functions:{...this.config.infrastructure?.functions,...J.functions},servers:{...this.config.infrastructure?.servers,...J.servers},databases:{...this.config.infrastructure?.databases,...J.databases},cdn:{...this.config.infrastructure?.cdn,...J.cdn},queues:{...this.config.infrastructure?.queues,...J.queues},realtime:{...this.config.infrastructure?.realtime,...J.realtime}}}}shouldDeploy($){if($.environments&&!$.environments.includes(this.environment))return!1;if($.requiresFeatures){let J=this.config.features||{};if(!$.requiresFeatures.every((Q)=>J[Q]===!0))return!1}if($.regions){let J=this.config.environments[this.environment]?.region||this.config.project.region;if(!$.regions.includes(J))return!1}if($.condition&&typeof $.condition==="function")return $.condition(this.config,this.environment);return!0}generate(){let $=this.mergedConfig.project.slug,J=this.environment,Y=!!(this.mergedConfig.infrastructure?.functions||this.mergedConfig.infrastructure?.api),Q=!!this.mergedConfig.infrastructure?.servers;if(Y)this.generateServerless($,J);if(Q)this.generateServer($,J);if(this.generateSharedInfrastructure($,J),this.config.tags)this.applyGlobalTags(this.config.tags);return this}applyGlobalTags($){}generateServerless($,J){if(this.mergedConfig.infrastructure?.functions)for(let[Y,Q]of Object.entries(this.mergedConfig.infrastructure.functions)){if(!this.shouldDeploy(Q))continue;let{role:W,logicalId:U}=d$.createRole({slug:$,environment:J,roleName:`${$}-${J}-${Y}-role`,servicePrincipal:"lambda.amazonaws.com",managedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]});this.builder.addResource(U,W);let{lambdaFunction:Z,logicalId:z}=a.createLambdaFunction({slug:$,environment:J,functionName:`${$}-${J}-${Y}`,handler:Q.handler||"index.handler",runtime:Q.runtime||"nodejs20.x",code:{zipFile:Q.code||"export const handler = async () => ({ statusCode: 200 });"},role:U,timeout:Q.timeout,memorySize:Q.memorySize});this.builder.addResource(z,Z)}if(this.config.infrastructure?.api){let{restApi:Y,logicalId:Q}=vJ.createRestApi({slug:$,environment:J,apiName:`${$}-${J}-api`});this.builder.addResource(Q,Y)}}generateServer($,J){if(this.config.infrastructure?.servers)for(let[Y,Q]of Object.entries(this.config.infrastructure.servers)){let{instance:W,logicalId:U}=a.createServer({slug:$,environment:J,instanceType:Q.size||"t3.micro",imageId:Q.image||"ami-0c55b159cbfafe1f0",userData:Q.startupScript});this.builder.addResource(U,W)}}generateSharedInfrastructure($,J){if(this.config.infrastructure?.storage)for(let[Y,Q]of Object.entries(this.config.infrastructure.storage)){let{bucket:W,logicalId:U}=o$.createBucket({slug:$,environment:J,bucketName:`${$}-${J}-${Y}`,versioning:Q.versioning,encryption:Q.encryption});if(this.builder.addResource(U,W),Q.website){let Z=typeof Q.website==="object"?Q.website:{},z=o$.enableWebsiteHosting(W,Z.indexDocument||"index.html",Z.errorDocument);this.builder.addResource(U,z)}}if(this.config.infrastructure?.databases){for(let[Y,Q]of Object.entries(this.config.infrastructure.databases))if(Q.engine==="dynamodb"){let{table:W,logicalId:U}=A0.createTable({slug:$,environment:J,tableName:`${$}-${J}-${Y}`,partitionKey:Q.partitionKey||{name:"id",type:"S"},sortKey:Q.sortKey});this.builder.addResource(U,W)}else if(Q.engine==="postgres"){let{dbInstance:W,logicalId:U}=A0.createPostgres({slug:$,environment:J,dbInstanceIdentifier:`${$}-${J}-${Y}`,masterUsername:Q.username||"admin",masterUserPassword:Q.password||"changeme123",allocatedStorage:Q.storage||20,dbInstanceClass:Q.instanceClass||"db.t3.micro"});this.builder.addResource(U,W)}else if(Q.engine==="mysql"){let{dbInstance:W,logicalId:U}=A0.createMysql({slug:$,environment:J,dbInstanceIdentifier:`${$}-${J}-${Y}`,masterUsername:Q.username||"admin",masterUserPassword:Q.password||"changeme123",allocatedStorage:Q.storage||20,dbInstanceClass:Q.instanceClass||"db.t3.micro"});this.builder.addResource(U,W)}}if(this.config.infrastructure?.cdn)for(let[Y,Q]of Object.entries(this.config.infrastructure.cdn)){let{distribution:W,logicalId:U}=u$.createDistribution({slug:$,environment:J,origin:{domainName:Q.origin,originId:`${$}-origin`}});this.builder.addResource(U,W)}if(this.mergedConfig.infrastructure?.queues)for(let[Y,Q]of Object.entries(this.mergedConfig.infrastructure.queues)){if(!this.shouldDeploy(Q))continue;let{queue:W,logicalId:U}=x$.createQueue({slug:$,environment:J,name:`${$}-${J}-${Y}`,fifo:Q.fifo,visibilityTimeout:Q.visibilityTimeout,messageRetentionPeriod:Q.messageRetentionPeriod,delaySeconds:Q.delaySeconds,maxMessageSize:Q.maxMessageSize,receiveMessageWaitTime:Q.receiveMessageWaitTime,contentBasedDeduplication:Q.contentBasedDeduplication,encrypted:Q.encrypted,kmsKeyId:Q.kmsKeyId});this.builder.addResource(U,W);let Z;if(Q.deadLetterQueue){let{deadLetterQueue:z,updatedSourceQueue:H,deadLetterLogicalId:K}=x$.createDeadLetterQueue(U,{slug:$,environment:J,maxReceiveCount:Q.maxReceiveCount});Z=K,this.builder.addResource(K,z);let O=this.builder.getResources()[U];if(O?.Properties)O.Properties.RedrivePolicy=H.Properties?.RedrivePolicy}if(Q.trigger){let z=Q.trigger,H=`${$}${J}${z.functionName}`.replace(/[^a-zA-Z0-9]/g,""),K={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:{"Fn::GetAtt":[U,"Arn"]},FunctionName:{Ref:H},BatchSize:z.batchSize||10,MaximumBatchingWindowInSeconds:z.batchWindow||0,Enabled:!0,...z.reportBatchItemFailures!==!1&&{FunctionResponseTypes:["ReportBatchItemFailures"]},...z.maxConcurrency&&{ScalingConfig:{MaximumConcurrency:z.maxConcurrency}},...z.filterPattern&&{FilterCriteria:{Filters:[{Pattern:JSON.stringify(z.filterPattern)}]}}},DependsOn:[U,H]};this.builder.addResource(`${U}Trigger`,K)}if(Q.alarms?.enabled){let z=Q.alarms,H=z.notificationTopicArn;if(!H&&z.notificationEmails?.length){let O=`${U}AlarmTopic`;this.builder.addResource(O,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${$}-${J}-${Y}-alarms`,DisplayName:`${Y} Queue Alarms`}}),z.notificationEmails.forEach((X,j)=>{this.builder.addResource(`${O}Sub${j}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:O},Protocol:"email",Endpoint:X}})}),H={Ref:O}}let K=z.queueDepthThreshold||1000;this.builder.addResource(`${U}DepthAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${$}-${J}-${Y}-queue-depth`,AlarmDescription:`Queue ${Y} depth exceeds ${K} messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:K,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[U,"QueueName"]}}],...H&&{AlarmActions:[H],OKActions:[H]}}});let B=z.messageAgeThreshold||3600;if(this.builder.addResource(`${U}AgeAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${$}-${J}-${Y}-message-age`,AlarmDescription:`Queue ${Y} oldest message exceeds ${B} seconds`,MetricName:"ApproximateAgeOfOldestMessage",Namespace:"AWS/SQS",Statistic:"Maximum",Period:300,EvaluationPeriods:2,Threshold:B,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[U,"QueueName"]}}],...H&&{AlarmActions:[H],OKActions:[H]}}}),Z&&z.dlqAlarm!==!1)this.builder.addResource(`${Z}Alarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${$}-${J}-${Y}-dlq-messages`,AlarmDescription:`Dead letter queue for ${Y} has messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Sum",Period:300,EvaluationPeriods:1,Threshold:0,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[Z,"QueueName"]}}],...H&&{AlarmActions:[H]}}})}if(Q.subscribe){let z=Q.subscribe,H=z.topicArn;if(!H&&z.topicName)H={Ref:z.topicName};if(H){this.builder.addResource(`${U}SnsPolicy`,{Type:"AWS::SQS::QueuePolicy",Properties:{Queues:[{Ref:U}],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"sns.amazonaws.com"},Action:"sqs:SendMessage",Resource:{"Fn::GetAtt":[U,"Arn"]},Condition:{ArnEquals:{"aws:SourceArn":H}}}]}}});let K={TopicArn:H,Protocol:"sqs",Endpoint:{"Fn::GetAtt":[U,"Arn"]},RawMessageDelivery:z.rawMessageDelivery||!1};if(z.filterPolicy)K.FilterPolicy=z.filterPolicy,K.FilterPolicyScope=z.filterPolicyScope||"MessageAttributes";this.builder.addResource(`${U}SnsSub`,{Type:"AWS::SNS::Subscription",Properties:K,DependsOn:`${U}SnsPolicy`})}}}if(this.mergedConfig.infrastructure?.realtime?.enabled)if((this.mergedConfig.infrastructure.realtime.mode||"serverless")==="server")this.generateRealtimeServerResources($,J);else this.generateRealtimeResources($,J);if(this.config.infrastructure?.monitoring?.alarms)for(let[Y,Q]of Object.entries(this.config.infrastructure.monitoring.alarms)){let{alarm:W,logicalId:U}=y1.createAlarm({slug:$,environment:J,alarmName:`${$}-${J}-${Y}`,metricName:Q.metricName||"Errors",namespace:Q.namespace||"AWS/Lambda",threshold:Q.threshold||1,comparisonOperator:Q.comparisonOperator||"GreaterThanThreshold"});this.builder.addResource(U,W)}}generateRealtimeResources($,J){let Y=this.mergedConfig.infrastructure?.realtime;if(!Y)return;let Q=Y.name||`${$}-${J}-realtime`,W=Y.scaling||{},U=Y.storage||{type:"dynamodb"},Z=W.handlerMemory||256,z=W.handlerTimeout||30,H=`${$}${J}RealtimeConnections`.replace(/[^a-zA-Z0-9]/g,""),K=`${$}${J}RealtimeChannels`.replace(/[^a-zA-Z0-9]/g,"");if(U.type==="dynamodb"){let D=U.dynamodb||{},k=D.billingMode||"PAY_PER_REQUEST";this.builder.addResource(H,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$}-${J}-realtime-connections`,BillingMode:k,AttributeDefinitions:[{AttributeName:"connectionId",AttributeType:"S"},{AttributeName:"userId",AttributeType:"S"}],KeySchema:[{AttributeName:"connectionId",KeyType:"HASH"}],GlobalSecondaryIndexes:[{IndexName:"userId-index",KeySchema:[{AttributeName:"userId",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"},...k==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:D.readCapacity||5,WriteCapacityUnits:D.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...k==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:D.readCapacity||5,WriteCapacityUnits:D.writeCapacity||5}},...D.pointInTimeRecovery&&{PointInTimeRecoverySpecification:{PointInTimeRecoveryEnabled:!0}},Tags:[{Key:"Name",Value:`${$}-${J}-realtime-connections`},{Key:"Environment",Value:J}]}}),this.builder.addResource(K,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$}-${J}-realtime-channels`,BillingMode:k,AttributeDefinitions:[{AttributeName:"channel",AttributeType:"S"},{AttributeName:"connectionId",AttributeType:"S"}],KeySchema:[{AttributeName:"channel",KeyType:"HASH"},{AttributeName:"connectionId",KeyType:"RANGE"}],GlobalSecondaryIndexes:[{IndexName:"connectionId-index",KeySchema:[{AttributeName:"connectionId",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"},...k==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:D.readCapacity||5,WriteCapacityUnits:D.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...k==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:D.readCapacity||5,WriteCapacityUnits:D.writeCapacity||5}},Tags:[{Key:"Name",Value:`${$}-${J}-realtime-channels`},{Key:"Environment",Value:J}]}})}let B=`${$}${J}RealtimeRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(B,{Type:"AWS::IAM::Role",Properties:{RoleName:`${$}-${J}-realtime-handler-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Policies:[{PolicyName:"RealtimeHandlerPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:UpdateItem"],Resource:[{"Fn::GetAtt":[H,"Arn"]},{"Fn::Sub":`\${${H}.Arn}/index/*`},{"Fn::GetAtt":[K,"Arn"]},{"Fn::Sub":`\${${K}.Arn}/index/*`}]},{Effect:"Allow",Action:"execute-api:ManageConnections",Resource:{"Fn::Sub":"arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:*/*"}}]}}]}});let O=`${$}${J}RealtimeConnect`.replace(/[^a-zA-Z0-9]/g,""),X=`${$}${J}RealtimeDisconnect`.replace(/[^a-zA-Z0-9]/g,""),j=`${$}${J}RealtimeMessage`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(O,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$}-${J}-realtime-connect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[B,"Arn"]},MemorySize:Z,Timeout:z,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:H},CHANNELS_TABLE:{Ref:K},ENVIRONMENT:J}},Code:{ZipFile:this.generateConnectHandlerCode()}},DependsOn:[B,H]}),this.builder.addResource(X,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$}-${J}-realtime-disconnect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[B,"Arn"]},MemorySize:Z,Timeout:z,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:H},CHANNELS_TABLE:{Ref:K},ENVIRONMENT:J}},Code:{ZipFile:this.generateDisconnectHandlerCode()}},DependsOn:[B,H,K]}),this.builder.addResource(j,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$}-${J}-realtime-message`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[B,"Arn"]},MemorySize:Z,Timeout:z,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:H},CHANNELS_TABLE:{Ref:K},ENVIRONMENT:J}},Code:{ZipFile:this.generateMessageHandlerCode()}},DependsOn:[B,H,K]});let q=`${$}${J}RealtimeApi`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(q,{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:Q,ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action",Tags:{Name:Q,Environment:J}}});let E=`${O}Permission`,F=`${X}Permission`,w=`${j}Permission`;this.builder.addResource(E,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:O},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${q}}/*/$connect`}}}),this.builder.addResource(F,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:X},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${q}}/*/$disconnect`}}}),this.builder.addResource(w,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:j},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${q}}/*/$default`}}});let T=`${q}ConnectInteg`,S=`${q}DisconnectInteg`,R=`${q}MessageInteg`;this.builder.addResource(T,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:q},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${O}.Arn}/invocations`}}}),this.builder.addResource(S,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:q},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${X}.Arn}/invocations`}}}),this.builder.addResource(R,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:q},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${j}.Arn}/invocations`}}}),this.builder.addResource(`${q}ConnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:q},RouteKey:"$connect",AuthorizationType:"NONE",Target:{"Fn::Sub":`integrations/\${${T}}`}}}),this.builder.addResource(`${q}DisconnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:q},RouteKey:"$disconnect",Target:{"Fn::Sub":`integrations/\${${S}}`}}}),this.builder.addResource(`${q}DefaultRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:q},RouteKey:"$default",Target:{"Fn::Sub":`integrations/\${${R}}`}}});let C=`${q}Stage`;if(this.builder.addResource(C,{Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:{Ref:q},StageName:J,AutoDeploy:!0,DefaultRouteSettings:{ThrottlingBurstLimit:W.messagesPerSecond||1000,ThrottlingRateLimit:W.messagesPerSecond||1000}}}),Y.monitoring?.enabled){let D=Y.monitoring,k=D.notificationTopicArn;if(!k&&D.notificationEmails?.length){let u=`${q}AlarmTopic`;this.builder.addResource(u,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${$}-${J}-realtime-alarms`,DisplayName:"Realtime WebSocket Alarms"}}),D.notificationEmails.forEach((b,v)=>{this.builder.addResource(`${u}Sub${v}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:u},Protocol:"email",Endpoint:b}})}),k={Ref:u}}if(D.connectionThreshold)this.builder.addResource(`${q}ConnectionAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${$}-${J}-realtime-connections`,AlarmDescription:`WebSocket connections exceed ${D.connectionThreshold}`,MetricName:"ConnectCount",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:300,EvaluationPeriods:2,Threshold:D.connectionThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:q}}],...k&&{AlarmActions:[k]}}});if(D.errorThreshold)this.builder.addResource(`${q}ErrorAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${$}-${J}-realtime-errors`,AlarmDescription:`WebSocket errors exceed ${D.errorThreshold}/min`,MetricName:"ExecutionError",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:60,EvaluationPeriods:3,Threshold:D.errorThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:q}}],...k&&{AlarmActions:[k]}}})}this.builder.addOutput(`${q}Endpoint`,{Description:"WebSocket API endpoint URL",Value:{"Fn::Sub":`wss://\${${q}}.execute-api.\${AWS::Region}.amazonaws.com/${J}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}}),this.builder.addOutput(`${q}Id`,{Description:"WebSocket API ID",Value:{Ref:q},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-api-id"}}})}generateConnectHandlerCode(){return`
1063
+ const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
1064
+ const { DynamoDBDocumentClient, PutCommand } = require('@aws-sdk/lib-dynamodb');
1065
+
1066
+ const client = new DynamoDBClient({});
1067
+ const docClient = DynamoDBDocumentClient.from(client);
1068
+
1069
+ exports.handler = async (event) => {
1070
+ const connectionId = event.requestContext.connectionId;
1071
+ const userId = event.queryStringParameters?.userId || 'anonymous';
1072
+ const ttl = Math.floor(Date.now() / 1000) + 86400; // 24 hours
1073
+
1074
+ try {
1075
+ await docClient.send(new PutCommand({
1076
+ TableName: process.env.CONNECTIONS_TABLE,
1077
+ Item: {
1078
+ connectionId,
1079
+ userId,
1080
+ connectedAt: new Date().toISOString(),
1081
+ ttl,
1082
+ },
1083
+ }));
1084
+
1085
+ return { statusCode: 200, body: 'Connected' };
1086
+ } catch (error) {
1087
+ console.error('Connect error:', error);
1088
+ return { statusCode: 500, body: 'Failed to connect' };
1089
+ }
1090
+ };
1091
+ `.trim()}generateDisconnectHandlerCode(){return`
1092
+ const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
1093
+ const { DynamoDBDocumentClient, DeleteCommand, QueryCommand } = require('@aws-sdk/lib-dynamodb');
1094
+
1095
+ const client = new DynamoDBClient({});
1096
+ const docClient = DynamoDBDocumentClient.from(client);
1097
+
1098
+ exports.handler = async (event) => {
1099
+ const connectionId = event.requestContext.connectionId;
1100
+
1101
+ try {
1102
+ // Remove connection record
1103
+ await docClient.send(new DeleteCommand({
1104
+ TableName: process.env.CONNECTIONS_TABLE,
1105
+ Key: { connectionId },
1106
+ }));
1107
+
1108
+ // Remove all channel subscriptions for this connection
1109
+ const subscriptions = await docClient.send(new QueryCommand({
1110
+ TableName: process.env.CHANNELS_TABLE,
1111
+ IndexName: 'connectionId-index',
1112
+ KeyConditionExpression: 'connectionId = :cid',
1113
+ ExpressionAttributeValues: { ':cid': connectionId },
1114
+ }));
1115
+
1116
+ if (subscriptions.Items) {
1117
+ for (const sub of subscriptions.Items) {
1118
+ await docClient.send(new DeleteCommand({
1119
+ TableName: process.env.CHANNELS_TABLE,
1120
+ Key: { channel: sub.channel, connectionId },
1121
+ }));
1122
+ }
1123
+ }
1124
+
1125
+ return { statusCode: 200, body: 'Disconnected' };
1126
+ } catch (error) {
1127
+ console.error('Disconnect error:', error);
1128
+ return { statusCode: 500, body: 'Failed to disconnect' };
1129
+ }
1130
+ };
1131
+ `.trim()}generateMessageHandlerCode(){return`
1132
+ const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
1133
+ const { DynamoDBDocumentClient, PutCommand, DeleteCommand, QueryCommand, GetCommand } = require('@aws-sdk/lib-dynamodb');
1134
+ const { ApiGatewayManagementApiClient, PostToConnectionCommand } = require('@aws-sdk/client-apigatewaymanagementapi');
1135
+
1136
+ const dynamoClient = new DynamoDBClient({});
1137
+ const docClient = DynamoDBDocumentClient.from(dynamoClient);
1138
+
1139
+ exports.handler = async (event) => {
1140
+ const connectionId = event.requestContext.connectionId;
1141
+ const endpoint = \`https://\${event.requestContext.domainName}/\${event.requestContext.stage}\`;
1142
+ const apiClient = new ApiGatewayManagementApiClient({ endpoint });
1143
+
1144
+ let body;
1145
+ try {
1146
+ body = JSON.parse(event.body);
1147
+ } catch {
1148
+ return { statusCode: 400, body: 'Invalid JSON' };
1149
+ }
1150
+
1151
+ const { action, channel, data } = body;
1152
+
1153
+ try {
1154
+ switch (action) {
1155
+ case 'subscribe': {
1156
+ const ttl = Math.floor(Date.now() / 1000) + 86400;
1157
+ await docClient.send(new PutCommand({
1158
+ TableName: process.env.CHANNELS_TABLE,
1159
+ Item: { channel, connectionId, subscribedAt: new Date().toISOString(), ttl },
1160
+ }));
1161
+ return { statusCode: 200, body: JSON.stringify({ action: 'subscribed', channel }) };
1162
+ }
1163
+
1164
+ case 'unsubscribe': {
1165
+ await docClient.send(new DeleteCommand({
1166
+ TableName: process.env.CHANNELS_TABLE,
1167
+ Key: { channel, connectionId },
1168
+ }));
1169
+ return { statusCode: 200, body: JSON.stringify({ action: 'unsubscribed', channel }) };
1170
+ }
1171
+
1172
+ case 'broadcast': {
1173
+ // Get all subscribers for the channel
1174
+ const subscribers = await docClient.send(new QueryCommand({
1175
+ TableName: process.env.CHANNELS_TABLE,
1176
+ KeyConditionExpression: 'channel = :channel',
1177
+ ExpressionAttributeValues: { ':channel': channel },
1178
+ }));
1179
+
1180
+ const message = JSON.stringify({ channel, event: body.event, data });
1181
+
1182
+ // Send to all subscribers
1183
+ const sendPromises = (subscribers.Items || []).map(async (sub) => {
1184
+ try {
1185
+ await apiClient.send(new PostToConnectionCommand({
1186
+ ConnectionId: sub.connectionId,
1187
+ Data: message,
1188
+ }));
1189
+ } catch (error) {
1190
+ if (error.statusCode === 410) {
1191
+ // Connection is stale, remove it
1192
+ await docClient.send(new DeleteCommand({
1193
+ TableName: process.env.CHANNELS_TABLE,
1194
+ Key: { channel, connectionId: sub.connectionId },
1195
+ }));
1196
+ }
1197
+ }
1198
+ });
1199
+
1200
+ await Promise.all(sendPromises);
1201
+ return { statusCode: 200, body: JSON.stringify({ action: 'broadcasted', channel, recipients: subscribers.Items?.length || 0 }) };
1202
+ }
1203
+
1204
+ case 'ping': {
1205
+ return { statusCode: 200, body: JSON.stringify({ action: 'pong', timestamp: Date.now() }) };
1206
+ }
1207
+
1208
+ default:
1209
+ return { statusCode: 400, body: JSON.stringify({ error: 'Unknown action', action }) };
1210
+ }
1211
+ } catch (error) {
1212
+ console.error('Message handler error:', error);
1213
+ return { statusCode: 500, body: JSON.stringify({ error: 'Internal error' }) };
1214
+ }
1215
+ };
1216
+ `.trim()}generateRealtimeServerResources($,J){let Y=this.mergedConfig.infrastructure?.realtime;if(!Y)return;let Q=Y.server||{},W=Q.port||6001,U=Q.instances||1,Z=`${$}${J}RealtimeSG`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Z,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`Security group for ${$} realtime WebSocket server`,GroupName:`${$}-${J}-realtime-sg`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:W,ToPort:W,CidrIp:"0.0.0.0/0",Description:"WebSocket connections"},{IpProtocol:"tcp",FromPort:443,ToPort:443,CidrIp:"0.0.0.0/0",Description:"HTTPS/WSS connections"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${$}-${J}-realtime-sg`},{Key:"Environment",Value:J}]}});let z=`${$}${J}RealtimeTaskDef`.replace(/[^a-zA-Z0-9]/g,""),H=`${$}${J}RealtimeTaskRole`.replace(/[^a-zA-Z0-9]/g,""),K=`${$}${J}RealtimeExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(K,{Type:"AWS::IAM::Role",Properties:{RoleName:`${$}-${J}-realtime-exec-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"]}}),this.builder.addResource(H,{Type:"AWS::IAM::Role",Properties:{RoleName:`${$}-${J}-realtime-task-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"RealtimeTaskPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogStream","logs:PutLogEvents"],Resource:"*"},...Q.redis?.enabled?[{Effect:"Allow",Action:["elasticache:DescribeCacheClusters","elasticache:DescribeReplicationGroups"],Resource:"*"}]:[]]}}]}});let B=[{Name:"BROADCAST_HOST",Value:Q.host||"0.0.0.0"},{Name:"BROADCAST_PORT",Value:String(W)},{Name:"NODE_ENV",Value:J==="production"?"production":"development"}];if(Q.redis?.enabled){if(Q.redis.useElastiCache)B.push({Name:"REDIS_HOST",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Address"]}}),B.push({Name:"REDIS_PORT",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Port"]}});else B.push({Name:"REDIS_HOST",Value:Q.redis.host||"localhost"}),B.push({Name:"REDIS_PORT",Value:String(Q.redis.port||6379)});if(Q.redis.keyPrefix)B.push({Name:"REDIS_KEY_PREFIX",Value:Q.redis.keyPrefix})}this.builder.addResource(z,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${$}-${J}-realtime`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:"512",Memory:"1024",ExecutionRoleArn:{"Fn::GetAtt":[K,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[H,"Arn"]},ContainerDefinitions:[{Name:"realtime",Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${$}-realtime:latest`},Essential:!0,PortMappings:[{ContainerPort:W,Protocol:"tcp"}],Environment:B,LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":`/ecs/${$}-${J}-realtime`,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":"realtime"}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${W}${Q.healthCheckPath||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${$}-${J}-realtime`},{Key:"Environment",Value:J}]},DependsOn:[K,H]});let O=`${$}${J}RealtimeLogs`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(O,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/ecs/${$}-${J}-realtime`,RetentionInDays:30}});let X=`${$}${J}RealtimeService`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(X,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${$}-${J}-realtime`,Cluster:{Ref:"ECSCluster"},TaskDefinition:{Ref:z},DesiredCount:U,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:Z}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},HealthCheckGracePeriodSeconds:60,Tags:[{Key:"Name",Value:`${$}-${J}-realtime`},{Key:"Environment",Value:J}]},DependsOn:[z,Z,O]}),Q.autoScaling){let j=Q.autoScaling,q=`${$}${J}RealtimeScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(q,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:j.max||10,MinCapacity:j.min||1,ResourceId:{"Fn::Sub":`service/\${ECSCluster}/${$}-${J}-realtime`},RoleARN:{"Fn::Sub":"arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService"},ScalableDimension:"ecs:service:DesiredCount",ServiceNamespace:"ecs"},DependsOn:X}),j.targetCPU)this.builder.addResource(`${$}${J}RealtimeCPUPolicy`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${$}-${J}-realtime-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:q},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:j.targetCPU,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(Y.monitoring?.enabled){let j=Y.monitoring,q=j.notificationTopicArn;if(!q&&j.notificationEmails?.length){let E=`${$}${J}RealtimeAlarmTopic`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(E,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${$}-${J}-realtime-alarms`,DisplayName:"Realtime Server Alarms"}}),j.notificationEmails.forEach((F,w)=>{this.builder.addResource(`${E}Sub${w}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:E},Protocol:"email",Endpoint:F}})}),q={Ref:E}}this.builder.addResource(`${$}${J}RealtimeCPUAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${$}-${J}-realtime-high-cpu`,AlarmDescription:"Realtime server CPU utilization is high",MetricName:"CPUUtilization",Namespace:"AWS/ECS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:80,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ClusterName",Value:{Ref:"ECSCluster"}},{Name:"ServiceName",Value:`${$}-${J}-realtime`}],...q&&{AlarmActions:[q]}},DependsOn:X}),this.builder.addResource(`${$}${J}RealtimeMemoryAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${$}-${J}-realtime-high-memory`,AlarmDescription:"Realtime server memory utilization is high",MetricName:"MemoryUtilization",Namespace:"AWS/ECS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:80,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ClusterName",Value:{Ref:"ECSCluster"}},{Name:"ServiceName",Value:`${$}-${J}-realtime`}],...q&&{AlarmActions:[q]}},DependsOn:X})}this.builder.addOutput(`${$}${J}RealtimeEndpoint`.replace(/[^a-zA-Z0-9]/g,""),{Description:"Realtime WebSocket server endpoint",Value:{"Fn::Sub":`wss://${$}-${J}-realtime.\${AWS::Region}.elb.amazonaws.com:${W}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}})}generateBroadcastConfig(){let $=this.mergedConfig.infrastructure?.realtime;if(!$||$.mode!=="server")return"";let J=$.server||{};return`import type { BroadcastConfig } from 'ts-broadcasting'
1217
+
1218
+ export default {
1219
+ verbose: ${this.environment!=="production"},
1220
+ driver: '${J.driver||"bun"}',
1221
+ default: 'bun',
1222
+
1223
+ connections: {
1224
+ bun: {
1225
+ driver: 'bun',
1226
+ host: process.env.BROADCAST_HOST || '${J.host||"0.0.0.0"}',
1227
+ port: Number(process.env.BROADCAST_PORT) || ${J.port||6001},
1228
+ scheme: '${J.scheme||"wss"}',
1229
+ options: {
1230
+ idleTimeout: ${J.idleTimeout||120},
1231
+ maxPayloadLength: ${J.maxPayloadLength||16777216},
1232
+ backpressureLimit: ${J.backpressureLimit||1048576},
1233
+ closeOnBackpressureLimit: ${J.closeOnBackpressureLimit||!1},
1234
+ sendPings: ${J.sendPings!==!1},
1235
+ perMessageDeflate: ${J.perMessageDeflate!==!1},
1236
+ },
1237
+ },
1238
+ },
1239
+ ${J.redis?.enabled?`
1240
+ redis: {
1241
+ host: process.env.REDIS_HOST || '${J.redis.host||"localhost"}',
1242
+ port: Number(process.env.REDIS_PORT) || ${J.redis.port||6379},
1243
+ ${J.redis.password?`password: process.env.REDIS_PASSWORD || '${J.redis.password}',`:""}
1244
+ database: ${J.redis.database||0},
1245
+ keyPrefix: '${J.redis.keyPrefix||"broadcasting:"}',
1246
+ },
1247
+ `:""}
1248
+ ${J.rateLimit?.enabled?`
1249
+ rateLimit: {
1250
+ max: ${J.rateLimit.max||100},
1251
+ window: ${J.rateLimit.window||60000},
1252
+ perChannel: ${J.rateLimit.perChannel!==!1},
1253
+ perUser: ${J.rateLimit.perUser!==!1},
1254
+ },
1255
+ `:""}
1256
+ ${J.loadManagement?.enabled?`
1257
+ loadManagement: {
1258
+ enabled: true,
1259
+ maxConnections: ${J.loadManagement.maxConnections||1e4},
1260
+ maxSubscriptionsPerConnection: ${J.loadManagement.maxSubscriptionsPerConnection||100},
1261
+ shedLoadThreshold: ${J.loadManagement.shedLoadThreshold||0.8},
1262
+ },
1263
+ `:""}
1264
+ } satisfies BroadcastConfig
1265
+ `}toYAML(){return this.builder.toYAML()}toJSON(){return this.builder.toJSON()}getBuilder(){return this.builder}}G0();function v1($){let J=[],Y=[];if(!$.AWSTemplateFormatVersion)J.push({path:"AWSTemplateFormatVersion",message:"AWSTemplateFormatVersion is required",severity:"error"});else if($.AWSTemplateFormatVersion!=="2010-09-09")Y.push({path:"AWSTemplateFormatVersion",message:'AWSTemplateFormatVersion should be "2010-09-09"',severity:"warning"});if(!$.Resources||Object.keys($.Resources).length===0)J.push({path:"Resources",message:"At least one resource is required",severity:"error"});else for(let[Q,W]of Object.entries($.Resources))zW(Q,W,J,Y);if($.Resources){let Q=KW($.Resources);if(Q.length>0)J.push({path:"Resources",message:`Circular dependencies detected: ${Q.join(" -> ")}`,severity:"error"})}if($.Parameters)for(let[Q,W]of Object.entries($.Parameters))GW(Q,W,J,Y);if($.Outputs)for(let[Q,W]of Object.entries($.Outputs))HW(Q,W,J,Y);return{valid:J.length===0,errors:J,warnings:Y}}function zW($,J,Y,Q){if(!J.Type)Y.push({path:`Resources.${$}.Type`,message:"Resource Type is required",severity:"error"});if(!/^[a-zA-Z0-9]+$/.test($))Q.push({path:`Resources.${$}`,message:"Logical ID should only contain alphanumeric characters",severity:"warning"});if(J.Type&&!J.Type.startsWith("AWS::")&&!J.Type.startsWith("Custom::"))Y.push({path:`Resources.${$}.Type`,message:'Resource Type must start with "AWS::" or "Custom::"',severity:"error"});if(J.Properties){for(let[W,U]of Object.entries(J.Properties))if(U===void 0||U===null)Q.push({path:`Resources.${$}.Properties.${W}`,message:"Property has undefined or null value",severity:"warning"})}if(J.DependsOn){if(typeof J.DependsOn==="string"){if(J.DependsOn===$)Y.push({path:`Resources.${$}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}else if(Array.isArray(J.DependsOn)){if(J.DependsOn.includes($))Y.push({path:`Resources.${$}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}}}function GW($,J,Y,Q){if(!J.Type)Y.push({path:`Parameters.${$}.Type`,message:"Parameter Type is required",severity:"error"});let W=["String","Number","List<Number>","CommaDelimitedList","AWS::SSM::Parameter::Value<String>"];if(J.Type&&!W.includes(J.Type)&&!J.Type.startsWith("AWS::"))Q.push({path:`Parameters.${$}.Type`,message:`Uncommon parameter type: ${J.Type}`,severity:"warning"});if(J.NoEcho&&J.Default)Q.push({path:`Parameters.${$}`,message:"NoEcho parameters should not have default values",severity:"warning"})}function HW($,J,Y,Q){if(!J.Value)Y.push({path:`Outputs.${$}.Value`,message:"Output Value is required",severity:"error"})}function KW($){let J={};for(let[Z,z]of Object.entries($)){if(J[Z]=[],z.DependsOn){if(typeof z.DependsOn==="string")J[Z].push(z.DependsOn);else if(Array.isArray(z.DependsOn))J[Z].push(...z.DependsOn)}let H=U6(z);J[Z].push(...H)}let Y=new Set,Q=new Set,W=[];function U(Z,z){Y.add(Z),Q.add(Z),z.push(Z);let H=J[Z]||[];for(let K of H)if(!Y.has(K)){if(U(K,z))return!0}else if(Q.has(K)){let B=z.indexOf(K);return W.push(...z.slice(B),K),!0}return z.pop(),Q.delete(Z),!1}for(let Z of Object.keys(J))if(!Y.has(Z)){if(U(Z,[]))return W}return[]}function U6($,J=[]){if(typeof $!=="object"||$===null)return J;if(Array.isArray($)){for(let Y of $)U6(Y,J);return J}if($.Ref&&typeof $.Ref==="string"&&!$.Ref.startsWith("AWS::"))J.push($.Ref);if($["Fn::GetAtt"]){let Y=$["Fn::GetAtt"];if(Array.isArray(Y)&&Y.length>0)J.push(Y[0])}for(let Y of Object.values($))U6(Y,J);return J}function f1($){let J=[],Y=[],Q=new TextEncoder().encode($).length,W=51200,U=460800;if(Q>51200)if(Q>460800)J.push({path:"template",message:`Template size (${Q} bytes) exceeds maximum allowed size of 460800 bytes`,severity:"error"});else Y.push({path:"template",message:`Template size (${Q} bytes) exceeds direct upload limit (51200 bytes). You must upload to S3 first.`,severity:"warning"});return{valid:J.length===0,errors:J,warnings:Y}}function g1($){let J=[],Y=[],Q=$.Resources?Object.keys($.Resources).length:0,W=$.Parameters?Object.keys($.Parameters).length:0,U=$.Outputs?Object.keys($.Outputs).length:0;if(Q>500)J.push({path:"Resources",message:`Template has ${Q} resources, exceeding the limit of 500`,severity:"error"});else if(Q>200)Y.push({path:"Resources",message:`Template has ${Q} resources. Consider using nested stacks for better organization.`,severity:"warning"});if(W>200)J.push({path:"Parameters",message:`Template has ${W} parameters, exceeding the limit of 200`,severity:"error"});if(U>200)J.push({path:"Outputs",message:`Template has ${U} outputs, exceeding the limit of 200`,severity:"error"});return{valid:J.length===0,errors:J,warnings:Y}}function Z6($){$.command("generate","Generate CloudFormation templates").alias("gen").option("--output <path>","Output directory for templates",{default:"cloudformation"}).option("--format <format>","Output format: json or yaml",{default:"json"}).option("--module <module>","Generate specific module only").action(async(J)=>{V("Generating CloudFormation Templates");let Y=new M("Loading configuration...");Y.start();try{let Q=await g();Y.succeed("Configuration loaded");let W=J?.output||"cloudformation",U=J?.format||"json",Z=J?.env||"production";if(!BW(W))await OW(W,{recursive:!0});r("Generating infrastructure...");let z=new g0({config:Q,environment:Z,modules:J?.module?[J.module]:void 0}),H=new M("Generating CloudFormation template...");H.start(),z.generate();let K=U==="yaml"?z.toYAML():z.toJSON();H.succeed("Template generated"),r("Validating template...");let B=JSON.parse(z.toJSON()),O=v1(B),X=f1(K),j=g1(B),q=[...O.errors,...X.errors,...j.errors];if(q.length>0){_("Template validation failed:");for(let D of q)_(` - ${D.path}: ${D.message}`)}else A("Template validated successfully");let E=[...O.warnings,...X.warnings,...j.warnings];if(E.length>0)for(let D of E)N(` - ${D.path}: ${D.message}`);let F=jW(W,`${Z}.${U}`);await XW(F,K),A(`Generated ${F}`);let w=z.getBuilder(),T=Object.keys(w.getResources()).length;G(`
1266
+ Generated ${T} resources:`);let S=w.getResources(),R={};for(let D of Object.values(S)){let k=D.Type;R[k]=(R[k]||0)+1}let C=Object.entries(R).sort((D,k)=>k[1]-D[1]);for(let[D,k]of C)G(` - ${D}: ${k}`);G(`
1267
+ Next steps:
1268
+ 1. Review the generated templates in ${W}/
1269
+ 2. Run 'cloud deploy' to deploy your infrastructure`)}catch(Q){Y.fail("Failed to generate templates"),_(Q instanceof Error?Q.message:"Unknown error")}}),$.command("generate:preview","Preview what will be generated").action(async()=>{V("Template Preview"),G("This command will show a preview of generated templates")}),$.command("diff","Show diff between local config and deployed stack").alias("generate:diff").option("--stack <name>","Stack name to compare against").option("--env <environment>","Environment (production, staging, development)").action(async(J)=>{V("Infrastructure Diff");try{let Y=await g(),Q=J?.env||"production",W=J?.stack||`${Y.project.slug}-${Q}`,U=Y.project.region||"us-east-1";G(`Stack: ${W}`),G(`Region: ${U}`),G(`Environment: ${Q}`),r("Generating template from configuration...");let Z=new g0({config:Y,environment:Q});Z.generate();let z=Z.toJSON(),H=JSON.parse(z);r("Fetching deployed template...");let K=new O$(U),B=null;try{let T=await K.getTemplate(W);if(T.TemplateBody)B=JSON.parse(T.TemplateBody)}catch(T){if(T.message?.includes("does not exist")){N(`Stack "${W}" does not exist yet`),G(`
1270
+ This will be a new deployment with the following resources:`);let S=Object.keys(H.Resources||{}).length;G(`
1271
+ Resources to create: ${S}`);let R={};for(let C of Object.values(H.Resources||{})){let D=C.Type;R[D]=(R[D]||0)+1}for(let[C,D]of Object.entries(R).sort((k,u)=>u[1]-k[1]))G(` + ${C}: ${D}`);G("\nRun `cloud deploy` to create this stack");return}throw T}r("Comparing templates...");let O=B.Resources||{},X=H.Resources||{},j=new Set(Object.keys(O)),q=new Set(Object.keys(X)),E=[];for(let T of q)if(!j.has(T))E.push(T);let F=[];for(let T of j)if(!q.has(T))F.push(T);let w=[];for(let T of q)if(j.has(T)){let S=JSON.stringify(O[T]),R=JSON.stringify(X[T]);if(S!==R)w.push(T)}if(E.length===0&&F.length===0&&w.length===0){A(`
1272
+ No changes detected - infrastructure is up to date`);return}if(G(`
1273
+ Changes detected:
1274
+ `),E.length>0){A(`Resources to add (${E.length}):`);for(let T of E){let S=X[T].Type;G(` + ${T} (${S})`)}console.log()}if(F.length>0){_(`Resources to remove (${F.length}):`);for(let T of F){let S=O[T].Type;G(` - ${T} (${S})`)}console.log()}if(w.length>0){N(`Resources to modify (${w.length}):`);for(let T of w){let S=X[T].Type;G(` ~ ${T} (${S})`)}console.log()}G("Summary:"),G(` - Add: ${E.length}`),G(` - Remove: ${F.length}`),G(` - Modify: ${w.length}`),G("\nRun `cloud deploy` to apply these changes")}catch(Y){_(`Diff failed: ${Y.message}`)}})}function z6($){$.command("server:list","List all servers").action(async()=>{V("Listing Servers"),x(["Name","Instance ID","Type","Status","AZ"],[["web-1","i-1234567890abcdef0","t3.micro","running","us-east-1a"],["web-2","i-0987654321fedcba0","t3.micro","running","us-east-1b"]])}),$.command("server:create <name>","Create a new server").option("--type <type>","Instance type (e.g., t3.micro)",{default:"t3.micro"}).option("--ami <ami>","AMI ID").action(async(J,Y)=>{V(`Creating Server: ${J}`);let Q=new M(`Creating server ${J}...`);Q.start(),await new Promise((W)=>setTimeout(W,2000)),Q.succeed(`Server ${J} created successfully`),G(`Instance type: ${Y?.type||"t3.micro"}`)}),$.command("server:ssh <name>","SSH into a server").action(async(J)=>{r(`Connecting to ${J}...`)}),$.command("server:logs <name>","View server logs").option("--tail","Tail logs in real-time").action(async(J)=>{V(`Logs for ${J}`)}),$.command("server:deploy <name>","Deploy app to server").option("--strategy <strategy>","Deployment strategy: git, rsync, or scp").action(async(J)=>{V(`Deploying to ${J}`)}),$.command("server:resize <name> <type>","Change server instance type").action(async(J,Y)=>{if(V(`Resizing Server: ${J}`),!await P(`This will stop and restart ${J}. Continue?`,!1)){G("Resize cancelled");return}let W=new M(`Resizing ${J} to ${Y}...`);W.start();try{await new Promise((U)=>setTimeout(U,2000)),W.succeed(`Server ${J} resized to ${Y}`),A(`Instance type changed from t3.micro to ${Y}`)}catch(U){W.fail("Resize failed"),_(U.message)}}),$.command("server:reboot <name>","Reboot a server").option("--force","Force reboot without confirmation").action(async(J,Y)=>{if(V(`Rebooting Server: ${J}`),!Y?.force){if(!await P(`Are you sure you want to reboot ${J}?`,!1)){G("Reboot cancelled");return}}let Q=new M(`Rebooting ${J}...`);Q.start();try{await new Promise((W)=>setTimeout(W,2000)),Q.succeed(`Server ${J} rebooted successfully`),G("Server will be available in a few moments")}catch(W){Q.fail("Reboot failed"),_(W.message)}}),$.command("server:destroy <name>","Terminate a server").option("--force","Skip confirmation prompt").action(async(J,Y)=>{if(V(`Destroying Server: ${J}`),i$("This action is irreversible!"),!Y?.force){if(!await P(`Are you absolutely sure you want to terminate ${J}?`,!1)){G("Termination cancelled");return}if(!await P(`Type the server name to confirm: ${J}`,!1)){G("Termination cancelled");return}}let Q=new M(`Terminating ${J}...`);Q.start();try{await new Promise((W)=>setTimeout(W,2000)),Q.succeed(`Server ${J} terminated successfully`),A("All resources have been cleaned up")}catch(W){Q.fail("Termination failed"),_(W.message)}}),$.command("server:recipe <name> <recipe>","Install software recipe").action(async(J,Y)=>{V(`Installing Recipe: ${Y}`);let Q=["lamp","lemp","nodejs","python","ruby","docker"];if(!Q.includes(Y.toLowerCase()))N(`Unknown recipe. Common recipes: ${Q.join(", ")}`);if(G(`Server: ${J}`),G(`Recipe: ${Y}`),!await P(`
1275
+ Install this recipe?`,!0)){G("Operation cancelled");return}let U=new M(`Installing ${Y} stack...`);U.start(),await new Promise((Z)=>setTimeout(Z,5000)),U.succeed("Recipe installed successfully"),A(`
1276
+ Software stack installed!`),G(`Server ${J} is now running ${Y}`)}),$.command("server:cron:add <name> <schedule> <command>","Add cron job to server").action(async(J,Y,Q)=>{if(V("Adding Cron Job"),G(`Server: ${J}`),G(`Schedule: ${Y}`),G(`Command: ${Q}`),!await P(`
1277
+ Add this cron job?`,!0)){G("Operation cancelled");return}let U=new M("Adding cron job...");U.start(),await new Promise((Z)=>setTimeout(Z,2000)),U.succeed("Cron job added"),A(`
1278
+ Cron job created!`),G("Job ID: cron-abc123")}),$.command("server:cron:list <name>","List cron jobs on server").action(async(J)=>{V(`Cron Jobs on ${J}`);let Y=new M("Fetching cron jobs...");Y.start(),await new Promise((Q)=>setTimeout(Q,1500)),Y.stop(),x(["ID","Schedule","Command","Last Run","Status"],[["cron-1","0 2 * * *","backup-db.sh","2h ago","Success"],["cron-2","*/15 * * * *","sync-files.sh","10m ago","Success"],["cron-3","0 0 * * 0","weekly-report.sh","2d ago","Success"]])}),$.command("server:cron:remove <name> <id>","Remove cron job").action(async(J,Y)=>{if(V("Removing Cron Job"),G(`Server: ${J}`),G(`Job ID: ${Y}`),!await P(`
1279
+ Remove this cron job?`,!0)){G("Operation cancelled");return}let W=new M("Removing cron job...");W.start(),await new Promise((U)=>setTimeout(U,1500)),W.succeed("Cron job removed"),A(`
1280
+ Cron job deleted!`)}),$.command("server:worker:add <name> <queue>","Add background worker").option("--processes <count>","Number of worker processes",{default:"1"}).action(async(J,Y,Q)=>{let W=Q?.processes||"1";if(V("Adding Background Worker"),G(`Server: ${J}`),G(`Queue: ${Y}`),G(`Processes: ${W}`),!await P(`
1281
+ Add this worker?`,!0)){G("Operation cancelled");return}let Z=new M("Configuring worker process...");Z.start(),await new Promise((z)=>setTimeout(z,2000)),Z.succeed("Worker configured"),A(`
1282
+ Background worker added!`),G("Worker ID: worker-abc123")}),$.command("server:worker:list <name>","List workers on server").action(async(J)=>{V(`Workers on ${J}`);let Y=new M("Fetching workers...");Y.start(),await new Promise((Q)=>setTimeout(Q,1500)),Y.stop(),x(["ID","Queue","Processes","Status","Uptime"],[["worker-1","emails","2","Running","5d 3h"],["worker-2","images","4","Running","2d 8h"],["worker-3","reports","1","Stopped","-"]])}),$.command("server:worker:restart <name> <id>","Restart worker").action(async(J,Y)=>{V("Restarting Worker"),G(`Server: ${J}`),G(`Worker ID: ${Y}`);let Q=new M("Restarting worker process...");Q.start(),await new Promise((W)=>setTimeout(W,2000)),Q.succeed("Worker restarted"),A(`
1283
+ Worker restarted successfully!`)}),$.command("server:worker:remove <name> <id>","Remove worker").action(async(J,Y)=>{if(V("Removing Worker"),G(`Server: ${J}`),G(`Worker ID: ${Y}`),!await P(`
1284
+ Remove this worker?`,!0)){G("Operation cancelled");return}let W=new M("Removing worker...");W.start(),await new Promise((U)=>setTimeout(U,1500)),W.succeed("Worker removed"),A(`
1285
+ Worker deleted!`)}),$.command("server:firewall:add <name> <rule>","Add firewall rule").action(async(J,Y)=>{if(V("Adding Firewall Rule"),G(`Server: ${J}`),G(`Rule: ${Y}`),!await P(`
1286
+ Add this firewall rule?`,!0)){G("Operation cancelled");return}let W=new M("Updating firewall rules (ufw)...");W.start(),await new Promise((U)=>setTimeout(U,2000)),W.succeed("Firewall rule added"),A(`
1287
+ Firewall rule configured!`)}),$.command("server:firewall:list <name>","List firewall rules").action(async(J)=>{V(`Firewall Rules on ${J}`);let Y=new M("Fetching firewall rules...");Y.start(),await new Promise((Q)=>setTimeout(Q,1500)),Y.stop(),x(["#","Action","From","To","Port","Protocol"],[["1","ALLOW","Anywhere","22/tcp","22","TCP"],["2","ALLOW","Anywhere","80/tcp","80","TCP"],["3","ALLOW","Anywhere","443/tcp","443","TCP"],["4","DENY","192.168.1.0/24","Any","Any","Any"]])}),$.command("server:firewall:remove <name> <rule>","Remove firewall rule").action(async(J,Y)=>{if(V("Removing Firewall Rule"),G(`Server: ${J}`),G(`Rule: ${Y}`),!await P(`
1288
+ Remove this firewall rule?`,!0)){G("Operation cancelled");return}let W=new M("Updating firewall rules...");W.start(),await new Promise((U)=>setTimeout(U,1500)),W.succeed("Firewall rule removed"),A(`
1289
+ Firewall rule deleted!`)}),$.command("server:ssl:install <domain>","Install Let's Encrypt certificate").action(async(J)=>{if(V(`Installing SSL Certificate for ${J}`),!await P(`
1290
+ Install Let's Encrypt certificate?`,!0)){G("Operation cancelled");return}let Q=new M("Installing certbot and obtaining certificate...");Q.start(),await new Promise((W)=>setTimeout(W,3000)),Q.succeed("SSL certificate installed"),A(`
1291
+ SSL certificate active!`),G(`HTTPS enabled for ${J}`),G("Auto-renewal configured via cron")}),$.command("server:ssl:renew <domain>","Renew SSL certificate").action(async(J)=>{V(`Renewing SSL Certificate for ${J}`);let Y=new M("Renewing certificate...");Y.start(),await new Promise((Q)=>setTimeout(Q,2000)),Y.succeed("Certificate renewed"),A(`
1292
+ SSL certificate renewed!`),G(`Valid until: ${new Date(Date.now()+7776000000).toLocaleDateString()}`)}),$.command("server:monitoring <name>","Show server metrics").action(async(J)=>{V(`Server Metrics: ${J}`);let Y=new M("Fetching metrics from CloudWatch...");Y.start(),await new Promise((Q)=>setTimeout(Q,2000)),Y.stop(),G(`
1293
+ Current Metrics:
1294
+ `),G("CPU Usage:"),G(" - Current: 23.5%"),G(" - Average (1h): 18.2%"),G(" - Peak (24h): 67.3%"),G(`
1295
+ Memory Usage:`),G(" - Used: 2.1 GB / 4 GB (52.5%)"),G(" - Available: 1.9 GB"),G(" - Swap: 0 GB"),G(`
1296
+ Disk Usage:`),G(" - /: 15.2 GB / 30 GB (50.7%)"),G(" - /data: 45.8 GB / 100 GB (45.8%)"),G(`
1297
+ Network:`),G(" - In: 125 MB/s"),G(" - Out: 87 MB/s")}),$.command("server:snapshot <name>","Create server snapshot").action(async(J)=>{if(V(`Creating Snapshot of ${J}`),!await P(`
1298
+ Create snapshot? This may take several minutes.`,!0)){G("Operation cancelled");return}let Q=new M("Creating EBS snapshot...");Q.start(),await new Promise((W)=>setTimeout(W,3000)),Q.succeed("Snapshot created"),A(`
1299
+ Server snapshot created!`),G("Snapshot ID: snap-abc123"),G("Use `cloud server:snapshot:restore` to restore from this snapshot")}),$.command("server:snapshot:restore <name> <snapshot-id>","Restore from snapshot").action(async(J,Y)=>{if(V("Restoring from Snapshot"),G(`Server: ${J}`),G(`Snapshot: ${Y}`),N(`
1300
+ This will replace the current server data`),!await P("Proceed with restore?",!1)){G("Operation cancelled");return}let W=new M("Restoring from snapshot...");W.start(),await new Promise((U)=>setTimeout(U,4000)),W.succeed("Restore complete"),A(`
1301
+ Server restored from snapshot!`),N("Reboot required to complete restoration")}),$.command("server:update <name>","Update server packages").action(async(J)=>{if(V(`Updating Packages on ${J}`),!await P(`
1302
+ Update all packages?`,!0)){G("Operation cancelled");return}let Q=new M("Running apt update && apt upgrade...");Q.start(),await new Promise((W)=>setTimeout(W,5000)),Q.succeed("Packages updated"),A(`
1303
+ Server packages updated!`),G("Updated: 45 packages"),N("Reboot recommended")}),$.command("server:secure <name>","Run security hardening script").action(async(J)=>{if(V(`Securing Server: ${J}`),!await P(`
1304
+ Run security hardening? This will:
1305
+ - Configure firewall
1306
+ - Disable root login
1307
+ - Setup fail2ban
1308
+ - Configure SSH keys only
1309
+ - Install security updates`,!0)){G("Operation cancelled");return}let Q=new M("Running security hardening script...");Q.start(),await new Promise((W)=>setTimeout(W,6000)),Q.succeed("Security hardening complete"),A(`
1310
+ Server secured!`),G(`
1311
+ Security measures applied:`),G(" - Firewall configured (ufw)"),G(" - Root login disabled"),G(" - fail2ban installed and configured"),G(" - SSH keys-only authentication"),G(" - Security updates installed")})}function G6($){$.command("function:list","List all Lambda functions").action(async()=>{V("Listing Functions"),x(["Name","Memory","Timeout","Invocations (24h)","Runtime"],[["api-handler","128 MB","30s","15","nodejs20.x"],["worker","512 MB","60s","3","nodejs20.x"]])}),$.command("function:logs <name>","View function logs").option("--tail","Tail logs in real-time").option("--filter <pattern>","Filter logs by pattern").action(async(J)=>{V(`Logs for ${J}`),G("Streaming logs...")}),$.command("function:invoke <name>","Test function invocation").option("--payload <json>","Event payload as JSON").action(async(J,Y)=>{V(`Invoking ${J}`);let Q=new M("Invoking function...");Q.start(),await new Promise((W)=>setTimeout(W,1000)),Q.succeed("Function invoked successfully")}),$.command("function:create <name>","Create a new Lambda function").option("--runtime <runtime>","Runtime (nodejs20.x, python3.12, etc.)",{default:"nodejs20.x"}).option("--memory <mb>","Memory allocation in MB",{default:"128"}).option("--timeout <seconds>","Timeout in seconds",{default:"30"}).option("--handler <handler>","Function handler",{default:"index.handler"}).action(async(J,Y)=>{V(`Creating Lambda Function: ${J}`);let Q=Y?.runtime||"nodejs20.x",W=Y?.memory||"128",U=Y?.timeout||"30",Z=Y?.handler||"index.handler";G(`Runtime: ${Q}`),G(`Memory: ${W} MB`),G(`Timeout: ${U}s`),G(`Handler: ${Z}`);let z=new M("Creating function...");z.start(),await new Promise((H)=>setTimeout(H,2000)),z.succeed(`Function ${J} created successfully`),A(`
1312
+ Function created!`),G(`
1313
+ Next steps:`),G(` - Edit the function code in functions/${J}/index.js`),G(` - cloud function:deploy ${J} - Deploy the function`),G(` - cloud function:invoke ${J} - Test the function`)}),$.command("function:deploy <name>","Deploy specific Lambda function").option("--env <environment>","Environment (production, staging, development)").action(async(J,Y)=>{V(`Deploying Function: ${J}`);let Q=Y?.env||"production";G(`Environment: ${Q}`);let W=new M("Packaging function...");W.start(),W.text="Uploading to Lambda...",await new Promise((U)=>setTimeout(U,1500)),W.text="Updating function configuration...",await new Promise((U)=>setTimeout(U,1000)),W.succeed(`Function ${J} deployed successfully`),A(`
1314
+ Deployment complete!`),G(`
1315
+ Function details:`),G(` - ARN: arn:aws:lambda:us-east-1:123456789:function:${J}`),G(" - Version: $LATEST"),G(` - Last Modified: ${new Date().toISOString()}`)})}function H6($){$.command("container:build","Build Docker image").option("--tag <tag>","Image tag",{default:"latest"}).option("--file <dockerfile>","Dockerfile path",{default:"Dockerfile"}).action(async(J)=>{V("Building Docker Image");let Y=J?.tag||"latest",Q=J?.file||"Dockerfile";G(`Tag: ${Y}`),G(`Dockerfile: ${Q}`);let W=new M("Building image...");W.start(),await new Promise((U)=>setTimeout(U,3000)),W.succeed(`Image built successfully: ${Y}`)}),$.command("container:push","Push Docker image to ECR").option("--tag <tag>","Image tag",{default:"latest"}).option("--repository <name>","ECR repository name").action(async(J)=>{V("Pushing to ECR");let Y=J?.tag||"latest",Q=J?.repository;if(!Q){_("Repository name is required. Use --repository <name>");return}G(`Repository: ${Q}`),G(`Tag: ${Y}`);let W=new M("Authenticating with ECR...");W.start(),await new Promise((U)=>setTimeout(U,1000)),W.text="Pushing image...",await new Promise((U)=>setTimeout(U,3000)),W.succeed("Image pushed successfully"),A(`
1316
+ Image available at:`),G(` 123456789.dkr.ecr.us-east-1.amazonaws.com/${Q}:${Y}`)}),$.command("container:deploy","Update ECS service with new image").option("--service <name>","ECS service name").option("--cluster <name>","ECS cluster name").option("--tag <tag>","Image tag",{default:"latest"}).action(async(J)=>{V("Deploying Container");let Y=J?.service,Q=J?.cluster,W=J?.tag||"latest";if(!Y||!Q){_("Service and cluster names are required"),G("Use: --service <name> --cluster <name>");return}G(`Cluster: ${Q}`),G(`Service: ${Y}`),G(`Tag: ${W}`);let U=new M("Updating task definition...");U.start(),await new Promise((Z)=>setTimeout(Z,1500)),U.text="Updating ECS service...",await new Promise((Z)=>setTimeout(Z,2000)),U.text="Waiting for deployment...",await new Promise((Z)=>setTimeout(Z,2000)),U.succeed(`Service ${Y} updated successfully`),A(`
1317
+ Deployment complete!`),G(`
1318
+ Service details:`),G(" - Running tasks: 2/2"),G(" - Pending tasks: 0"),G(" - Status: ACTIVE")})}X0();v0();function K6($){$.command("domain:list","List all domains").option("--provider <provider>","DNS provider: porkbun, godaddy, cloudflare, or route53").action(async(J)=>{V("Domains");try{let Y=t$(J?.provider),Q=g$(J?.provider)?.provider||"unknown",W=new M(`Fetching domains from ${Q}...`);W.start();let U=await Y.listDomains();if(W.succeed(`Found ${U.length} domain(s)`),U.length===0){G("No domains found in this provider");return}let Z=U.map((z)=>[z,"Active","-",Q.charAt(0).toUpperCase()+Q.slice(1)]);x(["Domain","Status","SSL","Provider"],Z)}catch(Y){_(`Failed to list domains: ${Y instanceof Error?Y.message:String(Y)}`)}}),$.command("domain:add <domain>","Add a new domain").option("--provider <provider>","DNS provider: porkbun, godaddy, cloudflare, or route53").action(async(J,Y)=>{V(`Adding Domain: ${J}`);try{let Q=t$(Y?.provider),W=g$(Y?.provider)?.provider||"unknown",U=new M(`Checking if ${W} can manage ${J}...`);if(U.start(),await Q.canManageDomain(J))U.succeed(`Domain ${J} is already available in ${W}`),G(`
1319
+ The domain is ready to use. You can now:`),G(` - Add DNS records: cloud dns:add ${J} A 192.168.1.1`),G(` - Generate SSL: cloud domain:ssl ${J}`);else if(U.warn(`Domain ${J} is not available in ${W}`),G(`
1320
+ To add this domain:`),W==="route53")G(" - Create a hosted zone in Route53 for this domain"),G(" - Update nameservers at your registrar to point to Route53");else G(` - Ensure the domain is registered with ${W}`),G(" - Enable API access for the domain in your provider dashboard")}catch(Q){_(`Failed to check domain: ${Q instanceof Error?Q.message:String(Q)}`)}}),$.command("domain:ssl <domain>","Generate SSL certificate via ACM with DNS validation").option("--provider <provider>","DNS provider for validation: porkbun, godaddy, or route53").option("--region <region>","AWS region for ACM (default: us-east-1 for CloudFront compatibility)").option("--wait","Wait for certificate validation to complete").action(async(J,Y)=>{V(`Generating SSL Certificate for ${J}`);try{let Q=g$(Y?.provider);if(!Q)throw Error("No DNS provider configured");let W=Y?.region||"us-east-1",U=Q.provider;G(`DNS Provider: ${U}`),G(`ACM Region: ${W}`);let Z=new f0(Q,W),z=new M("Requesting certificate and creating validation records...");z.start();let H=await Z.findOrCreateCertificate({domainName:J,subjectAlternativeNames:[`*.${J}`],waitForValidation:Y?.wait??!0,maxWaitMinutes:10});if(H.isNew)z.succeed("Certificate requested and validation records created");else z.succeed("Found existing valid certificate");if(G(`Certificate ARN: ${H.certificateArn}`),G(`Status: ${H.status}`),H.status==="issued")A(`
1321
+ SSL Certificate is ready!`),G(`
1322
+ You can now use this certificate with:`),G(" - CloudFront distributions"),G(" - Application Load Balancers"),G(" - API Gateway custom domains");else if(H.status==="pending")G(`
1323
+ DNS validation records have been created.`),G("Certificate validation may take a few more minutes."),G(`
1324
+ Check status with: cloud domain:verify ${J}`);else _(`
1325
+ Certificate validation failed. Check ACM console for details.`)}catch(Q){_(`Failed to generate SSL: ${Q instanceof Error?Q.message:String(Q)}`)}}),$.command("domain:verify <domain>","Verify domain ownership and SSL status").option("--provider <provider>","DNS provider: porkbun, godaddy, cloudflare, or route53").action(async(J,Y)=>{V(`Verifying Domain: ${J}`);try{let Q=t$(Y?.provider),W=g$(Y?.provider)?.provider||"unknown",U=new M("Checking domain ownership...");if(U.start(),!await Q.canManageDomain(J)){U.fail("Domain not found in provider"),_(`Domain ${J} is not available in ${W}`);return}U.succeed("Domain ownership verified"),U.text="Fetching DNS records...",U.start();let H=(await Q.listRecords(J)).records||[];U.succeed(`Found ${H.length} DNS record(s)`),U.text="Checking SSL certificate status...",U.start();let K=new S$("us-east-1"),B="Not found",O="";try{let q=(await K.listCertificates()).CertificateSummaryList.find((E)=>E.DomainName===J||E.DomainName===`*.${J}`);if(q)O=q.CertificateArn||"",B=(await K.describeCertificate({CertificateArn:O})).Status||"Unknown"}catch{}if(U.succeed("SSL check complete"),G(`
1326
+ Verification details:`),G(` - Provider: ${W}`),G(` - DNS records found: ${H.length}`),G(" - Domain managed: Yes"),G(` - SSL certificate: ${B}`),O)G(` - Certificate ARN: ${O}`);let X=new Map;for(let j of H){let q=X.get(j.type)||0;X.set(j.type,q+1)}if(X.size>0){G(`
1327
+ Record summary:`);for(let[j,q]of X)G(` - ${j}: ${q}`)}}catch(Q){_(`Failed to verify domain: ${Q instanceof Error?Q.message:String(Q)}`)}}),$.command("dns:records <domain>","List DNS records for a domain").option("--provider <provider>","DNS provider: porkbun, godaddy, cloudflare, or route53").option("--type <type>","Filter by record type (A, AAAA, CNAME, TXT, MX, etc.)").action(async(J,Y)=>{V(`DNS Records for ${J}`);try{let Q=t$(Y?.provider),W=g$(Y?.provider)?.provider||"unknown",U=new M(`Fetching records from ${W}...`);U.start();let z=(await Q.listRecords(J)).records||[];if(U.succeed(`Found ${z.length} record(s)`),Y?.type){let K=Y.type.toUpperCase();z=z.filter((B)=>B.type.toUpperCase()===K),G(`Filtered to ${z.length} ${K} record(s)`)}if(z.length===0){G("No records found");return}let H=z.map((K)=>[K.type,K.name||"@",K.content.length>50?`${K.content.substring(0,47)}...`:K.content,String(K.ttl||300)]);x(["Type","Name","Value","TTL"],H)}catch(Q){_(`Failed to list records: ${Q instanceof Error?Q.message:String(Q)}`)}}),$.command("dns:add <domain> <type> <value>","Add DNS record").option("--provider <provider>","DNS provider: porkbun, godaddy, cloudflare, or route53").option("--name <name>","Record name (subdomain)",{default:"@"}).option("--ttl <seconds>","Time to live in seconds",{default:"300"}).action(async(J,Y,Q,W)=>{V("Adding DNS Record");try{let U=t$(W?.provider),Z=g$(W?.provider)?.provider||"unknown",z=W?.name||"@",H=Number.parseInt(W?.ttl||"300",10),K=Y.toUpperCase();G(`Provider: ${Z}`),G(`Domain: ${J}`),G(`Type: ${K}`),G(`Name: ${z}`),G(`Value: ${Q}`),G(`TTL: ${H}`);let B=new M(`Adding record via ${Z}...`);B.start(),await U.createRecord(J,{type:K,name:z==="@"?"":z,content:Q,ttl:H}),B.succeed("DNS record added successfully"),A(`
1328
+ Record created!`),G(`
1329
+ Note: DNS changes may take a few minutes to propagate`)}catch(U){_(`Failed to add record: ${U instanceof Error?U.message:String(U)}`)}}),$.command("dns:delete <domain> <type>","Delete DNS record").option("--provider <provider>","DNS provider: porkbun, godaddy, cloudflare, or route53").option("--name <name>","Record name (subdomain)",{default:"@"}).option("--value <value>","Record value (required for multi-value records)").action(async(J,Y,Q)=>{V("Deleting DNS Record");try{let W=t$(Q?.provider),U=g$(Q?.provider)?.provider||"unknown",Z=Q?.name||"@",z=Y.toUpperCase();G(`Provider: ${U}`),G(`Domain: ${J}`),G(`Type: ${z}`),G(`Name: ${Z}`);let H=new M("Finding record...");H.start();let O=((await W.listRecords(J)).records||[]).filter((q)=>q.type.toUpperCase()===z&&(q.name===Z||q.name===""&&Z==="@"));if(O.length===0){H.fail("No matching record found");return}if(O.length>1&&!Q?.value){H.warn("Multiple records found"),G(`
1330
+ Please specify --value to identify which record to delete:`);for(let q of O)G(` - ${q.content}`);return}let X=Q?.value?O.find((q)=>q.content===Q.value)||O[0]:O[0];if(G(`Value: ${X.content}`),!await P("Delete this record?",!1)){G("Deletion cancelled");return}H.text=`Deleting record via ${U}...`,H.start(),await W.deleteRecord(J,X),H.succeed("DNS record deleted successfully"),A(`
1331
+ Record deleted!`)}catch(W){_(`Failed to delete record: ${W instanceof Error?W.message:String(W)}`)}})}function B6($){$.command("db:list","List all databases").action(async()=>{V("Databases"),x(["Name","Engine","Instance Type","Status","Storage"],[["production-db","PostgreSQL 15","db.t3.micro","available","20 GB"],["staging-db","PostgreSQL 15","db.t3.micro","available","20 GB"]])}),$.command("db:create <name>","Create a new database").option("--engine <engine>","Database engine: postgres, mysql, or dynamodb").option("--size <size>","Instance size (e.g., db.t3.micro)").action(async(J,Y)=>{V(`Creating Database: ${J}`);let Q=Y?.engine||"postgres",W=Y?.size||"db.t3.micro",U=new M(`Creating ${Q} database...`);U.start(),await new Promise((Z)=>setTimeout(Z,3000)),U.succeed(`Database ${J} created successfully`),G(`Engine: ${Q}`),G(`Size: ${W}`)}),$.command("db:backup <name>","Create database backup").action(async(J)=>{V(`Backing up ${J}`);let Y=new M("Creating snapshot...");Y.start(),await new Promise((Q)=>setTimeout(Q,2000)),Y.succeed("Backup created successfully")}),$.command("db:connect <name>","Get connection details").action(async(J)=>{V(`Connection Details for ${J}`),G("Host: my-db.xxxxx.us-east-1.rds.amazonaws.com"),G("Port: 5432"),G("Database: postgres"),N("Get password from AWS Secrets Manager")}),$.command("db:restore <name> <backup-id>","Restore database from backup").option("--new-name <name>","Name for restored database").action(async(J,Y,Q)=>{V(`Restoring Database: ${J}`);let W=Q?.newName||`${J}-restored-${Date.now()}`;if(G(`Source: ${J}`),G(`Backup ID: ${Y}`),G(`Target: ${W}`),i$(`
1332
+ This will create a new database instance from the backup.`),!await P("Continue with restore?",!1)){G("Restore cancelled");return}let Z=new M("Restoring from snapshot...");Z.start(),await new Promise((z)=>setTimeout(z,3000)),Z.succeed("Database restore initiated"),A(`
1333
+ Restore started!`),G(`
1334
+ The new database will be available in a few minutes`),G(`New instance: ${W}`)}),$.command("db:tunnel <name>","Create SSH tunnel to database").option("--local-port <port>","Local port for tunnel",{default:"5432"}).action(async(J,Y)=>{V(`Creating SSH Tunnel to ${J}`);let Q=Y?.localPort||"5432";G(`Database: ${J}`),G(`Local port: ${Q}`);let W=new M("Establishing SSH tunnel...");W.start(),await new Promise((U)=>setTimeout(U,2000)),W.succeed("SSH tunnel established"),A(`
1335
+ Tunnel active!`),G(`
1336
+ Connection details:`),G(" Host: localhost"),G(` Port: ${Q}`),G(" Database: postgres"),G(`
1337
+ Press Ctrl+C to close the tunnel`)}),$.command("db:migrations:run <name>","Run database migrations").action(async(J)=>{if(V(`Running Migrations for ${J}`),!await P(`
1338
+ Run pending migrations?`,!0)){G("Operation cancelled");return}let Q=new M("Running migrations...");Q.start(),await new Promise((W)=>setTimeout(W,3000)),Q.succeed("Migrations complete"),A(`
1339
+ Migrations applied!`),G("Executed: 3 migrations"),G(" - 20241101_add_users_table"),G(" - 20241102_add_email_column"),G(" - 20241103_create_indexes")}),$.command("db:migrations:rollback <name>","Rollback last migration").action(async(J)=>{if(V(`Rolling Back Migration for ${J}`),N(`
1340
+ This will revert the last migration`),!await P("Rollback last migration?",!1)){G("Operation cancelled");return}let Q=new M("Rolling back migration...");Q.start(),await new Promise((W)=>setTimeout(W,2000)),Q.succeed("Rollback complete"),A(`
1341
+ Migration rolled back!`),G("Reverted: 20241103_create_indexes")}),$.command("db:migrations:status <name>","Show migration status").action(async(J)=>{V(`Migration Status for ${J}`);let Y=new M("Fetching migration status...");Y.start(),await new Promise((Q)=>setTimeout(Q,1500)),Y.stop(),x(["Migration","Status","Executed"],[["20241101_add_users_table","Applied","2024-11-01 10:30"],["20241102_add_email_column","Applied","2024-11-02 15:45"],["20241103_create_indexes","Applied","2024-11-03 09:15"],["20241104_add_timestamps","Pending","-"]]),G(`
1342
+ Summary: 3 applied, 1 pending`)}),$.command("db:seed <name>","Seed database with test data").action(async(J)=>{if(V(`Seeding Database: ${J}`),N(`
1343
+ This will add test/sample data`),!await P("Seed database?",!0)){G("Operation cancelled");return}let Q=new M("Running database seeders...");Q.start(),await new Promise((W)=>setTimeout(W,3000)),Q.succeed("Seeding complete"),A(`
1344
+ Database seeded!`),G("Added:"),G(" - 100 users"),G(" - 500 products"),G(" - 1,000 orders")}),$.command("db:snapshot <name>","Create database snapshot").action(async(J)=>{if(V(`Creating Snapshot of ${J}`),!await P(`
1345
+ Create snapshot?`,!0)){G("Operation cancelled");return}let Q=new M("Creating RDS snapshot...");Q.start(),await new Promise((W)=>setTimeout(W,3000)),Q.succeed("Snapshot created"),A(`
1346
+ Database snapshot created!`),G("Snapshot ID: snap-db-abc123")}),$.command("db:snapshot:list <name>","List snapshots").action(async(J)=>{V(`Snapshots for ${J}`);let Y=new M("Fetching snapshots...");Y.start(),await new Promise((Q)=>setTimeout(Q,1500)),Y.stop(),x(["Snapshot ID","Created","Size","Status"],[["snap-db-001","2024-11-15 02:00","12.5 GB","Available"],["snap-db-002","2024-11-14 02:00","12.3 GB","Available"],["snap-db-003","2024-11-13 02:00","12.1 GB","Available"]])}),$.command("db:snapshot:restore <name> <snapshot-id>","Restore from snapshot").option("--new-name <name>","Name for restored database").action(async(J,Y,Q)=>{let W=Q?.newName||`${J}-restored`;if(V("Restoring from Snapshot"),G(`Source: ${J}`),G(`Snapshot: ${Y}`),G(`New database: ${W}`),!await P(`
1347
+ Restore from snapshot?`,!0)){G("Operation cancelled");return}let Z=new M("Restoring database from snapshot...");Z.start(),await new Promise((z)=>setTimeout(z,8000)),Z.succeed("Restore complete"),A(`
1348
+ Database restored!`),G(`New database: ${W}`)}),$.command("db:users:add <name> <user>","Create database user").option("--password <password>","User password").option("--readonly","Create readonly user").action(async(J,Y,Q)=>{let W=Q?.readonly||!1;if(V("Creating Database User"),G(`Database: ${J}`),G(`Username: ${Y}`),G(`Permissions: ${W?"Read-only":"Read-write"}`),!await P(`
1349
+ Create this user?`,!0)){G("Operation cancelled");return}let Z=new M("Creating database user...");Z.start(),await new Promise((z)=>setTimeout(z,2000)),Z.succeed("User created"),A(`
1350
+ Database user created!`),G(`Username: ${Y}`),G("Password: ************"),N(`
1351
+ Save credentials securely!`)}),$.command("db:users:list <name>","List database users").action(async(J)=>{V(`Users for ${J}`);let Y=new M("Fetching database users...");Y.start(),await new Promise((Q)=>setTimeout(Q,1500)),Y.stop(),x(["Username","Permissions","Created","Last Login"],[["admin","Superuser","2024-01-01","2h ago"],["app_user","Read-write","2024-01-15","5m ago"],["readonly","Read-only","2024-02-01","1d ago"],["backup","Read-only","2024-01-10","Never"]])}),$.command("db:slow-queries <name>","Show slow query log").option("--limit <count>","Number of queries to show",{default:"10"}).action(async(J,Y)=>{let Q=Y?.limit||"10";V(`Slow Queries for ${J}`);let W=new M("Analyzing slow query log...");W.start(),await new Promise((U)=>setTimeout(U,2000)),W.stop(),G(`
1352
+ Top ${Q} slow queries:
1353
+ `),x(["Time","Duration","Query","Rows"],[["2h ago","2.34s","SELECT * FROM users WHERE...","15,234"],["3h ago","1.89s","SELECT * FROM orders JOIN...","8,456"],["5h ago","1.56s","UPDATE products SET...","3,289"]]),G(`
1354
+ Recommendations:`),G(" - Add index on users.email"),G(" - Optimize JOIN query with covering index"),G(" - Consider batching UPDATE operations")})}function O6($){$.command("logs","Stream all application logs").option("--tail","Tail logs in real-time").option("--filter <pattern>","Filter logs by pattern").option("--since <duration>","Show logs since duration (e.g., 1h, 30m)").action(async(J)=>{if(V("Application Logs"),J?.tail)G("Tailing logs... (Ctrl+C to stop)");G("2025-01-15 10:30:45 [INFO] Application started"),G("2025-01-15 10:30:46 [INFO] Connected to database")}),$.command("logs:server <name>","View server-specific logs").option("--tail","Tail logs in real-time").option("--since <duration>","Show logs since duration (e.g., 1h, 30m)").action(async(J,Y)=>{V(`Server Logs: ${J}`);let Q=Y?.since||"1h";if(G(`Fetching logs from the last ${Q}...`),Y?.tail)G(`Tailing logs... (Ctrl+C to stop)
1355
+ `);G("[2025-01-15 10:30:45] Server started"),G("[2025-01-15 10:30:46] Listening on port 3000"),G("[2025-01-15 10:30:47] Connected to database")}),$.command("logs:function <name>","View function-specific logs").option("--tail","Tail logs in real-time").option("--since <duration>","Show logs since duration (e.g., 1h, 30m)").action(async(J,Y)=>{V(`Function Logs: ${J}`);let Q=Y?.since||"1h";if(G(`Fetching logs from the last ${Q}...`),Y?.tail)G(`Tailing logs... (Ctrl+C to stop)
1356
+ `);G("[2025-01-15 10:30:45] START RequestId: abc123"),G("[2025-01-15 10:30:46] Processing event..."),G("[2025-01-15 10:30:47] END RequestId: abc123")}),$.command("metrics","View key metrics").action(async()=>{V("Metrics Dashboard"),G("CPU Usage: 45%"),G("Memory Usage: 62%"),G("Requests/min: 1,234"),G("Error Rate: 0.02%")}),$.command("metrics:dashboard","Open CloudWatch dashboard").option("--env <environment>","Environment (production, staging, development)").action(async(J)=>{V("Opening CloudWatch Dashboard");let Y=J?.env||"production",Q=new M("Generating dashboard URL...");Q.start(),await new Promise((W)=>setTimeout(W,1000)),Q.succeed("Dashboard URL generated"),A(`
1357
+ Opening dashboard in browser...`),G(`
1358
+ Dashboard URL:`),G(" https://console.aws.amazon.com/cloudwatch/home?region=us-east-1#dashboards:name=my-app-production")}),$.command("alarms","List all alarms").action(async()=>{V("CloudWatch Alarms"),x(["Name","Status","Condition","Environment"],[["high-cpu","OK","CPU > 80%","production"],["high-memory","ALARM","Memory > 90%","production"]])}),$.command("alarms:create","Create a new alarm").option("--name <name>","Alarm name").option("--metric <metric>","Metric to monitor (CPU, Memory, etc.)").option("--threshold <value>","Threshold value").option("--comparison <op>","Comparison operator (>, <, >=, <=)",{default:">"}).action(async(J)=>{if(V("Creating CloudWatch Alarm"),!J?.name||!J?.metric||!J?.threshold){_("Missing required options: --name, --metric, --threshold");return}let{name:Y,metric:Q,threshold:W}=J,U=J.comparison||">";G(`Alarm: ${Y}`),G(`Metric: ${Q}`),G(`Condition: ${Q} ${U} ${W}`);let Z=new M("Creating alarm...");Z.start(),await new Promise((z)=>setTimeout(z,2000)),Z.succeed("Alarm created successfully"),A(`
1359
+ Alarm is now active!`),G(`
1360
+ You will be notified when the condition is met`)})}function X6($){$.command("secrets:list","List all secrets").action(async()=>{V("Secrets"),x(["Name","Status"],[["database-password","Last rotated 30 days ago"],["api-key","Last rotated 15 days ago"]])}),$.command("secrets:set <key> <value>","Set a secret").action(async(J,Y)=>{V("Setting Secret");let Q=new M(`Storing secret ${J}...`);Q.start(),await new Promise((W)=>setTimeout(W,1000)),Q.succeed(`Secret ${J} stored successfully`),N("Secret value is encrypted and stored in AWS Secrets Manager")}),$.command("secrets:get <key>","Get secret value").action(async(J)=>{V("Getting Secret");let Y=new M(`Retrieving secret ${J}...`);Y.start(),await new Promise((Q)=>setTimeout(Q,1000)),Y.stop(),A(`
1361
+ Secret: ${J}`),G("Value: ************"),N(`
1362
+ Secret values are hidden for security`),G("To view the actual value, use AWS Console or AWS CLI with --query")})}function j6($){$.command("firewall:rules","List WAF rules").option("--env <environment>","Environment (production, staging, development)").action(async(J)=>{V("WAF Rules");let Y=J?.env||"production";G(`Environment: ${Y}
1363
+ `),x(["Rule","Priority","Action","Requests Blocked"],[["Rate Limit","1","Block","1,234"],["Geo Block (CN, RU)","2","Block","567"],["SQL Injection","3","Block","89"],["XSS Prevention","4","Block","23"]])}),$.command("firewall:block <ip>","Block an IP address").option("--reason <reason>","Reason for blocking").action(async(J,Y)=>{V("Blocking IP Address");let Q=Y?.reason||"Manual block";if(G(`IP: ${J}`),G(`Reason: ${Q}`),!await P(`
1364
+ Block this IP address?`,!0)){G("Operation cancelled");return}let U=new M("Adding IP to WAF block list...");U.start(),await new Promise((Z)=>setTimeout(Z,2000)),U.succeed(`IP ${J} blocked successfully`),A(`
1365
+ IP blocked!`),G("The IP address will be blocked within 60 seconds")}),$.command("firewall:unblock <ip>","Unblock an IP address").action(async(J)=>{if(V("Unblocking IP Address"),G(`IP: ${J}`),!await P(`
1366
+ Unblock this IP address?`,!0)){G("Operation cancelled");return}let Q=new M("Removing IP from WAF block list...");Q.start(),await new Promise((W)=>setTimeout(W,2000)),Q.succeed(`IP ${J} unblocked successfully`),A(`
1367
+ IP unblocked!`)}),$.command("firewall:countries","Manage geo-blocking").option("--add <countries>","Comma-separated country codes to block (e.g., CN,RU)").option("--remove <countries>","Comma-separated country codes to unblock").option("--list","List currently blocked countries").action(async(J)=>{if(V("Geo-Blocking Management"),J?.list)G(`Currently blocked countries:
1368
+ `),x(["Country Code","Country Name","Blocked Since"],[["CN","China","2024-01-15"],["RU","Russia","2024-01-15"],["KP","North Korea","2024-01-10"]]);else if(J?.add){let Y=J.add.split(",").map((U)=>U.trim().toUpperCase());if(G(`Countries to block: ${Y.join(", ")}`),!await P(`
1369
+ Block these countries?`,!0)){G("Operation cancelled");return}let W=new M("Updating geo-blocking rules...");W.start(),await new Promise((U)=>setTimeout(U,2000)),W.succeed("Geo-blocking rules updated"),A(`
1370
+ Countries blocked!`)}else if(J?.remove){let Y=J.remove.split(",").map((U)=>U.trim().toUpperCase());if(G(`Countries to unblock: ${Y.join(", ")}`),!await P(`
1371
+ Unblock these countries?`,!0)){G("Operation cancelled");return}let W=new M("Updating geo-blocking rules...");W.start(),await new Promise((U)=>setTimeout(U,2000)),W.succeed("Geo-blocking rules updated"),A(`
1372
+ Countries unblocked!`)}else G("Use --list, --add, or --remove options"),G("Example: cloud firewall:countries --add CN,RU")})}X0();function q6($){$.command("ssl:list","List all SSL certificates").option("--region <region>","AWS region (default: us-east-1)").action(async(J)=>{V("SSL Certificates");let Y=J?.region||"us-east-1",Q=new M("Fetching certificates from ACM...");Q.start();try{let W=new S$(Y),U=await W.listCertificates();if(U.CertificateSummaryList.length===0){Q.succeed("No certificates found"),G(`
1373
+ No SSL certificates found in region ${Y}`),G("Use 'cloud domain:ssl <domain>' to request a new certificate");return}let Z=await Promise.all(U.CertificateSummaryList.map(async(K)=>{return await W.describeCertificate({CertificateArn:K.CertificateArn})}));Q.succeed(`Found ${Z.length} certificate(s)`);let z=(K)=>{if(!K)return"N/A";let B=typeof K==="string"?Number.parseFloat(K):K,O=B<1000000000000?B*1000:B;return new Date(O).toISOString().split("T")[0]},H=Z.map((K)=>{let B=z(K.NotAfter),O=K.Type==="AMAZON_ISSUED"?"Amazon Issued":K.Type||"Unknown",X=K.Status==="ISSUED"?"Available":K.Status||"Unknown";return[K.DomainName,K.Status||"Unknown",B,O,X]});x(["Domain","Status","Expiry","Type","State"],H),G(`
1374
+ ACM certificates are automatically renewed by AWS`),G(`Region: ${Y}`)}catch(W){Q.fail("Failed to fetch certificates"),_(W.message)}}),$.command("ssl:renew <domain>","Renew SSL certificate").option("--region <region>","AWS region (default: us-east-1)").action(async(J,Y)=>{V(`Checking SSL Certificate for ${J}`);let Q=Y?.region||"us-east-1";G(`Domain: ${J}`),G(`Region: ${Q}`);let W=new M("Checking certificate status...");W.start();try{let Z=await new S$(Q).findCertificateByDomain(J);if(!Z){W.fail("Certificate not found"),_(`No certificate found for domain: ${J}`),G("Use 'cloud domain:ssl <domain>' to request a new certificate");return}W.succeed("Certificate found"),G(`
1375
+ Certificate is managed by AWS Certificate Manager`),G("ACM certificates are automatically renewed 60 days before expiry"),N(`
1376
+ No manual renewal needed for ACM certificates`);let z=(B)=>{if(!B)return"N/A";let O=typeof B==="string"?Number.parseFloat(B):B,X=O<1000000000000?O*1000:O;return new Date(X).toISOString().split("T")[0]},H=z(Z.NotAfter),K=z(Z.IssuedAt);if(G(`
1377
+ Certificate details:`),G(` - Domain: ${Z.DomainName}`),G(` - Status: ${Z.Status}`),G(` - Issued: ${K}`),G(` - Expiry: ${H}`),G(` - Type: ${Z.Type||"Unknown"}`),G(` - ARN: ${Z.CertificateArn}`),G(` - Auto-renewal: ${Z.Type==="AMAZON_ISSUED"?"Enabled":"N/A (imported)"}`),Z.SubjectAlternativeNames&&Z.SubjectAlternativeNames.length>1)G(` - SANs: ${Z.SubjectAlternativeNames.join(", ")}`)}catch(U){W.fail("Failed to check certificate"),_(U.message)}})}function V6($){$.command("cost","Show estimated monthly cost").option("--env <environment>","Environment (production, staging, development)").action(async(J)=>{let Y=J?.env||"production";V(`Cost Estimate - ${Y}`);let Q=new M("Fetching cost data from AWS Cost Explorer...");Q.start(),await new Promise((W)=>setTimeout(W,2000)),Q.stop(),G(`
1378
+ Current Month (Estimated):`),G(" Total: $247.89"),G(` Projected: $325.00
1379
+ `),x(["Service","Current","Projected","Change"],[["EC2","$89.23","$120.00","+12%"],["S3","$12.45","$15.00","+8%"],["CloudFront","$45.67","$60.00","+15%"],["RDS","$67.89","$90.00","+10%"],["Lambda","$8.23","$10.00","+5%"],["ElastiCache","$24.42","$30.00","+12%"]]),G("\nTip: Use `cloud cost:breakdown` for detailed analysis"),G("Tip: Use `cloud optimize` for cost-saving recommendations")}),$.command("cost:breakdown","Cost breakdown by service").option("--env <environment>","Environment (production, staging, development)").option("--days <days>","Number of days to analyze",{default:"30"}).action(async(J)=>{let Y=J?.env||"production",Q=J?.days||"30";V(`Cost Breakdown - ${Y} (Last ${Q} days)`);let W=new M("Analyzing cost data...");W.start(),await new Promise((U)=>setTimeout(U,2000)),W.stop(),G(`
1380
+ Top Services by Cost:
1381
+ `),x(["Service","Cost","% of Total","Trend"],[["EC2 Instances","$89.23","36%","^ +12%"],["RDS Databases","$67.89","27%","^ +10%"],["CloudFront","$45.67","18%","^ +15%"],["ElastiCache","$24.42","10%","^ +12%"],["S3 Storage","$12.45","5%","^ +8%"],["Lambda","$8.23","3%","^ +5%"]]),G(`
1382
+ Cost Trends:`),G(" - Overall trend: +10.5% vs last month"),G(" - Highest growth: CloudFront (+15%)"),G(" - Most stable: Lambda (+5%)"),G(`
1383
+ Recommendations:`),G(" - Consider Reserved Instances for EC2 (save up to 40%)"),G(" - Review CloudFront cache settings to reduce origin requests"),G(" - Use S3 Intelligent Tiering for automatic cost optimization")}),$.command("resources","List all resources").option("--env <environment>","Environment (production, staging, development)").option("--type <type>","Resource type (ec2, rds, s3, lambda, etc.)").action(async(J)=>{let Y=J?.env||"production",Q=J?.type;if(V(`Resources - ${Y}`),Q)G(`Filtering by type: ${Q}
1384
+ `);let W=new M("Scanning resources...");W.start(),await new Promise((U)=>setTimeout(U,2000)),W.stop(),G(`
1385
+ Resource Summary:
1386
+ `),x(["Type","Count","Running","Stopped","Total Cost/mo"],[["EC2 Instances","5","4","1","$89.23"],["RDS Databases","2","2","0","$67.89"],["S3 Buckets","12","-","-","$12.45"],["Lambda Functions","23","-","-","$8.23"],["CloudFront Distributions","3","-","-","$45.67"],["ElastiCache Clusters","1","1","0","$24.42"]]),G("\nTip: Use `cloud resources:unused` to find resources you can delete"),G("Tip: Use --type to filter by specific resource type")}),$.command("resources:unused","Find unused resources").option("--env <environment>","Environment (production, staging, development)").action(async(J)=>{let Y=J?.env||"production";V(`Unused Resources - ${Y}`);let Q=new M("Scanning for unused resources...");Q.start(),await new Promise((W)=>setTimeout(W,3000)),Q.stop(),G(`
1387
+ Potentially Unused Resources:
1388
+ `),x(["Resource","Type","Last Used","Monthly Cost","Recommendation"],[["staging-server-old","EC2","45 days ago","$28.50","Terminate"],["test-db-snapshot","RDS Snapshot","90 days ago","$5.20","Delete"],["old-assets-bucket","S3","Never","$2.30","Delete"],["dev-redis","ElastiCache","30 days ago","$18.00","Review"],["legacy-function","Lambda","60 days ago","$0.00","Delete"]]),G(`
1389
+ Potential Monthly Savings: $54.00`),N(`
1390
+ Please review before deleting any resources`),G("Tip: Create snapshots/backups before deleting databases or instances")}),$.command("optimize","Suggest cost optimizations").option("--env <environment>","Environment (production, staging, development)").action(async(J)=>{let Y=J?.env||"production";V(`Cost Optimization Recommendations - ${Y}`);let Q=new M("Analyzing infrastructure...");Q.start(),await new Promise((W)=>setTimeout(W,3000)),Q.stop(),G(`
1391
+ Top Recommendations:
1392
+ `),G("1. Use EC2 Reserved Instances"),G(" Current: On-Demand instances ($89/mo)"),G(" Potential: Reserved Instances ($54/mo)"),G(" Savings: $35/month (39%)"),G(`
1393
+ 2. Enable S3 Intelligent Tiering`),G(" Current: Standard storage ($12.45/mo)"),G(" Potential: Intelligent Tiering ($7.50/mo)"),G(" Savings: $4.95/month (40%)"),G(`
1394
+ 3. Right-size EC2 Instances`),G(" 2 instances are under-utilized (<20% CPU)"),G(" Recommended: Downgrade from t3.medium to t3.small"),G(" Savings: $18/month (20%)"),G(`
1395
+ 4. Delete Unused Resources`),G(" Found 5 unused resources"),G(" Savings: $54/month"),G(" Run: `cloud resources:unused` for details"),G(`
1396
+ 5. Use CloudFront Compression`),G(" Enable automatic compression for text files"),G(" Savings: ~$8/month (18% reduction in data transfer)"),A(`
1397
+ Total Potential Savings: $119.95/month (37%)`),G(`
1398
+ Next Steps:`),G(" - Run `cloud resources:unused` to review unused resources"),G(" - Run `cloud cost:breakdown` for detailed cost analysis"),G(" - Contact AWS support for Reserved Instance recommendations")})}function M6($){$.command("git:add <repo>","Connect git repository").option("--branch <branch>","Default branch to deploy",{default:"main"}).action(async(J,Y)=>{let Q=Y?.branch||"main";if(V("Connecting Git Repository"),G(`Repository: ${J}`),G(`Default branch: ${Q}`),!await P(`
1399
+ Connect this repository?`,!0)){G("Operation cancelled");return}let U=new M("Setting up git integration...");U.start(),await new Promise((Z)=>setTimeout(Z,2000)),U.succeed("Repository connected"),A(`
1400
+ Git repository connected!`),G(`
1401
+ Next steps:`),G(" - Deploy: cloud git:deploy main"),G(" - Add webhook: cloud git:webhook:add")}),$.command("git:deploy <branch>","Deploy from git branch").option("--env <environment>","Target environment").action(async(J,Y)=>{let Q=Y?.env||"production";if(V(`Deploying from Git: ${J}`),G(`Branch: ${J}`),G(`Environment: ${Q}`),!await P(`
1402
+ Deploy this branch?`,!0)){G("Operation cancelled");return}let U=new M("Pulling latest changes and deploying...");U.start(),await new Promise((Z)=>setTimeout(Z,4000)),U.succeed("Deployment complete"),A(`
1403
+ Deployed successfully!`),G(`Branch ${J} is now live on ${Q}`)}),$.command("git:webhook:add <repo>","Add webhook for auto-deploy").action(async(J)=>{V("Adding Deploy Webhook"),G(`Repository: ${J}`);let Y=new M("Creating webhook endpoint...");Y.start(),await new Promise((Q)=>setTimeout(Q,2000)),Y.succeed("Webhook created"),A(`
1404
+ Webhook endpoint created!`),G(`
1405
+ Webhook URL:`),G(" https://api.example.com/webhooks/deploy/abc123"),G(`
1406
+ Add this webhook to your repository:`),G(" - GitHub: Settings > Webhooks > Add webhook"),G(" - GitLab: Settings > Webhooks > Add webhook"),G(" - Event: Push events")}),$.command("git:webhook:remove <repo>","Remove webhook").action(async(J)=>{if(V("Removing Deploy Webhook"),G(`Repository: ${J}`),!await P(`
1407
+ Remove this webhook?`,!0)){G("Operation cancelled");return}let Q=new M("Removing webhook...");Q.start(),await new Promise((W)=>setTimeout(W,1500)),Q.succeed("Webhook removed"),A(`
1408
+ Webhook deleted!`)}),$.command("git:branches","List deployable branches").action(async()=>{V("Deployable Branches");let J=new M("Fetching branches...");J.start(),await new Promise((Y)=>setTimeout(Y,1500)),J.stop(),x(["Branch","Last Commit","Author","Deployed To"],[["main","2h ago","john@example.com","production"],["develop","30m ago","jane@example.com","staging"],["feature/new-ui","1d ago","bob@example.com","-"],["hotfix/bug-123","5h ago","alice@example.com","-"]]),G("\nTip: Deploy a branch with `cloud git:deploy <branch>`")})}function E6($){$.command("env:create <name>","Create new environment").option("--clone <source>","Clone from existing environment").action(async(J,Y)=>{V(`Creating Environment: ${J}`);let Q=["production","staging","development","preview","test"];if(!Q.includes(J.toLowerCase()))N("Warning: Creating non-standard environment name"),G(`Standard names: ${Q.join(", ")}`);if(Y?.clone)G(`Cloning from: ${Y.clone}`);if(!await P(`
1409
+ Create this environment?`,!0)){G("Operation cancelled");return}let U=new M("Creating environment infrastructure...");U.start(),await new Promise((Z)=>setTimeout(Z,3000)),U.succeed("Environment created successfully"),A(`
1410
+ Environment created!`),G(`Environment ${J} is now available`),G(`
1411
+ Next steps:`),G(` - Deploy to environment: cloud deploy --env ${J}`),G(` - Switch to environment: cloud env:switch ${J}`)}),$.command("env:list","List environments").action(async()=>{V("Environments");let J=new M("Fetching environments...");J.start(),await new Promise((Y)=>setTimeout(Y,1500)),J.stop(),x(["Environment","Status","Region","Last Deployed","Active"],[["production","Active","us-east-1","2 hours ago",""],["staging","Active","us-east-1","1 day ago","*"],["development","Active","us-west-2","3 days ago",""],["preview-pr-123","Active","us-east-1","5 hours ago",""]]),G("\nTip: Use `cloud env:switch NAME` to switch active environment"),G("Tip: Use `cloud env:create NAME` to create new environment")}),$.command("env:switch <name>","Switch active environment").action(async(J)=>{V(`Switching to Environment: ${J}`),G(`Switching to: ${J}`);let Y=new M("Updating environment configuration...");Y.start(),await new Promise((Q)=>setTimeout(Q,1000)),Y.succeed("Environment switched successfully"),A(`
1412
+ Now using environment: ${J}`),G(`All commands will now target the ${J} environment`),G(`
1413
+ Environment details:`),G(" - Region: us-east-1"),G(" - Status: Active"),G(" - Last deployed: 1 day ago")}),$.command("env:clone <source> <target>","Clone environment").action(async(J,Y)=>{if(V("Cloning Environment"),G(`Source: ${J}`),G(`Target: ${Y}`),N(`
1414
+ This will copy:`),G(" - Infrastructure configuration"),G(" - Environment variables"),G(" - Database schema (not data)"),!await P(`
1415
+ Clone environment?`,!0)){G("Operation cancelled");return}let W=new M("Cloning environment...");W.start(),await new Promise((U)=>setTimeout(U,5000)),W.succeed("Environment cloned"),A(`
1416
+ Environment ${Y} created from ${J}!`),G("Deploy with: cloud deploy --env "+Y)}),$.command("env:promote <source> <target>","Promote environment").action(async(J,Y)=>{if(V("Promoting Environment"),G(`From: ${J}`),G(`To: ${Y}`),N(`
1417
+ This will:`),G(" - Deploy code from source to target"),G(" - Update target configuration"),G(" - Run database migrations if any"),!await P(`
1418
+ Promote to `+Y+"?",!1)){G("Operation cancelled");return}let W=new M("Promoting environment...");W.start(),await new Promise((U)=>setTimeout(U,6000)),W.succeed("Promotion complete"),A(`
1419
+ ${J} promoted to ${Y}!`)}),$.command("env:compare <env1> <env2>","Compare configurations").action(async(J,Y)=>{V("Comparing Environments"),G(`Environment 1: ${J}`),G(`Environment 2: ${Y}`);let Q=new M("Analyzing configurations...");Q.start(),await new Promise((W)=>setTimeout(W,2000)),Q.stop(),G(`
1420
+ Configuration Differences:
1421
+ `),x(["Setting",J,Y,"Match"],[["Instance Type","t3.medium","t3.small","X"],["Database Size","db.t3.medium","db.t3.micro","X"],["Auto Scaling","Enabled","Disabled","X"],["Region","us-east-1","us-east-1","*"],["Node Version","20.x","20.x","*"]]),G(`
1422
+ Found 3 differences`)}),$.command("env:sync <source> <target>","Sync configuration").action(async(J,Y)=>{if(V("Syncing Configuration"),G(`Source: ${J}`),G(`Target: ${Y}`),N(`
1423
+ This will sync configuration (not resources or data)`),!await P(`
1424
+ Sync configuration?`,!0)){G("Operation cancelled");return}let W=new M("Syncing configuration...");W.start(),await new Promise((U)=>setTimeout(U,2000)),W.succeed("Configuration synced"),A(`
1425
+ Configuration synchronized!`)}),$.command("env:preview <branch>","Create preview environment from branch").action(async(J)=>{V(`Creating Preview Environment for ${J}`);let Y=`preview-${J.replace(/[^a-z0-9]/gi,"-").toLowerCase()}`;if(G(`Environment name: ${Y}`),G(`Branch: ${J}`),!await P(`
1426
+ Create preview environment?`,!0)){G("Operation cancelled");return}let W=new M("Creating preview environment...");W.start(),await new Promise((U)=>setTimeout(U,8000)),W.succeed("Preview environment created"),A(`
1427
+ Preview environment ready!`),G(`URL: https://${Y}.preview.example.com`),G(`
1428
+ This environment will auto-delete after 7 days`)}),$.command("env:cleanup","Remove stale preview environments").action(async()=>{V("Cleaning Up Preview Environments");let J=new M("Finding stale preview environments...");if(J.start(),await new Promise((W)=>setTimeout(W,2000)),J.stop(),G(`
1429
+ Found 3 stale preview environments:
1430
+ `),x(["Environment","Created","Age","Status"],[["preview-feature-123","2024-10-15","30 days","Inactive"],["preview-bugfix-456","2024-10-20","25 days","Inactive"],["preview-test-789","2024-11-01","14 days","Inactive"]]),!await P(`
1431
+ Delete these environments?`,!0)){G("Operation cancelled");return}let Q=new M("Deleting stale environments...");Q.start(),await new Promise((W)=>setTimeout(W,4000)),Q.succeed("Cleanup complete"),A(`
1432
+ 3 preview environments deleted!`),G("Estimated monthly savings: $87")})}import{existsSync as MW}from"node:fs";V0();M0();function w6($){$.command("assets:build","Build assets").option("--minify","Minify output").option("--compress","Compress output").action(async(J)=>{V("Building Assets");let Y=J?.minify||!1,Q=J?.compress||!1;G("Build configuration:"),G(` - Minify: ${Y?"Yes":"No"}`),G(` - Compress: ${Q?"Yes":"No"}`);let W=new M("Building assets...");W.start(),await new Promise((U)=>setTimeout(U,4000)),W.succeed("Assets built successfully"),A(`
1433
+ Build complete!`),G(`
1434
+ Output:`),G(" - JS: 2.3 MB > 456 KB (80% reduction)"),G(" - CSS: 890 KB > 123 KB (86% reduction)"),G(" - Images: 15.2 MB > 8.9 MB (41% reduction)"),G(`
1435
+ Build directory: ./dist`)}),$.command("assets:optimize:images","Optimize images").option("--quality <quality>","Image quality (1-100)",{default:"85"}).action(async(J)=>{let Y=J?.quality||"85";V("Optimizing Images"),G(`Quality: ${Y}%`);let Q=new M("Optimizing images...");Q.start(),await new Promise((W)=>setTimeout(W,3000)),Q.succeed("Images optimized"),A(`
1436
+ Optimization complete!`),G(`
1437
+ Results:`),G(" - Processed: 127 images"),G(" - Original: 15.2 MB"),G(" - Optimized: 8.9 MB"),G(" - Savings: 6.3 MB (41%)")}),$.command("images:optimize","Optimize and compress images").option("--dir <directory>","Directory to optimize",{default:"./public/images"}).action(async(J)=>{let Y=J?.dir||"./public/images";V("Optimizing Images"),G(`Directory: ${Y}`);let Q=new M("Optimizing images...");Q.start(),await new Promise((W)=>setTimeout(W,3000)),Q.succeed("Images optimized"),A(`
1438
+ Optimization complete!`),G(`
1439
+ Results:`),G(" - PNG: 45 files, 3.2 MB > 1.8 MB (44% savings)"),G(" - JPG: 82 files, 12.0 MB > 7.1 MB (41% savings)"),G(" - Total savings: 6.3 MB")}),$.command("assets:deploy","Deploy static assets to S3").option("--source <path>","Source directory",{default:"dist"}).option("--bucket <name>","S3 bucket name").option("--prefix <prefix>","S3 prefix/folder").option("--delete","Delete files not in source").option("--cache-control <value>","Cache-Control header",{default:"public, max-age=31536000"}).action(async(J)=>{V("Deploying Assets to S3");try{let Q=(await g()).project.region||"us-east-1",W=J?.source||"dist",U=J?.bucket,Z=J?.prefix,z=J?.delete||!1,H=J?.cacheControl||"public, max-age=31536000";if(!U){_("--bucket is required");return}if(!MW(W)){_(`Source directory not found: ${W}`);return}if(G(`Source: ${W}`),G(`Bucket: s3://${U}${Z?`/${Z}`:""}`),G(`Cache-Control: ${H}`),z)N("Delete mode enabled - files not in source will be removed");if(!await P(`
1440
+ Deploy assets now?`,!0)){G("Deployment cancelled");return}let B=new X$(Q),O=new M("Uploading assets to S3...");O.start(),await B.sync({source:W,bucket:U,prefix:Z,delete:z,cacheControl:H,acl:"public-read"}),O.succeed("Assets deployed successfully!");let j=(await B.getBucketSize(U,Z)/1024/1024).toFixed(2);A(`
1441
+ Deployment complete!`),G(`Total size: ${j} MB`),G(`
1442
+ Assets URL: https://${U}.s3.${Q}.amazonaws.com${Z?`/${Z}`:""}`)}catch(Y){_(`Deployment failed: ${Y.message}`)}}),$.command("assets:invalidate","Invalidate CloudFront cache").option("--distribution <id>","CloudFront distribution ID").option("--paths <paths>","Paths to invalidate (comma-separated)",{default:"/*"}).option("--wait","Wait for invalidation to complete").action(async(J)=>{V("Invalidating CloudFront Cache");try{let Y=J?.distribution;if(!Y){_("--distribution is required");return}let W=(J?.paths||"/*").split(",").map((B)=>B.trim()),U=J?.wait||!1;if(G(`Distribution: ${Y}`),G(`Paths: ${W.join(", ")}`),!await P(`
1443
+ Invalidate cache now?`,!0)){G("Invalidation cancelled");return}let z=new j$,H=new M("Creating invalidation...");H.start();let K=await z.invalidatePaths(Y,W);if(H.succeed("Invalidation created"),A(`
1444
+ Invalidation ID: ${K.Id}`),G(`Status: ${K.Status}`),G(`Created: ${new Date(K.CreateTime).toLocaleString()}`),U){let B=new M("Waiting for invalidation to complete...");B.start(),await z.waitForInvalidation(Y,K.Id),B.succeed("Invalidation completed!")}else G(`
1445
+ Invalidation is in progress. Use --wait to wait for completion.`)}catch(Y){_(`Invalidation failed: ${Y.message}`)}})}function T6($){$.command("team:add <email> <role>","Add team member").action(async(J,Y)=>{V("Adding Team Member"),G(`Email: ${J}`),G(`Role: ${Y}`);let Q=["admin","developer","viewer"];if(!Q.includes(Y.toLowerCase())){_(`Invalid role. Must be one of: ${Q.join(", ")}`);return}if(!await P(`
1446
+ Add this team member?`,!0)){G("Operation cancelled");return}let U=new M("Creating IAM user and sending invitation...");U.start(),await new Promise((Z)=>setTimeout(Z,2000)),U.succeed("Team member added successfully"),A(`
1447
+ Team member added!`),G("An invitation email has been sent with access credentials"),G(`
1448
+ Access Details:`),G(` - Email: ${J}`),G(` - Role: ${Y}`),G(" - Status: Pending")}),$.command("team:list","List team members").action(async()=>{V("Team Members");let J=new M("Fetching team members...");J.start(),await new Promise((Y)=>setTimeout(Y,1500)),J.stop(),x(["Email","Role","Status","Added","Last Login"],[["admin@example.com","Admin","Active","2024-01-01","2 hours ago"],["dev@example.com","Developer","Active","2024-01-15","1 day ago"],["viewer@example.com","Viewer","Active","2024-02-01","3 days ago"],["new@example.com","Developer","Pending","2024-11-10","Never"]]),G("\nTip: Use `cloud team:add` to add new team members"),G("Tip: Use `cloud team:remove` to remove team members")}),$.command("team:remove <email>","Remove team member").action(async(J)=>{if(V("Removing Team Member"),G(`Email: ${J}`),N(`
1449
+ This will revoke all access for this team member`),!await P("Remove this team member?",!1)){G("Operation cancelled");return}let Q=new M("Removing IAM user and access...");Q.start(),await new Promise((W)=>setTimeout(W,2000)),Q.succeed("Team member removed successfully"),A(`
1450
+ Team member removed!`),G("All access credentials have been revoked")})}import{existsSync as m1}from"node:fs";G0();V0();M0();W$();class L6{client;region;constructor($="us-east-1",J){this.region=$,this.client=new l}async createRepository($){let J={repositoryName:$.repositoryName};if($.imageTagMutability)J.imageTagMutability=$.imageTagMutability;if($.imageScanningConfiguration)J.imageScanningConfiguration=$.imageScanningConfiguration;if($.encryptionConfiguration)J.encryptionConfiguration=$.encryptionConfiguration;if($.tags&&$.tags.length>0)J.tags=$.tags;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.CreateRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{repository:Y.repository?this.parseRepository(Y.repository):void 0}}async describeRepositories($){let J={};if($?.repositoryNames&&$.repositoryNames.length>0)J.repositoryNames=$.repositoryNames;if($?.registryId)J.registryId=$.registryId;if($?.maxResults)J.maxResults=$.maxResults;if($?.nextToken)J.nextToken=$.nextToken;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeRepositories","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{repositories:Y.repositories?.map((Q)=>this.parseRepository(Q)),nextToken:Y.nextToken}}async getAuthorizationToken($){let J={};if($&&$.length>0)J.registryIds=$;return{authorizationData:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetAuthorizationToken","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})).authorizationData?.map((Q)=>({authorizationToken:Q.authorizationToken,expiresAt:Q.expiresAt,proxyEndpoint:Q.proxyEndpoint}))}}async deleteRepository($){let J={repositoryName:$.repositoryName};if($.registryId)J.registryId=$.registryId;if($.force!==void 0)J.force=$.force;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DeleteRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{repository:Y.repository?this.parseRepository(Y.repository):void 0}}async describeImages($){let J={repositoryName:$.repositoryName};if($.registryId)J.registryId=$.registryId;if($.imageIds&&$.imageIds.length>0)J.imageIds=$.imageIds;if($.filter)J.filter=$.filter;if($.maxResults)J.maxResults=$.maxResults;if($.nextToken)J.nextToken=$.nextToken;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeImages","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{imageDetails:Y.imageDetails?.map((Q)=>this.parseImageDetail(Q)),nextToken:Y.nextToken}}async batchDeleteImage($){let J={repositoryName:$.repositoryName,imageIds:$.imageIds};if($.registryId)J.registryId=$.registryId;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.BatchDeleteImage","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{imageIds:Y.imageIds,failures:Y.failures}}async putLifecyclePolicy($){let J={repositoryName:$.repositoryName,lifecyclePolicyText:$.lifecyclePolicyText};if($.registryId)J.registryId=$.registryId;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.PutLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{registryId:Y.registryId,repositoryName:Y.repositoryName,lifecyclePolicyText:Y.lifecyclePolicyText}}async getLifecyclePolicy($){let J={repositoryName:$.repositoryName};if($.registryId)J.registryId=$.registryId;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{registryId:Y.registryId,repositoryName:Y.repositoryName,lifecyclePolicyText:Y.lifecyclePolicyText,lastEvaluatedAt:Y.lastEvaluatedAt}}async setRepositoryPolicy($){let J={repositoryName:$.repositoryName,policyText:$.policyText};if($.registryId)J.registryId=$.registryId;if($.force!==void 0)J.force=$.force;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.SetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{registryId:Y.registryId,repositoryName:Y.repositoryName,policyText:Y.policyText}}async getRepositoryPolicy($){let J={repositoryName:$.repositoryName};if($.registryId)J.registryId=$.registryId;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{registryId:Y.registryId,repositoryName:Y.repositoryName,policyText:Y.policyText}}async tagResource($){let J={resourceArn:$.resourceArn,tags:$.tags};await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listTagsForResource($){let J={resourceArn:$};return{tags:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})).tags}}createLifecyclePolicyText($){return JSON.stringify({rules:$.map((J)=>({rulePriority:J.rulePriority,description:J.description,selection:J.selection,action:J.action}))})}async getDockerLoginCommand(){let $=await this.getAuthorizationToken();if(!$.authorizationData?.[0])throw Error("Failed to get authorization token");let J=$.authorizationData[0],Y=J.authorizationToken||"",Q=J.proxyEndpoint||"";return`echo "${Buffer.from(Y,"base64").toString("utf8").split(":")[1]}" | docker login --username AWS --password-stdin ${Q}`}getRegistryUri($){return`${$}.dkr.ecr.${this.region}.amazonaws.com`}parseRepository($){return{repositoryArn:$.repositoryArn,registryId:$.registryId,repositoryName:$.repositoryName,repositoryUri:$.repositoryUri,createdAt:$.createdAt,imageTagMutability:$.imageTagMutability,imageScanningConfiguration:$.imageScanningConfiguration,encryptionConfiguration:$.encryptionConfiguration}}parseImageDetail($){return{registryId:$.registryId,repositoryName:$.repositoryName,imageDigest:$.imageDigest,imageTags:$.imageTags,imageSizeInBytes:$.imageSizeInBytes,imagePushedAt:$.imagePushedAt,imageScanStatus:$.imageScanStatus,imageScanFindingsSummary:$.imageScanFindingsSummary}}}W$();class A6{client;region;constructor($="us-east-1",J){this.region=$,this.client=new l}async describeServices($){let J={cluster:$.cluster,services:$.services};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeServices","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listServices($){let J={cluster:$};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListServices","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listTasks($,J){let Y={cluster:$};if(J)Y.serviceName=J;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListTasks","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(Y)})}async describeTasks($,J){let Y={cluster:$,tasks:J};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeTasks","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(Y)})}async updateService($){let J={cluster:$.cluster,service:$.service};if($.forceNewDeployment!==void 0)J.forceNewDeployment=$.forceNewDeployment;if($.desiredCount!==void 0)J.desiredCount=$.desiredCount;if($.taskDefinition)J.taskDefinition=$.taskDefinition;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.UpdateService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async createService($){let J={cluster:$.cluster,serviceName:$.serviceName,taskDefinition:$.taskDefinition,desiredCount:$.desiredCount};if($.launchType)J.launchType=$.launchType;if($.networkConfiguration)J.networkConfiguration=$.networkConfiguration;if($.loadBalancers)J.loadBalancers=$.loadBalancers;if($.healthCheckGracePeriodSeconds!==void 0)J.healthCheckGracePeriodSeconds=$.healthCheckGracePeriodSeconds;if($.deploymentConfiguration)J.deploymentConfiguration=$.deploymentConfiguration;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.CreateService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async deleteService($){let J={cluster:$.cluster,service:$.service};if($.force!==void 0)J.force=$.force;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DeleteService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listClusters(){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListClusters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({})})}async describeClusters($){let J={clusters:$,include:["ATTACHMENTS","CONFIGURATIONS","SETTINGS","STATISTICS","TAGS"]};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeClusters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async stopTask($){let J={cluster:$.cluster,task:$.task};if($.reason)J.reason=$.reason;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.StopTask","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async runTask($){let J={cluster:$.cluster,taskDefinition:$.taskDefinition};if($.count!==void 0)J.count=$.count;if($.launchType)J.launchType=$.launchType;if($.networkConfiguration)J.networkConfiguration=$.networkConfiguration;if($.overrides)J.overrides=$.overrides;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.RunTask","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async registerTaskDefinition($){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.RegisterTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify($)})}async deregisterTaskDefinition($){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DeregisterTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({taskDefinition:$})})}async describeTaskDefinition($){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({taskDefinition:$,include:["TAGS"]})})}async listTaskDefinitionFamilies($){let J={};if($?.familyPrefix)J.familyPrefix=$.familyPrefix;if($?.status)J.status=$.status;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListTaskDefinitionFamilies","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async waitForServiceStable($,J,Y=40,Q=15000){for(let W=0;W<Y;W++){let Z=(await this.describeServices({cluster:$,services:[J]})).services?.[0];if(Z){let z=Z.deployments?.find((H)=>H.status==="PRIMARY");if(z&&z.runningCount===z.desiredCount&&Z.deployments?.length===1)return!0}await new Promise((z)=>setTimeout(z,Q))}return!1}async forceNewDeployment($,J){return this.updateService({cluster:$,service:J,forceNewDeployment:!0})}async scaleService($,J,Y){return this.updateService({cluster:$,service:J,desiredCount:Y})}}P6();import{existsSync as wW,readdirSync as TW,readFileSync as LW,statSync as AW}from"node:fs";import{join as RW,relative as SW,extname as DW}from"node:path";var PW=[{name:"AWS Access Key ID",pattern:/(?:^|[^A-Z0-9])((AKIA|ABIA|ACCA|ASIA)[A-Z0-9]{16})(?:[^A-Z0-9]|$)/g,severity:"critical",description:"AWS Access Key ID detected"},{name:"AWS Secret Access Key",pattern:/(?:aws_secret_access_key|aws_secret_key|secret_access_key|secretAccessKey)\s*[=:]\s*['"]?([A-Za-z0-9/+=]{40})['"]?/gi,severity:"critical",description:"AWS Secret Access Key detected"},{name:"AWS Secret Key (Generic)",pattern:/(?:^|['"`:=\s])([A-Za-z0-9/+=]{40})(?:['"`\s]|$)/g,severity:"high",description:"Potential AWS Secret Key (40-char base64)"},{name:"Generic API Key",pattern:/(?:api[_-]?key|apikey|api[_-]?secret)\s*[=:]\s*['"]?([A-Za-z0-9_\-]{20,})['"]?/gi,severity:"high",description:"Generic API key detected"},{name:"RSA Private Key",pattern:/-----BEGIN RSA PRIVATE KEY-----/g,severity:"critical",description:"RSA private key detected"},{name:"OpenSSH Private Key",pattern:/-----BEGIN OPENSSH PRIVATE KEY-----/g,severity:"critical",description:"OpenSSH private key detected"},{name:"EC Private Key",pattern:/-----BEGIN EC PRIVATE KEY-----/g,severity:"critical",description:"EC private key detected"},{name:"PGP Private Key",pattern:/-----BEGIN PGP PRIVATE KEY BLOCK-----/g,severity:"critical",description:"PGP private key detected"},{name:"GitHub Token",pattern:/(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,}/g,severity:"critical",description:"GitHub personal access token detected"},{name:"GitHub OAuth",pattern:/github[_-]?oauth[_-]?token\s*[=:]\s*['"]?([A-Za-z0-9_]{40})['"]?/gi,severity:"critical",description:"GitHub OAuth token detected"},{name:"Slack Token",pattern:/xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*/g,severity:"critical",description:"Slack token detected"},{name:"Slack Webhook",pattern:/https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]+/g,severity:"high",description:"Slack webhook URL detected"},{name:"Discord Webhook",pattern:/https:\/\/discord(?:app)?\.com\/api\/webhooks\/[0-9]+\/[A-Za-z0-9_-]+/g,severity:"high",description:"Discord webhook URL detected"},{name:"JWT Token",pattern:/eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*/g,severity:"high",description:"JWT token detected"},{name:"Google API Key",pattern:/AIza[0-9A-Za-z_-]{35}/g,severity:"critical",description:"Google API key detected"},{name:"Google OAuth ID",pattern:/[0-9]+-[A-Za-z0-9_]{32}\.apps\.googleusercontent\.com/g,severity:"high",description:"Google OAuth client ID detected"},{name:"Firebase API Key",pattern:/(?:firebase[_-]?api[_-]?key)\s*[=:]\s*['"]?([A-Za-z0-9_-]{39})['"]?/gi,severity:"critical",description:"Firebase API key detected"},{name:"Cloudflare API Token",pattern:/(?:cloudflare[_-]?api[_-]?token|cf[_-]?api[_-]?token)\s*[=:]\s*['"]?([A-Za-z0-9_-]{40})['"]?/gi,severity:"critical",description:"Cloudflare API token detected"},{name:"Azure Client Secret",pattern:/(?:azure[_-]?client[_-]?secret|client[_-]?secret)\s*[=:]\s*['"]?([A-Za-z0-9~._-]{34,})['"]?/gi,severity:"critical",description:"Azure client secret detected"},{name:"Heroku API Key",pattern:/(?:heroku[_-]?api[_-]?key)\s*[=:]\s*['"]?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})['"]?/gi,severity:"critical",description:"Heroku API key detected"},{name:"Database Connection String",pattern:/(?:mysql|postgres|postgresql|mongodb|redis|mongodb\+srv):\/\/[^:]+:[^@]+@[^/\s]+/gi,severity:"critical",description:"Database connection string with credentials detected"},{name:"Database Password",pattern:/(?:db[_-]?password|database[_-]?password|mysql[_-]?password|postgres[_-]?password)\s*[=:]\s*['"]?([^'"\s]{8,})['"]?/gi,severity:"critical",description:"Database password detected"},{name:"Stripe API Key",pattern:/(?:sk|pk)_(?:test|live)_[0-9a-zA-Z]{24,}/g,severity:"critical",description:"Stripe API key detected"},{name:"PayPal Client ID",pattern:/(?:paypal[_-]?client[_-]?id)\s*[=:]\s*['"]?([A-Za-z0-9_-]{80})['"]?/gi,severity:"high",description:"PayPal client ID detected"},{name:"Square Access Token",pattern:/sq0[a-z]{3}-[0-9A-Za-z_-]{22,}/g,severity:"critical",description:"Square access token detected"},{name:"Twilio API Key",pattern:/SK[a-f0-9]{32}/g,severity:"critical",description:"Twilio API key detected"},{name:"SendGrid API Key",pattern:/SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}/g,severity:"critical",description:"SendGrid API key detected"},{name:"Mailgun API Key",pattern:/key-[0-9a-zA-Z]{32}/g,severity:"critical",description:"Mailgun API key detected"},{name:"Password in Code",pattern:/(?:password|passwd|pwd)\s*[=:]\s*['"]([^'"]{8,})['"](?!\s*[,\]])/gi,severity:"high",description:"Hardcoded password detected"},{name:"Secret/Token Assignment",pattern:/(?:secret|token|auth[_-]?token|access[_-]?token)\s*[=:]\s*['"]([A-Za-z0-9_\-/+=]{16,})['"](?!\s*[,\]])/gi,severity:"high",description:"Hardcoded secret or token detected"},{name:"NPM Token",pattern:/(?:npm[_-]?token)\s*[=:]\s*['"]?([A-Za-z0-9_-]{36})['"]?/gi,severity:"critical",description:"NPM token detected"},{name:"SSH Private Key Path Exposed",pattern:/~\/\.ssh\/id_[a-z]+|\/home\/[^/]+\/\.ssh\/id_[a-z]+/g,severity:"medium",description:"SSH private key path exposed"},{name:"Env Variable with Secret",pattern:/(?:process\.env\.)([A-Z_]*(?:SECRET|KEY|TOKEN|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)\s*(?:===?\s*['"]([^'"]+)['"])?/g,severity:"medium",description:"Environment variable containing secret may be exposed"}],CW=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".vue",".svelte",".html",".htm",".css",".scss",".less",".json",".yaml",".yml",".toml",".xml",".env",".config",".conf"],NW=["node_modules",".git",".svn",".hg","dist","build","coverage",".nyc_output","__pycache__",".pytest_cache","vendor",".idea",".vscode",".turbo",".next",".nuxt"],kW=["package-lock.json","yarn.lock","pnpm-lock.yaml","bun.lockb","*.min.js","*.min.css","*.map"];class N6{patterns;excludeDirs;excludeFiles;maxFileSize;constructor($){this.patterns=[...PW,...$?.customPatterns||[]],this.excludeDirs=[...NW,...$?.excludeDirs||[]],this.excludeFiles=[...kW,...$?.excludeFiles||[]],this.maxFileSize=$?.maxFileSize||1048576}async scan($){let J=Date.now(),Y=[],Q=0,{directory:W,exclude:U=[],include:Z,skipPatterns:z=[]}=$,H=$.failOnSeverity||"critical";if(!wW(W))throw Error(`Directory not found: ${W}`);let K=this.getFilesToScan(W,[...this.excludeDirs,...U],Z);for(let q of K){let E=SW(W,q);if(this.shouldExcludeFile(E))continue;try{if(AW(q).size>this.maxFileSize)continue;let w=LW(q,"utf-8"),T=this.scanContent(w,E,z);Y.push(...T),Q++}catch{continue}}let B={critical:Y.filter((q)=>q.pattern.severity==="critical").length,high:Y.filter((q)=>q.pattern.severity==="high").length,medium:Y.filter((q)=>q.pattern.severity==="medium").length,low:Y.filter((q)=>q.pattern.severity==="low").length},O=["low","medium","high","critical"],X=O.indexOf(H),j=!0;for(let q=X;q<O.length;q++)if(B[O[q]]>0){j=!1;break}return{passed:j,findings:Y,scannedFiles:Q,duration:Date.now()-J,summary:B}}scanContent($,J,Y){let Q=[],W=$.split(`
1451
+ `);for(let U of this.patterns){if(Y.includes(U.name))continue;U.pattern.lastIndex=0;let Z;while((Z=U.pattern.exec($))!==null){let z=$.substring(0,Z.index),H=z.split(`
1452
+ `).length,K=z.lastIndexOf(`
1453
+ `),B=Z.index-K,O=W[H-1]||"";if(this.isLikelyPlaceholder(Z[0],O))continue;Q.push({file:J,line:H,column:B,match:this.maskSecret(Z[0]),pattern:U,context:this.maskSecret(O.trim())})}}return Q}isLikelyPlaceholder($,J){let Y=["example","placeholder","your_","YOUR_","xxx","XXX","***","test","TEST","dummy","DUMMY","fake","FAKE","sample","SAMPLE","<your","${","{{","process.env","import.meta.env","CHANGEME","TODO","FIXME"],Q=$.toLowerCase(),W=J.toLowerCase();for(let Z of Y)if(Q.includes(Z.toLowerCase())||W.includes(Z.toLowerCase()))return!0;let U=J.trim();if(U.startsWith("//")||U.startsWith("#")||U.startsWith("*")||U.startsWith("/*")){if(W.includes("example")||W.includes("format:")||W.includes("e.g."))return!0}return!1}maskSecret($){if($.length<=8)return"*".repeat($.length);let J=Math.min(4,Math.floor($.length*0.2));return $.substring(0,J)+"*".repeat($.length-J*2)+$.substring($.length-J)}getFilesToScan($,J,Y){let Q=[],W=Y||CW,U=(Z)=>{let z=TW(Z,{withFileTypes:!0});for(let H of z){let K=RW(Z,H.name);if(H.isDirectory()){if(!J.includes(H.name))U(K)}else if(H.isFile()){let B=DW(H.name).toLowerCase();if(W.includes(B)||H.name.startsWith(".env")||H.name.endsWith(".config"))Q.push(K)}}};return U($),Q}shouldExcludeFile($){let J=$.split("/").pop()||"";for(let Y of this.excludeFiles)if(Y.startsWith("*")){let Q=Y.substring(1);if(J.endsWith(Q))return!0}else if(J===Y)return!0;return!1}addPattern($){this.patterns.push($)}getPatterns(){return[...this.patterns]}}async function u1($){let J=new N6;r("Running pre-deployment security scan...");let Y=await J.scan({directory:$.sourceDir,failOnSeverity:$.failOnSeverity||"critical",skipPatterns:$.skipPatterns});return{passed:Y.passed,result:Y}}function d1($){let{summary:J,findings:Y,scannedFiles:Q,duration:W}=$;if(G(`
1454
+ Scanned ${Q} files in ${W}ms`),J.critical>0)_(` Critical: ${J.critical}`);else G(` Critical: ${J.critical}`);if(J.high>0)N(` High: ${J.high}`);else G(` High: ${J.high}`);if(G(` Medium: ${J.medium}`),G(` Low: ${J.low}`),Y.length>0){G(`
1455
+ Findings:`);let U=Y.filter((B)=>B.pattern.severity==="critical"),Z=Y.filter((B)=>B.pattern.severity==="high"),z=Y.filter((B)=>B.pattern.severity==="medium"),H=Y.filter((B)=>B.pattern.severity==="low"),K=(B,O,X)=>{if(B.length>0){console.log(`
1456
+ ${L0(`[${O}]`,X)}`);for(let j of B.slice(0,10))G(` ${j.pattern.name}`),G(` File: ${j.file}:${j.line}`),G(` Match: ${j.match}`);if(B.length>10)G(` ... and ${B.length-10} more ${O.toLowerCase()} findings`)}};K(U,"CRITICAL","red"),K(Z,"HIGH","yellow"),K(z,"MEDIUM","blue"),K(H,"LOW","gray")}}function k6($){$.command("deploy:security-scan","Run pre-deployment security scan").option("--source <path>","Source directory to scan",{default:"."}).option("--fail-on <severity>","Fail on severity level (critical, high, medium, low)",{default:"critical"}).option("--skip-patterns <patterns>","Comma-separated list of pattern names to skip").action(async(J)=>{V("Pre-Deployment Security Scan");try{let Y=J?.source||".",Q=J?.failOn||"critical",W=J?.skipPatterns?.split(",").map((z)=>z.trim())||[];if(!m1(Y)){_(`Source directory not found: ${Y}`);return}G(`Source: ${Y}`),G(`Fail on: ${Q} or higher severity`);let{passed:U,result:Z}=await u1({sourceDir:Y,failOnSeverity:Q,skipPatterns:W});if(d1(Z),U)A(`
1457
+ ✓ Security scan passed - no blocking issues found`);else _(`
1458
+ ✗ Security scan failed - blocking issues detected`),G(`
1459
+ Recommendations:`),G(" 1. Remove any hardcoded credentials from your code"),G(" 2. Use environment variables or AWS Secrets Manager"),G(" 3. Add sensitive files to .gitignore"),G(" 4. Use --skip-patterns to ignore false positives"),process.exit(1)}catch(Y){_(`Security scan failed: ${Y.message}`),process.exit(1)}}),$.command("deploy","Deploy infrastructure").option("--stack <name>","Stack name").option("--env <environment>","Environment to deploy to").option("--site <name>","Deploy specific site only").option("--skip-security-scan","Skip pre-deployment security scan").option("--skip-dns-verification","Skip DNS provider verification and record creation (use when DNS is already configured)").option("--security-fail-on <severity>","Security scan fail threshold (critical, high, medium, low)",{default:"critical"}).action(async(J)=>{V("Deploying Infrastructure");try{let Y=await g();if(!J?.skipSecurityScan){let R=process.cwd(),{passed:C,result:D}=await u1({sourceDir:R,failOnSeverity:J?.securityFailOn||"critical"});if(d1(D),!C){_(`
1460
+ ✗ Security scan failed - deployment blocked`),G(`
1461
+ To proceed anyway, use --skip-security-scan flag`),G("To change sensitivity, use --security-fail-on <severity>");return}A(`✓ Security scan passed
1462
+ `)}else N(`Security scan skipped (--skip-security-scan)
1463
+ `);let Q=J?.env||"staging",W=J?.stack||`${Y.project.slug}-${Q}`,U=Y.project.region||"us-east-1";if(Y.sites&&Object.keys(Y.sites).length>0){let R=Y.infrastructure?.dns?.provider;if(R&&R!=="route53"){await IW(Y,J?.site,R,U,J?.skipDnsVerification);return}}G(`Stack: ${W}`),G(`Region: ${U}`),G(`Environment: ${Q}`),r("Generating CloudFormation template...");let Z=new g0({config:Y,environment:Q});Z.generate();let z=Z.toJSON(),H=JSON.parse(z);r("Validating template...");let K=v1(H),B=f1(z),O=g1(H),X=[...K.errors,...B.errors,...O.errors];if(X.length>0){_("Template validation failed:");for(let R of X)_(` - ${R.path}: ${R.message}`);return}let j=[...K.warnings,...B.warnings,...O.warnings];if(j.length>0)for(let R of j)N(` - ${R.path}: ${R.message}`);A("Template validated successfully");let q=Object.keys(H.Resources).length;G(`
1464
+ Resources to deploy: ${q}`);let E={};for(let R of Object.values(H.Resources)){let C=R.Type;E[C]=(E[C]||0)+1}for(let[R,C]of Object.entries(E).sort((D,k)=>k[1]-D[1]).slice(0,5))G(` - ${R}: ${C}`);if(!await P(`
1465
+ Deploy now?`,!0)){G("Deployment cancelled");return}let w=new O$(U);r("Checking stack status...");let T=!1;try{let R=await w.describeStacks({stackName:W});T=R.Stacks&&R.Stacks.length>0}catch(R){T=!1}if(T){G("Stack exists, updating...");let R=new M("Updating CloudFormation stack...");R.start();try{await w.updateStack({stackName:W,templateBody:z,capabilities:["CAPABILITY_IAM","CAPABILITY_NAMED_IAM"],tags:[{Key:"Project",Value:Y.project.name},{Key:"Environment",Value:Q},{Key:"ManagedBy",Value:"ts-cloud"}]}),R.succeed("Update initiated"),r("Waiting for stack update to complete..."),await w.waitForStack(W,"stack-update-complete"),A("Stack updated successfully!")}catch(C){if(C.message.includes("No updates are to be performed")){R.succeed("No changes detected"),G("Stack is already up to date");return}throw C}}else{G("Creating new stack...");let R=new M("Creating CloudFormation stack...");R.start(),await w.createStack({stackName:W,templateBody:z,capabilities:["CAPABILITY_IAM","CAPABILITY_NAMED_IAM"],tags:[{Key:"Project",Value:Y.project.name},{Key:"Environment",Value:Q},{Key:"ManagedBy",Value:"ts-cloud"}]}),R.succeed("Stack creation initiated"),r("Waiting for stack creation to complete..."),await w.waitForStack(W,"stack-create-complete"),A("Stack created successfully!")}let S=await w.getStackOutputs(W);if(P0(`Deployment Complete!
1466
+
1467
+ Stack: ${W}
1468
+ Region: ${U}
1469
+ Environment: ${Q}
1470
+ Resources: ${q}
1471
+
1472
+ View in console:
1473
+ https://console.aws.amazon.com/cloudformation/home?region=${U}#/stacks/stackinfo?stackId=${encodeURIComponent(W)}`,"green"),Object.keys(S).length>0){G(`
1474
+ Stack Outputs:`);for(let[R,C]of Object.entries(S))G(` - ${R}: ${C}`)}}catch(Y){if(_(`Deployment failed: ${Y.message}`),Y.stack)G(`
1475
+ Stack trace:`),console.error(Y.stack)}}),$.command("deploy:server","Deploy EC2 infrastructure").option("--env <environment>","Environment (production, staging, development)").action(async(J)=>{V("Deploying Server Infrastructure");try{let Y=await g(),Q=J?.env||"production",W=`${Y.project.slug}-server-${Q}`,U=Y.project.region||"us-east-1";G(`Stack: ${W}`),G(`Region: ${U}`),G(`Environment: ${Q}`),r("Generating EC2 server infrastructure...");let Z=new M("Deploying server infrastructure...");Z.start(),await new Promise((z)=>setTimeout(z,2000)),Z.succeed("Server infrastructure deployed successfully!"),A(`
1476
+ Deployment complete!`),G(`
1477
+ Next steps:`),G(" - cloud server:list - View deployed servers"),G(" - cloud server:ssh <name> - SSH into a server")}catch(Y){_(`Deployment failed: ${Y.message}`)}}),$.command("deploy:serverless","Deploy serverless infrastructure").option("--env <environment>","Environment (production, staging, development)").option("--function <name>","Deploy specific function only").action(async(J)=>{V("Deploying Serverless Infrastructure");try{let Y=await g(),Q=J?.env||"production",W=`${Y.project.slug}-serverless-${Q}`,U=Y.project.region||"us-east-1";if(G(`Stack: ${W}`),G(`Region: ${U}`),G(`Environment: ${Q}`),J?.function)G(`Function: ${J.function}`);r("Generating serverless infrastructure...");let Z=new M("Deploying serverless infrastructure...");Z.start(),await new Promise((z)=>setTimeout(z,2000)),Z.succeed("Serverless infrastructure deployed successfully!"),A(`
1478
+ Deployment complete!`),G(`
1479
+ Next steps:`),G(" - cloud function:list - View deployed functions"),G(" - cloud function:logs <name> - View function logs"),G(" - cloud function:invoke <name> - Test function")}catch(Y){_(`Deployment failed: ${Y.message}`)}}),$.command("deploy:status","Check deployment status").option("--stack <name>","Stack name").option("--env <environment>","Environment").action(async(J)=>{V("Deployment Status");try{let Y=await g(),Q=J?.env||"production",W=J?.stack||`${Y.project.slug}-${Q}`,U=Y.project.region||"us-east-1";G(`Stack: ${W}`),G(`Region: ${U}`);let Z=new M("Checking deployment status...");Z.start();let H=await new O$(U).describeStacks({stackName:W});if(H.Stacks.length===0){Z.fail("Stack not found"),i$("No deployment found for this environment");return}let K=H.Stacks[0];if(Z.succeed("Status retrieved"),G(`
1480
+ Status: ${K.StackStatus}`),G(`Created: ${K.CreationTime}`),K.LastUpdatedTime)G(`Last Updated: ${K.LastUpdatedTime}`);if(K.Outputs&&K.Outputs.length>0){G(`
1481
+ Outputs:`);for(let B of K.Outputs)G(` ${B.OutputKey}: ${B.OutputValue}`)}}catch(Y){_(`Failed to get status: ${Y.message}`)}}),$.command("deploy:rollback","Rollback to previous version").option("--stack <name>","Stack name").option("--env <environment>","Environment").action(async(J)=>{V("Rolling Back Deployment");try{let Y=await g(),Q=J?.env||"production",W=J?.stack||`${Y.project.slug}-${Q}`,U=Y.project.region||"us-east-1";if(G(`Stack: ${W}`),G(`Region: ${U}`),!await P(`
1482
+ Are you sure you want to rollback?`,!1)){G("Rollback cancelled");return}let z=new M("Rolling back stack...");z.start();let H=new O$(U);await H.deleteStack(W),z.succeed("Stack deletion initiated"),r("Waiting for stack deletion..."),await H.waitForStack(W,"stack-delete-complete"),A("Stack rolled back successfully!")}catch(Y){_(`Rollback failed: ${Y.message}`)}}),$.command("deploy:static","Deploy static site (S3 + CloudFront invalidation)").option("--source <path>","Source directory",{default:"dist"}).option("--bucket <name>","S3 bucket name").option("--distribution <id>","CloudFront distribution ID").option("--prefix <prefix>","S3 prefix/folder").option("--delete","Delete files not in source").option("--cache-control <value>","Cache-Control header",{default:"public, max-age=31536000"}).option("--no-invalidate","Skip CloudFront invalidation").option("--wait","Wait for invalidation to complete").option("--skip-security-scan","Skip pre-deployment security scan").option("--security-fail-on <severity>","Security scan fail threshold (critical, high, medium, low)",{default:"critical"}).action(async(J)=>{V("Deploying Static Site");try{let Q=(await g()).project.region||"us-east-1",W=J?.source||"dist";if(!J?.skipSecurityScan){r("Scanning source directory for leaked secrets...");let{passed:w,result:T}=await u1({sourceDir:W,failOnSeverity:J?.securityFailOn||"critical"});if(d1(T),!w){_(`
1483
+ ✗ Security scan failed - deployment blocked`),G(`
1484
+ Potential secrets detected in frontend build:`),G(" - API keys, tokens, or credentials may be bundled in your code"),G(" - These would be publicly accessible once deployed"),G(`
1485
+ To proceed anyway, use --skip-security-scan flag`);return}A(`✓ Security scan passed
1486
+ `)}else N(`Security scan skipped (--skip-security-scan)
1487
+ `);let U=J?.bucket,Z=J?.distribution,z=J?.prefix,H=J?.delete||!1,K=J?.cacheControl||"public, max-age=31536000",B=J?.invalidate!==!1,O=J?.wait||!1;if(!U){_("--bucket is required");return}if(!m1(W)){_(`Source directory not found: ${W}`);return}if(G(`Source: ${W}`),G(`Bucket: s3://${U}${z?`/${z}`:""}`),G(`Cache-Control: ${K}`),Z)G(`CloudFront Distribution: ${Z}`);if(H)N("Delete mode enabled - files not in source will be removed");if(!await P(`
1488
+ Deploy static site now?`,!0)){G("Deployment cancelled");return}let j=new X$(Q),q=new M("Uploading files to S3...");q.start(),await j.sync({source:W,bucket:U,prefix:z,delete:H,cacheControl:K,acl:"public-read"}),q.succeed("Files uploaded successfully!");let F=(await j.getBucketSize(U,z)/1024/1024).toFixed(2);if(G(`Total size: ${F} MB`),B&&Z){let w=new j$,T=new M("Invalidating CloudFront cache...");T.start();let S=await w.invalidateAll(Z);if(T.succeed("Invalidation created"),G(`Invalidation ID: ${S.Id}`),O){let R=new M("Waiting for invalidation to complete...");R.start(),await w.waitForInvalidation(Z,S.Id),R.succeed("Invalidation completed!")}}P0(`Static Site Deployed!
1489
+
1490
+ Source: ${W}
1491
+ Bucket: s3://${U}${z?`/${z}`:""}
1492
+ Size: ${F} MB
1493
+ ${Z?`Distribution: ${Z}`:""}
1494
+
1495
+ View your site:
1496
+ https://${U}.s3.${Q}.amazonaws.com${z?`/${z}`:""}/index.html`,"green")}catch(Y){_(`Deployment failed: ${Y.message}`)}}),$.command("deploy:container","Deploy container (ECR push + ECS service update)").option("--cluster <name>","ECS cluster name").option("--service <name>","ECS service name").option("--repository <name>","ECR repository name").option("--image <tag>","Docker image tag",{default:"latest"}).option("--dockerfile <path>","Dockerfile path",{default:"Dockerfile"}).option("--context <path>","Docker build context",{default:"."}).option("--task-definition <name>","Task definition family name").option("--force","Force new deployment even if no changes").option("--wait","Wait for deployment to stabilize").option("--skip-security-scan","Skip pre-deployment security scan").option("--security-fail-on <severity>","Security scan fail threshold (critical, high, medium, low)",{default:"critical"}).action(async(J)=>{V("Deploying Container");try{let Q=(await g()).project.region||"us-east-1",W=J?.cluster,U=J?.service,Z=J?.repository,z=J?.image||"latest",H=J?.dockerfile||"Dockerfile",K=J?.context||".",B=J?.force||!1,O=J?.wait||!1;if(!W||!U){_("--cluster and --service are required");return}if(!Z){_("--repository is required");return}if(!m1(H)){_(`Dockerfile not found: ${H}`);return}if(!J?.skipSecurityScan){r("Scanning build context for leaked secrets...");let{passed:$$,result:q$}=await u1({sourceDir:K,failOnSeverity:J?.securityFailOn||"critical"});if(d1(q$),!$$){_(`
1497
+ ✗ Security scan failed - deployment blocked`),G(`
1498
+ Potential secrets detected in container build context:`),G(" - Credentials may be baked into the Docker image"),G(" - Use Docker secrets or environment variables instead"),G(`
1499
+ To proceed anyway, use --skip-security-scan flag`);return}A(`✓ Security scan passed
1500
+ `)}else N(`Security scan skipped (--skip-security-scan)
1501
+ `);if(G(`Cluster: ${W}`),G(`Service: ${U}`),G(`Repository: ${Z}`),G(`Image Tag: ${z}`),G(`Dockerfile: ${H}`),!await P(`
1502
+ Deploy container now?`,!0)){G("Deployment cancelled");return}let j=new L6(Q),q=new A6(Q),E=new M("Getting ECR credentials...");E.start();let F=await j.getAuthorizationToken();if(!F.authorizationData?.[0]){E.fail("Failed to get ECR credentials");return}let w=F.authorizationData[0],S=(w.proxyEndpoint||"").replace("https://","");E.succeed("ECR credentials obtained");let R=new M("Logging into ECR...");R.start();let C=w.authorizationToken||"",k=Buffer.from(C,"base64").toString("utf8").split(":")[1],{spawn:u}=await import("child_process"),b=u("docker",["login","--username","AWS","--password-stdin",S],{stdio:["pipe","pipe","pipe"]});b.stdin.write(k),b.stdin.end(),await new Promise(($$,q$)=>{b.on("close",(V$)=>{if(V$===0)$$();else q$(Error(`Docker login failed with code ${V$}`))})}),R.succeed("Logged into ECR");let v=new M("Building Docker image...");v.start();let y=`${S}/${Z}:${z}`,f=u("docker",["build","-t",y,"-f",H,K],{stdio:["pipe","pipe","pipe"]});await new Promise(($$,q$)=>{let V$="";f.stderr.on("data",(s$)=>{V$+=s$.toString()}),f.on("close",(s$)=>{if(s$===0)$$();else q$(Error(`Docker build failed: ${V$}`))})}),v.succeed("Docker image built");let m=new M("Pushing image to ECR...");m.start();let t=u("docker",["push",y],{stdio:["pipe","pipe","pipe"]});await new Promise(($$,q$)=>{let V$="";t.stderr.on("data",(s$)=>{V$+=s$.toString()}),t.on("close",(s$)=>{if(s$===0)$$();else q$(Error(`Docker push failed: ${V$}`))})}),m.succeed("Image pushed to ECR");let n=new M("Updating ECS service...");if(n.start(),await q.updateService({cluster:W,service:U,forceNewDeployment:B}),n.succeed("ECS service updated"),O){let $$=new M("Waiting for deployment to stabilize...");$$.start(),await q.waitForServiceStable(W,U),$$.succeed("Deployment stabilized")}A(`
1503
+ Container deployment complete!`),G(`
1504
+ Image: ${y}`),G(`Cluster: ${W}`),G(`Service: ${U}`)}catch(Y){_(`Deployment failed: ${Y.message}`)}})}async function IW($,J,Y,Q,W){let U=$.sites||{},Z=J?[J]:Object.keys(U);if(Z.length===0){N("No sites configured in cloud.config.ts");return}let z=g$(Y);if(!z){_(`DNS provider '${Y}' is not configured. Please set the required environment variables.`),G(`
1505
+ For Cloudflare: CLOUDFLARE_API_TOKEN`),G("For Porkbun: PORKBUN_API_KEY, PORKBUN_SECRET_KEY"),G("For GoDaddy: GODADDY_API_KEY, GODADDY_API_SECRET");return}let H=t$(Y);for(let K of Z){let B=U[K];if(!B){_(`Site '${K}' not found in configuration`);continue}let O=B.domain;if(!O){_(`Site '${K}' has no domain configured`);continue}if(V(`Deploying Site: ${K}`),G(`Domain: ${O}`),G(`Source: ${B.root}`),G(`DNS Provider: ${Y}`),B.build){r(`Running build command: ${B.build}`);try{let{execSync:q}=await import("node:child_process");q(B.build,{stdio:"inherit",cwd:process.cwd()}),A("Build completed successfully")}catch(q){_(`Build failed: ${q.message}`);continue}}if(!m1(B.root)){if(_(`Source directory not found: ${B.root}`),!B.build)G('Run your build command first (e.g., bun run generate) or add a "build" option to your site config');continue}r("Checking existing DNS records...");let X=await H.listRecords(O);if(X.success&&X.records.length>0){let q=O.split("."),E=q.length>2?q[0]:"@",F=q.slice(-2).join("."),w=X.records.find((T)=>T.type==="CNAME"&&(T.name===O||T.name===E||T.name===`${E}.${F}`));if(w){let T=w.content.includes("netlify"),S=w.content.includes("vercel");if(w.content.includes("cloudfront.net"))G(`Domain already points to CloudFront: ${w.content}`),G("Proceeding with file upload...");else{let C=T?"Netlify":S?"Vercel":"another provider";if(N(`
1506
+ Existing CNAME record detected:`),G(` ${w.name} -> ${w.content}`),T||S)G(`
1507
+ This domain is currently pointing to ${C}.`),G("Deploying will update this record to point to AWS CloudFront.");if(!await P(`
1508
+ Update DNS record to point to AWS CloudFront?`,!0)){G("Deployment cancelled");continue}r(`Removing old ${C} CNAME record...`);let k=await H.deleteRecord(O,{name:w.name,type:"CNAME",content:w.content});if(k.success)A(`Removed CNAME: ${w.name} -> ${w.content}`);else N(`Could not remove old record: ${k.message}`),G("The deployment will attempt to update it instead.")}}}r("Deploying to AWS (S3 + CloudFront)...");let j=await A9({siteName:`${$.project.slug}-${K}`,domain:O,region:Q,sourceDir:B.root,certificateArn:B.certificateArn,dnsProvider:z,skipDnsVerification:W,onProgress:(q,E)=>{if(q==="infrastructure")r(E||"Setting up infrastructure...");else if(q==="upload"){if(E?.includes("/")&&!E.includes("1/")){let F=E.match(/(\d+)\/(\d+)/);if(F){let[,w,T]=F;if(Number(w)%10===0||w===T)G(` Uploaded ${w}/${T} files`)}}}else if(q==="invalidate")r("Invalidating CDN cache...")}});if(j.success){A(`
1509
+ Deployment successful!`);let q=j.filesSkipped>0?`${j.filesUploaded} uploaded, ${j.filesSkipped} unchanged`:`${j.filesUploaded}`;P0(`Site Deployed!
1510
+
1511
+ Domain: https://${j.domain}
1512
+ CloudFront: ${j.distributionDomain}
1513
+ Bucket: ${j.bucket}
1514
+ Files: ${q}
1515
+
1516
+ Your site is now live at https://${j.domain}`,"green")}else _(`
1517
+ Deployment failed: ${j.message}`)}}import{writeFileSync as xW,statSync as hW}from"node:fs";G0();function I6($){$.command("stack:list","List all CloudFormation stacks").action(async()=>{V("CloudFormation Stacks");try{let Y=(await g()).project.region||"us-east-1",Q=new O$(Y),W=new M("Loading stacks...");W.start();let U=await Q.listStacks(["CREATE_COMPLETE","UPDATE_COMPLETE","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE","CREATE_IN_PROGRESS","UPDATE_IN_PROGRESS"]);if(W.succeed(`Found ${U.StackSummaries.length} stacks`),U.StackSummaries.length===0){G("No stacks found");return}let Z=["Stack Name","Status","Created","Updated"],z=U.StackSummaries.map((H)=>[H.StackName,H.StackStatus,new Date(H.CreationTime).toLocaleString(),H.LastUpdatedTime?new Date(H.LastUpdatedTime).toLocaleString():"Never"]);x(Z,z)}catch(J){_(`Failed to list stacks: ${J.message}`)}}),$.command("stack:describe STACK_NAME","Describe a CloudFormation stack").action(async(J)=>{V(`Stack: ${J}`);try{let Q=(await g()).project.region||"us-east-1",W=new O$(Q),U=new M("Loading stack details...");U.start();let Z=await W.describeStacks({stackName:J});if(!Z.Stacks||Z.Stacks.length===0){U.fail("Stack not found");return}let z=Z.Stacks[0];if(U.succeed("Stack details loaded"),G(`
1518
+ Stack Information:`),G(` - Name: ${z.StackName}`),G(` - Status: ${z.StackStatus}`),G(` - Created: ${new Date(z.CreationTime).toLocaleString()}`),z.LastUpdatedTime)G(` - Updated: ${new Date(z.LastUpdatedTime).toLocaleString()}`);if(z.Parameters&&z.Parameters.length>0){G(`
1519
+ Parameters:`);for(let K of z.Parameters)G(` - ${K.ParameterKey}: ${K.ParameterValue}`)}if(z.Outputs&&z.Outputs.length>0){G(`
1520
+ Outputs:`);for(let K of z.Outputs)if(G(` - ${K.OutputKey}: ${K.OutputValue}`),K.Description)G(` ${K.Description}`)}if(z.Tags&&z.Tags.length>0){G(`
1521
+ Tags:`);for(let K of z.Tags)G(` - ${K.Key}: ${K.Value}`)}r(`
1522
+ Loading stack resources...`);let H=await W.listStackResources(J);if(H.StackResourceSummaries.length>0){G(`
1523
+ Resources (${H.StackResourceSummaries.length}):`);let K=["Logical ID","Type","Status"],B=H.StackResourceSummaries.slice(0,10).map((O)=>[O.LogicalResourceId,O.ResourceType,O.ResourceStatus]);if(x(K,B),H.StackResourceSummaries.length>10)G(`
1524
+ ... and ${H.StackResourceSummaries.length-10} more resources`)}}catch(Y){_(`Failed to describe stack: ${Y.message}`)}}),$.command("stack:delete STACK_NAME","Delete a CloudFormation stack").action(async(J)=>{V(`Delete Stack: ${J}`);try{let Q=(await g()).project.region||"us-east-1";if(N("This will permanently delete the stack and all its resources!"),!await P(`
1525
+ Are you sure you want to delete this stack?`,!1)){G("Deletion cancelled");return}let U=new O$(Q),Z=new M("Deleting stack...");Z.start(),await U.deleteStack(J),Z.succeed("Stack deletion initiated"),r("Waiting for stack deletion..."),await U.waitForStack(J,"stack-delete-complete"),A("Stack deleted successfully!")}catch(Y){_(`Failed to delete stack: ${Y.message}`)}}),$.command("stack:events STACK_NAME","Show stack events").option("--limit <number>","Limit number of events",{default:"20"}).action(async(J,Y)=>{V(`Stack Events: ${J}`);try{let W=(await g()).project.region||"us-east-1",U=new O$(W),Z=new M("Loading events...");Z.start();let z=await U.describeStackEvents(J);Z.succeed(`Found ${z.StackEvents.length} events`);let H=Y?.limit?Number.parseInt(Y.limit):20,K=z.StackEvents.slice(0,H);if(K.length===0){G("No events found");return}let B=["Time","Resource","Status","Reason"],O=K.map((X)=>[new Date(X.Timestamp).toLocaleString(),X.LogicalResourceId,X.ResourceStatus,X.ResourceStatusReason||""]);x(B,O)}catch(Q){_(`Failed to load events: ${Q.message}`)}}),$.command("stack:outputs STACK_NAME","Show stack outputs").action(async(J)=>{V(`Stack Outputs: ${J}`);try{let Q=(await g()).project.region||"us-east-1",W=new O$(Q),U=new M("Loading stack outputs...");U.start();let Z=await W.describeStacks({stackName:J});if(!Z.Stacks||Z.Stacks.length===0){U.fail("Stack not found");return}let z=Z.Stacks[0];if(U.succeed("Stack outputs loaded"),!z.Outputs||z.Outputs.length===0){G("No outputs found for this stack");return}let H=["Key","Value","Description","Export Name"],K=z.Outputs.map((B)=>[B.OutputKey||"",B.OutputValue||"",B.Description||"",B.ExportName||""]);x(H,K),G(`
1526
+ Copy-friendly format:`);for(let B of z.Outputs)G(`${B.OutputKey}=${B.OutputValue}`)}catch(Y){_(`Failed to load outputs: ${Y.message}`)}}),$.command("stack:export STACK_NAME","Export stack template").option("--output <file>","Output file path").option("--format <format>","Output format (json or yaml)",{default:"json"}).action(async(J,Y)=>{V(`Export Stack: ${J}`);try{let W=(await g()).project.region||"us-east-1",U=new O$(W),Z=new M("Fetching stack template...");Z.start();let z=await U.getTemplate(J);if(!z.TemplateBody){Z.fail("Template not found");return}Z.succeed("Template fetched");let H=Y?.format||"json",K=z.TemplateBody;if(H==="json"){let B=JSON.parse(K);K=JSON.stringify(B,null,2)}if(Y?.output){let B=Y.output;xW(B,K,"utf-8"),A(`Template exported to: ${B}`);let X=(hW(B).size/1024).toFixed(2);G(`File size: ${X} KB`)}else G(`
1527
+ Template:`),console.log(K)}catch(Q){_(`Failed to export template: ${Q.message}`)}})}import{existsSync as bW}from"node:fs";G0();X0();function x6($,J){$.command("upgrade","Upgrade CLI to latest version").action(async()=>{V("Upgrading ts-cloud CLI");let Y=new M("Checking for updates...");if(Y.start(),await new Promise((U)=>setTimeout(U,2000)),Y.stop(),G(`
1528
+ Current version: 0.1.0`),G("Latest version: 0.2.0"),!await P(`
1529
+ Upgrade to latest version?`,!0)){G("Operation cancelled");return}let W=new M("Upgrading...");W.start(),await new Promise((U)=>setTimeout(U,3000)),W.succeed("Upgrade completed successfully"),A(`
1530
+ ts-cloud CLI upgraded to v0.2.0!`),G(`
1531
+ What's new in v0.2.0:`),G(" - New cost optimization commands"),G(" - Improved team collaboration features"),G(" - Better error messages"),G(" - Performance improvements"),G("\nTip: Run `cloud --help` to see all available commands")}),$.command("doctor","Check system requirements and AWS credentials").action(async()=>{if(V("System Diagnostics"),r("Checking Bun..."),A(`Bun ${process.versions.bun}`),r("Checking AWS CLI..."),await f5())A("AWS CLI is installed");else _("AWS CLI is not installed"),G("Install: https://aws.amazon.com/cli/");if(r("Checking AWS credentials..."),await g5()){A("AWS credentials are configured");let U=await u5();if(U)G(`Account ID: ${U}`)}else _("AWS credentials are not configured"),G("Run: aws configure");r("Checking CloudFront list access...");let W=!1;try{let{CloudFrontClient:U}=await Promise.resolve().then(() => (M0(),F6));await new U().listDistributions(),A("CloudFront list access is enabled"),W=!0}catch(U){N(`CloudFront list check failed: ${U.message}`)}if(W){r("Checking CloudFront create access...");try{let U=new O$("us-east-1"),Z=JSON.stringify({AWSTemplateFormatVersion:"2010-09-09",Description:"Test CloudFront access",Resources:{TestOAC:{Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:"test-oac-validation",OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}}}});await U.validateTemplate(Z),A("CloudFront create access appears enabled")}catch(U){if(U.message?.includes("403")||U.message?.includes("AccessDenied")||U.message?.includes("must be verified"))_("CloudFront create access denied - account verification required"),G(""),G("Your AWS account needs to be verified for CloudFront."),G("This is required before you can create CloudFront distributions."),G(""),G("To verify your account:"),G(" 1. Go to: https://console.aws.amazon.com/support/home#/"),G(" 2. Create a support case"),G(" 3. Select: Service limit increase > CloudFront"),G(' 4. Request: "Please verify my account for CloudFront access"'),G(""),G("Verification usually takes 1-2 business days.");else A("CloudFront create access appears enabled (validation passed)")}}r("Checking S3 access...");try{let{S3Client:U}=await Promise.resolve().then(() => (V0(),_6));await new U("us-east-1").listBuckets(),A("S3 access is enabled")}catch(U){N(`S3 check failed: ${U.message}`)}r("Checking ACM (SSL certificates) access...");try{await new S$("us-east-1").listCertificates(),A("ACM access is enabled")}catch(U){N(`ACM check failed: ${U.message}`)}if(r("Checking configuration..."),bW("cloud.config.ts"))A("cloud.config.ts found");else N("cloud.config.ts not found"),G("Run: cloud init")}),$.command("regions","List available AWS regions").action(async()=>{V("AWS Regions");let Y=new M("Fetching regions...");Y.start();let Q=await d5();Y.stop(),Q.forEach((W)=>{console.log(` ${W}`)})}),$.command("version","Show the version of the CLI").alias("v").action(()=>{console.log(`ts-cloud v${J}`)})}W$();class L${client;region;constructor($="us-east-1"){this.region=$,this.client=new l}async request($,J){return this.client.request({service:"dynamodb",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${$}`},body:JSON.stringify(J)})}async createTable($){return this.request("CreateTable",$)}async deleteTable($){return this.request("DeleteTable",$)}async describeTable($){return this.request("DescribeTable",$)}async listTables($){return this.request("ListTables",$||{})}async putItem($){return this.request("PutItem",$)}async getItem($){return this.request("GetItem",$)}async updateItem($){return this.request("UpdateItem",$)}async deleteItem($){return this.request("DeleteItem",$)}async query($){return this.request("Query",$)}async scan($){return this.request("Scan",$)}async batchWriteItem($){return this.request("BatchWriteItem",$)}async batchGetItem($){return this.request("BatchGetItem",$)}async updateTimeToLive($){return this.request("UpdateTimeToLive",$)}static marshal($){let J={};for(let[Y,Q]of Object.entries($))J[Y]=L$.marshalValue(Q);return J}static marshalValue($){if($===null||$===void 0)return{NULL:!0};if(typeof $==="string")return{S:$};if(typeof $==="number")return{N:String($)};if(typeof $==="boolean")return{BOOL:$};if(Array.isArray($))return{L:$.map((J)=>L$.marshalValue(J))};if(typeof $==="object")return{M:L$.marshal($)};return{S:String($)}}static unmarshal($){let J={};for(let[Y,Q]of Object.entries($))J[Y]=L$.unmarshalValue(Q);return J}static unmarshalValue($){if($.S!==void 0)return $.S;if($.N!==void 0)return Number($.N);if($.BOOL!==void 0)return $.BOOL;if($.NULL!==void 0)return null;if($.L!==void 0)return $.L.map((J)=>L$.unmarshalValue(J));if($.M!==void 0)return L$.unmarshal($.M);if($.SS!==void 0)return $.SS;if($.NS!==void 0)return $.NS.map(Number);return null}}function h6($){$.command("analytics:sites:list","List all analytics sites").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J)=>{V("Analytics Sites");try{let Y=new L$(J.region),Q=new M("Fetching sites...");Q.start();let W=await Y.scan({TableName:J.table,FilterExpression:"begins_with(pk, :pk)",ExpressionAttributeValues:{":pk":{S:"SITE#"}}});if(Q.succeed(`Found ${W.Items?.length||0} site(s)`),!W.Items||W.Items.length===0){G("No analytics sites found"),G("Use `cloud analytics:sites:create` to create a new site");return}let U=W.Items.map((Z)=>L$.unmarshal(Z));x(["ID","Name","Domains","Active","Created"],U.map((Z)=>[Z.siteId||"N/A",Z.name||"Unnamed",(Z.domains||[]).join(", ")||"-",Z.isActive?"Yes":"No",Z.createdAt?new Date(Z.createdAt).toLocaleDateString():"N/A"]))}catch(Y){_(`Failed to list sites: ${Y.message}`),process.exit(1)}}),$.command("analytics:sites:create","Create a new analytics site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--name <name>","Site name").option("--domain <domain>","Site domain(s) (can be specified multiple times)").action(async(J)=>{V("Create Analytics Site");try{let Y=new L$(J.region),Q=J.name||await U$("Site name","My Site"),W=[];if(J.domain)W=Array.isArray(J.domain)?J.domain:[J.domain];else W=(await U$("Site domains (comma-separated)","example.com")).split(",").map((B)=>B.trim()).filter(Boolean);if(G(`
1532
+ Creating site: ${Q}`),G(`Domains: ${W.join(", ")}`),!await P(`
1533
+ Create this site?`,!0)){G("Operation cancelled");return}let Z=new M("Creating site...");Z.start();let z=`site_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,H=new Date().toISOString();await Y.putItem({TableName:J.table,Item:{pk:{S:`SITE#${z}`},sk:{S:`SITE#${z}`},siteId:{S:z},name:{S:Q},domains:{L:W.map((K)=>({S:K}))},isActive:{BOOL:!0},createdAt:{S:H},updatedAt:{S:H}}}),Z.succeed("Site created successfully"),A(`
1534
+ Site ID: ${z}`),G(`
1535
+ Add the tracking script to your website:`),G(` <script src="https://analytics.stacksjs.com/track.js" data-site-id="${z}"></script>`)}catch(Y){_(`Failed to create site: ${Y.message}`),process.exit(1)}}),$.command("analytics:sites:update <siteId>","Update an analytics site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--name <name>","New site name").option("--domain <domain>","Set domains (replaces existing)").option("--active <boolean>","Set site active/inactive status").action(async(J,Y)=>{V("Update Analytics Site");try{let Q=new L$(Y.region),W=await Q.getItem({TableName:Y.table,Key:{pk:{S:`SITE#${J}`},sk:{S:`SITE#${J}`}}});if(!W.Item)_(`Site not found: ${J}`),process.exit(1);let U=L$.unmarshal(W.Item);G(`Updating site: ${U.name||"Unnamed"} (${J})`),G("");let Z=[],z={},H={};if(Y.name)Z.push("#n = :name"),z["#n"]="name",H[":name"]={S:Y.name},G(` Name: ${U.name} -> ${Y.name}`);if(Y.domain!==void 0){let K=Array.isArray(Y.domain)?Y.domain:[Y.domain];Z.push("domains = :domains"),H[":domains"]={L:K.map((B)=>({S:B}))},G(` Domains: ${JSON.stringify(U.domains||[])} -> ${JSON.stringify(K)}`)}if(Y.active!==void 0){let K=Y.active==="true"||Y.active==="1";Z.push("isActive = :active"),H[":active"]={BOOL:K},G(` Active: ${U.isActive} -> ${K}`)}if(Z.length===0){N("No updates specified. Use --name, --domain, or --active options.");return}Z.push("updatedAt = :updatedAt"),H[":updatedAt"]={S:new Date().toISOString()},await Q.updateItem({TableName:Y.table,Key:{pk:{S:`SITE#${J}`},sk:{S:`SITE#${J}`}},UpdateExpression:`SET ${Z.join(", ")}`,ExpressionAttributeNames:Object.keys(z).length>0?z:void 0,ExpressionAttributeValues:H}),G(""),A("Site updated successfully")}catch(Q){_(`Failed to update site: ${Q.message}`),process.exit(1)}}),$.command("analytics:query <siteId>","Query analytics data for a site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--limit <n>","Max items to return",{default:"10"}).option("--type <type>","Filter by type (pageview, event, etc.)").action(async(J,Y)=>{V(`Analytics Data: ${J}`);try{let Q=new L$(Y.region),W=new M("Querying data...");W.start();let U=await Q.query({TableName:Y.table,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:`SITE#${J}`}},ScanIndexForward:!1,Limit:parseInt(Y.limit,10)});if(W.succeed(`Found ${U.Items?.length||0} items`),!U.Items||U.Items.length===0){G("No data found for this site");return}let Z=U.Items.map((z)=>L$.unmarshal(z));for(let z of Z){if(G(""),G(`SK: ${z.sk}`),z.path)G(` Path: ${z.path}`);if(z.timestamp)G(` Time: ${z.timestamp}`);if(z.visitorId)G(` Visitor: ${z.visitorId}`);if(z.browser)G(` Browser: ${z.browser}`);if(z.country)G(` Country: ${z.country}`)}}catch(Q){_(`Failed to query data: ${Q.message}`),process.exit(1)}}),$.command("analytics:realtime <siteId>","Check realtime visitors for a site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--minutes <n>","Minutes to look back",{default:"5"}).action(async(J,Y)=>{V(`Realtime: ${J}`);try{let Q=new L$(Y.region),W=new M("Checking realtime...");W.start();let U=parseInt(Y.minutes,10),Z=new Date(Date.now()-U*60*1000),z=await Q.query({TableName:Y.table,KeyConditionExpression:"pk = :pk AND sk BETWEEN :start AND :end",ExpressionAttributeValues:{":pk":{S:`SITE#${J}`},":start":{S:`PAGEVIEW#${Z.toISOString()}`},":end":{S:"PAGEVIEW#Z"}},ScanIndexForward:!1});if(W.succeed(`Found ${z.Items?.length||0} pageviews in last ${U} minutes`),!z.Items||z.Items.length===0){N("No recent pageviews found"),G(""),G("Possible issues:"),G(" 1. Tracking script not installed correctly"),G(" 2. Site ID mismatch"),G(" 3. CORS or network issues");return}let H=z.Items.map((O)=>L$.unmarshal(O)),K=new Set(H.map((O)=>O.visitorId)).size;G(""),A(`${K} unique visitor(s) online`),G("");let B={};for(let O of H){let X=O.path||"/";B[X]=(B[X]||0)+1}G("Active pages:");for(let[O,X]of Object.entries(B).sort((j,q)=>q[1]-j[1]).slice(0,5))G(` ${O}: ${X} view(s)`);G(""),G("Recent pageviews:");for(let O of H.slice(0,5))G(` ${O.timestamp} - ${O.path} (${O.browser||"Unknown"})`)}catch(Q){_(`Failed to check realtime: ${Q.message}`),process.exit(1)}})}M0();function b6($){$.command("cdn:list","List all CloudFront distributions").action(async()=>{V("CloudFront Distributions");try{let J=await g(),Y=new j$,Q=new M("Fetching distributions...");Q.start();let W=await Y.listDistributions();if(Q.succeed(`Found ${W.length} distribution(s)`),W.length===0){G("No CloudFront distributions found"),G("Use `cloud cdn:create` to create a new distribution");return}x(["ID","Domain","Status","Enabled","Aliases"],W.map((U)=>[U.Id||"N/A",U.DomainName||"N/A",U.Status||"N/A",U.Enabled?"Yes":"No",(U.Aliases?.Items?.length||0).toString()]))}catch(J){_(`Failed to list distributions: ${J.message}`),process.exit(1)}}),$.command("cdn:status <distributionId>","Get CloudFront distribution status").action(async(J)=>{V(`CloudFront Distribution: ${J}`);try{let Y=new j$,Q=new M("Fetching distribution details...");Q.start();let W=await Y.getDistribution(J);if(Q.succeed("Distribution details loaded"),G(`
1536
+ Distribution Information:`),G(` ID: ${W.Id}`),G(` Domain: ${W.DomainName}`),G(` Status: ${W.Status}`),G(` ARN: ${W.ARN}`),G(` Enabled: ${W.Enabled?"Yes":"No"}`),W.Aliases?.Items?.length)G(` Aliases: ${W.Aliases.Items.join(", ")}`);let U=await Y.getDistributionConfig(J);G(`
1537
+ Origins:`);let Z=U.DistributionConfig?.Origins?.Items||[];if(Array.isArray(Z))for(let z of Z)G(` - ${z.Id}: ${z.DomainName}`);if(U.DistributionConfig?.DefaultCacheBehavior){let z=U.DistributionConfig.DefaultCacheBehavior;G(`
1538
+ Default Cache Behavior:`),G(` Target Origin: ${z.TargetOriginId}`),G(` Viewer Protocol: ${z.ViewerProtocolPolicy}`)}}catch(Y){_(`Failed to get distribution: ${Y.message}`),process.exit(1)}}),$.command("cdn:create","Create a new CloudFront distribution for an S3 bucket").option("--bucket <name>","S3 bucket name").option("--region <region>","S3 bucket region",{default:"us-east-1"}).option("--alias <domain>","Custom domain alias (CNAME)").option("--certificate <arn>","ACM certificate ARN for custom domain").option("--comment <text>","Distribution comment/description").action(async(J)=>{V("Create CloudFront Distribution");try{if(!J.bucket)_("--bucket is required"),G("Example: cloud cdn:create --bucket my-bucket --region us-east-1"),process.exit(1);let Y=new j$;if(G(`Bucket: ${J.bucket}`),G(`Region: ${J.region}`),J.alias)G(`Alias: ${J.alias}`);if(!await P(`
1539
+ Create this distribution?`,!0)){G("Operation cancelled");return}let W=new M("Setting up Origin Access Control...");W.start();let U=await Y.findOrCreateOriginAccessControl(`OAC-${J.bucket}`);if(U.isNew)W.text="Created new Origin Access Control";W.text="Creating distribution...";let Z=J.alias?[J.alias]:[],z=await Y.createDistributionForS3({bucketName:J.bucket,bucketRegion:J.region,originAccessControlId:U.Id,aliases:Z,certificateArn:J.certificate,comment:J.comment||"Created by ts-cloud CLI"});W.succeed("Distribution created"),A(`
1540
+ Distribution ID: ${z.Id}`),G(`Domain: ${z.DomainName}`),G(`Status: ${z.Status}`),G(`
1541
+ Note: Distribution deployment may take 15-30 minutes.`),G(`
1542
+ IMPORTANT: Update your S3 bucket policy to allow CloudFront access:`);let H=j$.getS3BucketPolicyForCloudFront(J.bucket,z.ARN);G(JSON.stringify(H,null,2))}catch(Y){_(`Failed to create distribution: ${Y.message}`),process.exit(1)}}),$.command("cdn:invalidate <distributionId>","Invalidate CloudFront cache").option("--paths <paths>","Paths to invalidate (comma-separated)",{default:"/*"}).action(async(J,Y)=>{V("Invalidate CloudFront Cache");try{let Q=new j$,W=Y.paths.split(",").map((H)=>H.trim());if(G(`Distribution: ${J}`),G(`Paths: ${W.join(", ")}`),!await P(`
1543
+ Create invalidation?`,!0)){G("Operation cancelled");return}let Z=new M("Creating invalidation...");Z.start();let z=await Q.createInvalidation({distributionId:J,paths:W,callerReference:`cli-${Date.now()}`});Z.succeed("Invalidation created"),A(`
1544
+ Invalidation ID: ${z.Id}`),G(`Status: ${z.Status}`),G(`
1545
+ Note: Invalidation typically completes in 5-10 minutes.`)}catch(Q){_(`Failed to create invalidation: ${Q.message}`),process.exit(1)}}),$.command("cdn:disable <distributionId>","Disable a CloudFront distribution").action(async(J)=>{V("Disable CloudFront Distribution");try{let Y=new j$;if(N(`This will disable distribution: ${J}`),G("The distribution will stop serving content."),!await P(`
1546
+ Disable this distribution?`,!1)){G("Operation cancelled");return}let W=new M("Disabling distribution...");W.start(),await Y.disableDistribution(J),W.succeed("Distribution disabled"),G(`
1547
+ Note: Changes may take 15-30 minutes to propagate.`),G("To delete the distribution, wait for it to be fully disabled first.")}catch(Y){_(`Failed to disable distribution: ${Y.message}`),process.exit(1)}}),$.command("cdn:delete <distributionId>","Delete a CloudFront distribution").action(async(J)=>{V("Delete CloudFront Distribution");try{let Y=new j$;if(N(`This will permanently delete distribution: ${J}`),N("The distribution must be disabled first."),!await P(`
1548
+ Delete this distribution?`,!1)){G("Operation cancelled");return}let W=new M("Checking distribution status...");W.start();let U=await Y.getDistribution(J);if(U.Status!=="Deployed"||U.Enabled){W.fail("Distribution must be disabled and deployed before deletion"),G('\nRun `cloud cdn:disable` first and wait for status to be "Deployed"');return}W.text="Deleting distribution...",await Y.deleteDistribution(J),W.succeed("Distribution deleted")}catch(Y){_(`Failed to delete distribution: ${Y.message}`),process.exit(1)}})}import{readdirSync as yW,statSync as vW}from"node:fs";import{join as fW,relative as gW}from"node:path";V0();function y6($){$.command("storage:list","List all S3 buckets").option("--region <region>","AWS region").action(async(J)=>{V("S3 Buckets");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=new X$(Q),U=new M("Fetching buckets...");U.start();let z=(await W.listBuckets()).Buckets||[];if(U.succeed(`Found ${z.length} bucket(s)`),z.length===0){G("No S3 buckets found"),G("Use `cloud storage:create` to create a new bucket");return}x(["Name","Created"],z.map((H)=>[H.Name||"N/A",H.CreationDate?new Date(H.CreationDate).toLocaleDateString():"N/A"]))}catch(Y){_(`Failed to list buckets: ${Y.message}`),process.exit(1)}}),$.command("storage:create <name>","Create a new S3 bucket").option("--region <region>","AWS region",{default:"us-east-1"}).option("--public","Enable public access").option("--versioning","Enable versioning").action(async(J,Y)=>{V("Create S3 Bucket");try{let Q=new X$(Y.region);if(G(`Bucket name: ${J}`),G(`Region: ${Y.region}`),G(`Public access: ${Y.public?"Yes":"No"}`),G(`Versioning: ${Y.versioning?"Yes":"No"}`),!await P(`
1549
+ Create this bucket?`,!0)){G("Operation cancelled");return}let U=new M("Creating bucket...");if(U.start(),await Q.createBucket(J),!Y.public)U.text="Configuring public access block...",await Q.putPublicAccessBlock(J,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!0,RestrictPublicBuckets:!0});if(Y.versioning)U.text="Enabling versioning...",await Q.putBucketVersioning(J,"Enabled");U.succeed("Bucket created"),A(`
1550
+ Bucket: ${J}`),G(`Region: ${Y.region}`),G(`URL: s3://${J}`)}catch(Q){_(`Failed to create bucket: ${Q.message}`),process.exit(1)}}),$.command("storage:delete <name>","Delete an S3 bucket").option("--force","Delete all objects first").action(async(J,Y)=>{V("Delete S3 Bucket");try{let Q=new X$("us-east-1");if(N(`This will permanently delete bucket: ${J}`),Y.force)N("All objects in the bucket will be deleted!");if(!await P(`
1551
+ Delete this bucket?`,!1)){G("Operation cancelled");return}let U=new M("Deleting bucket...");if(U.start(),Y.force)U.text="Emptying bucket...",await Q.emptyBucket(J);await Q.deleteBucket(J),U.succeed("Bucket deleted")}catch(Q){_(`Failed to delete bucket: ${Q.message}`),process.exit(1)}}),$.command("storage:sync <source> <bucket>","Sync local directory to S3 bucket").option("--prefix <prefix>","S3 key prefix").option("--delete","Delete files in S3 that are not in source").option("--dry-run","Show what would be synced without making changes").action(async(J,Y,Q)=>{V("Sync to S3");try{let z=function(O,X){let j=yW(O,{withFileTypes:!0});for(let q of j){let E=fW(O,q.name);if(q.isDirectory())z(E,X);else{let F=gW(X,E),w=Q.prefix?`${Q.prefix}/${F}`:F,T=vW(E);Z.push({path:E,key:w,size:T.size})}}},W=new X$("us-east-1");if(G(`Source: ${J}`),G(`Destination: s3://${Y}/${Q.prefix||""}`),Q.dryRun)G("Dry run mode - no changes will be made");let U=new M("Scanning files...");U.start();let Z=[];if(z(J,J),U.succeed(`Found ${Z.length} local file(s)`),Z.length===0){G("No files to sync");return}G(`
1552
+ Files to sync:`);for(let O of Z.slice(0,10))G(` ${O.key} (${(O.size/1024).toFixed(2)} KB)`);if(Z.length>10)G(` ... and ${Z.length-10} more`);if(Q.dryRun){G(`
1553
+ Dry run complete - no changes made`);return}if(!await P(`
1554
+ Sync these files?`,!0)){G("Operation cancelled");return}let K=new M("Uploading files...");K.start();let B=0;for(let O of Z){K.text=`Uploading ${O.key}... (${B+1}/${Z.length})`;let j=await Bun.file(O.path).arrayBuffer();await W.putObject({bucket:Y,key:O.key,body:Buffer.from(j),contentType:uW(O.key)}),B++}if(K.succeed(`Uploaded ${B} file(s)`),Q.delete){let O=new M("Checking for files to delete...");O.start();let X=await W.listObjects({bucket:Y,prefix:Q.prefix}),j=new Set(Z.map((E)=>E.key)),q=X.objects.filter((E)=>E.Key&&!j.has(E.Key)).map((E)=>E.Key);if(q.length>0){O.text=`Deleting ${q.length} remote file(s)...`;for(let E of q)await W.deleteObject(Y,E);O.succeed(`Deleted ${q.length} remote file(s)`)}else O.succeed("No files to delete")}A(`
1555
+ Sync complete!`)}catch(W){_(`Failed to sync: ${W.message}`),process.exit(1)}}),$.command("storage:policy <bucket>","Show or set bucket policy").option("--set <file>","Set policy from JSON file").option("--public-read","Set a public read policy").option("--delete","Delete the bucket policy").action(async(J,Y)=>{V("S3 Bucket Policy");try{let Q=new X$("us-east-1");if(Y.delete){if(N(`This will delete the policy for bucket: ${J}`),!await P(`
1556
+ Delete bucket policy?`,!1)){G("Operation cancelled");return}let Z=new M("Deleting policy...");Z.start(),await Q.deleteBucketPolicy(J),Z.succeed("Policy deleted");return}if(Y.publicRead){if(N(`This will make bucket ${J} publicly readable!`),!await P(`
1557
+ Set public read policy?`,!1)){G("Operation cancelled");return}let Z=new M("Setting policy...");Z.start();let z={Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:"s3:GetObject",Resource:`arn:aws:s3:::${J}/*`}]};await Q.putBucketPolicy(J,z),Z.succeed("Public read policy set");return}if(Y.set){let U=new M("Setting policy...");U.start();let z=await Bun.file(Y.set).text();await Q.putBucketPolicy(J,z),U.succeed("Policy set");return}let W=new M("Fetching policy...");W.start();try{let U=await Q.getBucketPolicy(J);W.succeed("Policy loaded"),G(`
1558
+ Bucket Policy:`),console.log(JSON.stringify(U||{},null,2))}catch(U){if(U.message?.includes("NoSuchBucketPolicy"))W.succeed("No policy set"),G("This bucket has no policy configured.");else throw U}}catch(Q){_(`Failed to manage policy: ${Q.message}`),process.exit(1)}}),$.command("storage:ls <bucket>","List objects in a bucket").option("--prefix <prefix>","Filter by prefix").option("--limit <number>","Limit number of results",{default:"100"}).action(async(J,Y)=>{V(`Objects in ${J}`);try{let Q=new X$("us-east-1"),W=new M("Listing objects...");W.start();let U=await Q.listObjects({bucket:J,prefix:Y.prefix,maxKeys:Number.parseInt(Y.limit||"100")}),Z=U.objects;if(W.succeed(`Found ${Z.length} object(s)${U.nextContinuationToken?" (truncated)":""}`),Z.length===0){G("No objects found");return}if(x(["Key","Size","Last Modified"],Z.map((z)=>[z.Key||"N/A",dW(z.Size||0),z.LastModified?new Date(z.LastModified).toLocaleString():"N/A"])),U.nextContinuationToken)G(`
1559
+ More objects available. Use --limit to see more.`)}catch(Q){_(`Failed to list objects: ${Q.message}`),process.exit(1)}})}function uW($){let J=$.split(".").pop()?.toLowerCase();return{html:"text/html",css:"text/css",js:"application/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",eot:"application/vnd.ms-fontobject",pdf:"application/pdf",zip:"application/zip",xml:"application/xml",txt:"text/plain",md:"text/markdown"}[J||""]||"application/octet-stream"}function dW($){if($===0)return"0 B";let J=1024,Y=["B","KB","MB","GB","TB"],Q=Math.floor(Math.log($)/Math.log(J));return`${Number.parseFloat(($/J**Q).toFixed(2))} ${Y[Q]}`}W$();class E0{client;region;constructor($="us-east-1",J){this.region=$,this.client=new l}async describeCacheClusters($){let J={Action:"DescribeCacheClusters",Version:"2015-02-02",ShowCacheNodeInfo:"true"};if($)J.CacheClusterId=$;let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{CacheClusters:this.parseCacheClusters(Y)}}async describeReplicationGroups($){let J={Action:"DescribeReplicationGroups",Version:"2015-02-02"};if($)J.ReplicationGroupId=$;let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{ReplicationGroups:[]}}async createCacheCluster($){let J={Action:"CreateCacheCluster",Version:"2015-02-02",CacheClusterId:$.cacheClusterId,Engine:$.engine,CacheNodeType:$.cacheNodeType};if($.numCacheNodes)J.NumCacheNodes=$.numCacheNodes;if($.engineVersion)J.EngineVersion=$.engineVersion;if($.port)J.Port=$.port;if($.securityGroupIds&&$.securityGroupIds.length>0)$.securityGroupIds.forEach((Q,W)=>{J[`SecurityGroupIds.member.${W+1}`]=Q});if($.subnetGroupName)J.CacheSubnetGroupName=$.subnetGroupName;if($.tags&&$.tags.length>0)$.tags.forEach((Q,W)=>{J[`Tags.member.${W+1}.Key`]=Q.Key,J[`Tags.member.${W+1}.Value`]=Q.Value});let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{CacheCluster:this.parseCacheCluster(Y)}}async deleteCacheCluster($,J){let Y={Action:"DeleteCacheCluster",Version:"2015-02-02",CacheClusterId:$};if(J)Y.FinalSnapshotIdentifier=J;await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async rebootCacheCluster($,J){let Y={Action:"RebootCacheCluster",Version:"2015-02-02",CacheClusterId:$};J.forEach((Q,W)=>{Y[`CacheNodeIdsToReboot.member.${W+1}`]=Q}),await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async describeCacheEngineVersions($){let J={Action:"DescribeCacheEngineVersions",Version:"2015-02-02"};if($)J.Engine=$;let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{CacheEngineVersions:[]}}async getCacheStatistics($){let J=await this.describeCacheClusters($);if(!J.CacheClusters||J.CacheClusters.length===0)throw Error(`Cache cluster ${$} not found`);return{cpuUtilization:0,evictions:0,hits:0,misses:0,connections:0}}parseCacheClusters($){if($.CacheClusterId)return[{CacheClusterId:$.CacheClusterId,CacheClusterStatus:$.CacheClusterStatus||"available",Engine:$.Engine||"redis",EngineVersion:$.EngineVersion||"7.0",CacheNodeType:$.CacheNodeType||"cache.t3.micro",NumCacheNodes:Number.parseInt($.NumCacheNodes||"1"),CacheClusterCreateTime:$.CacheClusterCreateTime||new Date().toISOString()}];return[]}parseCacheCluster($){return{CacheClusterId:$.CacheClusterId,CacheClusterStatus:$.CacheClusterStatus||"creating",Engine:$.Engine||"redis",EngineVersion:$.EngineVersion||"7.0",CacheNodeType:$.CacheNodeType||"cache.t3.micro",NumCacheNodes:Number.parseInt($.NumCacheNodes||"1"),CacheClusterCreateTime:$.CacheClusterCreateTime||new Date().toISOString()}}}function v6($){$.command("cache:list","List all ElastiCache clusters").option("--region <region>","AWS region").action(async(J)=>{V("ElastiCache Clusters");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=new E0(Q),U=new M("Fetching clusters...");U.start();let z=(await W.describeCacheClusters()).CacheClusters||[];if(U.succeed(`Found ${z.length} cluster(s)`),z.length===0){G("No ElastiCache clusters found"),G("Use `cloud cache:create` to create a new cluster");return}x(["Cluster ID","Engine","Node Type","Nodes","Status"],z.map((H)=>[H.CacheClusterId||"N/A",`${H.Engine||"N/A"} ${H.EngineVersion||""}`,H.CacheNodeType||"N/A",(H.NumCacheNodes||0).toString(),H.CacheClusterStatus||"N/A"]))}catch(Y){_(`Failed to list clusters: ${Y.message}`),process.exit(1)}}),$.command("cache:create <name>","Create a new ElastiCache cluster").option("--engine <engine>","Cache engine (redis or memcached)",{default:"redis"}).option("--node-type <type>","Node instance type",{default:"cache.t3.micro"}).option("--nodes <number>","Number of cache nodes",{default:"1"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--version <version>","Engine version").action(async(J,Y)=>{V("Create ElastiCache Cluster");try{let Q=new E0(Y.region);if(G(`Cluster ID: ${J}`),G(`Engine: ${Y.engine}`),G(`Node Type: ${Y.nodeType}`),G(`Number of Nodes: ${Y.nodes}`),G(`Region: ${Y.region}`),!await P(`
1560
+ Create this cluster?`,!0)){G("Operation cancelled");return}let U=new M("Creating cluster...");U.start(),await Q.createCacheCluster({cacheClusterId:J,engine:Y.engine,cacheNodeType:Y.nodeType,numCacheNodes:Number.parseInt(Y.nodes),engineVersion:Y.version}),U.succeed("Cluster creation initiated"),A(`
1561
+ Cluster: ${J}`),G("Status: creating"),G(`
1562
+ Note: Cluster creation may take several minutes.`),G("Use `cloud cache:list` to check status.")}catch(Q){_(`Failed to create cluster: ${Q.message}`),process.exit(1)}}),$.command("cache:delete <clusterId>","Delete an ElastiCache cluster").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{V("Delete ElastiCache Cluster");try{let Q=new E0(Y.region);if(N(`This will permanently delete cluster: ${J}`),N("All data in the cluster will be lost!"),!await P(`
1563
+ Delete this cluster?`,!1)){G("Operation cancelled");return}let U=new M("Deleting cluster...");U.start(),await Q.deleteCacheCluster(J),U.succeed("Cluster deletion initiated"),G(`
1564
+ Note: Cluster deletion may take several minutes.`)}catch(Q){_(`Failed to delete cluster: ${Q.message}`),process.exit(1)}}),$.command("cache:stats <clusterId>","Show ElastiCache cluster statistics").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{V(`ElastiCache Stats: ${J}`);try{let Q=new E0(Y.region),W=new M("Fetching cluster details...");W.start();let Z=(await Q.describeCacheClusters(J)).CacheClusters?.[0];if(!Z){W.fail("Cluster not found");return}if(W.succeed("Cluster details loaded"),G(`
1565
+ Cluster Information:`),G(` Cluster ID: ${Z.CacheClusterId}`),G(` Engine: ${Z.Engine} ${Z.EngineVersion}`),G(` Node Type: ${Z.CacheNodeType}`),G(` Status: ${Z.CacheClusterStatus}`),G(` Nodes: ${Z.NumCacheNodes}`),G(` Availability Zone: ${Z.PreferredAvailabilityZone||"Not set"}`),Z.CacheNodes&&Z.CacheNodes.length>0){G(`
1566
+ Cache Nodes:`);for(let z of Z.CacheNodes)if(G(` - ${z.CacheNodeId}: ${z.CacheNodeStatus}`),z.Endpoint)G(` Endpoint: ${z.Endpoint.Address}:${z.Endpoint.Port}`)}}catch(Q){_(`Failed to get cluster stats: ${Q.message}`),process.exit(1)}}),$.command("cache:flush <clusterId>","Flush all data from a Redis cluster").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{V("Flush ElastiCache Cluster");try{let Q=new E0(Y.region),W=new M("Getting cluster endpoint...");W.start();let Z=(await Q.describeCacheClusters(J)).CacheClusters?.[0];if(!Z){W.fail("Cluster not found");return}if(Z.Engine!=="redis"){W.fail("Flush is only supported for Redis clusters"),G("For Memcached, items expire automatically based on TTL.");return}W.stop();let z=Z.CacheNodes?.[0]?.Endpoint;if(!z){_("Could not determine cluster endpoint");return}if(N(`This will delete ALL data in cluster: ${J}`),N(`Endpoint: ${z.Address}:${z.Port}`),N("This action cannot be undone!"),!await P(`
1567
+ Flush all data?`,!1)){G("Operation cancelled");return}G(`
1568
+ To flush the Redis cluster, connect and run FLUSHALL:`),G(` redis-cli -h ${z.Address} -p ${z.Port} FLUSHALL`),G(`
1569
+ Note: Direct FLUSHALL via AWS API is not supported.`),G("You must connect to the cluster directly to execute this command.")}catch(Q){_(`Failed to get cluster info: ${Q.message}`),process.exit(1)}}),$.command("cache:reboot <clusterId>","Reboot cache cluster nodes").option("--region <region>","AWS region",{default:"us-east-1"}).option("--node <nodeId>","Specific node ID to reboot").action(async(J,Y)=>{V("Reboot ElastiCache Cluster");try{let Q=new E0(Y.region),W=new M("Getting cluster info...");W.start();let Z=(await Q.describeCacheClusters(J)).CacheClusters?.[0];if(!Z){W.fail("Cluster not found");return}W.stop();let z=Y.node?[Y.node]:Z.CacheNodes?.map((B)=>B.CacheNodeId).filter(Boolean)||[];if(z.length===0){_("No nodes found to reboot");return}if(N(`This will reboot the following nodes: ${z.join(", ")}`),N("The cluster may be temporarily unavailable during reboot."),!await P(`
1570
+ Reboot these nodes?`,!1)){G("Operation cancelled");return}let K=new M("Rebooting nodes...");K.start(),await Q.rebootCacheCluster(J,z),K.succeed("Reboot initiated"),G(`
1571
+ Note: Reboot may take several minutes to complete.`),G("Use `cloud cache:stats` to check status.")}catch(Q){_(`Failed to reboot cluster: ${Q.message}`),process.exit(1)}})}f6();function g6($){$.command("queue:list","List all SQS queues").option("--region <region>","AWS region").action(async(J)=>{V("SQS Queues");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=new e$(Q),U=new M("Fetching queues...");U.start();let z=(await W.listQueues()).QueueUrls||[];if(U.succeed(`Found ${z.length} queue(s)`),z.length===0){G("No SQS queues found"),G("Use `cloud queue:create` to create a new queue");return}let H=[];for(let K of z)try{let B=await W.getQueueAttributes(K),O=K.split("/").pop()||K;H.push({url:K,name:O,messages:B.Attributes?.ApproximateNumberOfMessages||"0",type:B.Attributes?.FifoQueue==="true"?"FIFO":"Standard"})}catch{let B=K.split("/").pop()||K;H.push({url:K,name:B,messages:"N/A",type:"Unknown"})}x(["Queue Name","Messages","Type"],H.map((K)=>[K.name,K.messages,K.type]))}catch(Y){_(`Failed to list queues: ${Y.message}`),process.exit(1)}}),$.command("queue:create <name>","Create a new SQS queue").option("--region <region>","AWS region",{default:"us-east-1"}).option("--fifo","Create a FIFO queue").option("--dlq <queueArn>","Dead letter queue ARN").option("--max-retries <number>","Max receive count before DLQ",{default:"3"}).option("--visibility <seconds>","Visibility timeout in seconds",{default:"30"}).option("--retention <days>","Message retention in days",{default:"4"}).action(async(J,Y)=>{V("Create SQS Queue");try{let Q=new e$(Y.region),W=Y.fifo&&!J.endsWith(".fifo")?`${J}.fifo`:J;if(G(`Queue name: ${W}`),G(`Type: ${Y.fifo?"FIFO":"Standard"}`),G(`Visibility timeout: ${Y.visibility} seconds`),G(`Message retention: ${Y.retention} days`),Y.dlq)G(`Dead letter queue: ${Y.dlq}`),G(`Max retries: ${Y.maxRetries}`);if(!await P(`
1572
+ Create this queue?`,!0)){G("Operation cancelled");return}let Z=new M("Creating queue...");Z.start();let z=await Q.createQueue({queueName:W,fifo:Y.fifo,visibilityTimeout:Number.parseInt(Y.visibility),messageRetentionPeriod:Number.parseInt(Y.retention)*24*60*60,contentBasedDeduplication:Y.fifo?!0:void 0,deadLetterTargetArn:Y.dlq,maxReceiveCount:Y.dlq?Number.parseInt(Y.maxRetries):void 0});Z.succeed("Queue created"),A(`
1573
+ Queue URL: ${z.QueueUrl}`),G(`
1574
+ To send a message:`),G(` cloud queue:send ${W} --message "Hello World"`)}catch(Q){_(`Failed to create queue: ${Q.message}`),process.exit(1)}}),$.command("queue:delete <name>","Delete an SQS queue").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{V("Delete SQS Queue");try{let Q=new e$(Y.region);if(N(`This will permanently delete queue: ${J}`),N("All messages in the queue will be lost!"),!await P(`
1575
+ Delete this queue?`,!1)){G("Operation cancelled");return}let U=new M("Getting queue URL...");U.start();let Z=await Q.getQueueUrl(J);if(!Z.QueueUrl){U.fail("Queue not found");return}U.text="Deleting queue...",await Q.deleteQueue(Z.QueueUrl),U.succeed("Queue deleted")}catch(Q){_(`Failed to delete queue: ${Q.message}`),process.exit(1)}}),$.command("queue:send <name>","Send a message to an SQS queue").option("--region <region>","AWS region",{default:"us-east-1"}).option("--message <body>","Message body").option("--file <path>","Read message body from file").option("--group <id>","Message group ID (for FIFO queues)").option("--dedup <id>","Deduplication ID (for FIFO queues)").option("--delay <seconds>","Delay delivery in seconds",{default:"0"}).action(async(J,Y)=>{V("Send SQS Message");try{let Q=new e$(Y.region),W;if(Y.file)W=await Bun.file(Y.file).text();else if(Y.message)W=Y.message;else W=await U$("Message body");if(!W){_("Message body is required");return}let U=new M("Getting queue URL...");U.start();let Z=await Q.getQueueUrl(J);if(!Z.QueueUrl){U.fail("Queue not found");return}U.text="Sending message...";let z=await Q.sendMessage({queueUrl:Z.QueueUrl,messageBody:W,delaySeconds:Number.parseInt(Y.delay),messageGroupId:Y.group,messageDeduplicationId:Y.dedup});U.succeed("Message sent"),A(`
1576
+ Message ID: ${z.MessageId}`)}catch(Q){_(`Failed to send message: ${Q.message}`),process.exit(1)}}),$.command("queue:receive <name>","Receive messages from an SQS queue").option("--region <region>","AWS region",{default:"us-east-1"}).option("--max <number>","Maximum number of messages",{default:"1"}).option("--wait <seconds>","Long polling wait time",{default:"0"}).option("--delete","Delete messages after receiving").action(async(J,Y)=>{V("Receive SQS Messages");try{let Q=new e$(Y.region),W=new M("Getting queue URL...");W.start();let U=await Q.getQueueUrl(J);if(!U.QueueUrl){W.fail("Queue not found");return}W.text="Receiving messages...";let z=(await Q.receiveMessages({queueUrl:U.QueueUrl,maxMessages:Number.parseInt(Y.max),waitTimeSeconds:Number.parseInt(Y.wait)})).Messages||[];if(W.succeed(`Received ${z.length} message(s)`),z.length===0){G("No messages available");return}for(let H of z){if(G(`
1577
+ --- Message: ${H.MessageId} ---`),G(`Body: ${H.Body}`),H.Attributes)G(`Sent: ${H.Attributes.SentTimestamp?new Date(Number.parseInt(H.Attributes.SentTimestamp)).toISOString():"N/A"}`),G(`Receive Count: ${H.Attributes.ApproximateReceiveCount||"N/A"}`);if(Y.delete&&H.ReceiptHandle)await Q.deleteMessage(U.QueueUrl,H.ReceiptHandle),G("(Deleted)")}}catch(Q){_(`Failed to receive messages: ${Q.message}`),process.exit(1)}}),$.command("queue:purge <name>","Purge all messages from an SQS queue").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{V("Purge SQS Queue");try{let Q=new e$(Y.region);if(N(`This will delete ALL messages in queue: ${J}`),N("This action cannot be undone!"),!await P(`
1578
+ Purge this queue?`,!1)){G("Operation cancelled");return}let U=new M("Getting queue URL...");U.start();let Z=await Q.getQueueUrl(J);if(!Z.QueueUrl){U.fail("Queue not found");return}U.text="Purging queue...",await Q.purgeQueue(Z.QueueUrl),U.succeed("Queue purged"),G(`
1579
+ Note: It may take up to 60 seconds for the purge to complete.`)}catch(Q){_(`Failed to purge queue: ${Q.message}`),process.exit(1)}}),$.command("queue:stats <name>","Show SQS queue statistics").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{V(`SQS Queue Stats: ${J}`);try{let Q=new e$(Y.region),W=new M("Fetching queue stats...");W.start();let U=await Q.getQueueUrl(J);if(!U.QueueUrl){W.fail("Queue not found");return}let Z=await Q.getQueueAttributes(U.QueueUrl);W.succeed("Stats loaded");let z=Z.Attributes||{};if(G(`
1580
+ Queue Information:`),G(` URL: ${U.QueueUrl}`),G(` ARN: ${z.QueueArn||"N/A"}`),G(` Type: ${z.FifoQueue==="true"?"FIFO":"Standard"}`),G(`
1581
+ Messages:`),G(` Available: ${z.ApproximateNumberOfMessages||"0"}`),G(` In Flight: ${z.ApproximateNumberOfMessagesNotVisible||"0"}`),G(` Delayed: ${z.ApproximateNumberOfMessagesDelayed||"0"}`),G(`
1582
+ Configuration:`),G(` Visibility Timeout: ${z.VisibilityTimeout||"30"} seconds`),G(` Message Retention: ${Number.parseInt(z.MessageRetentionPeriod||"345600")/86400} days`),G(` Max Message Size: ${Number.parseInt(z.MaximumMessageSize||"262144")/1024} KB`),G(` Receive Wait Time: ${z.ReceiveMessageWaitTimeSeconds||"0"} seconds`),z.RedrivePolicy){let H=JSON.parse(z.RedrivePolicy);G(`
1583
+ Dead Letter Queue:`),G(` Target ARN: ${H.deadLetterTargetArn}`),G(` Max Receives: ${H.maxReceiveCount}`)}G(`
1584
+ Timestamps:`),G(` Created: ${z.CreatedTimestamp?new Date(Number.parseInt(z.CreatedTimestamp)*1000).toISOString():"N/A"}`),G(` Last Modified: ${z.LastModifiedTimestamp?new Date(Number.parseInt(z.LastModifiedTimestamp)*1000).toISOString():"N/A"}`)}catch(Q){_(`Failed to get queue stats: ${Q.message}`),process.exit(1)}})}u6();function d6($){$.command("network:list","List all VPCs").option("--region <region>","AWS region").action(async(J)=>{V("VPCs");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=new b$(Q),U=new M("Fetching VPCs...");U.start();let z=(await W.describeVpcs()).Vpcs||[];if(U.succeed(`Found ${z.length} VPC(s)`),z.length===0){G("No VPCs found");return}x(["VPC ID","Name","CIDR","State","Default"],z.map((H)=>[H.VpcId||"N/A",H.Tags?.find((K)=>K.Key==="Name")?.Value||"-",H.CidrBlock||"N/A",H.State||"N/A",H.IsDefault?"Yes":"No"]))}catch(Y){_(`Failed to list VPCs: ${Y.message}`),process.exit(1)}}),$.command("network:subnets","List all subnets").option("--region <region>","AWS region").option("--vpc <vpcId>","Filter by VPC ID").action(async(J)=>{V("Subnets");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=new b$(Q),U=new M("Fetching subnets...");U.start();let Z=J.vpc?[{Name:"vpc-id",Values:[J.vpc]}]:void 0,H=(await W.describeSubnets({Filters:Z})).Subnets||[];if(U.succeed(`Found ${H.length} subnet(s)`),H.length===0){G("No subnets found");return}x(["Subnet ID","Name","VPC","CIDR","AZ","IPs Available","Public"],H.map((K)=>[K.SubnetId||"N/A",K.Tags?.find((B)=>B.Key==="Name")?.Value||"-",K.VpcId||"N/A",K.CidrBlock||"N/A",K.AvailabilityZone||"N/A",(K.AvailableIpAddressCount||0).toString(),K.MapPublicIpOnLaunch?"Yes":"No"]))}catch(Y){_(`Failed to list subnets: ${Y.message}`),process.exit(1)}}),$.command("network:security-groups","List all security groups").option("--region <region>","AWS region").option("--vpc <vpcId>","Filter by VPC ID").action(async(J)=>{V("Security Groups");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=new b$(Q),U=new M("Fetching security groups...");U.start();let Z=J.vpc?[{Name:"vpc-id",Values:[J.vpc]}]:void 0,H=(await W.describeSecurityGroups({Filters:Z})).SecurityGroups||[];if(U.succeed(`Found ${H.length} security group(s)`),H.length===0){G("No security groups found");return}x(["Group ID","Name","VPC","Description","Inbound Rules","Outbound Rules"],H.map((K)=>[K.GroupId||"N/A",K.GroupName||"N/A",K.VpcId||"N/A",(K.Description||"").substring(0,30),(K.IpPermissions?.length||0).toString(),(K.IpPermissionsEgress?.length||0).toString()]))}catch(Y){_(`Failed to list security groups: ${Y.message}`),process.exit(1)}}),$.command("network:security-group <groupId>","Show security group details").option("--region <region>","AWS region").action(async(J,Y)=>{V(`Security Group: ${J}`);try{let Q=await g(),W=Y.region||Q.project.region||"us-east-1",U=new b$(W),Z=new M("Fetching security group...");Z.start();let H=(await U.describeSecurityGroups({GroupIds:[J]})).SecurityGroups?.[0];if(!H){Z.fail("Security group not found");return}if(Z.succeed("Security group loaded"),G(`
1585
+ General Information:`),G(` Group ID: ${H.GroupId}`),G(` Name: ${H.GroupName}`),G(` VPC: ${H.VpcId}`),G(` Description: ${H.Description}`),H.IpPermissions&&H.IpPermissions.length>0){G(`
1586
+ Inbound Rules:`);for(let K of H.IpPermissions){let B=K.IpProtocol==="-1"?"All":K.IpProtocol?.toUpperCase(),O=K.FromPort===K.ToPort?K.FromPort?.toString()||"All":`${K.FromPort}-${K.ToPort}`;for(let X of K.IpRanges||[])G(` - ${B} ${O} from ${X.CidrIp}${X.Description?` (${X.Description})`:""}`);for(let X of K.UserIdGroupPairs||[])G(` - ${B} ${O} from ${X.GroupId}${X.Description?` (${X.Description})`:""}`)}}else G(`
1587
+ No inbound rules configured.`);if(H.IpPermissionsEgress&&H.IpPermissionsEgress.length>0){G(`
1588
+ Outbound Rules:`);for(let K of H.IpPermissionsEgress){let B=K.IpProtocol==="-1"?"All":K.IpProtocol?.toUpperCase(),O=K.FromPort===K.ToPort?K.FromPort?.toString()||"All":`${K.FromPort}-${K.ToPort}`;for(let X of K.IpRanges||[])G(` - ${B} ${O} to ${X.CidrIp}${X.Description?` (${X.Description})`:""}`);for(let X of K.UserIdGroupPairs||[])G(` - ${B} ${O} to ${X.GroupId}${X.Description?` (${X.Description})`:""}`)}}else G(`
1589
+ No outbound rules configured.`);if(H.Tags&&H.Tags.length>0){G(`
1590
+ Tags:`);for(let K of H.Tags)G(` ${K.Key}: ${K.Value}`)}}catch(Q){_(`Failed to get security group: ${Q.message}`),process.exit(1)}}),$.command("network:create-vpc <cidr>","Create a new VPC").option("--region <region>","AWS region",{default:"us-east-1"}).option("--name <name>","VPC name tag").option("--tenancy <tenancy>","Instance tenancy (default or dedicated)",{default:"default"}).action(async(J,Y)=>{V("Create VPC");try{let Q=new b$(Y.region);if(G(`CIDR Block: ${J}`),G(`Region: ${Y.region}`),G(`Tenancy: ${Y.tenancy}`),Y.name)G(`Name: ${Y.name}`);if(!await P(`
1591
+ Create this VPC?`,!0)){G("Operation cancelled");return}let U=new M("Creating VPC...");U.start();let Z=await Q.createVpc({CidrBlock:J,InstanceTenancy:Y.tenancy,TagSpecifications:Y.name?[{ResourceType:"vpc",Tags:[{Key:"Name",Value:Y.name}]}]:void 0});U.succeed("VPC created"),A(`
1592
+ VPC ID: ${Z.Vpc?.VpcId}`),G(`CIDR: ${Z.Vpc?.CidrBlock}`),G(`State: ${Z.Vpc?.State}`)}catch(Q){_(`Failed to create VPC: ${Q.message}`),process.exit(1)}}),$.command("network:create-subnet <vpcId> <cidr>","Create a new subnet").option("--region <region>","AWS region",{default:"us-east-1"}).option("--name <name>","Subnet name tag").option("--az <zone>","Availability zone").option("--public","Auto-assign public IPs").action(async(J,Y,Q)=>{V("Create Subnet");try{let W=new b$(Q.region);if(G(`VPC: ${J}`),G(`CIDR Block: ${Y}`),Q.az)G(`Availability Zone: ${Q.az}`);if(Q.name)G(`Name: ${Q.name}`);if(G(`Auto-assign Public IP: ${Q.public?"Yes":"No"}`),!await P(`
1593
+ Create this subnet?`,!0)){G("Operation cancelled");return}let Z=new M("Creating subnet...");Z.start();let z=await W.createSubnet({VpcId:J,CidrBlock:Y,AvailabilityZone:Q.az,TagSpecifications:Q.name?[{ResourceType:"subnet",Tags:[{Key:"Name",Value:Q.name}]}]:void 0});if(Q.public&&z.Subnet?.SubnetId)Z.text="Enabling auto-assign public IP...",await W.modifySubnetAttribute({SubnetId:z.Subnet.SubnetId,MapPublicIpOnLaunch:{Value:!0}});Z.succeed("Subnet created"),A(`
1594
+ Subnet ID: ${z.Subnet?.SubnetId}`),G(`CIDR: ${z.Subnet?.CidrBlock}`),G(`Availability Zone: ${z.Subnet?.AvailabilityZone}`)}catch(W){_(`Failed to create subnet: ${W.message}`),process.exit(1)}}),$.command("network:create-sg <vpcId> <name>","Create a new security group").option("--region <region>","AWS region",{default:"us-east-1"}).option("--description <desc>","Security group description").action(async(J,Y,Q)=>{V("Create Security Group");try{let W=new b$(Q.region),U=Q.description||`Security group for ${Y}`;if(G(`VPC: ${J}`),G(`Name: ${Y}`),G(`Description: ${U}`),!await P(`
1595
+ Create this security group?`,!0)){G("Operation cancelled");return}let z=new M("Creating security group...");z.start();let H=await W.createSecurityGroup({GroupName:Y,Description:U,VpcId:J,TagSpecifications:[{ResourceType:"security-group",Tags:[{Key:"Name",Value:Y}]}]});z.succeed("Security group created"),A(`
1596
+ Group ID: ${H.GroupId}`),G(`
1597
+ To add rules:`),G(` cloud network:sg-rule ${H.GroupId} --inbound --port 443 --cidr 0.0.0.0/0`)}catch(W){_(`Failed to create security group: ${W.message}`),process.exit(1)}}),$.command("network:sg-rule <groupId>","Add a rule to a security group").option("--region <region>","AWS region",{default:"us-east-1"}).option("--inbound","Add inbound rule").option("--outbound","Add outbound rule").option("--protocol <protocol>","Protocol (tcp, udp, icmp, or -1 for all)",{default:"tcp"}).option("--port <port>","Port number or range (e.g., 80 or 80-443)").option("--cidr <cidr>","CIDR block (e.g., 0.0.0.0/0)").option("--source-group <groupId>","Source security group").option("--description <desc>","Rule description").action(async(J,Y)=>{V("Add Security Group Rule");try{let Q=new b$(Y.region);if(!Y.inbound&&!Y.outbound){_("Specify --inbound or --outbound");return}if(!Y.cidr&&!Y.sourceGroup){_("Specify --cidr or --source-group");return}let W,U;if(Y.port)if(Y.port.includes("-")){let[O,X]=Y.port.split("-");W=Number.parseInt(O),U=Number.parseInt(X)}else W=Number.parseInt(Y.port),U=W;else if(Y.protocol!=="-1"){_("Port is required for TCP/UDP protocols");return}let Z=Y.inbound?"Inbound":"Outbound",z=Y.protocol==="-1"?"All":W===U?W:`${W}-${U}`;if(G(`Security Group: ${J}`),G(`Direction: ${Z}`),G(`Protocol: ${Y.protocol}`),G(`Port(s): ${z}`),G(`Source: ${Y.cidr||Y.sourceGroup}`),!await P(`
1598
+ Add this rule?`,!0)){G("Operation cancelled");return}let K=new M("Adding rule...");K.start();let B={IpProtocol:Y.protocol,FromPort:W,ToPort:U};if(Y.cidr)B.IpRanges=[{CidrIp:Y.cidr,Description:Y.description}];if(Y.sourceGroup)B.UserIdGroupPairs=[{GroupId:Y.sourceGroup,Description:Y.description}];if(Y.inbound)await Q.authorizeSecurityGroupIngress({GroupId:J,IpPermissions:[B]});else await Q.authorizeSecurityGroupEgress({GroupId:J,IpPermissions:[B]});K.succeed("Rule added")}catch(Q){_(`Failed to add rule: ${Q.message}`),process.exit(1)}}),$.command("network:elastic-ips","List Elastic IP addresses").option("--region <region>","AWS region").action(async(J)=>{V("Elastic IP Addresses");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=new b$(Q),U=new M("Fetching Elastic IPs...");U.start();let z=(await W.describeAddresses()).Addresses||[];if(U.succeed(`Found ${z.length} Elastic IP(s)`),z.length===0){G("No Elastic IPs found");return}x(["Public IP","Allocation ID","Association ID","Instance","Name"],z.map((H)=>[H.PublicIp||"N/A",H.AllocationId||"N/A",H.AssociationId||"-",H.InstanceId||"-",H.Tags?.find((K)=>K.Key==="Name")?.Value||"-"]))}catch(Y){_(`Failed to list Elastic IPs: ${Y.message}`),process.exit(1)}}),$.command("network:route-tables","List route tables").option("--region <region>","AWS region").option("--vpc <vpcId>","Filter by VPC ID").action(async(J)=>{V("Route Tables");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=new b$(Q),U=new M("Fetching route tables...");U.start();let Z=J.vpc?[{Name:"vpc-id",Values:[J.vpc]}]:void 0,H=(await W.describeRouteTables({Filters:Z})).RouteTables||[];if(U.succeed(`Found ${H.length} route table(s)`),H.length===0){G("No route tables found");return}x(["Route Table ID","VPC","Name","Main","Associations","Routes"],H.map((K)=>[K.RouteTableId||"N/A",K.VpcId||"N/A",K.Tags?.find((B)=>B.Key==="Name")?.Value||"-",K.Associations?.some((B)=>B.Main)?"Yes":"No",(K.Associations?.length||0).toString(),(K.Routes?.length||0).toString()]))}catch(Y){_(`Failed to list route tables: ${Y.message}`),process.exit(1)}})}W$();class H0{client;region;constructor($="us-east-1",J){this.region=$,this.client=new l}async createRule($){let J={Action:"PutRule",Name:$.name,ScheduleExpression:$.scheduleExpression,Version:"2015-10-07"};if($.description)J.Description=$.description;if($.state)J.State=$.state;else J.State="ENABLED";return{RuleArn:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$.name,ScheduleExpression:$.scheduleExpression,State:$.state||"ENABLED",Description:$.description})})).RuleArn}}async putTargets($,J){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:$,Targets:J})})}async listRules($){let J={};if($)J.NamePrefix=$;return{Rules:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListRules","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})).Rules||[]}}async describeRule($){let J=await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DescribeRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$})});return{Name:J.Name,Arn:J.Arn,ScheduleExpression:J.ScheduleExpression,State:J.State,Description:J.Description}}async listTargetsByRule($){return{Targets:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListTargetsByRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:$})})).Targets||[]}}async deleteRule($,J){if(J)try{let Y=await this.listTargetsByRule($);if(Y.Targets&&Y.Targets.length>0)await this.removeTargets($,Y.Targets.map((Q)=>Q.Id))}catch{}await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DeleteRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$,Force:J||!1})})}async removeTargets($,J){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.RemoveTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:$,Ids:J})})}async enableRule($){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.EnableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$})})}async disableRule($){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DisableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$})})}async createLambdaSchedule($){let J=await this.createRule({name:$.name,scheduleExpression:$.scheduleExpression,description:$.description,state:"ENABLED"});return await this.putTargets($.name,[{Id:"1",Arn:$.functionArn,Input:$.input}]),J}async createEcsSchedule($){let J=await this.createRule({name:$.name,scheduleExpression:$.scheduleExpression,description:$.description,state:"ENABLED"});return await this.putTargets($.name,[{Id:"1",Arn:$.clusterArn,RoleArn:$.roleArn,Input:JSON.stringify({containerOverrides:[]})}]),J}async listSchedules($){let J={};if($?.NamePrefix)J.NamePrefix=$.NamePrefix;if($?.State)J.State=$.State;let Y=$?.GroupName||"default";return{Schedules:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedules",queryParams:{...J,ScheduleGroup:Y}}))?.Schedules||[]}}async getSchedule($){try{let J={};if($.GroupName)J.groupName=$.GroupName;return await this.client.request({service:"scheduler",region:this.region,method:"GET",path:`/schedules/${encodeURIComponent($.Name)}`,queryParams:Object.keys(J).length>0?J:void 0})}catch(J){if(J.statusCode===404||J.code==="ResourceNotFoundException")return null;throw J}}async createSchedule($){let J={ScheduleExpression:$.ScheduleExpression,FlexibleTimeWindow:$.FlexibleTimeWindow,Target:$.Target};if($.GroupName)J.GroupName=$.GroupName;if($.ScheduleExpressionTimezone)J.ScheduleExpressionTimezone=$.ScheduleExpressionTimezone;if($.Description)J.Description=$.Description;if($.State)J.State=$.State;if($.StartDate)J.StartDate=$.StartDate.toISOString();if($.EndDate)J.EndDate=$.EndDate.toISOString();return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${encodeURIComponent($.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(J)}))?.ScheduleArn||""}}async updateSchedule($){let J={};if($.GroupName)J.GroupName=$.GroupName;if($.ScheduleExpression)J.ScheduleExpression=$.ScheduleExpression;if($.ScheduleExpressionTimezone)J.ScheduleExpressionTimezone=$.ScheduleExpressionTimezone;if($.Description!==void 0)J.Description=$.Description;if($.State)J.State=$.State;if($.FlexibleTimeWindow)J.FlexibleTimeWindow=$.FlexibleTimeWindow;if($.Target)J.Target=$.Target;return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"PUT",path:`/schedules/${encodeURIComponent($.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(J)}))?.ScheduleArn||""}}async deleteSchedule($){let J={};if($.GroupName)J.groupName=$.GroupName;await this.client.request({service:"scheduler",region:this.region,method:"DELETE",path:`/schedules/${encodeURIComponent($.Name)}`,queryParams:Object.keys(J).length>0?J:void 0})}async listScheduleGroups($){let J={};if($?.NamePrefix)J.NamePrefix=$.NamePrefix;return{ScheduleGroups:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedule-groups",queryParams:Object.keys(J).length>0?J:void 0}))?.ScheduleGroups||[]}}}function m6($){$.command("scheduler:list","List all EventBridge schedules").option("--region <region>","AWS region").option("--group <name>","Schedule group name",{default:"default"}).action(async(J)=>{V("EventBridge Schedules");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=new H0(Q),U=new M("Fetching schedules...");U.start();let z=(await W.listSchedules({GroupName:J.group})).Schedules||[];if(U.succeed(`Found ${z.length} schedule(s)`),z.length===0){G("No schedules found"),G("Use `cloud scheduler:create` to create a new schedule");return}x(["Name","State","Schedule Expression","Group"],z.map((H)=>[H.Name||"N/A",H.State||"N/A",H.ScheduleExpression||"N/A",H.GroupName||"default"]))}catch(Y){_(`Failed to list schedules: ${Y.message}`),process.exit(1)}}),$.command("scheduler:create <name>","Create a new EventBridge schedule").option("--region <region>","AWS region",{default:"us-east-1"}).option("--schedule <expression>","Schedule expression (rate or cron)").option("--target-arn <arn>","Target ARN (Lambda, SQS, SNS, etc.)").option("--role-arn <arn>","IAM role ARN for scheduler").option("--input <json>","JSON input to pass to target").option("--group <name>","Schedule group name",{default:"default"}).option("--timezone <tz>","Timezone for cron expressions",{default:"UTC"}).option("--description <text>","Schedule description").option("--start <datetime>","Start date/time (ISO 8601)").option("--end <datetime>","End date/time (ISO 8601)").action(async(J,Y)=>{V("Create EventBridge Schedule");try{if(!Y.schedule){_("--schedule is required"),G("Examples:"),G(" Rate: rate(5 minutes), rate(1 hour), rate(1 day)"),G(" Cron: cron(0 12 * * ? *) - every day at 12:00 UTC");return}if(!Y.targetArn){_("--target-arn is required");return}if(!Y.roleArn){_("--role-arn is required"),G("The role must have permissions to invoke the target.");return}let Q=new H0(Y.region);if(G(`Name: ${J}`),G(`Schedule: ${Y.schedule}`),G(`Target: ${Y.targetArn}`),G(`Group: ${Y.group}`),G(`Timezone: ${Y.timezone}`),!await P(`
1599
+ Create this schedule?`,!0)){G("Operation cancelled");return}let U=new M("Creating schedule...");U.start(),await Q.createSchedule({Name:J,GroupName:Y.group,ScheduleExpression:Y.schedule,ScheduleExpressionTimezone:Y.timezone,Description:Y.description,State:"ENABLED",FlexibleTimeWindow:{Mode:"OFF"},Target:{Arn:Y.targetArn,RoleArn:Y.roleArn,Input:Y.input},StartDate:Y.start?new Date(Y.start):void 0,EndDate:Y.end?new Date(Y.end):void 0}),U.succeed("Schedule created"),A(`
1600
+ Schedule: ${J}`),G(`Expression: ${Y.schedule}`)}catch(Q){_(`Failed to create schedule: ${Q.message}`),process.exit(1)}}),$.command("scheduler:delete <name>","Delete an EventBridge schedule").option("--region <region>","AWS region",{default:"us-east-1"}).option("--group <name>","Schedule group name",{default:"default"}).action(async(J,Y)=>{V("Delete EventBridge Schedule");try{let Q=new H0(Y.region);if(N(`This will delete schedule: ${J}`),!await P(`
1601
+ Delete this schedule?`,!1)){G("Operation cancelled");return}let U=new M("Deleting schedule...");U.start(),await Q.deleteSchedule({Name:J,GroupName:Y.group}),U.succeed("Schedule deleted")}catch(Q){_(`Failed to delete schedule: ${Q.message}`),process.exit(1)}}),$.command("scheduler:enable <name>","Enable an EventBridge schedule").option("--region <region>","AWS region",{default:"us-east-1"}).option("--group <name>","Schedule group name",{default:"default"}).action(async(J,Y)=>{V("Enable EventBridge Schedule");try{let Q=new H0(Y.region),W=new M("Getting schedule...");W.start();let U=await Q.getSchedule({Name:J,GroupName:Y.group});if(!U){W.fail("Schedule not found");return}W.text="Enabling schedule...",await Q.updateSchedule({Name:J,GroupName:Y.group,ScheduleExpression:U.ScheduleExpression,ScheduleExpressionTimezone:U.ScheduleExpressionTimezone,FlexibleTimeWindow:U.FlexibleTimeWindow,Target:U.Target,State:"ENABLED"}),W.succeed("Schedule enabled")}catch(Q){_(`Failed to enable schedule: ${Q.message}`),process.exit(1)}}),$.command("scheduler:disable <name>","Disable an EventBridge schedule").option("--region <region>","AWS region",{default:"us-east-1"}).option("--group <name>","Schedule group name",{default:"default"}).action(async(J,Y)=>{V("Disable EventBridge Schedule");try{let Q=new H0(Y.region),W=new M("Getting schedule...");W.start();let U=await Q.getSchedule({Name:J,GroupName:Y.group});if(!U){W.fail("Schedule not found");return}W.text="Disabling schedule...",await Q.updateSchedule({Name:J,GroupName:Y.group,ScheduleExpression:U.ScheduleExpression,ScheduleExpressionTimezone:U.ScheduleExpressionTimezone,FlexibleTimeWindow:U.FlexibleTimeWindow,Target:U.Target,State:"DISABLED"}),W.succeed("Schedule disabled")}catch(Q){_(`Failed to disable schedule: ${Q.message}`),process.exit(1)}}),$.command("scheduler:describe <name>","Show EventBridge schedule details").option("--region <region>","AWS region",{default:"us-east-1"}).option("--group <name>","Schedule group name",{default:"default"}).action(async(J,Y)=>{V(`Schedule: ${J}`);try{let Q=new H0(Y.region),W=new M("Fetching schedule...");W.start();let U=await Q.getSchedule({Name:J,GroupName:Y.group});if(!U){W.fail("Schedule not found");return}if(W.succeed("Schedule loaded"),G(`
1602
+ Schedule Information:`),G(` Name: ${U.Name}`),G(` ARN: ${U.Arn}`),G(` Group: ${U.GroupName}`),G(` State: ${U.State}`),G(` Expression: ${U.ScheduleExpression}`),G(` Timezone: ${U.ScheduleExpressionTimezone}`),U.Description)G(` Description: ${U.Description}`);if(U.Target){if(G(`
1603
+ Target:`),G(` ARN: ${U.Target.Arn}`),G(` Role ARN: ${U.Target.RoleArn}`),U.Target.Input)G(` Input: ${U.Target.Input}`)}if(G(`
1604
+ Flexible Time Window:`),G(` Mode: ${U.FlexibleTimeWindow?.Mode}`),U.FlexibleTimeWindow?.MaximumWindowInMinutes)G(` Max Window: ${U.FlexibleTimeWindow.MaximumWindowInMinutes} minutes`);if(U.StartDate)G(`
1605
+ Start Date: ${U.StartDate}`);if(U.EndDate)G(`End Date: ${U.EndDate}`);G(`
1606
+ Created: ${U.CreationDate||"N/A"}`),G(`Last Modified: ${U.LastModificationDate||"N/A"}`)}catch(Q){_(`Failed to get schedule: ${Q.message}`),process.exit(1)}}),$.command("scheduler:groups","List schedule groups").option("--region <region>","AWS region").action(async(J)=>{V("Schedule Groups");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=new H0(Q),U=new M("Fetching groups...");U.start();let z=(await W.listScheduleGroups()).ScheduleGroups||[];if(U.succeed(`Found ${z.length} group(s)`),z.length===0){G("No schedule groups found");return}x(["Name","State","Created"],z.map((H)=>[H.Name||"N/A",H.State||"N/A",H.CreationDate?new Date(H.CreationDate).toLocaleString():"N/A"]))}catch(Y){_(`Failed to list groups: ${Y.message}`),process.exit(1)}})}W$();class $0{client;region;constructor($="us-east-1"){this.region=$,this.client=new l}async request($,J){return this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSEvents.${$}`},body:JSON.stringify(J)})}async putRule($){return this.request("PutRule",$)}async deleteRule($){return this.request("DeleteRule",$)}async describeRule($){return this.request("DescribeRule",$)}async listRules($){return this.request("ListRules",$||{})}async listEventBuses($){return this.request("ListEventBuses",$||{})}async enableRule($){return this.request("EnableRule",$)}async disableRule($){return this.request("DisableRule",$)}async putTargets($){return this.request("PutTargets",$)}async removeTargets($){return this.request("RemoveTargets",$)}async listTargetsByRule($){return this.request("ListTargetsByRule",$)}async putEvents($){return this.request("PutEvents",$)}async createSchedule($){return this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${$.Name}`,headers:{"Content-Type":"application/json"},body:JSON.stringify($)})}}function c6($){$.command("events:list","List all EventBridge rules").option("--region <region>","AWS region").option("--bus <name>","Event bus name",{default:"default"}).action(async(J)=>{V("EventBridge Rules");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=new $0(Q),U=new M("Fetching rules...");U.start();let z=(await W.listRules({EventBusName:J.bus})).Rules||[];if(U.succeed(`Found ${z.length} rule(s)`),z.length===0){G("No EventBridge rules found"),G("Use `cloud events:create` to create a new rule");return}x(["Name","State","Schedule/Pattern","Description"],z.map((H)=>[H.Name||"N/A",H.State||"N/A",H.ScheduleExpression||(H.EventPattern?"Event Pattern":"N/A"),(H.Description||"").substring(0,40)]))}catch(Y){_(`Failed to list rules: ${Y.message}`),process.exit(1)}}),$.command("events:create <name>","Create a new EventBridge rule").option("--region <region>","AWS region",{default:"us-east-1"}).option("--bus <name>","Event bus name",{default:"default"}).option("--schedule <expression>","Schedule expression (rate or cron)").option("--pattern <json>","Event pattern JSON").option("--pattern-file <path>","Event pattern from JSON file").option("--description <text>","Rule description").option("--disabled","Create in disabled state").action(async(J,Y)=>{V("Create EventBridge Rule");try{if(!Y.schedule&&!Y.pattern&&!Y.patternFile){_("Either --schedule or --pattern/--pattern-file is required"),G(`
1607
+ Examples:`),G(' Schedule: --schedule "rate(5 minutes)"'),G(` Pattern: --pattern '{"source": ["aws.ec2"]}'`);return}let Q=new $0(Y.region),W;if(Y.patternFile)W=await Bun.file(Y.patternFile).text();else if(Y.pattern)W=Y.pattern;if(G(`Name: ${J}`),G(`Event Bus: ${Y.bus}`),Y.schedule)G(`Schedule: ${Y.schedule}`);if(W)G(`Event Pattern: ${W}`);if(G(`State: ${Y.disabled?"DISABLED":"ENABLED"}`),!await P(`
1608
+ Create this rule?`,!0)){G("Operation cancelled");return}let Z=new M("Creating rule...");Z.start();let z=await Q.putRule({Name:J,EventBusName:Y.bus,ScheduleExpression:Y.schedule,EventPattern:W,Description:Y.description,State:Y.disabled?"DISABLED":"ENABLED"});Z.succeed("Rule created"),A(`
1609
+ Rule ARN: ${z.RuleArn}`),G("\nNote: Add targets to the rule with `cloud events:target`")}catch(Q){_(`Failed to create rule: ${Q.message}`),process.exit(1)}}),$.command("events:delete <name>","Delete an EventBridge rule").option("--region <region>","AWS region",{default:"us-east-1"}).option("--bus <name>","Event bus name",{default:"default"}).option("--force","Remove all targets and delete rule").action(async(J,Y)=>{V("Delete EventBridge Rule");try{let Q=new $0(Y.region);if(N(`This will delete rule: ${J}`),!await P(`
1610
+ Delete this rule?`,!1)){G("Operation cancelled");return}let U=new M("Checking targets...");U.start();let Z=await Q.listTargetsByRule({Rule:J,EventBusName:Y.bus});if(Z.Targets&&Z.Targets.length>0){if(!Y.force){U.fail("Rule has targets"),G(`
1611
+ The rule has ${Z.Targets.length} target(s).`),G("Use --force to remove targets and delete the rule.");return}U.text="Removing targets...",await Q.removeTargets({Rule:J,EventBusName:Y.bus,Ids:Z.Targets.map((z)=>z.Id)})}U.text="Deleting rule...",await Q.deleteRule({Name:J,EventBusName:Y.bus}),U.succeed("Rule deleted")}catch(Q){_(`Failed to delete rule: ${Q.message}`),process.exit(1)}}),$.command("events:describe <name>","Show EventBridge rule details").option("--region <region>","AWS region",{default:"us-east-1"}).option("--bus <name>","Event bus name",{default:"default"}).action(async(J,Y)=>{V(`Rule: ${J}`);try{let Q=new $0(Y.region),W=new M("Fetching rule...");W.start();let U=await Q.describeRule({Name:J,EventBusName:Y.bus});if(!U){W.fail("Rule not found");return}let Z=await Q.listTargetsByRule({Rule:J,EventBusName:Y.bus});if(W.succeed("Rule loaded"),G(`
1612
+ Rule Information:`),G(` Name: ${U.Name}`),G(` ARN: ${U.Arn}`),G(` State: ${U.State}`),G(` Event Bus: ${U.EventBusName}`),U.Description)G(` Description: ${U.Description}`);if(U.ScheduleExpression)G(`
1613
+ Schedule Expression: ${U.ScheduleExpression}`);if(U.EventPattern)G(`
1614
+ Event Pattern:`),console.log(JSON.stringify(JSON.parse(U.EventPattern),null,2));if(Z.Targets&&Z.Targets.length>0){G(`
1615
+ Targets (${Z.Targets.length}):`);for(let z of Z.Targets)if(G(` - ${z.Id}: ${z.Arn}`),z.Input)G(` Input: ${z.Input}`)}else G(`
1616
+ No targets configured.`)}catch(Q){_(`Failed to get rule: ${Q.message}`),process.exit(1)}}),$.command("events:target <ruleName>","Add a target to an EventBridge rule").option("--region <region>","AWS region",{default:"us-east-1"}).option("--bus <name>","Event bus name",{default:"default"}).option("--id <id>","Target ID").option("--arn <arn>","Target ARN (Lambda, SQS, SNS, etc.)").option("--role <arn>","IAM role ARN (for some targets)").option("--input <json>","Constant JSON input").option("--input-path <path>","JSONPath expression for input").action(async(J,Y)=>{V("Add EventBridge Target");try{if(!Y.arn){_("--arn is required");return}let Q=new $0(Y.region),W=Y.id||`target-${Date.now()}`;if(G(`Rule: ${J}`),G(`Target ID: ${W}`),G(`Target ARN: ${Y.arn}`),!await P(`
1617
+ Add this target?`,!0)){G("Operation cancelled");return}let Z=new M("Adding target...");Z.start();let z={Id:W,Arn:Y.arn};if(Y.role)z.RoleArn=Y.role;if(Y.input)z.Input=Y.input;if(Y.inputPath)z.InputPath=Y.inputPath;await Q.putTargets({Rule:J,EventBusName:Y.bus,Targets:[z]}),Z.succeed("Target added"),A(`
1618
+ Target ${W} added to rule ${J}`)}catch(Q){_(`Failed to add target: ${Q.message}`),process.exit(1)}}),$.command("events:buses","List event buses").option("--region <region>","AWS region").action(async(J)=>{V("Event Buses");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=new $0(Q),U=new M("Fetching event buses...");U.start();let z=(await W.listEventBuses()).EventBuses||[];if(U.succeed(`Found ${z.length} event bus(es)`),z.length===0){G("No event buses found");return}x(["Name","ARN","Policy"],z.map((H)=>[H.Name||"N/A",H.Arn||"N/A",H.Policy?"Custom":"Default"]))}catch(Y){_(`Failed to list event buses: ${Y.message}`),process.exit(1)}}),$.command("events:enable <name>","Enable an EventBridge rule").option("--region <region>","AWS region",{default:"us-east-1"}).option("--bus <name>","Event bus name",{default:"default"}).action(async(J,Y)=>{V("Enable EventBridge Rule");try{let Q=new $0(Y.region),W=new M("Enabling rule...");W.start(),await Q.enableRule({Name:J,EventBusName:Y.bus}),W.succeed("Rule enabled")}catch(Q){_(`Failed to enable rule: ${Q.message}`),process.exit(1)}}),$.command("events:disable <name>","Disable an EventBridge rule").option("--region <region>","AWS region",{default:"us-east-1"}).option("--bus <name>","Event bus name",{default:"default"}).action(async(J,Y)=>{V("Disable EventBridge Rule");try{let Q=new $0(Y.region),W=new M("Disabling rule...");W.start(),await Q.disableRule({Name:J,EventBusName:Y.bus}),W.succeed("Rule disabled")}catch(Q){_(`Failed to disable rule: ${Q.message}`),process.exit(1)}})}W$();class J0{client;region;constructor($="us-east-1"){this.region=$,this.client=new l}async createEmailIdentity($){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify($)})}async getEmailIdentity($){let J=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent($)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:J.IdentityType,IdentityName:$,SendingEnabled:J.VerifiedForSendingStatus,VerificationStatus:J.VerificationStatus,DkimAttributes:J.DkimAttributes,MailFromAttributes:J.MailFromAttributes}}async putEmailIdentityMailFromAttributes($,J){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent($)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(J)})}async listEmailIdentities($){let J="/v2/email/identities",Y=[];if($?.PageSize)Y.push(`PageSize=${$.PageSize}`);if($?.NextToken)Y.push(`NextToken=${encodeURIComponent($.NextToken)}`);if(Y.length>0)J+=`?${Y.join("&")}`;let Q=await this.client.request({service:"email",region:this.region,method:"GET",path:J,headers:{"Content-Type":"application/json"}});return{EmailIdentities:Q.EmailIdentities,NextToken:Q.NextToken}}async deleteEmailIdentity($){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent($)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes($){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent($.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:$.SigningEnabled})})}async sendEmail($){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify($)})).MessageId}}async sendBulkEmail($){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify($)})).BulkEmailEntryResults}}async createEmailTemplate($){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify($)})}async getEmailTemplate($){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent($)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate($){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent($)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates($){let J="/v2/email/templates",Y=[];if($?.PageSize)Y.push(`PageSize=${$.PageSize}`);if($?.NextToken)Y.push(`NextToken=${encodeURIComponent($.NextToken)}`);if(Y.length>0)J+=`?${Y.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:J,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){return{SendDataPoints:(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"})).GetSendStatisticsResponse?.GetSendStatisticsResult?.SendDataPoints?.member}}async getSendQuota(){let J=(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"})).GetSendQuotaResponse?.GetSendQuotaResult;return{Max24HourSend:J?.Max24HourSend?Number(J.Max24HourSend):void 0,MaxSendRate:J?.MaxSendRate?Number(J.MaxSendRate):void 0,SentLast24Hours:J?.SentLast24Hours?Number(J.SentLast24Hours):void 0}}async verifyDomain($){let J=await this.createEmailIdentity({EmailIdentity:$});return{dkimTokens:J.DkimAttributes?.Tokens,verificationStatus:J.DkimAttributes?.Status}}async sendSimpleEmail($){let J=Array.isArray($.to)?$.to:[$.to],Y=$.replyTo?Array.isArray($.replyTo)?$.replyTo:[$.replyTo]:void 0,Q={};if($.text)Q.Text={Data:$.text};if($.html)Q.Html={Data:$.html};return this.sendEmail({FromEmailAddress:$.from,Destination:{ToAddresses:J},Content:{Simple:{Subject:{Data:$.subject},Body:Q}},ReplyToAddresses:Y})}async sendTemplatedEmail($){let J=Array.isArray($.to)?$.to:[$.to],Y=$.replyTo?Array.isArray($.replyTo)?$.replyTo:[$.replyTo]:void 0;return this.sendEmail({FromEmailAddress:$.from,Destination:{ToAddresses:J},Content:{Template:{TemplateName:$.templateName,TemplateData:JSON.stringify($.templateData)}},ReplyToAddresses:Y})}async getDkimRecords($){let J=await this.getEmailIdentity($);if(!J.DkimAttributes?.Tokens)return[];return J.DkimAttributes.Tokens.map((Y)=>({name:`${Y}._domainkey.${$}`,type:"CNAME",value:`${Y}.dkim.amazonses.com`}))}async isDomainVerified($){try{let J=await this.getEmailIdentity($);return J.VerificationStatus==="SUCCESS"&&J.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification($,J=60,Y=30000){for(let Q=0;Q<J;Q++){if(await this.isDomainVerified($))return!0;await new Promise((U)=>setTimeout(U,Y))}return!1}buildFormBody($){return Object.entries($).filter(([,Y])=>Y!==void 0).map(([Y,Q])=>`${encodeURIComponent(Y)}=${encodeURIComponent(Q)}`).join("&")}async createReceiptRuleSet($){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:$})})}async deleteReceiptRuleSet($){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:$})})}async setActiveReceiptRuleSet($){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:$})})}async listReceiptRuleSets($){let J={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if($)J.NextToken=$;let Y=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)}),Q=Y?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||Y?.ListReceiptRuleSetsResult,W=Q?.RuleSets?.member;return{RuleSets:Array.isArray(W)?W:W?[W]:[],NextToken:Q?.NextToken}}async describeReceiptRuleSet($){let J=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:$})}),Y=J?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||J?.DescribeReceiptRuleSetResult,Q=Y?.Rules?.member;return{Metadata:Y?.Metadata,Rules:Array.isArray(Q)?Q:Q?[Q]:[]}}async createReceiptRule($){let J={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:$.RuleSetName,"Rule.Name":$.Rule.Name,"Rule.Enabled":$.Rule.Enabled!==!1?"true":"false"};if($.Rule.TlsPolicy)J["Rule.TlsPolicy"]=$.Rule.TlsPolicy;if($.Rule.ScanEnabled!==void 0)J["Rule.ScanEnabled"]=$.Rule.ScanEnabled?"true":"false";if($.After)J.After=$.After;if($.Rule.Recipients)$.Rule.Recipients.forEach((Y,Q)=>{J[`Rule.Recipients.member.${Q+1}`]=Y});$.Rule.Actions.forEach((Y,Q)=>{let W=Q+1;if(Y.S3Action){if(J[`Rule.Actions.member.${W}.S3Action.BucketName`]=Y.S3Action.BucketName,Y.S3Action.ObjectKeyPrefix)J[`Rule.Actions.member.${W}.S3Action.ObjectKeyPrefix`]=Y.S3Action.ObjectKeyPrefix;if(Y.S3Action.KmsKeyArn)J[`Rule.Actions.member.${W}.S3Action.KmsKeyArn`]=Y.S3Action.KmsKeyArn}if(Y.LambdaAction)J[`Rule.Actions.member.${W}.LambdaAction.FunctionArn`]=Y.LambdaAction.FunctionArn,J[`Rule.Actions.member.${W}.LambdaAction.InvocationType`]=Y.LambdaAction.InvocationType||"Event";if(Y.SNSAction){if(J[`Rule.Actions.member.${W}.SNSAction.TopicArn`]=Y.SNSAction.TopicArn,Y.SNSAction.Encoding)J[`Rule.Actions.member.${W}.SNSAction.Encoding`]=Y.SNSAction.Encoding}if(Y.StopAction){if(J[`Rule.Actions.member.${W}.StopAction.Scope`]=Y.StopAction.Scope,Y.StopAction.TopicArn)J[`Rule.Actions.member.${W}.StopAction.TopicArn`]=Y.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)})}async deleteReceiptRule($,J){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:$,RuleName:J})})}async receiptRuleSetExists($){try{return await this.describeReceiptRuleSet($),!0}catch(J){if(J.code==="RuleSetDoesNotExist"||J.statusCode===400)return!1;throw J}}async getActiveReceiptRuleSet(){let $=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),J=$?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||$?.DescribeActiveReceiptRuleSetResult;if(!J?.Metadata)return null;let Y=J?.Rules?.member;return{Metadata:J?.Metadata,Rules:Array.isArray(Y)?Y:Y?[Y]:[]}}async updateReceiptRule($){let J={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:$.RuleSetName,"Rule.Name":$.Rule.Name};if($.Rule.Enabled!==void 0)J["Rule.Enabled"]=$.Rule.Enabled?"true":"false";if($.Rule.TlsPolicy)J["Rule.TlsPolicy"]=$.Rule.TlsPolicy;if($.Rule.ScanEnabled!==void 0)J["Rule.ScanEnabled"]=$.Rule.ScanEnabled?"true":"false";if($.Rule.Recipients)$.Rule.Recipients.forEach((Y,Q)=>{J[`Rule.Recipients.member.${Q+1}`]=Y});$.Rule.Actions.forEach((Y,Q)=>{let W=Q+1;if(Y.S3Action){if(J[`Rule.Actions.member.${W}.S3Action.BucketName`]=Y.S3Action.BucketName,Y.S3Action.ObjectKeyPrefix)J[`Rule.Actions.member.${W}.S3Action.ObjectKeyPrefix`]=Y.S3Action.ObjectKeyPrefix;if(Y.S3Action.KmsKeyArn)J[`Rule.Actions.member.${W}.S3Action.KmsKeyArn`]=Y.S3Action.KmsKeyArn}if(Y.LambdaAction)J[`Rule.Actions.member.${W}.LambdaAction.FunctionArn`]=Y.LambdaAction.FunctionArn,J[`Rule.Actions.member.${W}.LambdaAction.InvocationType`]=Y.LambdaAction.InvocationType||"Event";if(Y.SNSAction){if(J[`Rule.Actions.member.${W}.SNSAction.TopicArn`]=Y.SNSAction.TopicArn,Y.SNSAction.Encoding)J[`Rule.Actions.member.${W}.SNSAction.Encoding`]=Y.SNSAction.Encoding}if(Y.StopAction){if(J[`Rule.Actions.member.${W}.StopAction.Scope`]=Y.StopAction.Scope,Y.StopAction.TopicArn)J[`Rule.Actions.member.${W}.StopAction.TopicArn`]=Y.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)})}async sendRawEmail($){let J=Buffer.from($.rawMessage).toString("base64"),Y={Action:"SendRawEmail",Version:"2010-12-01",Source:$.source,"RawMessage.Data":J};$.destinations.forEach((U,Z)=>{Y[`Destinations.member.${Z+1}`]=U});let Q=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(Y)});return{MessageId:(Q?.SendRawEmailResponse?.SendRawEmailResult||Q?.SendRawEmailResult)?.MessageId}}}function l6($){$.command("email:identities","List verified email identities").option("--region <region>","AWS region").action(async(J)=>{V("Email Identities");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=new J0(Q),U=new M("Fetching identities...");U.start();let z=(await W.listEmailIdentities()).EmailIdentities||[];if(U.succeed(`Found ${z.length} identity(s)`),z.length===0){G("No email identities found"),G("Use `cloud email:verify` to verify an email or domain");return}let H=[];for(let K of z){let B=K.IdentityName||"Unknown",O="Unknown";try{O=(await W.getEmailIdentity(B)).VerificationStatus||"Unknown"}catch{}let X=K.IdentityType==="EMAIL_ADDRESS"?"Email":K.IdentityType==="DOMAIN"?"Domain":K.IdentityType||"Unknown";H.push([B,X,O])}x(["Identity","Type","Verification Status"],H)}catch(Y){let Q=Y instanceof Error?Y.message:String(Y);_(`Failed to list identities: ${Q}`),process.exit(1)}}),$.command("email:verify <identity>","Verify an email address or domain").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{V("Verify Email Identity");try{let Q=new J0(Y.region),W=J.includes("@");if(G(`Identity: ${J}`),G(`Type: ${W?"Email Address":"Domain"}`),!await P(`
1619
+ Send verification?`,!0)){G("Operation cancelled");return}let Z=new M("Initiating verification...");if(Z.start(),W)await Q.createEmailIdentity({EmailIdentity:J}),Z.succeed("Verification email sent"),G(`
1620
+ A verification email has been sent to ${J}`),G("Click the link in the email to complete verification.");else{let z=await Q.verifyDomain(J);Z.succeed("Domain verification initiated");let H=z.dkimTokens||[];if(H.length>0){G(`
1621
+ DKIM Records (for email authentication):`);for(let K of H)G(`
1622
+ Name: ${K}._domainkey.${J}`),G(" Type: CNAME"),G(` Value: ${K}.dkim.amazonses.com`)}G(`
1623
+ Verification Status: ${z.verificationStatus||"PENDING"}`)}}catch(Q){let W=Q instanceof Error?Q.message:String(Q);_(`Failed to verify identity: ${W}`),process.exit(1)}}),$.command("email:delete <identity>","Delete a verified email identity").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{V("Delete Email Identity");try{let Q=new J0(Y.region);if(N(`This will remove identity: ${J}`),!await P(`
1624
+ Delete this identity?`,!1)){G("Operation cancelled");return}let U=new M("Deleting identity...");U.start(),await Q.deleteEmailIdentity(J),U.succeed("Identity deleted")}catch(Q){let W=Q instanceof Error?Q.message:String(Q);_(`Failed to delete identity: ${W}`),process.exit(1)}}),$.command("email:send","Send a test email").option("--region <region>","AWS region",{default:"us-east-1"}).option("--from <email>","From email address (must be verified)").option("--to <email>","To email address").option("--subject <text>","Email subject").option("--body <text>","Email body (text)").option("--html <html>","Email body (HTML)").action(async(J)=>{V("Send Email");try{let Y=new J0(J.region),Q=J.from||await U$("From (verified email)"),W=J.to||await U$("To"),U=J.subject||await U$("Subject","Test Email from ts-cloud"),Z=J.body||await U$("Body","This is a test email sent from ts-cloud CLI.");if(G(`
1625
+ From: ${Q}`),G(`To: ${W}`),G(`Subject: ${U}`),!await P(`
1626
+ Send this email?`,!0)){G("Operation cancelled");return}let H=new M("Sending email...");H.start();let K=await Y.sendEmail({FromEmailAddress:Q,Destination:{ToAddresses:[W]},Content:{Simple:{Subject:{Data:U},Body:{Text:{Data:Z},...J.html&&{Html:{Data:J.html}}}}}});H.succeed("Email sent"),A(`
1627
+ Message ID: ${K.MessageId}`)}catch(Y){let Q=Y instanceof Error?Y.message:String(Y);_(`Failed to send email: ${Q}`),process.exit(1)}}),$.command("email:templates","List email templates").option("--region <region>","AWS region").action(async(J)=>{V("Email Templates");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=new J0(Q),U=new M("Fetching templates...");U.start();let z=(await W.listEmailTemplates()).TemplatesMetadata||[];if(U.succeed(`Found ${z.length} template(s)`),z.length===0){G("No email templates found"),G("Use `cloud email:template:create` to create a template");return}x(["Name","Created"],z.map((H)=>[H.TemplateName||"N/A",H.CreatedTimestamp?new Date(H.CreatedTimestamp).toLocaleString():"N/A"]))}catch(Y){let Q=Y instanceof Error?Y.message:String(Y);_(`Failed to list templates: ${Q}`),process.exit(1)}}),$.command("email:template:create <name>","Create an email template").option("--region <region>","AWS region",{default:"us-east-1"}).option("--subject <text>","Email subject (supports {{variable}} placeholders)").option("--text <text>","Text body").option("--html <html>","HTML body").option("--html-file <path>","HTML body from file").action(async(J,Y)=>{V("Create Email Template");try{let Q=new J0(Y.region),W=Y.subject||await U$("Subject template","Hello {{name}}"),U=Y.text||await U$("Text body","Hello {{name}}, this is a test."),Z=Y.html;if(Y.htmlFile)Z=await Bun.file(Y.htmlFile).text();if(G(`
1628
+ Template Name: ${J}`),G(`Subject: ${W}`),!await P(`
1629
+ Create this template?`,!0)){G("Operation cancelled");return}let H=new M("Creating template...");H.start(),await Q.createEmailTemplate({TemplateName:J,TemplateContent:{Subject:W,Text:U,Html:Z}}),H.succeed("Template created"),G(`
1630
+ To send using this template:`),G(` cloud email:send:template --template ${J} --to user@example.com --data '{"name":"John"}'`)}catch(Q){let W=Q instanceof Error?Q.message:String(Q);_(`Failed to create template: ${W}`),process.exit(1)}}),$.command("email:template:delete <name>","Delete an email template").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{V("Delete Email Template");try{let Q=new J0(Y.region);if(N(`This will delete template: ${J}`),!await P(`
1631
+ Delete this template?`,!1)){G("Operation cancelled");return}let U=new M("Deleting template...");U.start(),await Q.deleteEmailTemplate(J),U.succeed("Template deleted")}catch(Q){let W=Q instanceof Error?Q.message:String(Q);_(`Failed to delete template: ${W}`),process.exit(1)}}),$.command("email:stats","Show SES sending statistics").option("--region <region>","AWS region").action(async(J)=>{V("Email Statistics");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=new J0(Q),U=new M("Fetching statistics...");U.start();let[Z,z]=await Promise.all([W.getSendQuota(),W.getSendStatistics()]);U.succeed("Statistics loaded"),G(`
1632
+ Sending Quota:`),G(` Max 24-hour Send: ${Z.Max24HourSend||0}`),G(` Max Send Rate: ${Z.MaxSendRate||0} emails/second`),G(` Sent Last 24h: ${Z.SentLast24Hours||0}`);let H=(Z.Max24HourSend||0)-(Z.SentLast24Hours||0);if(G(` Remaining: ${H}`),z.SendDataPoints&&z.SendDataPoints.length>0){G(`
1633
+ Recent Statistics:`);let K=0,B=0,O=0,X=0;for(let j of z.SendDataPoints)K+=j.DeliveryAttempts||0,B+=j.Bounces||0,O+=j.Complaints||0,X+=j.Rejects||0;if(G(` Total Attempts: ${K}`),G(` Bounces: ${B}`),G(` Complaints: ${O}`),G(` Rejects: ${X}`),K>0){let j=(B/K*100).toFixed(2),q=(O/K*100).toFixed(2);if(G(`
1634
+ Bounce Rate: ${j}%`),G(` Complaint Rate: ${q}%`),Number.parseFloat(j)>5)N(`
1635
+ Warning: Bounce rate is high (>5%). This may affect your sender reputation.`);if(Number.parseFloat(q)>0.1)N(`
1636
+ Warning: Complaint rate is high (>0.1%). This may affect your sender reputation.`)}}}catch(Y){let Q=Y instanceof Error?Y.message:String(Y);_(`Failed to get statistics: ${Q}`),process.exit(1)}})}W$();class r${client;region;constructor($="us-east-1"){this.region=$,this.client=new l}buildFormBody($){return Object.entries($).filter(([,Y])=>Y!==void 0).map(([Y,Q])=>`${encodeURIComponent(Y)}=${encodeURIComponent(Q)}`).join("&")}async createTopic($){let J={Action:"CreateTopic",Version:"2010-03-31",Name:$.Name};if($.DisplayName)J["Attributes.entry.1.key"]="DisplayName",J["Attributes.entry.1.value"]=$.DisplayName;if($.Tags)$.Tags.forEach((Q,W)=>{J[`Tags.member.${W+1}.Key`]=Q.Key,J[`Tags.member.${W+1}.Value`]=Q.Value});if($.Attributes){let Q=$.DisplayName?2:1;Object.entries($.Attributes).forEach(([W,U])=>{J[`Attributes.entry.${Q}.key`]=W,J[`Attributes.entry.${Q}.value`]=U,Q++})}let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)});return{TopicArn:Y?.CreateTopicResponse?.CreateTopicResult?.TopicArn||Y?.TopicArn}}async deleteTopic($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteTopic",Version:"2010-03-31",TopicArn:$})})}async listTopics($){let J={Action:"ListTopics",Version:"2010-03-31"};if($)J.NextToken=$;let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)}),Q=Y?.ListTopicsResponse?.ListTopicsResult||Y?.ListTopicsResult,W=Q?.Topics?.member;return{Topics:Array.isArray(W)?W:W?[W]:[],NextToken:Q?.NextToken}}async getTopicAttributes($){let Y=(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetTopicAttributes",Version:"2010-03-31",TopicArn:$})}))?.GetTopicAttributesResponse?.GetTopicAttributesResult?.Attributes?.entry,Q={TopicArn:$};if(Array.isArray(Y))Y.forEach((W)=>{Q[W.key]=W.value});return Q}async setTopicAttributes($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetTopicAttributes",Version:"2010-03-31",TopicArn:$.TopicArn,AttributeName:$.AttributeName,AttributeValue:$.AttributeValue})})}async subscribe($){let J={Action:"Subscribe",Version:"2010-03-31",TopicArn:$.TopicArn,Protocol:$.Protocol,Endpoint:$.Endpoint};if($.ReturnSubscriptionArn)J.ReturnSubscriptionArn="true";if($.Attributes){let Q=1;Object.entries($.Attributes).forEach(([W,U])=>{J[`Attributes.entry.${Q}.key`]=W,J[`Attributes.entry.${Q}.value`]=U,Q++})}let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)});return{SubscriptionArn:Y?.SubscribeResponse?.SubscribeResult?.SubscriptionArn||Y?.SubscriptionArn}}async unsubscribe($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"Unsubscribe",Version:"2010-03-31",SubscriptionArn:$})})}async listSubscriptionsByTopic($,J){let Y={Action:"ListSubscriptionsByTopic",Version:"2010-03-31",TopicArn:$};if(J)Y.NextToken=J;let Q=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(Y)}),W=Q?.ListSubscriptionsByTopicResponse?.ListSubscriptionsByTopicResult?.Subscriptions?.member;return{Subscriptions:Array.isArray(W)?W:W?[W]:[],NextToken:Q?.ListSubscriptionsByTopicResponse?.ListSubscriptionsByTopicResult?.NextToken}}async publish($){let J={Action:"Publish",Version:"2010-03-31",Message:$.Message};if($.TopicArn)J.TopicArn=$.TopicArn;if($.TargetArn)J.TargetArn=$.TargetArn;if($.PhoneNumber)J.PhoneNumber=$.PhoneNumber;if($.Subject)J.Subject=$.Subject;if($.MessageStructure)J.MessageStructure=$.MessageStructure;if($.MessageAttributes){let Q=1;Object.entries($.MessageAttributes).forEach(([W,U])=>{if(J[`MessageAttributes.entry.${Q}.Name`]=W,J[`MessageAttributes.entry.${Q}.Value.DataType`]=U.DataType,U.StringValue)J[`MessageAttributes.entry.${Q}.Value.StringValue`]=U.StringValue;if(U.BinaryValue)J[`MessageAttributes.entry.${Q}.Value.BinaryValue`]=U.BinaryValue;Q++})}let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)});return{MessageId:Y?.PublishResponse?.PublishResult?.MessageId||Y?.MessageId}}async publishSMS($,J,Y){let Q={};if(Y)Q["AWS.SNS.SMS.SenderID"]={DataType:"String",StringValue:Y};return this.publish({PhoneNumber:$,Message:J,MessageAttributes:Object.keys(Q).length>0?Q:void 0})}async subscribeEmail($,J){return this.subscribe({TopicArn:$,Protocol:"email",Endpoint:J})}async subscribeLambda($,J){return this.subscribe({TopicArn:$,Protocol:"lambda",Endpoint:J})}async subscribeSqs($,J,Y){let Q={};if(Y)Q.RawMessageDelivery="true";return this.subscribe({TopicArn:$,Protocol:"sqs",Endpoint:J,Attributes:Object.keys(Q).length>0?Q:void 0})}async subscribeHttp($,J,Y){let Q=J.startsWith("https")?"https":"http",W={};if(Y)W.RawMessageDelivery="true";return this.subscribe({TopicArn:$,Protocol:Q,Endpoint:J,Attributes:Object.keys(W).length>0?W:void 0})}async subscribeSms($,J){return this.subscribe({TopicArn:$,Protocol:"sms",Endpoint:J})}async topicExists($){try{return await this.getTopicAttributes($),!0}catch(J){if(J.code==="NotFound"||J.statusCode===404)return!1;throw J}}async getSMSAttributes(){let J=(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSAttributes",Version:"2010-03-31"})}))?.GetSMSAttributesResponse?.GetSMSAttributesResult?.attributes?.entry,Y={};if(Array.isArray(J))J.forEach((Q)=>{Y[Q.key]=Q.value});else if(J)Y[J.key]=J.value;return Y}async setSMSAttributes($){let J={Action:"SetSMSAttributes",Version:"2010-03-31"},Y=1;Object.entries($).forEach(([Q,W])=>{if(W!==void 0)J[`attributes.entry.${Y}.key`]=Q,J[`attributes.entry.${Y}.value`]=W,Y++}),await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)})}async checkIfPhoneNumberIsOptedOut($){return(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CheckIfPhoneNumberIsOptedOut",Version:"2010-03-31",phoneNumber:$})}))?.CheckIfPhoneNumberIsOptedOutResponse?.CheckIfPhoneNumberIsOptedOutResult?.isOptedOut==="true"}async listPhoneNumbersOptedOut($){let J={Action:"ListPhoneNumbersOptedOut",Version:"2010-03-31"};if($)J.nextToken=$;let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)}),Q=Y?.ListPhoneNumbersOptedOutResponse?.ListPhoneNumbersOptedOutResult?.phoneNumbers?.member;return{phoneNumbers:Array.isArray(Q)?Q:Q?[Q]:[],nextToken:Y?.ListPhoneNumbersOptedOutResponse?.ListPhoneNumbersOptedOutResult?.nextToken}}async optInPhoneNumber($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"OptInPhoneNumber",Version:"2010-03-31",phoneNumber:$})})}async listSMSSandboxPhoneNumbers($){let J={Action:"ListSMSSandboxPhoneNumbers",Version:"2010-03-31"};if($)J.NextToken=$;let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)}),Q=Y?.ListSMSSandboxPhoneNumbersResponse?.ListSMSSandboxPhoneNumbersResult?.PhoneNumbers?.member;return{PhoneNumbers:Array.isArray(Q)?Q:Q?[Q]:[],NextToken:Y?.ListSMSSandboxPhoneNumbersResponse?.ListSMSSandboxPhoneNumbersResult?.NextToken}}async createSMSSandboxPhoneNumber($,J){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:$,LanguageCode:J||"en-US"})})}async verifySMSSandboxPhoneNumber($,J){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"VerifySMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:$,OneTimePassword:J})})}async deleteSMSSandboxPhoneNumber($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:$})})}async getSMSSandboxAccountStatus(){return{IsInSandbox:(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSSandboxAccountStatus",Version:"2010-03-31"})}))?.GetSMSSandboxAccountStatusResponse?.GetSMSSandboxAccountStatusResult?.IsInSandbox==="true"}}}function p6($){$.command("notify:topics","List all SNS topics").option("--region <region>","AWS region").action(async(J)=>{V("SNS Topics");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=new r$(Q),U=new M("Fetching topics...");U.start();let z=(await W.listTopics()).Topics||[];if(U.succeed(`Found ${z.length} topic(s)`),z.length===0){G("No SNS topics found"),G("Use `cloud notify:create` to create a new topic");return}x(["Topic ARN","Name"],z.map((H)=>{let K=H.TopicArn?.split(":").pop()||"N/A";return[H.TopicArn||"N/A",K]}))}catch(Y){_(`Failed to list topics: ${Y.message}`),process.exit(1)}}),$.command("notify:create <name>","Create a new SNS topic").option("--region <region>","AWS region",{default:"us-east-1"}).option("--fifo","Create a FIFO topic").option("--display-name <name>","Display name for SMS subscriptions").action(async(J,Y)=>{V("Create SNS Topic");try{let Q=new r$(Y.region),W=Y.fifo&&!J.endsWith(".fifo")?`${J}.fifo`:J;if(G(`Topic name: ${W}`),G(`Type: ${Y.fifo?"FIFO":"Standard"}`),!await P(`
1637
+ Create this topic?`,!0)){G("Operation cancelled");return}let Z=new M("Creating topic...");Z.start();let z={};if(Y.fifo)z.FifoTopic="true",z.ContentBasedDeduplication="true";if(Y.displayName)z.DisplayName=Y.displayName;let H=await Q.createTopic({Name:W,Attributes:Object.keys(z).length>0?z:void 0});Z.succeed("Topic created"),A(`
1638
+ Topic ARN: ${H.TopicArn}`),G(`
1639
+ To subscribe:`),G(` cloud notify:subscribe ${H.TopicArn} --email user@example.com`)}catch(Q){_(`Failed to create topic: ${Q.message}`),process.exit(1)}}),$.command("notify:delete <topicArn>","Delete an SNS topic").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{V("Delete SNS Topic");try{let Q=new r$(Y.region);if(N(`This will delete topic: ${J}`),N("All subscriptions will be removed."),!await P(`
1640
+ Delete this topic?`,!1)){G("Operation cancelled");return}let U=new M("Deleting topic...");U.start(),await Q.deleteTopic(J),U.succeed("Topic deleted")}catch(Q){_(`Failed to delete topic: ${Q.message}`),process.exit(1)}}),$.command("notify:subscribe <topicArn>","Subscribe to an SNS topic").option("--region <region>","AWS region",{default:"us-east-1"}).option("--email <address>","Email address").option("--sms <number>","Phone number (E.164 format)").option("--sqs <queueArn>","SQS queue ARN").option("--lambda <functionArn>","Lambda function ARN").option("--https <url>","HTTPS endpoint URL").option("--filter <json>","Filter policy JSON").action(async(J,Y)=>{V("Subscribe to SNS Topic");try{let Q=new r$(Y.region),W,U;if(Y.email)W="email",U=Y.email;else if(Y.sms)W="sms",U=Y.sms;else if(Y.sqs)W="sqs",U=Y.sqs;else if(Y.lambda)W="lambda",U=Y.lambda;else if(Y.https)W="https",U=Y.https;else{_("Specify a subscription type: --email, --sms, --sqs, --lambda, or --https");return}if(G(`Topic: ${J}`),G(`Protocol: ${W}`),G(`Endpoint: ${U}`),!await P(`
1641
+ Create this subscription?`,!0)){G("Operation cancelled");return}let z=new M("Creating subscription...");z.start();let H={TopicArn:J,Protocol:W,Endpoint:U};if(Y.filter)H.Attributes={FilterPolicy:Y.filter};let K=await Q.subscribe(H);if(z.succeed("Subscription created"),K.SubscriptionArn==="pending confirmation")G(`
1642
+ Subscription is pending confirmation.`),G("The subscriber will receive a confirmation message.");else A(`
1643
+ Subscription ARN: ${K.SubscriptionArn}`)}catch(Q){_(`Failed to subscribe: ${Q.message}`),process.exit(1)}}),$.command("notify:unsubscribe <subscriptionArn>","Unsubscribe from an SNS topic").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{V("Unsubscribe from SNS Topic");try{let Q=new r$(Y.region);if(N(`This will remove subscription: ${J}`),!await P(`
1644
+ Unsubscribe?`,!1)){G("Operation cancelled");return}let U=new M("Unsubscribing...");U.start(),await Q.unsubscribe(J),U.succeed("Unsubscribed")}catch(Q){_(`Failed to unsubscribe: ${Q.message}`),process.exit(1)}}),$.command("notify:subscriptions <topicArn>","List subscriptions for a topic").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{V("Topic Subscriptions");try{let Q=new r$(Y.region),W=new M("Fetching subscriptions...");W.start();let Z=(await Q.listSubscriptionsByTopic(J)).Subscriptions||[];if(W.succeed(`Found ${Z.length} subscription(s)`),Z.length===0){G("No subscriptions found");return}x(["Protocol","Endpoint","Status","Subscription ARN"],Z.map((z)=>[z.Protocol||"N/A",z.Endpoint||"N/A",z.SubscriptionArn==="PendingConfirmation"?"Pending":"Confirmed",(z.SubscriptionArn||"N/A").substring(0,50)]))}catch(Q){_(`Failed to list subscriptions: ${Q.message}`),process.exit(1)}}),$.command("notify:publish <topicArn>","Publish a message to an SNS topic").option("--region <region>","AWS region",{default:"us-east-1"}).option("--message <text>","Message body").option("--subject <text>","Message subject (for email)").option("--file <path>","Read message from file").option("--json","Send as JSON message structure").option("--group <id>","Message group ID (for FIFO topics)").option("--dedup <id>","Deduplication ID (for FIFO topics)").action(async(J,Y)=>{V("Publish to SNS Topic");try{let Q=new r$(Y.region),W;if(Y.file)W=await Bun.file(Y.file).text();else if(Y.message)W=Y.message;else W=await U$("Message");if(!W){_("Message is required");return}if(G(`Topic: ${J}`),G(`Message length: ${W.length} characters`),!await P(`
1645
+ Publish this message?`,!0)){G("Operation cancelled");return}let Z=new M("Publishing message...");Z.start();let z={TopicArn:J,Message:W};if(Y.subject)z.Subject=Y.subject;if(Y.json)z.MessageStructure="json";if(Y.group)z.MessageGroupId=Y.group;if(Y.dedup)z.MessageDeduplicationId=Y.dedup;let H=await Q.publish(z);Z.succeed("Message published"),A(`
1646
+ Message ID: ${H.MessageId}`)}catch(Q){_(`Failed to publish message: ${Q.message}`),process.exit(1)}}),$.command("notify:sms <phoneNumber>","Send an SMS message directly").option("--region <region>","AWS region",{default:"us-east-1"}).option("--message <text>","Message body").option("--sender <id>","Sender ID or short code").option("--type <type>","Message type (Transactional or Promotional)",{default:"Transactional"}).action(async(J,Y)=>{V("Send SMS");try{let Q=new r$(Y.region),W=Y.message||await U$("Message");if(!W){_("Message is required");return}if(G(`To: ${J}`),G(`Message: ${W}`),G(`Type: ${Y.type}`),!await P(`
1647
+ Send this SMS?`,!0)){G("Operation cancelled");return}let Z=new M("Sending SMS...");Z.start();let z={PhoneNumber:J,Message:W,MessageAttributes:{"AWS.SNS.SMS.SMSType":{DataType:"String",StringValue:Y.type}}};if(Y.sender)z.MessageAttributes["AWS.SNS.SMS.SenderID"]={DataType:"String",StringValue:Y.sender};let H=await Q.publish(z);Z.succeed("SMS sent"),A(`
1648
+ Message ID: ${H.MessageId}`)}catch(Q){_(`Failed to send SMS: ${Q.message}`),process.exit(1)}}),$.command("notify:topic:attributes <topicArn>","Show topic attributes").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{V("Topic Attributes");try{let Q=new r$(Y.region),W=new M("Fetching attributes...");W.start();let U=await Q.getTopicAttributes(J);if(W.succeed("Attributes loaded"),G(`
1649
+ Topic Information:`),G(` ARN: ${J}`),G(` Display Name: ${U.DisplayName||"Not set"}`),G(` Owner: ${U.Owner||"N/A"}`),G(`
1650
+ Subscriptions:`),G(` Confirmed: ${U.SubscriptionsConfirmed||0}`),G(` Pending: ${U.SubscriptionsPending||0}`),G(` Deleted: ${U.SubscriptionsDeleted||0}`),G(`
1651
+ Settings:`),G(` FIFO: ${U.FifoTopic==="true"?"Yes":"No"}`),G(` Content Deduplication: ${U.ContentBasedDeduplication==="true"?"Yes":"No"}`),U.EffectiveDeliveryPolicy)G(`
1652
+ Delivery Policy: Configured`);if(U.Policy)G(`
1653
+ Access Policy: Configured`)}catch(Q){_(`Failed to get attributes: ${Q.message}`),process.exit(1)}})}W$();function mW($,J){let Y=[`Action=${$}`,"Version=2010-05-08"];for(let[Q,W]of Object.entries(J)){if(W===void 0||W===null)continue;if(Array.isArray(W))W.forEach((U,Z)=>{if(typeof U==="object"&&U!==null)for(let[z,H]of Object.entries(U))Y.push(`${Q}.member.${Z+1}.${z}=${encodeURIComponent(String(H))}`);else Y.push(`${Q}.member.${Z+1}=${encodeURIComponent(String(U))}`)});else if(typeof W==="object"){for(let[U,Z]of Object.entries(W))if(Z!==void 0&&Z!==null)Y.push(`${Q}.${U}=${encodeURIComponent(String(Z))}`)}else Y.push(`${Q}=${encodeURIComponent(String(W))}`)}return Y.join("&")}function L($,J){let Y=new RegExp(`<${J}>([^<]*)</${J}>`),Q=$.match(Y);return Q?Q[1]:void 0}function D$($,J,Y){let Q=new RegExp(`<${J}>([\\s\\S]*?)</${J}>`),W=$.match(Q);if(!W)return[];let U=[],Z=new RegExp(`<${Y}>([\\s\\S]*?)</${Y}>`,"g"),z;while((z=Z.exec(W[1]))!==null)U.push(z[1]);return U}class a${client;region;constructor($="us-east-1"){this.client=new l,this.region=$}async request($,J={}){let Y=mW($,J);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y})}async createUser($){let J=await this.request("CreateUser",$);return this.parseUser(J)}async getUser($={}){let J=await this.request("GetUser",$);return this.parseUser(J)}async listUsers($={}){let J=await this.request("ListUsers",$),Y=this.parseUsers(J),Q=L(J,"IsTruncated")==="true",W=L(J,"Marker");return{Users:Y,IsTruncated:Q,Marker:W}}async updateUser($){await this.request("UpdateUser",$)}async deleteUser($){await this.request("DeleteUser",$)}parseUser($){return{UserName:L($,"UserName")||"",UserId:L($,"UserId")||"",Arn:L($,"Arn")||"",Path:L($,"Path"),CreateDate:L($,"CreateDate"),PasswordLastUsed:L($,"PasswordLastUsed")}}parseUsers($){return D$($,"Users","member").map((Y)=>({UserName:L(Y,"UserName")||"",UserId:L(Y,"UserId")||"",Arn:L(Y,"Arn")||"",Path:L(Y,"Path"),CreateDate:L(Y,"CreateDate"),PasswordLastUsed:L(Y,"PasswordLastUsed")}))}async createGroup($){let J=await this.request("CreateGroup",$);return this.parseGroup(J)}async getGroup($){let J=await this.request("GetGroup",$),Y=this.parseGroup(J),Q=this.parseUsers(J),W=L(J,"IsTruncated")==="true",U=L(J,"Marker");return{Group:Y,Users:Q,IsTruncated:W,Marker:U}}async listGroups($={}){let J=await this.request("ListGroups",$),Y=this.parseGroups(J),Q=L(J,"IsTruncated")==="true",W=L(J,"Marker");return{Groups:Y,IsTruncated:Q,Marker:W}}async updateGroup($){await this.request("UpdateGroup",$)}async deleteGroup($){await this.request("DeleteGroup",$)}async addUserToGroup($){await this.request("AddUserToGroup",$)}async removeUserFromGroup($){await this.request("RemoveUserFromGroup",$)}async listGroupsForUser($){let J=await this.request("ListGroupsForUser",$),Y=this.parseGroups(J),Q=L(J,"IsTruncated")==="true",W=L(J,"Marker");return{Groups:Y,IsTruncated:Q,Marker:W}}parseGroup($){return{GroupName:L($,"GroupName")||"",GroupId:L($,"GroupId")||"",Arn:L($,"Arn")||"",Path:L($,"Path"),CreateDate:L($,"CreateDate")}}parseGroups($){return D$($,"Groups","member").map((Y)=>({GroupName:L(Y,"GroupName")||"",GroupId:L(Y,"GroupId")||"",Arn:L(Y,"Arn")||"",Path:L(Y,"Path"),CreateDate:L(Y,"CreateDate")}))}async createRole($){let J=await this.request("CreateRole",$);return this.parseRole(J)}async getRole($){let J=await this.request("GetRole",$);return this.parseRole(J)}async listRoles($={}){let J=await this.request("ListRoles",$),Y=this.parseRoles(J),Q=L(J,"IsTruncated")==="true",W=L(J,"Marker");return{Roles:Y,IsTruncated:Q,Marker:W}}async updateRole($){await this.request("UpdateRole",$)}async updateRoleDescription($){let J=await this.request("UpdateRoleDescription",$);return this.parseRole(J)}async updateAssumeRolePolicy($){await this.request("UpdateAssumeRolePolicy",$)}async deleteRole($){await this.request("DeleteRole",$)}async tagRole($){await this.request("TagRole",$)}async untagRole($){await this.request("UntagRole",$)}async listRoleTags($){let J=await this.request("ListRoleTags",$),Y=this.parseTags(J),Q=L(J,"IsTruncated")==="true",W=L(J,"Marker");return{Tags:Y,IsTruncated:Q,Marker:W}}parseRole($){return{RoleName:L($,"RoleName")||"",RoleId:L($,"RoleId")||"",Arn:L($,"Arn")||"",Path:L($,"Path"),CreateDate:L($,"CreateDate"),AssumeRolePolicyDocument:L($,"AssumeRolePolicyDocument"),Description:L($,"Description"),MaxSessionDuration:L($,"MaxSessionDuration")?Number.parseInt(L($,"MaxSessionDuration"),10):void 0}}parseRoles($){return D$($,"Roles","member").map((Y)=>({RoleName:L(Y,"RoleName")||"",RoleId:L(Y,"RoleId")||"",Arn:L(Y,"Arn")||"",Path:L(Y,"Path"),CreateDate:L(Y,"CreateDate"),AssumeRolePolicyDocument:L(Y,"AssumeRolePolicyDocument"),Description:L(Y,"Description"),MaxSessionDuration:L(Y,"MaxSessionDuration")?Number.parseInt(L(Y,"MaxSessionDuration"),10):void 0}))}parseTags($){return D$($,"Tags","member").map((Y)=>({Key:L(Y,"Key")||"",Value:L(Y,"Value")||""}))}async createPolicy($){let J=await this.request("CreatePolicy",$);return this.parsePolicy(J)}async getPolicy($){let J=await this.request("GetPolicy",$);return this.parsePolicy(J)}async getPolicyVersion($){let J=await this.request("GetPolicyVersion",$);return{VersionId:L(J,"VersionId")||"",IsDefaultVersion:L(J,"IsDefaultVersion")==="true",CreateDate:L(J,"CreateDate"),Document:L(J,"Document")}}async listPolicies($={}){let J=await this.request("ListPolicies",$),Y=this.parsePolicies(J),Q=L(J,"IsTruncated")==="true",W=L(J,"Marker");return{Policies:Y,IsTruncated:Q,Marker:W}}async listPolicyVersions($){let J=await this.request("ListPolicyVersions",$),Y=this.parsePolicyVersions(J),Q=L(J,"IsTruncated")==="true",W=L(J,"Marker");return{Versions:Y,IsTruncated:Q,Marker:W}}async createPolicyVersion($){let J=await this.request("CreatePolicyVersion",$);return{VersionId:L(J,"VersionId")||"",IsDefaultVersion:L(J,"IsDefaultVersion")==="true",CreateDate:L(J,"CreateDate")}}async deletePolicyVersion($){await this.request("DeletePolicyVersion",$)}async setDefaultPolicyVersion($){await this.request("SetDefaultPolicyVersion",$)}async deletePolicy($){await this.request("DeletePolicy",$)}async attachUserPolicy($){await this.request("AttachUserPolicy",$)}async detachUserPolicy($){await this.request("DetachUserPolicy",$)}async attachGroupPolicy($){await this.request("AttachGroupPolicy",$)}async detachGroupPolicy($){await this.request("DetachGroupPolicy",$)}async attachRolePolicy($){await this.request("AttachRolePolicy",$)}async detachRolePolicy($){await this.request("DetachRolePolicy",$)}async listAttachedUserPolicies($){let J=await this.request("ListAttachedUserPolicies",$),Y=this.parseAttachedPolicies(J),Q=L(J,"IsTruncated")==="true",W=L(J,"Marker");return{AttachedPolicies:Y,IsTruncated:Q,Marker:W}}async listAttachedGroupPolicies($){let J=await this.request("ListAttachedGroupPolicies",$),Y=this.parseAttachedPolicies(J),Q=L(J,"IsTruncated")==="true",W=L(J,"Marker");return{AttachedPolicies:Y,IsTruncated:Q,Marker:W}}async listAttachedRolePolicies($){let J=await this.request("ListAttachedRolePolicies",$),Y=this.parseAttachedPolicies(J),Q=L(J,"IsTruncated")==="true",W=L(J,"Marker");return{AttachedPolicies:Y,IsTruncated:Q,Marker:W}}parsePolicy($){return{PolicyName:L($,"PolicyName")||"",PolicyId:L($,"PolicyId")||"",Arn:L($,"Arn")||"",Path:L($,"Path"),DefaultVersionId:L($,"DefaultVersionId"),AttachmentCount:L($,"AttachmentCount")?Number.parseInt(L($,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:L($,"PermissionsBoundaryUsageCount")?Number.parseInt(L($,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:L($,"IsAttachable")==="true",Description:L($,"Description"),CreateDate:L($,"CreateDate"),UpdateDate:L($,"UpdateDate")}}parsePolicies($){return D$($,"Policies","member").map((Y)=>({PolicyName:L(Y,"PolicyName")||"",PolicyId:L(Y,"PolicyId")||"",Arn:L(Y,"Arn")||"",Path:L(Y,"Path"),DefaultVersionId:L(Y,"DefaultVersionId"),AttachmentCount:L(Y,"AttachmentCount")?Number.parseInt(L(Y,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:L(Y,"PermissionsBoundaryUsageCount")?Number.parseInt(L(Y,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:L(Y,"IsAttachable")==="true",Description:L(Y,"Description"),CreateDate:L(Y,"CreateDate"),UpdateDate:L(Y,"UpdateDate")}))}parsePolicyVersions($){return D$($,"Versions","member").map((Y)=>({VersionId:L(Y,"VersionId")||"",IsDefaultVersion:L(Y,"IsDefaultVersion")==="true",CreateDate:L(Y,"CreateDate")}))}parseAttachedPolicies($){return D$($,"AttachedPolicies","member").map((Y)=>({PolicyName:L(Y,"PolicyName")||"",PolicyArn:L(Y,"PolicyArn")||""}))}async putUserPolicy($){await this.request("PutUserPolicy",$)}async getUserPolicy($){let J=await this.request("GetUserPolicy",$);return{UserName:L(J,"UserName")||"",PolicyName:L(J,"PolicyName")||"",PolicyDocument:decodeURIComponent(L(J,"PolicyDocument")||"")}}async deleteUserPolicy($){await this.request("DeleteUserPolicy",$)}async listUserPolicies($){let J=await this.request("ListUserPolicies",$),Y=D$(J,"PolicyNames","member"),Q=L(J,"IsTruncated")==="true",W=L(J,"Marker");return{PolicyNames:Y,IsTruncated:Q,Marker:W}}async putGroupPolicy($){await this.request("PutGroupPolicy",$)}async getGroupPolicy($){let J=await this.request("GetGroupPolicy",$);return{GroupName:L(J,"GroupName")||"",PolicyName:L(J,"PolicyName")||"",PolicyDocument:decodeURIComponent(L(J,"PolicyDocument")||"")}}async deleteGroupPolicy($){await this.request("DeleteGroupPolicy",$)}async listGroupPolicies($){let J=await this.request("ListGroupPolicies",$),Y=D$(J,"PolicyNames","member"),Q=L(J,"IsTruncated")==="true",W=L(J,"Marker");return{PolicyNames:Y,IsTruncated:Q,Marker:W}}async putRolePolicy($){await this.request("PutRolePolicy",$)}async getRolePolicy($){let J=await this.request("GetRolePolicy",$);return{RoleName:L(J,"RoleName")||"",PolicyName:L(J,"PolicyName")||"",PolicyDocument:decodeURIComponent(L(J,"PolicyDocument")||"")}}async deleteRolePolicy($){await this.request("DeleteRolePolicy",$)}async listRolePolicies($){let J=await this.request("ListRolePolicies",$),Y=D$(J,"PolicyNames","member"),Q=L(J,"IsTruncated")==="true",W=L(J,"Marker");return{PolicyNames:Y,IsTruncated:Q,Marker:W}}async createAccessKey($={}){let J=await this.request("CreateAccessKey",$);if(typeof J==="object"){let Y=J?.CreateAccessKeyResult?.AccessKey||J?.AccessKey;if(Y)return{AccessKey:{UserName:Y.UserName||"",AccessKeyId:Y.AccessKeyId||"",Status:Y.Status||"Active",SecretAccessKey:Y.SecretAccessKey||"",CreateDate:Y.CreateDate}}}return{AccessKey:{UserName:L(J,"UserName")||"",AccessKeyId:L(J,"AccessKeyId")||"",Status:L(J,"Status")||"Active",SecretAccessKey:L(J,"SecretAccessKey")||"",CreateDate:L(J,"CreateDate")}}}async listAccessKeys($={}){let J=await this.request("ListAccessKeys",$),Y=this.parseAccessKeys(J),Q=L(J,"IsTruncated")==="true",W=L(J,"Marker");return{AccessKeyMetadata:Y,IsTruncated:Q,Marker:W}}async updateAccessKey($){await this.request("UpdateAccessKey",$)}async deleteAccessKey($){await this.request("DeleteAccessKey",$)}async getAccessKeyLastUsed($){let J=await this.request("GetAccessKeyLastUsed",$);return{UserName:L(J,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:L(J,"LastUsedDate"),ServiceName:L(J,"ServiceName"),Region:L(J,"Region")}}}parseAccessKeys($){return D$($,"AccessKeyMetadata","member").map((Y)=>({UserName:L(Y,"UserName"),AccessKeyId:L(Y,"AccessKeyId")||"",Status:L(Y,"Status")||"Active",CreateDate:L(Y,"CreateDate")}))}async createInstanceProfile($){let J=await this.request("CreateInstanceProfile",$);return this.parseInstanceProfile(J)}async getInstanceProfile($){let J=await this.request("GetInstanceProfile",$);return this.parseInstanceProfile(J)}async listInstanceProfiles($={}){let J=await this.request("ListInstanceProfiles",$),Y=this.parseInstanceProfiles(J),Q=L(J,"IsTruncated")==="true",W=L(J,"Marker");return{InstanceProfiles:Y,IsTruncated:Q,Marker:W}}async listInstanceProfilesForRole($){let J=await this.request("ListInstanceProfilesForRole",$),Y=this.parseInstanceProfiles(J),Q=L(J,"IsTruncated")==="true",W=L(J,"Marker");return{InstanceProfiles:Y,IsTruncated:Q,Marker:W}}async addRoleToInstanceProfile($){await this.request("AddRoleToInstanceProfile",$)}async removeRoleFromInstanceProfile($){await this.request("RemoveRoleFromInstanceProfile",$)}async deleteInstanceProfile($){await this.request("DeleteInstanceProfile",$)}parseInstanceProfile($){return{InstanceProfileName:L($,"InstanceProfileName")||"",InstanceProfileId:L($,"InstanceProfileId")||"",Arn:L($,"Arn")||"",Path:L($,"Path"),CreateDate:L($,"CreateDate")}}parseInstanceProfiles($){return D$($,"InstanceProfiles","member").map((Y)=>({InstanceProfileName:L(Y,"InstanceProfileName")||"",InstanceProfileId:L(Y,"InstanceProfileId")||"",Arn:L(Y,"Arn")||"",Path:L(Y,"Path"),CreateDate:L(Y,"CreateDate")}))}async getAccountPasswordPolicy(){let $=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:L($,"MinimumPasswordLength")?Number.parseInt(L($,"MinimumPasswordLength"),10):void 0,RequireSymbols:L($,"RequireSymbols")==="true",RequireNumbers:L($,"RequireNumbers")==="true",RequireUppercaseCharacters:L($,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:L($,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:L($,"AllowUsersToChangePassword")==="true",ExpirePasswords:L($,"ExpirePasswords")==="true",MaxPasswordAge:L($,"MaxPasswordAge")?Number.parseInt(L($,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:L($,"PasswordReusePrevention")?Number.parseInt(L($,"PasswordReusePrevention"),10):void 0,HardExpiry:L($,"HardExpiry")==="true"}}async updateAccountPasswordPolicy($){await this.request("UpdateAccountPasswordPolicy",$)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let $=await this.request("GetAccountSummary"),J={},Y=D$($,"SummaryMap","entry");for(let Q of Y){let W=L(Q,"key"),U=L(Q,"value");if(W&&U)J[W]=Number.parseInt(U,10)}return J}async listAccountAliases(){let $=await this.request("ListAccountAliases"),J=D$($,"AccountAliases","member"),Y=L($,"IsTruncated")==="true",Q=L($,"Marker");return{AccountAliases:J,IsTruncated:Y,Marker:Q}}async createAccountAlias($){await this.request("CreateAccountAlias",$)}async deleteAccountAlias($){await this.request("DeleteAccountAlias",$)}async simulatePrincipalPolicy($){let J=await this.request("SimulatePrincipalPolicy",$);return this.parseSimulationResults(J)}parseSimulationResults($){let Y=D$($,"EvaluationResults","member").map((U)=>{let z=D$(U,"MatchedStatements","member").map((H)=>({SourcePolicyId:L(H,"SourcePolicyId"),SourcePolicyType:L(H,"SourcePolicyType")}));return{EvalActionName:L(U,"EvalActionName")||"",EvalResourceName:L(U,"EvalResourceName"),EvalDecision:L(U,"EvalDecision")||"",MatchedStatements:z.length>0?z:void 0}}),Q=L($,"IsTruncated")==="true",W=L($,"Marker");return{EvaluationResults:Y,IsTruncated:Q,Marker:W}}}function r6($){$.command("iam:roles","List IAM roles").option("--prefix <prefix>","Filter by role name prefix").option("--path <path>","Filter by path prefix",{default:"/"}).action(async(J)=>{V("IAM Roles");try{let Y=new a$,Q=new M("Fetching roles...");Q.start();let U=(await Y.listRoles({PathPrefix:J.path})).Roles||[];if(J.prefix)U=U.filter((Z)=>Z.RoleName?.startsWith(J.prefix));if(Q.succeed(`Found ${U.length} role(s)`),U.length===0){G("No IAM roles found");return}x(["Role Name","Path","Created","Description"],U.map((Z)=>[Z.RoleName||"N/A",Z.Path||"/",Z.CreateDate?new Date(Z.CreateDate).toLocaleDateString():"N/A",(Z.Description||"").substring(0,40)]))}catch(Y){_(`Failed to list roles: ${Y.message}`),process.exit(1)}}),$.command("iam:role <roleName>","Show IAM role details").action(async(J)=>{V(`IAM Role: ${J}`);try{let Y=new a$,Q=new M("Fetching role details...");Q.start();let W=await Y.getRole({RoleName:J}),U=await Y.listAttachedRolePolicies({RoleName:J}),Z=await Y.listRolePolicies({RoleName:J});if(Q.succeed("Role details loaded"),G(`
1654
+ Role Information:`),G(` Name: ${W.RoleName}`),G(` ARN: ${W.Arn}`),G(` Path: ${W.Path}`),G(` Created: ${W.CreateDate?new Date(W.CreateDate).toLocaleString():"N/A"}`),W.Description)G(` Description: ${W.Description}`);if(W.MaxSessionDuration)G(` Max Session: ${W.MaxSessionDuration/3600} hours`);if(W.AssumeRolePolicyDocument){G(`
1655
+ Trust Policy:`);let z=JSON.parse(decodeURIComponent(W.AssumeRolePolicyDocument));console.log(JSON.stringify(z,null,2))}if(U.AttachedPolicies&&U.AttachedPolicies.length>0){G(`
1656
+ Attached Managed Policies:`);for(let z of U.AttachedPolicies)G(` - ${z.PolicyName}`)}if(Z.PolicyNames&&Z.PolicyNames.length>0){G(`
1657
+ Inline Policies:`);for(let z of Z.PolicyNames)G(` - ${z}`)}if(W.Tags&&W.Tags.length>0){G(`
1658
+ Tags:`);for(let z of W.Tags)G(` ${z.Key}: ${z.Value}`)}}catch(Y){_(`Failed to get role: ${Y.message}`),process.exit(1)}}),$.command("iam:policies","List IAM policies").option("--scope <scope>","Filter by scope (All, AWS, Local)",{default:"Local"}).option("--prefix <prefix>","Filter by policy name prefix").option("--path <path>","Filter by path prefix",{default:"/"}).action(async(J)=>{V("IAM Policies");try{let Y=new a$,Q=new M("Fetching policies...");Q.start();let U=(await Y.listPolicies({Scope:J.scope,PathPrefix:J.path,OnlyAttached:!1})).Policies||[];if(J.prefix)U=U.filter((Z)=>Z.PolicyName?.startsWith(J.prefix));if(Q.succeed(`Found ${U.length} policy(s)`),U.length===0){G("No IAM policies found");return}if(x(["Policy Name","ARN","Attachments","Created"],U.slice(0,50).map((Z)=>[Z.PolicyName||"N/A",(Z.Arn||"N/A").substring(0,50),(Z.AttachmentCount||0).toString(),Z.CreateDate?new Date(Z.CreateDate).toLocaleDateString():"N/A"])),U.length>50)G(`
1659
+ ... and ${U.length-50} more policies`)}catch(Y){_(`Failed to list policies: ${Y.message}`),process.exit(1)}}),$.command("iam:policy <policyArn>","Show IAM policy details").option("--version <version>","Policy version ID").action(async(J,Y)=>{V("IAM Policy Details");try{let Q=new a$,W=new M("Fetching policy...");W.start();let U=await Q.getPolicy({PolicyArn:J}),Z=Y.version||U.DefaultVersionId||"v1",z=await Q.getPolicyVersion({PolicyArn:J,VersionId:Z});if(W.succeed("Policy loaded"),G(`
1660
+ Policy Information:`),G(` Name: ${U.PolicyName}`),G(` ARN: ${U.Arn}`),G(` Path: ${U.Path}`),G(` Created: ${U.CreateDate?new Date(U.CreateDate).toLocaleString():"N/A"}`),G(` Updated: ${U.UpdateDate?new Date(U.UpdateDate).toLocaleString():"N/A"}`),G(` Attachment Count: ${U.AttachmentCount||0}`),G(` Version: ${Z}`),U.Description)G(` Description: ${U.Description}`);if(z.Document){G(`
1661
+ Policy Document:`);let H=JSON.parse(decodeURIComponent(z.Document));console.log(JSON.stringify(H,null,2))}}catch(Q){_(`Failed to get policy: ${Q.message}`),process.exit(1)}}),$.command("iam:users","List IAM users").option("--path <path>","Filter by path prefix",{default:"/"}).action(async(J)=>{V("IAM Users");try{let Y=new a$,Q=new M("Fetching users...");Q.start();let U=(await Y.listUsers({PathPrefix:J.path})).Users||[];if(Q.succeed(`Found ${U.length} user(s)`),U.length===0){G("No IAM users found");return}x(["User Name","User ID","Path","Created","Password Last Used"],U.map((Z)=>[Z.UserName||"N/A",Z.UserId||"N/A",Z.Path||"/",Z.CreateDate?new Date(Z.CreateDate).toLocaleDateString():"N/A",Z.PasswordLastUsed?new Date(Z.PasswordLastUsed).toLocaleDateString():"Never"]))}catch(Y){_(`Failed to list users: ${Y.message}`),process.exit(1)}}),$.command("iam:user <userName>","Show IAM user details").action(async(J)=>{V(`IAM User: ${J}`);try{let Y=new a$,Q=new M("Fetching user details...");Q.start();let W=await Y.getUser({UserName:J}),[U,Z,z]=await Promise.all([Y.listGroupsForUser({UserName:J}),Y.listAttachedUserPolicies({UserName:J}),Y.listAccessKeys({UserName:J})]);if(Q.succeed("User details loaded"),G(`
1662
+ User Information:`),G(` Name: ${W.UserName}`),G(` ARN: ${W.Arn}`),G(` User ID: ${W.UserId}`),G(` Path: ${W.Path}`),G(` Created: ${W.CreateDate?new Date(W.CreateDate).toLocaleString():"N/A"}`),W.PasswordLastUsed)G(` Password Last Used: ${new Date(W.PasswordLastUsed).toLocaleString()}`);if(U.Groups&&U.Groups.length>0){G(`
1663
+ Groups:`);for(let H of U.Groups)G(` - ${H.GroupName}`)}if(Z.AttachedPolicies&&Z.AttachedPolicies.length>0){G(`
1664
+ Attached Policies:`);for(let H of Z.AttachedPolicies)G(` - ${H.PolicyName}`)}if(z.AccessKeyMetadata&&z.AccessKeyMetadata.length>0){G(`
1665
+ Access Keys:`);for(let H of z.AccessKeyMetadata)if(G(` - ${H.AccessKeyId}: ${H.Status}`),H.CreateDate)G(` Created: ${new Date(H.CreateDate).toLocaleString()}`)}if(W.Tags&&W.Tags.length>0){G(`
1666
+ Tags:`);for(let H of W.Tags)G(` ${H.Key}: ${H.Value}`)}}catch(Y){_(`Failed to get user: ${Y.message}`),process.exit(1)}}),$.command("iam:groups","List IAM groups").option("--path <path>","Filter by path prefix",{default:"/"}).action(async(J)=>{V("IAM Groups");try{let Y=new a$,Q=new M("Fetching groups...");Q.start();let U=(await Y.listGroups({PathPrefix:J.path})).Groups||[];if(Q.succeed(`Found ${U.length} group(s)`),U.length===0){G("No IAM groups found");return}x(["Group Name","Group ID","Path","Created"],U.map((Z)=>[Z.GroupName||"N/A",Z.GroupId||"N/A",Z.Path||"/",Z.CreateDate?new Date(Z.CreateDate).toLocaleDateString():"N/A"]))}catch(Y){_(`Failed to list groups: ${Y.message}`),process.exit(1)}}),$.command("iam:simulate <policyArn>","Simulate IAM policy").option("--action <action>","Action to simulate (e.g., s3:GetObject)").option("--resource <arn>","Resource ARN to test against").action(async(J,Y)=>{V("Simulate IAM Policy");try{let Q=new a$,W=Y.action||await U$("Action to simulate","s3:GetObject"),U=Y.resource||await U$("Resource ARN","*");G(`
1667
+ Policy: ${J}`),G(`Action: ${W}`),G(`Resource: ${U}`);let Z=new M("Running simulation...");Z.start();let z=await Q.simulatePrincipalPolicy({PolicySourceArn:J,ActionNames:[W],ResourceArns:[U]});if(Z.succeed("Simulation complete"),z.EvaluationResults&&z.EvaluationResults.length>0)for(let H of z.EvaluationResults){let K=H.EvalDecision;if(G(`
1668
+ Result for ${H.EvalActionName}:`),K==="allowed")A(" Decision: ALLOWED");else if(K==="implicitDeny")N(" Decision: IMPLICIT DENY (no matching allow statement)");else _(" Decision: EXPLICIT DENY");if(H.MatchedStatements&&H.MatchedStatements.length>0){G(" Matched Statements:");for(let B of H.MatchedStatements)G(` - ${B.SourcePolicyId}: ${B.SourcePolicyType}`)}}}catch(Q){_(`Failed to simulate policy: ${Q.message}`),process.exit(1)}}),$.command("iam:whoami","Show current IAM identity").action(async()=>{V("Current IAM Identity");try{let J=new a$,Y=new M("Fetching identity...");Y.start();let{STSClient:Q}=await Promise.resolve().then(() => (C9(),P9)),U=await new Q("us-east-1").getCallerIdentity();Y.succeed("Identity loaded"),G(`
1669
+ Caller Identity:`),G(` Account: ${U.Account}`),G(` ARN: ${U.Arn}`),G(` User ID: ${U.UserId}`);let Z=U.Arn||"";if(Z.includes(":user/"))G(" Type: IAM User");else if(Z.includes(":assumed-role/"))G(" Type: Assumed Role");else if(Z.includes(":root"))N(" Type: Root Account"),N(`
1670
+ Warning: Using root credentials is not recommended!`)}catch(J){_(`Failed to get identity: ${J.message}`),process.exit(1)}})}async function _0($){let{AWSClient:J}=await Promise.resolve().then(() => (W$(),T0));class Y{client;region;constructor(Q){this.region=Q,this.client=new J}async jsonRpcRequest(Q,W){return this.client.request({service:"cloudtrail",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.${Q}`},body:JSON.stringify(W)})}async describeTrails(){return this.jsonRpcRequest("DescribeTrails",{})}async getTrailStatus(Q){return this.jsonRpcRequest("GetTrailStatus",{Name:Q})}async lookupEvents(Q){return this.jsonRpcRequest("LookupEvents",{...Q,StartTime:Q.StartTime?.toISOString(),EndTime:Q.EndTime?.toISOString()})}async getEventSelectors(Q){return this.jsonRpcRequest("GetEventSelectors",{TrailName:Q})}async createTrail(Q){return this.jsonRpcRequest("CreateTrail",Q)}async startLogging(Q){return this.jsonRpcRequest("StartLogging",{Name:Q})}async stopLogging(Q){return this.jsonRpcRequest("StopLogging",{Name:Q})}async deleteTrail(Q){return this.jsonRpcRequest("DeleteTrail",{Name:Q})}}return new Y($)}function a6($){$.command("audit:trails","List CloudTrail trails").option("--region <region>","AWS region").action(async(J)=>{V("CloudTrail Trails");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=await _0(Q),U=new M("Fetching trails...");U.start();let z=(await W.describeTrails()).trailList||[];if(U.succeed(`Found ${z.length} trail(s)`),z.length===0){G("No CloudTrail trails found"),G("Use `cloud audit:create` to create a new trail");return}x(["Name","Multi-Region","S3 Bucket","Log Validation","Home Region"],z.map((H)=>[H.Name||"N/A",H.IsMultiRegionTrail?"Yes":"No",H.S3BucketName||"N/A",H.LogFileValidationEnabled?"Yes":"No",H.HomeRegion||"N/A"]))}catch(Y){_(`Failed to list trails: ${Y.message}`),process.exit(1)}}),$.command("audit:trail <trailName>","Show CloudTrail trail details").option("--region <region>","AWS region").action(async(J,Y)=>{V(`CloudTrail: ${J}`);try{let Q=await g(),W=Y.region||Q.project.region||"us-east-1",U=await _0(W),Z=new M("Fetching trail details...");Z.start();let[z,H]=await Promise.all([U.describeTrails(),U.getTrailStatus(J)]),K=(z.trailList||[]).find((B)=>B.Name===J);if(!K){Z.fail("Trail not found");return}if(Z.succeed("Trail details loaded"),G(`
1671
+ Trail Configuration:`),G(` Name: ${K.Name}`),G(` ARN: ${K.TrailARN}`),G(` Home Region: ${K.HomeRegion}`),G(` Multi-Region: ${K.IsMultiRegionTrail?"Yes":"No"}`),G(` Organization Trail: ${K.IsOrganizationTrail?"Yes":"No"}`),G(`
1672
+ Storage:`),G(` S3 Bucket: ${K.S3BucketName}`),K.S3KeyPrefix)G(` S3 Prefix: ${K.S3KeyPrefix}`);if(G(` Log Validation: ${K.LogFileValidationEnabled?"Enabled":"Disabled"}`),K.CloudWatchLogsLogGroupArn)G(`
1673
+ CloudWatch Logs:`),G(` Log Group: ${K.CloudWatchLogsLogGroupArn}`);if(K.KMSKeyId)G(`
1674
+ Encryption:`),G(` KMS Key: ${K.KMSKeyId}`);if(G(`
1675
+ Status:`),G(` Logging: ${H.IsLogging?"Active":"Stopped"}`),H.LatestDeliveryTime)G(` Latest Delivery: ${new Date(H.LatestDeliveryTime).toLocaleString()}`);if(H.LatestDeliveryError)N(` Latest Error: ${H.LatestDeliveryError}`);try{let B=await U.getEventSelectors(J);if(B.EventSelectors&&B.EventSelectors.length>0){G(`
1676
+ Event Selectors:`);for(let O of B.EventSelectors)if(G(` - Read/Write: ${O.ReadWriteType}`),G(` Management Events: ${O.IncludeManagementEvents?"Yes":"No"}`),O.DataResources&&O.DataResources.length>0)G(` Data Resources: ${O.DataResources.length} configured`)}}catch{}}catch(Q){_(`Failed to get trail: ${Q.message}`),process.exit(1)}}),$.command("audit:events","Look up recent CloudTrail events").option("--region <region>","AWS region").option("--user <username>","Filter by IAM user").option("--event <eventName>","Filter by event name").option("--resource <resourceName>","Filter by resource name").option("--hours <number>","Hours to look back",{default:"24"}).option("--limit <number>","Maximum events to return",{default:"50"}).action(async(J)=>{V("CloudTrail Events");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=await _0(Q),U=new M("Looking up events...");U.start();let Z=new Date,H={StartTime:new Date(Z.getTime()-Number.parseInt(J.hours)*60*60*1000),EndTime:Z,MaxResults:Number.parseInt(J.limit)};if(J.user)H.LookupAttributes=[{AttributeKey:"Username",AttributeValue:J.user}];else if(J.event)H.LookupAttributes=[{AttributeKey:"EventName",AttributeValue:J.event}];else if(J.resource)H.LookupAttributes=[{AttributeKey:"ResourceName",AttributeValue:J.resource}];let B=(await W.lookupEvents(H)).Events||[];if(U.succeed(`Found ${B.length} event(s)`),B.length===0){G("No events found matching criteria");return}x(["Time","Event","User","Source IP","Resources"],B.map((O)=>[O.EventTime?new Date(O.EventTime).toLocaleString():"N/A",O.EventName||"N/A",O.Username||"N/A",O.SourceIPAddress||"N/A",(O.Resources||[]).map((X)=>X.ResourceName).join(", ").substring(0,30)||"-"]))}catch(Y){_(`Failed to lookup events: ${Y.message}`),process.exit(1)}}),$.command("audit:event <eventId>","Show CloudTrail event details").option("--region <region>","AWS region").action(async(J,Y)=>{V(`Event: ${J}`);try{let Q=await g(),W=Y.region||Q.project.region||"us-east-1",U=await _0(W),Z=new M("Fetching event...");Z.start();let H=(await U.lookupEvents({LookupAttributes:[{AttributeKey:"EventId",AttributeValue:J}],MaxResults:1})).Events?.[0];if(!H){Z.fail("Event not found");return}if(Z.succeed("Event loaded"),G(`
1677
+ Event Information:`),G(` Event ID: ${H.EventId}`),G(` Event Name: ${H.EventName}`),G(` Event Time: ${H.EventTime?new Date(H.EventTime).toLocaleString():"N/A"}`),G(` Event Source: ${H.EventSource}`),G(` Username: ${H.Username}`),G(` Source IP: ${H.SourceIPAddress}`),G(` Access Key: ${H.AccessKeyId||"N/A"}`),H.Resources&&H.Resources.length>0){G(`
1678
+ Resources:`);for(let K of H.Resources)G(` - ${K.ResourceType}: ${K.ResourceName}`)}if(H.CloudTrailEvent){G(`
1679
+ Full Event Record:`);let K=JSON.parse(H.CloudTrailEvent);console.log(JSON.stringify(K,null,2))}}catch(Q){_(`Failed to get event: ${Q.message}`),process.exit(1)}}),$.command("audit:create <trailName>","Create a new CloudTrail trail").option("--region <region>","AWS region",{default:"us-east-1"}).option("--bucket <name>","S3 bucket for logs").option("--prefix <prefix>","S3 key prefix").option("--multi-region","Enable multi-region trail").option("--validation","Enable log file validation").option("--global-events","Include global service events").action(async(J,Y)=>{V("Create CloudTrail Trail");try{if(!Y.bucket){_("--bucket is required");return}let Q=await _0(Y.region);if(G(`Trail Name: ${J}`),G(`S3 Bucket: ${Y.bucket}`),G(`Multi-Region: ${Y.multiRegion?"Yes":"No"}`),G(`Log Validation: ${Y.validation?"Yes":"No"}`),G(`Global Events: ${Y.globalEvents?"Yes":"No"}`),!await P(`
1680
+ Create this trail?`,!0)){G("Operation cancelled");return}let U=new M("Creating trail...");U.start();let Z=await Q.createTrail({Name:J,S3BucketName:Y.bucket,S3KeyPrefix:Y.prefix,IsMultiRegionTrail:Y.multiRegion,EnableLogFileValidation:Y.validation,IncludeGlobalServiceEvents:Y.globalEvents??!0});U.text="Starting logging...",await Q.startLogging(J),U.succeed("Trail created and logging started"),A(`
1681
+ Trail ARN: ${Z.TrailARN}`),G(`S3 Bucket: ${Z.S3BucketName}`)}catch(Q){_(`Failed to create trail: ${Q.message}`),process.exit(1)}}),$.command("audit:start <trailName>","Start CloudTrail logging").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{V("Start CloudTrail Logging");try{let Q=await _0(Y.region),W=new M("Starting logging...");W.start(),await Q.startLogging(J),W.succeed("Logging started")}catch(Q){_(`Failed to start logging: ${Q.message}`),process.exit(1)}}),$.command("audit:stop <trailName>","Stop CloudTrail logging").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{V("Stop CloudTrail Logging");try{let Q=await _0(Y.region);if(N(`This will stop logging for trail: ${J}`),!await P(`
1682
+ Stop logging?`,!1)){G("Operation cancelled");return}let U=new M("Stopping logging...");U.start(),await Q.stopLogging(J),U.succeed("Logging stopped")}catch(Q){_(`Failed to stop logging: ${Q.message}`),process.exit(1)}}),$.command("audit:delete <trailName>","Delete a CloudTrail trail").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{V("Delete CloudTrail Trail");try{let Q=await _0(Y.region);if(N(`This will permanently delete trail: ${J}`),!await P(`
1683
+ Delete this trail?`,!1)){G("Operation cancelled");return}let U=new M("Deleting trail...");U.start(),await Q.deleteTrail(J),U.succeed("Trail deleted")}catch(Q){_(`Failed to delete trail: ${Q.message}`),process.exit(1)}})}function i6($){$.command("status","Show overall infrastructure health dashboard").option("--region <region>","AWS region").action(async(J)=>{V("Infrastructure Status Dashboard");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1";G(`Region: ${Q}`),G(`Project: ${Y.project.name||"Unknown"}`),G("");let W=[],U=new M("Checking EC2 instances...");U.start();try{let{EC2Client:E}=await Promise.resolve().then(() => (u6(),S9)),w=await new E(Q).describeInstances({Filters:[{Name:"instance-state-name",Values:["running","pending","stopping","stopped"]}]}),T=0,S=0,R=0;for(let C of w.Reservations||[])for(let D of C.Instances||[])if(R++,D.State?.Name==="running")T++;else if(D.State?.Name==="stopped")S++;U.succeed("EC2 instances checked"),W.push({name:"EC2 Instances",status:T>0?"OK":R>0?"WARN":"INFO",details:`${T} running, ${S} stopped, ${R} total`})}catch(E){U.fail("EC2 check failed"),W.push({name:"EC2 Instances",status:"ERROR",details:E.message})}let Z=new M("Checking RDS instances...");Z.start();try{let{RDSClient:E}=await Promise.resolve().then(() => (I9(),k9)),T=(await new E(Q).describeDBInstances()).DBInstances||[],S=T.filter((R)=>R.DBInstanceStatus==="available").length;Z.succeed("RDS instances checked"),W.push({name:"RDS Databases",status:T.length>0&&S===T.length?"OK":T.length>0?"WARN":"INFO",details:`${S} available, ${T.length} total`})}catch(E){Z.fail("RDS check failed"),W.push({name:"RDS Databases",status:"ERROR",details:E.message})}let z=new M("Checking Lambda functions...");z.start();try{let{LambdaClient:E}=await Promise.resolve().then(() => (s6(),n6)),T=(await new E(Q).listFunctions()).Functions||[];z.succeed("Lambda functions checked"),W.push({name:"Lambda Functions",status:"OK",details:`${T.length} function(s)`})}catch(E){z.fail("Lambda check failed"),W.push({name:"Lambda Functions",status:"ERROR",details:E.message})}let H=new M("Checking S3 buckets...");H.start();try{let{S3Client:E}=await Promise.resolve().then(() => (V0(),_6)),T=(await new E(Q).listBuckets()).Buckets||[];H.succeed("S3 buckets checked"),W.push({name:"S3 Buckets",status:"OK",details:`${T.length} bucket(s)`})}catch(E){H.fail("S3 check failed"),W.push({name:"S3 Buckets",status:"ERROR",details:E.message})}let K=new M("Checking CloudFront distributions...");K.start();try{let{CloudFrontClient:E}=await Promise.resolve().then(() => (M0(),F6)),w=await new E().listDistributions(),T=w.filter((S)=>S.Status==="Deployed").length;K.succeed("CloudFront checked"),W.push({name:"CloudFront",status:w.length>0&&T===w.length?"OK":w.length>0?"WARN":"INFO",details:`${T} deployed, ${w.length} total`})}catch(E){K.fail("CloudFront check failed"),W.push({name:"CloudFront",status:"ERROR",details:E.message})}let B=new M("Checking SQS queues...");B.start();try{let{SQSClient:E}=await Promise.resolve().then(() => (f6(),R9)),T=(await new E(Q).listQueues()).QueueUrls||[];B.succeed("SQS queues checked"),W.push({name:"SQS Queues",status:"OK",details:`${T.length} queue(s)`})}catch(E){B.fail("SQS check failed"),W.push({name:"SQS Queues",status:"ERROR",details:E.message})}let O=new M("Checking CloudFormation stacks...");O.start();try{let{CloudFormationClient:E}=await Promise.resolve().then(() => (G0(),W6)),T=(await new E(Q).listStacks(["CREATE_COMPLETE","UPDATE_COMPLETE","CREATE_IN_PROGRESS","UPDATE_IN_PROGRESS","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE"])).StackSummaries||[],S=T.filter((D)=>D.StackStatus==="CREATE_COMPLETE"||D.StackStatus==="UPDATE_COMPLETE").length,R=T.filter((D)=>D.StackStatus?.includes("IN_PROGRESS")).length,C=T.filter((D)=>D.StackStatus?.includes("ROLLBACK")).length;O.succeed("CloudFormation checked"),W.push({name:"CloudFormation",status:C>0?"WARN":R>0?"INFO":"OK",details:`${S} healthy, ${R} in progress, ${C} rolled back`})}catch(E){O.fail("CloudFormation check failed"),W.push({name:"CloudFormation",status:"ERROR",details:E.message})}let X=new M("Checking SSL certificates...");X.start();try{let{ACMClient:E}=await Promise.resolve().then(() => (X0(),I8)),F=new E("us-east-1"),T=(await F.listCertificates()).CertificateSummaryList||[],S=await Promise.all(T.map((k)=>F.describeCertificate({CertificateArn:k.CertificateArn}))),R=S.filter((k)=>k.Status==="ISSUED").length,C=S.filter((k)=>k.Status==="PENDING_VALIDATION").length,D=S.filter((k)=>{if(k.NotAfter)return(new Date(k.NotAfter).getTime()-Date.now())/86400000<30;return!1}).length;X.succeed("SSL certificates checked"),W.push({name:"SSL Certificates",status:D>0?"WARN":C>0?"INFO":"OK",details:`${R} issued, ${C} pending${D>0?`, ${D} expiring soon`:""}`})}catch(E){X.fail("ACM check failed"),W.push({name:"SSL Certificates",status:"ERROR",details:E.message})}G(`
1684
+ `+"=".repeat(60)),G("HEALTH SUMMARY"),G("=".repeat(60)+`
1685
+ `);for(let E of W){let F="";if(E.status==="OK")F=`${s.green}[OK]${s.reset}`;else if(E.status==="WARN")F=`${s.yellow}[WARN]${s.reset}`;else if(E.status==="ERROR")F=`${s.red}[ERROR]${s.reset}`;else F=`${s.blue}[INFO]${s.reset}`;console.log(`${F} ${E.name.padEnd(20)} ${E.details}`)}let j=W.some((E)=>E.status==="ERROR"),q=W.some((E)=>E.status==="WARN");if(G(""),j)_("Some services have errors. Check the details above.");else if(q)N("Some services need attention. Check the warnings above.");else A("All services are healthy!")}catch(Y){_(`Failed to get status: ${Y.message}`),process.exit(1)}}),$.command("status:costs","Show current month cost summary").option("--region <region>","AWS region").action(async(J)=>{V("Cost Summary");try{G("Fetching cost data from AWS Cost Explorer..."),G("");let Y=new Date,Q=new Date(Y.getFullYear(),Y.getMonth(),1),W=new Date(Y.getFullYear(),Y.getMonth()+1,0);G(`Period: ${Q.toISOString().split("T")[0]} to ${W.toISOString().split("T")[0]}`),G(""),G("Note: Cost data requires AWS Cost Explorer API access."),G("Run `cloud cost` for detailed cost analysis.")}catch(Y){_(`Failed to get cost summary: ${Y.message}`),process.exit(1)}}),$.command("status:alarms","Show CloudWatch alarm status").option("--region <region>","AWS region").action(async(J)=>{V("CloudWatch Alarms");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",{AWSClient:W}=await Promise.resolve().then(() => (W$(),T0));class U{client;region;constructor(j){this.region=j,this.client=new W}async describeAlarms(){return this.client.request({service:"monitoring",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=DescribeAlarms&Version=2010-08-01"})}}let Z=new U(Q),z=new M("Fetching alarms...");z.start();let K=(await Z.describeAlarms()).MetricAlarms||[];if(z.succeed(`Found ${K.length} alarm(s)`),K.length===0){G("No CloudWatch alarms configured");return}let B=K.filter((j)=>j.StateValue==="ALARM"),O=K.filter((j)=>j.StateValue==="OK"),X=K.filter((j)=>j.StateValue==="INSUFFICIENT_DATA");if(G(""),G(`Alarming: ${B.length}`),G(`OK: ${O.length}`),G(`Insufficient Data: ${X.length}`),B.length>0){G(`
1686
+ Alarms in ALARM state:`);for(let j of B)_(` - ${j.AlarmName}: ${j.AlarmDescription||"No description"}`)}}catch(Y){_(`Failed to get alarms: ${Y.message}`),process.exit(1)}})}async function n$($){let{AWSClient:J}=await Promise.resolve().then(() => (W$(),T0));class Y{client;region;constructor(Q){this.region=Q,this.client=new J}async jsonRpcRequest(Q,W){return this.client.request({service:"backup",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`CryoControllerFrontendService.${Q}`},body:JSON.stringify(W)})}async listBackupVaults(){return this.jsonRpcRequest("ListBackupVaults",{})}async listBackupPlans(){return this.jsonRpcRequest("ListBackupPlans",{})}async listRecoveryPointsByBackupVault(Q,W){return this.jsonRpcRequest("ListRecoveryPointsByBackupVault",{BackupVaultName:Q,...W})}async describeBackupVault(Q){return this.jsonRpcRequest("DescribeBackupVault",{BackupVaultName:Q})}async getBackupPlan(Q){return this.jsonRpcRequest("GetBackupPlan",{BackupPlanId:Q})}async createBackupVault(Q,W){return this.jsonRpcRequest("CreateBackupVault",{BackupVaultName:Q,...W})}async deleteBackupVault(Q){return this.jsonRpcRequest("DeleteBackupVault",{BackupVaultName:Q})}async createBackupPlan(Q){return this.jsonRpcRequest("CreateBackupPlan",{BackupPlan:Q})}async deleteBackupPlan(Q){return this.jsonRpcRequest("DeleteBackupPlan",{BackupPlanId:Q})}async startBackupJob(Q){return this.jsonRpcRequest("StartBackupJob",Q)}async startRestoreJob(Q){return this.jsonRpcRequest("StartRestoreJob",Q)}async describeBackupJob(Q){return this.jsonRpcRequest("DescribeBackupJob",{BackupJobId:Q})}async describeRestoreJob(Q){return this.jsonRpcRequest("DescribeRestoreJob",{RestoreJobId:Q})}async listBackupJobs(Q){return this.jsonRpcRequest("ListBackupJobs",Q||{})}async listRestoreJobs(Q){return this.jsonRpcRequest("ListRestoreJobs",Q||{})}async createBackupSelection(Q,W){return this.jsonRpcRequest("CreateBackupSelection",{BackupPlanId:Q,BackupSelection:W})}async listBackupSelections(Q){return this.jsonRpcRequest("ListBackupSelections",{BackupPlanId:Q})}}return new Y($)}function t6($){$.command("backup:vaults","List backup vaults").option("--region <region>","AWS region").action(async(J)=>{V("Backup Vaults");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=await n$(Q),U=new M("Fetching vaults...");U.start();let z=(await W.listBackupVaults()).BackupVaultList||[];if(U.succeed(`Found ${z.length} vault(s)`),z.length===0){G("No backup vaults found"),G("Use `cloud backup:create-vault` to create a new vault");return}x(["Vault Name","Recovery Points","Created","Encrypted"],z.map((H)=>[H.BackupVaultName||"N/A",(H.NumberOfRecoveryPoints||0).toString(),H.CreationDate?new Date(H.CreationDate).toLocaleDateString():"N/A",H.EncryptionKeyArn?"Yes":"Default"]))}catch(Y){_(`Failed to list vaults: ${Y.message}`),process.exit(1)}}),$.command("backup:list","List backup plans").option("--region <region>","AWS region").action(async(J)=>{V("Backup Plans");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=await n$(Q),U=new M("Fetching backup plans...");U.start();let z=(await W.listBackupPlans()).BackupPlansList||[];if(U.succeed(`Found ${z.length} backup plan(s)`),z.length===0){G("No backup plans found"),G("Use `cloud backup:create` to create a backup plan");return}x(["Plan Name","Plan ID","Version","Created"],z.map((H)=>[H.BackupPlanName||"N/A",H.BackupPlanId||"N/A",H.VersionId?.substring(0,8)||"N/A",H.CreationDate?new Date(H.CreationDate).toLocaleDateString():"N/A"]))}catch(Y){_(`Failed to list backup plans: ${Y.message}`),process.exit(1)}}),$.command("backup:recovery-points <vaultName>","List recovery points in a vault").option("--region <region>","AWS region").option("--limit <number>","Maximum results",{default:"50"}).action(async(J,Y)=>{V(`Recovery Points: ${J}`);try{let Q=await g(),W=Y.region||Q.project.region||"us-east-1",U=await n$(W),Z=new M("Fetching recovery points...");Z.start();let H=(await U.listRecoveryPointsByBackupVault(J,{MaxResults:Number.parseInt(Y.limit)})).RecoveryPoints||[];if(Z.succeed(`Found ${H.length} recovery point(s)`),H.length===0){G("No recovery points found");return}x(["Resource","Status","Created","Size","Lifecycle"],H.map((K)=>[K.ResourceArn?.split(":").pop()||"N/A",K.Status||"N/A",K.CreationDate?new Date(K.CreationDate).toLocaleString():"N/A",K.BackupSizeInBytes?b9(K.BackupSizeInBytes):"N/A",K.Lifecycle?.DeleteAfterDays?`${K.Lifecycle.DeleteAfterDays} days`:"Indefinite"]))}catch(Q){_(`Failed to list recovery points: ${Q.message}`),process.exit(1)}}),$.command("backup:create-vault <vaultName>","Create a backup vault").option("--region <region>","AWS region",{default:"us-east-1"}).option("--kms-key <arn>","KMS key ARN for encryption").action(async(J,Y)=>{V("Create Backup Vault");try{let Q=await n$(Y.region);if(G(`Vault Name: ${J}`),G(`Region: ${Y.region}`),G(`Encryption: ${Y.kmsKey?"Custom KMS":"AWS Managed"}`),!await P(`
1687
+ Create this vault?`,!0)){G("Operation cancelled");return}let U=new M("Creating vault...");U.start(),await Q.createBackupVault(J,{EncryptionKeyArn:Y.kmsKey}),U.succeed("Vault created"),A(`
1688
+ Vault: ${J}`)}catch(Q){_(`Failed to create vault: ${Q.message}`),process.exit(1)}}),$.command("backup:create <planName>","Create a backup plan").option("--region <region>","AWS region",{default:"us-east-1"}).option("--vault <name>","Target backup vault",{default:"Default"}).option("--schedule <cron>","Backup schedule (cron expression)",{default:"cron(0 5 ? * * *)"}).option("--retention <days>","Retention period in days",{default:"30"}).option("--lifecycle-cold <days>","Move to cold storage after days").action(async(J,Y)=>{V("Create Backup Plan");try{let Q=await n$(Y.region);if(G(`Plan Name: ${J}`),G(`Vault: ${Y.vault}`),G(`Schedule: ${Y.schedule}`),G(`Retention: ${Y.retention} days`),!await P(`
1689
+ Create this backup plan?`,!0)){G("Operation cancelled");return}let U=new M("Creating backup plan...");U.start();let Z={DeleteAfterDays:Number.parseInt(Y.retention)};if(Y.lifecycleCold)Z.MoveToColdStorageAfterDays=Number.parseInt(Y.lifecycleCold);let z=await Q.createBackupPlan({BackupPlanName:J,Rules:[{RuleName:`${J}-daily`,TargetBackupVaultName:Y.vault,ScheduleExpression:Y.schedule,StartWindowMinutes:60,CompletionWindowMinutes:180,Lifecycle:Z}]});U.succeed("Backup plan created"),A(`
1690
+ Plan ID: ${z.BackupPlanId}`),G("\nNote: Add resource selections with `cloud backup:add-selection`")}catch(Q){_(`Failed to create backup plan: ${Q.message}`),process.exit(1)}}),$.command("backup:add-selection <planId>","Add resources to a backup plan").option("--region <region>","AWS region",{default:"us-east-1"}).option("--name <name>","Selection name").option("--role <arn>","IAM role ARN for backup").option("--resource <arn>","Resource ARN to backup").option("--tag-key <key>","Tag key for resource selection").option("--tag-value <value>","Tag value for resource selection").action(async(J,Y)=>{V("Add Backup Selection");try{if(!Y.role){_("--role is required (IAM role ARN for AWS Backup)");return}if(!Y.resource&&!Y.tagKey){_("Specify --resource or --tag-key/--tag-value");return}let Q=await n$(Y.region),U={SelectionName:Y.name||`selection-${Date.now()}`,IamRoleArn:Y.role};if(Y.resource)U.Resources=[Y.resource],G(`Resource: ${Y.resource}`);if(Y.tagKey&&Y.tagValue)U.ListOfTags=[{ConditionType:"STRINGEQUALS",ConditionKey:Y.tagKey,ConditionValue:Y.tagValue}],G(`Tag: ${Y.tagKey}=${Y.tagValue}`);if(!await P(`
1691
+ Add this selection?`,!0)){G("Operation cancelled");return}let z=new M("Adding selection...");z.start();let H=await Q.createBackupSelection(J,U);z.succeed("Selection added"),A(`
1692
+ Selection ID: ${H.SelectionId}`)}catch(Q){_(`Failed to add selection: ${Q.message}`),process.exit(1)}}),$.command("backup:start <resourceArn>","Start an on-demand backup").option("--region <region>","AWS region",{default:"us-east-1"}).option("--vault <name>","Backup vault name",{default:"Default"}).option("--role <arn>","IAM role ARN for backup").action(async(J,Y)=>{V("Start Backup Job");try{if(!Y.role){_("--role is required (IAM role ARN for AWS Backup)");return}let Q=await n$(Y.region);if(G(`Resource: ${J}`),G(`Vault: ${Y.vault}`),!await P(`
1693
+ Start backup?`,!0)){G("Operation cancelled");return}let U=new M("Starting backup job...");U.start();let Z=await Q.startBackupJob({BackupVaultName:Y.vault,ResourceArn:J,IamRoleArn:Y.role,IdempotencyToken:`cli-${Date.now()}`});U.succeed("Backup job started"),A(`
1694
+ Job ID: ${Z.BackupJobId}`),G("Use `cloud backup:jobs` to check status")}catch(Q){_(`Failed to start backup: ${Q.message}`),process.exit(1)}}),$.command("backup:restore <recoveryPointArn>","Start a restore job").option("--region <region>","AWS region",{default:"us-east-1"}).option("--role <arn>","IAM role ARN for restore").option("--metadata <json>","Restore metadata JSON").action(async(J,Y)=>{V("Start Restore Job");try{if(!Y.role){_("--role is required (IAM role ARN for AWS Backup)");return}let Q=await n$(Y.region);G(`Recovery Point: ${J}`);let W={};if(Y.metadata)W=JSON.parse(Y.metadata);if(N(`
1695
+ Restore will create new resources. Review carefully.`),!await P(`
1696
+ Start restore?`,!1)){G("Operation cancelled");return}let Z=new M("Starting restore job...");Z.start();let z=await Q.startRestoreJob({RecoveryPointArn:J,IamRoleArn:Y.role,Metadata:W,IdempotencyToken:`cli-${Date.now()}`});Z.succeed("Restore job started"),A(`
1697
+ Job ID: ${z.RestoreJobId}`),G("Use `cloud backup:restore-jobs` to check status")}catch(Q){_(`Failed to start restore: ${Q.message}`),process.exit(1)}}),$.command("backup:jobs","List recent backup jobs").option("--region <region>","AWS region").option("--state <state>","Filter by state (CREATED, PENDING, RUNNING, COMPLETED, FAILED)").action(async(J)=>{V("Backup Jobs");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=await n$(Q),U=new M("Fetching backup jobs...");U.start();let z=(await W.listBackupJobs({ByState:J.state,MaxResults:50})).BackupJobs||[];if(U.succeed(`Found ${z.length} job(s)`),z.length===0){G("No backup jobs found");return}x(["Job ID","Resource","State","Started","Size"],z.map((H)=>[H.BackupJobId?.substring(0,16)||"N/A",H.ResourceArn?.split(":").pop()||"N/A",H.State||"N/A",H.CreationDate?new Date(H.CreationDate).toLocaleString():"N/A",H.BackupSizeInBytes?b9(H.BackupSizeInBytes):"N/A"]))}catch(Y){_(`Failed to list backup jobs: ${Y.message}`),process.exit(1)}}),$.command("backup:restore-jobs","List recent restore jobs").option("--region <region>","AWS region").option("--status <status>","Filter by status").action(async(J)=>{V("Restore Jobs");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=await n$(Q),U=new M("Fetching restore jobs...");U.start();let z=(await W.listRestoreJobs({ByStatus:J.status,MaxResults:50})).RestoreJobs||[];if(U.succeed(`Found ${z.length} job(s)`),z.length===0){G("No restore jobs found");return}x(["Job ID","Resource","Status","Started","Completed"],z.map((H)=>[H.RestoreJobId?.substring(0,16)||"N/A",H.CreatedResourceArn?.split(":").pop()||"Pending",H.Status||"N/A",H.CreationDate?new Date(H.CreationDate).toLocaleString():"N/A",H.CompletionDate?new Date(H.CompletionDate).toLocaleString():"-"]))}catch(Y){_(`Failed to list restore jobs: ${Y.message}`),process.exit(1)}}),$.command("backup:schedule","Show backup schedule overview").option("--region <region>","AWS region").action(async(J)=>{V("Backup Schedule Overview");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",W=await n$(Q),U=new M("Fetching backup plans...");U.start();let z=(await W.listBackupPlans()).BackupPlansList||[];if(U.succeed(`Found ${z.length} backup plan(s)`),z.length===0){G("No backup plans configured");return}for(let H of z){G(`
1698
+ ${H.BackupPlanName}`),G("=".repeat(40));try{let B=(await W.getBackupPlan(H.BackupPlanId)).BackupPlan?.Rules||[];for(let X of B)if(G(` Rule: ${X.RuleName}`),G(` Schedule: ${X.ScheduleExpression}`),G(` Vault: ${X.TargetBackupVaultName}`),X.Lifecycle?.DeleteAfterDays)G(` Retention: ${X.Lifecycle.DeleteAfterDays} days`);let O=await W.listBackupSelections(H.BackupPlanId);if(O.BackupSelectionsList&&O.BackupSelectionsList.length>0)G(` Selections: ${O.BackupSelectionsList.length}`)}catch{G(" (Unable to load plan details)")}}}catch(Y){_(`Failed to get schedule: ${Y.message}`),process.exit(1)}})}function b9($){if($===0)return"0 B";let J=1024,Y=["B","KB","MB","GB","TB"],Q=Math.floor(Math.log($)/Math.log(J));return`${Number.parseFloat(($/J**Q).toFixed(2))} ${Y[Q]}`}function o6($){$.command("api:list","List all API Gateway APIs").option("--region <region>","AWS region").action(async(J)=>{V("API Gateway APIs");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1",{LambdaClient:W}=await Promise.resolve().then(() => (s6(),n6)),U=new W(Q),Z=new M("Fetching APIs...");Z.start();let{CloudFormationClient:z}=await Promise.resolve().then(() => (G0(),W6)),B=(await new z(Q).listStacks(["CREATE_COMPLETE","UPDATE_COMPLETE"])).StackSummaries.filter((O)=>O.StackName?.includes("api")||O.StackName?.includes("Api")||O.StackName?.includes("API"));if(Z.succeed("APIs listed"),G(`
1699
+ API-related CloudFormation stacks:`),B.length===0)G("No API Gateway stacks found"),G(`
1700
+ To create an API, you can:`),G(" 1. Use cloud.config.ts to define your API"),G(" 2. Deploy with `cloud deploy`");else x(["Stack Name","Status","Created"],B.map((O)=>[O.StackName||"N/A",O.StackStatus||"N/A",O.CreationTime?new Date(O.CreationTime).toLocaleDateString():"N/A"]));G("\nTip: Use AWS Console or `aws apigateway get-rest-apis` for detailed API listing")}catch(Y){_(`Failed to list APIs: ${Y.message}`),process.exit(1)}}),$.command("api:describe <apiId>","Show API Gateway API details").option("--region <region>","AWS region").action(async(J,Y)=>{V(`API: ${J}`);try{let Q=await g(),W=Y.region||Q.project.region||"us-east-1";G(`API ID: ${J}`),G(`Region: ${W}`),G(""),G("For detailed API information, use AWS CLI:"),G(` aws apigateway get-rest-api --rest-api-id ${J} --region ${W}`),G(` aws apigateway get-resources --rest-api-id ${J} --region ${W}`),G(` aws apigateway get-stages --rest-api-id ${J} --region ${W}`)}catch(Q){_(`Failed to describe API: ${Q.message}`),process.exit(1)}}),$.command("api:stages <apiId>","List API stages").option("--region <region>","AWS region").action(async(J,Y)=>{V(`API Stages: ${J}`);try{let Q=await g(),W=Y.region||Q.project.region||"us-east-1";G(`API ID: ${J}`),G(`Region: ${W}`),G(""),G("Common stages:"),G(" - prod (production)"),G(" - staging"),G(" - dev (development)"),G(""),G("For detailed stage information, use AWS CLI:"),G(` aws apigateway get-stages --rest-api-id ${J} --region ${W}`)}catch(Q){_(`Failed to list stages: ${Q.message}`),process.exit(1)}}),$.command("api:deploy <apiId>","Deploy API to a stage").option("--region <region>","AWS region",{default:"us-east-1"}).option("--stage <name>","Stage name",{default:"prod"}).option("--description <text>","Deployment description").action(async(J,Y)=>{V("Deploy API");try{if(G(`API ID: ${J}`),G(`Stage: ${Y.stage}`),!await P(`
1701
+ Deploy to this stage?`,!0)){G("Operation cancelled");return}if(G(""),G("To deploy an API Gateway API:"),G(" aws apigateway create-deployment \\"),G(` --rest-api-id ${J} \\`),G(` --stage-name ${Y.stage} \\`),G(` --region ${Y.region}`),Y.description)G(` --description "${Y.description}"`)}catch(Q){_(`Failed to deploy API: ${Q.message}`),process.exit(1)}}),$.command("api:domains","List custom domain names").option("--region <region>","AWS region").action(async(J)=>{V("API Gateway Custom Domains");try{let Y=await g(),Q=J.region||Y.project.region||"us-east-1";G(`Region: ${Q}`),G(""),G("To list custom domains, use AWS CLI:"),G(` aws apigateway get-domain-names --region ${Q}`),G(""),G("To create a custom domain:"),G(" 1. Request or import an SSL certificate in ACM"),G(" 2. Create a custom domain in API Gateway"),G(" 3. Create a base path mapping to your API"),G(" 4. Add a DNS record pointing to the distribution")}catch(Y){_(`Failed to list domains: ${Y.message}`),process.exit(1)}}),$.command("api:usage <apiId>","Show API usage statistics").option("--region <region>","AWS region").option("--stage <name>","Stage name",{default:"prod"}).option("--days <number>","Number of days to show",{default:"7"}).action(async(J,Y)=>{V("API Usage Statistics");try{let Q=await g(),W=Y.region||Q.project.region||"us-east-1";G(`API ID: ${J}`),G(`Stage: ${Y.stage}`),G(`Period: Last ${Y.days} days`),G("");let U=new Date,Z=new Date;Z.setDate(Z.getDate()-Number.parseInt(Y.days)),G("To view API metrics in CloudWatch:"),G(" aws cloudwatch get-metric-statistics \\"),G(" --namespace AWS/ApiGateway \\"),G(" --metric-name Count \\"),G(` --dimensions Name=ApiName,Value=${J} Name=Stage,Value=${Y.stage} \\`),G(` --start-time ${Z.toISOString()} \\`),G(` --end-time ${U.toISOString()} \\`),G(" --period 86400 \\"),G(" --statistics Sum \\"),G(` --region ${W}`),G(""),G("Available metrics:"),G(" - Count: Total API calls"),G(" - Latency: Response latency"),G(" - 4XXError: Client errors"),G(" - 5XXError: Server errors"),G(" - IntegrationLatency: Backend latency")}catch(Q){_(`Failed to get usage: ${Q.message}`),process.exit(1)}}),$.command("api:export <apiId>","Export API specification").option("--region <region>","AWS region",{default:"us-east-1"}).option("--stage <name>","Stage name",{default:"prod"}).option("--format <format>","Export format (oas30, swagger)",{default:"oas30"}).option("--output <file>","Output file path").action(async(J,Y)=>{V("Export API Specification");try{G(`API ID: ${J}`),G(`Stage: ${Y.stage}`),G(`Format: ${Y.format==="oas30"?"OpenAPI 3.0":"Swagger 2.0"}`),G("");let Q=Y.format==="oas30"?"oas30":"swagger";G("To export the API specification:"),G(" aws apigateway get-export \\"),G(` --rest-api-id ${J} \\`),G(` --stage-name ${Y.stage} \\`),G(` --export-type ${Q} \\`),G(" --accepts application/json \\"),G(` --region ${Y.region} \\`),G(` ${Y.output||"api-spec.json"}`)}catch(Q){_(`Failed to export API: ${Q.message}`),process.exit(1)}}),$.command("api:logs <apiId>","View API Gateway logs").option("--region <region>","AWS region").option("--stage <name>","Stage name",{default:"prod"}).option("--tail","Tail the logs").action(async(J,Y)=>{V("API Gateway Logs");try{let Q=await g(),W=Y.region||Q.project.region||"us-east-1",U=`API-Gateway-Execution-Logs_${J}/${Y.stage}`;if(G(`Log Group: ${U}`),G(""),G("To view logs:"),G(" aws logs filter-log-events \\"),G(` --log-group-name "${U}" \\`),G(` --region ${W}`),Y.tail)G(""),G("For real-time log tailing, use:"),G(` aws logs tail "${U}" --follow --region ${W}`);G(""),G("Note: Ensure logging is enabled for the API stage."),G("You can enable it in the stage settings.")}catch(Q){_(`Failed to get logs: ${Q.message}`),process.exit(1)}}),$.command("api:test <apiId> <path>","Test an API endpoint").option("--region <region>","AWS region").option("--stage <name>","Stage name",{default:"prod"}).option("--method <method>","HTTP method",{default:"GET"}).option("--body <json>","Request body (JSON)").option("--header <header>","Request header (can be specified multiple times)").action(async(J,Y,Q)=>{V("Test API Endpoint");try{let W=await g(),U=Q.region||W.project.region||"us-east-1",Z=`https://${J}.execute-api.${U}.amazonaws.com/${Q.stage}${Y.startsWith("/")?Y:`/${Y}`}`;G(`URL: ${Z}`),G(`Method: ${Q.method}`);let z={"Content-Type":"application/json"};if(Q.header){let q=Array.isArray(Q.header)?Q.header:[Q.header];for(let E of q){let[F,...w]=E.split(":");z[F.trim()]=w.join(":").trim()}}G("Headers:");for(let[q,E]of Object.entries(z))G(` ${q}: ${E}`);if(Q.body)G(`Body: ${Q.body}`);if(!await P(`
1702
+ Send request?`,!0)){G("Operation cancelled");return}let K=new M("Sending request...");K.start();let B=Date.now(),O=await fetch(Z,{method:Q.method,headers:z,body:Q.body}),X=Date.now()-B,j=await O.text();K.succeed(`Response received (${X}ms)`),G(`
1703
+ Status: ${O.status} ${O.statusText}`),G(`
1704
+ Response Headers:`),O.headers.forEach((q,E)=>{G(` ${E}: ${q}`)}),G(`
1705
+ Response Body:`);try{let q=JSON.parse(j);console.log(JSON.stringify(q,null,2))}catch{console.log(j)}}catch(W){_(`Failed to test API: ${W.message}`),process.exit(1)}})}function e6($){$.command("tunnel","Start a local tunnel to expose your local server").option("--port <number>","Local port to expose",{default:"3000"}).option("--subdomain <name>","Custom subdomain (if available)").option("--host <hostname>","Local hostname",{default:"localhost"}).option("--server <url>","Tunnel server URL",{default:"localtunnel.dev"}).option("--verbose","Enable verbose logging").action(async(J)=>{V("Local Tunnel");let Y=Number.parseInt(J.port);if(G(`Local server: ${J.host}:${Y}`),G(`Tunnel server: ${J.server}`),J.subdomain)G(`Requested subdomain: ${J.subdomain}`);let Q=new M("Connecting to tunnel server...");Q.start();try{let W;try{W=(await import("localtunnels")).TunnelClient}catch{Q.fail("localtunnels package not found"),G(`
1706
+ To use tunnels, install the localtunnels package:`),G(" bun add localtunnels"),G(`
1707
+ Or use the standalone CLI:`),G(" bunx localtunnels --port 3000");return}let U=J.server.replace(/^(wss?|https?):\/\//,""),Z=J.server.startsWith("wss://")||J.server.startsWith("https://")||U==="localtunnel.dev",z=new W({localPort:Y,localHost:J.host,subdomain:J.subdomain,host:U,port:Z?443:80,secure:Z,verbose:J.verbose});z.on("connected",(K)=>{Q.succeed("Connected!"),A(`
1708
+ Your tunnel URL: ${K.url}`),G(`Subdomain: ${K.subdomain}`),G(`
1709
+ Forwarding: ${K.url} -> http://${J.host}:${Y}`),G(`
1710
+ Press Ctrl+C to stop the tunnel`)}),z.on("request",(K)=>{if(J.verbose)G(`→ ${K.method} ${K.url}`)}),z.on("response",(K)=>{if(J.verbose)G(`← ${K.status} (${K.size} bytes${K.duration?`, ${K.duration}ms`:""})`)}),z.on("reconnecting",(K)=>{G(`Reconnecting... (attempt ${K.attempt}/${K.maxAttempts})`)}),z.on("error",(K)=>{_(`Tunnel error: ${K.message}`)}),z.on("close",()=>{G(`
1711
+ Tunnel closed`)});let H=()=>{G(`
1712
+ Shutting down tunnel...`),z.disconnect(),process.exit(0)};process.on("SIGINT",H),process.on("SIGTERM",H),await z.connect(),await new Promise(()=>{})}catch(W){Q.fail("Failed to connect"),_(`Error: ${W.message}`),process.exit(1)}}),$.command("tunnel:status","Check tunnel server status").option("--server <url>","Tunnel server URL",{default:"https://localtunnel.dev"}).action(async(J)=>{V("Tunnel Server Status");let Y=new M("Checking server status...");Y.start();try{let Q=J.server.startsWith("http")?J.server:`https://${J.server}`,W=await fetch(`${Q}/status`,{method:"GET",headers:{Accept:"application/json"}});if(W.ok){let U=await W.json();if(Y.succeed("Server is online"),G(`
1713
+ Server: ${J.server}`),G(`Status: ${U.status||"operational"}`),U.version)G(`Version: ${U.version}`);if(U.connections!==void 0)G(`Active connections: ${U.connections}`);if(U.uptime)G(`Uptime: ${U.uptime}`);if(U.activeSubdomains?.length)G(`Active subdomains: ${U.activeSubdomains.join(", ")}`)}else Y.fail(`Server returned status ${W.status}`)}catch(Q){Y.fail("Failed to check server status"),_(`Error: ${Q.message}`),G(`
1714
+ The tunnel server may be offline or unreachable.`)}}),$.command("tunnel:info","Show tunnel configuration and setup info").action(async()=>{V("Local Tunnel Information"),G("ts-cloud uses localtunnels for secure tunnel connections."),G(""),G("Default server: localtunnel.dev"),G(""),G("Usage:"),G(" cloud tunnel --port 3000 # Expose port 3000"),G(" cloud tunnel --port 8080 --subdomain myapp"),G(""),G("Features:"),G(" - Secure WebSocket-based tunnels"),G(" - Custom subdomains (when available)"),G(" - Automatic reconnection"),G(" - Request logging"),G(" - Binary data support"),G(""),G("Self-hosted tunnel server:"),G(" You can run your own tunnel server using localtunnels."),G(" See: https://github.com/stacksjs/localtunnels"),G(""),G("Environment variables:"),G(" TUNNEL_SERVER - Custom tunnel server URL"),G(" TUNNEL_SUBDOMAIN - Default subdomain to request")}),$.command("tunnel:deploy","Deploy tunnel infrastructure to AWS").option("--region <region>","AWS region",{default:"us-east-1"}).option("--prefix <prefix>","Resource name prefix",{default:"localtunnel"}).option("--verbose","Enable verbose logging").action(async(J)=>{if(V("Deploy Tunnel Infrastructure"),G(`Region: ${J.region}`),G(`Prefix: ${J.prefix}`),G(""),G("This will deploy:"),G(" - DynamoDB tables for connection tracking"),G(" - Lambda functions for handling requests"),G(" - Lambda Function URLs for public access"),G(""),!await P("Deploy tunnel infrastructure?",!1)){G("Operation cancelled");return}let Q=new M("Deploying infrastructure...");Q.start();try{let W;try{W=(await import("localtunnels/cloud")).deployTunnelInfrastructure}catch{Q.fail("localtunnels package not found"),G(`
1715
+ To deploy tunnel infrastructure, install localtunnels:`),G(" bun add localtunnels"),G(`
1716
+ Or deploy using the localtunnels CLI directly:`),G(" bunx localtunnels deploy --region us-east-1");return}let U=await W({region:J.region,prefix:J.prefix,verbose:J.verbose});if(Q.succeed("Deployment complete!"),G(""),G("Resources created:"),G(" DynamoDB Tables:"),G(` - ${U.connectionsTable}`),G(` - ${U.responsesTable}`),G(""),G(" Lambda Functions:"),G(` - ${U.functions.http}`),G(` - ${U.functions.message}`),G(""),U.httpUrl||U.wsUrl){if(G("Endpoints:"),U.httpUrl)G(` HTTP URL: ${U.httpUrl}`);if(U.wsUrl)G(` WebSocket URL: ${U.wsUrl}`)}}catch(W){if(Q.fail("Deployment failed"),_(`Error: ${W.message}`),J.verbose)console.error(W.stack);process.exit(1)}}),$.command("tunnel:destroy","Destroy tunnel infrastructure from AWS").option("--region <region>","AWS region",{default:"us-east-1"}).option("--prefix <prefix>","Resource name prefix",{default:"localtunnel"}).option("--verbose","Enable verbose logging").action(async(J)=>{if(V("Destroy Tunnel Infrastructure"),G(`Region: ${J.region}`),G(`Prefix: ${J.prefix}`),G(""),N("This will permanently delete:"),N(" - All DynamoDB tables and data"),N(" - All Lambda functions"),N(" - All IAM roles and policies"),G(""),!await P("Are you sure you want to destroy this infrastructure?",!1)){G("Operation cancelled");return}let Q=new M("Destroying infrastructure...");Q.start();try{let W;try{W=(await import("localtunnels/cloud")).destroyTunnelInfrastructure}catch{Q.fail("localtunnels package not found"),G(`
1717
+ To destroy tunnel infrastructure, install localtunnels:`),G(" bun add localtunnels"),G(`
1718
+ Or destroy using the localtunnels CLI directly:`),G(" bunx localtunnels destroy --region us-east-1");return}await W({region:J.region,prefix:J.prefix,verbose:J.verbose}),Q.succeed("Infrastructure destroyed!")}catch(W){if(Q.fail("Destruction failed"),_(`Error: ${W.message}`),J.verbose)console.error(W.stack);process.exit(1)}}),$.command("tunnel:logs","View tunnel server logs").option("--region <region>","AWS region",{default:"us-east-1"}).option("--prefix <prefix>","Resource name prefix",{default:"localtunnel"}).option("--tail","Tail the logs").action(async(J)=>{V("Tunnel Server Logs"),G("Tunnel server log groups:"),G(` - /aws/lambda/${J.prefix}-connect`),G(` - /aws/lambda/${J.prefix}-disconnect`),G(` - /aws/lambda/${J.prefix}-message`),G(` - /aws/lambda/${J.prefix}-http`),G(""),G("To view logs:"),G(` aws logs tail /aws/lambda/${J.prefix}-http --region ${J.region}${J.tail?" --follow":""}`),G(""),G("Or use CloudWatch Insights:"),G(" 1. Go to CloudWatch > Logs Insights"),G(" 2. Select the tunnel log groups"),G(" 3. Run queries like:"),G(" fields @timestamp, @message | filter @message like /error/i")}),$.command("tunnel:test <url>","Test a tunnel connection").action(async(J)=>{V("Test Tunnel Connection");let Y=new M(`Testing ${J}...`);Y.start();try{let Q=Date.now(),W=await fetch(J,{method:"GET",headers:{"User-Agent":"ts-cloud-tunnel-test"}}),U=Date.now()-Q;Y.succeed(`Connected in ${U}ms`),G(`
1719
+ Status: ${W.status} ${W.statusText}`),G(`
1720
+ Response headers:`),W.headers.forEach((z,H)=>{G(` ${H}: ${z}`)});let Z=await W.text();if(Z.length>0){if(G(`
1721
+ Response body (first 500 chars):`),console.log(Z.substring(0,500)),Z.length>500)G(`... (${Z.length-500} more characters)`)}}catch(Q){Y.fail("Connection failed"),_(`Error: ${Q.message}`)}}),$.command("tunnel:server","Start a self-hosted tunnel server").option("--port <number>","Port to listen on",{default:"3000"}).option("--host <hostname>","Host to bind to",{default:"0.0.0.0"}).option("--domain <domain>","Domain for tunnel URLs",{default:"localhost"}).option("--verbose","Enable verbose logging").action(async(J)=>{V("Local Tunnel Server");let Y=Number.parseInt(J.port);G(`Listening on: ${J.host}:${Y}`),G(`Domain: ${J.domain}`),G("");let Q=new M("Starting tunnel server...");Q.start();try{let W;try{W=(await import("localtunnels")).TunnelServer}catch{Q.fail("localtunnels package not found"),G(`
1722
+ To run a tunnel server, install localtunnels:`),G(" bun add localtunnels"),G(`
1723
+ Or use the standalone CLI:`),G(" bunx localtunnels server --port 3000");return}let U=new W({port:Y,host:J.host,verbose:J.verbose});U.on("connection",(z)=>{G(`+ Client connected: ${z.subdomain} (total: ${z.totalConnections})`)}),U.on("disconnection",(z)=>{G(`- Client disconnected: ${z.subdomain}`)});let Z=()=>{G(`
1724
+ Shutting down server...`),U.stop(),process.exit(0)};process.on("SIGINT",Z),process.on("SIGTERM",Z),await U.start(),Q.succeed("Server running!"),G(""),G(`WebSocket URL: ws://${J.host==="0.0.0.0"?"localhost":J.host}:${Y}`),G(`HTTP URL: http://${J.host==="0.0.0.0"?"localhost":J.host}:${Y}`),G(""),G("Clients can connect with:"),G(` cloud tunnel --port 3000 --server ${J.host==="0.0.0.0"?"localhost":J.host}:${Y}`),G(""),G("Press Ctrl+C to stop the server"),await new Promise(()=>{})}catch(W){Q.fail("Failed to start server"),_(`Error: ${W.message}`),process.exit(1)}})}var p=new o1("cloud");p.option("--env <environment>","Environment (production, staging, development)").option("--region <region>","AWS Region").option("--profile <profile>","AWS CLI Profile").option("--verbose","Enable verbose logging").option("--dry-run","Show what would be done without making changes");KJ(p);bJ(p);Z6(p);k6(p);I6(p);z6(p);G6(p);H6(p);b6(p);y6(p);v6(p);g6(p);d6(p);K6(p);q6(p);B6(p);O6(p);i6(p);m6(p);c6(p);l6(p);p6(p);X6(p);j6(p);r6(p);a6(p);t6(p);o6(p);V6(p);M6(p);E6(p);w6(p);T6(p);h6(p);e6(p);x6(p,JJ);p.version(JJ);p.help();p.parse();