@stacksjs/ts-cloud 0.9.4 → 0.11.0

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 (252) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/chunk-0djsffn6.js +1 -0
  3. package/dist/bin/chunk-0t3sev1j.js +1 -0
  4. package/dist/bin/chunk-0y89hs67.js +6 -0
  5. package/dist/bin/chunk-21gggxvf.js +2 -0
  6. package/dist/bin/chunk-26cj89s6.js +1 -0
  7. package/dist/bin/chunk-35xstvnq.js +1 -0
  8. package/dist/bin/chunk-41yqpdv7.js +2 -0
  9. package/dist/bin/chunk-4a85nk2q.js +92 -0
  10. package/dist/bin/{chunk-rxcvf10f.js → chunk-4a97kbk1.js} +129 -129
  11. package/dist/bin/chunk-4kbhbfq8.js +34 -0
  12. package/dist/bin/chunk-4vdv41nh.js +70 -0
  13. package/dist/bin/chunk-67jsyn0g.js +111 -0
  14. package/dist/bin/chunk-6tct7e89.js +1 -0
  15. package/dist/bin/chunk-6vjrts39.js +1 -0
  16. package/dist/bin/chunk-7v5ff3vc.js +1 -0
  17. package/dist/bin/chunk-80nra92y.js +1 -0
  18. package/dist/bin/chunk-9mydnqr6.js +2 -0
  19. package/dist/bin/chunk-9rsn48qg.js +3 -0
  20. package/dist/bin/chunk-a2t1e5yb.js +1 -0
  21. package/dist/bin/chunk-akbfefwq.js +1 -0
  22. package/dist/bin/chunk-b704nznp.js +1 -0
  23. package/dist/bin/chunk-c1j9v7ee.js +2 -0
  24. package/dist/bin/chunk-cjz36ths.js +1 -0
  25. package/dist/bin/chunk-cxd5cevb.js +2 -0
  26. package/dist/bin/chunk-dbv8w56s.js +50 -0
  27. package/dist/bin/chunk-dxchg0g1.js +1 -0
  28. package/dist/bin/{chunk-tx0tqq2k.js → chunk-e1bfd1yv.js} +6 -6
  29. package/dist/bin/chunk-fpcghdr3.js +585 -0
  30. package/dist/bin/chunk-ftse39wf.js +9 -0
  31. package/dist/bin/chunk-g0ewbkbq.js +1 -0
  32. package/dist/bin/chunk-gskbezam.js +141 -0
  33. package/dist/bin/chunk-gvs85t2j.js +1 -0
  34. package/dist/bin/chunk-hej39dwr.js +2 -0
  35. package/dist/bin/chunk-jce28gnz.js +2 -0
  36. package/dist/bin/chunk-kbtrr0c3.js +1 -0
  37. package/dist/bin/chunk-khrye4x9.js +1 -0
  38. package/dist/bin/{chunk-mh0kdzqp.js → chunk-ks4ewy1s.js} +1 -1
  39. package/dist/bin/chunk-mbnwt3r5.js +2 -0
  40. package/dist/bin/chunk-md2k3n21.js +37 -0
  41. package/dist/bin/chunk-memfxrcn.js +1 -0
  42. package/dist/bin/chunk-mwgxyc0z.js +44 -0
  43. package/dist/bin/chunk-neampxq1.js +4 -0
  44. package/dist/bin/chunk-nkpf91d3.js +1 -0
  45. package/dist/bin/chunk-nmkm1f68.js +2 -0
  46. package/dist/bin/chunk-nyc2jxd8.js +2 -0
  47. package/dist/bin/chunk-pqr8jqnd.js +1 -0
  48. package/dist/bin/chunk-q182t9ba.js +3 -0
  49. package/dist/bin/chunk-r6x7beew.js +60 -0
  50. package/dist/bin/chunk-rfqk5xym.js +1 -0
  51. package/dist/bin/{chunk-etrb03mt.js → chunk-ww770qpn.js} +30 -30
  52. package/dist/bin/chunk-wy20ztb6.js +1 -0
  53. package/dist/bin/chunk-wzepfqf4.js +512 -0
  54. package/dist/bin/chunk-xcqmwphz.js +1 -0
  55. package/dist/bin/chunk-xev7qr2h.js +3 -0
  56. package/dist/bin/chunk-y3rm37z1.js +6 -0
  57. package/dist/bin/chunk-zejwh9cy.js +6 -0
  58. package/dist/bin/chunk-zwwnt4x1.js +1 -0
  59. package/dist/bin/cli.js +431 -418
  60. package/dist/bin/dashboard-server.js +1 -1
  61. package/dist/{chunk-dskvqt67.js → chunk-0hj552t7.js} +127 -127
  62. package/dist/chunk-1ypkh8g6.js +5 -0
  63. package/dist/chunk-2m09t0c0.js +60 -0
  64. package/dist/chunk-7fkyfh65.js +1 -0
  65. package/dist/chunk-7xpxzbkr.js +442 -0
  66. package/dist/chunk-8e0az001.js +2 -0
  67. package/dist/chunk-b10cbk8z.js +44 -0
  68. package/dist/chunk-gk58959n.js +6 -0
  69. package/dist/chunk-h1rc94df.js +114 -0
  70. package/dist/chunk-hbhxk5a0.js +4 -0
  71. package/dist/chunk-hz7k9ymh.js +1 -0
  72. package/dist/chunk-kj7gzdj6.js +1 -0
  73. package/dist/chunk-ky5c6t5y.js +2 -0
  74. package/dist/chunk-mch30cyc.js +1 -0
  75. package/dist/chunk-n04a3bgf.js +1 -0
  76. package/dist/chunk-nnqxmh7f.js +34 -0
  77. package/dist/chunk-p6vszgc2.js +92 -0
  78. package/dist/chunk-q2njk4hx.js +141 -0
  79. package/dist/chunk-qjk1v1gs.js +50 -0
  80. package/dist/chunk-qtp90j44.js +2 -0
  81. package/dist/chunk-r5natbed.js +37 -0
  82. package/dist/chunk-rcxq9aaa.js +704 -0
  83. package/dist/{chunk-gahsdmxf.js → chunk-s3rpd72x.js} +52 -52
  84. package/dist/{chunk-xt3s24vr.js → chunk-spx89gaw.js} +1 -1
  85. package/dist/chunk-t0kh8haz.js +2 -0
  86. package/dist/chunk-vz95qy3n.js +1 -0
  87. package/dist/deploy/attach-credentials.d.ts +4 -8
  88. package/dist/deploy/index.js +1 -1
  89. package/dist/dns/cloudflare.d.ts +27 -0
  90. package/dist/dns/godaddy.d.ts +18 -1
  91. package/dist/dns/index.d.ts +2 -0
  92. package/dist/dns/index.js +1 -1
  93. package/dist/dns/zone-migration.d.ts +92 -0
  94. package/dist/dns/zone-migration.test.d.ts +1 -0
  95. package/dist/drivers/hetzner/driver.d.ts +8 -1
  96. package/dist/drivers/index.js +1 -1
  97. package/dist/drivers/shared/app-updates.d.ts +36 -0
  98. package/dist/drivers/shared/compute-provision.d.ts +14 -2
  99. package/dist/drivers/shared/db-provision.d.ts +3 -2
  100. package/dist/drivers/shared/mail-provision.d.ts +116 -0
  101. package/dist/drivers/shared/mail-provision.test.d.ts +1 -0
  102. package/dist/drivers/shared/managed-services-probe.d.ts +47 -0
  103. package/dist/drivers/shared/managed-services-probe.test.d.ts +1 -0
  104. package/dist/drivers/shared/package-manager.d.ts +1 -0
  105. package/dist/drivers/shared/remote-failure.d.ts +21 -0
  106. package/dist/drivers/shared/remote-failure.test.d.ts +1 -0
  107. package/dist/drivers/shared/sqlite-shared-path.d.ts +50 -0
  108. package/dist/drivers/shared/sqlite-shared-path.test.d.ts +1 -0
  109. package/dist/index.d.ts +2 -0
  110. package/dist/index.js +92 -89
  111. package/dist/operations/plan.d.ts +136 -0
  112. package/dist/operations/plan.test.d.ts +1 -0
  113. package/dist/operations/server-rename.d.ts +84 -0
  114. package/dist/operations/server-rename.test.d.ts +1 -0
  115. package/dist/operations/site-move.d.ts +263 -0
  116. package/dist/operations/site-move.test.d.ts +1 -0
  117. package/dist/protection/index.js +1 -1
  118. package/dist/push/index.js +1 -1
  119. package/dist/spend/index.js +1 -1
  120. package/dist/ui/404.html +1 -1
  121. package/dist/ui/accept-invitation.html +1 -1
  122. package/dist/ui/access-denied.html +1 -1
  123. package/dist/ui/account/automation.html +6 -6
  124. package/dist/ui/account/security.html +2 -2
  125. package/dist/ui/applications/compose.html +6 -6
  126. package/dist/ui/applications/new.html +2 -2
  127. package/dist/ui/data/backups.html +80 -80
  128. package/dist/ui/data/services.html +78 -78
  129. package/dist/ui/data/volumes.html +50 -50
  130. package/dist/ui/index.html +50 -50
  131. package/dist/ui/infrastructure/topology.html +118 -118
  132. package/dist/ui/integrations.html +2 -2
  133. package/dist/ui/operations/alerts.html +48 -48
  134. package/dist/ui/operations/configuration.html +6 -6
  135. package/dist/ui/operations/jobs.html +75 -75
  136. package/dist/ui/operations/maintenance.html +6 -6
  137. package/dist/ui/operations/observability.html +82 -82
  138. package/dist/ui/operations/previews.html +6 -6
  139. package/dist/ui/operations/queue.html +6 -6
  140. package/dist/ui/operations/regions.html +6 -6
  141. package/dist/ui/operations/releases.html +6 -6
  142. package/dist/ui/operations/spend.html +54 -54
  143. package/dist/ui/operations/workloads.html +104 -104
  144. package/dist/ui/security.html +2 -2
  145. package/dist/ui/server/actions.html +56 -56
  146. package/dist/ui/server/activity.html +1 -1
  147. package/dist/ui/server/capacity.html +6 -6
  148. package/dist/ui/server/database.html +106 -106
  149. package/dist/ui/server/deployments.html +50 -50
  150. package/dist/ui/server/diagnostics.html +2 -2
  151. package/dist/ui/server/firewall.html +76 -76
  152. package/dist/ui/server/fleet.html +34 -34
  153. package/dist/ui/server/logs.html +24 -24
  154. package/dist/ui/server/metrics.html +112 -112
  155. package/dist/ui/server/security.html +2 -2
  156. package/dist/ui/server/services.html +27 -27
  157. package/dist/ui/server/sites.html +120 -120
  158. package/dist/ui/server/ssh-keys.html +52 -52
  159. package/dist/ui/server/team.html +144 -144
  160. package/dist/ui/server/terminal.html +15 -15
  161. package/dist/ui/serverless/alarms.html +52 -52
  162. package/dist/ui/serverless/assets.html +27 -27
  163. package/dist/ui/serverless/cost.html +2 -2
  164. package/dist/ui/serverless/data.html +36 -36
  165. package/dist/ui/serverless/deployments.html +27 -27
  166. package/dist/ui/serverless/firewall.html +1 -1
  167. package/dist/ui/serverless/functions.html +40 -40
  168. package/dist/ui/serverless/logs.html +24 -24
  169. package/dist/ui/serverless/metrics.html +2 -2
  170. package/dist/ui/serverless/queues.html +48 -48
  171. package/dist/ui/serverless/secrets.html +51 -51
  172. package/dist/ui/serverless/traces.html +6 -6
  173. package/dist/ui/serverless.html +53 -53
  174. package/dist/ui-src/src/charts.ts +17499 -12662
  175. package/dist/ui-src/src/topology.ts +2 -2
  176. package/package.json +3 -3
  177. package/dist/bin/chunk-00kg80qg.js +0 -1
  178. package/dist/bin/chunk-09nwf2gy.js +0 -34
  179. package/dist/bin/chunk-1k5kszjp.js +0 -111
  180. package/dist/bin/chunk-21e0mavm.js +0 -1
  181. package/dist/bin/chunk-271gk1n2.js +0 -6
  182. package/dist/bin/chunk-2empps47.js +0 -2
  183. package/dist/bin/chunk-38pq971s.js +0 -2
  184. package/dist/bin/chunk-3gykfyq4.js +0 -37
  185. package/dist/bin/chunk-3vqfexc4.js +0 -70
  186. package/dist/bin/chunk-4vrqm9h0.js +0 -2
  187. package/dist/bin/chunk-598yf4bs.js +0 -1
  188. package/dist/bin/chunk-5ectjq0b.js +0 -1
  189. package/dist/bin/chunk-5erkxpt7.js +0 -512
  190. package/dist/bin/chunk-5mrtzemj.js +0 -1
  191. package/dist/bin/chunk-5n9fmabb.js +0 -1
  192. package/dist/bin/chunk-9knpg30y.js +0 -1
  193. package/dist/bin/chunk-9pvsff8g.js +0 -1
  194. package/dist/bin/chunk-ax9mr6wm.js +0 -44
  195. package/dist/bin/chunk-axhnkn5g.js +0 -2
  196. package/dist/bin/chunk-c1vcdgvr.js +0 -1
  197. package/dist/bin/chunk-ctd2vg9w.js +0 -2
  198. package/dist/bin/chunk-dbgffky8.js +0 -1
  199. package/dist/bin/chunk-ddk4rt4j.js +0 -6
  200. package/dist/bin/chunk-dwr30vbv.js +0 -1
  201. package/dist/bin/chunk-e0rkrq70.js +0 -1
  202. package/dist/bin/chunk-e3xrwh9z.js +0 -1
  203. package/dist/bin/chunk-fhc6ntvd.js +0 -2
  204. package/dist/bin/chunk-fpm59y25.js +0 -6
  205. package/dist/bin/chunk-fvbxvq6b.js +0 -1
  206. package/dist/bin/chunk-fy8j3y8p.js +0 -92
  207. package/dist/bin/chunk-fz21b57w.js +0 -1
  208. package/dist/bin/chunk-gavvf0pg.js +0 -141
  209. package/dist/bin/chunk-ggn7ax8p.js +0 -4
  210. package/dist/bin/chunk-gpe2prkm.js +0 -1
  211. package/dist/bin/chunk-h5pa5men.js +0 -2
  212. package/dist/bin/chunk-hm08xdxf.js +0 -2
  213. package/dist/bin/chunk-hzgz13nf.js +0 -1
  214. package/dist/bin/chunk-j703btc5.js +0 -50
  215. package/dist/bin/chunk-k9t9wvms.js +0 -1
  216. package/dist/bin/chunk-m669wtgr.js +0 -1
  217. package/dist/bin/chunk-m7dgskt1.js +0 -1
  218. package/dist/bin/chunk-mr0atd2s.js +0 -2
  219. package/dist/bin/chunk-mz0wbbsj.js +0 -3
  220. package/dist/bin/chunk-ngcyftm2.js +0 -1
  221. package/dist/bin/chunk-p66ptpmr.js +0 -2
  222. package/dist/bin/chunk-qk9qgepa.js +0 -1
  223. package/dist/bin/chunk-rytk89az.js +0 -60
  224. package/dist/bin/chunk-tga3hhwk.js +0 -6
  225. package/dist/bin/chunk-vek8a0w6.js +0 -1
  226. package/dist/bin/chunk-vm3q5gf2.js +0 -3
  227. package/dist/bin/chunk-y7s5r8y6.js +0 -3
  228. package/dist/bin/chunk-yv9sth30.js +0 -1
  229. package/dist/bin/chunk-zmegvjp8.js +0 -581
  230. package/dist/chunk-0ccta6z6.js +0 -6
  231. package/dist/chunk-0k1cs6pp.js +0 -1
  232. package/dist/chunk-1egjn203.js +0 -704
  233. package/dist/chunk-2wx29qga.js +0 -5
  234. package/dist/chunk-5m5rqmv7.js +0 -1
  235. package/dist/chunk-8ea5022g.js +0 -114
  236. package/dist/chunk-8xqn3c0w.js +0 -2
  237. package/dist/chunk-b4esxhmw.js +0 -2
  238. package/dist/chunk-b8e5wzwn.js +0 -44
  239. package/dist/chunk-bggt4n6e.js +0 -2
  240. package/dist/chunk-cwkg37rs.js +0 -37
  241. package/dist/chunk-gnv3r2jg.js +0 -1
  242. package/dist/chunk-hg3c48cp.js +0 -34
  243. package/dist/chunk-m5azeva3.js +0 -2
  244. package/dist/chunk-r3qf56b3.js +0 -92
  245. package/dist/chunk-sdqa9ghv.js +0 -141
  246. package/dist/chunk-svrvvcm7.js +0 -1
  247. package/dist/chunk-v0p3hpc3.js +0 -60
  248. package/dist/chunk-wdzjbecg.js +0 -50
  249. package/dist/chunk-ww8k3g7j.js +0 -1
  250. package/dist/chunk-xmqfc62w.js +0 -1
  251. package/dist/chunk-xrebj679.js +0 -435
  252. package/dist/chunk-y21zk0pn.js +0 -4
@@ -1,2 +0,0 @@
1
- import{Pf as F}from"./chunk-wdzjbecg.js";import{Th as h}from"./chunk-0ccta6z6.js";var A=new Set(["A","AAAA","CNAME"]);function z(Q,J=""){return Q===408||Q===409||Q===425||Q===429||Q>=500||/rate limit|temporar|timed? ?out|try again/i.test(J)}async function k(Q,J){let $=J?.headers.get("retry-after"),H=$===null||$===void 0?void 0:Number($)*1000,Y=Number.isFinite(H)?Math.max(0,H):Math.min(1000*2**(Q-1),30000);await new Promise((X)=>setTimeout(X,Y))}class U{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(Q,J,$=15000){this.apiKey=Q,this.secretKey=J,this.requestTimeoutMs=$}async request(Q,J={}){let $;for(let H=1;H<=8;H+=1){let Y,X=new AbortController,j=setTimeout(()=>{X.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{Y=await fetch(`https://api.porkbun.com/api/json/v3${Q}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...J}),signal:X.signal})}catch(O){if($=O,H===8)throw O;await k(H);continue}finally{clearTimeout(j)}if(!Y.ok){if($=Error(`Porkbun API error: ${Y.status} ${Y.statusText}`),!z(Y.status)||H===8)throw $;await k(H,Y);continue}let G=await Y.json();if(G.status==="ERROR"){if($=Error(`Porkbun API error: ${G.message||"Unknown error"}`),!z(0,G.message)||H===8)throw $;await k(H,Y);continue}return G}throw $}getSubdomain(Q,J){let $=Q.replace(/\.$/,""),H=J.replace(/\.$/,"");if($===H)return"";if($.endsWith(`.${H}`))return $.slice(0,-(H.length+1));return $}getRootDomain(Q){let J=Q.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return Q}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(Q,J){if(!U.ADDRESS_TYPES.has(J.type))return[];let $=this.getRootDomain(Q),H=this.getSubdomain(J.name,$),Y=await this.listRecords(Q);if(!Y.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${Y.message??"unknown provider error"}`];let X=[];for(let j of Y.records){if(j.type!=="ALIAS"&&j.type!=="CNAME")continue;if(this.getSubdomain(j.name,$)!==H)continue;let G=await this.deleteRecord(Q,j);if(!G.success)X.push(`could not remove conflicting ${j.type} on ${j.name}: ${G.message??"unknown provider error"}`)}return X}async addressRecordExists(Q,J){let $=this.getRootDomain(Q),H=this.getSubdomain(J.name,$),Y=await this.listRecords(Q);if(!Y.success)return!0;return Y.records.some((X)=>X.type===J.type&&this.getSubdomain(X.name,$)===H&&X.content===J.content)}async createRecord(Q,J){try{let $=this.getRootDomain(Q),H=this.getSubdomain(J.name,$),Y={type:J.type,content:J.content,ttl:String(J.ttl||600)};if(H)Y.name=H;if((J.type==="MX"||J.type==="SRV")&&J.priority!==void 0)Y.prio=String(J.priority);if(J.type==="SRV"&&J.weight!==void 0&&J.port!==void 0)Y.content=`${J.weight} ${J.port} ${J.content}`;let X=await this.clearConflictingAliases(Q,J),j=await this.request(`/dns/create/${$}`,Y);if(U.ADDRESS_TYPES.has(J.type)&&!await this.addressRecordExists(Q,J))return{success:!1,message:`Porkbun reported success but no ${J.type} record for ${J.name} exists${X.length>0?` (${X.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:j.id?.toString(),message:"Record created successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async upsertRecord(Q,J){try{let $=this.getRootDomain(Q),H=this.getSubdomain(J.name,$),Y=await this.listRecords(Q,J.type);if(Y.success){let X=Y.records.find((j)=>{return this.getSubdomain(j.name,$)===H&&j.type===J.type});if(X?.id){let j={type:J.type,content:J.content,ttl:String(J.ttl||600)};if(H)j.name=H;if((J.type==="MX"||J.type==="SRV")&&J.priority!==void 0)j.prio=String(J.priority);if(J.type==="SRV"&&J.weight!==void 0&&J.port!==void 0)j.content=`${J.weight} ${J.port} ${J.content}`;return await this.request(`/dns/edit/${$}/${X.id}`,j),{success:!0,id:X.id,message:"Record updated successfully"}}}return this.createRecord(Q,J)}catch($){return this.createRecord(Q,J)}}async deleteRecord(Q,J){try{let $=this.getRootDomain(Q);if("id"in J&&J.id)return await this.request(`/dns/delete/${$}/${J.id}`),{success:!0,message:"Record deleted successfully"};let H=this.getSubdomain(J.name,$),Y=await this.listRecords(Q);if(!Y.success)return{success:!1,message:"Failed to list records"};let X=Y.records.find((j)=>{return this.getSubdomain(j.name,$)===H&&j.type===J.type&&j.content===J.content});if(!X?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${$}/${X.id}`),{success:!0,message:"Record deleted successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async listRecords(Q,J){try{let $=this.getRootDomain(Q),H=`/dns/retrieve/${$}`;if(J)H=`/dns/retrieveByNameType/${$}/${J}`;return{success:!0,records:((await this.request(H)).records||[]).map((j)=>({id:j.id,name:j.name||$,type:j.type,content:j.content,ttl:Number.parseInt(j.ttl,10),priority:j.prio?Number.parseInt(j.prio,10):void 0}))}}catch($){return{success:!1,records:[],message:$ instanceof Error?$.message:"Unknown error"}}}async canManageDomain(Q){try{let J=this.getRootDomain(Q);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(Q){try{let J=this.getRootDomain(Q);return(await this.request(`/dns/getNS/${J}`)).ns||[]}catch{return[]}}async updateNameServers(Q,J){try{let $=this.getRootDomain(Q);return await this.request(`/dns/updateNS/${$}`,{ns:J}),!0}catch{return!1}}}class K{name="godaddy";apiKey;apiSecret;baseUrl;constructor(Q,J,$="production"){this.apiKey=Q,this.apiSecret=J,this.baseUrl=$==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}async request(Q,J,$){let H=`${this.baseUrl}${J}`,Y={Authorization:`sso-key ${this.apiKey}:${this.apiSecret}`,"Content-Type":"application/json",Accept:"application/json"},X={method:Q,headers:Y};if($)X.body=JSON.stringify($);let j=await fetch(H,X);if(j.status===204)return{};if(j.ok){let O=await j.text();if(O)return JSON.parse(O);return{}}let G=`GoDaddy API error: ${j.status} ${j.statusText}`;try{let O=await j.json();if(O.message)G=`GoDaddy API error: ${O.message}`;if(O.fields)G+=` - Fields: ${JSON.stringify(O.fields)}`}catch{}throw Error(G)}getSubdomain(Q,J){let $=Q.replace(/\.$/,""),H=J.replace(/\.$/,"");if($===H)return"@";if($.endsWith(`.${H}`))return $.slice(0,-(H.length+1));return $}getRootDomain(Q){let J=Q.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return Q}toGoDaddyRecord(Q,J){let $=this.getRootDomain(J),H=this.getSubdomain(Q.name,$),Y={type:Q.type,name:H,data:Q.content,ttl:Q.ttl||600};if(Q.type==="MX"&&Q.priority!==void 0)Y.priority=Q.priority;return Y}fromGoDaddyRecord(Q,J){let $=this.getRootDomain(J),H=Q.name;if(H==="@")H=$;else if(!H.endsWith($))H=`${H}.${$}`;return{name:H,type:Q.type,content:Q.data,ttl:Q.ttl,priority:Q.priority}}async createRecord(Q,J){try{let $=this.getRootDomain(Q),H=this.toGoDaddyRecord(J,Q);return await this.request("PATCH",`/v1/domains/${$}/records`,[H]),{success:!0,message:"Record created successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async upsertRecord(Q,J){try{let $=this.getRootDomain(Q),H=this.toGoDaddyRecord(J,Q);return await this.request("PUT",`/v1/domains/${$}/records/${J.type}/${H.name}`,[H]),{success:!0,message:"Record upserted successfully"}}catch($){return this.createRecord(Q,J)}}async deleteRecord(Q,J){try{let $=this.getRootDomain(Q),H=this.getSubdomain(J.name,$),Y=await this.request("GET",`/v1/domains/${$}/records/${J.type}/${H}`),X=Y.filter((j)=>j.data!==J.content);if(X.length===Y.length)return{success:!1,message:"Record not found"};if(X.length===0)try{await this.request("DELETE",`/v1/domains/${$}/records/${J.type}/${H}`)}catch{}else await this.request("PUT",`/v1/domains/${$}/records/${J.type}/${H}`,X);return{success:!0,message:"Record deleted successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async listRecords(Q,J){try{let $=this.getRootDomain(Q),H=`/v1/domains/${$}/records`;if(J)H=`/v1/domains/${$}/records/${J}`;return{success:!0,records:(await this.request("GET",H)).map((X)=>this.fromGoDaddyRecord(X,Q))}}catch($){return{success:!1,records:[],message:$ instanceof Error?$.message:"Unknown error"}}}async canManageDomain(Q){try{let J=this.getRootDomain(Q);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(Q){try{let J=this.getRootDomain(Q),$=await this.request("GET",`/v1/domains/${J}`);return{domain:$.domain,status:$.status,nameServers:$.nameServers,expires:$.expires}}catch{return null}}async updateNameServers(Q,J){try{let $=this.getRootDomain(Q);return await this.request("PUT",`/v1/domains/${$}/records/NS`,J.map((H)=>({type:"NS",name:"@",data:H,ttl:3600}))),!0}catch{return!1}}async checkDomainAvailability(Q){try{let J=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(Q)}`);return{available:J.available,price:J.price,currency:J.currency}}catch{return{available:!1}}}}var D="https://api.cloudflare.com/client/v4",C="[ts-cloud]";class M{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(Q,J={}){this.apiToken=Q,this.configuredZoneId=J.zoneId,this.accountId=J.accountId}async request(Q,J,$){let H=`${D}${J}`,Y={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},X={method:Q,headers:Y};if($)X.body=JSON.stringify($);let G=await(await fetch(H,X)).json();if(!G.success){let O=G.errors.map((W)=>W.message).join(", ");throw Error(`Cloudflare API error: ${O}`)}return G}getRootDomain(Q){let J=Q.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return Q}async resolveZone(Q){let J=Q.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let j=await this.resolveConfiguredZoneName();if(j&&(J===j||J.endsWith(`.${j}`)))return{id:this.configuredZoneId,name:j}}let $=this.getRootDomain(J),H=this.zoneCache.get($);if(H)return{id:H,name:$};let Y=await this.request("GET",`/zones?name=${encodeURIComponent($)}`);if(!Y.result||Y.result.length===0)throw Error(`Zone not found for domain: ${$}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let X=Y.result[0].id;return this.zoneCache.set($,X),{id:X,name:Y.result[0].name||$}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let J=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!J)return;return this.configuredZoneName=J,this.zoneCache.set(J,this.configuredZoneId),J}catch{return}}async getZoneId(Q){return(await this.resolveZone(Q)).id}getFullRecordName(Q,J){let $=Q.replace(/\.$/,"");if(!$||$===J||$==="@")return J;if($.endsWith(`.${J}`))return $;return`${$}.${J}`}toCloudflareRecord(Q,J,$){let H={type:Q.type,name:this.getFullRecordName(Q.name,J),content:Q.content||Q.value||"",ttl:Q.ttl||1},Y=$??Q.proxied;if(Y!==void 0&&A.has(Q.type)){if(H.proxied=Y,Y)H.ttl=1}if(Q.type==="MX"&&Q.priority!==void 0)H.priority=Q.priority;if(Q.type==="SRV"){if(Q.priority!==void 0)H.priority=Q.priority}return H}fromCloudflareRecord(Q){return{id:Q.id,name:Q.name,type:Q.type,content:Q.content,ttl:Q.ttl,priority:Q.priority,proxied:Q.proxied}}async createRecord(Q,J){try{let $=await this.resolveZone(Q),H=this.toCloudflareRecord(J,$.name);return{success:!0,id:(await this.request("POST",`/zones/${$.id}/dns_records`,H)).result.id,message:"Record created successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async upsertRecord(Q,J){try{let $=await this.resolveZone(Q),H=this.getFullRecordName(J.name,$.name),X=(await this.request("GET",`/zones/${$.id}/dns_records?type=${J.type}&name=${encodeURIComponent(H)}`)).result?.[0],j=J.proxied??X?.proxied,G=this.toCloudflareRecord(J,$.name,j);if(X)return{success:!0,id:(await this.request("PUT",`/zones/${$.id}/dns_records/${X.id}`,G)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${$.id}/dns_records`,G)).result.id,message:"Record created successfully"}}catch($){return this.createRecord(Q,J)}}async deleteRecord(Q,J){try{let $=await this.resolveZone(Q),H=$.id,Y=this.getFullRecordName(J.name,$.name),X=await this.request("GET",`/zones/${H}/dns_records?type=${J.type}&name=${encodeURIComponent(Y)}`);if(!X.result||X.result.length===0)return{success:!1,message:"Record not found"};let j=X.result.find((G)=>G.content===J.content);if(!j)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${H}/dns_records/${j.id}`),{success:!0,message:"Record deleted successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async listRecords(Q,J){try{let H=`/zones/${await this.getZoneId(Q)}/dns_records?per_page=100`;if(J)H+=`&type=${J}`;let Y=[],X=1,j=!0;while(j){let G=await this.request("GET",`${H}&page=${X}`);if(Y.push(...G.result||[]),G.result_info)j=X<G.result_info.total_pages,X++;else j=!1}return{success:!0,records:Y.map((G)=>this.fromCloudflareRecord(G))}}catch($){return{success:!1,records:[],message:$ instanceof Error?$.message:"Unknown error"}}}async canManageDomain(Q){try{return await this.getZoneId(Q),!0}catch{return!1}}async listDomains(){try{let Q=[],J=1,$=!0;while($){let H=await this.request("GET",`/zones?per_page=50&page=${J}`);if(Q.push(...H.result||[]),H.result_info)$=J<H.result_info.total_pages,J++;else $=!1}return Q.map((H)=>H.name)}catch{return[]}}async getZoneDetails(Q){try{let J=await this.getZoneId(Q),$=await this.request("GET",`/zones/${J}`);return{id:$.result.id,name:$.result.name,status:$.result.status,nameServers:$.result.name_servers,paused:$.result.paused}}catch{return null}}async purgeCache(Q,J){try{let $=await this.getZoneId(Q),H={};if(J?.purgeEverything)H.purge_everything=!0;else{if(J?.files)H.files=J.files;if(J?.tags)H.tags=J.tags;if(J?.hosts)H.hosts=J.hosts}if(Object.keys(H).length===0)H.purge_everything=!0;return await this.request("POST",`/zones/${$}/purge_cache`,H),!0}catch{return!1}}async getRecordProxyStatus(Q,J){try{let $=await this.resolveZone(Q),H=$.id,Y=this.getFullRecordName(J.name,$.name),X=await this.request("GET",`/zones/${H}/dns_records?type=${J.type}&name=${encodeURIComponent(Y)}`);if(X.result&&X.result.length>0)return X.result.find((G)=>G.content===J.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(Q,J,$){try{let H=await this.resolveZone(Q),Y=H.id,X=this.getFullRecordName(J.name,H.name),j=await this.request("GET",`/zones/${Y}/dns_records?type=${J.type}&name=${encodeURIComponent(X)}`);if(!j.result||j.result.length===0)return!1;let G=j.result.find((O)=>O.content===J.content);if(!G)return!1;return await this.request("PATCH",`/zones/${Y}/dns_records/${G.id}`,{proxied:$}),!0}catch{return!1}}async zoneIdFor(Q){return this.getZoneId(Q)}get account(){return this.accountId}async getZoneSettings(Q){let J=await this.getZoneId(Q),$=await this.request("GET",`/zones/${J}/settings`),H={};for(let Y of $.result||[])H[Y.id]=Y.value;return H}async applyZoneSettings(Q,J){let $=await this.getZoneId(Q),H=await this.getZoneSettings(Q).catch(()=>({})),Y=[],X=[];for(let[j,G]of Object.entries(J)){if(G===void 0)continue;let O=H[j];if(O!==void 0&&I(O,G))continue;try{await this.request("PATCH",`/zones/${$}/settings/${j}`,{value:G}),Y.push({id:j,from:O,to:G})}catch(W){X.push({id:j,error:W instanceof Error?W.message:String(W)})}}return{changed:Y,failed:X}}async getPhaseRules(Q,J){let $=await this.getZoneId(Q);try{return(await this.request("GET",`/zones/${$}/rulesets/phases/${J}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(Q,J,$){try{let H=await this.getZoneId(Q),X=(await this.getPhaseRules(Q,J)).filter((O)=>!(O.description||"").startsWith(C)),j=$.map((O)=>({...O,description:O.description?.startsWith(C)?O.description:`${C} ${O.description||J}`})),G=[...X,...j].map(({id:O,...W})=>W);return await this.request("PUT",`/zones/${H}/rulesets/phases/${J}/entrypoint`,{rules:G}),{success:!0}}catch(H){return{success:!1,message:H instanceof Error?H.message:String(H)}}}}function I(Q,J){if(Q===J)return!0;if(typeof Q!==typeof J||Q===null||J===null)return!1;if(typeof Q!=="object")return!1;if(Array.isArray(Q)||Array.isArray(J)){if(!Array.isArray(Q)||!Array.isArray(J)||Q.length!==J.length)return!1;return Q.every((Y,X)=>I(Y,J[X]))}let $=Q,H=J;return Object.keys(H).every((Y)=>I($[Y],H[Y]))}var R=new Set(["A","AAAA","CNAME","ALIAS"]);function E(Q){let J=Q.trim().replace(/^"|"$/g,"").toLowerCase();if(J.startsWith("v=spf1"))return"v=spf1";if(J.startsWith("v=dmarc1"))return"v=dmarc1";return}function T(Q){return Q.trim().replace(/^"(.*)"$/s,"$1")}function L(Q){return Q.replace(/\.$/,"").toLowerCase()}function x(Q,J){let $=L(J),H=(Q??"@").trim();if(!H||H==="@")return $;let Y=L(H);if(Y===$||Y.endsWith(`.${$}`))return Y;return`${Y}.${$}`}function b(Q,J){return Q.map(($)=>({...$,name:x($.name,J),proxied:$.proxied??!1}))}function v(Q,J){if(Q.type!==J.type)return!1;if(L(Q.name)!==L(J.name))return!1;if(R.has(J.type))return!0;if(J.type==="TXT"){let $=E(J.content);if($)return E(T(Q.content))===$;return T(Q.content)===T(J.content)}return T(Q.content)===T(J.content)}function f(Q,J){if(T(Q.content)!==T(J.content))return!1;if(J.priority!==void 0&&Q.priority!==J.priority)return!1;if(J.proxied!==void 0&&Q.proxied!==void 0&&Q.proxied!==J.proxied)return!1;return!0}async function y(Q){let{provider:J,zone:$,records:H}=Q,Y={outcomes:[],warnings:[]};if(H.length===0)return Y;let X=await J.listRecords($);if(!X.success)return Y.warnings.push(`could not list ${$}: ${X.message||"unknown provider error"} — records not reconciled`),Y;let j=X.records;for(let G of H){let O=j.filter((B)=>v(B,G));if(O.length>0&&O.every((B)=>f(B,G))){Y.outcomes.push({record:G,action:"unchanged"});continue}let W={name:G.name,type:G.type,content:G.content,ttl:G.ttl??3600,...G.priority!==void 0?{priority:G.priority}:{},...G.proxied!==void 0?{proxied:G.proxied}:{}},q=G.type==="TXT"&&E(G.content)!==void 0;if(q)for(let B of O){let P=await J.deleteRecord($,{name:B.name,type:B.type,content:B.content});if(!P.success)Y.warnings.push(`could not remove superseded ${B.type} at ${B.name}: ${P.message||"unknown error"}`)}let w=q||O.length===0?await J.createRecord($,W):await J.upsertRecord($,W);if(w.success)Y.outcomes.push({record:G,action:O.length>0?"updated":"created"});else Y.outcomes.push({record:G,action:"failed",message:w.message})}for(let G of["MX"]){let O=new Set(H.filter((W)=>W.type===G).map((W)=>L(W.name)));for(let W of O){let q=new Set(H.filter((B)=>B.type===G&&L(B.name)===W).map((B)=>T(B.content).toLowerCase())),w=j.filter((B)=>B.type===G&&L(B.name)===W&&!q.has(T(B.content).toLowerCase()));for(let B of w)Y.warnings.push(`${W} has an undeclared ${G} record (${B.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return Y}class V{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(Q="us-east-1",J){this.client=new F(Q),this.providedHostedZoneId=J}getRootDomain(Q){let J=Q.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return Q}async getHostedZoneId(Q){if(this.providedHostedZoneId)return this.providedHostedZoneId;let J=this.getRootDomain(Q),$=this.hostedZoneCache.get(J);if($)return $;let H=await this.client.findHostedZoneForDomain(Q);if(H){let Y=H.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(J,Y),Y}return null}normalizeName(Q,J){let $=Q.replace(/\.$/,""),H=J.replace(/\.$/,"");if(!H||H==="@")return`${$}.`;if(H===$||H.endsWith(`.${$}`))return`${H}.`;return`${H}.${$}.`}async createRecord(Q,J){try{let $=await this.getHostedZoneId(Q);if(!$)return{success:!1,message:`No hosted zone found for domain: ${Q}`};let H=this.normalizeName(Q,J.name),Y=J.content;if(J.type==="TXT"&&!Y.startsWith('"'))Y=`"${Y}"`;if(J.type==="MX"&&J.priority!==void 0)Y=`${J.priority} ${Y}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:$,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:"CREATE",ResourceRecordSet:{Name:H,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:Y}]}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async upsertRecord(Q,J){try{let $=await this.getHostedZoneId(Q);if(!$)return{success:!1,message:`No hosted zone found for domain: ${Q}`};let H=this.normalizeName(Q,J.name),Y=J.content;if(J.type==="TXT"&&!Y.startsWith('"'))Y=`"${Y}"`;if(J.type==="MX"&&J.priority!==void 0)Y=`${J.priority} ${Y}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:$,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:H,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:Y}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async deleteRecord(Q,J){try{let $=await this.getHostedZoneId(Q);if(!$)return{success:!1,message:`No hosted zone found for domain: ${Q}`};let H=this.normalizeName(Q,J.name),Y=J.content;if(J.type==="TXT"&&!Y.startsWith('"'))Y=`"${Y}"`;if(J.type==="MX"&&J.priority!==void 0)Y=`${J.priority} ${Y}`;return await this.client.changeResourceRecordSets({HostedZoneId:$,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:H,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:Y}]}}]}}),{success:!0,message:"Record deleted successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async listRecords(Q,J){try{let $=await this.getHostedZoneId(Q);if(!$)return{success:!1,records:[],message:`No hosted zone found for domain: ${Q}`};let H=await this.client.listResourceRecordSets({HostedZoneId:$,StartRecordType:J}),Y=[];for(let X of H.ResourceRecordSets){if(J&&X.Type!==J)continue;if(X.AliasTarget)continue;for(let j of X.ResourceRecords||[]){let G=j.Value,O;if(X.Type==="MX"){let W=G.split(" ");if(W.length>=2)O=Number.parseInt(W[0],10),G=W.slice(1).join(" ")}if(X.Type==="TXT"&&G.startsWith('"')&&G.endsWith('"'))G=G.slice(1,-1);Y.push({name:X.Name.replace(/\.$/,""),type:X.Type,content:G,ttl:X.TTL,priority:O})}}return{success:!0,records:Y}}catch($){return{success:!1,records:[],message:$ instanceof Error?$.message:"Unknown error"}}}async canManageDomain(Q){return await this.getHostedZoneId(Q)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((J)=>J.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(Q){try{let J=await this.getHostedZoneId(Q.domain);if(!J)return{success:!1,message:`No hosted zone found for domain: ${Q.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:J,Name:this.normalizeName(Q.domain,Q.name),TargetHostedZoneId:Q.targetHostedZoneId,TargetDNSName:Q.targetDnsName,EvaluateTargetHealth:Q.evaluateTargetHealth,Type:Q.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(J){return{success:!1,message:J instanceof Error?J.message:"Unknown error"}}}async createCloudFrontAlias(Q){return this.createAliasRecord({domain:Q.domain,name:Q.name,targetHostedZoneId:F.CloudFrontHostedZoneId,targetDnsName:Q.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(Q){let J=F.ALBHostedZoneIds[Q.region];if(!J)return{success:!1,message:`Unknown region for ALB: ${Q.region}`};return this.createAliasRecord({domain:Q.domain,name:Q.name,targetHostedZoneId:J,targetDnsName:Q.albDnsName,evaluateTargetHealth:!0})}}class Z{client;region;constructor(Q="us-east-1"){this.client=new h,this.region=Q}async requestCertificate(Q){let J={DomainName:Q.DomainName,ValidationMethod:Q.ValidationMethod||"DNS"};if(Q.SubjectAlternativeNames)J.SubjectAlternativeNames=Q.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(Q){let $=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:Q.CertificateArn})})).Certificate||{};return{CertificateArn:$.CertificateArn||"",DomainName:$.DomainName||"",SubjectAlternativeNames:$.SubjectAlternativeNames,Status:$.Status||"PENDING_VALIDATION",Type:$.Type,DomainValidationOptions:$.DomainValidationOptions?.map((H)=>({DomainName:H.DomainName,ValidationDomain:H.ValidationDomain,ValidationStatus:H.ValidationStatus,ResourceRecord:H.ResourceRecord?{Name:H.ResourceRecord.Name,Type:H.ResourceRecord.Type,Value:H.ResourceRecord.Value}:void 0,ValidationMethod:H.ValidationMethod})),CreatedAt:$.CreatedAt,IssuedAt:$.IssuedAt,NotBefore:$.NotBefore,NotAfter:$.NotAfter}}async listCertificates(Q){let J={};if(Q?.CertificateStatuses)J.CertificateStatuses=Q.CertificateStatuses;if(Q?.MaxItems)J.MaxItems=Q.MaxItems;if(Q?.NextToken)J.NextToken=Q.NextToken;let $=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(J)});return{CertificateSummaryList:($.CertificateSummaryList||[]).map((H)=>({CertificateArn:H.CertificateArn,DomainName:H.DomainName})),NextToken:$.NextToken}}async deleteCertificate(Q){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:Q.CertificateArn})})}async listTagsForCertificate(Q){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:Q.CertificateArn})})).Tags||[]}}async addTagsToCertificate(Q){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:Q.CertificateArn,Tags:Q.Tags})})}async resendValidationEmail(Q){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:Q.CertificateArn,Domain:Q.Domain,ValidationDomain:Q.ValidationDomain})})}async findCertificateByDomain(Q){let $=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((H)=>H.DomainName===Q||H.DomainName===`*.${Q.split(".").slice(1).join(".")}`);if(!$)return null;return this.describeCertificate({CertificateArn:$.CertificateArn})}async waitForCertificateValidation(Q,J=60,$=30000){for(let H=0;H<J;H++){let Y=await this.describeCertificate({CertificateArn:Q});if(Y.Status==="ISSUED")return Y;if(Y.Status==="FAILED"||Y.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((X)=>setTimeout(X,$))}return null}async getDnsValidationRecords(Q){let J=await this.describeCertificate({CertificateArn:Q});if(!J.DomainValidationOptions)return[];return J.DomainValidationOptions.filter(($)=>$.ResourceRecord&&$.ValidationMethod==="DNS").map(($)=>({domainName:$.DomainName,recordName:$.ResourceRecord.Name,recordType:$.ResourceRecord.Type,recordValue:$.ResourceRecord.Value}))}async requestCertificateWithSans(Q){let J=new Set;if(J.add(Q.DomainName),Q.IncludeWww!==!1)J.add(`www.${Q.DomainName}`);if(Q.IncludeWildcard)J.add(`*.${Q.DomainName}`);if(Q.AdditionalSans)for(let $ of Q.AdditionalSans)J.add($);return this.requestCertificate({DomainName:Q.DomainName,SubjectAlternativeNames:Array.from(J),ValidationMethod:"DNS"})}async isCertificateValidForDomain(Q,J){let $=await this.describeCertificate({CertificateArn:Q});if($.Status!=="ISSUED")return!1;if($.DomainName===J)return!0;if($.DomainName?.startsWith("*.")){let H=$.DomainName.slice(2),Y=J.split("."),X=H.split(".");if(Y.slice(-X.length).join(".")===H)return!0}if($.SubjectAlternativeNames)for(let H of $.SubjectAlternativeNames){if(H===J)return!0;if(H.startsWith("*.")){let Y=H.slice(2),X=J.split("."),j=Y.split(".");if(X.slice(-j.length).join(".")===Y)return!0}}return!1}}class g{acm;route53;dnsProvider;constructor(Q="us-east-1",J){if(this.acm=new Z(Q),this.route53=new F,J&&J.provider!=="route53")this.dnsProvider=_(J)}async requestAndValidate(Q){let{domainName:J,hostedZoneId:$,subjectAlternativeNames:H=[],waitForValidation:Y=!1,maxWaitMinutes:X=30}=Q;if(!this.dnsProvider&&!$)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:j}=await this.acm.requestCertificate({DomainName:J,SubjectAlternativeNames:H.length>0?[J,...H]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(j);let G=await this.acm.getDnsValidationRecords(j);if(this.dnsProvider)for(let O of G){let W=await this.dnsProvider.upsertRecord(J,{name:O.recordName,type:O.recordType,content:O.recordValue,ttl:300});if(!W.success)console.warn(`Failed to create validation record for ${O.domainName}: ${W.message}`)}else if($)for(let O of G)await this.route53.changeResourceRecordSets({HostedZoneId:$,ChangeBatch:{Comment:`ACM DNS validation for ${O.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:O.recordName,Type:O.recordType,TTL:300,ResourceRecords:[{Value:O.recordValue}]}}]}});if(Y){if(!await this.acm.waitForCertificateValidation(j,X*2,30000))throw Error(`Certificate validation timed out after ${X} minutes`)}return{certificateArn:j,validationRecords:G}}async waitForValidationOptions(Q,J=30){for(let $=0;$<J;$++){let H=await this.acm.describeCertificate({CertificateArn:Q});if(H.DomainValidationOptions&&H.DomainValidationOptions.length>0&&H.DomainValidationOptions[0].ResourceRecord)return;await new Promise((Y)=>setTimeout(Y,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(Q){let{certificateArn:J,hostedZoneId:$,domain:H}=Q;if(!this.dnsProvider&&!$)throw Error("Either hostedZoneId or external DNS provider configuration is required");let Y=await this.acm.getDnsValidationRecords(J),X=[];if(this.dnsProvider){let j=H||Y[0]?.domainName;for(let G of Y){let O=await this.dnsProvider.upsertRecord(j,{name:G.recordName,type:G.recordType,content:G.recordValue,ttl:300});X.push({...G,changeId:O.success?O.id:void 0})}}else if($)for(let j of Y){let G=await this.route53.changeResourceRecordSets({HostedZoneId:$,ChangeBatch:{Comment:`ACM DNS validation for ${j.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:j.recordName,Type:j.recordType,TTL:300,ResourceRecords:[{Value:j.recordValue}]}}]}});X.push({...j,changeId:G.ChangeInfo?.Id})}return X}async deleteValidationRecords(Q){let{certificateArn:J,hostedZoneId:$,domain:H}=Q,Y=await this.acm.getDnsValidationRecords(J);if(this.dnsProvider){let X=H||Y[0]?.domainName;for(let j of Y)try{await this.dnsProvider.deleteRecord(X,{name:j.recordName,type:j.recordType,content:j.recordValue})}catch{}}else if($)for(let X of Y)try{await this.route53.changeResourceRecordSets({HostedZoneId:$,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${X.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:X.recordName,Type:X.recordType,TTL:300,ResourceRecords:[{Value:X.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(Q){let{domainName:J,hostedZoneId:$,subjectAlternativeNames:H,waitForValidation:Y=!0}=Q;if(!this.dnsProvider&&!$)throw Error("Either hostedZoneId or external DNS provider configuration is required");let X=await this.acm.findCertificateByDomain(J);if(X&&X.Status==="ISSUED")return{certificateArn:X.CertificateArn,isNew:!1};let{certificateArn:j}=await this.requestAndValidate({domainName:J,hostedZoneId:$,subjectAlternativeNames:H,waitForValidation:Y});return{certificateArn:j,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}class S{acm;dnsProvider;constructor(Q,J="us-east-1"){if(this.acm=new Z(J),"provider"in Q)this.dnsProvider=_(Q);else this.dnsProvider=Q}getProvider(){return this.dnsProvider}async requestAndValidate(Q){let{domainName:J,subjectAlternativeNames:$=[],waitForValidation:H=!1,maxWaitMinutes:Y=30}=Q,{CertificateArn:X}=await this.acm.requestCertificate({DomainName:J,SubjectAlternativeNames:$.length>0?[J,...$]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(X);let j=await this.acm.getDnsValidationRecords(X);for(let O of j){let W=await this.dnsProvider.upsertRecord(J,{name:O.recordName,type:O.recordType,content:O.recordValue,ttl:300});if(!W.success)console.warn(`Failed to create validation record for ${O.domainName}: ${W.message}`)}let G="pending";if(H)G=(await this.acm.waitForCertificateValidation(X,Y*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:X,validationRecords:j.map((O)=>({domainName:O.domainName,recordName:O.recordName,recordType:O.recordType,recordValue:O.recordValue})),isNew:!0,status:G}}async createValidationRecords(Q){let{certificateArn:J,domain:$}=Q,H=[],Y=await this.acm.getDnsValidationRecords(J);for(let X of Y){let j=await this.dnsProvider.upsertRecord($,{name:X.recordName,type:X.recordType,content:X.recordValue,ttl:300});if(!j.success)H.push(`Failed to create record for ${X.domainName}: ${j.message}`)}return{success:H.length===0,records:Y.map((X)=>({domainName:X.domainName,recordName:X.recordName,recordType:X.recordType,recordValue:X.recordValue})),errors:H}}async deleteValidationRecords(Q){let{certificateArn:J,domain:$}=Q,H=[],Y=await this.acm.getDnsValidationRecords(J);for(let X of Y){let j=await this.dnsProvider.deleteRecord($,{name:X.recordName,type:X.recordType,content:X.recordValue});if(!j.success)H.push(`Failed to delete record for ${X.domainName}: ${j.message}`)}return{success:H.length===0,errors:H}}async findOrCreateCertificate(Q){let{domainName:J,subjectAlternativeNames:$=[],waitForValidation:H=!0,maxWaitMinutes:Y}=Q,X=await this.acm.findCertificateByDomain(J);if(X&&X.Status==="ISSUED"){let j=X.SubjectAlternativeNames||[X.DomainName],G=j.some((W)=>W===`*.${J}`);if($.every((W)=>j.includes(W)||G))return{certificateArn:X.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:J,subjectAlternativeNames:$,waitForValidation:H,maxWaitMinutes:Y})}async requestCertificateWithCommonSans(Q){let{domainName:J,includeWww:$=!0,includeWildcard:H=!1,additionalSans:Y=[],waitForValidation:X=!1}=Q,j=[];if($)j.push(`www.${J}`);if(H)j.push(`*.${J}`);return j.push(...Y),this.requestAndValidate({domainName:J,subjectAlternativeNames:j,waitForValidation:X})}async waitForValidationOptions(Q,J=30){for(let $=0;$<J;$++){let H=await this.acm.describeCertificate({CertificateArn:Q});if(H.DomainValidationOptions&&H.DomainValidationOptions.length>0&&H.DomainValidationOptions[0].ResourceRecord)return;await new Promise((Y)=>setTimeout(Y,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(Q){let J=await this.acm.describeCertificate({CertificateArn:Q});return{status:J.Status,domainValidations:(J.DomainValidationOptions||[]).map(($)=>({domain:$.DomainName,status:$.ValidationStatus||"UNKNOWN"}))}}}function u(Q,J,$){return new S({provider:"porkbun",apiKey:Q,secretKey:J},$)}function l(Q,J,$,H){return new S({provider:"godaddy",apiKey:Q,apiSecret:J,environment:H},$)}function p(Q,J,$){return new S({provider:"route53",region:Q,hostedZoneId:J},$||Q)}function _(Q){switch(Q.provider){case"route53":return new V(Q.region,Q.hostedZoneId);case"porkbun":return new U(Q.apiKey,Q.secretKey);case"godaddy":return new K(Q.apiKey,Q.apiSecret,Q.environment);case"cloudflare":return new M(Q.apiToken,{zoneId:Q.zoneId,accountId:Q.accountId});default:throw Error(`Unknown DNS provider: ${Q.provider}`)}}async function OJ(Q,J){for(let $ of J){let H=_($);if(await H.canManageDomain(Q))return H}return null}class N{providers=new Map;configs=[];addConfig(Q){return this.configs.push(Q),this}addRoute53(Q,J){return this.configs.push({provider:"route53",region:Q,hostedZoneId:J}),this}addPorkbun(Q,J){return this.configs.push({provider:"porkbun",apiKey:Q,secretKey:J}),this}addGoDaddy(Q,J,$){return this.configs.push({provider:"godaddy",apiKey:Q,apiSecret:J,environment:$}),this}addCloudflare(Q,J={}){return this.configs.push({provider:"cloudflare",apiToken:Q,zoneId:J.zoneId,accountId:J.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let Q=process.env.PORKBUN_API_KEY,J=process.env.PORKBUN_SECRET_KEY;if(Q&&J)this.addPorkbun(Q,J);let $=process.env.GODADDY_API_KEY,H=process.env.GODADDY_API_SECRET;if($&&H){let X=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy($,H,X)}let Y=process.env.CLOUDFLARE_API_TOKEN;if(Y)this.addCloudflare(Y,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(Q){let J=this.providers.get(Q);if(J)return J;let $=this.configs.find((Y)=>Y.provider===Q);if(!$)return null;let H=_($);return this.providers.set(Q,H),H}async getProviderForDomain(Q){for(let J of this.configs){let $=_(J);if(await $.canManageDomain(Q))return $}return null}getAllProviders(){return this.configs.map((Q)=>_(Q))}}var WJ=new N;
2
- export{A as vf,U as wf,K as xf,C as yf,M as zf,E as Af,x as Bf,b as Cf,y as Df,V as Ef,S as Ff,u as Gf,l as Hf,p as If,_ as Jf,OJ as Kf,N as Lf,WJ as Mf,Z as Nf,g as Of};
@@ -1,2 +0,0 @@
1
- import{Th as _}from"./chunk-0ccta6z6.js";class ${client;region;constructor(j="us-east-1",q){this.region=j,this.client=new _(void 0,{profile:q})}async createStack(j){let q={Action:"CreateStack",StackName:j.stackName,Version:"2010-05-15"};if(j.templateBody)q.TemplateBody=j.templateBody;else if(j.templateUrl)q.TemplateURL=j.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(j.parameters)j.parameters.forEach((z,H)=>{q[`Parameters.member.${H+1}.ParameterKey`]=z.ParameterKey,q[`Parameters.member.${H+1}.ParameterValue`]=z.ParameterValue});if(j.capabilities)j.capabilities.forEach((z,H)=>{q[`Capabilities.member.${H+1}`]=z});if(j.roleArn)q.RoleARN=j.roleArn;if(j.tags)j.tags.forEach((z,H)=>{q[`Tags.member.${H+1}.Key`]=z.Key,q[`Tags.member.${H+1}.Value`]=z.Value});if(j.timeoutInMinutes)q.TimeoutInMinutes=j.timeoutInMinutes;if(j.onFailure)q.OnFailure=j.onFailure;let G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{StackId:G.StackId||G.CreateStackResult?.StackId}}async updateStack(j){let q={Action:"UpdateStack",StackName:j.stackName,Version:"2010-05-15"};if(j.templateBody)q.TemplateBody=j.templateBody;else if(j.templateUrl)q.TemplateURL=j.templateUrl;if(j.parameters)j.parameters.forEach((z,H)=>{if(q[`Parameters.member.${H+1}.ParameterKey`]=z.ParameterKey,z.UsePreviousValue)q[`Parameters.member.${H+1}.UsePreviousValue`]="true";else q[`Parameters.member.${H+1}.ParameterValue`]=z.ParameterValue});if(j.capabilities)j.capabilities.forEach((z,H)=>{q[`Capabilities.member.${H+1}`]=z});if(j.roleArn)q.RoleARN=j.roleArn;if(j.tags)j.tags.forEach((z,H)=>{q[`Tags.member.${H+1}.Key`]=z.Key,q[`Tags.member.${H+1}.Value`]=z.Value});let G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{StackId:G.StackId||G.UpdateStackResult?.StackId}}async deleteStack(j,q,G){let z={Action:"DeleteStack",StackName:j,Version:"2010-05-15"};if(q)z.RoleARN=q;if(G&&G.length>0)G.forEach((H,Q)=>{z[`RetainResources.member.${Q+1}`]=H});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(z).toString()})}async describeStacks(j={}){let q={Action:"DescribeStacks",Version:"2010-05-15"};if(j.stackName)q.StackName=j.stackName;let G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{Stacks:this.parseStacksResponse(G)}}async describeStackEvents(j){let q={Action:"DescribeStackEvents",StackName:j,Version:"2010-05-15"},G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{StackEvents:this.parseStackEvents(G)}}async listStackResources(j){let q={Action:"ListStackResources",StackName:j,Version:"2010-05-15"},z=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,H=[];if(z)H=Array.isArray(z)?z:[z];return{StackResourceSummaries:H}}async waitForStack(j,q){let G={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},z=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],H=G[q],Q=360,J=0;while(J<360)try{let I=await this.describeStacks({stackName:j});if(I.Stacks.length===0){if(q==="stack-delete-complete")return;if(J%10===0)console.log(`[waitForStack] Attempt ${J}: Stack not visible yet`);await new Promise((O)=>setTimeout(O,2000)),J++;continue}let L=I.Stacks[0];if(J%10===0)console.log(`[waitForStack] Attempt ${J}: Status = ${L.StackStatus}${L.StackStatusReason?` (${L.StackStatusReason})`:""}`);if(H.includes(L.StackStatus))return;if((q==="stack-create-complete"||q==="stack-update-complete")&&(L.StackStatus==="DELETE_IN_PROGRESS"||L.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let O="";try{let U=await this.describeStackEvents(j);console.log("[waitForStack] Stack events (most recent first):");for(let X of U.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&&!O)O=X.ResourceStatusReason}}catch{}let V=O||L.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${V}`)}if(L.StackStatus==="DELETE_FAILED"&&q==="stack-delete-complete"){let O=Error("Stack deletion failed - may have resources that need to be retained");throw O.code="DELETE_FAILED",O.stackStatus=L.StackStatus,O.statusReason=L.StackStatusReason,O}if(z.includes(L.StackStatus))throw Error(`Stack reached failure status: ${L.StackStatus}`);await new Promise((O)=>setTimeout(O,5000)),J++}catch(I){if(q==="stack-delete-complete"&&I.message?.includes("does not exist"))return;if(q==="stack-create-complete"&&I.message?.includes("does not exist")){if(J%10===0)console.log(`[waitForStack] Attempt ${J}: Stack does not exist (error), retrying...`);await new Promise((L)=>setTimeout(L,2000)),J++;continue}throw console.log(`[waitForStack] Unexpected error: ${I.message}`),I}throw console.log(`[waitForStack] Timeout after ${J} attempts`),Error(`Timeout waiting for stack to reach ${q}`)}async validateTemplate(j){let q={Action:"ValidateTemplate",TemplateBody:j,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()})}async listStacks(j){let q={Action:"ListStacks",Version:"2010-05-15"};if(j)j.forEach((I,L)=>{q[`StackStatusFilter.member.${L+1}`]=I});let G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()}),z=G.ListStacksResponse||G,H=z.ListStacksResult||z,Q=H.StackSummaries?.member||H.StackSummaries||[];return{StackSummaries:(Array.isArray(Q)?Q:Q?[Q]:[]).map((I)=>({StackId:I.StackId||"",StackName:I.StackName||"",TemplateDescription:I.TemplateDescription,CreationTime:I.CreationTime||"",LastUpdatedTime:I.LastUpdatedTime,DeletionTime:I.DeletionTime,StackStatus:I.StackStatus||""}))}}async createChangeSet(j){let q={Action:"CreateChangeSet",StackName:j.stackName,ChangeSetName:j.changeSetName,Version:"2010-05-15"};if(j.templateBody)q.TemplateBody=j.templateBody;else if(j.templateUrl)q.TemplateURL=j.templateUrl;if(j.parameters)j.parameters.forEach((z,H)=>{q[`Parameters.member.${H+1}.ParameterKey`]=z.ParameterKey,q[`Parameters.member.${H+1}.ParameterValue`]=z.ParameterValue});if(j.capabilities)j.capabilities.forEach((z,H)=>{q[`Capabilities.member.${H+1}`]=z});if(j.changeSetType)q.ChangeSetType=j.changeSetType;let G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{Id:G.Id,StackId:G.StackId}}async describeChangeSet(j,q){let G={Action:"DescribeChangeSet",StackName:j,ChangeSetName:q,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(G).toString()})}async executeChangeSet(j,q){let G={Action:"ExecuteChangeSet",StackName:j,ChangeSetName:q,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(G).toString()})}async deleteChangeSet(j,q){let G={Action:"DeleteChangeSet",StackName:j,ChangeSetName:q,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(G).toString()})}async getStackOutputs(j){let q=await this.describeStacks({stackName:j});if(!q.Stacks||q.Stacks.length===0)throw Error(`Stack ${j} not found`);let G=q.Stacks[0],z={};if(G.Outputs)for(let H of G.Outputs)z[H.OutputKey]=H.OutputValue;return z}async getTemplate(j){let q={Action:"GetTemplate",StackName:j,Version:"2010-05-15"},G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{TemplateBody:G?.GetTemplateResult?.TemplateBody||G?.TemplateBody||""}}parseStacksResponse(j){let q=[],G=j?.DescribeStacksResult?.Stacks?.member||j?.Stacks?.member||j?.Stacks||j;if(G&&!Array.isArray(G))G=[G];if(Array.isArray(G)){for(let z of G)if(z.StackId||z.StackName){let H;if(z.Outputs?.member)H=(Array.isArray(z.Outputs.member)?z.Outputs.member:[z.Outputs.member]).map((J)=>({OutputKey:J.OutputKey,OutputValue:J.OutputValue,Description:J.Description,ExportName:J.ExportName}));q.push({StackId:z.StackId,StackName:z.StackName,StackStatus:z.StackStatus,CreationTime:z.CreationTime,LastUpdatedTime:z.LastUpdatedTime,StackStatusReason:z.StackStatusReason,Outputs:H})}}else if(j.StackId)q.push({StackId:j.StackId,StackName:j.StackName,StackStatus:j.StackStatus,CreationTime:j.CreationTime,LastUpdatedTime:j.LastUpdatedTime});return q}parseStackEvents(j){let q=[],G=j?.DescribeStackEventsResult?.StackEvents?.member||j?.StackEvents?.member||j?.StackEvents||[];if(G&&!Array.isArray(G))G=[G];for(let z of G)if(z.LogicalResourceId)q.push({Timestamp:z.Timestamp,ResourceType:z.ResourceType,LogicalResourceId:z.LogicalResourceId,ResourceStatus:z.ResourceStatus,ResourceStatusReason:z.ResourceStatusReason});return q}async waitForStackWithProgress(j,q,G){let z={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},H=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],Q=z[q],J=360,I=0,L=new Set;while(I<360)try{if(G)try{let X=[...(await this.describeStackEvents(j)).StackEvents||[]].reverse();for(let Y of X){let Z=`${Y.LogicalResourceId}-${Y.ResourceStatus}-${Y.Timestamp}`;if(!L.has(Z))L.add(Z),G({resourceId:Y.LogicalResourceId,resourceType:Y.ResourceType,status:Y.ResourceStatus,reason:Y.ResourceStatusReason,timestamp:Y.Timestamp})}}catch{}let O=await this.describeStacks({stackName:j});if(O.Stacks.length===0){if(q==="stack-delete-complete")return;await new Promise((U)=>setTimeout(U,2000)),I++;continue}let V=O.Stacks[0];if(Q.includes(V.StackStatus))return;if(V.StackStatus==="DELETE_FAILED"&&q==="stack-delete-complete"){let U=Error("Stack deletion failed - may have resources that need to be retained");throw U.code="DELETE_FAILED",U.stackStatus=V.StackStatus,U.statusReason=V.StackStatusReason,U}if(H.includes(V.StackStatus))throw Error(`Stack reached failure status: ${V.StackStatus}`);await new Promise((U)=>setTimeout(U,3000)),I++}catch(O){if(q==="stack-delete-complete"&&O.message?.includes("does not exist"))return;if(q==="stack-create-complete"&&O.message?.includes("does not exist")){await new Promise((V)=>setTimeout(V,2000)),I++;continue}throw O}throw Error(`Timeout waiting for stack to reach ${q}`)}async waitForStackComplete(j,q=120,G=5000){let z=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],H=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let Q=0;Q<q;Q++)try{let J=await this.describeStacks({stackName:j});if(J.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let I=J.Stacks[0],L=I.StackStatus;if(z.includes(L))return{success:!0,status:L};if(H.includes(L))return{success:!1,status:L,reason:I.StackStatusReason};await new Promise((O)=>setTimeout(O,G))}catch(J){if(J.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw J}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
2
- export{$ as Ph};
@@ -1,44 +0,0 @@
1
- var V={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function N(j){return{...V,...j.thresholds}}var m=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function I(j){if(!m.test(j))return!1;let[q,z]=j.split("/");if(q.includes(":"))return z==null||Number(z)>=0&&Number(z)<=128;let K=q.split(".");if(K.length!==4||K.some((W)=>Number(W)>255||W===""))return!1;return z==null||Number(z)>=0&&Number(z)<=32}function U(j){return[...new Set((j??[]).map((q)=>q.trim()).filter(I))]}function O(j){let q=(j??[80,443]).filter((z)=>Number.isInteger(z)&&z>=1&&z<=65535);return[...new Set(q)].sort((z,K)=>z-K)}function k(j={}){let q=N(j);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,q.synPerSecond*4)),"net.ipv4.tcp_synack_retries":"2","net.ipv4.tcp_abort_on_overflow":"1","net.ipv4.tcp_fin_timeout":"15","net.ipv4.tcp_keepalive_time":"300","net.ipv4.tcp_keepalive_intvl":"30","net.ipv4.tcp_keepalive_probes":"3","net.core.somaxconn":"4096","net.core.netdev_max_backlog":"16384","net.ipv4.conf.all.rp_filter":"1","net.ipv4.conf.default.rp_filter":"1","net.ipv4.conf.all.accept_source_route":"0","net.ipv4.conf.all.accept_redirects":"0","net.ipv4.conf.all.send_redirects":"0","net.ipv6.conf.all.accept_redirects":"0","net.ipv6.conf.all.accept_source_route":"0","net.ipv4.icmp_echo_ignore_broadcasts":"1","net.ipv4.icmp_ignore_bogus_error_responses":"1","net.netfilter.nf_conntrack_max":"262144","net.netfilter.nf_conntrack_tcp_timeout_established":"3600"}}function _(j={}){let q=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[z,K]of Object.entries(k(j)))q.push(`${z} = ${K}`);return`${q.join(`
2
- `)}
3
- `}function y(j={}){let q=N(j),z=O(j.ports),K=U(j.allowlist),W=U(j.blocklist),X=j.monitorOnly?"counter":"counter drop",M=j.originProtection?.enabled?U(j.originProtection.cdnRanges):[],Q=K.filter((J)=>!J.includes(":")),Z=K.filter((J)=>J.includes(":")),$=W.filter((J)=>!J.includes(":")),G=["#!/usr/sbin/nft -f","# Managed by ts-cloud. Edits are overwritten on the next deploy.","","table inet ts_cloud_ddos","delete table inet ts_cloud_ddos","","table inet ts_cloud_ddos {"," # Sources that tripped a limit, with a timeout so a ban self-expires.",` set banned4 { type ipv4_addr; flags timeout; timeout ${q.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${q.banSeconds}s; }`];if(Q.length>0)G.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${Q.join(", ")} } }`);if(Z.length>0)G.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${Z.join(", ")} } }`);if($.length>0)G.push(` set block4 { type ipv4_addr; flags interval; elements = { ${$.join(", ")} } }`);if(M.length>0)G.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${M.filter((J)=>!J.includes(":")).join(", ")} } }`);if(G.push(""," chain input {"," type filter hook input priority -150; policy accept;",""," # Established traffic is already paid for; never re-inspect it."," ct state established,related accept"," iif lo accept",""," # Invalid packets are never legitimate and are cheap to drop early."," ct state invalid counter drop"),Q.length>0)G.push(" ip saddr @allow4 accept");if(Z.length>0)G.push(" ip6 saddr @allow6 accept");if($.length>0)G.push(" ip saddr @block4 counter drop");if(G.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),G.push(" # Nonsense TCP flag combinations: scanners and stack fingerprinting."," tcp flags & (fin|syn) == (fin|syn) counter drop"," tcp flags & (syn|rst) == (syn|rst) counter drop"," tcp flags & (fin|rst) == (fin|rst) counter drop"," tcp flags & (fin|ack) == fin counter drop"," tcp flags & (syn|fin|ack|rst|psh|urg) == 0x0 counter drop",""," # Ping stays usable, ping floods do not.",` ip protocol icmp icmp type echo-request limit rate ${q.icmpPerSecond}/second burst ${q.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),z.length>0){let J=z.join(", ");if(G.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${J} } ct state new limit rate ${q.synPerSecond}/second burst ${q.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${J} } ct state new meter conn_rate4 { ip saddr limit rate over ${q.newConnectionsPerSecond}/second burst ${q.burst} packets } add @banned4 { ip saddr } ${X}`,` tcp dport { ${J} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${q.newConnectionsPerSecond}/second burst ${q.burst} packets } add @banned6 { ip6 saddr } ${X}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${J} } ct state new meter conn_count4 { ip saddr ct count over ${q.concurrentPerSource} } ${X}`,` tcp dport { ${J} } ct state new meter conn_count6 { ip6 saddr ct count over ${q.concurrentPerSource} } ${X}`,""),M.length>0)G.push(" # Origin protection: reject traffic that skipped the CDN and came"," # straight to the box, which is how an attacker bypasses the edge.",` tcp dport { ${J} } ip saddr != @cdn4 counter drop`,"")}return G.push(" }","}",""),G.join(`
4
- `)}function C(j={}){return`#!/usr/bin/env bash
5
- # Managed by ts-cloud. Installs L3/L4 flood mitigation.
6
- set -euo pipefail
7
-
8
- if ! command -v nft >/dev/null 2>&1; then
9
- export DEBIAN_FRONTEND=noninteractive
10
- apt-get update -qq
11
- apt-get install -y -qq nftables
12
- fi
13
-
14
- install -d -m 0755 /etc/ts-cloud /etc/nftables.d
15
- cat > /etc/sysctl.d/90-ts-cloud-ddos.conf <<'SYSCTL_EOF'
16
- ${_(j)}SYSCTL_EOF
17
- sysctl --system >/dev/null
18
-
19
- cat > /etc/nftables.d/ts-cloud-ddos.nft.new <<'NFT_EOF'
20
- ${y(j)}NFT_EOF
21
-
22
- # Syntax-check before applying: a bad ruleset would leave the box unprotected.
23
- if ! nft -c -f /etc/nftables.d/ts-cloud-ddos.nft.new; then
24
- echo "ts-cloud: generated nftables ruleset failed validation, keeping the previous one" >&2
25
- rm -f /etc/nftables.d/ts-cloud-ddos.nft.new
26
- exit 1
27
- fi
28
-
29
- mv /etc/nftables.d/ts-cloud-ddos.nft.new /etc/nftables.d/ts-cloud-ddos.nft
30
- nft -f /etc/nftables.d/ts-cloud-ddos.nft
31
-
32
- # Applying the ruleset does not survive a reboot on its own: nftables.service
33
- # loads /etc/nftables.conf, so the file has to be included from there or the box
34
- # comes back up unprotected and nothing says so.
35
- touch /etc/nftables.conf
36
- if ! grep -q 'ts-cloud-ddos.nft' /etc/nftables.conf; then
37
- printf '
38
- include "/etc/nftables.d/ts-cloud-ddos.nft"
39
- ' >> /etc/nftables.conf
40
- fi
41
- systemctl enable nftables >/dev/null 2>&1 || true
42
- echo "ts-cloud: L3/L4 mitigation active"
43
- `}var F=["off","monitor","rate_limit","challenge","lockdown"];function L(j,q=[]){let z=[],K=Math.max(1,j.baselineRequestsPerSecond),W=j.requestsPerSecond/K,X=0,M=(B,H)=>{z.push(H),X=Math.max(X,F.indexOf(B))},Q=W>=3;if(Q)M("monitor",`Traffic is ${W.toFixed(1)}x the baseline.`);let Z=j.topSourceShare>=0.25,$=j.errorRate>=0.25,G=(j.suspiciousAgentShare??0)>=0.5,J=j.uniqueSources>0&&j.requestsPerSecond/j.uniqueSources>=50;if(Q&&Z)M("rate_limit",`One source accounts for ${(j.topSourceShare*100).toFixed(0)}% of traffic.`);if(Q&&J)M("rate_limit","Request rate per unique source is far above what a browser produces.");if(Q&&$)M("challenge",`Error rate is ${(j.errorRate*100).toFixed(0)}% under load.`);if(Q&&G)M("challenge","Most requests carry no recognisable browser agent.");if(W>=20&&(Z||$||G||J))M("lockdown",`Traffic is ${W.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!Q&&j.topSourceShare>=0.6&&j.requestsPerSecond>K)M("rate_limit","A single source dominates traffic without an overall surge.");let Y=F[X],P={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[Y];return{level:Y,reasons:z,rateLimitFactor:P,challengeEnabled:Y==="challenge"||Y==="lockdown",staticOnly:Y==="lockdown",banCandidates:Y==="off"||Y==="monitor"?[]:U(q)}}function T(j,q){return Math.max(1,Math.floor(j*q.rateLimitFactor))}
44
- export{V as ll,I as ml,k as nl,_ as ol,y as pl,C as ql,L as rl,T as sl};
@@ -1,2 +0,0 @@
1
- import{Th as w}from"./chunk-0ccta6z6.js";class x{client;region;constructor(b="us-east-1",j){this.region=b,this.client=new w(void 0,{profile:j})}async createRepository(b){let j={repositoryName:b.repositoryName};if(b.imageTagMutability)j.imageTagMutability=b.imageTagMutability;if(b.imageScanningConfiguration)j.imageScanningConfiguration=b.imageScanningConfiguration;if(b.encryptionConfiguration)j.encryptionConfiguration=b.encryptionConfiguration;if(b.tags&&b.tags.length>0)j.tags=b.tags;let q=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:q.repository?this.parseRepository(q.repository):void 0}}async describeRepositories(b){let j={};if(b?.repositoryNames&&b.repositoryNames.length>0)j.repositoryNames=b.repositoryNames;if(b?.registryId)j.registryId=b.registryId;if(b?.maxResults)j.maxResults=b.maxResults;if(b?.nextToken)j.nextToken=b.nextToken;let q=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:q.repositories?.map((v)=>this.parseRepository(v)),nextToken:q.nextToken}}async getAuthorizationToken(b){let j={};if(b&&b.length>0)j.registryIds=b;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((v)=>({authorizationToken:v.authorizationToken,expiresAt:v.expiresAt,proxyEndpoint:v.proxyEndpoint}))}}async deleteRepository(b){let j={repositoryName:b.repositoryName};if(b.registryId)j.registryId=b.registryId;if(b.force!==void 0)j.force=b.force;let q=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:q.repository?this.parseRepository(q.repository):void 0}}async describeImages(b){let j={repositoryName:b.repositoryName};if(b.registryId)j.registryId=b.registryId;if(b.imageIds&&b.imageIds.length>0)j.imageIds=b.imageIds;if(b.filter)j.filter=b.filter;if(b.maxResults)j.maxResults=b.maxResults;if(b.nextToken)j.nextToken=b.nextToken;let q=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:q.imageDetails?.map((v)=>this.parseImageDetail(v)),nextToken:q.nextToken}}async batchDeleteImage(b){let j={repositoryName:b.repositoryName,imageIds:b.imageIds};if(b.registryId)j.registryId=b.registryId;let q=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:q.imageIds,failures:q.failures}}async putLifecyclePolicy(b){let j={repositoryName:b.repositoryName,lifecyclePolicyText:b.lifecyclePolicyText};if(b.registryId)j.registryId=b.registryId;let q=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:q.registryId,repositoryName:q.repositoryName,lifecyclePolicyText:q.lifecyclePolicyText}}async getLifecyclePolicy(b){let j={repositoryName:b.repositoryName};if(b.registryId)j.registryId=b.registryId;let q=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:q.registryId,repositoryName:q.repositoryName,lifecyclePolicyText:q.lifecyclePolicyText,lastEvaluatedAt:q.lastEvaluatedAt}}async setRepositoryPolicy(b){let j={repositoryName:b.repositoryName,policyText:b.policyText};if(b.registryId)j.registryId=b.registryId;if(b.force!==void 0)j.force=b.force;let q=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:q.registryId,repositoryName:q.repositoryName,policyText:q.policyText}}async getRepositoryPolicy(b){let j={repositoryName:b.repositoryName};if(b.registryId)j.registryId=b.registryId;let q=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:q.registryId,repositoryName:q.repositoryName,policyText:q.policyText}}async tagResource(b){let j={resourceArn:b.resourceArn,tags:b.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(b){let j={resourceArn:b};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(b){return JSON.stringify({rules:b.map((j)=>({rulePriority:j.rulePriority,description:j.description,selection:j.selection,action:j.action}))})}async getDockerLoginCommand(){let b=await this.getAuthorizationToken();if(!b.authorizationData?.[0])throw Error("Failed to get authorization token");let j=b.authorizationData[0],q=j.authorizationToken||"",v=j.proxyEndpoint||"";return`echo "${Buffer.from(q,"base64").toString("utf8").split(":")[1]}" | docker login --username AWS --password-stdin ${v}`}getRegistryUri(b){return`${b}.dkr.ecr.${this.region}.amazonaws.com`}parseRepository(b){return{repositoryArn:b.repositoryArn,registryId:b.registryId,repositoryName:b.repositoryName,repositoryUri:b.repositoryUri,createdAt:b.createdAt,imageTagMutability:b.imageTagMutability,imageScanningConfiguration:b.imageScanningConfiguration,encryptionConfiguration:b.encryptionConfiguration}}parseImageDetail(b){return{registryId:b.registryId,repositoryName:b.repositoryName,imageDigest:b.imageDigest,imageTags:b.imageTags,imageSizeInBytes:b.imageSizeInBytes,imagePushedAt:b.imagePushedAt,imageScanStatus:b.imageScanStatus,imageScanFindingsSummary:b.imageScanFindingsSummary}}}
2
- export{x as tf};
@@ -1,37 +0,0 @@
1
- var Y={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},C={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function X(q){return q.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function W(q){if(q.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(q))return!1;if(/\[[^\]]*\][+*]\{/.test(q))return!1;try{return new RegExp(q),!0}catch{return!1}}function R(q,V){let G=[],K=[],J=V;for(let H of q){if(H.enabled===!1)continue;if(H.key&&(H.key.source==="cookie"||H.key.source==="header")&&!H.key.name){K.push({ruleId:H.id,reason:"The rule keys on a header or cookie but names none."});continue}let $=H.path?_(H.path):".*";if(!W($)){K.push({ruleId:H.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let Z=[`SecRule REQUEST_URI "@rx ${X($)}"`];if(H.methods?.length)Z.push(` "chain,id:${J},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${X(H.id)}'"`);else Z.push(` "id:${J},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${X(H.id)}'"`);if(G.push(`# Marks requests governed by the ts-cloud rate limit "${X(H.id)}".`),G.push(Z.join(" \\\n")),H.methods?.length)G.push(` SecRule REQUEST_METHOD "@within ${X(H.methods.join(" ").toUpperCase())}" "t:none"`);G.push(""),J++}return{lines:G,unmapped:K}}function _(q){return`^${q.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function y(q={},V=[]){let G=q.mode??Y.mode,K=[],J=q.paranoiaLevel??Y.paranoiaLevel,H=q.inboundThreshold??Y.inboundThreshold,$=q.outboundThreshold??Y.outboundThreshold,Z=q.maxBodyBytes??Y.maxBodyBytes,j=q.rejectOversizedBody!==!1;if(G==="blocking"&&J>=3)K.push(`Paranoia level ${J} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(G==="blocking")K.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!j)K.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(q.bypassPaths?.length)K.push(`${q.bypassPaths.length} path(s) bypass inspection entirely.`);let Q=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${G}. Paranoia level: ${J}.`,""];if(G==="off")return Q.push("SecRuleEngine Off",""),{config:`${Q.join(`
2
- `)}
3
- `,unmappedRateLimits:[],warnings:K,mode:G};Q.push(`SecRuleEngine ${G==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${Z}`,`SecRequestBodyNoFilesLimit ${Math.min(Z,131072)}`,`SecRequestBodyLimitAction ${j?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${G==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${X(q.auditLogPath??Y.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${G==="blocking"?`deny,status:${q.blockStatus??Y.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${J}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${H}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${$}"`,'SecAction "id:900003,phase:1,pass,nolog,t:none,setvar:tx.critical_anomaly_score=5,setvar:tx.error_anomaly_score=4,setvar:tx.warning_anomaly_score=3,setvar:tx.notice_anomaly_score=2"','SecAction "id:900004,phase:1,pass,nolog,t:none,setvar:tx.anomaly_score=0"',"");let z=C.bypassBase;for(let N of q.bypassPaths??[]){let k=_(N);if(!W(k)){K.push(`Bypass path "${N}" was dropped: it compiles to an unsafe regular expression.`);continue}Q.push(`# Inspection bypass for ${X(N)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${X(k)}" "id:${z},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),z++}let B=C.exclusionBase;for(let N of q.exclusions??[]){if(!Number.isInteger(N.ruleId)||N.ruleId<=0){K.push(`Exclusion with rule id "${N.ruleId}" was dropped: the id is not a positive integer.`);continue}if(Q.push(`# ${X(N.reason)}`),N.pathPattern){if(!W(N.pathPattern)){K.push(`Exclusion for rule ${N.ruleId} was dropped: its path pattern is unsafe.`);continue}Q.push(`SecRule REQUEST_URI "@rx ${X(N.pathPattern)}" "id:${B},phase:1,pass,nolog,ctl:ruleRemoveById=${N.ruleId}"`),B++}else Q.push(`SecRuleRemoveById ${N.ruleId}`);Q.push("")}let M=R(V,C.rateLimitBase);if(M.lines.length>0)Q.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...M.lines);let O=C.customBase;for(let N of q.customRules??[])Q.push(`# Operator-supplied rule ${O}.`,N.trim(),""),O++;if(G==="blocking")Q.push("# Blocking decision: one rule, at the end, on the accumulated score.",`SecRule TX:ANOMALY_SCORE "@ge %{tx.inbound_anomaly_score_threshold}" "id:949110,phase:2,deny,status:${q.blockStatus??Y.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${Q.join(`
4
- `)}
5
- `,unmappedRateLimits:M.unmapped,warnings:K,mode:G}}function A(q={},V=[],G={}){let K=G.binary??"/usr/local/bin/zig-waf",J=G.configPath??"/etc/ts-cloud/waf.conf",H=y(q,V);return`#!/usr/bin/env bash
6
- # Managed by ts-cloud. Installs the zig-waf ruleset.
7
- set -euo pipefail
8
-
9
- if [ ! -x "${K}" ]; then
10
- echo "ts-cloud: ${K} is not installed; skipping WAF configuration" >&2
11
- exit 0
12
- fi
13
-
14
- install -d -m 0755 "$(dirname "${J}")"
15
- install -d -m 0750 /var/log/ts-cloud
16
-
17
- cat > "${J}.new" <<'WAF_EOF'
18
- ${H.config}WAF_EOF
19
-
20
- # Compile the config before it goes live. A config that does not validate
21
- # would leave the engine with no rules while still reporting itself enabled.
22
- if ! "${K}" validate "${J}.new"; then
23
- echo "ts-cloud: generated WAF config failed validation, keeping the previous one" >&2
24
- rm -f "${J}.new"
25
- exit 1
26
- fi
27
-
28
- if [ -f "${J}" ] && cmp -s "${J}.new" "${J}"; then
29
- rm -f "${J}.new"
30
- echo "ts-cloud: WAF config unchanged"
31
- exit 0
32
- fi
33
-
34
- mv "${J}.new" "${J}"
35
- echo "ts-cloud: WAF config installed (mode: ${H.mode})"
36
- `}function F(q,V){return q.map((G)=>({projectId:V.projectId,environmentId:V.environmentId,resourceId:V.resourceId,kind:"event",source:"zig-waf",name:G.action==="blocked"?"waf.blocked":"waf.matched",timestamp:G.timestamp,value:1,host:G.host,pathTemplate:G.path,method:G.method,attributes:{ruleId:G.ruleId??null,anomalyScore:G.anomalyScore,action:G.action,messages:G.messages.slice(0,5)}}))}
37
- export{X as fl,W as gl,_ as hl,y as il,A as jl,F as kl};
@@ -1 +0,0 @@
1
- import{ml as L}from"./chunk-b8e5wzwn.js";var _="\x00";function X(R,E){if(R==="*"||R==="**")return!0;let D=R.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${D}$`).test(E)}function A(R,E){if(R.startsWith("*.")){let D=R.slice(1);return E.endsWith(D)&&E.length>D.length}return R===E}function W(R,E){if(R.enabled===!1)return!1;if(R.methods?.length&&!R.methods.some((D)=>D.toUpperCase()===E.method.toUpperCase()))return!1;if(R.path&&!X(R.path,E.path))return!1;if(R.host&&!A(R.host,E.host??""))return!1;return!0}function Z(R,E){let D=R.key??{source:"ip"},F=D.fallbackToIp!==!1,H;if(D.source==="ip")H=E.ip;else if(D.source==="global")H="global";else if(D.source==="host")H=E.host??"";else if(D.source==="path")H=E.path;else if(D.source==="header")H=D.name?E.headers?.[D.name.toLowerCase()]:void 0;else if(D.source==="cookie")H=D.name?E.cookies?.[D.name]:void 0;if(!H&&D.source!=="global")H=F?E.ip:"__missing__";return`${R.id}\x00${H}`}class C{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(R,E=()=>Date.now(),D=1e5){this.clock=E;this.maxTrackedKeys=D;this.rules=[...R].sort((F,H)=>(F.priority??0)-(H.priority??0))}check(R){let E=this.clock(),D=this.rules.filter((j)=>W(j,R)),F;for(let j of D){let z=this.test(j,R,E);if(z.allowed)continue;if(!F||$(z.action)>$(F.action))F=z}if(F)return F;let H={action:"allow",allowed:!0};for(let j of D){let z=this.consume(j,R,E);if(z.remaining!=null&&(H.remaining??1/0)>z.remaining)H=z}return H}test(R,E,D){let F=Z(R,E);if((R.algorithm??"token_bucket")==="token_bucket"){let j=R.burst??R.limit,z=this.buckets.get(F),B=z?Math.min(j,z.tokens+this.refill(R,D-z.updatedAt)):j;if(B>=1)return{action:"allow",allowed:!0};return this.blocked(R,F,0,this.msPerToken(R)*(1-B),D)}let H=(this.windows.get(F)?.hits??[]).filter((j)=>j>D-R.windowMs);if(H.length<R.limit)return{action:"allow",allowed:!0};return this.blocked(R,F,0,H[0]+R.windowMs-D,D)}peek(R){let E=this.clock();for(let D of this.rules){if(!W(D,R))continue;let F=this.test(D,R,E);if(!F.allowed)return F}return{action:"allow",allowed:!0}}msPerToken(R){return R.windowMs/Math.max(1,R.limit)}refill(R,E){return Math.max(0,E)/this.msPerToken(R)}blocked(R,E,D,F,H){let j=R.action??"deny";return{action:j,allowed:j==="allow"||j==="log",ruleId:R.id,limit:R.limit,remaining:D,retryAfterMs:Math.max(0,Math.ceil(F)),resetAt:H+Math.max(0,F),key:E}}consume(R,E,D){let F=Z(R,E);if((R.algorithm??"token_bucket")==="token_bucket"){let J=R.burst??R.limit,V=this.buckets.get(F)??{tokens:J,updatedAt:D},Q=Math.min(J,V.tokens+this.refill(R,D-V.updatedAt));if(Q<1)return this.buckets.set(F,{tokens:Q,updatedAt:D}),this.blocked(R,F,0,this.msPerToken(R)*(1-Q),D);return this.evictIfNeeded(this.buckets),this.buckets.set(F,{tokens:Q-1,updatedAt:D}),{action:"allow",allowed:!0,ruleId:R.id,limit:J,remaining:Math.floor(Q-1),resetAt:D+this.msPerToken(R)*(J-(Q-1)),key:F}}let j=this.windows.get(F)??{hits:[]},z=D-R.windowMs,B=j.hits.filter((J)=>J>z);if(B.length>=R.limit)return this.windows.set(F,{hits:B}),this.blocked(R,F,0,B[0]+R.windowMs-D,D);return B.push(D),this.evictIfNeeded(this.windows),this.windows.set(F,{hits:B}),{action:"allow",allowed:!0,ruleId:R.id,limit:R.limit,remaining:R.limit-B.length,resetAt:B[0]+R.windowMs,key:F}}evictIfNeeded(R){if(R.size<this.maxTrackedKeys)return;let E=R.size-this.maxTrackedKeys+1,D=0;for(let F of R.keys())if(R.delete(F),++D>=E)break}sweep(){let R=this.clock(),E=0;for(let[D,F]of this.windows){let H=D.split("\x00")[0],j=this.rules.find((z)=>z.id===H);if(!j){this.windows.delete(D),E++;continue}if(F.hits.every((z)=>z<=R-j.windowMs))this.windows.delete(D),E++}for(let[D,F]of this.buckets){let H=D.split("\x00")[0],j=this.rules.find((z)=>z.id===H);if(!j||R-F.updatedAt>j.windowMs*2)this.buckets.delete(D),E++}return E}get trackedKeys(){return this.buckets.size+this.windows.size}}function $(R){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[R]}function O(R){let E={};if(R.limit!=null)E["ratelimit-limit"]=String(R.limit);if(R.remaining!=null)E["ratelimit-remaining"]=String(R.remaining);if(R.resetAt!=null)E["ratelimit-reset"]=String(Math.max(0,Math.ceil((R.resetAt-Date.now())/1000)));if(!R.allowed&&R.retryAfterMs!=null)E["retry-after"]=String(Math.max(1,Math.ceil(R.retryAfterMs/1000)));return E}function T(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var G="protection.controls",U=24,N=4,P={ipRules:{allow:[],block:[]}};function Y(R,E){if(!R?.enabled)return;return new Date(R.expiresAt).getTime()>E.getTime()?R:void 0}function I(R,E){let D=Number.isFinite(R)?Number(R):E;return Math.min(U,Math.max(0.25,D))}var K=500;class S{controlPlane;options;constructor(R,E={}){this.controlPlane=R;this.options=E}now(){return this.options.now?.()??new Date}read(){let R=this.controlPlane.getSetting(G);if(!R||typeof R!=="object"||Array.isArray(R))return{...P,ipRules:{allow:[],block:[]}};let E=R;return{attackMode:E.attackMode,mitigationPause:E.mitigationPause,ipRules:{allow:Array.isArray(E.ipRules?.allow)?E.ipRules.allow:[],block:Array.isArray(E.ipRules?.block)?E.ipRules.block:[]},updatedAt:E.updatedAt}}write(R){let E={...R,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(G,E),E}raw(){return this.read()}current(){let R=this.now(),E=this.read();return{attackMode:Y(E.attackMode,R),mitigationPause:Y(E.mitigationPause,R),ipRules:E.ipRules}}enableAttackMode(R){let E=this.now(),D={enabled:!0,startedAt:E.toISOString(),expiresAt:new Date(E.getTime()+I(R.hours,N)*3600000).toISOString(),reason:R.reason.trim()||"Attack mode enabled by an operator.",actorId:R.actorId};return this.write({...this.read(),attackMode:D}),D}disableAttackMode(){let R=this.read();if(!R.attackMode?.enabled)return!1;return this.write({...R,attackMode:{...R.attackMode,enabled:!1}}),!0}pauseMitigations(R){let E=R.reason.trim();if(!E)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let D=this.now(),F={enabled:!0,startedAt:D.toISOString(),expiresAt:new Date(D.getTime()+I(R.hours,U)*3600000).toISOString(),reason:E,actorId:R.actorId};return this.write({...this.read(),mitigationPause:F}),F}resumeMitigations(){let R=this.read();if(!R.mitigationPause?.enabled)return!1;return this.write({...R,mitigationPause:{...R.mitigationPause,enabled:!1}}),!0}addIpRule(R,E){let D=E.trim();if(!L(D))throw Error(`Not a valid IP or CIDR: ${E}`);let F=this.read(),H={...F.ipRules,[R]:[...new Set([...F.ipRules[R],D])]};if(H[R].length>K)throw Error(`At most ${K} ${R} rules are supported.`);let j=R==="allow"?"block":"allow";return H[j]=H[j].filter((z)=>z!==D),this.write({...F,ipRules:H}),H}removeIpRule(R,E){let D=this.read(),F={...D.ipRules,[R]:D.ipRules[R].filter((H)=>H!==E.trim())};return this.write({...D,ipRules:F}),F}}function b(R){if(R.mitigationPause)return{attackMode:!!R.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${R.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:R.mitigationPause.expiresAt};if(R.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${R.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:R.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function m(R,E){if(E.mitigationPause)return R.map((D)=>({...D,enabled:!1}));if(!E.attackMode)return[...R];return R.map((D)=>({...D,action:D.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(D.burst??D.limit,5))}))}function x(R,E){let D=[...new Set([...R.allowlist??[],...E.ipRules.allow])],F=[...new Set([...R.blocklist??[],...E.ipRules.block])];if(E.mitigationPause)return{...R,allowlist:D,blocklist:F,monitorOnly:!0};if(!E.attackMode)return{...R,allowlist:D,blocklist:F};let H=R.thresholds??{};return{...R,allowlist:D,blocklist:F,thresholds:{...H,newConnectionsPerSecond:Math.max(1,Math.floor((H.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((H.concurrentPerSource??100)/5))}}}function f(R,E){let D=R?.infrastructure?.compute;if(!D||D.ddos===!1)return R;let F=typeof D.ddos==="object"&&D.ddos!==null?D.ddos:{};return{...R,infrastructure:{...R.infrastructure,compute:{...D,ddos:x(F,E)}}}}export{_ as Sk,X as Tk,W as Uk,Z as Vk,C as Wk,O as Xk,T as Yk,G as Zk,U as _k,N as $k,S as al,b as bl,m as cl,x as dl,f as el};
@@ -1,34 +0,0 @@
1
- import{Pf as j}from"./chunk-wdzjbecg.js";import{Rh as E}from"./chunk-r3qf56b3.js";import{Th as L}from"./chunk-0ccta6z6.js";import{qt as W}from"./chunk-xt3s24vr.js";function h(z,D){let F=[`Action=${z}`,"Version=2010-05-08"];for(let[J,H]of Object.entries(D)){if(H===void 0||H===null)continue;if(Array.isArray(H))H.forEach((O,Z)=>{if(typeof O==="object"&&O!==null)for(let[$,_]of Object.entries(O))F.push(`${J}.member.${Z+1}.${$}=${encodeURIComponent(String(_))}`);else F.push(`${J}.member.${Z+1}=${encodeURIComponent(String(O))}`)});else if(typeof H==="object"){for(let[O,Z]of Object.entries(H))if(Z!==void 0&&Z!==null)F.push(`${J}.${O}=${encodeURIComponent(String(Z))}`)}else F.push(`${J}=${encodeURIComponent(String(H))}`)}return F.join("&")}function G(z,D){let F=new RegExp(`<${D}>([^<]*)</${D}>`),J=z.match(F);return J?J[1]:void 0}function Y(z,D,F){let J=new RegExp(`<${D}>([\\s\\S]*?)</${D}>`),H=z.match(J);if(!H)return[];let O=[],Z=new RegExp(`<${F}>([\\s\\S]*?)</${F}>`,"g"),$;while(($=Z.exec(H[1]))!==null)O.push($[1]);return O}class w{client;region;constructor(z="us-east-1",D){this.client=new L(void 0,{profile:D}),this.region=z}async request(z,D={}){let F=h(z,D);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:F})}async createUser(z){let D=await this.request("CreateUser",z);return this.parseUser(D)}async getUser(z={}){let D=await this.request("GetUser",z);return this.parseUser(D)}async listUsers(z={}){let D=await this.request("ListUsers",z),F=this.parseUsers(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Users:F,IsTruncated:J,Marker:H}}async updateUser(z){await this.request("UpdateUser",z)}async deleteUser(z){await this.request("DeleteUser",z)}parseUser(z){return{UserName:G(z,"UserName")||"",UserId:G(z,"UserId")||"",Arn:G(z,"Arn")||"",Path:G(z,"Path"),CreateDate:G(z,"CreateDate"),PasswordLastUsed:G(z,"PasswordLastUsed")}}parseUsers(z){return Y(z,"Users","member").map((F)=>({UserName:G(F,"UserName")||"",UserId:G(F,"UserId")||"",Arn:G(F,"Arn")||"",Path:G(F,"Path"),CreateDate:G(F,"CreateDate"),PasswordLastUsed:G(F,"PasswordLastUsed")}))}async createGroup(z){let D=await this.request("CreateGroup",z);return this.parseGroup(D)}async getGroup(z){let D=await this.request("GetGroup",z),F=this.parseGroup(D),J=this.parseUsers(D),H=G(D,"IsTruncated")==="true",O=G(D,"Marker");return{Group:F,Users:J,IsTruncated:H,Marker:O}}async listGroups(z={}){let D=await this.request("ListGroups",z),F=this.parseGroups(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Groups:F,IsTruncated:J,Marker:H}}async updateGroup(z){await this.request("UpdateGroup",z)}async deleteGroup(z){await this.request("DeleteGroup",z)}async addUserToGroup(z){await this.request("AddUserToGroup",z)}async removeUserFromGroup(z){await this.request("RemoveUserFromGroup",z)}async listGroupsForUser(z){let D=await this.request("ListGroupsForUser",z),F=this.parseGroups(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Groups:F,IsTruncated:J,Marker:H}}parseGroup(z){return{GroupName:G(z,"GroupName")||"",GroupId:G(z,"GroupId")||"",Arn:G(z,"Arn")||"",Path:G(z,"Path"),CreateDate:G(z,"CreateDate")}}parseGroups(z){return Y(z,"Groups","member").map((F)=>({GroupName:G(F,"GroupName")||"",GroupId:G(F,"GroupId")||"",Arn:G(F,"Arn")||"",Path:G(F,"Path"),CreateDate:G(F,"CreateDate")}))}async createRole(z){let D=await this.request("CreateRole",z);return this.parseRole(D)}async getRole(z){let D=await this.request("GetRole",z);return this.parseRole(D)}async listRoles(z={}){let D=await this.request("ListRoles",z),F=this.parseRoles(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Roles:F,IsTruncated:J,Marker:H}}async updateRole(z){await this.request("UpdateRole",z)}async updateRoleDescription(z){let D=await this.request("UpdateRoleDescription",z);return this.parseRole(D)}async updateAssumeRolePolicy(z){await this.request("UpdateAssumeRolePolicy",z)}async deleteRole(z){await this.request("DeleteRole",z)}async tagRole(z){await this.request("TagRole",z)}async untagRole(z){await this.request("UntagRole",z)}async listRoleTags(z){let D=await this.request("ListRoleTags",z),F=this.parseTags(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Tags:F,IsTruncated:J,Marker:H}}parseRole(z){return{RoleName:G(z,"RoleName")||"",RoleId:G(z,"RoleId")||"",Arn:G(z,"Arn")||"",Path:G(z,"Path"),CreateDate:G(z,"CreateDate"),AssumeRolePolicyDocument:G(z,"AssumeRolePolicyDocument"),Description:G(z,"Description"),MaxSessionDuration:G(z,"MaxSessionDuration")?Number.parseInt(G(z,"MaxSessionDuration"),10):void 0}}parseRoles(z){return Y(z,"Roles","member").map((F)=>({RoleName:G(F,"RoleName")||"",RoleId:G(F,"RoleId")||"",Arn:G(F,"Arn")||"",Path:G(F,"Path"),CreateDate:G(F,"CreateDate"),AssumeRolePolicyDocument:G(F,"AssumeRolePolicyDocument"),Description:G(F,"Description"),MaxSessionDuration:G(F,"MaxSessionDuration")?Number.parseInt(G(F,"MaxSessionDuration"),10):void 0}))}parseTags(z){return Y(z,"Tags","member").map((F)=>({Key:G(F,"Key")||"",Value:G(F,"Value")||""}))}async createPolicy(z){let D=await this.request("CreatePolicy",z);return this.parsePolicy(D)}async getPolicy(z){let D=await this.request("GetPolicy",z);return this.parsePolicy(D)}async getPolicyVersion(z){let D=await this.request("GetPolicyVersion",z);return{VersionId:G(D,"VersionId")||"",IsDefaultVersion:G(D,"IsDefaultVersion")==="true",CreateDate:G(D,"CreateDate"),Document:G(D,"Document")}}async listPolicies(z={}){let D=await this.request("ListPolicies",z),F=this.parsePolicies(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Policies:F,IsTruncated:J,Marker:H}}async listPolicyVersions(z){let D=await this.request("ListPolicyVersions",z),F=this.parsePolicyVersions(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Versions:F,IsTruncated:J,Marker:H}}async createPolicyVersion(z){let D=await this.request("CreatePolicyVersion",z);return{VersionId:G(D,"VersionId")||"",IsDefaultVersion:G(D,"IsDefaultVersion")==="true",CreateDate:G(D,"CreateDate")}}async deletePolicyVersion(z){await this.request("DeletePolicyVersion",z)}async setDefaultPolicyVersion(z){await this.request("SetDefaultPolicyVersion",z)}async deletePolicy(z){await this.request("DeletePolicy",z)}async attachUserPolicy(z){await this.request("AttachUserPolicy",z)}async detachUserPolicy(z){await this.request("DetachUserPolicy",z)}async attachGroupPolicy(z){await this.request("AttachGroupPolicy",z)}async detachGroupPolicy(z){await this.request("DetachGroupPolicy",z)}async attachRolePolicy(z){await this.request("AttachRolePolicy",z)}async detachRolePolicy(z){await this.request("DetachRolePolicy",z)}async listAttachedUserPolicies(z){let D=await this.request("ListAttachedUserPolicies",z),F=this.parseAttachedPolicies(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{AttachedPolicies:F,IsTruncated:J,Marker:H}}async listAttachedGroupPolicies(z){let D=await this.request("ListAttachedGroupPolicies",z),F=this.parseAttachedPolicies(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{AttachedPolicies:F,IsTruncated:J,Marker:H}}async listAttachedRolePolicies(z){let D=await this.request("ListAttachedRolePolicies",z),F=this.parseAttachedPolicies(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{AttachedPolicies:F,IsTruncated:J,Marker:H}}parsePolicy(z){return{PolicyName:G(z,"PolicyName")||"",PolicyId:G(z,"PolicyId")||"",Arn:G(z,"Arn")||"",Path:G(z,"Path"),DefaultVersionId:G(z,"DefaultVersionId"),AttachmentCount:G(z,"AttachmentCount")?Number.parseInt(G(z,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:G(z,"PermissionsBoundaryUsageCount")?Number.parseInt(G(z,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:G(z,"IsAttachable")==="true",Description:G(z,"Description"),CreateDate:G(z,"CreateDate"),UpdateDate:G(z,"UpdateDate")}}parsePolicies(z){return Y(z,"Policies","member").map((F)=>({PolicyName:G(F,"PolicyName")||"",PolicyId:G(F,"PolicyId")||"",Arn:G(F,"Arn")||"",Path:G(F,"Path"),DefaultVersionId:G(F,"DefaultVersionId"),AttachmentCount:G(F,"AttachmentCount")?Number.parseInt(G(F,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:G(F,"PermissionsBoundaryUsageCount")?Number.parseInt(G(F,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:G(F,"IsAttachable")==="true",Description:G(F,"Description"),CreateDate:G(F,"CreateDate"),UpdateDate:G(F,"UpdateDate")}))}parsePolicyVersions(z){return Y(z,"Versions","member").map((F)=>({VersionId:G(F,"VersionId")||"",IsDefaultVersion:G(F,"IsDefaultVersion")==="true",CreateDate:G(F,"CreateDate")}))}parseAttachedPolicies(z){return Y(z,"AttachedPolicies","member").map((F)=>({PolicyName:G(F,"PolicyName")||"",PolicyArn:G(F,"PolicyArn")||""}))}async putUserPolicy(z){await this.request("PutUserPolicy",z)}async getUserPolicy(z){let D=await this.request("GetUserPolicy",z);return{UserName:G(D,"UserName")||"",PolicyName:G(D,"PolicyName")||"",PolicyDocument:decodeURIComponent(G(D,"PolicyDocument")||"")}}async deleteUserPolicy(z){await this.request("DeleteUserPolicy",z)}async listUserPolicies(z){let D=await this.request("ListUserPolicies",z),F=Y(D,"PolicyNames","member"),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{PolicyNames:F,IsTruncated:J,Marker:H}}async putGroupPolicy(z){await this.request("PutGroupPolicy",z)}async getGroupPolicy(z){let D=await this.request("GetGroupPolicy",z);return{GroupName:G(D,"GroupName")||"",PolicyName:G(D,"PolicyName")||"",PolicyDocument:decodeURIComponent(G(D,"PolicyDocument")||"")}}async deleteGroupPolicy(z){await this.request("DeleteGroupPolicy",z)}async listGroupPolicies(z){let D=await this.request("ListGroupPolicies",z),F=Y(D,"PolicyNames","member"),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{PolicyNames:F,IsTruncated:J,Marker:H}}async putRolePolicy(z){await this.request("PutRolePolicy",z)}async getRolePolicy(z){let D=await this.request("GetRolePolicy",z);return{RoleName:G(D,"RoleName")||"",PolicyName:G(D,"PolicyName")||"",PolicyDocument:decodeURIComponent(G(D,"PolicyDocument")||"")}}async deleteRolePolicy(z){await this.request("DeleteRolePolicy",z)}async listRolePolicies(z){let D=await this.request("ListRolePolicies",z),F=Y(D,"PolicyNames","member"),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{PolicyNames:F,IsTruncated:J,Marker:H}}async createAccessKey(z={}){let D=await this.request("CreateAccessKey",z);if(typeof D==="object"){let F=D?.CreateAccessKeyResult?.AccessKey||D?.AccessKey;if(F)return{AccessKey:{UserName:F.UserName||"",AccessKeyId:F.AccessKeyId||"",Status:F.Status||"Active",SecretAccessKey:F.SecretAccessKey||"",CreateDate:F.CreateDate}}}return{AccessKey:{UserName:G(D,"UserName")||"",AccessKeyId:G(D,"AccessKeyId")||"",Status:G(D,"Status")||"Active",SecretAccessKey:G(D,"SecretAccessKey")||"",CreateDate:G(D,"CreateDate")}}}async listAccessKeys(z={}){let D=await this.request("ListAccessKeys",z),F=this.parseAccessKeys(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{AccessKeyMetadata:F,IsTruncated:J,Marker:H}}async updateAccessKey(z){await this.request("UpdateAccessKey",z)}async deleteAccessKey(z){await this.request("DeleteAccessKey",z)}async getAccessKeyLastUsed(z){let D=await this.request("GetAccessKeyLastUsed",z);return{UserName:G(D,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:G(D,"LastUsedDate"),ServiceName:G(D,"ServiceName"),Region:G(D,"Region")}}}parseAccessKeys(z){return Y(z,"AccessKeyMetadata","member").map((F)=>({UserName:G(F,"UserName"),AccessKeyId:G(F,"AccessKeyId")||"",Status:G(F,"Status")||"Active",CreateDate:G(F,"CreateDate")}))}async createInstanceProfile(z){let D=await this.request("CreateInstanceProfile",z);return this.parseInstanceProfile(D)}async getInstanceProfile(z){let D=await this.request("GetInstanceProfile",z);return this.parseInstanceProfile(D)}async listInstanceProfiles(z={}){let D=await this.request("ListInstanceProfiles",z),F=this.parseInstanceProfiles(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{InstanceProfiles:F,IsTruncated:J,Marker:H}}async listInstanceProfilesForRole(z){let D=await this.request("ListInstanceProfilesForRole",z),F=this.parseInstanceProfiles(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{InstanceProfiles:F,IsTruncated:J,Marker:H}}async addRoleToInstanceProfile(z){await this.request("AddRoleToInstanceProfile",z)}async removeRoleFromInstanceProfile(z){await this.request("RemoveRoleFromInstanceProfile",z)}async deleteInstanceProfile(z){await this.request("DeleteInstanceProfile",z)}parseInstanceProfile(z){return{InstanceProfileName:G(z,"InstanceProfileName")||"",InstanceProfileId:G(z,"InstanceProfileId")||"",Arn:G(z,"Arn")||"",Path:G(z,"Path"),CreateDate:G(z,"CreateDate")}}parseInstanceProfiles(z){return Y(z,"InstanceProfiles","member").map((F)=>({InstanceProfileName:G(F,"InstanceProfileName")||"",InstanceProfileId:G(F,"InstanceProfileId")||"",Arn:G(F,"Arn")||"",Path:G(F,"Path"),CreateDate:G(F,"CreateDate")}))}async getAccountPasswordPolicy(){let z=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:G(z,"MinimumPasswordLength")?Number.parseInt(G(z,"MinimumPasswordLength"),10):void 0,RequireSymbols:G(z,"RequireSymbols")==="true",RequireNumbers:G(z,"RequireNumbers")==="true",RequireUppercaseCharacters:G(z,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:G(z,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:G(z,"AllowUsersToChangePassword")==="true",ExpirePasswords:G(z,"ExpirePasswords")==="true",MaxPasswordAge:G(z,"MaxPasswordAge")?Number.parseInt(G(z,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:G(z,"PasswordReusePrevention")?Number.parseInt(G(z,"PasswordReusePrevention"),10):void 0,HardExpiry:G(z,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(z){await this.request("UpdateAccountPasswordPolicy",z)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let z=await this.request("GetAccountSummary"),D={},F=Y(z,"SummaryMap","entry");for(let J of F){let H=G(J,"key"),O=G(J,"value");if(H&&O)D[H]=Number.parseInt(O,10)}return D}async listAccountAliases(){let z=await this.request("ListAccountAliases"),D=Y(z,"AccountAliases","member"),F=G(z,"IsTruncated")==="true",J=G(z,"Marker");return{AccountAliases:D,IsTruncated:F,Marker:J}}async createAccountAlias(z){await this.request("CreateAccountAlias",z)}async deleteAccountAlias(z){await this.request("DeleteAccountAlias",z)}async simulatePrincipalPolicy(z){let D=await this.request("SimulatePrincipalPolicy",z);return this.parseSimulationResults(D)}parseSimulationResults(z){let F=Y(z,"EvaluationResults","member").map((O)=>{let $=Y(O,"MatchedStatements","member").map((_)=>({SourcePolicyId:G(_,"SourcePolicyId"),SourcePolicyType:G(_,"SourcePolicyType")}));return{EvalActionName:G(O,"EvalActionName")||"",EvalResourceName:G(O,"EvalResourceName"),EvalDecision:G(O,"EvalDecision")||"",MatchedStatements:$.length>0?$:void 0}}),J=G(z,"IsTruncated")==="true",H=G(z,"Marker");return{EvaluationResults:F,IsTruncated:J,Marker:H}}}class U{client;region;constructor(z="us-east-1",D){this.region=z,this.client=new L(D)}async createEmailIdentity(z){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(z)})}async getEmailIdentity(z){let D=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(z)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:D.IdentityType,IdentityName:z,SendingEnabled:D.VerifiedForSendingStatus,VerificationStatus:D.VerificationStatus,DkimAttributes:D.DkimAttributes,MailFromAttributes:D.MailFromAttributes}}async putEmailIdentityMailFromAttributes(z,D){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(z)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(D)})}async listEmailIdentities(z){let D="/v2/email/identities",F=[];if(z?.PageSize)F.push(`PageSize=${z.PageSize}`);if(z?.NextToken)F.push(`NextToken=${encodeURIComponent(z.NextToken)}`);if(F.length>0)D+=`?${F.join("&")}`;let J=await this.client.request({service:"email",region:this.region,method:"GET",path:D,headers:{"Content-Type":"application/json"}});return{EmailIdentities:J.EmailIdentities,NextToken:J.NextToken}}async deleteEmailIdentity(z){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(z)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(z){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(z.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:z.SigningEnabled})})}async sendEmail(z){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(z)})).MessageId}}async sendBulkEmail(z){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(z)})).BulkEmailEntryResults}}async createEmailTemplate(z){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(z)})}async getEmailTemplate(z){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(z)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(z){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(z)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(z){let D="/v2/email/templates",F=[];if(z?.PageSize)F.push(`PageSize=${z.PageSize}`);if(z?.NextToken)F.push(`NextToken=${encodeURIComponent(z.NextToken)}`);if(F.length>0)D+=`?${F.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:D,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 D=(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:D?.Max24HourSend?Number(D.Max24HourSend):void 0,MaxSendRate:D?.MaxSendRate?Number(D.MaxSendRate):void 0,SentLast24Hours:D?.SentLast24Hours?Number(D.SentLast24Hours):void 0}}async verifyDomain(z){let D=await this.createEmailIdentity({EmailIdentity:z});return{dkimTokens:D.DkimAttributes?.Tokens,verificationStatus:D.DkimAttributes?.Status}}async sendSimpleEmail(z){let D=Array.isArray(z.to)?z.to:[z.to],F=z.replyTo?Array.isArray(z.replyTo)?z.replyTo:[z.replyTo]:void 0,J={};if(z.text)J.Text={Data:z.text};if(z.html)J.Html={Data:z.html};return this.sendEmail({FromEmailAddress:z.from,Destination:{ToAddresses:D},Content:{Simple:{Subject:{Data:z.subject},Body:J}},ReplyToAddresses:F})}async sendTemplatedEmail(z){let D=Array.isArray(z.to)?z.to:[z.to],F=z.replyTo?Array.isArray(z.replyTo)?z.replyTo:[z.replyTo]:void 0;return this.sendEmail({FromEmailAddress:z.from,Destination:{ToAddresses:D},Content:{Template:{TemplateName:z.templateName,TemplateData:JSON.stringify(z.templateData)}},ReplyToAddresses:F})}async getDkimRecords(z){let D=await this.getEmailIdentity(z);if(!D.DkimAttributes?.Tokens)return[];return D.DkimAttributes.Tokens.map((F)=>({name:`${F}._domainkey.${z}`,type:"CNAME",value:`${F}.dkim.amazonses.com`}))}async isDomainVerified(z){try{let D=await this.getEmailIdentity(z);return D.VerificationStatus==="SUCCESS"&&D.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(z,D=60,F=30000){for(let J=0;J<D;J++){if(await this.isDomainVerified(z))return!0;await new Promise((O)=>setTimeout(O,F))}return!1}buildFormBody(z){return Object.entries(z).filter(([,F])=>F!==void 0).map(([F,J])=>`${encodeURIComponent(F)}=${encodeURIComponent(J)}`).join("&")}async createReceiptRuleSet(z){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:z})})}async deleteReceiptRuleSet(z){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:z})})}async setActiveReceiptRuleSet(z){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:z})})}async listReceiptRuleSets(z){let D={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(z)D.NextToken=z;let F=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(D)}),J=F?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||F?.ListReceiptRuleSetsResult,H=J?.RuleSets?.member;return{RuleSets:Array.isArray(H)?H:H?[H]:[],NextToken:J?.NextToken}}async describeReceiptRuleSet(z){let D=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:z})}),F=D?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||D?.DescribeReceiptRuleSetResult,J=F?.Rules?.member;return{Metadata:F?.Metadata,Rules:Array.isArray(J)?J:J?[J]:[]}}async createReceiptRule(z){let D={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:z.RuleSetName,"Rule.Name":z.Rule.Name,"Rule.Enabled":z.Rule.Enabled!==!1?"true":"false"};if(z.Rule.TlsPolicy)D["Rule.TlsPolicy"]=z.Rule.TlsPolicy;if(z.Rule.ScanEnabled!==void 0)D["Rule.ScanEnabled"]=z.Rule.ScanEnabled?"true":"false";if(z.After)D.After=z.After;if(z.Rule.Recipients)z.Rule.Recipients.forEach((F,J)=>{D[`Rule.Recipients.member.${J+1}`]=F});z.Rule.Actions.forEach((F,J)=>{let H=J+1;if(F.S3Action){if(D[`Rule.Actions.member.${H}.S3Action.BucketName`]=F.S3Action.BucketName,F.S3Action.ObjectKeyPrefix)D[`Rule.Actions.member.${H}.S3Action.ObjectKeyPrefix`]=F.S3Action.ObjectKeyPrefix;if(F.S3Action.KmsKeyArn)D[`Rule.Actions.member.${H}.S3Action.KmsKeyArn`]=F.S3Action.KmsKeyArn}if(F.LambdaAction)D[`Rule.Actions.member.${H}.LambdaAction.FunctionArn`]=F.LambdaAction.FunctionArn,D[`Rule.Actions.member.${H}.LambdaAction.InvocationType`]=F.LambdaAction.InvocationType||"Event";if(F.SNSAction){if(D[`Rule.Actions.member.${H}.SNSAction.TopicArn`]=F.SNSAction.TopicArn,F.SNSAction.Encoding)D[`Rule.Actions.member.${H}.SNSAction.Encoding`]=F.SNSAction.Encoding}if(F.StopAction){if(D[`Rule.Actions.member.${H}.StopAction.Scope`]=F.StopAction.Scope,F.StopAction.TopicArn)D[`Rule.Actions.member.${H}.StopAction.TopicArn`]=F.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(D)})}async deleteReceiptRule(z,D){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:z,RuleName:D})})}async receiptRuleSetExists(z){try{return await this.describeReceiptRuleSet(z),!0}catch(D){if(D.code==="RuleSetDoesNotExist"||D.statusCode===400)return!1;throw D}}async getActiveReceiptRuleSet(){let z=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"})}),D=z?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||z?.DescribeActiveReceiptRuleSetResult;if(!D?.Metadata)return null;let F=D?.Rules?.member;return{Metadata:D?.Metadata,Rules:Array.isArray(F)?F:F?[F]:[]}}async updateReceiptRule(z){let D={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:z.RuleSetName,"Rule.Name":z.Rule.Name};if(z.Rule.Enabled!==void 0)D["Rule.Enabled"]=z.Rule.Enabled?"true":"false";if(z.Rule.TlsPolicy)D["Rule.TlsPolicy"]=z.Rule.TlsPolicy;if(z.Rule.ScanEnabled!==void 0)D["Rule.ScanEnabled"]=z.Rule.ScanEnabled?"true":"false";if(z.Rule.Recipients)z.Rule.Recipients.forEach((F,J)=>{D[`Rule.Recipients.member.${J+1}`]=F});z.Rule.Actions.forEach((F,J)=>{let H=J+1;if(F.S3Action){if(D[`Rule.Actions.member.${H}.S3Action.BucketName`]=F.S3Action.BucketName,F.S3Action.ObjectKeyPrefix)D[`Rule.Actions.member.${H}.S3Action.ObjectKeyPrefix`]=F.S3Action.ObjectKeyPrefix;if(F.S3Action.KmsKeyArn)D[`Rule.Actions.member.${H}.S3Action.KmsKeyArn`]=F.S3Action.KmsKeyArn}if(F.LambdaAction)D[`Rule.Actions.member.${H}.LambdaAction.FunctionArn`]=F.LambdaAction.FunctionArn,D[`Rule.Actions.member.${H}.LambdaAction.InvocationType`]=F.LambdaAction.InvocationType||"Event";if(F.SNSAction){if(D[`Rule.Actions.member.${H}.SNSAction.TopicArn`]=F.SNSAction.TopicArn,F.SNSAction.Encoding)D[`Rule.Actions.member.${H}.SNSAction.Encoding`]=F.SNSAction.Encoding}if(F.StopAction){if(D[`Rule.Actions.member.${H}.StopAction.Scope`]=F.StopAction.Scope,F.StopAction.TopicArn)D[`Rule.Actions.member.${H}.StopAction.TopicArn`]=F.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(D)})}async sendRawEmail(z){let D=Buffer.from(z.rawMessage).toString("base64"),F={Action:"SendRawEmail",Version:"2010-12-01",Source:z.source,"RawMessage.Data":D};z.destinations.forEach((O,Z)=>{F[`Destinations.member.${Z+1}`]=O});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(F)});return{MessageId:(J?.SendRawEmailResponse?.SendRawEmailResult||J?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(z){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(z)}`}))?.SuppressedDestination||null}catch(D){if(D.message?.includes("404")||D.message?.includes("NotFoundException"))return null;throw D}}async deleteSuppressedDestination(z){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(z)}`})}}class M{ses;s3;iam;route53;region;domain;defaultFrom;constructor(z={}){this.region=z.region||"us-east-1",this.domain=z.domain,this.defaultFrom=z.defaultFrom,this.ses=new U(this.region),this.s3=new E(this.region),this.iam=new w(this.region),this.route53=new j(this.region)}async send(z){let D=z.from||this.defaultFrom;if(!D)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let F=z.fromName?`${z.fromName} <${D}>`:D,J=Array.isArray(z.to)?z.to:[z.to];if(!z.attachments||z.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:F,to:J,subject:z.subject,text:z.text,html:z.html,replyTo:z.replyTo})).MessageId||""};let H=this.buildRawEmail(z,F,J);return{messageId:(await this.ses.sendEmail({FromEmailAddress:F,Destination:{ToAddresses:J,CcAddresses:z.cc?Array.isArray(z.cc)?z.cc:[z.cc]:void 0,BccAddresses:z.bcc?Array.isArray(z.bcc)?z.bcc:[z.bcc]:void 0},Content:{Raw:{Data:Buffer.from(H).toString("base64")}}})).MessageId||""}}async sendTemplate(z){let D=z.from||this.defaultFrom;if(!D)throw Error("From address is required");let F=z.fromName?`${z.fromName} <${D}>`:D;return{messageId:(await this.ses.sendTemplatedEmail({from:F,to:z.to,templateName:z.templateName,templateData:z.templateData,replyTo:z.replyTo})).MessageId||""}}async sendBulk(z){let D=z.from||this.defaultFrom;if(!D)throw Error("From address is required");let F=z.recipients.map((H)=>({Destination:{ToAddresses:Array.isArray(H.to)?H.to:[H.to]},ReplacementEmailContent:H.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(H.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:D,BulkEmailEntries:F,DefaultContent:{Template:{TemplateName:z.templateName,TemplateData:JSON.stringify(z.defaultTemplateData)}}})).BulkEmailEntryResults?.map((H)=>({status:H.Status||"UNKNOWN",messageId:H.MessageId,error:H.Error}))||[]}}async setupDomain(z){let D;try{D=await this.ses.getEmailIdentity(z)}catch{let J=await this.ses.createEmailIdentity({EmailIdentity:z});D={VerificationStatus:J.DkimAttributes?.Status,DkimAttributes:J.DkimAttributes,SendingEnabled:J.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:z,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(z,{MailFromDomain:`mail.${z}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let F=await this.ses.getDkimRecords(z);return{domainVerified:D.SendingEnabled===!0,dkimStatus:D.DkimAttributes?.Status||"UNKNOWN",dkimTokens:D.DkimAttributes?.Tokens,mailFromStatus:D.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(z){let D=[],F=await this.ses.getDkimRecords(z);for(let J of F)D.push({type:J.type,name:J.name,value:J.value,ttl:1800});return D.push({type:"MX",name:z,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),D.push({type:"MX",name:`mail.${z}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),D.push({type:"TXT",name:`mail.${z}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),D.push({type:"TXT",name:`_dmarc.${z}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${z}`,ttl:3600}),D}async isDomainReady(z){try{let D=await this.ses.getEmailIdentity(z);return D.SendingEnabled===!0&&D.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(z){let D={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${z.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":z.accountId}}}]};await this.s3.putBucketPolicy(z.bucketName,D);try{await this.ses.createReceiptRuleSet(z.ruleSetName)}catch(J){if(!J.message?.includes("already exists")&&J.code!=="AlreadyExists")throw J}let F=[{S3Action:{BucketName:z.bucketName,ObjectKeyPrefix:z.prefix||"inbox/"}}];if(z.lambdaArn)F.push({LambdaAction:{FunctionArn:z.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:z.ruleSetName,Rule:{Name:z.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:z.recipients||[z.domain],ScanEnabled:z.scanEnabled!==!1,Actions:F}})}catch(J){if(J.message?.includes("already exists"))await this.ses.deleteReceiptRule(z.ruleSetName,z.ruleName),await this.ses.createReceiptRule({RuleSetName:z.ruleSetName,Rule:{Name:z.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:z.recipients||[z.domain],ScanEnabled:z.scanEnabled!==!1,Actions:F}});else throw J}await this.ses.setActiveReceiptRuleSet(z.ruleSetName)}async getIncomingEmails(z){return(await this.s3.list({bucket:z.bucket,prefix:z.prefix||"incoming/",maxKeys:z.maxResults||100})).map((F)=>({key:F.Key||"",lastModified:F.LastModified||"",size:F.Size||0}))}async readEmail(z){return await this.s3.getObject(z.bucket,z.key)}async createSmtpCredentials(z){let D=`ses-smtp-${z.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:F}=await import("./chunk-ww8k3g7j.js"),J=new F,H=(Q,C)=>{let I={Action:Q,Version:"2010-05-08",...C};return Object.entries(I).map(([R,K])=>`${encodeURIComponent(R)}=${encodeURIComponent(K)}`).join("&")};try{await J.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H("CreateUser",{UserName:D})})}catch(Q){if(!Q.message?.includes("EntityAlreadyExists"))throw Q}let O={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${z.domain}`}}}]},Z=`ses-smtp-policy-${z.domain.replace(/\./g,"-")}`;try{await J.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H("PutUserPolicy",{UserName:D,PolicyName:Z,PolicyDocument:JSON.stringify(O)})})}catch{}let _=(await J.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H("CreateAccessKey",{UserName:D})}))?.CreateAccessKeyResult?.AccessKey;if(!_?.AccessKeyId||!_?.SecretAccessKey)throw Error("Failed to create access key");let B=this.deriveSmtpPassword(_.SecretAccessKey);return{username:_.AccessKeyId,password:B,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(z){let D=W("node:crypto"),F="SendRawEmail",J=Buffer.from([4]),H=D.createHmac("sha256",`AWS4${z}`).update("11111111").digest();return H=D.createHmac("sha256",H).update(this.region).digest(),H=D.createHmac("sha256",H).update("ses").digest(),H=D.createHmac("sha256",H).update("aws4_request").digest(),H=D.createHmac("sha256",H).update("SendRawEmail").digest(),Buffer.concat([J,H]).toString("base64")}async createTemplate(z){await this.ses.createEmailTemplate({TemplateName:z.name,TemplateContent:{Subject:z.subject,Text:z.text,Html:z.html}})}async getTemplate(z){try{let D=await this.ses.getEmailTemplate(z);return{name:D.TemplateName||z,subject:D.TemplateContent?.Subject,text:D.TemplateContent?.Text,html:D.TemplateContent?.Html}}catch{return null}}async deleteTemplate(z){await this.ses.deleteEmailTemplate(z)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((D)=>({name:D.TemplateName||"",createdAt:D.CreatedTimestamp}))||[]}async deploy(z){let D=`${z.appName}-${z.environment}-email-rules`,F=`${z.appName}-inbound-email`,J=z.storage?.bucketName||`${z.appName}-${z.environment}-email`,H=await this.setupDomain(z.domain);if(!(await this.s3.listBuckets()).Buckets?.some((_)=>_.Name===J))await this.s3.createBucket(J);await this.setupReceiving({domain:z.domain,ruleSetName:D,ruleName:F,bucketName:J,prefix:z.storage?.prefix||"inbox/",accountId:z.accountId,recipients:z.catchAll?[z.domain]:z.mailboxes,scanEnabled:!0});let $=await this.getDnsRecords(z.domain);return{success:!0,domainVerified:H.domainVerified,dkimStatus:H.dkimStatus,receiptRuleSet:D,storageBucket:J,dnsRecords:$}}async undeploy(z){let D=`${z.appName}-${z.environment}-email-rules`,F=`${z.appName}-inbound-email`,J=`${z.appName}-${z.environment}-email`;try{await this.ses.deleteReceiptRule(D,F)}catch{}try{await this.ses.deleteReceiptRuleSet(D)}catch{}if(z.deleteBucket)try{await this.s3.emptyAndDeleteBucket(J)}catch{}}async getSendingStats(){let z=await this.ses.getSendQuota();return{sentLast24Hours:z.SentLast24Hours||0,maxSendRate:z.MaxSendRate||0,max24HourSend:z.Max24HourSend||0}}buildRawEmail(z,D,F){let J=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,H="";if(H+=`From: ${D}\r
2
- `,H+=`To: ${F.join(", ")}\r
3
- `,z.cc){let O=Array.isArray(z.cc)?z.cc:[z.cc];H+=`Cc: ${O.join(", ")}\r
4
- `}if(H+=`Subject: ${z.subject}\r
5
- `,H+=`MIME-Version: 1.0\r
6
- `,H+=`Content-Type: multipart/mixed; boundary="${J}"\r
7
- `,H+=`\r
8
- `,z.text||z.html)if(H+=`--${J}\r
9
- `,z.html&&z.text){let O=`----=_Alt_${Date.now()}`;H+=`Content-Type: multipart/alternative; boundary="${O}"\r
10
- `,H+=`\r
11
- `,H+=`--${O}\r
12
- `,H+=`Content-Type: text/plain; charset="UTF-8"\r
13
- `,H+=`\r
14
- `,H+=`${z.text}\r
15
- `,H+=`--${O}\r
16
- `,H+=`Content-Type: text/html; charset="UTF-8"\r
17
- `,H+=`\r
18
- `,H+=`${z.html}\r
19
- `,H+=`--${O}--\r
20
- `}else if(z.html)H+=`Content-Type: text/html; charset="UTF-8"\r
21
- `,H+=`\r
22
- `,H+=`${z.html}\r
23
- `;else H+=`Content-Type: text/plain; charset="UTF-8"\r
24
- `,H+=`\r
25
- `,H+=`${z.text}\r
26
- `;if(z.attachments)for(let O of z.attachments)H+=`--${J}\r
27
- `,H+=`Content-Type: ${O.contentType||"application/octet-stream"}; name="${O.filename}"\r
28
- `,H+=`Content-Transfer-Encoding: base64\r
29
- `,H+=`Content-Disposition: attachment; filename="${O.filename}"\r
30
- `,H+=`\r
31
- `,H+=`${O.content}\r
32
- `;return H+=`--${J}--\r
33
- `,H}}var y=new M;
34
- export{w as of,U as pf,M as qf,y as rf};
@@ -1,2 +0,0 @@
1
- import{Th as T,Uh as J}from"./chunk-0ccta6z6.js";class U{client;region;constructor(k="us-east-1"){this.region=k,this.client=new T}async describeDBInstances(k){let w={Action:"DescribeDBInstances",Version:"2014-10-31"};if(k?.DBInstanceIdentifier)w.DBInstanceIdentifier=k.DBInstanceIdentifier;if(k?.MaxRecords)w.MaxRecords=k.MaxRecords;if(k?.Marker)w.Marker=k.Marker;if(k?.Filters)k.Filters.forEach((K,L)=>{w[`Filters.Filter.${L+1}.Name`]=K.Name,K.Values.forEach((O,R)=>{w[`Filters.Filter.${L+1}.Values.Value.${R+1}`]=O})});let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E}),H=z.DescribeDBInstancesResult||z,G=H.DBInstances?.DBInstance||[];if(!Array.isArray(G))G=G?[G]:[];return{DBInstances:G,Marker:H.Marker}}async describeDBInstance(k){return(await this.describeDBInstances({DBInstanceIdentifier:k})).DBInstances?.[0]}async describeDBClusters(k){let w={Action:"DescribeDBClusters",Version:"2014-10-31"};if(k?.DBClusterIdentifier)w.DBClusterIdentifier=k.DBClusterIdentifier;if(k?.MaxRecords)w.MaxRecords=k.MaxRecords;if(k?.Marker)w.Marker=k.Marker;if(k?.Filters)k.Filters.forEach((K,L)=>{w[`Filters.Filter.${L+1}.Name`]=K.Name,K.Values.forEach((O,R)=>{w[`Filters.Filter.${L+1}.Values.Value.${R+1}`]=O})});let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E}),H=z.DescribeDBClustersResult||z,G=H.DBClusters?.DBCluster||[];if(!Array.isArray(G))G=G?[G]:[];return{DBClusters:G,Marker:H.Marker}}async describeDBSnapshots(k){let w={Action:"DescribeDBSnapshots",Version:"2014-10-31"};if(k?.DBInstanceIdentifier)w.DBInstanceIdentifier=k.DBInstanceIdentifier;if(k?.DBSnapshotIdentifier)w.DBSnapshotIdentifier=k.DBSnapshotIdentifier;if(k?.SnapshotType)w.SnapshotType=k.SnapshotType;if(k?.MaxRecords)w.MaxRecords=k.MaxRecords;if(k?.Marker)w.Marker=k.Marker;let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E}),H=z.DescribeDBSnapshotsResult||z,G=H.DBSnapshots?.DBSnapshot||[];if(!Array.isArray(G))G=G?[G]:[];return{DBSnapshots:G,Marker:H.Marker}}async describeDBSubnetGroups(k){let w={Action:"DescribeDBSubnetGroups",Version:"2014-10-31"};if(k?.DBSubnetGroupName)w.DBSubnetGroupName=k.DBSubnetGroupName;if(k?.MaxRecords)w.MaxRecords=k.MaxRecords;if(k?.Marker)w.Marker=k.Marker;let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E}),H=z.DescribeDBSubnetGroupsResult||z,G=H.DBSubnetGroups?.DBSubnetGroup||[];if(!Array.isArray(G))G=G?[G]:[];return{DBSubnetGroups:G,Marker:H.Marker}}async createDBInstance(k){let w={Action:"CreateDBInstance",Version:"2014-10-31",DBInstanceIdentifier:k.DBInstanceIdentifier,DBInstanceClass:k.DBInstanceClass,Engine:k.Engine};if(k.DBClusterIdentifier)w.DBClusterIdentifier=k.DBClusterIdentifier;if(k.MasterUsername)w.MasterUsername=k.MasterUsername;if(k.MasterUserPassword)w.MasterUserPassword=k.MasterUserPassword;if(k.DBName)w.DBName=k.DBName;if(k.AllocatedStorage)w.AllocatedStorage=k.AllocatedStorage;if(k.DBSubnetGroupName)w.DBSubnetGroupName=k.DBSubnetGroupName;if(k.AvailabilityZone)w.AvailabilityZone=k.AvailabilityZone;if(k.PreferredMaintenanceWindow)w.PreferredMaintenanceWindow=k.PreferredMaintenanceWindow;if(k.PreferredBackupWindow)w.PreferredBackupWindow=k.PreferredBackupWindow;if(k.BackupRetentionPeriod!==void 0)w.BackupRetentionPeriod=k.BackupRetentionPeriod;if(k.MultiAZ!==void 0)w.MultiAZ=k.MultiAZ;if(k.EngineVersion)w.EngineVersion=k.EngineVersion;if(k.AutoMinorVersionUpgrade!==void 0)w.AutoMinorVersionUpgrade=k.AutoMinorVersionUpgrade;if(k.LicenseModel)w.LicenseModel=k.LicenseModel;if(k.PubliclyAccessible!==void 0)w.PubliclyAccessible=k.PubliclyAccessible;if(k.StorageType)w.StorageType=k.StorageType;if(k.StorageEncrypted!==void 0)w.StorageEncrypted=k.StorageEncrypted;if(k.KmsKeyId)w.KmsKeyId=k.KmsKeyId;if(k.DeletionProtection!==void 0)w.DeletionProtection=k.DeletionProtection;if(k.VpcSecurityGroupIds)k.VpcSecurityGroupIds.forEach((G,K)=>{w[`VpcSecurityGroupIds.VpcSecurityGroupId.${K+1}`]=G});if(k.Tags)k.Tags.forEach((G,K)=>{w[`Tags.Tag.${K+1}.Key`]=G.Key,w[`Tags.Tag.${K+1}.Value`]=G.Value});let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBInstance:(z.CreateDBInstanceResult||z).DBInstance}}async createDBCluster(k){let w={Action:"CreateDBCluster",Version:"2014-10-31",DBClusterIdentifier:k.DBClusterIdentifier,Engine:k.Engine};if(k.EngineVersion)w.EngineVersion=k.EngineVersion;if(k.MasterUsername)w.MasterUsername=k.MasterUsername;if(k.MasterUserPassword)w.MasterUserPassword=k.MasterUserPassword;if(k.DatabaseName)w.DatabaseName=k.DatabaseName;if(k.DBSubnetGroupName)w.DBSubnetGroupName=k.DBSubnetGroupName;if(k.BackupRetentionPeriod!==void 0)w.BackupRetentionPeriod=k.BackupRetentionPeriod;if(k.StorageEncrypted!==void 0)w.StorageEncrypted=k.StorageEncrypted;if(k.KmsKeyId)w.KmsKeyId=k.KmsKeyId;if(k.DeletionProtection!==void 0)w.DeletionProtection=k.DeletionProtection;if(k.ServerlessV2ScalingConfiguration)w["ServerlessV2ScalingConfiguration.MinCapacity"]=k.ServerlessV2ScalingConfiguration.MinCapacity,w["ServerlessV2ScalingConfiguration.MaxCapacity"]=k.ServerlessV2ScalingConfiguration.MaxCapacity;k.VpcSecurityGroupIds?.forEach((H,G)=>{w[`VpcSecurityGroupIds.VpcSecurityGroupId.${G+1}`]=H});let E=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J(w)).toString()});return{DBCluster:(E.CreateDBClusterResult||E).DBCluster}}async deleteDBInstance(k){let w={Action:"DeleteDBInstance",Version:"2014-10-31",DBInstanceIdentifier:k.DBInstanceIdentifier};if(k.SkipFinalSnapshot!==void 0)w.SkipFinalSnapshot=k.SkipFinalSnapshot;if(k.FinalDBSnapshotIdentifier)w.FinalDBSnapshotIdentifier=k.FinalDBSnapshotIdentifier;if(k.DeleteAutomatedBackups!==void 0)w.DeleteAutomatedBackups=k.DeleteAutomatedBackups;let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBInstance:(z.DeleteDBInstanceResult||z).DBInstance}}async modifyDBInstance(k){let w={Action:"ModifyDBInstance",Version:"2014-10-31",DBInstanceIdentifier:k.DBInstanceIdentifier};if(k.DBInstanceClass)w.DBInstanceClass=k.DBInstanceClass;if(k.AllocatedStorage)w.AllocatedStorage=k.AllocatedStorage;if(k.MasterUserPassword)w.MasterUserPassword=k.MasterUserPassword;if(k.BackupRetentionPeriod!==void 0)w.BackupRetentionPeriod=k.BackupRetentionPeriod;if(k.PreferredBackupWindow)w.PreferredBackupWindow=k.PreferredBackupWindow;if(k.PreferredMaintenanceWindow)w.PreferredMaintenanceWindow=k.PreferredMaintenanceWindow;if(k.MultiAZ!==void 0)w.MultiAZ=k.MultiAZ;if(k.EngineVersion)w.EngineVersion=k.EngineVersion;if(k.AutoMinorVersionUpgrade!==void 0)w.AutoMinorVersionUpgrade=k.AutoMinorVersionUpgrade;if(k.PubliclyAccessible!==void 0)w.PubliclyAccessible=k.PubliclyAccessible;if(k.ApplyImmediately!==void 0)w.ApplyImmediately=k.ApplyImmediately;if(k.StorageType)w.StorageType=k.StorageType;if(k.DeletionProtection!==void 0)w.DeletionProtection=k.DeletionProtection;if(k.VpcSecurityGroupIds)k.VpcSecurityGroupIds.forEach((G,K)=>{w[`VpcSecurityGroupIds.VpcSecurityGroupId.${K+1}`]=G});let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBInstance:(z.ModifyDBInstanceResult||z).DBInstance}}async modifyDBCluster(k){let w={Action:"ModifyDBCluster",Version:"2014-10-31",DBClusterIdentifier:k.DBClusterIdentifier};if(k.ServerlessV2ScalingConfiguration)w["ServerlessV2ScalingConfiguration.MinCapacity"]=k.ServerlessV2ScalingConfiguration.MinCapacity,w["ServerlessV2ScalingConfiguration.MaxCapacity"]=k.ServerlessV2ScalingConfiguration.MaxCapacity;if(k.BackupRetentionPeriod!==void 0)w.BackupRetentionPeriod=k.BackupRetentionPeriod;if(k.EngineVersion)w.EngineVersion=k.EngineVersion;if(k.MasterUserPassword)w.MasterUserPassword=k.MasterUserPassword;if(k.DeletionProtection!==void 0)w.DeletionProtection=k.DeletionProtection;if(k.ApplyImmediately!==void 0)w.ApplyImmediately=k.ApplyImmediately;let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBCluster:(z.ModifyDBClusterResult||z).DBCluster}}async rebootDBCluster(k){let w={Action:"FailoverDBCluster",Version:"2014-10-31",DBClusterIdentifier:k},E=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J(w)).toString()});return{DBCluster:(E.FailoverDBClusterResult||E).DBCluster}}async createDBClusterSnapshot(k,w){let E={Action:"CreateDBClusterSnapshot",Version:"2014-10-31",DBClusterIdentifier:k,DBClusterSnapshotIdentifier:w};return this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J(E)).toString()})}async describeDBClusterSnapshots(k={}){let w={Action:"DescribeDBClusterSnapshots",Version:"2014-10-31",...k},E=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J(w)).toString()}),z=E.DescribeDBClusterSnapshotsResult||E,H=z.DBClusterSnapshots?.DBClusterSnapshot??z.DBClusterSnapshots??[];return{DBClusterSnapshots:Array.isArray(H)?H:[H]}}async deleteDBClusterSnapshot(k){await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J({Action:"DeleteDBClusterSnapshot",Version:"2014-10-31",DBClusterSnapshotIdentifier:k})).toString()})}async deleteDBCluster(k,w){let E={Action:"DeleteDBCluster",Version:"2014-10-31",DBClusterIdentifier:k,SkipFinalSnapshot:!w};if(w)E.FinalDBSnapshotIdentifier=w;let z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J(E)).toString()});return{DBCluster:(z.DeleteDBClusterResult||z).DBCluster}}async restoreDBClusterToPointInTime(k){let w={Action:"RestoreDBClusterToPointInTime",Version:"2014-10-31",DBClusterIdentifier:k.DBClusterIdentifier,SourceDBClusterIdentifier:k.SourceDBClusterIdentifier};if(k.RestoreToTime)w.RestoreToTime=k.RestoreToTime.toISOString();if(k.UseLatestRestorableTime)w.UseLatestRestorableTime=!0;if(k.DBSubnetGroupName)w.DBSubnetGroupName=k.DBSubnetGroupName;if(k.VpcSecurityGroupIds)k.VpcSecurityGroupIds.forEach((G,K)=>{w[`VpcSecurityGroupIds.VpcSecurityGroupId.${K+1}`]=G});let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBCluster:(z.RestoreDBClusterToPointInTimeResult||z).DBCluster}}async restoreDBClusterFromSnapshot(k){let w={Action:"RestoreDBClusterFromSnapshot",Version:"2014-10-31",DBClusterIdentifier:k.DBClusterIdentifier,SnapshotIdentifier:k.SnapshotIdentifier,Engine:k.Engine};if(k.EngineVersion)w.EngineVersion=k.EngineVersion;if(k.DBSubnetGroupName)w.DBSubnetGroupName=k.DBSubnetGroupName;if(k.DeletionProtection!==void 0)w.DeletionProtection=k.DeletionProtection;if(k.VpcSecurityGroupIds?.forEach((H,G)=>{w[`VpcSecurityGroupIds.VpcSecurityGroupId.${G+1}`]=H}),k.ServerlessV2ScalingConfiguration)w["ServerlessV2ScalingConfiguration.MinCapacity"]=k.ServerlessV2ScalingConfiguration.MinCapacity,w["ServerlessV2ScalingConfiguration.MaxCapacity"]=k.ServerlessV2ScalingConfiguration.MaxCapacity;let E=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J(w)).toString()});return{DBCluster:(E.RestoreDBClusterFromSnapshotResult||E).DBCluster}}async startDBInstance(k){let E=new URLSearchParams(J({Action:"StartDBInstance",Version:"2014-10-31",DBInstanceIdentifier:k})).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBInstance:(z.StartDBInstanceResult||z).DBInstance}}async stopDBInstance(k){let w={Action:"StopDBInstance",Version:"2014-10-31",DBInstanceIdentifier:k.DBInstanceIdentifier};if(k.DBSnapshotIdentifier)w.DBSnapshotIdentifier=k.DBSnapshotIdentifier;let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBInstance:(z.StopDBInstanceResult||z).DBInstance}}async rebootDBInstance(k){let w={Action:"RebootDBInstance",Version:"2014-10-31",DBInstanceIdentifier:k.DBInstanceIdentifier};if(k.ForceFailover!==void 0)w.ForceFailover=k.ForceFailover;let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBInstance:(z.RebootDBInstanceResult||z).DBInstance}}async createDBSnapshot(k){let w={Action:"CreateDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:k.DBInstanceIdentifier,DBSnapshotIdentifier:k.DBSnapshotIdentifier};if(k.Tags)k.Tags.forEach((G,K)=>{w[`Tags.Tag.${K+1}.Key`]=G.Key,w[`Tags.Tag.${K+1}.Value`]=G.Value});let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBSnapshot:(z.CreateDBSnapshotResult||z).DBSnapshot}}async deleteDBSnapshot(k){let E=new URLSearchParams(J({Action:"DeleteDBSnapshot",Version:"2014-10-31",DBSnapshotIdentifier:k})).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBSnapshot:(z.DeleteDBSnapshotResult||z).DBSnapshot}}async restoreDBInstanceFromDBSnapshot(k){let w={Action:"RestoreDBInstanceFromDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:k.DBInstanceIdentifier,DBSnapshotIdentifier:k.DBSnapshotIdentifier};if(k.DBInstanceClass)w.DBInstanceClass=k.DBInstanceClass;if(k.Port)w.Port=k.Port;if(k.AvailabilityZone)w.AvailabilityZone=k.AvailabilityZone;if(k.DBSubnetGroupName)w.DBSubnetGroupName=k.DBSubnetGroupName;if(k.MultiAZ!==void 0)w.MultiAZ=k.MultiAZ;if(k.PubliclyAccessible!==void 0)w.PubliclyAccessible=k.PubliclyAccessible;if(k.AutoMinorVersionUpgrade!==void 0)w.AutoMinorVersionUpgrade=k.AutoMinorVersionUpgrade;if(k.StorageType)w.StorageType=k.StorageType;if(k.DeletionProtection!==void 0)w.DeletionProtection=k.DeletionProtection;if(k.VpcSecurityGroupIds)k.VpcSecurityGroupIds.forEach((G,K)=>{w[`VpcSecurityGroupIds.VpcSecurityGroupId.${K+1}`]=G});if(k.Tags)k.Tags.forEach((G,K)=>{w[`Tags.Tag.${K+1}.Key`]=G.Key,w[`Tags.Tag.${K+1}.Value`]=G.Value});let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBInstance:(z.RestoreDBInstanceFromDBSnapshotResult||z).DBInstance}}async waitForDBInstanceAvailable(k,w=60,E=30000){for(let z=0;z<w;z++){let H=await this.describeDBInstance(k);if(H?.DBInstanceStatus==="available")return H;if(["deleted","failed","incompatible-restore","incompatible-parameters"].includes(H?.DBInstanceStatus||""))throw Error(`DB instance ${k} is in terminal state: ${H?.DBInstanceStatus}`);await new Promise((G)=>setTimeout(G,E))}throw Error(`Timeout waiting for DB instance ${k} to become available`)}async waitForDBInstanceDeleted(k,w=60,E=30000){for(let z=0;z<w;z++)try{let H=await this.describeDBInstance(k);if(H?.DBInstanceStatus==="deleting"){await new Promise((G)=>setTimeout(G,E));continue}throw Error(`DB instance ${k} is in state: ${H?.DBInstanceStatus}`)}catch(H){if(H.code==="DBInstanceNotFound"||H.code==="DBInstanceNotFoundFault")return;throw H}throw Error(`Timeout waiting for DB instance ${k} to be deleted`)}}
2
- export{U as uf};