@stacksjs/ts-cloud 0.12.15 → 0.13.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 (178) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-9e22a51n.js → chunk-22c3pk8s.js} +78 -78
  3. package/dist/bin/chunk-2synp9gh.js +1 -0
  4. package/dist/bin/{chunk-ejqhbj1h.js → chunk-2v0qm547.js} +1 -1
  5. package/dist/bin/chunk-4qzpqmhe.js +1 -0
  6. package/dist/bin/chunk-5n3ejway.js +1 -0
  7. package/dist/bin/{chunk-ynr22ma8.js → chunk-7jwxgxxf.js} +1 -1
  8. package/dist/bin/{chunk-gd4w6bht.js → chunk-8bbw6qc2.js} +1 -1
  9. package/dist/bin/{chunk-7a7n6p2m.js → chunk-9jmnmhpy.js} +1 -1
  10. package/dist/bin/{chunk-pt2bz3kr.js → chunk-9qndhwbe.js} +1 -1
  11. package/dist/bin/chunk-9yra64dd.js +1 -0
  12. package/dist/bin/{chunk-ng0949x3.js → chunk-b48j6k55.js} +1 -1
  13. package/dist/bin/{chunk-r1w08y38.js → chunk-bdgkeqv6.js} +1 -1
  14. package/dist/bin/chunk-c82rh7qe.js +1 -0
  15. package/dist/bin/{chunk-zzsdhhmb.js → chunk-d4bb9qg9.js} +1 -1
  16. package/dist/bin/{chunk-pcyywgx7.js → chunk-d6kqbp8q.js} +1 -1
  17. package/dist/bin/{chunk-swete552.js → chunk-dk38j1qr.js} +9 -9
  18. package/dist/bin/{chunk-x42gb7pq.js → chunk-e1cxh9rj.js} +2 -2
  19. package/dist/bin/{chunk-9k60q9qz.js → chunk-edaq5jef.js} +3 -3
  20. package/dist/bin/chunk-fbe5kk6w.js +1 -0
  21. package/dist/bin/{chunk-n7eq4t9a.js → chunk-fbycbnvj.js} +4 -4
  22. package/dist/bin/chunk-fj89173b.js +1 -0
  23. package/dist/bin/{chunk-8tbj9h2a.js → chunk-gxwsq3k0.js} +40 -40
  24. package/dist/bin/{chunk-kc2e193t.js → chunk-hwp5xp1c.js} +63 -63
  25. package/dist/bin/chunk-j3w462ep.js +1 -0
  26. package/dist/bin/chunk-k2zzny51.js +1 -0
  27. package/dist/bin/{chunk-80zkjpfz.js → chunk-k3er0h4j.js} +1 -1
  28. package/dist/bin/chunk-kjatss6s.js +1 -0
  29. package/dist/bin/{chunk-w5hzt11d.js → chunk-kxa4t4wh.js} +2 -2
  30. package/dist/bin/{chunk-raj6j2j5.js → chunk-m5sjzxm3.js} +1 -1
  31. package/dist/bin/{chunk-dhxwmkhz.js → chunk-mcqkjhgp.js} +1 -1
  32. package/dist/bin/{chunk-77qpn2m8.js → chunk-n56c0j1e.js} +4 -4
  33. package/dist/bin/chunk-ntahmgqg.js +1 -0
  34. package/dist/bin/{chunk-57w9nsjk.js → chunk-p197a99s.js} +1 -1
  35. package/dist/bin/{chunk-vymg9ywg.js → chunk-pd8v6bpd.js} +1 -1
  36. package/dist/bin/{chunk-yhxpmk29.js → chunk-pthfzst7.js} +1 -1
  37. package/dist/bin/{chunk-5tsxt28g.js → chunk-ptt8me4h.js} +2 -2
  38. package/dist/bin/{chunk-7xvm2ygt.js → chunk-qmqmnxmm.js} +3 -3
  39. package/dist/bin/{chunk-r1vtnn8w.js → chunk-rzt92fwv.js} +3 -3
  40. package/dist/bin/chunk-t1eft7s7.js +1 -0
  41. package/dist/bin/{chunk-49sthm4q.js → chunk-t7seq21w.js} +1 -1
  42. package/dist/bin/chunk-t8n2961n.js +1 -0
  43. package/dist/bin/{chunk-vesvsvdy.js → chunk-vwzgtsn9.js} +1 -1
  44. package/dist/bin/{chunk-s1j941z1.js → chunk-w0g72e50.js} +1 -1
  45. package/dist/bin/chunk-wb8y7zey.js +1 -0
  46. package/dist/bin/{chunk-n8cwx54p.js → chunk-x4gsw45d.js} +5 -5
  47. package/dist/bin/{chunk-yx1qgp1q.js → chunk-xs62dg7t.js} +2 -2
  48. package/dist/bin/chunk-xtp2zf3j.js +1 -0
  49. package/dist/bin/chunk-xvn07b0e.js +1 -0
  50. package/dist/bin/{chunk-sdwr2tnp.js → chunk-xw9vcdwt.js} +1 -1
  51. package/dist/bin/{chunk-4zbnwt9b.js → chunk-y1r1evt0.js} +1 -1
  52. package/dist/bin/{chunk-c51xp8f7.js → chunk-zs8bfer0.js} +1 -1
  53. package/dist/bin/cli.js +98 -98
  54. package/dist/bin/dashboard-server.js +1 -1
  55. package/dist/chunk-05qawkra.js +1 -0
  56. package/dist/{chunk-jb8em9ba.js → chunk-0g2jkhy5.js} +1 -1
  57. package/dist/chunk-1jx53q5e.js +1 -0
  58. package/dist/{chunk-30h9rgfn.js → chunk-2s65yj3g.js} +4 -4
  59. package/dist/{chunk-x07tpsv0.js → chunk-3k60wm30.js} +5 -5
  60. package/dist/chunk-3qtce4mm.js +1 -0
  61. package/dist/chunk-3tt5em2c.js +1 -0
  62. package/dist/{chunk-hw3p6pth.js → chunk-42kv07cs.js} +1 -1
  63. package/dist/{chunk-wjgnfg6q.js → chunk-65ajja2a.js} +1 -1
  64. package/dist/{chunk-yq3pdbz7.js → chunk-6gtqjsg9.js} +3 -3
  65. package/dist/{chunk-6g81m01r.js → chunk-8s9m8pyb.js} +1 -1
  66. package/dist/{chunk-gd9g0v9w.js → chunk-asmv4fw1.js} +19 -19
  67. package/dist/{chunk-83p688yv.js → chunk-ds92qg3g.js} +4 -4
  68. package/dist/{chunk-6nvn041c.js → chunk-dzqz1sm0.js} +3 -3
  69. package/dist/{chunk-88nxsyry.js → chunk-hyj2ymp1.js} +6 -6
  70. package/dist/chunk-j4ed179k.js +2 -0
  71. package/dist/{chunk-g9mnmddy.js → chunk-m5r0dt28.js} +2 -2
  72. package/dist/{chunk-zftpjxkr.js → chunk-mcfdtg5w.js} +1 -1
  73. package/dist/{chunk-cy6qh4ea.js → chunk-ngdhqwf3.js} +3 -3
  74. package/dist/{chunk-6znnde1s.js → chunk-nhtz2k8d.js} +5 -5
  75. package/dist/{chunk-rbem58rx.js → chunk-nw0tvrrr.js} +1 -1
  76. package/dist/{chunk-hnkw6pde.js → chunk-p9fqsz06.js} +2 -2
  77. package/dist/{chunk-qzwack6w.js → chunk-r4dpn715.js} +7 -7
  78. package/dist/{chunk-678rwkz8.js → chunk-vk513ge7.js} +89 -89
  79. package/dist/{chunk-w495x89g.js → chunk-w5fmaaxa.js} +4 -4
  80. package/dist/chunk-wr7tn9j5.js +1 -0
  81. package/dist/{chunk-a6k322xc.js → chunk-xqx5szta.js} +30 -30
  82. package/dist/{chunk-jvqcw0b4.js → chunk-y13zcbnp.js} +101 -101
  83. package/dist/{chunk-2knc1zyy.js → chunk-ycs26jsj.js} +124 -124
  84. package/dist/{chunk-r5emv4x8.js → chunk-z7v4evbh.js} +2 -2
  85. package/dist/deploy/index.js +1 -1
  86. package/dist/dns/delegate-from-config.d.ts +50 -0
  87. package/dist/dns/delegate-from-config.test.d.ts +1 -0
  88. package/dist/dns/delegation.d.ts +110 -0
  89. package/dist/dns/delegation.test.d.ts +1 -0
  90. package/dist/dns/index.d.ts +4 -0
  91. package/dist/dns/index.js +1 -1
  92. package/dist/drivers/index.js +1 -1
  93. package/dist/drivers/shared/rpx-gateway.d.ts +17 -0
  94. package/dist/index.d.ts +1 -1
  95. package/dist/index.js +49 -49
  96. package/dist/operations/index.js +1 -1
  97. package/dist/protection/index.js +1 -1
  98. package/dist/spend/index.js +1 -1
  99. package/dist/ui/404.html +1 -1
  100. package/dist/ui/accept-invitation.html +1 -1
  101. package/dist/ui/access-denied.html +1 -1
  102. package/dist/ui/account/automation.html +5 -5
  103. package/dist/ui/account/security.html +2 -2
  104. package/dist/ui/applications/compose.html +5 -5
  105. package/dist/ui/applications/new.html +2 -2
  106. package/dist/ui/data/backups.html +6 -6
  107. package/dist/ui/data/services.html +6 -6
  108. package/dist/ui/data/volumes.html +6 -6
  109. package/dist/ui/index.html +5 -5
  110. package/dist/ui/infrastructure/topology.html +6 -6
  111. package/dist/ui/integrations.html +1 -1
  112. package/dist/ui/operations/alerts.html +5 -5
  113. package/dist/ui/operations/configuration.html +6 -6
  114. package/dist/ui/operations/jobs.html +6 -6
  115. package/dist/ui/operations/maintenance.html +5 -5
  116. package/dist/ui/operations/observability.html +6 -6
  117. package/dist/ui/operations/previews.html +6 -6
  118. package/dist/ui/operations/queue.html +6 -6
  119. package/dist/ui/operations/regions.html +5 -5
  120. package/dist/ui/operations/releases.html +6 -6
  121. package/dist/ui/operations/spend.html +6 -6
  122. package/dist/ui/operations/workloads.html +6 -6
  123. package/dist/ui/security.html +2 -2
  124. package/dist/ui/server/actions.html +5 -5
  125. package/dist/ui/server/activity.html +1 -1
  126. package/dist/ui/server/capacity.html +6 -6
  127. package/dist/ui/server/database.html +5 -5
  128. package/dist/ui/server/deployments.html +5 -5
  129. package/dist/ui/server/diagnostics.html +2 -2
  130. package/dist/ui/server/firewall.html +6 -6
  131. package/dist/ui/server/fleet.html +6 -6
  132. package/dist/ui/server/logs.html +6 -6
  133. package/dist/ui/server/metrics.html +5 -5
  134. package/dist/ui/server/security.html +2 -2
  135. package/dist/ui/server/services.html +2 -2
  136. package/dist/ui/server/sites.html +6 -6
  137. package/dist/ui/server/ssh-keys.html +6 -6
  138. package/dist/ui/server/team.html +6 -6
  139. package/dist/ui/server/terminal.html +2 -2
  140. package/dist/ui/serverless/alarms.html +6 -6
  141. package/dist/ui/serverless/assets.html +2 -2
  142. package/dist/ui/serverless/cost.html +2 -2
  143. package/dist/ui/serverless/data.html +6 -6
  144. package/dist/ui/serverless/deployments.html +2 -2
  145. package/dist/ui/serverless/firewall.html +2 -2
  146. package/dist/ui/serverless/functions.html +6 -6
  147. package/dist/ui/serverless/logs.html +6 -6
  148. package/dist/ui/serverless/metrics.html +2 -2
  149. package/dist/ui/serverless/queues.html +5 -5
  150. package/dist/ui/serverless/secrets.html +6 -6
  151. package/dist/ui/serverless/traces.html +6 -6
  152. package/dist/ui/serverless.html +6 -6
  153. package/dist/ui-src/src/charts.ts +1 -1
  154. package/dist/ui-src/src/topology.ts +1 -1
  155. package/package.json +3 -3
  156. package/dist/bin/chunk-1s4dny8d.js +0 -1
  157. package/dist/bin/chunk-4w80w3sm.js +0 -1
  158. package/dist/bin/chunk-4yntpqbe.js +0 -1
  159. package/dist/bin/chunk-7x0hrna6.js +0 -1
  160. package/dist/bin/chunk-971tfc6m.js +0 -1
  161. package/dist/bin/chunk-dpw8x3sr.js +0 -1
  162. package/dist/bin/chunk-h785hw6a.js +0 -1
  163. package/dist/bin/chunk-jyggrdh2.js +0 -1
  164. package/dist/bin/chunk-q524s7cx.js +0 -1
  165. package/dist/bin/chunk-q9gpw6wv.js +0 -1
  166. package/dist/bin/chunk-r6cvc2pr.js +0 -1
  167. package/dist/bin/chunk-rh2sqtew.js +0 -1
  168. package/dist/bin/chunk-tkzpbb7n.js +0 -1
  169. package/dist/bin/chunk-v78r5tx0.js +0 -1
  170. package/dist/bin/chunk-v7f4c62s.js +0 -1
  171. package/dist/bin/chunk-vx649y7t.js +0 -1
  172. package/dist/chunk-6t9tjvpy.js +0 -2
  173. package/dist/chunk-9w32efae.js +0 -1
  174. package/dist/chunk-atny1wp9.js +0 -1
  175. package/dist/chunk-fdexq9e1.js +0 -1
  176. package/dist/chunk-hn2v0b0d.js +0 -1
  177. package/dist/chunk-v46b25w9.js +0 -1
  178. /package/dist/bin/{chunk-bckm6fre.js → chunk-pdw0qjq1.js} +0 -0
@@ -0,0 +1,2 @@
1
+ import{n}from"./chunk-2s65yj3g.js";import{h}from"./chunk-65ajja2a.js";var tt=new Set(["A","AAAA","CNAME"]);function S(e,t=""){return e===408||e===409||e===425||e===429||e>=500||/rate limit|temporar|timed? ?out|try again/i.test(t)}async function P(e,t){let r=t?.headers.get("retry-after"),s=r===null||r===void 0?void 0:Number(r)*1000,o=Number.isFinite(s)?Math.max(0,s):Math.min(1000*2**(e-1),30000);await new Promise((i)=>setTimeout(i,o))}class ie{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(e,t,r=15000){this.apiKey=e,this.secretKey=t,this.requestTimeoutMs=r}async request(e,t={}){let r;for(let s=1;s<=8;s+=1){let o,i=new AbortController,a=setTimeout(()=>{i.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{o=await fetch(`https://api.porkbun.com/api/json/v3${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...t}),signal:i.signal})}catch(d){if(r=d,s===8)throw d;await P(s);continue}finally{clearTimeout(a)}if(!o.ok){if(r=Error(`Porkbun API error: ${o.status} ${o.statusText}`),!S(o.status)||s===8)throw r;await P(s,o);continue}let c=await o.json();if(c.status==="ERROR"){if(r=Error(`Porkbun API error: ${c.message||"Unknown error"}`),!S(0,c.message)||s===8)throw r;await P(s,o);continue}return c}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(e,t){if(!ie.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${o.message??"unknown provider error"}`];let i=[];for(let a of o.records){if(a.type!=="ALIAS"&&a.type!=="CNAME")continue;if(this.getSubdomain(a.name,r)!==s)continue;let c=await this.deleteRecord(e,a);if(!c.success)i.push(`could not remove conflicting ${a.type} on ${a.name}: ${c.message??"unknown provider error"}`)}return i}async addressRecordExists(e,t){let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return!0;return o.records.some((i)=>i.type===t.type&&this.getSubdomain(i.name,r)===s&&i.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)o.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)o.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)o.content=`${t.weight} ${t.port} ${t.content}`;let i=await this.clearConflictingAliases(e,t),a=await this.request(`/dns/create/${r}`,o);if(ie.ADDRESS_TYPES.has(t.type)&&!await this.addressRecordExists(e,t))return{success:!1,message:`Porkbun reported success but no ${t.type} record for ${t.name} exists${i.length>0?` (${i.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:a.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.listRecords(e,t.type);if(o.success){let i=o.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type);if(i?.id){let a={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)a.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)a.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)a.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${i.id}`,a),{success:!0,id:i.id,message:"Record updated successfully"}}}return this.createRecord(e,t)}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e);if("id"in t&&t.id)return await this.request(`/dns/delete/${r}/${t.id}`),{success:!0,message:"Record deleted successfully"};let s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return{success:!1,message:"Failed to list records"};let i=o.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type&&a.content===t.content);if(!i?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${i.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/dns/retrieve/${r}`;if(t)s=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(s)).records||[]).map((a)=>({id:a.id,name:a.name||r,type:a.type,content:a.content,ttl:Number.parseInt(a.ttl,10),priority:a.prio?Number.parseInt(a.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request(`/dns/retrieve/${t}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((t)=>t.domain)}catch{return[]}}async getNameServers(e){try{let t=this.getRootDomain(e);return(await this.request(`/dns/getNS/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/dns/updateNS/${r}`,{ns:t}),!0}catch{return!1}}}class ke{name="godaddy";apiKey;apiSecret;baseUrl;constructor(e,t="",r="production"){this.apiKey=e,this.apiSecret=t,this.baseUrl=r==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}authorization(){if(!this.apiSecret||this.apiKey.startsWith("gd_pat_"))return`Bearer ${this.apiKey}`;return`sso-key ${this.apiKey}:${this.apiSecret}`}async request(e,t,r){let s=`${this.baseUrl}${t}`,o={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},i={method:e,headers:o};if(r)i.body=JSON.stringify(r);let a=await fetch(s,i);if(a.status===204)return{};if(a.ok){let d=await a.text();if(d)return JSON.parse(d);return{}}let c=`GoDaddy API error: ${a.status} ${a.statusText}`;try{let d=await a.json();if(d.message)c=`GoDaddy API error: ${d.message}`;if(d.fields)c+=` - Fields: ${JSON.stringify(d.fields)}`}catch{}throw Error(c)}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"@";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}toGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=this.getSubdomain(e.name,r),o={type:e.type,name:s,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)o.priority=e.priority;return o}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=e.name;if(s==="@")s=r;else if(!s.endsWith(r))s=`${s}.${r}`;return{name:s,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[s]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s.name}`,[s]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${s}`),i=o.filter((a)=>a.data!==t.content);if(i.length===o.length)return{success:!1,message:"Record not found"};if(i.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${s}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s}`,i);return{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/v1/domains/${r}/records`;if(t)s=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",s)).map((i)=>this.fromGoDaddyRecord(i,e))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request("GET",`/v1/domains/${t}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((t)=>t.domain)}catch{return[]}}async getDomainDetails(e){try{let t=this.getRootDomain(e),r=await this.request("GET",`/v1/domains/${t}`);return{domain:r.domain,status:r.status,nameServers:r.nameServers,expires:r.expires}}catch{return null}}async getNameServers(e){return(await this.getDomainDetails(e))?.nameServers??[]}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request("PATCH",`/v1/domains/${r}`,{nameServers:t}),!0}catch{return!1}}async checkDomainAvailability(e){try{let t=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(e)}`);return{available:t.available,price:t.price,currency:t.currency}}catch{return{available:!1}}}}var x="https://api.cloudflare.com/client/v4",ts="[ts-cloud]";class Be{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(e,t={}){this.apiToken=e,this.configuredZoneId=t.zoneId,this.accountId=t.accountId}async request(e,t,r){let s=`${x}${t}`,o={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},i={method:e,headers:o};if(r)i.body=JSON.stringify(r);let c=await(await fetch(s,i)).json();if(!c.success){let d=c.errors.map((u)=>u.message).join(", ");throw Error(`Cloudflare API error: ${d}`)}return c}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async resolveZone(e){let t=e.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let a=await this.resolveConfiguredZoneName();if(a&&(t===a||t.endsWith(`.${a}`)))return{id:this.configuredZoneId,name:a}}let r=this.getRootDomain(t),s=this.zoneCache.get(r);if(s)return{id:s,name:r};let o=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!o.result||o.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"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 i=o.result[0].id;return this.zoneCache.set(r,i),{id:i,name:o.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let t=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!t)return;return this.configuredZoneName=t,this.zoneCache.set(t,this.configuredZoneId),t}catch{return}}async getZoneId(e){return(await this.resolveZone(e)).id}getFullRecordName(e,t){let r=e.replace(/\.$/,"");if(!r||r===t||r==="@")return t;if(r.endsWith(`.${t}`))return r;return`${r}.${t}`}toCloudflareRecord(e,t,r){let s={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},o=r??e.proxied;if(o!==void 0&&tt.has(e.type)){if(s.proxied=o,o)s.ttl=1}if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;if(e.type==="SRV"){let i=k(e);if(i)s.data=i,delete s.content,delete s.priority;else if(e.priority!==void 0)s.priority=e.priority}return s}fromCloudflareRecord(e){return{id:e.id,name:e.name,type:e.type,content:e.content,ttl:e.ttl,priority:e.priority,proxied:e.proxied}}async createRecord(e,t){try{let r=await this.resolveZone(e),s=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,s)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.resolveZone(e),s=this.getFullRecordName(t.name,r.name),i=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`)).result?.[0],a=t.proxied??i?.proxied,c=this.toCloudflareRecord(t,r.name,a);if(i)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${i.id}`,c)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,c)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),s=r.id,o=this.getFullRecordName(t.name,r.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!i.result||i.result.length===0)return{success:!1,message:"Record not found"};let a=i.result.find((c)=>c.content===t.content);if(!a)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${s}/dns_records/${a.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let s=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)s+=`&type=${t}`;let o=[],i=1,a=!0;while(a){let c=await this.request("GET",`${s}&page=${i}`);if(o.push(...c.result||[]),c.result_info)a=i<c.result_info.total_pages,i++;else a=!1}return{success:!0,records:o.map((c)=>this.fromCloudflareRecord(c))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{return await this.getZoneId(e),!0}catch{return!1}}async listDomains(){try{let e=[],t=1,r=!0;while(r){let s=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...s.result||[]),s.result_info)r=t<s.result_info.total_pages,t++;else r=!1}return e.map((s)=>s.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),s=t.accountId??this.accountId;if(!s)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let o=await this.getZoneDetails(r);if(o)return{...o,created:!1};try{let a=(await this.request("POST","/zones",{name:r,account:{id:s},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(a.name,a.id),{id:a.id,name:a.name,status:a.status,nameServers:a.name_servers??[],created:!0}}catch(i){let a=i instanceof Error?i.message:String(i);if(!/already exists|1061/i.test(a))throw i;let c=await this.getZoneDetails(r);if(!c)throw i;return{...c,created:!1}}}async getZoneDetails(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}`);return{id:r.result.id,name:r.result.name,status:r.result.status,nameServers:r.result.name_servers,paused:r.result.paused}}catch{return null}}async listEdgeCertificateHosts(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/ssl/certificate_packs?per_page=50`),s=new Set;for(let o of r.result||[]){if(o.status!=="active")continue;for(let i of o.hosts||[])s.add(i.toLowerCase())}return[...s]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),s={};if(t?.purgeEverything)s.purge_everything=!0;else{if(t?.files)s.files=t.files;if(t?.tags)s.tags=t.tags;if(t?.hosts)s.hosts=t.hosts}if(Object.keys(s).length===0)s.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,s),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),s=r.id,o=this.getFullRecordName(t.name,r.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(i.result&&i.result.length>0)return i.result.find((c)=>c.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let s=await this.resolveZone(e),o=s.id,i=this.getFullRecordName(t.name,s.name),a=await this.request("GET",`/zones/${o}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);if(!a.result||a.result.length===0)return!1;let c=a.result.find((d)=>d.content===t.content);if(!c)return!1;return await this.request("PATCH",`/zones/${o}/dns_records/${c.id}`,{proxied:r}),!0}catch{return!1}}async zoneIdFor(e){return this.getZoneId(e)}get account(){return this.accountId}async getZoneSettings(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/settings`),s={};for(let o of r.result||[])s[o.id]=o.value;return s}async applyZoneSettings(e,t){let r=await this.getZoneId(e),s=await this.getZoneSettings(e).catch(()=>({})),o=[],i=[];for(let[a,c]of Object.entries(t)){if(c===void 0)continue;let d=s[a];if(d!==void 0&&N(d,c))continue;try{await this.request("PATCH",`/zones/${r}/settings/${a}`,{value:c}),o.push({id:a,from:d,to:c})}catch(u){i.push({id:a,error:u instanceof Error?u.message:String(u)})}}return{changed:o,failed:i}}async getPhaseRules(e,t){let r=await this.getZoneId(e);try{return(await this.request("GET",`/zones/${r}/rulesets/phases/${t}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(e,t,r){try{let s=await this.getZoneId(e),i=(await this.getPhaseRules(e,t)).filter((d)=>!(d.description||"").startsWith(ts)),a=r.map((d)=>({...d,description:d.description?.startsWith(ts)?d.description:`${ts} ${d.description||t}`})),c=[...i,...a].map(({id:d,...u})=>u);return await this.request("PUT",`/zones/${s}/rulesets/phases/${t}/entrypoint`,{rules:c}),{success:!0}}catch(s){return{success:!1,message:s instanceof Error?s.message:String(s)}}}}function N(e,t){if(e===t)return!0;if(typeof e!==typeof t||e===null||t===null)return!1;if(typeof e!=="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;return e.every((o,i)=>N(o,t[i]))}let r=e,s=t;return Object.keys(s).every((o)=>N(r[o],s[o]))}function k(e){let t=(e.content||e.value||"").trim();if(e.weight!==void 0&&e.port!==void 0&&e.priority!==void 0&&t)return{priority:e.priority,weight:e.weight,port:e.port,target:b(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[s,o,i]=r.slice(0,3).map(Number);if(![s,o,i].every(Number.isFinite))return null;return{priority:s,weight:o,port:i,target:b(r.slice(3).join(" "))}}function b(e){return e.replace(/\.$/,"")}var V=new Set(["A","AAAA","CNAME","ALIAS"]);function Tt(e){let t=e.trim().replace(/^"|"$/g,"").toLowerCase();if(t.startsWith("v=spf1"))return"v=spf1";if(t.startsWith("v=dmarc1"))return"v=dmarc1";return}function R(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function D(e){return e.replace(/\.$/,"").toLowerCase()}function hn(e,t){let r=D(t),s=(e??"@").trim();if(!s||s==="@")return r;let o=D(s);if(o===r||o.endsWith(`.${r}`))return o;return`${o}.${r}`}function rs(e,t){return e.map((r)=>({...r,name:hn(r.name,t),proxied:r.proxied??!1}))}function _(e,t){if(e.type!==t.type)return!1;if(D(e.name)!==D(t.name))return!1;if(V.has(t.type))return!0;if(t.type==="TXT"){let r=Tt(t.content);if(r)return Tt(R(e.content))===r;return R(e.content)===R(t.content)}return R(e.content)===R(t.content)}function Z(e,t){if(R(e.content)!==R(t.content))return!1;if(t.priority!==void 0&&e.priority!==t.priority)return!1;if(t.proxied!==void 0&&e.proxied!==void 0&&e.proxied!==t.proxied)return!1;return!0}async function ns(e){let{provider:t,zone:r,records:s}=e,o={outcomes:[],warnings:[]};if(s.length===0)return o;let i=await t.listRecords(r);if(!i.success)return o.warnings.push(`could not list ${r}: ${i.message||"unknown provider error"} — records not reconciled`),o;let a=i.records;for(let c of s){let d=a.filter((l)=>_(l,c));if(d.length>0&&d.every((l)=>Z(l,c))){o.outcomes.push({record:c,action:"unchanged"});continue}let u={name:c.name,type:c.type,content:c.content,ttl:c.ttl??3600,...c.priority!==void 0?{priority:c.priority}:{},...c.proxied!==void 0?{proxied:c.proxied}:{}},p=c.type==="TXT"&&Tt(c.content)!==void 0;if(p)for(let l of d){let A=await t.deleteRecord(r,{name:l.name,type:l.type,content:l.content});if(!A.success)o.warnings.push(`could not remove superseded ${l.type} at ${l.name}: ${A.message||"unknown error"}`)}let m=p||d.length===0?await t.createRecord(r,u):await t.upsertRecord(r,u);if(m.success)o.outcomes.push({record:c,action:d.length>0?"updated":"created"});else o.outcomes.push({record:c,action:"failed",message:m.message})}for(let c of["MX"]){let d=new Set(s.filter((u)=>u.type===c).map((u)=>D(u.name)));for(let u of d){let p=new Set(s.filter((l)=>l.type===c&&D(l.name)===u).map((l)=>R(l.content).toLowerCase())),m=a.filter((l)=>l.type===c&&D(l.name)===u&&!p.has(R(l.content).toLowerCase()));for(let l of m)o.warnings.push(`${u} has an undeclared ${c} record (${l.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return o}function nr(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.getNameServers==="function"&&typeof t.updateNameServers==="function"}function ir(e){return Boolean(e&&typeof e.createZone==="function")}var M=new Set(["NS"]);function v(e){return e.replace(/\.$/,"").toLowerCase()}function fn(e,t){if(e.length===0||t.length===0)return!1;let r=new Set(e.map(v)),s=new Set(t.map(v));if(r.size!==s.size)return!1;for(let o of r)if(!s.has(o))return!1;return!0}function I(e){let t=e.content.trim(),r=t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t;return e.type==="TXT"?r:v(r)}function O(e,t){return e.type===t.type&&v(e.name)===v(t.name)&&I(e)===I(t)}async function sr(e){let{domain:t,registrar:r,host:s,dryRun:o=!1}=e,i=new Set([...e.proxiedHosts??[]].map(v)),a=[],c=await s.createZone(t,{accountId:e.accountId,jumpStart:!1}),d=await r.getNameServers(t),u={status:"ready",domain:t,zoneId:c.id,targetNameservers:c.nameServers,currentNameservers:d,records:[],missing:[],warnings:a};if(fn(d,c.nameServers))return u.status="already-delegated",u;if(c.nameServers.length===0)return a.push(`${s.name} did not report nameservers for ${t}; cannot delegate.`),u.status="blocked",u;let p=await r.listRecords(t);if(!p.success)return a.push(`Could not read ${t} from ${r.name}: ${p.message??"unknown error"}`),u.status="blocked",u;let m=[];for(let g of p.records){if(M.has(g.type)){u.records.push({record:g,status:"skipped",reason:`${g.type} describes the delegation itself; ${s.name} owns it`});continue}let y=tt.has(g.type)&&i.has(v(g.name));m.push({name:g.name,type:g.type,content:g.content,ttl:g.ttl,priority:g.priority,...tt.has(g.type)?{proxied:y}:{}})}if(o){for(let g of m)u.records.push({record:g,status:"copied",reason:"dry run"});return u}for(let g of m){let y;try{y=await s.upsertRecord(t,g)}catch(C){y={success:!1,message:C instanceof Error?C.message:String(C)}}u.records.push(y.success?{record:g,status:"copied"}:{record:g,status:"failed",reason:y.message})}let l=await s.listRecords(t);if(!l.success)return a.push(`Could not read back ${t} from ${s.name}: ${l.message??"unknown error"}`),u.status="blocked",u;for(let g of m)if(!l.records.some((y)=>O(g,y)))u.missing.push(g);if(u.missing.length>0)return a.push(`${u.missing.length} record(s) did not arrive at ${s.name}; leaving ${r.name}'s nameservers alone. Delegating now would take the domain off a complete zone and onto an incomplete one.`),u.status="blocked",u;if(!await r.updateNameServers(t,c.nameServers))return a.push(`${r.name} refused the nameserver update for ${t}.`),u.status="blocked",u;return u.status="delegated",u}function z(e){return{porkbunApiKey:e.PORKBUN_API_KEY,porkbunSecretKey:e.PORKBUN_SECRET_KEY,godaddyApiKey:e.GODADDY_API_KEY,godaddyApiSecret:e.GODADDY_API_SECRET,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID}}function L(e,t){if(e==="porkbun"){if(!t.porkbunApiKey||!t.porkbunSecretKey)return"PORKBUN_API_KEY / PORKBUN_SECRET_KEY are not set";return new ie(t.porkbunApiKey,t.porkbunSecretKey)}if(!t.godaddyApiKey||!t.godaddyApiSecret)return"GODADDY_API_KEY / GODADDY_API_SECRET are not set";let r=new ke(t.godaddyApiKey,t.godaddyApiSecret);if(!nr(r))return"the GoDaddy provider cannot change nameservers";return r}async function is(e,t={}){let r=e.registrar;if(!r)return{status:"skipped",reason:"no dns.registrar configured"};if(r.delegate===!1)return{status:"skipped",reason:"dns.registrar.delegate is false"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(!e.provider||e.provider===r.provider)return{status:"skipped",reason:`dns.provider is already ${r.provider}`};if(e.provider!=="cloudflare")return{status:"skipped",reason:`delegation to ${e.provider} is not supported yet`};let s=t.credentials??z(t.env??process.env);if(!s.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let o=L(r.provider,s);if(typeof o==="string")return{status:"skipped",reason:o};let i=new Be(s.cloudflareApiToken,{accountId:s.cloudflareAccountId});if(!ir(i))return{status:"skipped",reason:"the Cloudflare provider cannot create zones"};return sr({domain:e.domain,registrar:o,host:i,proxiedHosts:r.proxied,accountId:s.cloudflareAccountId,dryRun:r.dryRun})}function ss(e){if(e.status==="skipped")return[`dns: delegation skipped — ${e.reason}`];let t=[];switch(e.status){case"already-delegated":t.push(`dns: ${e.domain} already delegated to ${e.targetNameservers.join(", ")}`);break;case"delegated":t.push(`dns: ${e.domain} delegated to ${e.targetNameservers.join(", ")} (${e.records.filter((r)=>r.status==="copied").length} record(s) copied)`),t.push("dns: nameserver changes take up to 24h to propagate; the old zone answers until then");break;case"ready":t.push(`dns: ${e.domain} would delegate to ${e.targetNameservers.join(", ")} (dry run)`);break;case"blocked":t.push(`dns: ${e.domain} NOT delegated — nameservers left at ${e.currentNameservers.join(", ")}`);for(let r of e.missing)t.push(` missing at destination: ${r.type} ${r.name}`);break}for(let r of e.warnings)t.push(` ${r}`);return t}class he{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new h(e),this.providedHostedZoneId=t}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async getHostedZoneId(e){if(this.providedHostedZoneId)return this.providedHostedZoneId;let t=this.getRootDomain(e),r=this.hostedZoneCache.get(t);if(r)return r;let s=await this.client.findHostedZoneForDomain(e);if(s){let o=s.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,o),o}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(!s||s==="@")return`${r}.`;if(s===r||s.endsWith(`.${r}`))return`${s}.`;return`${s}.${r}.`}async createRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),o=t.content;if(t.type==="TXT"&&!o.startsWith('"'))o=`"${o}"`;if(t.type==="MX"&&t.priority!==void 0)o=`${t.priority} ${o}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:"CREATE",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),o=t.content;if(t.type==="TXT"&&!o.startsWith('"'))o=`"${o}"`;if(t.type==="MX"&&t.priority!==void 0)o=`${t.priority} ${o}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),o=t.content;if(t.type==="TXT"&&!o.startsWith('"'))o=`"${o}"`;if(t.type==="MX"&&t.priority!==void 0)o=`${t.priority} ${o}`;return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}}),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,records:[],message:`No hosted zone found for domain: ${e}`};let s=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),o=[];for(let i of s.ResourceRecordSets){if(t&&i.Type!==t)continue;if(i.AliasTarget)continue;for(let a of i.ResourceRecords||[]){let c=a.Value,d;if(i.Type==="MX"){let u=c.split(" ");if(u.length>=2)d=Number.parseInt(u[0],10),c=u.slice(1).join(" ")}if(i.Type==="TXT"&&c.startsWith('"')&&c.endsWith('"'))c=c.slice(1,-1);o.push({name:i.Name.replace(/\.$/,""),type:i.Type,content:c,ttl:i.TTL,priority:d})}}return{success:!0,records:o}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){return await this.getHostedZoneId(e)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((t)=>t.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(e){try{let t=await this.getHostedZoneId(e.domain);if(!t)return{success:!1,message:`No hosted zone found for domain: ${e.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:t,Name:this.normalizeName(e.domain,e.name),TargetHostedZoneId:e.targetHostedZoneId,TargetDNSName:e.targetDnsName,EvaluateTargetHealth:e.evaluateTargetHealth,Type:e.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(t){return{success:!1,message:t instanceof Error?t.message:"Unknown error"}}}async createCloudFrontAlias(e){return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:h.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=h.ALBHostedZoneIds[e.region];if(!t)return{success:!1,message:`Unknown region for ALB: ${e.region}`};return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:t,targetDnsName:e.albDnsName,evaluateTargetHealth:!0})}}async function os(e,t){let r=[],s,o;for(;;){let i=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:s,StartRecordType:o,MaxItems:"100"});if(r.push(...i.ResourceRecordSets),!i.IsTruncated)break;if(s=i.NextRecordName,o=i.NextRecordType,!s)break}return r}function f(e){return e.replace(/\.$/,"").toLowerCase()}function E(e){return e.replace(/\.$/,"")}function w(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${E(e.content)}`;return E(e.content)}function U(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function as(e,t){let r=f(t),s=[],o=[],i=[],a=new Set;for(let c of e){let d=f(c.Name),u=c.Type;if(u==="SOA"||u==="NS"&&d===r){o.push({name:d,type:u,reason:"owned by the destination provider"});continue}if(c.SetIdentifier){o.push({name:d,type:u,reason:`routing policy record (SetIdentifier=${c.SetIdentifier}) has no equivalent — recreate by hand`}),i.push(`${u} ${d} is part of a Route53 routing policy and was NOT migrated`);continue}if(c.AliasTarget){if(a.has(d))continue;a.add(d);let p=f(c.AliasTarget.DNSName);if(s.push({name:d,type:"CNAME",content:p,ttl:300,translatedFrom:`${u} ALIAS → ${p}`}),c.AliasTarget.EvaluateTargetHealth)i.push(`${d} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let p of c.ResourceRecords||[]){let m=q(d,u,p.Value,c.TTL);if("reason"in m){o.push({name:d,type:u,reason:m.reason}),i.push(`${u} ${d}: ${m.reason}`);continue}s.push(m)}}return{zone:r,records:s,skipped:o,warnings:i}}function q(e,t,r,s){let o={name:e,ttl:s};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...o,type:t==="PTR"?"CNAME":t,content:f(r)};case"TXT":return{...o,type:"TXT",content:U(r)};case"MX":{let[i,...a]=r.trim().split(/\s+/);if(!a.length)return{reason:`malformed MX value "${r}"`};return{...o,type:"MX",content:f(a.join(" ")),priority:Number(i)}}case"SRV":{let i=r.trim().split(/\s+/);if(i.length<4)return{reason:`malformed SRV value "${r}"`};let[a,c,d]=i.slice(0,3).map(Number);return{...o,type:"SRV",content:f(i.slice(3).join(" ")),priority:a,weight:c,port:d}}case"NS":return{...o,type:"NS",content:f(r)};case"CAA":return{...o,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var j=new Set(["TXT","MX","SRV","NS","CAA"]);async function cs(e,t){let r=[],s=[],o=new Set;try{let i=await e.listRecords(t.zone);for(let a of i.records||[])o.add(`${f(a.name)}|${a.type}|${w(a)}`)}catch{}for(let i of t.records){let a={...i,proxied:!1},c=`${f(i.name)}|${i.type}|${w(i)}`;if(!j.has(i.type)){let u=await e.upsertRecord(t.zone,a);if(u.success)r.push(i);else s.push({record:i,message:u.message||"unknown provider error"});continue}if(o.has(c)){r.push(i);continue}let d=await e.createRecord(t.zone,a);if(d.success)o.add(c),r.push(i);else s.push({record:i,message:d.message||"unknown provider error"})}return{applied:r,failed:s}}async function ds(e,t){let r=await e.listRecords(t.zone),s=[],o=[],i=new Map;for(let a of r.records||[]){let c=`${f(a.name)}|${a.type}`,d=i.get(c)??[];d.push(w(a)),i.set(c,d)}for(let a of t.records){let c=i.get(`${f(a.name)}|${a.type}`),d=w(a);if(c?.some((u)=>u===d))s.push(a);else o.push({record:a,found:c?.join(", ")})}return{matched:s,missing:o,ok:o.length===0}}class oe{client;region;constructor(e="us-east-1"){this.client=new n,this.region=e}async requestCertificate(e){let t={DomainName:e.DomainName,ValidationMethod:e.ValidationMethod||"DNS"};if(e.SubjectAlternativeNames)t.SubjectAlternativeNames=e.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(t)})).CertificateArn||""}}async describeCertificate(e){let r=(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:e.CertificateArn})})).Certificate||{};return{CertificateArn:r.CertificateArn||"",DomainName:r.DomainName||"",SubjectAlternativeNames:r.SubjectAlternativeNames,Status:r.Status||"PENDING_VALIDATION",Type:r.Type,DomainValidationOptions:r.DomainValidationOptions?.map((s)=>({DomainName:s.DomainName,ValidationDomain:s.ValidationDomain,ValidationStatus:s.ValidationStatus,ResourceRecord:s.ResourceRecord?{Name:s.ResourceRecord.Name,Type:s.ResourceRecord.Type,Value:s.ResourceRecord.Value}:void 0,ValidationMethod:s.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(e){let t={};if(e?.CertificateStatuses)t.CertificateStatuses=e.CertificateStatuses;if(e?.MaxItems)t.MaxItems=e.MaxItems;if(e?.NextToken)t.NextToken=e.NextToken;let r=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(t)});return{CertificateSummaryList:(r.CertificateSummaryList||[]).map((s)=>({CertificateArn:s.CertificateArn,DomainName:s.DomainName})),NextToken:r.NextToken}}async deleteCertificate(e){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:e.CertificateArn})})}async listTagsForCertificate(e){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:e.CertificateArn})})).Tags||[]}}async addTagsToCertificate(e){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:e.CertificateArn,Tags:e.Tags})})}async resendValidationEmail(e){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:e.CertificateArn,Domain:e.Domain,ValidationDomain:e.ValidationDomain})})}async findCertificateByDomain(e){let r=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((s)=>s.DomainName===e||s.DomainName===`*.${e.split(".").slice(1).join(".")}`);if(!r)return null;return this.describeCertificate({CertificateArn:r.CertificateArn})}async waitForCertificateValidation(e,t=60,r=30000){for(let s=0;s<t;s++){let o=await this.describeCertificate({CertificateArn:e});if(o.Status==="ISSUED")return o;if(o.Status==="FAILED"||o.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((i)=>setTimeout(i,r))}return null}async getDnsValidationRecords(e){let t=await this.describeCertificate({CertificateArn:e});if(!t.DomainValidationOptions)return[];return t.DomainValidationOptions.filter((r)=>r.ResourceRecord&&r.ValidationMethod==="DNS").map((r)=>({domainName:r.DomainName,recordName:r.ResourceRecord.Name,recordType:r.ResourceRecord.Type,recordValue:r.ResourceRecord.Value}))}async requestCertificateWithSans(e){let t=new Set;if(t.add(e.DomainName),e.IncludeWww!==!1)t.add(`www.${e.DomainName}`);if(e.IncludeWildcard)t.add(`*.${e.DomainName}`);if(e.AdditionalSans)for(let r of e.AdditionalSans)t.add(r);return this.requestCertificate({DomainName:e.DomainName,SubjectAlternativeNames:Array.from(t),ValidationMethod:"DNS"})}async isCertificateValidForDomain(e,t){let r=await this.describeCertificate({CertificateArn:e});if(r.Status!=="ISSUED")return!1;if(r.DomainName===t)return!0;if(r.DomainName?.startsWith("*.")){let s=r.DomainName.slice(2),o=t.split("."),i=s.split(".");if(o.slice(-i.length).join(".")===s)return!0}if(r.SubjectAlternativeNames)for(let s of r.SubjectAlternativeNames){if(s===t)return!0;if(s.startsWith("*.")){let o=s.slice(2),i=t.split("."),a=o.split(".");if(i.slice(-a.length).join(".")===o)return!0}}return!1}}class or{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new oe(e),this.route53=new h,t&&t.provider!=="route53")this.dnsProvider=T(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s=[],waitForValidation:o=!1,maxWaitMinutes:i=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:a}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:s.length>0?[t,...s]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(a);let c=await this.acm.getDnsValidationRecords(a);if(this.dnsProvider)for(let d of c){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}else if(r)for(let d of c)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${d.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:d.recordName,Type:d.recordType,TTL:300,ResourceRecords:[{Value:d.recordValue}]}}]}});if(o){if(!await this.acm.waitForCertificateValidation(a,i*2,30000))throw Error(`Certificate validation timed out after ${i} minutes`)}return{certificateArn:a,validationRecords:c}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.getDnsValidationRecords(t),i=[];if(this.dnsProvider){let a=s||o[0]?.domainName;for(let c of o){let d=await this.dnsProvider.upsertRecord(a,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});i.push({...c,changeId:d.success?d.id:void 0})}}else if(r)for(let a of o){let c=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${a.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:a.recordName,Type:a.recordType,TTL:300,ResourceRecords:[{Value:a.recordValue}]}}]}});i.push({...a,changeId:c.ChangeInfo?.Id})}return i}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e,o=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let i=s||o[0]?.domainName;for(let a of o)try{await this.dnsProvider.deleteRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue})}catch{}}else if(r)for(let i of o)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${i.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:o=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let i=await this.acm.findCertificateByDomain(t);if(i&&i.Status==="ISSUED")return{certificateArn:i.CertificateArn,isNew:!1};let{certificateArn:a}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:o});return{certificateArn:a,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}class se{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new oe(t),"provider"in e)this.dnsProvider=T(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!1,maxWaitMinutes:o=30}=e,{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);for(let d of a){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}let c="pending";if(s)c=(await this.acm.waitForCertificateValidation(i,o*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:i,validationRecords:a.map((d)=>({domainName:d.domainName,recordName:d.recordName,recordType:d.recordType,recordValue:d.recordValue})),isNew:!0,status:c}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],o=await this.acm.getDnsValidationRecords(t);for(let i of o){let a=await this.dnsProvider.upsertRecord(r,{name:i.recordName,type:i.recordType,content:i.recordValue,ttl:300});if(!a.success)s.push(`Failed to create record for ${i.domainName}: ${a.message}`)}return{success:s.length===0,records:o.map((i)=>({domainName:i.domainName,recordName:i.recordName,recordType:i.recordType,recordValue:i.recordValue})),errors:s}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],o=await this.acm.getDnsValidationRecords(t);for(let i of o){let a=await this.dnsProvider.deleteRecord(r,{name:i.recordName,type:i.recordType,content:i.recordValue});if(!a.success)s.push(`Failed to delete record for ${i.domainName}: ${a.message}`)}return{success:s.length===0,errors:s}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!0,maxWaitMinutes:o}=e,i=await this.acm.findCertificateByDomain(t);if(i&&i.Status==="ISSUED"){let a=i.SubjectAlternativeNames||[i.DomainName],c=a.some((u)=>u===`*.${t}`);if(r.every((u)=>a.includes(u)||c))return{certificateArn:i.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:t,subjectAlternativeNames:r,waitForValidation:s,maxWaitMinutes:o})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:s=!1,additionalSans:o=[],waitForValidation:i=!1}=e,a=[];if(r)a.push(`www.${t}`);if(s)a.push(`*.${t}`);return a.push(...o),this.requestAndValidate({domainName:t,subjectAlternativeNames:a,waitForValidation:i})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(e){let t=await this.acm.describeCertificate({CertificateArn:e});return{status:t.Status,domainValidations:(t.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function ls(e,t,r){return new se({provider:"porkbun",apiKey:e,secretKey:t},r)}function us(e,t,r,s){return new se({provider:"godaddy",apiKey:e,apiSecret:t,environment:s},r)}function ps(e,t,r){return new se({provider:"route53",region:e,hostedZoneId:t},r||e)}function T(e){switch(e.provider){case"route53":return new he(e.region,e.hostedZoneId);case"porkbun":return new ie(e.apiKey,e.secretKey);case"godaddy":return new ke(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new Be(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}async function Oa(e,t){for(let r of t){let s=T(r);if(await s.canManageDomain(e))return s}return null}class An{providers=new Map;configs=[];addConfig(e){return this.configs.push(e),this}addRoute53(e,t){return this.configs.push({provider:"route53",region:e,hostedZoneId:t}),this}addPorkbun(e,t){return this.configs.push({provider:"porkbun",apiKey:e,secretKey:t}),this}addGoDaddy(e,t,r){return this.configs.push({provider:"godaddy",apiKey:e,apiSecret:t,environment:r}),this}addCloudflare(e,t={}){return this.configs.push({provider:"cloudflare",apiToken:e,zoneId:t.zoneId,accountId:t.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let e=process.env.PORKBUN_API_KEY,t=process.env.PORKBUN_SECRET_KEY;if(e&&t)this.addPorkbun(e,t);let r=process.env.GODADDY_API_KEY,s=process.env.GODADDY_API_SECRET;if(r&&s){let i=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,s,i)}let o=process.env.CLOUDFLARE_API_TOKEN;if(o)this.addCloudflare(o,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(e){let t=this.providers.get(e);if(t)return t;let r=this.configs.find((o)=>o.provider===e);if(!r)return null;let s=T(r);return this.providers.set(e,s),s}async getProviderForDomain(e){for(let t of this.configs){let r=T(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>T(e))}}var La=new An;
2
+ export{tt,ie,ke,ts,Be,Tt,hn,rs,ns,nr,ir,fn,sr,is,ss,he,os,as,cs,ds,se,ls,us,ps,T,Oa,An,La,oe,or};
@@ -1,2 +1,2 @@
1
- import{O,Yc}from"./chunk-jvqcw0b4.js";function B(t,s){return`/var/www/${t}-${s}`}var y=new Set(["laravel","php","statamic","wordpress"]);function hr(t){return t.type!=null&&y.has(t.type)}function fr(t){let s=t.proxyTo;if(s==null)return[];return(Array.isArray(s)?s:[s]).map((n)=>String(n).trim()).filter((n)=>n.length>0)}function lc(t){return fr(t).length>0}function fs(t){if(t.deploy)return t.deploy;if(hr(t))return"server";if(t.start)return"server";return"bucket"}function u(t){if(t.redirect)return"redirect";if(lc(t))return"proxy";if(hr(t))return"server-php";if(fs(t)==="bucket")return"bucket";return t.start?"server-app":"server-static"}function Rh(t){return t.infrastructure?.compute!=null||Boolean(t.cloud?.attachTo?.trim())}function Ku(t,s={}){let r=[],n=[],c=t.sites||{},p=Rh(t),f=Yc(t);if(f)r.push(f);let d=new Map;for(let[o,e]of Object.entries(c)){if(!e)continue;let h=fs(e),l=u(e);if(l==="redirect"){if(!e.domain)r.push(`Site '${o}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof e.redirect==="string"?e.redirect:e.redirect?.to))r.push(`Site '${o}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!p)r.push(`Site '${o}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let a=[];if(e.start)a.push("start");if(e.root)a.push("root");if(e.proxyTo)a.push("proxyTo");if(a.length>0)n.push(`Site '${o}' is a redirect site but also sets ${a.join(", ")}. These are ignored.`);continue}if(l==="proxy"){if(!e.domain)r.push(`Site '${o}' is a proxy site but has no \`domain\` to route from.`);if(!p)r.push(`Site '${o}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let i=[];if(e.start)i.push("start");if(e.root)i.push("root");if(typeof e.port==="number")i.push("port");if(e.build)i.push("build");if(e.preStart&&e.preStart.length>0)i.push("preStart");if(i.length>0)n.push(`Site '${o}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${i.join(", ")} ${i.length===1?"is":"are"} ignored — remove ${i.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(h==="server"&&!e.start&&!e.root){r.push(`Site '${o}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(l==="server-php"){if(!p)r.push(`Site '${o}' is a PHP site (type:'${e.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!e.repository?.url)r.push(`Site '${o}' is a PHP site (type:'${e.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(l==="server-app"){if(!p)r.push(`Site '${o}' deploys to a server (deploy:'server'${e.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof e.port==="number"){let i=s.occupiedPorts?.get(e.port);if(i)r.push(`Site '${o}' wants port ${e.port}, which project '${i}' already serves on this box. Attached projects share one port namespace. Give '${o}' a free port, or let the attach allocate one.`);let a=d.get(e.port);if(a)r.push(`Sites '${a}' and '${o}' both use port ${e.port}. Server apps sharing a box must use distinct ports.`);else d.set(e.port,o)}}else if(l==="server-static"){if(!e.root)r.push(`Site '${o}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!p)r.push(`Site '${o}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!e.root)r.push(`Site '${o}' deploys to a bucket but has no \`root\` directory to upload.`);let i=[];if(e.start)i.push("start");if(typeof e.port==="number")i.push("port");if(e.preStart&&e.preStart.length>0)i.push("preStart");if(i.length>0)n.push(`Site '${o}' deploys to a bucket but sets server-only field(s): ${i.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function Wu(t){let s=u(t);return s!=="bucket"&&s!=="redirect"&&s!=="proxy"}function sy(t){return u(t)==="bucket"}function oy(t,s){if(O(t)==="serverless")return!0;let r=Object.entries(t.sites??{}).filter(([,c])=>c!=null),n=s?r.filter(([c])=>c===s):r;if(n.length===0)return!0;return!n.every(([,c])=>{let p=u(c);return p==="redirect"||p==="proxy"})}
2
- export{B,hr,fr,lc,fs,u,Rh,Ku,Wu,sy,oy};
1
+ import{O,id}from"./chunk-y13zcbnp.js";function B(t,s){return`/var/www/${t}-${s}`}var y=new Set(["laravel","php","statamic","wordpress"]);function Ir(t){return t.type!=null&&y.has(t.type)}function Sr(t){let s=t.proxyTo;if(s==null)return[];return(Array.isArray(s)?s:[s]).map((n)=>String(n).trim()).filter((n)=>n.length>0)}function fc(t){return Sr(t).length>0}function bs(t){if(t.deploy)return t.deploy;if(Ir(t))return"server";if(t.start)return"server";return"bucket"}function u(t){if(t.redirect)return"redirect";if(fc(t))return"proxy";if(Ir(t))return"server-php";if(bs(t)==="bucket")return"bucket";return t.start?"server-app":"server-static"}function xh(t){return t.infrastructure?.compute!=null||Boolean(t.cloud?.attachTo?.trim())}function ep(t,s={}){let r=[],n=[],c=t.sites||{},p=xh(t),f=id(t);if(f)r.push(f);let d=new Map;for(let[o,e]of Object.entries(c)){if(!e)continue;let h=bs(e),l=u(e);if(l==="redirect"){if(!e.domain)r.push(`Site '${o}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof e.redirect==="string"?e.redirect:e.redirect?.to))r.push(`Site '${o}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!p)r.push(`Site '${o}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let a=[];if(e.start)a.push("start");if(e.root)a.push("root");if(e.proxyTo)a.push("proxyTo");if(a.length>0)n.push(`Site '${o}' is a redirect site but also sets ${a.join(", ")}. These are ignored.`);continue}if(l==="proxy"){if(!e.domain)r.push(`Site '${o}' is a proxy site but has no \`domain\` to route from.`);if(!p)r.push(`Site '${o}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let i=[];if(e.start)i.push("start");if(e.root)i.push("root");if(typeof e.port==="number")i.push("port");if(e.build)i.push("build");if(e.preStart&&e.preStart.length>0)i.push("preStart");if(i.length>0)n.push(`Site '${o}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${i.join(", ")} ${i.length===1?"is":"are"} ignored — remove ${i.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(h==="server"&&!e.start&&!e.root){r.push(`Site '${o}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(l==="server-php"){if(!p)r.push(`Site '${o}' is a PHP site (type:'${e.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!e.repository?.url)r.push(`Site '${o}' is a PHP site (type:'${e.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(l==="server-app"){if(!p)r.push(`Site '${o}' deploys to a server (deploy:'server'${e.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof e.port==="number"){let i=s.occupiedPorts?.get(e.port);if(i)r.push(`Site '${o}' wants port ${e.port}, which project '${i}' already serves on this box. Attached projects share one port namespace. Give '${o}' a free port, or let the attach allocate one.`);let a=d.get(e.port);if(a)r.push(`Sites '${a}' and '${o}' both use port ${e.port}. Server apps sharing a box must use distinct ports.`);else d.set(e.port,o)}}else if(l==="server-static"){if(!e.root)r.push(`Site '${o}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!p)r.push(`Site '${o}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!e.root)r.push(`Site '${o}' deploys to a bucket but has no \`root\` directory to upload.`);let i=[];if(e.start)i.push("start");if(typeof e.port==="number")i.push("port");if(e.preStart&&e.preStart.length>0)i.push("preStart");if(i.length>0)n.push(`Site '${o}' deploys to a bucket but sets server-only field(s): ${i.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function tp(t){let s=u(t);return s!=="bucket"&&s!=="redirect"&&s!=="proxy"}function uy(t){return u(t)==="bucket"}function py(t,s){if(O(t)==="serverless")return!0;let r=Object.entries(t.sites??{}).filter(([,c])=>c!=null),n=s?r.filter(([c])=>c===s):r;if(n.length===0)return!0;return!n.every(([,c])=>{let p=u(c);return p==="redirect"||p==="proxy"})}
2
+ export{B,Ir,Sr,fc,bs,u,xh,ep,tp,uy,py};
@@ -1,2 +1,2 @@
1
- import{n,l}from"./chunk-30h9rgfn.js";class j{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async describeDBInstances(e){let r={Action:"DescribeDBInstances",Version:"2014-10-31"};if(e?.DBInstanceIdentifier)r.DBInstanceIdentifier=e.DBInstanceIdentifier;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;if(e?.Filters)e.Filters.forEach((o,c)=>{r[`Filters.Filter.${c+1}.Name`]=o.Name,o.Values.forEach((u,d)=>{r[`Filters.Filter.${c+1}.Values.Value.${d+1}`]=u})});let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s}),a=t.DescribeDBInstancesResult||t,i=a.DBInstances?.DBInstance||[];if(!Array.isArray(i))i=i?[i]:[];return{DBInstances:i,Marker:a.Marker}}async describeDBInstance(e){return(await this.describeDBInstances({DBInstanceIdentifier:e})).DBInstances?.[0]}async describeDBClusters(e){let r={Action:"DescribeDBClusters",Version:"2014-10-31"};if(e?.DBClusterIdentifier)r.DBClusterIdentifier=e.DBClusterIdentifier;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;if(e?.Filters)e.Filters.forEach((o,c)=>{r[`Filters.Filter.${c+1}.Name`]=o.Name,o.Values.forEach((u,d)=>{r[`Filters.Filter.${c+1}.Values.Value.${d+1}`]=u})});let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s}),a=t.DescribeDBClustersResult||t,i=a.DBClusters?.DBCluster||[];if(!Array.isArray(i))i=i?[i]:[];return{DBClusters:i,Marker:a.Marker}}async describeDBSnapshots(e){let r={Action:"DescribeDBSnapshots",Version:"2014-10-31"};if(e?.DBInstanceIdentifier)r.DBInstanceIdentifier=e.DBInstanceIdentifier;if(e?.DBSnapshotIdentifier)r.DBSnapshotIdentifier=e.DBSnapshotIdentifier;if(e?.SnapshotType)r.SnapshotType=e.SnapshotType;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s}),a=t.DescribeDBSnapshotsResult||t,i=a.DBSnapshots?.DBSnapshot||[];if(!Array.isArray(i))i=i?[i]:[];return{DBSnapshots:i,Marker:a.Marker}}async describeDBSubnetGroups(e){let r={Action:"DescribeDBSubnetGroups",Version:"2014-10-31"};if(e?.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s}),a=t.DescribeDBSubnetGroupsResult||t,i=a.DBSubnetGroups?.DBSubnetGroup||[];if(!Array.isArray(i))i=i?[i]:[];return{DBSubnetGroups:i,Marker:a.Marker}}async createDBInstance(e){let r={Action:"CreateDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier,DBInstanceClass:e.DBInstanceClass,Engine:e.Engine};if(e.DBClusterIdentifier)r.DBClusterIdentifier=e.DBClusterIdentifier;if(e.MasterUsername)r.MasterUsername=e.MasterUsername;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.DBName)r.DBName=e.DBName;if(e.AllocatedStorage)r.AllocatedStorage=e.AllocatedStorage;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.AvailabilityZone)r.AvailabilityZone=e.AvailabilityZone;if(e.PreferredMaintenanceWindow)r.PreferredMaintenanceWindow=e.PreferredMaintenanceWindow;if(e.PreferredBackupWindow)r.PreferredBackupWindow=e.PreferredBackupWindow;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.MultiAZ!==void 0)r.MultiAZ=e.MultiAZ;if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.AutoMinorVersionUpgrade!==void 0)r.AutoMinorVersionUpgrade=e.AutoMinorVersionUpgrade;if(e.LicenseModel)r.LicenseModel=e.LicenseModel;if(e.PubliclyAccessible!==void 0)r.PubliclyAccessible=e.PubliclyAccessible;if(e.StorageType)r.StorageType=e.StorageType;if(e.StorageEncrypted!==void 0)r.StorageEncrypted=e.StorageEncrypted;if(e.KmsKeyId)r.KmsKeyId=e.KmsKeyId;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((i,o)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${o+1}`]=i});if(e.Tags)e.Tags.forEach((i,o)=>{r[`Tags.Tag.${o+1}.Key`]=i.Key,r[`Tags.Tag.${o+1}.Value`]=i.Value});let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBInstance:(t.CreateDBInstanceResult||t).DBInstance}}async createDBCluster(e){let r={Action:"CreateDBCluster",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier,Engine:e.Engine};if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.MasterUsername)r.MasterUsername=e.MasterUsername;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.DatabaseName)r.DatabaseName=e.DatabaseName;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.StorageEncrypted!==void 0)r.StorageEncrypted=e.StorageEncrypted;if(e.KmsKeyId)r.KmsKeyId=e.KmsKeyId;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.ServerlessV2ScalingConfiguration)r["ServerlessV2ScalingConfiguration.MinCapacity"]=e.ServerlessV2ScalingConfiguration.MinCapacity,r["ServerlessV2ScalingConfiguration.MaxCapacity"]=e.ServerlessV2ScalingConfiguration.MaxCapacity;e.VpcSecurityGroupIds?.forEach((a,i)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${i+1}`]=a});let s=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l(r)).toString()});return{DBCluster:(s.CreateDBClusterResult||s).DBCluster}}async deleteDBInstance(e){let r={Action:"DeleteDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.SkipFinalSnapshot!==void 0)r.SkipFinalSnapshot=e.SkipFinalSnapshot;if(e.FinalDBSnapshotIdentifier)r.FinalDBSnapshotIdentifier=e.FinalDBSnapshotIdentifier;if(e.DeleteAutomatedBackups!==void 0)r.DeleteAutomatedBackups=e.DeleteAutomatedBackups;let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBInstance:(t.DeleteDBInstanceResult||t).DBInstance}}async modifyDBInstance(e){let r={Action:"ModifyDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.DBInstanceClass)r.DBInstanceClass=e.DBInstanceClass;if(e.AllocatedStorage)r.AllocatedStorage=e.AllocatedStorage;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.PreferredBackupWindow)r.PreferredBackupWindow=e.PreferredBackupWindow;if(e.PreferredMaintenanceWindow)r.PreferredMaintenanceWindow=e.PreferredMaintenanceWindow;if(e.MultiAZ!==void 0)r.MultiAZ=e.MultiAZ;if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.AutoMinorVersionUpgrade!==void 0)r.AutoMinorVersionUpgrade=e.AutoMinorVersionUpgrade;if(e.PubliclyAccessible!==void 0)r.PubliclyAccessible=e.PubliclyAccessible;if(e.ApplyImmediately!==void 0)r.ApplyImmediately=e.ApplyImmediately;if(e.StorageType)r.StorageType=e.StorageType;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((i,o)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${o+1}`]=i});let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBInstance:(t.ModifyDBInstanceResult||t).DBInstance}}async modifyDBCluster(e){let r={Action:"ModifyDBCluster",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier};if(e.ServerlessV2ScalingConfiguration)r["ServerlessV2ScalingConfiguration.MinCapacity"]=e.ServerlessV2ScalingConfiguration.MinCapacity,r["ServerlessV2ScalingConfiguration.MaxCapacity"]=e.ServerlessV2ScalingConfiguration.MaxCapacity;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.ApplyImmediately!==void 0)r.ApplyImmediately=e.ApplyImmediately;let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBCluster:(t.ModifyDBClusterResult||t).DBCluster}}async rebootDBCluster(e){let r={Action:"FailoverDBCluster",Version:"2014-10-31",DBClusterIdentifier:e},s=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l(r)).toString()});return{DBCluster:(s.FailoverDBClusterResult||s).DBCluster}}async createDBClusterSnapshot(e,r){let s={Action:"CreateDBClusterSnapshot",Version:"2014-10-31",DBClusterIdentifier:e,DBClusterSnapshotIdentifier:r};return this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l(s)).toString()})}async describeDBClusterSnapshots(e={}){let r={Action:"DescribeDBClusterSnapshots",Version:"2014-10-31",...e},s=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l(r)).toString()}),t=s.DescribeDBClusterSnapshotsResult||s,a=t.DBClusterSnapshots?.DBClusterSnapshot??t.DBClusterSnapshots??[];return{DBClusterSnapshots:Array.isArray(a)?a:[a]}}async deleteDBClusterSnapshot(e){await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l({Action:"DeleteDBClusterSnapshot",Version:"2014-10-31",DBClusterSnapshotIdentifier:e})).toString()})}async deleteDBCluster(e,r){let s={Action:"DeleteDBCluster",Version:"2014-10-31",DBClusterIdentifier:e,SkipFinalSnapshot:!r};if(r)s.FinalDBSnapshotIdentifier=r;let t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l(s)).toString()});return{DBCluster:(t.DeleteDBClusterResult||t).DBCluster}}async restoreDBClusterToPointInTime(e){let r={Action:"RestoreDBClusterToPointInTime",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier,SourceDBClusterIdentifier:e.SourceDBClusterIdentifier};if(e.RestoreToTime)r.RestoreToTime=e.RestoreToTime.toISOString();if(e.UseLatestRestorableTime)r.UseLatestRestorableTime=!0;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((i,o)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${o+1}`]=i});let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBCluster:(t.RestoreDBClusterToPointInTimeResult||t).DBCluster}}async restoreDBClusterFromSnapshot(e){let r={Action:"RestoreDBClusterFromSnapshot",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier,SnapshotIdentifier:e.SnapshotIdentifier,Engine:e.Engine};if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds?.forEach((a,i)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${i+1}`]=a}),e.ServerlessV2ScalingConfiguration)r["ServerlessV2ScalingConfiguration.MinCapacity"]=e.ServerlessV2ScalingConfiguration.MinCapacity,r["ServerlessV2ScalingConfiguration.MaxCapacity"]=e.ServerlessV2ScalingConfiguration.MaxCapacity;let s=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l(r)).toString()});return{DBCluster:(s.RestoreDBClusterFromSnapshotResult||s).DBCluster}}async startDBInstance(e){let s=new URLSearchParams(l({Action:"StartDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e})).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBInstance:(t.StartDBInstanceResult||t).DBInstance}}async stopDBInstance(e){let r={Action:"StopDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.DBSnapshotIdentifier)r.DBSnapshotIdentifier=e.DBSnapshotIdentifier;let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBInstance:(t.StopDBInstanceResult||t).DBInstance}}async rebootDBInstance(e){let r={Action:"RebootDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.ForceFailover!==void 0)r.ForceFailover=e.ForceFailover;let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBInstance:(t.RebootDBInstanceResult||t).DBInstance}}async createDBSnapshot(e){let r={Action:"CreateDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier,DBSnapshotIdentifier:e.DBSnapshotIdentifier};if(e.Tags)e.Tags.forEach((i,o)=>{r[`Tags.Tag.${o+1}.Key`]=i.Key,r[`Tags.Tag.${o+1}.Value`]=i.Value});let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBSnapshot:(t.CreateDBSnapshotResult||t).DBSnapshot}}async deleteDBSnapshot(e){let s=new URLSearchParams(l({Action:"DeleteDBSnapshot",Version:"2014-10-31",DBSnapshotIdentifier:e})).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBSnapshot:(t.DeleteDBSnapshotResult||t).DBSnapshot}}async restoreDBInstanceFromDBSnapshot(e){let r={Action:"RestoreDBInstanceFromDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier,DBSnapshotIdentifier:e.DBSnapshotIdentifier};if(e.DBInstanceClass)r.DBInstanceClass=e.DBInstanceClass;if(e.Port)r.Port=e.Port;if(e.AvailabilityZone)r.AvailabilityZone=e.AvailabilityZone;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.MultiAZ!==void 0)r.MultiAZ=e.MultiAZ;if(e.PubliclyAccessible!==void 0)r.PubliclyAccessible=e.PubliclyAccessible;if(e.AutoMinorVersionUpgrade!==void 0)r.AutoMinorVersionUpgrade=e.AutoMinorVersionUpgrade;if(e.StorageType)r.StorageType=e.StorageType;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((i,o)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${o+1}`]=i});if(e.Tags)e.Tags.forEach((i,o)=>{r[`Tags.Tag.${o+1}.Key`]=i.Key,r[`Tags.Tag.${o+1}.Value`]=i.Value});let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBInstance:(t.RestoreDBInstanceFromDBSnapshotResult||t).DBInstance}}async waitForDBInstanceAvailable(e,r=60,s=30000){for(let t=0;t<r;t++){let a=await this.describeDBInstance(e);if(a?.DBInstanceStatus==="available")return a;if(["deleted","failed","incompatible-restore","incompatible-parameters"].includes(a?.DBInstanceStatus||""))throw Error(`DB instance ${e} is in terminal state: ${a?.DBInstanceStatus}`);await new Promise((i)=>setTimeout(i,s))}throw Error(`Timeout waiting for DB instance ${e} to become available`)}async waitForDBInstanceDeleted(e,r=60,s=30000){for(let t=0;t<r;t++)try{let a=await this.describeDBInstance(e);if(a?.DBInstanceStatus==="deleting"){await new Promise((i)=>setTimeout(i,s));continue}throw Error(`DB instance ${e} is in state: ${a?.DBInstanceStatus}`)}catch(a){if(a.code==="DBInstanceNotFound"||a.code==="DBInstanceNotFoundFault")return;throw a}throw Error(`Timeout waiting for DB instance ${e} to be deleted`)}}
1
+ import{n,l}from"./chunk-2s65yj3g.js";class j{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async describeDBInstances(e){let r={Action:"DescribeDBInstances",Version:"2014-10-31"};if(e?.DBInstanceIdentifier)r.DBInstanceIdentifier=e.DBInstanceIdentifier;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;if(e?.Filters)e.Filters.forEach((o,c)=>{r[`Filters.Filter.${c+1}.Name`]=o.Name,o.Values.forEach((u,d)=>{r[`Filters.Filter.${c+1}.Values.Value.${d+1}`]=u})});let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s}),a=t.DescribeDBInstancesResult||t,i=a.DBInstances?.DBInstance||[];if(!Array.isArray(i))i=i?[i]:[];return{DBInstances:i,Marker:a.Marker}}async describeDBInstance(e){return(await this.describeDBInstances({DBInstanceIdentifier:e})).DBInstances?.[0]}async describeDBClusters(e){let r={Action:"DescribeDBClusters",Version:"2014-10-31"};if(e?.DBClusterIdentifier)r.DBClusterIdentifier=e.DBClusterIdentifier;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;if(e?.Filters)e.Filters.forEach((o,c)=>{r[`Filters.Filter.${c+1}.Name`]=o.Name,o.Values.forEach((u,d)=>{r[`Filters.Filter.${c+1}.Values.Value.${d+1}`]=u})});let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s}),a=t.DescribeDBClustersResult||t,i=a.DBClusters?.DBCluster||[];if(!Array.isArray(i))i=i?[i]:[];return{DBClusters:i,Marker:a.Marker}}async describeDBSnapshots(e){let r={Action:"DescribeDBSnapshots",Version:"2014-10-31"};if(e?.DBInstanceIdentifier)r.DBInstanceIdentifier=e.DBInstanceIdentifier;if(e?.DBSnapshotIdentifier)r.DBSnapshotIdentifier=e.DBSnapshotIdentifier;if(e?.SnapshotType)r.SnapshotType=e.SnapshotType;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s}),a=t.DescribeDBSnapshotsResult||t,i=a.DBSnapshots?.DBSnapshot||[];if(!Array.isArray(i))i=i?[i]:[];return{DBSnapshots:i,Marker:a.Marker}}async describeDBSubnetGroups(e){let r={Action:"DescribeDBSubnetGroups",Version:"2014-10-31"};if(e?.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s}),a=t.DescribeDBSubnetGroupsResult||t,i=a.DBSubnetGroups?.DBSubnetGroup||[];if(!Array.isArray(i))i=i?[i]:[];return{DBSubnetGroups:i,Marker:a.Marker}}async createDBInstance(e){let r={Action:"CreateDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier,DBInstanceClass:e.DBInstanceClass,Engine:e.Engine};if(e.DBClusterIdentifier)r.DBClusterIdentifier=e.DBClusterIdentifier;if(e.MasterUsername)r.MasterUsername=e.MasterUsername;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.DBName)r.DBName=e.DBName;if(e.AllocatedStorage)r.AllocatedStorage=e.AllocatedStorage;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.AvailabilityZone)r.AvailabilityZone=e.AvailabilityZone;if(e.PreferredMaintenanceWindow)r.PreferredMaintenanceWindow=e.PreferredMaintenanceWindow;if(e.PreferredBackupWindow)r.PreferredBackupWindow=e.PreferredBackupWindow;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.MultiAZ!==void 0)r.MultiAZ=e.MultiAZ;if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.AutoMinorVersionUpgrade!==void 0)r.AutoMinorVersionUpgrade=e.AutoMinorVersionUpgrade;if(e.LicenseModel)r.LicenseModel=e.LicenseModel;if(e.PubliclyAccessible!==void 0)r.PubliclyAccessible=e.PubliclyAccessible;if(e.StorageType)r.StorageType=e.StorageType;if(e.StorageEncrypted!==void 0)r.StorageEncrypted=e.StorageEncrypted;if(e.KmsKeyId)r.KmsKeyId=e.KmsKeyId;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((i,o)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${o+1}`]=i});if(e.Tags)e.Tags.forEach((i,o)=>{r[`Tags.Tag.${o+1}.Key`]=i.Key,r[`Tags.Tag.${o+1}.Value`]=i.Value});let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBInstance:(t.CreateDBInstanceResult||t).DBInstance}}async createDBCluster(e){let r={Action:"CreateDBCluster",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier,Engine:e.Engine};if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.MasterUsername)r.MasterUsername=e.MasterUsername;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.DatabaseName)r.DatabaseName=e.DatabaseName;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.StorageEncrypted!==void 0)r.StorageEncrypted=e.StorageEncrypted;if(e.KmsKeyId)r.KmsKeyId=e.KmsKeyId;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.ServerlessV2ScalingConfiguration)r["ServerlessV2ScalingConfiguration.MinCapacity"]=e.ServerlessV2ScalingConfiguration.MinCapacity,r["ServerlessV2ScalingConfiguration.MaxCapacity"]=e.ServerlessV2ScalingConfiguration.MaxCapacity;e.VpcSecurityGroupIds?.forEach((a,i)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${i+1}`]=a});let s=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l(r)).toString()});return{DBCluster:(s.CreateDBClusterResult||s).DBCluster}}async deleteDBInstance(e){let r={Action:"DeleteDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.SkipFinalSnapshot!==void 0)r.SkipFinalSnapshot=e.SkipFinalSnapshot;if(e.FinalDBSnapshotIdentifier)r.FinalDBSnapshotIdentifier=e.FinalDBSnapshotIdentifier;if(e.DeleteAutomatedBackups!==void 0)r.DeleteAutomatedBackups=e.DeleteAutomatedBackups;let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBInstance:(t.DeleteDBInstanceResult||t).DBInstance}}async modifyDBInstance(e){let r={Action:"ModifyDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.DBInstanceClass)r.DBInstanceClass=e.DBInstanceClass;if(e.AllocatedStorage)r.AllocatedStorage=e.AllocatedStorage;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.PreferredBackupWindow)r.PreferredBackupWindow=e.PreferredBackupWindow;if(e.PreferredMaintenanceWindow)r.PreferredMaintenanceWindow=e.PreferredMaintenanceWindow;if(e.MultiAZ!==void 0)r.MultiAZ=e.MultiAZ;if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.AutoMinorVersionUpgrade!==void 0)r.AutoMinorVersionUpgrade=e.AutoMinorVersionUpgrade;if(e.PubliclyAccessible!==void 0)r.PubliclyAccessible=e.PubliclyAccessible;if(e.ApplyImmediately!==void 0)r.ApplyImmediately=e.ApplyImmediately;if(e.StorageType)r.StorageType=e.StorageType;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((i,o)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${o+1}`]=i});let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBInstance:(t.ModifyDBInstanceResult||t).DBInstance}}async modifyDBCluster(e){let r={Action:"ModifyDBCluster",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier};if(e.ServerlessV2ScalingConfiguration)r["ServerlessV2ScalingConfiguration.MinCapacity"]=e.ServerlessV2ScalingConfiguration.MinCapacity,r["ServerlessV2ScalingConfiguration.MaxCapacity"]=e.ServerlessV2ScalingConfiguration.MaxCapacity;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.ApplyImmediately!==void 0)r.ApplyImmediately=e.ApplyImmediately;let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBCluster:(t.ModifyDBClusterResult||t).DBCluster}}async rebootDBCluster(e){let r={Action:"FailoverDBCluster",Version:"2014-10-31",DBClusterIdentifier:e},s=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l(r)).toString()});return{DBCluster:(s.FailoverDBClusterResult||s).DBCluster}}async createDBClusterSnapshot(e,r){let s={Action:"CreateDBClusterSnapshot",Version:"2014-10-31",DBClusterIdentifier:e,DBClusterSnapshotIdentifier:r};return this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l(s)).toString()})}async describeDBClusterSnapshots(e={}){let r={Action:"DescribeDBClusterSnapshots",Version:"2014-10-31",...e},s=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l(r)).toString()}),t=s.DescribeDBClusterSnapshotsResult||s,a=t.DBClusterSnapshots?.DBClusterSnapshot??t.DBClusterSnapshots??[];return{DBClusterSnapshots:Array.isArray(a)?a:[a]}}async deleteDBClusterSnapshot(e){await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l({Action:"DeleteDBClusterSnapshot",Version:"2014-10-31",DBClusterSnapshotIdentifier:e})).toString()})}async deleteDBCluster(e,r){let s={Action:"DeleteDBCluster",Version:"2014-10-31",DBClusterIdentifier:e,SkipFinalSnapshot:!r};if(r)s.FinalDBSnapshotIdentifier=r;let t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l(s)).toString()});return{DBCluster:(t.DeleteDBClusterResult||t).DBCluster}}async restoreDBClusterToPointInTime(e){let r={Action:"RestoreDBClusterToPointInTime",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier,SourceDBClusterIdentifier:e.SourceDBClusterIdentifier};if(e.RestoreToTime)r.RestoreToTime=e.RestoreToTime.toISOString();if(e.UseLatestRestorableTime)r.UseLatestRestorableTime=!0;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((i,o)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${o+1}`]=i});let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBCluster:(t.RestoreDBClusterToPointInTimeResult||t).DBCluster}}async restoreDBClusterFromSnapshot(e){let r={Action:"RestoreDBClusterFromSnapshot",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier,SnapshotIdentifier:e.SnapshotIdentifier,Engine:e.Engine};if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds?.forEach((a,i)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${i+1}`]=a}),e.ServerlessV2ScalingConfiguration)r["ServerlessV2ScalingConfiguration.MinCapacity"]=e.ServerlessV2ScalingConfiguration.MinCapacity,r["ServerlessV2ScalingConfiguration.MaxCapacity"]=e.ServerlessV2ScalingConfiguration.MaxCapacity;let s=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l(r)).toString()});return{DBCluster:(s.RestoreDBClusterFromSnapshotResult||s).DBCluster}}async startDBInstance(e){let s=new URLSearchParams(l({Action:"StartDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e})).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBInstance:(t.StartDBInstanceResult||t).DBInstance}}async stopDBInstance(e){let r={Action:"StopDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.DBSnapshotIdentifier)r.DBSnapshotIdentifier=e.DBSnapshotIdentifier;let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBInstance:(t.StopDBInstanceResult||t).DBInstance}}async rebootDBInstance(e){let r={Action:"RebootDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.ForceFailover!==void 0)r.ForceFailover=e.ForceFailover;let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBInstance:(t.RebootDBInstanceResult||t).DBInstance}}async createDBSnapshot(e){let r={Action:"CreateDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier,DBSnapshotIdentifier:e.DBSnapshotIdentifier};if(e.Tags)e.Tags.forEach((i,o)=>{r[`Tags.Tag.${o+1}.Key`]=i.Key,r[`Tags.Tag.${o+1}.Value`]=i.Value});let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBSnapshot:(t.CreateDBSnapshotResult||t).DBSnapshot}}async deleteDBSnapshot(e){let s=new URLSearchParams(l({Action:"DeleteDBSnapshot",Version:"2014-10-31",DBSnapshotIdentifier:e})).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBSnapshot:(t.DeleteDBSnapshotResult||t).DBSnapshot}}async restoreDBInstanceFromDBSnapshot(e){let r={Action:"RestoreDBInstanceFromDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier,DBSnapshotIdentifier:e.DBSnapshotIdentifier};if(e.DBInstanceClass)r.DBInstanceClass=e.DBInstanceClass;if(e.Port)r.Port=e.Port;if(e.AvailabilityZone)r.AvailabilityZone=e.AvailabilityZone;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.MultiAZ!==void 0)r.MultiAZ=e.MultiAZ;if(e.PubliclyAccessible!==void 0)r.PubliclyAccessible=e.PubliclyAccessible;if(e.AutoMinorVersionUpgrade!==void 0)r.AutoMinorVersionUpgrade=e.AutoMinorVersionUpgrade;if(e.StorageType)r.StorageType=e.StorageType;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((i,o)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${o+1}`]=i});if(e.Tags)e.Tags.forEach((i,o)=>{r[`Tags.Tag.${o+1}.Key`]=i.Key,r[`Tags.Tag.${o+1}.Value`]=i.Value});let s=new URLSearchParams(l(r)).toString(),t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});return{DBInstance:(t.RestoreDBInstanceFromDBSnapshotResult||t).DBInstance}}async waitForDBInstanceAvailable(e,r=60,s=30000){for(let t=0;t<r;t++){let a=await this.describeDBInstance(e);if(a?.DBInstanceStatus==="available")return a;if(["deleted","failed","incompatible-restore","incompatible-parameters"].includes(a?.DBInstanceStatus||""))throw Error(`DB instance ${e} is in terminal state: ${a?.DBInstanceStatus}`);await new Promise((i)=>setTimeout(i,s))}throw Error(`Timeout waiting for DB instance ${e} to become available`)}async waitForDBInstanceDeleted(e,r=60,s=30000){for(let t=0;t<r;t++)try{let a=await this.describeDBInstance(e);if(a?.DBInstanceStatus==="deleting"){await new Promise((i)=>setTimeout(i,s));continue}throw Error(`DB instance ${e} is in state: ${a?.DBInstanceStatus}`)}catch(a){if(a.code==="DBInstanceNotFound"||a.code==="DBInstanceNotFoundFault")return;throw a}throw Error(`Timeout waiting for DB instance ${e} to be deleted`)}}
2
2
  export{j};
@@ -1,4 +1,4 @@
1
- import{n}from"./chunk-30h9rgfn.js";import{a}from"./chunk-yq3pdbz7.js";import{h}from"./chunk-wjgnfg6q.js";import{Oe}from"./chunk-hnkw6pde.js";function S(e,t){let s=[`Action=${e}`,"Version=2010-05-08"];for(let[o,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((c,u)=>{if(typeof c==="object"&&c!==null)for(let[d,m]of Object.entries(c))s.push(`${o}.member.${u+1}.${d}=${encodeURIComponent(String(m))}`);else s.push(`${o}.member.${u+1}=${encodeURIComponent(String(c))}`)});else if(typeof i==="object"){for(let[c,u]of Object.entries(i))if(u!==void 0&&u!==null)s.push(`${o}.${c}=${encodeURIComponent(String(u))}`)}else s.push(`${o}=${encodeURIComponent(String(i))}`)}return s.join("&")}function r(e,t){let s=new RegExp(`<${t}>([^<]*)</${t}>`),o=e.match(s);return o?o[1]:void 0}function l(e,t,s){let o=new RegExp(`<${t}>([\\s\\S]*?)</${t}>`),i=e.match(o);if(!i)return[];let c=[],u=new RegExp(`<${s}>([\\s\\S]*?)</${s}>`,"g"),d;while((d=u.exec(i[1]))!==null)c.push(d[1]);return c}class ge{client;region;constructor(e="us-east-1",t){this.client=new n(void 0,{profile:t}),this.region=e}async request(e,t={}){let s=S(e,t);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s})}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),s=this.parseUsers(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Users:s,IsTruncated:o,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:r(e,"UserName")||"",UserId:r(e,"UserId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),PasswordLastUsed:r(e,"PasswordLastUsed")}}parseUsers(e){return l(e,"Users","member").map((s)=>({UserName:r(s,"UserName")||"",UserId:r(s,"UserId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),PasswordLastUsed:r(s,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),s=this.parseGroup(t),o=this.parseUsers(t),i=r(t,"IsTruncated")==="true",c=r(t,"Marker");return{Group:s,Users:o,IsTruncated:i,Marker:c}}async listGroups(e={}){let t=await this.request("ListGroups",e),s=this.parseGroups(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:o,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),s=this.parseGroups(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:o,Marker:i}}parseGroup(e){return{GroupName:r(e,"GroupName")||"",GroupId:r(e,"GroupId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseGroups(e){return l(e,"Groups","member").map((s)=>({GroupName:r(s,"GroupName")||"",GroupId:r(s,"GroupId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),s=this.parseRoles(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Roles:s,IsTruncated:o,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),s=this.parseTags(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Tags:s,IsTruncated:o,Marker:i}}parseRole(e){return{RoleName:r(e,"RoleName")||"",RoleId:r(e,"RoleId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),AssumeRolePolicyDocument:r(e,"AssumeRolePolicyDocument"),Description:r(e,"Description"),MaxSessionDuration:r(e,"MaxSessionDuration")?Number.parseInt(r(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return l(e,"Roles","member").map((s)=>({RoleName:r(s,"RoleName")||"",RoleId:r(s,"RoleId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),AssumeRolePolicyDocument:r(s,"AssumeRolePolicyDocument"),Description:r(s,"Description"),MaxSessionDuration:r(s,"MaxSessionDuration")?Number.parseInt(r(s,"MaxSessionDuration"),10):void 0}))}parseTags(e){return l(e,"Tags","member").map((s)=>({Key:r(s,"Key")||"",Value:r(s,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate"),Document:r(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),s=this.parsePolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Policies:s,IsTruncated:o,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),s=this.parsePolicyVersions(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Versions:s,IsTruncated:o,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),s=this.parseAttachedPolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:o,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),s=this.parseAttachedPolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:o,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),s=this.parseAttachedPolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:o,Marker:i}}parsePolicy(e){return{PolicyName:r(e,"PolicyName")||"",PolicyId:r(e,"PolicyId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),DefaultVersionId:r(e,"DefaultVersionId"),AttachmentCount:r(e,"AttachmentCount")?Number.parseInt(r(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(e,"PermissionsBoundaryUsageCount")?Number.parseInt(r(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(e,"IsAttachable")==="true",Description:r(e,"Description"),CreateDate:r(e,"CreateDate"),UpdateDate:r(e,"UpdateDate")}}parsePolicies(e){return l(e,"Policies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyId:r(s,"PolicyId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),DefaultVersionId:r(s,"DefaultVersionId"),AttachmentCount:r(s,"AttachmentCount")?Number.parseInt(r(s,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(s,"PermissionsBoundaryUsageCount")?Number.parseInt(r(s,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(s,"IsAttachable")==="true",Description:r(s,"Description"),CreateDate:r(s,"CreateDate"),UpdateDate:r(s,"UpdateDate")}))}parsePolicyVersions(e){return l(e,"Versions","member").map((s)=>({VersionId:r(s,"VersionId")||"",IsDefaultVersion:r(s,"IsDefaultVersion")==="true",CreateDate:r(s,"CreateDate")}))}parseAttachedPolicies(e){return l(e,"AttachedPolicies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyArn:r(s,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:r(t,"UserName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),s=l(t,"PolicyNames","member"),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:o,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:r(t,"GroupName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),s=l(t,"PolicyNames","member"),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:o,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:r(t,"RoleName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),s=l(t,"PolicyNames","member"),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:o,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let s=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(s)return{AccessKey:{UserName:s.UserName||"",AccessKeyId:s.AccessKeyId||"",Status:s.Status||"Active",SecretAccessKey:s.SecretAccessKey||"",CreateDate:s.CreateDate}}}return{AccessKey:{UserName:r(t,"UserName")||"",AccessKeyId:r(t,"AccessKeyId")||"",Status:r(t,"Status")||"Active",SecretAccessKey:r(t,"SecretAccessKey")||"",CreateDate:r(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),s=this.parseAccessKeys(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AccessKeyMetadata:s,IsTruncated:o,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:r(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:r(t,"LastUsedDate"),ServiceName:r(t,"ServiceName"),Region:r(t,"Region")}}}parseAccessKeys(e){return l(e,"AccessKeyMetadata","member").map((s)=>({UserName:r(s,"UserName"),AccessKeyId:r(s,"AccessKeyId")||"",Status:r(s,"Status")||"Active",CreateDate:r(s,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),s=this.parseInstanceProfiles(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:o,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),s=this.parseInstanceProfiles(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:o,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:r(e,"InstanceProfileName")||"",InstanceProfileId:r(e,"InstanceProfileId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseInstanceProfiles(e){return l(e,"InstanceProfiles","member").map((s)=>({InstanceProfileName:r(s,"InstanceProfileName")||"",InstanceProfileId:r(s,"InstanceProfileId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:r(e,"MinimumPasswordLength")?Number.parseInt(r(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:r(e,"RequireSymbols")==="true",RequireNumbers:r(e,"RequireNumbers")==="true",RequireUppercaseCharacters:r(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:r(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:r(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:r(e,"ExpirePasswords")==="true",MaxPasswordAge:r(e,"MaxPasswordAge")?Number.parseInt(r(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:r(e,"PasswordReusePrevention")?Number.parseInt(r(e,"PasswordReusePrevention"),10):void 0,HardExpiry:r(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},s=l(e,"SummaryMap","entry");for(let o of s){let i=r(o,"key"),c=r(o,"value");if(i&&c)t[i]=Number.parseInt(c,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=l(e,"AccountAliases","member"),s=r(e,"IsTruncated")==="true",o=r(e,"Marker");return{AccountAliases:t,IsTruncated:s,Marker:o}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let s=l(e,"EvaluationResults","member").map((c)=>{let d=l(c,"MatchedStatements","member").map((m)=>({SourcePolicyId:r(m,"SourcePolicyId"),SourcePolicyType:r(m,"SourcePolicyType")}));return{EvalActionName:r(c,"EvalActionName")||"",EvalResourceName:r(c,"EvalResourceName"),EvalDecision:r(c,"EvalDecision")||"",MatchedStatements:d.length>0?d:void 0}}),o=r(e,"IsTruncated")==="true",i=r(e,"Marker");return{EvaluationResults:s,IsTruncated:o,Marker:i}}}class Xe{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;let o=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:o.EmailIdentities,NextToken:o.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){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(e)})).MessageId}}async sendBulkEmail(e){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(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,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 t=(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:t?.Max24HourSend?Number(t.Max24HourSend):void 0,MaxSendRate:t?.MaxSendRate?Number(t.MaxSendRate):void 0,SentLast24Hours:t?.SentLast24Hours?Number(t.SentLast24Hours):void 0}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,o={};if(e.text)o.Text={Data:e.text};if(e.html)o.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:o}},ReplyToAddresses:s})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:s})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((s)=>({name:`${s}._domainkey.${e}`,type:"CNAME",value:`${s}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,s=30000){for(let o=0;o<t;o++){if(await this.isDomainVerified(e))return!0;await new Promise((c)=>setTimeout(c,s))}return!1}buildFormBody(e){return Object.entries(e).filter(([,s])=>s!==void 0).map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&")}async createReceiptRuleSet(e){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:e})})}async deleteReceiptRuleSet(e){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:e})})}async setActiveReceiptRuleSet(e){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:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let s=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),o=s?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||s?.ListReceiptRuleSetsResult,i=o?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:o?.NextToken}}async describeReceiptRuleSet(e){let t=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:e})}),s=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,o=s?.Rules?.member;return{Metadata:s?.Metadata,Rules:Array.isArray(o)?o:o?[o]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,o)=>{t[`Rule.Recipients.member.${o+1}`]=s});e.Rule.Actions.forEach((s,o)=>{let i=o+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.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(t)})}async deleteReceiptRule(e,t){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:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=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"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let s=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(s)?s:s?[s]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,o)=>{t[`Rule.Recipients.member.${o+1}`]=s});e.Rule.Actions.forEach((s,o)=>{let i=o+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.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(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),s={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((c,u)=>{s[`Destinations.member.${u+1}`]=c});let o=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(s)});return{MessageId:(o?.SendRawEmailResponse?.SendRawEmailResult||o?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class ln{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new Xe(this.region),this.s3=new a(this.region),this.iam=new ge(this.region),this.route53=new h(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let s=e.fromName?`${e.fromName} <${t}>`:t,o=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:s,to:o,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,s,o);return{messageId:(await this.ses.sendEmail({FromEmailAddress:s,Destination:{ToAddresses:o,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:s,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:s,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let o=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:o.DkimAttributes?.Status,DkimAttributes:o.DkimAttributes,SendingEnabled:o.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let s=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],s=await this.ses.getDkimRecords(e);for(let o of s)t.push({type:o.type,name:o.name,value:o.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(o){if(!o.message?.includes("already exists")&&o.code!=="AlreadyExists")throw o}let s=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)s.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}})}catch(o){if(o.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}});else throw o}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((s)=>({key:s.Key||"",lastModified:s.LastModified||"",size:s.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:s}=await import("./chunk-9w32efae.js"),o=new s,i=(g,y)=>{let P={Action:g,Version:"2010-05-08",...y};return Object.entries(P).map(([A,R])=>`${encodeURIComponent(A)}=${encodeURIComponent(R)}`).join("&")};try{await o.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(g){if(!g.message?.includes("EntityAlreadyExists"))throw g}let c={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},u=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await o.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:u,PolicyDocument:JSON.stringify(c)})})}catch{}let m=(await o.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!m?.AccessKeyId||!m?.SecretAccessKey)throw Error("Failed to create access key");let p=this.deriveSmtpPassword(m.SecretAccessKey);return{username:m.AccessKeyId,password:p,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=Oe("node:crypto"),s="SendRawEmail",o=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([o,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,o=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((m)=>m.Name===o))await this.s3.createBucket(o);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:s,bucketName:o,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let d=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:o,dnsRecords:d}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,o=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,s)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(o)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,s){let o=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
1
+ import{n}from"./chunk-2s65yj3g.js";import{a}from"./chunk-6gtqjsg9.js";import{h}from"./chunk-65ajja2a.js";import{Me}from"./chunk-p9fqsz06.js";function S(e,t){let s=[`Action=${e}`,"Version=2010-05-08"];for(let[o,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((c,u)=>{if(typeof c==="object"&&c!==null)for(let[d,m]of Object.entries(c))s.push(`${o}.member.${u+1}.${d}=${encodeURIComponent(String(m))}`);else s.push(`${o}.member.${u+1}=${encodeURIComponent(String(c))}`)});else if(typeof i==="object"){for(let[c,u]of Object.entries(i))if(u!==void 0&&u!==null)s.push(`${o}.${c}=${encodeURIComponent(String(u))}`)}else s.push(`${o}=${encodeURIComponent(String(i))}`)}return s.join("&")}function r(e,t){let s=new RegExp(`<${t}>([^<]*)</${t}>`),o=e.match(s);return o?o[1]:void 0}function l(e,t,s){let o=new RegExp(`<${t}>([\\s\\S]*?)</${t}>`),i=e.match(o);if(!i)return[];let c=[],u=new RegExp(`<${s}>([\\s\\S]*?)</${s}>`,"g"),d;while((d=u.exec(i[1]))!==null)c.push(d[1]);return c}class me{client;region;constructor(e="us-east-1",t){this.client=new n(void 0,{profile:t}),this.region=e}async request(e,t={}){let s=S(e,t);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s})}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),s=this.parseUsers(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Users:s,IsTruncated:o,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:r(e,"UserName")||"",UserId:r(e,"UserId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),PasswordLastUsed:r(e,"PasswordLastUsed")}}parseUsers(e){return l(e,"Users","member").map((s)=>({UserName:r(s,"UserName")||"",UserId:r(s,"UserId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),PasswordLastUsed:r(s,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),s=this.parseGroup(t),o=this.parseUsers(t),i=r(t,"IsTruncated")==="true",c=r(t,"Marker");return{Group:s,Users:o,IsTruncated:i,Marker:c}}async listGroups(e={}){let t=await this.request("ListGroups",e),s=this.parseGroups(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:o,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),s=this.parseGroups(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:o,Marker:i}}parseGroup(e){return{GroupName:r(e,"GroupName")||"",GroupId:r(e,"GroupId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseGroups(e){return l(e,"Groups","member").map((s)=>({GroupName:r(s,"GroupName")||"",GroupId:r(s,"GroupId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),s=this.parseRoles(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Roles:s,IsTruncated:o,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),s=this.parseTags(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Tags:s,IsTruncated:o,Marker:i}}parseRole(e){return{RoleName:r(e,"RoleName")||"",RoleId:r(e,"RoleId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),AssumeRolePolicyDocument:r(e,"AssumeRolePolicyDocument"),Description:r(e,"Description"),MaxSessionDuration:r(e,"MaxSessionDuration")?Number.parseInt(r(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return l(e,"Roles","member").map((s)=>({RoleName:r(s,"RoleName")||"",RoleId:r(s,"RoleId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),AssumeRolePolicyDocument:r(s,"AssumeRolePolicyDocument"),Description:r(s,"Description"),MaxSessionDuration:r(s,"MaxSessionDuration")?Number.parseInt(r(s,"MaxSessionDuration"),10):void 0}))}parseTags(e){return l(e,"Tags","member").map((s)=>({Key:r(s,"Key")||"",Value:r(s,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate"),Document:r(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),s=this.parsePolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Policies:s,IsTruncated:o,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),s=this.parsePolicyVersions(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Versions:s,IsTruncated:o,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),s=this.parseAttachedPolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:o,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),s=this.parseAttachedPolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:o,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),s=this.parseAttachedPolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:o,Marker:i}}parsePolicy(e){return{PolicyName:r(e,"PolicyName")||"",PolicyId:r(e,"PolicyId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),DefaultVersionId:r(e,"DefaultVersionId"),AttachmentCount:r(e,"AttachmentCount")?Number.parseInt(r(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(e,"PermissionsBoundaryUsageCount")?Number.parseInt(r(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(e,"IsAttachable")==="true",Description:r(e,"Description"),CreateDate:r(e,"CreateDate"),UpdateDate:r(e,"UpdateDate")}}parsePolicies(e){return l(e,"Policies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyId:r(s,"PolicyId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),DefaultVersionId:r(s,"DefaultVersionId"),AttachmentCount:r(s,"AttachmentCount")?Number.parseInt(r(s,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(s,"PermissionsBoundaryUsageCount")?Number.parseInt(r(s,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(s,"IsAttachable")==="true",Description:r(s,"Description"),CreateDate:r(s,"CreateDate"),UpdateDate:r(s,"UpdateDate")}))}parsePolicyVersions(e){return l(e,"Versions","member").map((s)=>({VersionId:r(s,"VersionId")||"",IsDefaultVersion:r(s,"IsDefaultVersion")==="true",CreateDate:r(s,"CreateDate")}))}parseAttachedPolicies(e){return l(e,"AttachedPolicies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyArn:r(s,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:r(t,"UserName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),s=l(t,"PolicyNames","member"),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:o,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:r(t,"GroupName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),s=l(t,"PolicyNames","member"),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:o,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:r(t,"RoleName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),s=l(t,"PolicyNames","member"),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:o,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let s=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(s)return{AccessKey:{UserName:s.UserName||"",AccessKeyId:s.AccessKeyId||"",Status:s.Status||"Active",SecretAccessKey:s.SecretAccessKey||"",CreateDate:s.CreateDate}}}return{AccessKey:{UserName:r(t,"UserName")||"",AccessKeyId:r(t,"AccessKeyId")||"",Status:r(t,"Status")||"Active",SecretAccessKey:r(t,"SecretAccessKey")||"",CreateDate:r(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),s=this.parseAccessKeys(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AccessKeyMetadata:s,IsTruncated:o,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:r(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:r(t,"LastUsedDate"),ServiceName:r(t,"ServiceName"),Region:r(t,"Region")}}}parseAccessKeys(e){return l(e,"AccessKeyMetadata","member").map((s)=>({UserName:r(s,"UserName"),AccessKeyId:r(s,"AccessKeyId")||"",Status:r(s,"Status")||"Active",CreateDate:r(s,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),s=this.parseInstanceProfiles(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:o,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),s=this.parseInstanceProfiles(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:o,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:r(e,"InstanceProfileName")||"",InstanceProfileId:r(e,"InstanceProfileId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseInstanceProfiles(e){return l(e,"InstanceProfiles","member").map((s)=>({InstanceProfileName:r(s,"InstanceProfileName")||"",InstanceProfileId:r(s,"InstanceProfileId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:r(e,"MinimumPasswordLength")?Number.parseInt(r(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:r(e,"RequireSymbols")==="true",RequireNumbers:r(e,"RequireNumbers")==="true",RequireUppercaseCharacters:r(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:r(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:r(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:r(e,"ExpirePasswords")==="true",MaxPasswordAge:r(e,"MaxPasswordAge")?Number.parseInt(r(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:r(e,"PasswordReusePrevention")?Number.parseInt(r(e,"PasswordReusePrevention"),10):void 0,HardExpiry:r(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},s=l(e,"SummaryMap","entry");for(let o of s){let i=r(o,"key"),c=r(o,"value");if(i&&c)t[i]=Number.parseInt(c,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=l(e,"AccountAliases","member"),s=r(e,"IsTruncated")==="true",o=r(e,"Marker");return{AccountAliases:t,IsTruncated:s,Marker:o}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let s=l(e,"EvaluationResults","member").map((c)=>{let d=l(c,"MatchedStatements","member").map((m)=>({SourcePolicyId:r(m,"SourcePolicyId"),SourcePolicyType:r(m,"SourcePolicyType")}));return{EvalActionName:r(c,"EvalActionName")||"",EvalResourceName:r(c,"EvalResourceName"),EvalDecision:r(c,"EvalDecision")||"",MatchedStatements:d.length>0?d:void 0}}),o=r(e,"IsTruncated")==="true",i=r(e,"Marker");return{EvaluationResults:s,IsTruncated:o,Marker:i}}}class et{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;let o=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:o.EmailIdentities,NextToken:o.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){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(e)})).MessageId}}async sendBulkEmail(e){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(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,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 t=(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:t?.Max24HourSend?Number(t.Max24HourSend):void 0,MaxSendRate:t?.MaxSendRate?Number(t.MaxSendRate):void 0,SentLast24Hours:t?.SentLast24Hours?Number(t.SentLast24Hours):void 0}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,o={};if(e.text)o.Text={Data:e.text};if(e.html)o.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:o}},ReplyToAddresses:s})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:s})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((s)=>({name:`${s}._domainkey.${e}`,type:"CNAME",value:`${s}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,s=30000){for(let o=0;o<t;o++){if(await this.isDomainVerified(e))return!0;await new Promise((c)=>setTimeout(c,s))}return!1}buildFormBody(e){return Object.entries(e).filter(([,s])=>s!==void 0).map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&")}async createReceiptRuleSet(e){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:e})})}async deleteReceiptRuleSet(e){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:e})})}async setActiveReceiptRuleSet(e){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:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let s=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),o=s?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||s?.ListReceiptRuleSetsResult,i=o?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:o?.NextToken}}async describeReceiptRuleSet(e){let t=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:e})}),s=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,o=s?.Rules?.member;return{Metadata:s?.Metadata,Rules:Array.isArray(o)?o:o?[o]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,o)=>{t[`Rule.Recipients.member.${o+1}`]=s});e.Rule.Actions.forEach((s,o)=>{let i=o+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.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(t)})}async deleteReceiptRule(e,t){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:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=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"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let s=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(s)?s:s?[s]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,o)=>{t[`Rule.Recipients.member.${o+1}`]=s});e.Rule.Actions.forEach((s,o)=>{let i=o+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.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(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),s={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((c,u)=>{s[`Destinations.member.${u+1}`]=c});let o=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(s)});return{MessageId:(o?.SendRawEmailResponse?.SendRawEmailResult||o?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class mn{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new et(this.region),this.s3=new a(this.region),this.iam=new me(this.region),this.route53=new h(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let s=e.fromName?`${e.fromName} <${t}>`:t,o=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:s,to:o,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,s,o);return{messageId:(await this.ses.sendEmail({FromEmailAddress:s,Destination:{ToAddresses:o,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:s,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:s,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let o=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:o.DkimAttributes?.Status,DkimAttributes:o.DkimAttributes,SendingEnabled:o.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let s=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],s=await this.ses.getDkimRecords(e);for(let o of s)t.push({type:o.type,name:o.name,value:o.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(o){if(!o.message?.includes("already exists")&&o.code!=="AlreadyExists")throw o}let s=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)s.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}})}catch(o){if(o.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}});else throw o}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((s)=>({key:s.Key||"",lastModified:s.LastModified||"",size:s.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:s}=await import("./chunk-05qawkra.js"),o=new s,i=(g,y)=>{let P={Action:g,Version:"2010-05-08",...y};return Object.entries(P).map(([A,R])=>`${encodeURIComponent(A)}=${encodeURIComponent(R)}`).join("&")};try{await o.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(g){if(!g.message?.includes("EntityAlreadyExists"))throw g}let c={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},u=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await o.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:u,PolicyDocument:JSON.stringify(c)})})}catch{}let m=(await o.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!m?.AccessKeyId||!m?.SecretAccessKey)throw Error("Failed to create access key");let p=this.deriveSmtpPassword(m.SecretAccessKey);return{username:m.AccessKeyId,password:p,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=Me("node:crypto"),s="SendRawEmail",o=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([o,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,o=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((m)=>m.Name===o))await this.s3.createBucket(o);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:s,bucketName:o,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let d=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:o,dnsRecords:d}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,o=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,s)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(o)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,s){let o=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
2
2
  `,i+=`To: ${s.join(", ")}\r
3
3
  `,e.cc){let c=Array.isArray(e.cc)?e.cc:[e.cc];i+=`Cc: ${c.join(", ")}\r
4
4
  `}if(i+=`Subject: ${e.subject}\r
@@ -30,5 +30,5 @@ import{n}from"./chunk-30h9rgfn.js";import{a}from"./chunk-yq3pdbz7.js";import{h}f
30
30
  `,i+=`\r
31
31
  `,i+=`${c.content}\r
32
32
  `;return i+=`--${o}--\r
33
- `,i}}var Lm=new ln;
34
- export{ge,Xe,ln,Lm};
33
+ `,i}}var Hm=new mn;
34
+ export{me,et,mn,Hm};
@@ -1,8 +1,8 @@
1
- var l={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},d={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function W(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function Vn(e){if(e.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(e))return!1;if(/\[[^\]]*\][+*]\{/.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}function b(e,r){let t=[],o=[],s=r;for(let n of e){if(n.enabled===!1)continue;if(n.key&&(n.key.source==="cookie"||n.key.source==="header")&&!n.key.name){o.push({ruleId:n.id,reason:"The rule keys on a header or cookie but names none."});continue}let c=n.path?hs(n.path):".*";if(!Vn(c)){o.push({ruleId:n.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let u=[`SecRule REQUEST_URI "@rx ${W(c)}"`];if(n.methods?.length)u.push(` "chain,id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${W(n.id)}'"`);else u.push(` "id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${W(n.id)}'"`);if(t.push(`# Marks requests governed by the ts-cloud rate limit "${W(n.id)}".`),t.push(u.join(" \\\n")),n.methods?.length)t.push(` SecRule REQUEST_METHOD "@within ${W(n.methods.join(" ").toUpperCase())}" "t:none"`);t.push(""),s++}return{lines:t,unmapped:o}}function hs(e){return`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function oc(e={},r=[]){let t=e.mode??l.mode,o=[],s=e.paranoiaLevel??l.paranoiaLevel,n=e.inboundThreshold??l.inboundThreshold,c=e.outboundThreshold??l.outboundThreshold,u=e.maxBodyBytes??l.maxBodyBytes,h=e.rejectOversizedBody!==!1;if(t==="blocking"&&s>=3)o.push(`Paranoia level ${s} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(t==="blocking")o.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!h)o.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(e.bypassPaths?.length)o.push(`${e.bypassPaths.length} path(s) bypass inspection entirely.`);let i=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${t}. Paranoia level: ${s}.`,""];if(t==="off")return i.push("SecRuleEngine Off",""),{config:`${i.join(`
1
+ var l={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},d={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function W(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function Wn(e){if(e.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(e))return!1;if(/\[[^\]]*\][+*]\{/.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}function b(e,r){let t=[],o=[],s=r;for(let n of e){if(n.enabled===!1)continue;if(n.key&&(n.key.source==="cookie"||n.key.source==="header")&&!n.key.name){o.push({ruleId:n.id,reason:"The rule keys on a header or cookie but names none."});continue}let c=n.path?Cs(n.path):".*";if(!Wn(c)){o.push({ruleId:n.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let u=[`SecRule REQUEST_URI "@rx ${W(c)}"`];if(n.methods?.length)u.push(` "chain,id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${W(n.id)}'"`);else u.push(` "id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${W(n.id)}'"`);if(t.push(`# Marks requests governed by the ts-cloud rate limit "${W(n.id)}".`),t.push(u.join(" \\\n")),n.methods?.length)t.push(` SecRule REQUEST_METHOD "@within ${W(n.methods.join(" ").toUpperCase())}" "t:none"`);t.push(""),s++}return{lines:t,unmapped:o}}function Cs(e){return`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function pc(e={},r=[]){let t=e.mode??l.mode,o=[],s=e.paranoiaLevel??l.paranoiaLevel,n=e.inboundThreshold??l.inboundThreshold,c=e.outboundThreshold??l.outboundThreshold,u=e.maxBodyBytes??l.maxBodyBytes,h=e.rejectOversizedBody!==!1;if(t==="blocking"&&s>=3)o.push(`Paranoia level ${s} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(t==="blocking")o.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!h)o.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(e.bypassPaths?.length)o.push(`${e.bypassPaths.length} path(s) bypass inspection entirely.`);let i=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${t}. Paranoia level: ${s}.`,""];if(t==="off")return i.push("SecRuleEngine Off",""),{config:`${i.join(`
2
2
  `)}
3
- `,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${u}`,`SecRequestBodyNoFilesLimit ${Math.min(u,131072)}`,`SecRequestBodyLimitAction ${h?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${W(e.auditLogPath??l.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${t==="blocking"?`deny,status:${e.blockStatus??l.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${s}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${n}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${c}"`,'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 g=d.bypassBase;for(let a of e.bypassPaths??[]){let y=hs(a);if(!Vn(y)){o.push(`Bypass path "${a}" was dropped: it compiles to an unsafe regular expression.`);continue}i.push(`# Inspection bypass for ${W(a)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${W(y)}" "id:${g},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),g++}let m=d.exclusionBase;for(let a of e.exclusions??[]){if(!Number.isInteger(a.ruleId)||a.ruleId<=0){o.push(`Exclusion with rule id "${a.ruleId}" was dropped: the id is not a positive integer.`);continue}if(i.push(`# ${W(a.reason)}`),a.pathPattern){if(!Vn(a.pathPattern)){o.push(`Exclusion for rule ${a.ruleId} was dropped: its path pattern is unsafe.`);continue}i.push(`SecRule REQUEST_URI "@rx ${W(a.pathPattern)}" "id:${m},phase:1,pass,nolog,ctl:ruleRemoveById=${a.ruleId}"`),m++}else i.push(`SecRuleRemoveById ${a.ruleId}`);i.push("")}let p=b(r,d.rateLimitBase);if(p.lines.length>0)i.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...p.lines);let f=d.customBase;for(let a of e.customRules??[])i.push(`# Operator-supplied rule ${f}.`,a.trim(),""),f++;if(t==="blocking")i.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:${e.blockStatus??l.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${i.join(`
3
+ `,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${u}`,`SecRequestBodyNoFilesLimit ${Math.min(u,131072)}`,`SecRequestBodyLimitAction ${h?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${W(e.auditLogPath??l.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${t==="blocking"?`deny,status:${e.blockStatus??l.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${s}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${n}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${c}"`,'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 g=d.bypassBase;for(let a of e.bypassPaths??[]){let y=Cs(a);if(!Wn(y)){o.push(`Bypass path "${a}" was dropped: it compiles to an unsafe regular expression.`);continue}i.push(`# Inspection bypass for ${W(a)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${W(y)}" "id:${g},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),g++}let m=d.exclusionBase;for(let a of e.exclusions??[]){if(!Number.isInteger(a.ruleId)||a.ruleId<=0){o.push(`Exclusion with rule id "${a.ruleId}" was dropped: the id is not a positive integer.`);continue}if(i.push(`# ${W(a.reason)}`),a.pathPattern){if(!Wn(a.pathPattern)){o.push(`Exclusion for rule ${a.ruleId} was dropped: its path pattern is unsafe.`);continue}i.push(`SecRule REQUEST_URI "@rx ${W(a.pathPattern)}" "id:${m},phase:1,pass,nolog,ctl:ruleRemoveById=${a.ruleId}"`),m++}else i.push(`SecRuleRemoveById ${a.ruleId}`);i.push("")}let p=b(r,d.rateLimitBase);if(p.lines.length>0)i.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...p.lines);let f=d.customBase;for(let a of e.customRules??[])i.push(`# Operator-supplied rule ${f}.`,a.trim(),""),f++;if(t==="blocking")i.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:${e.blockStatus??l.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${i.join(`
4
4
  `)}
5
- `,unmappedRateLimits:p.unmapped,warnings:o,mode:t}}function jn(e={},r=[],t={}){let o=t.binary??"/usr/local/bin/zig-waf",s=t.configPath??"/etc/ts-cloud/waf.conf",n=oc(e,r);return`#!/usr/bin/env bash
5
+ `,unmappedRateLimits:p.unmapped,warnings:o,mode:t}}function Jn(e={},r=[],t={}){let o=t.binary??"/usr/local/bin/zig-waf",s=t.configPath??"/etc/ts-cloud/waf.conf",n=pc(e,r);return`#!/usr/bin/env bash
6
6
  # Managed by ts-cloud. Installs the zig-waf ruleset.
7
7
  set -euo pipefail
8
8
 
@@ -33,5 +33,5 @@ fi
33
33
 
34
34
  mv "${s}.new" "${s}"
35
35
  echo "ts-cloud: WAF config installed (mode: ${n.mode})"
36
- `}function Ru(e,r){return e.map((t)=>({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"event",source:"zig-waf",name:t.action==="blocked"?"waf.blocked":"waf.matched",timestamp:t.timestamp,value:1,host:t.host,pathTemplate:t.path,method:t.method,attributes:{ruleId:t.ruleId??null,anomalyScore:t.anomalyScore,action:t.action,messages:t.messages.slice(0,5)}}))}
37
- export{W,Vn,hs,oc,jn,Ru};
36
+ `}function xu(e,r){return e.map((t)=>({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"event",source:"zig-waf",name:t.action==="blocked"?"waf.blocked":"waf.matched",timestamp:t.timestamp,value:1,host:t.host,pathTemplate:t.path,method:t.method,attributes:{ruleId:t.ruleId??null,anomalyScore:t.anomalyScore,action:t.action,messages:t.messages.slice(0,5)}}))}
37
+ export{W,Wn,Cs,pc,Jn,xu};
@@ -1,4 +1,4 @@
1
- import{eh}from"./chunk-hnkw6pde.js";var wQ=eh(function(qA,nI){/*!
1
+ import{oh}from"./chunk-p9fqsz06.js";var wQ=oh(function(qA,nI){/*!
2
2
  * hash-wasm (https://www.npmjs.com/package/hash-wasm)
3
3
  * (c) Dani Biro
4
4
  * @license MIT
@@ -1,2 +1,2 @@
1
- import{createRequire as q}from"node:module";var k=Object.create;var{getPrototypeOf:l,defineProperty:i,getOwnPropertyNames:m}=Object;var j=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,Zm=(a,b,d)=>{var f=a!=null&&typeof a==="object";if(f){var g=b?o??=new WeakMap:p??=new WeakMap,h=g.get(a);if(h)return h}d=a!=null?k(l(a)):{};let c=b||!a||!a.__esModule||!j.call(a,"default")?i(d,"default",{value:a,enumerable:!0}):d;if(a&&typeof a==="object"||typeof a==="function"){for(let e of m(a))if(!j.call(c,e))i(c,e,{get:n.bind(a,e),enumerable:!0})}if(f)g.set(a,c);return c};var eh=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var Oe=q(import.meta.url);
2
- export{Zm,eh,Oe};
1
+ import{createRequire as q}from"node:module";var k=Object.create;var{getPrototypeOf:l,defineProperty:i,getOwnPropertyNames:m}=Object;var j=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,sh=(a,b,d)=>{var f=a!=null&&typeof a==="object";if(f){var g=b?o??=new WeakMap:p??=new WeakMap,h=g.get(a);if(h)return h}d=a!=null?k(l(a)):{};let c=b||!a||!a.__esModule||!j.call(a,"default")?i(d,"default",{value:a,enumerable:!0}):d;if(a&&typeof a==="object"||typeof a==="function"){for(let e of m(a))if(!j.call(c,e))i(c,e,{get:n.bind(a,e),enumerable:!0})}if(f)g.set(a,c);return c};var oh=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var Me=q(import.meta.url);
2
+ export{sh,oh,Me};
@@ -1,7 +1,7 @@
1
- var Vc={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function h(e){return{...Vc,...e.thresholds}}var _=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function Dr(e){if(!_.test(e))return!1;let[t,n]=e.split("/");if(t.includes(":"))return n==null||Number(n)>=0&&Number(n)<=128;let s=t.split(".");if(s.length!==4||s.some((a)=>Number(a)>255||a===""))return!1;return n==null||Number(n)>=0&&Number(n)<=32}function f(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(Dr))]}function y(e){let t=(e??[80,443]).filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535);return[...new Set(t)].sort((n,s)=>n-s)}function jc(e={}){let t=h(e);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,t.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 zc(e={}){let t=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[n,s]of Object.entries(jc(e)))t.push(`${n} = ${s}`);return`${t.join(`
1
+ var Xc={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function h(e){return{...Xc,...e.thresholds}}var _=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function Br(e){if(!_.test(e))return!1;let[t,n]=e.split("/");if(t.includes(":"))return n==null||Number(n)>=0&&Number(n)<=128;let s=t.split(".");if(s.length!==4||s.some((a)=>Number(a)>255||a===""))return!1;return n==null||Number(n)>=0&&Number(n)<=32}function f(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(Br))]}function y(e){let t=(e??[80,443]).filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535);return[...new Set(t)].sort((n,s)=>n-s)}function Yc(e={}){let t=h(e);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,t.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 Zc(e={}){let t=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[n,s]of Object.entries(Yc(e)))t.push(`${n} = ${s}`);return`${t.join(`
2
2
  `)}
3
- `}function Kc(e={}){let t=h(e),n=y(e.ports),s=f(e.allowlist),a=f(e.blocklist),l=e.monitorOnly?"counter":"counter drop",i=e.originProtection?.enabled?f(e.originProtection.cdnRanges):[],c=s.filter((r)=>!r.includes(":")),p=s.filter((r)=>r.includes(":")),u=a.filter((r)=>!r.includes(":")),o=["#!/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 ${t.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${t.banSeconds}s; }`];if(c.length>0)o.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${c.join(", ")} } }`);if(p.length>0)o.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${p.join(", ")} } }`);if(u.length>0)o.push(` set block4 { type ipv4_addr; flags interval; elements = { ${u.join(", ")} } }`);if(i.length>0)o.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${i.filter((r)=>!r.includes(":")).join(", ")} } }`);if(o.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"),c.length>0)o.push(" ip saddr @allow4 accept");if(p.length>0)o.push(" ip6 saddr @allow6 accept");if(u.length>0)o.push(" ip saddr @block4 counter drop");if(o.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),o.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 ${t.icmpPerSecond}/second burst ${t.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),n.length>0){let r=n.join(", ");if(o.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${r} } ct state new limit rate ${t.synPerSecond}/second burst ${t.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${r} } ct state new meter conn_rate4 { ip saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned4 { ip saddr } ${l}`,` tcp dport { ${r} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned6 { ip6 saddr } ${l}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${r} } ct state new meter conn_count4 { ip saddr ct count over ${t.concurrentPerSource} } ${l}`,` tcp dport { ${r} } ct state new meter conn_count6 { ip6 saddr ct count over ${t.concurrentPerSource} } ${l}`,""),i.length>0)o.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 { ${r} } ip saddr != @cdn4 counter drop`,"")}return o.push(" }","}",""),o.join(`
4
- `)}function li(e={}){return`#!/usr/bin/env bash
3
+ `}function ed(e={}){let t=h(e),n=y(e.ports),s=f(e.allowlist),a=f(e.blocklist),l=e.monitorOnly?"counter":"counter drop",i=e.originProtection?.enabled?f(e.originProtection.cdnRanges):[],c=s.filter((r)=>!r.includes(":")),p=s.filter((r)=>r.includes(":")),u=a.filter((r)=>!r.includes(":")),o=["#!/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 ${t.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${t.banSeconds}s; }`];if(c.length>0)o.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${c.join(", ")} } }`);if(p.length>0)o.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${p.join(", ")} } }`);if(u.length>0)o.push(` set block4 { type ipv4_addr; flags interval; elements = { ${u.join(", ")} } }`);if(i.length>0)o.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${i.filter((r)=>!r.includes(":")).join(", ")} } }`);if(o.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"),c.length>0)o.push(" ip saddr @allow4 accept");if(p.length>0)o.push(" ip6 saddr @allow6 accept");if(u.length>0)o.push(" ip saddr @block4 counter drop");if(o.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),o.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 ${t.icmpPerSecond}/second burst ${t.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),n.length>0){let r=n.join(", ");if(o.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${r} } ct state new limit rate ${t.synPerSecond}/second burst ${t.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${r} } ct state new meter conn_rate4 { ip saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned4 { ip saddr } ${l}`,` tcp dport { ${r} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned6 { ip6 saddr } ${l}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${r} } ct state new meter conn_count4 { ip saddr ct count over ${t.concurrentPerSource} } ${l}`,` tcp dport { ${r} } ct state new meter conn_count6 { ip6 saddr ct count over ${t.concurrentPerSource} } ${l}`,""),i.length>0)o.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 { ${r} } ip saddr != @cdn4 counter drop`,"")}return o.push(" }","}",""),o.join(`
4
+ `)}function mi(e={}){return`#!/usr/bin/env bash
5
5
  # Managed by ts-cloud. Installs L3/L4 flood mitigation.
6
6
  set -euo pipefail
7
7
 
@@ -13,11 +13,11 @@ fi
13
13
 
14
14
  install -d -m 0755 /etc/ts-cloud /etc/nftables.d
15
15
  cat > /etc/sysctl.d/90-ts-cloud-ddos.conf <<'SYSCTL_EOF'
16
- ${zc(e)}SYSCTL_EOF
16
+ ${Zc(e)}SYSCTL_EOF
17
17
  sysctl --system >/dev/null
18
18
 
19
19
  cat > /etc/nftables.d/ts-cloud-ddos.nft.new <<'NFT_EOF'
20
- ${Kc(e)}NFT_EOF
20
+ ${ed(e)}NFT_EOF
21
21
 
22
22
  # Syntax-check before applying: a bad ruleset would leave the box unprotected.
23
23
  if ! nft -c -f /etc/nftables.d/ts-cloud-ddos.nft.new; then
@@ -40,5 +40,5 @@ include "/etc/nftables.d/ts-cloud-ddos.nft"
40
40
  fi
41
41
  systemctl enable nftables >/dev/null 2>&1 || true
42
42
  echo "ts-cloud: L3/L4 mitigation active"
43
- `}var b=["off","monitor","rate_limit","challenge","lockdown"];function Ip(e,t=[]){let n=[],s=Math.max(1,e.baselineRequestsPerSecond),a=e.requestsPerSecond/s,l=0,i=(g,v)=>{n.push(v),l=Math.max(l,b.indexOf(g))},c=a>=3;if(c)i("monitor",`Traffic is ${a.toFixed(1)}x the baseline.`);let p=e.topSourceShare>=0.25,u=e.errorRate>=0.25,o=(e.suspiciousAgentShare??0)>=0.5,r=e.uniqueSources>0&&e.requestsPerSecond/e.uniqueSources>=50;if(c&&p)i("rate_limit",`One source accounts for ${(e.topSourceShare*100).toFixed(0)}% of traffic.`);if(c&&r)i("rate_limit","Request rate per unique source is far above what a browser produces.");if(c&&u)i("challenge",`Error rate is ${(e.errorRate*100).toFixed(0)}% under load.`);if(c&&o)i("challenge","Most requests carry no recognisable browser agent.");if(a>=20&&(p||u||o||r))i("lockdown",`Traffic is ${a.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!c&&e.topSourceShare>=0.6&&e.requestsPerSecond>s)i("rate_limit","A single source dominates traffic without an overall surge.");let d=b[l],m={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[d];return{level:d,reasons:n,rateLimitFactor:m,challengeEnabled:d==="challenge"||d==="lockdown",staticOnly:d==="lockdown",banCandidates:d==="off"||d==="monitor"?[]:f(t)}}function Pr(e,t){return Math.max(1,Math.floor(e*t.rateLimitFactor))}
44
- export{Vc,Dr,jc,zc,Kc,li,Ip,Pr};
43
+ `}var b=["off","monitor","rate_limit","challenge","lockdown"];function Tp(e,t=[]){let n=[],s=Math.max(1,e.baselineRequestsPerSecond),a=e.requestsPerSecond/s,l=0,i=(g,v)=>{n.push(v),l=Math.max(l,b.indexOf(g))},c=a>=3;if(c)i("monitor",`Traffic is ${a.toFixed(1)}x the baseline.`);let p=e.topSourceShare>=0.25,u=e.errorRate>=0.25,o=(e.suspiciousAgentShare??0)>=0.5,r=e.uniqueSources>0&&e.requestsPerSecond/e.uniqueSources>=50;if(c&&p)i("rate_limit",`One source accounts for ${(e.topSourceShare*100).toFixed(0)}% of traffic.`);if(c&&r)i("rate_limit","Request rate per unique source is far above what a browser produces.");if(c&&u)i("challenge",`Error rate is ${(e.errorRate*100).toFixed(0)}% under load.`);if(c&&o)i("challenge","Most requests carry no recognisable browser agent.");if(a>=20&&(p||u||o||r))i("lockdown",`Traffic is ${a.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!c&&e.topSourceShare>=0.6&&e.requestsPerSecond>s)i("rate_limit","A single source dominates traffic without an overall surge.");let d=b[l],m={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[d];return{level:d,reasons:n,rateLimitFactor:m,challengeEnabled:d==="challenge"||d==="lockdown",staticOnly:d==="lockdown",banCandidates:d==="off"||d==="monitor"?[]:f(t)}}function xr(e,t){return Math.max(1,Math.floor(e*t.rateLimitFactor))}
44
+ export{Xc,Br,Yc,Zc,ed,mi,Tp,xr};