@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 @@
1
+ import{K}from"./chunk-9jmnmhpy.js";import"./chunk-pdw0qjq1.js";export{K as EC2Client};
@@ -0,0 +1 @@
1
+ import{q,ji}from"./chunk-ptt8me4h.js";import"./chunk-p197a99s.js";import"./chunk-pdw0qjq1.js";export{q as ACMClient,ji as ACMDnsValidator};
@@ -1,4 +1,4 @@
1
- import{di,u}from"./chunk-bckm6fre.js";import{li}from"./chunk-wge61ccr.js";import*as c from"node:crypto";import{readFileSync as D}from"node:fs";import{readdir as U}from"node:fs/promises";import{join as L}from"node:path";function yt(e){if(e){let r=R(e);if(!r)throw Error(`AWS profile '${e}' not found in ~/.aws/credentials`);return r}let t=process.env.AWS_ACCESS_KEY_ID,s=process.env.AWS_SECRET_ACCESS_KEY;if(t&&s)return{accessKeyId:t,secretAccessKey:s,sessionToken:process.env.AWS_SESSION_TOKEN};return R(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function R(e){let{existsSync:t,readFileSync:s}=li("node:fs"),{homedir:r}=li("node:os"),{join:n}=li("node:path"),i=process.env.AWS_SHARED_CREDENTIALS_FILE||n(r(),".aws","credentials");if(!t(i))return null;let o=s(i,"utf-8"),a=null,g,l,h;for(let d of o.split(`
1
+ import{di,u}from"./chunk-pdw0qjq1.js";import{li}from"./chunk-wge61ccr.js";import*as c from"node:crypto";import{readFileSync as D}from"node:fs";import{readdir as U}from"node:fs/promises";import{join as L}from"node:path";function yt(e){if(e){let r=R(e);if(!r)throw Error(`AWS profile '${e}' not found in ~/.aws/credentials`);return r}let t=process.env.AWS_ACCESS_KEY_ID,s=process.env.AWS_SECRET_ACCESS_KEY;if(t&&s)return{accessKeyId:t,secretAccessKey:s,sessionToken:process.env.AWS_SESSION_TOKEN};return R(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function R(e){let{existsSync:t,readFileSync:s}=li("node:fs"),{homedir:r}=li("node:os"),{join:n}=li("node:path"),i=process.env.AWS_SHARED_CREDENTIALS_FILE||n(r(),".aws","credentials");if(!t(i))return null;let o=s(i,"utf-8"),a=null,g,l,h;for(let d of o.split(`
2
2
  `)){let p=d.trim();if(!p||p.startsWith("#")||p.startsWith(";"))continue;let y=p.match(/^\[([^\]]+)\]$/);if(y){if(a===e&&g&&l)return{accessKeyId:g,secretAccessKey:l,sessionToken:h};a=y[1],g=void 0,l=void 0,h=void 0;continue}if(a===e){let[b,...S]=p.split("="),m=S.join("=").trim();switch(b.trim().toLowerCase()){case"aws_access_key_id":g=m;break;case"aws_secret_access_key":l=m;break;case"aws_session_token":h=m;break}}}if(a===e&&g&&l)return{accessKeyId:g,secretAccessKey:l,sessionToken:h};return null}function B(e){let{buffer:t,byteOffset:s,byteLength:r}=e;if(t instanceof ArrayBuffer)return t.slice(s,s+r);let n=new ArrayBuffer(r);return new Uint8Array(n).set(new Uint8Array(e)),n}class f{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(e="us-east-1",t,s){let r=typeof e==="string"?s:e,n=typeof e==="string"?e:e.region??"us-east-1",i=typeof e==="string"?t:e.profile,o=r?.endpoint?di({region:n,path:"/",endpoint:r.endpoint}):void 0;this.region=n,this.explicitProfile=i,this.endpoint=o?.host,this.endpointProtocol=o?.protocol??"https",this.forcePathStyle=r?.forcePathStyle,this.explicitCredentials=r?.credentials,this.client=new u(r?.credentials,{profile:i,endpoint:r?.endpoint,forcePathStyle:r?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let e=yt(this.explicitProfile);if(e.accessKeyId&&e.secretAccessKey)return e;throw Error("S3 credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or pass explicit credentials/profile), or configure ~/.aws/credentials.")}s3BaseHost(){return this.endpoint||`s3.${this.region}.amazonaws.com`}s3VirtualHost(e){return this.forcePathStyle?this.s3BaseHost():`${e}.${this.s3BaseHost()}`}objectPath(e,t){return this.forcePathStyle?`/${e}/${t}`:`/${t}`}objectUrl(e,t){return`${this.endpointProtocol}://${this.s3VirtualHost(e)}${this.objectPath(e,t)}`}async listBuckets(){let e=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),t=[],r=(e?.ListAllMyBucketsResult??e)?.Buckets?.Bucket;if(r){let n=Array.isArray(r)?r:[r];for(let i of n)t.push({Name:i.Name,CreationDate:i.CreationDate})}return{Buckets:t}}async createBucket(e,t){let s={};if(t?.acl)s["x-amz-acl"]=t.acl;let r;if(this.region!=="us-east-1"&&!this.endpoint)r=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  <CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
4
4
  <LocationConstraint>${this.region}</LocationConstraint>
@@ -0,0 +1 @@
1
+ import{ti}from"./chunk-hwp5xp1c.js";import"./chunk-9jmnmhpy.js";import"./chunk-fbycbnvj.js";import"./chunk-x4gsw45d.js";import"./chunk-pd8v6bpd.js";import"./chunk-k3er0h4j.js";import"./chunk-pdw0qjq1.js";import"./chunk-gxwsq3k0.js";export{ti as resolveServerDashboardData};
@@ -1,2 +1,2 @@
1
- import{u}from"./chunk-bckm6fre.js";class ct{client;region;constructor(t="us-east-1",e){this.region=t,this.client=new u(void 0,{profile:e})}async getCallerIdentity(){let t=await this.client.request({service:"sts",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetCallerIdentity&Version=2011-06-15"});if(typeof t==="string"){let n=t.match(/<Account>(\d+)<\/Account>/),r=t.match(/<UserId>([^<]+)<\/UserId>/),i=t.match(/<Arn>([^<]+)<\/Arn>/);return{Account:n?.[1],UserId:r?.[1],Arn:i?.[1]}}let e=t?.GetCallerIdentityResponse?.GetCallerIdentityResult||t?.GetCallerIdentityResult;if(e)return{Account:String(e.Account),UserId:e.UserId,Arn:e.Arn};if(t?.Account)return{Account:String(t.Account),UserId:t.UserId,Arn:t.Arn};return{Account:void 0,UserId:void 0,Arn:void 0}}}
2
- export{ct};
1
+ import{u}from"./chunk-pdw0qjq1.js";class dt{client;region;constructor(t="us-east-1",e){this.region=t,this.client=new u(void 0,{profile:e})}async getCallerIdentity(){let t=await this.client.request({service:"sts",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetCallerIdentity&Version=2011-06-15"});if(typeof t==="string"){let n=t.match(/<Account>(\d+)<\/Account>/),r=t.match(/<UserId>([^<]+)<\/UserId>/),i=t.match(/<Arn>([^<]+)<\/Arn>/);return{Account:n?.[1],UserId:r?.[1],Arn:i?.[1]}}let e=t?.GetCallerIdentityResponse?.GetCallerIdentityResult||t?.GetCallerIdentityResult;if(e)return{Account:String(e.Account),UserId:e.UserId,Arn:e.Arn};if(t?.Account)return{Account:String(t.Account),UserId:t.UserId,Arn:t.Arn};return{Account:void 0,UserId:void 0,Arn:void 0}}}
2
+ export{dt};
@@ -1,4 +1,4 @@
1
- import{h}from"./chunk-gd4w6bht.js";var y=(e)=>e==null?void 0:String(e),w=(e)=>Number(e)===1,C=(e,r)=>{try{return e==null?r:JSON.parse(String(e))}catch{return r}};function b(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),scope:{type:String(e.scope_type),id:String(e.scope_id),environmentId:y(e.environment_id),resourceId:y(e.resource_id),previewId:y(e.preview_id)},key:String(e.key),kind:String(e.kind),value:y(e.value),valueFingerprint:String(e.value_fingerprint),secretRef:y(e.secret_ref),backend:String(e.backend),backendVersion:y(e.backend_version),origin:String(e.origin),required:w(e.required),metadata:C(e.metadata,{}),lastUsedAt:y(e.last_used_at),rotatedAt:y(e.rotated_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function I(e){return{entryId:String(e.entry_id),resourceId:String(e.resource_id),injectionTarget:String(e.injection_target),required:w(e.required),requiresRedeploy:w(e.requires_redeploy),lastDeployedVersion:e.last_deployed_version==null?void 0:Number(e.last_deployed_version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class hr{controlPlane;now;constructor(e,r=()=>new Date){this.controlPlane=e;this.now=r}get(e){let r=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE id=?").get(e);return r?b(r):void 0}find(e,r,n){let t=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE project_id=? AND scope_type=? AND scope_id=? AND key=?").get(e,r.type,r.id,n);return t?b(t):void 0}list(e){let r=["project_id=?"],n=[e.projectId];if(e.scope)r.push("scope_type=?","scope_id=?"),n.push(e.scope.type,e.scope.id);if(e.kind)r.push("kind=?"),n.push(e.kind);return this.controlPlane.database.query(`SELECT * FROM configuration_entries WHERE ${r.join(" AND ")} ORDER BY key,scope_type,scope_id`).all(...n).map(b)}create(e){this.validateScope(e),this.validateEntry(e);let r=crypto.randomUUID(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_entries (id,organization_id,project_id,scope_type,scope_id,environment_id,resource_id,preview_id,key,kind,value,value_fingerprint,secret_ref,backend,backend_version,origin,required,metadata,last_used_at,rotated_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.scope.type,e.scope.id,e.scope.environmentId??null,e.scope.resourceId??null,e.scope.previewId??null,e.key,e.kind,e.value??null,e.valueFingerprint,e.secretRef??null,e.backend,e.backendVersion??null,e.origin,e.required?1:0,JSON.stringify(e.metadata),e.lastUsedAt??null,e.rotatedAt??null,1,n,n]),this.get(r)}update(e,r,n){let t=this.get(e);if(!t)throw Error("Configuration entry was not found.");if(this.validateEntry({...t,...n}),this.controlPlane.database.run("UPDATE configuration_entries SET value=?,value_fingerprint=?,secret_ref=?,backend=?,backend_version=?,required=?,metadata=?,rotated_at=?,version=version+1,updated_at=? WHERE id=? AND version=?",[n.value??null,n.valueFingerprint,n.secretRef??null,n.backend,n.backendVersion??null,n.required?1:0,JSON.stringify(n.metadata),n.rotatedAt??null,this.now().toISOString(),e,r]).changes!==1)throw Error("Configuration entry changed; refresh and retry.");return this.get(e)}remove(e,r){let n=this.get(e);if(!n)throw Error("Configuration entry was not found.");if(n.version!==r)throw Error("Configuration entry changed; refresh and retry.");if(this.controlPlane.database.run("DELETE FROM configuration_entries WHERE id=? AND version=?",[e,r]).changes<1)throw Error("Configuration entry changed; refresh and retry.");return n}setDependency(e){let r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_dependencies (entry_id,resource_id,injection_target,required,requires_redeploy,last_deployed_version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(entry_id,resource_id) DO UPDATE SET injection_target=excluded.injection_target,required=excluded.required,requires_redeploy=excluded.requires_redeploy,last_deployed_version=excluded.last_deployed_version,updated_at=excluded.updated_at",[e.entryId,e.resourceId,e.injectionTarget,e.required?1:0,e.requiresRedeploy?1:0,e.lastDeployedVersion??null,r,r]),this.dependencies(e.entryId).find((n)=>n.resourceId===e.resourceId)}dependencies(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE entry_id=? ORDER BY resource_id").all(e).map(I)}dependenciesForResource(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE resource_id=? ORDER BY entry_id").all(e).map(I)}mutation(e){let r=this.controlPlane.database.query("SELECT request_hash,result FROM configuration_mutations WHERE idempotency_key=?").get(e);return r?{requestHash:r.request_hash,result:C(r.result,{})}:void 0}recordMutation(e){this.controlPlane.database.run("INSERT INTO configuration_mutations (id,project_id,idempotency_key,request_hash,result,actor_id,created_at) VALUES (?,?,?,?,?,?,?)",[crypto.randomUUID(),e.projectId,e.idempotencyKey,e.requestHash,JSON.stringify(e.result),e.actorId??null,this.now().toISOString()])}validateEntry(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,255}$/.test(e.key))throw Error(`Invalid configuration key: ${e.key}`);if(e.kind==="variable"&&(e.value==null||e.secretRef||e.backend!=="plaintext"))throw Error("Variables require a plaintext value and cannot use a secret backend.");if(e.kind==="secret"&&(e.value!=null||!e.secretRef||e.backend==="plaintext"))throw Error("Secrets require a non-plaintext backend reference and cannot store a plaintext value.")}validateScope(e){let r=this.controlPlane.getProject(e.projectId);if(!r||r.organizationId!==e.organizationId)throw Error("Configuration project does not belong to the organization.");let n=e.scope;if(n.type==="project"){if(n.id!==e.projectId||n.environmentId||n.resourceId||n.previewId)throw Error("Project configuration scope must reference only its project.");return}if(n.type==="environment"){let i=this.controlPlane.database.query("SELECT project_id FROM environments WHERE id=?").get(n.id);if(!i||i.project_id!==e.projectId||n.environmentId&&n.environmentId!==n.id||n.resourceId||n.previewId)throw Error("Environment configuration scope does not belong to the project.");return}if(n.type==="service"||n.type==="function"){let i=this.controlPlane.getResource(n.id);if(!i||i.projectId!==e.projectId||n.type==="function"&&i.kind!=="function"||n.resourceId&&n.resourceId!==n.id||n.environmentId&&i.environmentId!==n.environmentId||n.previewId)throw Error(`${n.type==="function"?"Function":"Service"} configuration scope does not belong to the project.`);return}let t=this.controlPlane.database.query("SELECT project_id,base_environment_id,resource_id FROM preview_instances WHERE id=?").get(n.id);if(!t||t.project_id!==e.projectId||n.previewId&&n.previewId!==n.id||n.environmentId&&n.environmentId!==t.base_environment_id||n.resourceId&&n.resourceId!==t.resource_id)throw Error("Preview configuration scope does not belong to the project.")}}var E=/^[A-Za-z_][A-Za-z0-9_]{0,255}$/;function j(e){let r={n:`
1
+ import{h}from"./chunk-8bbw6qc2.js";var y=(e)=>e==null?void 0:String(e),w=(e)=>Number(e)===1,C=(e,r)=>{try{return e==null?r:JSON.parse(String(e))}catch{return r}};function b(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),scope:{type:String(e.scope_type),id:String(e.scope_id),environmentId:y(e.environment_id),resourceId:y(e.resource_id),previewId:y(e.preview_id)},key:String(e.key),kind:String(e.kind),value:y(e.value),valueFingerprint:String(e.value_fingerprint),secretRef:y(e.secret_ref),backend:String(e.backend),backendVersion:y(e.backend_version),origin:String(e.origin),required:w(e.required),metadata:C(e.metadata,{}),lastUsedAt:y(e.last_used_at),rotatedAt:y(e.rotated_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function I(e){return{entryId:String(e.entry_id),resourceId:String(e.resource_id),injectionTarget:String(e.injection_target),required:w(e.required),requiresRedeploy:w(e.requires_redeploy),lastDeployedVersion:e.last_deployed_version==null?void 0:Number(e.last_deployed_version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class hr{controlPlane;now;constructor(e,r=()=>new Date){this.controlPlane=e;this.now=r}get(e){let r=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE id=?").get(e);return r?b(r):void 0}find(e,r,n){let t=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE project_id=? AND scope_type=? AND scope_id=? AND key=?").get(e,r.type,r.id,n);return t?b(t):void 0}list(e){let r=["project_id=?"],n=[e.projectId];if(e.scope)r.push("scope_type=?","scope_id=?"),n.push(e.scope.type,e.scope.id);if(e.kind)r.push("kind=?"),n.push(e.kind);return this.controlPlane.database.query(`SELECT * FROM configuration_entries WHERE ${r.join(" AND ")} ORDER BY key,scope_type,scope_id`).all(...n).map(b)}create(e){this.validateScope(e),this.validateEntry(e);let r=crypto.randomUUID(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_entries (id,organization_id,project_id,scope_type,scope_id,environment_id,resource_id,preview_id,key,kind,value,value_fingerprint,secret_ref,backend,backend_version,origin,required,metadata,last_used_at,rotated_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.scope.type,e.scope.id,e.scope.environmentId??null,e.scope.resourceId??null,e.scope.previewId??null,e.key,e.kind,e.value??null,e.valueFingerprint,e.secretRef??null,e.backend,e.backendVersion??null,e.origin,e.required?1:0,JSON.stringify(e.metadata),e.lastUsedAt??null,e.rotatedAt??null,1,n,n]),this.get(r)}update(e,r,n){let t=this.get(e);if(!t)throw Error("Configuration entry was not found.");if(this.validateEntry({...t,...n}),this.controlPlane.database.run("UPDATE configuration_entries SET value=?,value_fingerprint=?,secret_ref=?,backend=?,backend_version=?,required=?,metadata=?,rotated_at=?,version=version+1,updated_at=? WHERE id=? AND version=?",[n.value??null,n.valueFingerprint,n.secretRef??null,n.backend,n.backendVersion??null,n.required?1:0,JSON.stringify(n.metadata),n.rotatedAt??null,this.now().toISOString(),e,r]).changes!==1)throw Error("Configuration entry changed; refresh and retry.");return this.get(e)}remove(e,r){let n=this.get(e);if(!n)throw Error("Configuration entry was not found.");if(n.version!==r)throw Error("Configuration entry changed; refresh and retry.");if(this.controlPlane.database.run("DELETE FROM configuration_entries WHERE id=? AND version=?",[e,r]).changes<1)throw Error("Configuration entry changed; refresh and retry.");return n}setDependency(e){let r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_dependencies (entry_id,resource_id,injection_target,required,requires_redeploy,last_deployed_version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(entry_id,resource_id) DO UPDATE SET injection_target=excluded.injection_target,required=excluded.required,requires_redeploy=excluded.requires_redeploy,last_deployed_version=excluded.last_deployed_version,updated_at=excluded.updated_at",[e.entryId,e.resourceId,e.injectionTarget,e.required?1:0,e.requiresRedeploy?1:0,e.lastDeployedVersion??null,r,r]),this.dependencies(e.entryId).find((n)=>n.resourceId===e.resourceId)}dependencies(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE entry_id=? ORDER BY resource_id").all(e).map(I)}dependenciesForResource(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE resource_id=? ORDER BY entry_id").all(e).map(I)}mutation(e){let r=this.controlPlane.database.query("SELECT request_hash,result FROM configuration_mutations WHERE idempotency_key=?").get(e);return r?{requestHash:r.request_hash,result:C(r.result,{})}:void 0}recordMutation(e){this.controlPlane.database.run("INSERT INTO configuration_mutations (id,project_id,idempotency_key,request_hash,result,actor_id,created_at) VALUES (?,?,?,?,?,?,?)",[crypto.randomUUID(),e.projectId,e.idempotencyKey,e.requestHash,JSON.stringify(e.result),e.actorId??null,this.now().toISOString()])}validateEntry(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,255}$/.test(e.key))throw Error(`Invalid configuration key: ${e.key}`);if(e.kind==="variable"&&(e.value==null||e.secretRef||e.backend!=="plaintext"))throw Error("Variables require a plaintext value and cannot use a secret backend.");if(e.kind==="secret"&&(e.value!=null||!e.secretRef||e.backend==="plaintext"))throw Error("Secrets require a non-plaintext backend reference and cannot store a plaintext value.")}validateScope(e){let r=this.controlPlane.getProject(e.projectId);if(!r||r.organizationId!==e.organizationId)throw Error("Configuration project does not belong to the organization.");let n=e.scope;if(n.type==="project"){if(n.id!==e.projectId||n.environmentId||n.resourceId||n.previewId)throw Error("Project configuration scope must reference only its project.");return}if(n.type==="environment"){let i=this.controlPlane.database.query("SELECT project_id FROM environments WHERE id=?").get(n.id);if(!i||i.project_id!==e.projectId||n.environmentId&&n.environmentId!==n.id||n.resourceId||n.previewId)throw Error("Environment configuration scope does not belong to the project.");return}if(n.type==="service"||n.type==="function"){let i=this.controlPlane.getResource(n.id);if(!i||i.projectId!==e.projectId||n.type==="function"&&i.kind!=="function"||n.resourceId&&n.resourceId!==n.id||n.environmentId&&i.environmentId!==n.environmentId||n.previewId)throw Error(`${n.type==="function"?"Function":"Service"} configuration scope does not belong to the project.`);return}let t=this.controlPlane.database.query("SELECT project_id,base_environment_id,resource_id FROM preview_instances WHERE id=?").get(n.id);if(!t||t.project_id!==e.projectId||n.previewId&&n.previewId!==n.id||n.environmentId&&n.environmentId!==t.base_environment_id||n.resourceId&&n.resourceId!==t.resource_id)throw Error("Preview configuration scope does not belong to the project.")}}var E=/^[A-Za-z_][A-Za-z0-9_]{0,255}$/;function j(e){let r={n:`
2
2
  `,r:"\r",t:"\t","\\":"\\",'"':'"',$:"$"};return e.replace(/\\(n|r|t|\\|"|\$)/g,(n,t)=>r[t])}function qa(e){let r={},n=[],t=e.replace(/\r\n?/g,`
3
3
  `).split(`
4
4
  `);for(let i=0;i<t.length;i++){let s=i+1,c=t[i];if(!c.trim()||c.trimStart().startsWith("#"))continue;if(/^\s*export\s+/.test(c))c=c.replace(/^\s*export\s+/,"");let u=c.match(/^\s*([^=\s]+)\s*=\s*(.*)$/);if(!u){n.push({line:s,severity:"error",code:"invalid_line",message:"Expected KEY=VALUE."});continue}let o=u[1],a=u[2];if(!E.test(o)){n.push({line:s,key:o,severity:"error",code:"invalid_key",message:`Invalid environment variable name: ${o}`});continue}let d=a;if(a.startsWith('"')||a.startsWith("'")){let g=a[0],l=[a.slice(1)],v=!1;while(!0){let f=l[l.length-1],m=!1,S=-1;for(let k=0;k<f.length;k++){if(g==='"'&&f[k]==="\\"&&!m){m=!0;continue}if(f[k]===g&&!m){S=k;break}m=!1}if(S>=0){l[l.length-1]=f.slice(0,S),v=!0;break}if(++i>=t.length)break;l.push(t[i])}if(!v){n.push({line:s,key:o,severity:"error",code:"unterminated_quote",message:`Unterminated quoted value for ${o}.`});continue}if(d=l.join(`
@@ -1,2 +1,2 @@
1
- import{u}from"./chunk-bckm6fre.js";class F{client;region;constructor(e="us-east-1",i){this.region=e,this.client=new u}async createQueue(e){let t={Action:"CreateQueue",QueueName:e.fifo&&!e.queueName.endsWith(".fifo")?`${e.queueName}.fifo`:e.queueName,Version:"2012-11-05"},s=1;if(e.visibilityTimeout!==void 0)t[`Attribute.${s}.Name`]="VisibilityTimeout",t[`Attribute.${s}.Value`]=e.visibilityTimeout.toString(),s++;if(e.messageRetentionPeriod!==void 0)t[`Attribute.${s}.Name`]="MessageRetentionPeriod",t[`Attribute.${s}.Value`]=e.messageRetentionPeriod.toString(),s++;if(e.delaySeconds!==void 0)t[`Attribute.${s}.Name`]="DelaySeconds",t[`Attribute.${s}.Value`]=e.delaySeconds.toString(),s++;if(e.maxMessageSize!==void 0)t[`Attribute.${s}.Name`]="MaximumMessageSize",t[`Attribute.${s}.Value`]=e.maxMessageSize.toString(),s++;if(e.receiveMessageWaitTime!==void 0)t[`Attribute.${s}.Name`]="ReceiveMessageWaitTimeSeconds",t[`Attribute.${s}.Value`]=e.receiveMessageWaitTime.toString(),s++;if(e.fifo){if(t[`Attribute.${s}.Name`]="FifoQueue",t[`Attribute.${s}.Value`]="true",s++,e.contentBasedDeduplication)t[`Attribute.${s}.Name`]="ContentBasedDeduplication",t[`Attribute.${s}.Value`]="true",s++}if(e.deadLetterTargetArn&&e.maxReceiveCount)t[`Attribute.${s}.Name`]="RedrivePolicy",t[`Attribute.${s}.Value`]=JSON.stringify({deadLetterTargetArn:e.deadLetterTargetArn,maxReceiveCount:e.maxReceiveCount}),s++;if(e.tags&&Object.keys(e.tags).length>0){let a=1;for(let[n,g]of Object.entries(e.tags))t[`Tag.${a}.Key`]=n,t[`Tag.${a}.Value`]=g,a++}let r=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{QueueUrl:r.QueueUrl||r.CreateQueueResult?.QueueUrl}}async listQueues(e){let i={Action:"ListQueues",Version:"2012-11-05"};if(e)i.QueueNamePrefix=e;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[];if(t.QueueUrl)s.push(t.QueueUrl);else if(t.ListQueuesResult?.QueueUrl)if(Array.isArray(t.ListQueuesResult.QueueUrl))s.push(...t.ListQueuesResult.QueueUrl);else s.push(t.ListQueuesResult.QueueUrl);return{QueueUrls:s}}async getQueueAttributes(e){let i={Action:"GetQueueAttributes",QueueUrl:e,Version:"2012-11-05","AttributeName.1":"All"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{Attributes:t.Attributes||t.GetQueueAttributesResult?.Attributes||{}}}async getQueueUrl(e){let i={Action:"GetQueueUrl",QueueName:e,Version:"2012-11-05"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{QueueUrl:t.QueueUrl||t.GetQueueUrlResult?.QueueUrl}}async deleteQueue(e){let i={Action:"DeleteQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async purgeQueue(e){let i={Action:"PurgeQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async sendMessage(e){let i={Action:"SendMessage",QueueUrl:e.queueUrl,MessageBody:e.messageBody,Version:"2012-11-05"};if(e.delaySeconds!==void 0)i.DelaySeconds=e.delaySeconds;if(e.messageGroupId)i.MessageGroupId=e.messageGroupId;if(e.messageDeduplicationId)i.MessageDeduplicationId=e.messageDeduplicationId;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{MessageId:t.MessageId||t.SendMessageResult?.MessageId}}async receiveMessages(e){let i={Action:"ReceiveMessage",QueueUrl:e.queueUrl,Version:"2012-11-05"};if(e.maxMessages!==void 0)i.MaxNumberOfMessages=e.maxMessages;if(e.visibilityTimeout!==void 0)i.VisibilityTimeout=e.visibilityTimeout;if(e.waitTimeSeconds!==void 0)i.WaitTimeSeconds=e.waitTimeSeconds;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[],r=t.Message||t.ReceiveMessageResult?.Message;if(r)if(Array.isArray(r))s.push(...r.map((a)=>({MessageId:a.MessageId,ReceiptHandle:a.ReceiptHandle,Body:a.Body})));else s.push({MessageId:r.MessageId,ReceiptHandle:r.ReceiptHandle,Body:r.Body});return{Messages:s}}async deleteMessage(e,i){let t={Action:"DeleteMessage",QueueUrl:e,ReceiptHandle:i,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}}
1
+ import{u}from"./chunk-pdw0qjq1.js";class F{client;region;constructor(e="us-east-1",i){this.region=e,this.client=new u}async createQueue(e){let t={Action:"CreateQueue",QueueName:e.fifo&&!e.queueName.endsWith(".fifo")?`${e.queueName}.fifo`:e.queueName,Version:"2012-11-05"},s=1;if(e.visibilityTimeout!==void 0)t[`Attribute.${s}.Name`]="VisibilityTimeout",t[`Attribute.${s}.Value`]=e.visibilityTimeout.toString(),s++;if(e.messageRetentionPeriod!==void 0)t[`Attribute.${s}.Name`]="MessageRetentionPeriod",t[`Attribute.${s}.Value`]=e.messageRetentionPeriod.toString(),s++;if(e.delaySeconds!==void 0)t[`Attribute.${s}.Name`]="DelaySeconds",t[`Attribute.${s}.Value`]=e.delaySeconds.toString(),s++;if(e.maxMessageSize!==void 0)t[`Attribute.${s}.Name`]="MaximumMessageSize",t[`Attribute.${s}.Value`]=e.maxMessageSize.toString(),s++;if(e.receiveMessageWaitTime!==void 0)t[`Attribute.${s}.Name`]="ReceiveMessageWaitTimeSeconds",t[`Attribute.${s}.Value`]=e.receiveMessageWaitTime.toString(),s++;if(e.fifo){if(t[`Attribute.${s}.Name`]="FifoQueue",t[`Attribute.${s}.Value`]="true",s++,e.contentBasedDeduplication)t[`Attribute.${s}.Name`]="ContentBasedDeduplication",t[`Attribute.${s}.Value`]="true",s++}if(e.deadLetterTargetArn&&e.maxReceiveCount)t[`Attribute.${s}.Name`]="RedrivePolicy",t[`Attribute.${s}.Value`]=JSON.stringify({deadLetterTargetArn:e.deadLetterTargetArn,maxReceiveCount:e.maxReceiveCount}),s++;if(e.tags&&Object.keys(e.tags).length>0){let a=1;for(let[n,g]of Object.entries(e.tags))t[`Tag.${a}.Key`]=n,t[`Tag.${a}.Value`]=g,a++}let r=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{QueueUrl:r.QueueUrl||r.CreateQueueResult?.QueueUrl}}async listQueues(e){let i={Action:"ListQueues",Version:"2012-11-05"};if(e)i.QueueNamePrefix=e;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[];if(t.QueueUrl)s.push(t.QueueUrl);else if(t.ListQueuesResult?.QueueUrl)if(Array.isArray(t.ListQueuesResult.QueueUrl))s.push(...t.ListQueuesResult.QueueUrl);else s.push(t.ListQueuesResult.QueueUrl);return{QueueUrls:s}}async getQueueAttributes(e){let i={Action:"GetQueueAttributes",QueueUrl:e,Version:"2012-11-05","AttributeName.1":"All"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{Attributes:t.Attributes||t.GetQueueAttributesResult?.Attributes||{}}}async getQueueUrl(e){let i={Action:"GetQueueUrl",QueueName:e,Version:"2012-11-05"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{QueueUrl:t.QueueUrl||t.GetQueueUrlResult?.QueueUrl}}async deleteQueue(e){let i={Action:"DeleteQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async purgeQueue(e){let i={Action:"PurgeQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async sendMessage(e){let i={Action:"SendMessage",QueueUrl:e.queueUrl,MessageBody:e.messageBody,Version:"2012-11-05"};if(e.delaySeconds!==void 0)i.DelaySeconds=e.delaySeconds;if(e.messageGroupId)i.MessageGroupId=e.messageGroupId;if(e.messageDeduplicationId)i.MessageDeduplicationId=e.messageDeduplicationId;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{MessageId:t.MessageId||t.SendMessageResult?.MessageId}}async receiveMessages(e){let i={Action:"ReceiveMessage",QueueUrl:e.queueUrl,Version:"2012-11-05"};if(e.maxMessages!==void 0)i.MaxNumberOfMessages=e.maxMessages;if(e.visibilityTimeout!==void 0)i.VisibilityTimeout=e.visibilityTimeout;if(e.waitTimeSeconds!==void 0)i.WaitTimeSeconds=e.waitTimeSeconds;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[],r=t.Message||t.ReceiveMessageResult?.Message;if(r)if(Array.isArray(r))s.push(...r.map((a)=>({MessageId:a.MessageId,ReceiptHandle:a.ReceiptHandle,Body:a.Body})));else s.push({MessageId:r.MessageId,ReceiptHandle:r.ReceiptHandle,Body:r.Body});return{Messages:s}}async deleteMessage(e,i){let t={Action:"DeleteMessage",QueueUrl:e,ReceiptHandle:i,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}}
2
2
  export{F};
@@ -1,6 +1,6 @@
1
- import{Ql}from"./chunk-wge61ccr.js";var g={};Ql(g,{ProgressBar:()=>v,Spinner:()=>o,box:()=>ye,checkAwsCli:()=>As,checkAwsCredentials:()=>Is,colorize:()=>Lt,colors:()=>T,confirm:()=>d,error:()=>r,formatBytes:()=>tn,formatDuration:()=>b,getAwsAccountId:()=>Rs,getAwsRegions:()=>Ps,header:()=>i,info:()=>e,prompt:()=>I,select:()=>fo,step:()=>m,success:()=>n,table:()=>c,warn:()=>a,warning:()=>Er});var T={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function Lt(t,s){return`${T[s]}${t}${T.reset}`}function n(t){console.log(`${T.green}✓${T.reset} ${t}`)}function r(t){console.error(`${T.red}✗${T.reset} ${t}`)}function a(t){console.warn(`${T.yellow}⚠${T.reset} ${t}`)}var Er=a;function e(t){console.log(`${T.blue}ℹ${T.reset} ${t}`)}function m(t){console.log(`${T.cyan}→${T.reset} ${t}`)}function i(t){console.log(`
1
+ import{Ql}from"./chunk-wge61ccr.js";var g={};Ql(g,{ProgressBar:()=>v,Spinner:()=>o,box:()=>ye,checkAwsCli:()=>As,checkAwsCredentials:()=>Is,colorize:()=>Mt,colors:()=>T,confirm:()=>d,error:()=>r,formatBytes:()=>tn,formatDuration:()=>b,getAwsAccountId:()=>Rs,getAwsRegions:()=>Ps,header:()=>i,info:()=>e,prompt:()=>I,select:()=>fo,step:()=>m,success:()=>n,table:()=>c,warn:()=>a,warning:()=>Er});var T={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function Mt(t,s){return`${T[s]}${t}${T.reset}`}function n(t){console.log(`${T.green}✓${T.reset} ${t}`)}function r(t){console.error(`${T.red}✗${T.reset} ${t}`)}function a(t){console.warn(`${T.yellow}⚠${T.reset} ${t}`)}var Er=a;function e(t){console.log(`${T.blue}ℹ${T.reset} ${t}`)}function m(t){console.log(`${T.cyan}→${T.reset} ${t}`)}function i(t){console.log(`
2
2
  ${T.bright}${T.cyan}${t}${T.reset}
3
3
  `)}var x=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);class o{frames=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];interval=null;currentFrame=0;message;constructor(t){this.message=t}get text(){return this.message}set text(t){if(this.message=t,x&&this.interval)console.log(` ${t}`)}start(){if(x){console.log(` ${this.message}`),this.interval=!0;return}this.interval=setInterval(()=>{process.stdout.write(`\r${T.cyan}${this.frames[this.currentFrame]}${T.reset} ${this.message}`),this.currentFrame=(this.currentFrame+1)%this.frames.length},80)}succeed(t){this.stop(),n(t||this.message)}fail(t){this.stop(),r(t||this.message)}warn(t){this.stop(),Er(t||this.message)}stop(){if(this.interval){if(!x)process.stdout.write("\r");if(typeof this.interval==="object")clearInterval(this.interval);this.interval=null}}}class v{total;current=0;width=40;constructor(t){this.total=t}update(t){this.current=t,this.render()}increment(){this.current++,this.render()}render(){let t=Math.floor(this.current/this.total*100),s=Math.floor(this.current/this.total*this.width),l=this.width-s,u=`${"█".repeat(s)}${"░".repeat(l)}`;if(process.stdout.write(`\r${T.cyan}${u}${T.reset} ${t}% (${this.current}/${this.total})`),this.current>=this.total)process.stdout.write(`
4
- `)}}async function I(t,s){let l=await import("node:readline"),u=l.createInterface({input:process.stdin,output:process.stdout});return new Promise((p)=>{let h=s?`${T.cyan}?${T.reset} ${t} ${T.gray}(${s})${T.reset}: `:`${T.cyan}?${T.reset} ${t}: `;u.question(h,(f)=>{u.close(),p(f||s||"")})})}async function d(t,s=!1){let l=await I(`${t} (y/n)`,s?"y":"n");return l.toLowerCase()==="y"||l.toLowerCase()==="yes"}async function fo(t,s){console.log(`${T.cyan}?${T.reset} ${t}`),s.forEach((p,h)=>{console.log(` ${T.gray}${h+1}.${T.reset} ${p}`)});let l=await I("Select","1"),u=Number.parseInt(l)-1;if(u>=0&&u<s.length)return s[u];return s[0]}function c(t,s){let l=t.map((p,h)=>{let f=Math.max(...s.map((w)=>(w[h]||"").length));return Math.max(p.length,f)}),u=t.map((p,h)=>p.padEnd(l[h])).join(" ");console.log(Lt(u,"bright")),console.log(Lt("─".repeat(u.length),"gray")),s.forEach((p)=>{let h=p.map((f,w)=>(f||"").padEnd(l[w])).join(" ");console.log(h)})}function tn(t){if(t===0)return"0 B";let s=1024,l=["B","KB","MB","GB","TB"],u=Math.floor(Math.log(t)/Math.log(s));return`${Number.parseFloat((t/s**u).toFixed(2))} ${l[u]}`}function b(t){if(t<1000)return`${t}ms`;let s=Math.floor(t/1000);if(s<60)return`${s}s`;let l=Math.floor(s/60),u=s%60;if(l<60)return`${l}m ${u}s`;let p=Math.floor(l/60),h=l%60;return`${p}h ${h}m`}function ye(t,s="cyan"){let l=t.split(`
5
- `),u=Math.max(...l.map((h)=>h.length)),p="─".repeat(u+2);console.log(Lt(`┌${p}┐`,s)),l.forEach((h)=>{console.log(Lt(`│ ${h.padEnd(u)} │`,s))}),console.log(Lt(`└${p}┘`,s))}async function As(){return!0}async function Is(){try{let{AWSClient:t}=await import("./chunk-c51xp8f7.js");return await new t().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()}),!0}catch{return!1}}async function Rs(){try{let{AWSClient:t}=await import("./chunk-c51xp8f7.js"),l=await new t().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()});return l.Account||l.GetCallerIdentityResult?.Account||null}catch{return null}}async function Ps(){try{let{AWSClient:t}=await import("./chunk-c51xp8f7.js"),l=await new t().request({service:"ec2",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"DescribeRegions",Version:"2016-11-15"}).toString()}),u=[];if(l.regionInfo){let p=Array.isArray(l.regionInfo)?l.regionInfo:[l.regionInfo];u.push(...p.map((h)=>h.regionName))}return u.length>0?u:y()}catch{return y()}}function y(){return["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1","ap-northeast-1"]}
6
- export{T,Lt,n,r,a,Er,e,m,i,o,I,d,fo,c,tn,ye,As,Is,Rs,Ps,g};
4
+ `)}}async function I(t,s){let l=await import("node:readline"),u=l.createInterface({input:process.stdin,output:process.stdout});return new Promise((p)=>{let h=s?`${T.cyan}?${T.reset} ${t} ${T.gray}(${s})${T.reset}: `:`${T.cyan}?${T.reset} ${t}: `;u.question(h,(f)=>{u.close(),p(f||s||"")})})}async function d(t,s=!1){let l=await I(`${t} (y/n)`,s?"y":"n");return l.toLowerCase()==="y"||l.toLowerCase()==="yes"}async function fo(t,s){console.log(`${T.cyan}?${T.reset} ${t}`),s.forEach((p,h)=>{console.log(` ${T.gray}${h+1}.${T.reset} ${p}`)});let l=await I("Select","1"),u=Number.parseInt(l)-1;if(u>=0&&u<s.length)return s[u];return s[0]}function c(t,s){let l=t.map((p,h)=>{let f=Math.max(...s.map((w)=>(w[h]||"").length));return Math.max(p.length,f)}),u=t.map((p,h)=>p.padEnd(l[h])).join(" ");console.log(Mt(u,"bright")),console.log(Mt("─".repeat(u.length),"gray")),s.forEach((p)=>{let h=p.map((f,w)=>(f||"").padEnd(l[w])).join(" ");console.log(h)})}function tn(t){if(t===0)return"0 B";let s=1024,l=["B","KB","MB","GB","TB"],u=Math.floor(Math.log(t)/Math.log(s));return`${Number.parseFloat((t/s**u).toFixed(2))} ${l[u]}`}function b(t){if(t<1000)return`${t}ms`;let s=Math.floor(t/1000);if(s<60)return`${s}s`;let l=Math.floor(s/60),u=s%60;if(l<60)return`${l}m ${u}s`;let p=Math.floor(l/60),h=l%60;return`${p}h ${h}m`}function ye(t,s="cyan"){let l=t.split(`
5
+ `),u=Math.max(...l.map((h)=>h.length)),p="─".repeat(u+2);console.log(Mt(`┌${p}┐`,s)),l.forEach((h)=>{console.log(Mt(`│ ${h.padEnd(u)} │`,s))}),console.log(Mt(`└${p}┘`,s))}async function As(){return!0}async function Is(){try{let{AWSClient:t}=await import("./chunk-zs8bfer0.js");return await new t().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()}),!0}catch{return!1}}async function Rs(){try{let{AWSClient:t}=await import("./chunk-zs8bfer0.js"),l=await new t().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()});return l.Account||l.GetCallerIdentityResult?.Account||null}catch{return null}}async function Ps(){try{let{AWSClient:t}=await import("./chunk-zs8bfer0.js"),l=await new t().request({service:"ec2",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"DescribeRegions",Version:"2016-11-15"}).toString()}),u=[];if(l.regionInfo){let p=Array.isArray(l.regionInfo)?l.regionInfo:[l.regionInfo];u.push(...p.map((h)=>h.regionName))}return u.length>0?u:y()}catch{return y()}}function y(){return["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1","ap-northeast-1"]}
6
+ export{T,Mt,n,r,a,Er,e,m,i,o,I,d,fo,c,tn,ye,As,Is,Rs,Ps,g};
@@ -0,0 +1 @@
1
+ import{f}from"./chunk-k3er0h4j.js";import"./chunk-pdw0qjq1.js";export{f as S3Client};
@@ -1,4 +1,4 @@
1
- import{u}from"./chunk-bckm6fre.js";class O{client;region;constructor(e="us-east-1"){this.region=e,this.client=new u}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{u}from"./chunk-pdw0qjq1.js";class O{client;region;constructor(e="us-east-1"){this.region=e,this.client=new u}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
3
3
  <Name>${e.Name}</Name>
4
4
  <CallerReference>${t}</CallerReference>`;if(e.HostedZoneConfig){if(o+=`
@@ -1,2 +1,2 @@
1
- import{u}from"./chunk-bckm6fre.js";class v{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(void 0,{profile:t})}async createStack(e){let t={Action:"CreateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});if(e.timeoutInMinutes)t.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)t.OnFailure=e.onFailure;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.CreateStackResult?.StackId}}async updateStack(e){let t={Action:"UpdateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{if(t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,a.UsePreviousValue)t[`Parameters.member.${r+1}.UsePreviousValue`]="true";else t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.UpdateStackResult?.StackId}}async deleteStack(e,t,s){let a={Action:"DeleteStack",StackName:e,Version:"2010-05-15"};if(t)a.RoleARN=t;if(s&&s.length>0)s.forEach((r,m)=>{a[`RetainResources.member.${m+1}`]=r});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(a).toString()})}async describeStacks(e={}){let t={Action:"DescribeStacks",Version:"2010-05-15"};if(e.stackName)t.StackName=e.stackName;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Stacks:this.parseStacksResponse(s)}}async describeStackEvents(e){let t={Action:"DescribeStackEvents",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackEvents:this.parseStackEvents(s)}}async listStackResources(e){let t={Action:"ListStackResources",StackName:e,Version:"2010-05-15"},a=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,r=[];if(a)r=Array.isArray(a)?a:[a];return{StackResourceSummaries:r}}async waitForStack(e,t){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},a=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],r=s[t],m=360,i=0;while(i<360)try{let c=await this.describeStacks({stackName:e});if(c.Stacks.length===0){if(t==="stack-delete-complete")return;if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack not visible yet`);await new Promise((o)=>setTimeout(o,2000)),i++;continue}let n=c.Stacks[0];if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Status = ${n.StackStatus}${n.StackStatusReason?` (${n.StackStatusReason})`:""}`);if(r.includes(n.StackStatus))return;if((t==="stack-create-complete"||t==="stack-update-complete")&&(n.StackStatus==="DELETE_IN_PROGRESS"||n.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let o="";try{let S=await this.describeStackEvents(e);console.log("[waitForStack] Stack events (most recent first):");for(let k of S.StackEvents.slice(0,15))if(k.ResourceStatus.includes("FAILED")||k.ResourceStatusReason){if(console.log(` ${k.LogicalResourceId}: ${k.ResourceStatus} - ${k.ResourceStatusReason||"No reason provided"}`),k.ResourceStatus.includes("FAILED")&&k.ResourceStatusReason&&!o)o=k.ResourceStatusReason}}catch{}let l=o||n.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${l}`)}if(n.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let o=Error("Stack deletion failed - may have resources that need to be retained");throw o.code="DELETE_FAILED",o.stackStatus=n.StackStatus,o.statusReason=n.StackStatusReason,o}if(a.includes(n.StackStatus))throw Error(`Stack reached failure status: ${n.StackStatus}`);await new Promise((o)=>setTimeout(o,5000)),i++}catch(c){if(t==="stack-delete-complete"&&c.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&c.message?.includes("does not exist")){if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack does not exist (error), retrying...`);await new Promise((n)=>setTimeout(n,2000)),i++;continue}throw console.log(`[waitForStack] Unexpected error: ${c.message}`),c}throw console.log(`[waitForStack] Timeout after ${i} attempts`),Error(`Timeout waiting for stack to reach ${t}`)}async validateTemplate(e){let t={Action:"ValidateTemplate",TemplateBody:e,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}async listStacks(e){let t={Action:"ListStacks",Version:"2010-05-15"};if(e)e.forEach((c,n)=>{t[`StackStatusFilter.member.${n+1}`]=c});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=s.ListStacksResponse||s,r=a.ListStacksResult||a,m=r.StackSummaries?.member||r.StackSummaries||[];return{StackSummaries:(Array.isArray(m)?m:m?[m]:[]).map((c)=>({StackId:c.StackId||"",StackName:c.StackName||"",TemplateDescription:c.TemplateDescription,CreationTime:c.CreationTime||"",LastUpdatedTime:c.LastUpdatedTime,DeletionTime:c.DeletionTime,StackStatus:c.StackStatus||""}))}}async createChangeSet(e){let t={Action:"CreateChangeSet",StackName:e.stackName,ChangeSetName:e.changeSetName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.changeSetType)t.ChangeSetType=e.changeSetType;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Id:s.Id,StackId:s.StackId}}async describeChangeSet(e,t){let s={Action:"DescribeChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async executeChangeSet(e,t){let s={Action:"ExecuteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async deleteChangeSet(e,t){let s={Action:"DeleteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async getStackOutputs(e){let t=await this.describeStacks({stackName:e});if(!t.Stacks||t.Stacks.length===0)throw Error(`Stack ${e} not found`);let s=t.Stacks[0],a={};if(s.Outputs)for(let r of s.Outputs)a[r.OutputKey]=r.OutputValue;return a}async getTemplate(e){let t={Action:"GetTemplate",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{TemplateBody:s?.GetTemplateResult?.TemplateBody||s?.TemplateBody||""}}parseStacksResponse(e){let t=[],s=e?.DescribeStacksResult?.Stacks?.member||e?.Stacks?.member||e?.Stacks||e;if(s&&!Array.isArray(s))s=[s];if(Array.isArray(s)){for(let a of s)if(a.StackId||a.StackName){let r;if(a.Outputs?.member)r=(Array.isArray(a.Outputs.member)?a.Outputs.member:[a.Outputs.member]).map((i)=>({OutputKey:i.OutputKey,OutputValue:i.OutputValue,Description:i.Description,ExportName:i.ExportName}));t.push({StackId:a.StackId,StackName:a.StackName,StackStatus:a.StackStatus,CreationTime:a.CreationTime,LastUpdatedTime:a.LastUpdatedTime,StackStatusReason:a.StackStatusReason,Outputs:r})}}else if(e.StackId)t.push({StackId:e.StackId,StackName:e.StackName,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime});return t}parseStackEvents(e){let t=[],s=e?.DescribeStackEventsResult?.StackEvents?.member||e?.StackEvents?.member||e?.StackEvents||[];if(s&&!Array.isArray(s))s=[s];for(let a of s)if(a.LogicalResourceId)t.push({Timestamp:a.Timestamp,ResourceType:a.ResourceType,LogicalResourceId:a.LogicalResourceId,ResourceStatus:a.ResourceStatus,ResourceStatusReason:a.ResourceStatusReason});return t}async waitForStackWithProgress(e,t,s){let a={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},r=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],m=a[t],i=360,c=0,n=new Set;while(c<360)try{if(s)try{let k=[...(await this.describeStackEvents(e)).StackEvents||[]].reverse();for(let d of k){let g=`${d.LogicalResourceId}-${d.ResourceStatus}-${d.Timestamp}`;if(!n.has(g))n.add(g),s({resourceId:d.LogicalResourceId,resourceType:d.ResourceType,status:d.ResourceStatus,reason:d.ResourceStatusReason,timestamp:d.Timestamp})}}catch{}let o=await this.describeStacks({stackName:e});if(o.Stacks.length===0){if(t==="stack-delete-complete")return;await new Promise((S)=>setTimeout(S,2000)),c++;continue}let l=o.Stacks[0];if(m.includes(l.StackStatus))return;if(l.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let S=Error("Stack deletion failed - may have resources that need to be retained");throw S.code="DELETE_FAILED",S.stackStatus=l.StackStatus,S.statusReason=l.StackStatusReason,S}if(r.includes(l.StackStatus))throw Error(`Stack reached failure status: ${l.StackStatus}`);await new Promise((S)=>setTimeout(S,3000)),c++}catch(o){if(t==="stack-delete-complete"&&o.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&o.message?.includes("does not exist")){await new Promise((l)=>setTimeout(l,2000)),c++;continue}throw o}throw Error(`Timeout waiting for stack to reach ${t}`)}async waitForStackComplete(e,t=120,s=5000){let a=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],r=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let m=0;m<t;m++)try{let i=await this.describeStacks({stackName:e});if(i.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let c=i.Stacks[0],n=c.StackStatus;if(a.includes(n))return{success:!0,status:n};if(r.includes(n))return{success:!1,status:n,reason:c.StackStatusReason};await new Promise((o)=>setTimeout(o,s))}catch(i){if(i.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw i}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
1
+ import{u}from"./chunk-pdw0qjq1.js";class v{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(void 0,{profile:t})}async createStack(e){let t={Action:"CreateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});if(e.timeoutInMinutes)t.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)t.OnFailure=e.onFailure;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.CreateStackResult?.StackId}}async updateStack(e){let t={Action:"UpdateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{if(t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,a.UsePreviousValue)t[`Parameters.member.${r+1}.UsePreviousValue`]="true";else t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.UpdateStackResult?.StackId}}async deleteStack(e,t,s){let a={Action:"DeleteStack",StackName:e,Version:"2010-05-15"};if(t)a.RoleARN=t;if(s&&s.length>0)s.forEach((r,m)=>{a[`RetainResources.member.${m+1}`]=r});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(a).toString()})}async describeStacks(e={}){let t={Action:"DescribeStacks",Version:"2010-05-15"};if(e.stackName)t.StackName=e.stackName;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Stacks:this.parseStacksResponse(s)}}async describeStackEvents(e){let t={Action:"DescribeStackEvents",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackEvents:this.parseStackEvents(s)}}async listStackResources(e){let t={Action:"ListStackResources",StackName:e,Version:"2010-05-15"},a=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,r=[];if(a)r=Array.isArray(a)?a:[a];return{StackResourceSummaries:r}}async waitForStack(e,t){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},a=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],r=s[t],m=360,i=0;while(i<360)try{let c=await this.describeStacks({stackName:e});if(c.Stacks.length===0){if(t==="stack-delete-complete")return;if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack not visible yet`);await new Promise((o)=>setTimeout(o,2000)),i++;continue}let n=c.Stacks[0];if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Status = ${n.StackStatus}${n.StackStatusReason?` (${n.StackStatusReason})`:""}`);if(r.includes(n.StackStatus))return;if((t==="stack-create-complete"||t==="stack-update-complete")&&(n.StackStatus==="DELETE_IN_PROGRESS"||n.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let o="";try{let S=await this.describeStackEvents(e);console.log("[waitForStack] Stack events (most recent first):");for(let k of S.StackEvents.slice(0,15))if(k.ResourceStatus.includes("FAILED")||k.ResourceStatusReason){if(console.log(` ${k.LogicalResourceId}: ${k.ResourceStatus} - ${k.ResourceStatusReason||"No reason provided"}`),k.ResourceStatus.includes("FAILED")&&k.ResourceStatusReason&&!o)o=k.ResourceStatusReason}}catch{}let l=o||n.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${l}`)}if(n.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let o=Error("Stack deletion failed - may have resources that need to be retained");throw o.code="DELETE_FAILED",o.stackStatus=n.StackStatus,o.statusReason=n.StackStatusReason,o}if(a.includes(n.StackStatus))throw Error(`Stack reached failure status: ${n.StackStatus}`);await new Promise((o)=>setTimeout(o,5000)),i++}catch(c){if(t==="stack-delete-complete"&&c.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&c.message?.includes("does not exist")){if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack does not exist (error), retrying...`);await new Promise((n)=>setTimeout(n,2000)),i++;continue}throw console.log(`[waitForStack] Unexpected error: ${c.message}`),c}throw console.log(`[waitForStack] Timeout after ${i} attempts`),Error(`Timeout waiting for stack to reach ${t}`)}async validateTemplate(e){let t={Action:"ValidateTemplate",TemplateBody:e,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}async listStacks(e){let t={Action:"ListStacks",Version:"2010-05-15"};if(e)e.forEach((c,n)=>{t[`StackStatusFilter.member.${n+1}`]=c});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=s.ListStacksResponse||s,r=a.ListStacksResult||a,m=r.StackSummaries?.member||r.StackSummaries||[];return{StackSummaries:(Array.isArray(m)?m:m?[m]:[]).map((c)=>({StackId:c.StackId||"",StackName:c.StackName||"",TemplateDescription:c.TemplateDescription,CreationTime:c.CreationTime||"",LastUpdatedTime:c.LastUpdatedTime,DeletionTime:c.DeletionTime,StackStatus:c.StackStatus||""}))}}async createChangeSet(e){let t={Action:"CreateChangeSet",StackName:e.stackName,ChangeSetName:e.changeSetName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.changeSetType)t.ChangeSetType=e.changeSetType;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Id:s.Id,StackId:s.StackId}}async describeChangeSet(e,t){let s={Action:"DescribeChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async executeChangeSet(e,t){let s={Action:"ExecuteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async deleteChangeSet(e,t){let s={Action:"DeleteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async getStackOutputs(e){let t=await this.describeStacks({stackName:e});if(!t.Stacks||t.Stacks.length===0)throw Error(`Stack ${e} not found`);let s=t.Stacks[0],a={};if(s.Outputs)for(let r of s.Outputs)a[r.OutputKey]=r.OutputValue;return a}async getTemplate(e){let t={Action:"GetTemplate",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{TemplateBody:s?.GetTemplateResult?.TemplateBody||s?.TemplateBody||""}}parseStacksResponse(e){let t=[],s=e?.DescribeStacksResult?.Stacks?.member||e?.Stacks?.member||e?.Stacks||e;if(s&&!Array.isArray(s))s=[s];if(Array.isArray(s)){for(let a of s)if(a.StackId||a.StackName){let r;if(a.Outputs?.member)r=(Array.isArray(a.Outputs.member)?a.Outputs.member:[a.Outputs.member]).map((i)=>({OutputKey:i.OutputKey,OutputValue:i.OutputValue,Description:i.Description,ExportName:i.ExportName}));t.push({StackId:a.StackId,StackName:a.StackName,StackStatus:a.StackStatus,CreationTime:a.CreationTime,LastUpdatedTime:a.LastUpdatedTime,StackStatusReason:a.StackStatusReason,Outputs:r})}}else if(e.StackId)t.push({StackId:e.StackId,StackName:e.StackName,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime});return t}parseStackEvents(e){let t=[],s=e?.DescribeStackEventsResult?.StackEvents?.member||e?.StackEvents?.member||e?.StackEvents||[];if(s&&!Array.isArray(s))s=[s];for(let a of s)if(a.LogicalResourceId)t.push({Timestamp:a.Timestamp,ResourceType:a.ResourceType,LogicalResourceId:a.LogicalResourceId,ResourceStatus:a.ResourceStatus,ResourceStatusReason:a.ResourceStatusReason});return t}async waitForStackWithProgress(e,t,s){let a={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},r=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],m=a[t],i=360,c=0,n=new Set;while(c<360)try{if(s)try{let k=[...(await this.describeStackEvents(e)).StackEvents||[]].reverse();for(let d of k){let g=`${d.LogicalResourceId}-${d.ResourceStatus}-${d.Timestamp}`;if(!n.has(g))n.add(g),s({resourceId:d.LogicalResourceId,resourceType:d.ResourceType,status:d.ResourceStatus,reason:d.ResourceStatusReason,timestamp:d.Timestamp})}}catch{}let o=await this.describeStacks({stackName:e});if(o.Stacks.length===0){if(t==="stack-delete-complete")return;await new Promise((S)=>setTimeout(S,2000)),c++;continue}let l=o.Stacks[0];if(m.includes(l.StackStatus))return;if(l.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let S=Error("Stack deletion failed - may have resources that need to be retained");throw S.code="DELETE_FAILED",S.stackStatus=l.StackStatus,S.statusReason=l.StackStatusReason,S}if(r.includes(l.StackStatus))throw Error(`Stack reached failure status: ${l.StackStatus}`);await new Promise((S)=>setTimeout(S,3000)),c++}catch(o){if(t==="stack-delete-complete"&&o.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&o.message?.includes("does not exist")){await new Promise((l)=>setTimeout(l,2000)),c++;continue}throw o}throw Error(`Timeout waiting for stack to reach ${t}`)}async waitForStackComplete(e,t=120,s=5000){let a=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],r=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let m=0;m<t;m++)try{let i=await this.describeStacks({stackName:e});if(i.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let c=i.Stacks[0],n=c.StackStatus;if(a.includes(n))return{success:!0,status:n};if(r.includes(n))return{success:!1,status:n,reason:c.StackStatusReason};await new Promise((o)=>setTimeout(o,s))}catch(i){if(i.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw i}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
2
2
  export{v};
@@ -1,4 +1,4 @@
1
- import{u}from"./chunk-bckm6fre.js";class w{client;constructor(e,i){this.client=i??new u(void 0,{profile:e})}collectionItems(e,i){let t=e?.Items??e?.[i];if(!t)return[];if(Array.isArray(t))return t;let n=t[i]??t.Item;if(n===void 0)return typeof t==="object"&&(t.Id||t.PathPattern)?[t]:[];return Array.isArray(n)?n:[n]}validateExistingOriginInput(e,i){if(!/^[A-Z0-9]{8,32}$/.test(e))throw Error("CloudFront distribution ID is invalid");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(i.id))throw Error("CloudFront origin ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(i.domainName))throw Error("CloudFront origin must be a hostname without a scheme or path");let t=i.pathPattern.startsWith("/")?i.pathPattern:`/${i.pathPattern}`;if(t==="/"||t==="/*"||!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]{1,255}$/.test(t))throw Error("CloudFront path pattern must be a non-default absolute pattern");if(i.originPath&&(!i.originPath.startsWith("/")||i.originPath.includes("..")))throw Error("CloudFront origin path must be absolute and traversal-free");if(Object.entries(i.customHeaders??{}).some(([n,s])=>!/^[A-Za-z0-9-]{1,64}$/.test(n)||!s||s.length>1024))throw Error("CloudFront custom origin headers are invalid");return{...i,pathPattern:t}}async upsertExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),s=n.headers?.etag||n.headers?.ETag||n.ETag||"",r=n.body?.DistributionConfig||n.DistributionConfig||n.body;if(!r||r.Enabled===void 0||!s)throw Error("Failed to read an ETag-protected CloudFront distribution config");let o=this.collectionItems(r.Origins,"Origin"),a=this.collectionItems(r.CacheBehaviors,"CacheBehavior"),g=o.find((y)=>String(y.Id)===t.id),c=a.find((y)=>String(y.PathPattern)===t.pathPattern);if(g&&String(g.DomainName)!==t.domainName&&!t.replaceExisting)throw Error(`Origin ${t.id} already targets ${g.DomainName}; pass replaceExisting only after reviewing the live config`);if(c&&String(c.TargetOriginId)!==t.id&&!t.replaceExisting)throw Error(`Path ${t.pathPattern} already targets ${c.TargetOriginId}; pass replaceExisting only after reviewing the live config`);let d={Id:t.id,DomainName:t.domainName,OriginPath:t.originPath??"",CustomHeaders:{Quantity:Object.keys(t.customHeaders??{}).length,...Object.keys(t.customHeaders??{}).length?{Items:{OriginCustomHeader:Object.entries(t.customHeaders).map(([y,E])=>({HeaderName:y,HeaderValue:E}))}}:{}},CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:t.protocolPolicy??"https-only",OriginSslProtocols:{Quantity:1,Items:{SslProtocol:["TLSv1.2"]}},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:3,ConnectionTimeout:10,...t.originAccessControlId?{OriginAccessControlId:t.originAccessControlId}:{}},h=["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],l={PathPattern:t.pathPattern,TargetOriginId:t.id,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",AllowedMethods:{Quantity:h.length,Items:{Method:h},CachedMethods:{Quantity:2,Items:{Method:["GET","HEAD"]}}},SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0}},f=g?o.map((y)=>String(y.Id)===t.id?d:y):[...o,d],m=c?a.map((y)=>String(y.PathPattern)===t.pathPattern?l:y):[...a,l],p=JSON.stringify(o)!==JSON.stringify(f)||JSON.stringify(a)!==JSON.stringify(m);if(!p||t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:p,applied:!1,etag:s};r.Origins={Quantity:f.length,Items:{Origin:f}},r.CacheBehaviors={Quantity:m.length,...m.length?{Items:{CacheBehavior:m}}:{}};let b=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(r),headers:{"Content-Type":"application/xml","If-Match":s}});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,etag:b.ETag||b.headers?.etag||""}}async removeExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),s=n.headers?.etag||n.headers?.ETag||n.ETag||"",r=n.body?.DistributionConfig||n.DistributionConfig||n.body;if(!r||r.Enabled===void 0||!s)throw Error("Failed to read an ETag-protected CloudFront distribution config");let o=this.collectionItems(r.Origins,"Origin"),a=this.collectionItems(r.CacheBehaviors,"CacheBehavior"),g=o.find((m)=>String(m.Id)===t.id),c=a.find((m)=>String(m.PathPattern)===t.pathPattern);if(g&&String(g.DomainName)!==t.domainName)throw Error(`Origin ${t.id} no longer targets ${t.domainName}; refusing ambiguous removal`);if(c&&String(c.TargetOriginId)!==t.id)throw Error(`Path ${t.pathPattern} no longer targets ${t.id}; refusing ambiguous removal`);if(!c)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!1,applied:!1,originRemoved:!1,etag:s};let d=a.filter((m)=>String(m.PathPattern)!==t.pathPattern),h=String(r.DefaultCacheBehavior?.TargetOriginId)===t.id||d.some((m)=>String(m.TargetOriginId)===t.id),l=h?o:o.filter((m)=>String(m.Id)!==t.id);if(t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!1,originRemoved:!h&&!!g,etag:s};r.Origins={Quantity:l.length,Items:{Origin:l}},r.CacheBehaviors={Quantity:d.length,...d.length?{Items:{CacheBehavior:d}}:{}};let f=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(r),headers:{"Content-Type":"application/xml","If-Match":s}});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,originRemoved:!h&&!!g,etag:f.ETag||f.headers?.etag||""}}async createInvalidation(e){let i=e.callerReference||Date.now().toString(),t=`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{u}from"./chunk-pdw0qjq1.js";class w{client;constructor(e,i){this.client=i??new u(void 0,{profile:e})}collectionItems(e,i){let t=e?.Items??e?.[i];if(!t)return[];if(Array.isArray(t))return t;let n=t[i]??t.Item;if(n===void 0)return typeof t==="object"&&(t.Id||t.PathPattern)?[t]:[];return Array.isArray(n)?n:[n]}validateExistingOriginInput(e,i){if(!/^[A-Z0-9]{8,32}$/.test(e))throw Error("CloudFront distribution ID is invalid");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(i.id))throw Error("CloudFront origin ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(i.domainName))throw Error("CloudFront origin must be a hostname without a scheme or path");let t=i.pathPattern.startsWith("/")?i.pathPattern:`/${i.pathPattern}`;if(t==="/"||t==="/*"||!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]{1,255}$/.test(t))throw Error("CloudFront path pattern must be a non-default absolute pattern");if(i.originPath&&(!i.originPath.startsWith("/")||i.originPath.includes("..")))throw Error("CloudFront origin path must be absolute and traversal-free");if(Object.entries(i.customHeaders??{}).some(([n,s])=>!/^[A-Za-z0-9-]{1,64}$/.test(n)||!s||s.length>1024))throw Error("CloudFront custom origin headers are invalid");return{...i,pathPattern:t}}async upsertExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),s=n.headers?.etag||n.headers?.ETag||n.ETag||"",r=n.body?.DistributionConfig||n.DistributionConfig||n.body;if(!r||r.Enabled===void 0||!s)throw Error("Failed to read an ETag-protected CloudFront distribution config");let o=this.collectionItems(r.Origins,"Origin"),a=this.collectionItems(r.CacheBehaviors,"CacheBehavior"),g=o.find((y)=>String(y.Id)===t.id),c=a.find((y)=>String(y.PathPattern)===t.pathPattern);if(g&&String(g.DomainName)!==t.domainName&&!t.replaceExisting)throw Error(`Origin ${t.id} already targets ${g.DomainName}; pass replaceExisting only after reviewing the live config`);if(c&&String(c.TargetOriginId)!==t.id&&!t.replaceExisting)throw Error(`Path ${t.pathPattern} already targets ${c.TargetOriginId}; pass replaceExisting only after reviewing the live config`);let d={Id:t.id,DomainName:t.domainName,OriginPath:t.originPath??"",CustomHeaders:{Quantity:Object.keys(t.customHeaders??{}).length,...Object.keys(t.customHeaders??{}).length?{Items:{OriginCustomHeader:Object.entries(t.customHeaders).map(([y,E])=>({HeaderName:y,HeaderValue:E}))}}:{}},CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:t.protocolPolicy??"https-only",OriginSslProtocols:{Quantity:1,Items:{SslProtocol:["TLSv1.2"]}},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:3,ConnectionTimeout:10,...t.originAccessControlId?{OriginAccessControlId:t.originAccessControlId}:{}},h=["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],l={PathPattern:t.pathPattern,TargetOriginId:t.id,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",AllowedMethods:{Quantity:h.length,Items:{Method:h},CachedMethods:{Quantity:2,Items:{Method:["GET","HEAD"]}}},SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0}},f=g?o.map((y)=>String(y.Id)===t.id?d:y):[...o,d],m=c?a.map((y)=>String(y.PathPattern)===t.pathPattern?l:y):[...a,l],p=JSON.stringify(o)!==JSON.stringify(f)||JSON.stringify(a)!==JSON.stringify(m);if(!p||t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:p,applied:!1,etag:s};r.Origins={Quantity:f.length,Items:{Origin:f}},r.CacheBehaviors={Quantity:m.length,...m.length?{Items:{CacheBehavior:m}}:{}};let b=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(r),headers:{"Content-Type":"application/xml","If-Match":s}});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,etag:b.ETag||b.headers?.etag||""}}async removeExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),s=n.headers?.etag||n.headers?.ETag||n.ETag||"",r=n.body?.DistributionConfig||n.DistributionConfig||n.body;if(!r||r.Enabled===void 0||!s)throw Error("Failed to read an ETag-protected CloudFront distribution config");let o=this.collectionItems(r.Origins,"Origin"),a=this.collectionItems(r.CacheBehaviors,"CacheBehavior"),g=o.find((m)=>String(m.Id)===t.id),c=a.find((m)=>String(m.PathPattern)===t.pathPattern);if(g&&String(g.DomainName)!==t.domainName)throw Error(`Origin ${t.id} no longer targets ${t.domainName}; refusing ambiguous removal`);if(c&&String(c.TargetOriginId)!==t.id)throw Error(`Path ${t.pathPattern} no longer targets ${t.id}; refusing ambiguous removal`);if(!c)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!1,applied:!1,originRemoved:!1,etag:s};let d=a.filter((m)=>String(m.PathPattern)!==t.pathPattern),h=String(r.DefaultCacheBehavior?.TargetOriginId)===t.id||d.some((m)=>String(m.TargetOriginId)===t.id),l=h?o:o.filter((m)=>String(m.Id)!==t.id);if(t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!1,originRemoved:!h&&!!g,etag:s};r.Origins={Quantity:l.length,Items:{Origin:l}},r.CacheBehaviors={Quantity:d.length,...d.length?{Items:{CacheBehavior:d}}:{}};let f=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(r),headers:{"Content-Type":"application/xml","If-Match":s}});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,originRemoved:!h&&!!g,etag:f.ETag||f.headers?.etag||""}}async createInvalidation(e){let i=e.callerReference||Date.now().toString(),t=`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <InvalidationBatch>
3
3
  <Paths>
4
4
  <Quantity>${e.paths.length}</Quantity>
@@ -1,2 +1,2 @@
1
- import{u}from"./chunk-bckm6fre.js";import{O}from"./chunk-57w9nsjk.js";var C=new Set(["A","AAAA","CNAME"]);function P(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 D(e,t){let r=t?.headers.get("retry-after"),n=r===null||r===void 0?void 0:Number(r)*1000,s=Number.isFinite(n)?Math.max(0,n):Math.min(1000*2**(e-1),30000);await new Promise((o)=>setTimeout(o,s))}class lt{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 n=1;n<=8;n+=1){let s,o=new AbortController,i=setTimeout(()=>{o.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{s=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:o.signal})}catch(c){if(r=c,n===8)throw c;await D(n);continue}finally{clearTimeout(i)}if(!s.ok){if(r=Error(`Porkbun API error: ${s.status} ${s.statusText}`),!P(s.status)||n===8)throw r;await D(n,s);continue}let a=await s.json();if(a.status==="ERROR"){if(r=Error(`Porkbun API error: ${a.message||"Unknown error"}`),!P(0,a.message)||n===8)throw r;await D(n,s);continue}return a}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"";if(r.endsWith(`.${n}`))return r.slice(0,-(n.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(!lt.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.listRecords(e);if(!s.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${s.message??"unknown provider error"}`];let o=[];for(let i of s.records){if(i.type!=="ALIAS"&&i.type!=="CNAME")continue;if(this.getSubdomain(i.name,r)!==n)continue;let a=await this.deleteRecord(e,i);if(!a.success)o.push(`could not remove conflicting ${i.type} on ${i.name}: ${a.message??"unknown provider error"}`)}return o}async addressRecordExists(e,t){let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.listRecords(e);if(!s.success)return!0;return s.records.some((o)=>o.type===t.type&&this.getSubdomain(o.name,r)===n&&o.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)s.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)s.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)s.content=`${t.weight} ${t.port} ${t.content}`;let o=await this.clearConflictingAliases(e,t),i=await this.request(`/dns/create/${r}`,s);if(lt.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${o.length>0?` (${o.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:i.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),n=this.getSubdomain(t.name,r),s=await this.listRecords(e,t.type);if(s.success){let o=s.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type);if(o?.id){let i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)i.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)i.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)i.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${o.id}`,i),{success:!0,id:o.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 n=this.getSubdomain(t.name,r),s=await this.listRecords(e);if(!s.success)return{success:!1,message:"Failed to list records"};let o=s.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type&&i.content===t.content);if(!o?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${o.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),n=`/dns/retrieve/${r}`;if(t)n=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(n)).records||[]).map((i)=>({id:i.id,name:i.name||r,type:i.type,content:i.content,ttl:Number.parseInt(i.ttl,10),priority:i.prio?Number.parseInt(i.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 or{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 n=`${this.baseUrl}${t}`,s={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},o={method:e,headers:s};if(r)o.body=JSON.stringify(r);let i=await fetch(n,o);if(i.status===204)return{};if(i.ok){let c=await i.text();if(c)return JSON.parse(c);return{}}let a=`GoDaddy API error: ${i.status} ${i.statusText}`;try{let c=await i.json();if(c.message)a=`GoDaddy API error: ${c.message}`;if(c.fields)a+=` - Fields: ${JSON.stringify(c.fields)}`}catch{}throw Error(a)}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"@";if(r.endsWith(`.${n}`))return r.slice(0,-(n.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),n=this.getSubdomain(e.name,r),s={type:e.type,name:n,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;return s}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),n=e.name;if(n==="@")n=r;else if(!n.endsWith(r))n=`${n}.${r}`;return{name:n,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[n]),{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),n=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n.name}`,[n]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${n}`),o=s.filter((i)=>i.data!==t.content);if(o.length===s.length)return{success:!1,message:"Record not found"};if(o.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${n}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n}`,o);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),n=`/v1/domains/${r}/records`;if(t)n=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",n)).map((o)=>this.fromGoDaddyRecord(o,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 b="https://api.cloudflare.com/client/v4",w="[ts-cloud]";class dt{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 n=`${b}${t}`,s={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},o={method:e,headers:s};if(r)o.body=JSON.stringify(r);let a=await(await fetch(n,o)).json();if(!a.success){let c=a.errors.map((d)=>d.message).join(", ");throw Error(`Cloudflare API error: ${c}`)}return a}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 i=await this.resolveConfiguredZoneName();if(i&&(t===i||t.endsWith(`.${i}`)))return{id:this.configuredZoneId,name:i}}let r=this.getRootDomain(t),n=this.zoneCache.get(r);if(n)return{id:n,name:r};let s=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!s.result||s.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 o=s.result[0].id;return this.zoneCache.set(r,o),{id:o,name:s.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 n={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},s=r??e.proxied;if(s!==void 0&&C.has(e.type)){if(n.proxied=s,s)n.ttl=1}if(e.type==="MX"&&e.priority!==void 0)n.priority=e.priority;if(e.type==="SRV"){let o=I(e);if(o)n.data=o,delete n.content,delete n.priority;else if(e.priority!==void 0)n.priority=e.priority}return n}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),n=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,n)).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),n=this.getFullRecordName(t.name,r.name),o=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(n)}`)).result?.[0],i=t.proxied??o?.proxied,a=this.toCloudflareRecord(t,r.name,i);if(o)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${o.id}`,a)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,a)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),n=r.id,s=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`);if(!o.result||o.result.length===0)return{success:!1,message:"Record not found"};let i=o.result.find((a)=>a.content===t.content);if(!i)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${n}/dns_records/${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 n=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)n+=`&type=${t}`;let s=[],o=1,i=!0;while(i){let a=await this.request("GET",`${n}&page=${o}`);if(s.push(...a.result||[]),a.result_info)i=o<a.result_info.total_pages,o++;else i=!1}return{success:!0,records:s.map((a)=>this.fromCloudflareRecord(a))}}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 n=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...n.result||[]),n.result_info)r=t<n.result_info.total_pages,t++;else r=!1}return e.map((n)=>n.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),n=t.accountId??this.accountId;if(!n)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let s=await this.getZoneDetails(r);if(s)return{...s,created:!1};try{let i=(await this.request("POST","/zones",{name:r,account:{id:n},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(i.name,i.id),{id:i.id,name:i.name,status:i.status,nameServers:i.name_servers??[],created:!0}}catch(o){let i=o instanceof Error?o.message:String(o);if(!/already exists|1061/i.test(i))throw o;let a=await this.getZoneDetails(r);if(!a)throw o;return{...a,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`),n=new Set;for(let s of r.result||[]){if(s.status!=="active")continue;for(let o of s.hosts||[])n.add(o.toLowerCase())}return[...n]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),n={};if(t?.purgeEverything)n.purge_everything=!0;else{if(t?.files)n.files=t.files;if(t?.tags)n.tags=t.tags;if(t?.hosts)n.hosts=t.hosts}if(Object.keys(n).length===0)n.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,n),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),n=r.id,s=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`);if(o.result&&o.result.length>0)return o.result.find((a)=>a.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let n=await this.resolveZone(e),s=n.id,o=this.getFullRecordName(t.name,n.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!i.result||i.result.length===0)return!1;let a=i.result.find((c)=>c.content===t.content);if(!a)return!1;return await this.request("PATCH",`/zones/${s}/dns_records/${a.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`),n={};for(let s of r.result||[])n[s.id]=s.value;return n}async applyZoneSettings(e,t){let r=await this.getZoneId(e),n=await this.getZoneSettings(e).catch(()=>({})),s=[],o=[];for(let[i,a]of Object.entries(t)){if(a===void 0)continue;let c=n[i];if(c!==void 0&&v(c,a))continue;try{await this.request("PATCH",`/zones/${r}/settings/${i}`,{value:a}),s.push({id:i,from:c,to:a})}catch(d){o.push({id:i,error:d instanceof Error?d.message:String(d)})}}return{changed:s,failed:o}}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 n=await this.getZoneId(e),o=(await this.getPhaseRules(e,t)).filter((c)=>!(c.description||"").startsWith(w)),i=r.map((c)=>({...c,description:c.description?.startsWith(w)?c.description:`${w} ${c.description||t}`})),a=[...o,...i].map(({id:c,...d})=>d);return await this.request("PUT",`/zones/${n}/rulesets/phases/${t}/entrypoint`,{rules:a}),{success:!0}}catch(n){return{success:!1,message:n instanceof Error?n.message:String(n)}}}}function v(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((s,o)=>v(s,t[o]))}let r=e,n=t;return Object.keys(n).every((s)=>v(r[s],n[s]))}function I(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:N(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[n,s,o]=r.slice(0,3).map(Number);if(![n,s,o].every(Number.isFinite))return null;return{priority:n,weight:s,port:o,target:N(r.slice(3).join(" "))}}function N(e){return e.replace(/\.$/,"")}var E=new Set(["A","AAAA","CNAME","ALIAS"]);function R(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 f(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function h(e){return e.replace(/\.$/,"").toLowerCase()}function S(e,t){let r=h(t),n=(e??"@").trim();if(!n||n==="@")return r;let s=h(n);if(s===r||s.endsWith(`.${r}`))return s;return`${s}.${r}`}function Oi(e,t){return e.map((r)=>({...r,name:S(r.name,t),proxied:r.proxied??!1}))}function x(e,t){if(e.type!==t.type)return!1;if(h(e.name)!==h(t.name))return!1;if(E.has(t.type))return!0;if(t.type==="TXT"){let r=R(t.content);if(r)return R(f(e.content))===r;return f(e.content)===f(t.content)}return f(e.content)===f(t.content)}function V(e,t){if(f(e.content)!==f(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 Li(e){let{provider:t,zone:r,records:n}=e,s={outcomes:[],warnings:[]};if(n.length===0)return s;let o=await t.listRecords(r);if(!o.success)return s.warnings.push(`could not list ${r}: ${o.message||"unknown provider error"} — records not reconciled`),s;let i=o.records;for(let a of n){let c=i.filter((l)=>x(l,a));if(c.length>0&&c.every((l)=>V(l,a))){s.outcomes.push({record:a,action:"unchanged"});continue}let d={name:a.name,type:a.type,content:a.content,ttl:a.ttl??3600,...a.priority!==void 0?{priority:a.priority}:{},...a.proxied!==void 0?{proxied:a.proxied}:{}},g=a.type==="TXT"&&R(a.content)!==void 0;if(g)for(let l of c){let A=await t.deleteRecord(r,{name:l.name,type:l.type,content:l.content});if(!A.success)s.warnings.push(`could not remove superseded ${l.type} at ${l.name}: ${A.message||"unknown error"}`)}let p=g||c.length===0?await t.createRecord(r,d):await t.upsertRecord(r,d);if(p.success)s.outcomes.push({record:a,action:c.length>0?"updated":"created"});else s.outcomes.push({record:a,action:"failed",message:p.message})}for(let a of["MX"]){let c=new Set(n.filter((d)=>d.type===a).map((d)=>h(d.name)));for(let d of c){let g=new Set(n.filter((l)=>l.type===a&&h(l.name)===d).map((l)=>f(l.content).toLowerCase())),p=i.filter((l)=>l.type===a&&h(l.name)===d&&!g.has(f(l.content).toLowerCase()));for(let l of p)s.warnings.push(`${d} has an undeclared ${a} record (${l.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return s}class jr{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new O(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 n=await this.client.findHostedZoneForDomain(e);if(n){let s=n.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,s),s}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(!n||n==="@")return`${r}.`;if(n===r||n.endsWith(`.${r}`))return`${n}.`;return`${n}.${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 n=this.normalizeName(e,t.name),s=t.content;if(t.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(t.type==="MX"&&t.priority!==void 0)s=`${t.priority} ${s}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:"CREATE",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:s}]}}]}})).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 n=this.normalizeName(e,t.name),s=t.content;if(t.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(t.type==="MX"&&t.priority!==void 0)s=`${t.priority} ${s}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:s}]}}]}})).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 n=this.normalizeName(e,t.name),s=t.content;if(t.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(t.type==="MX"&&t.priority!==void 0)s=`${t.priority} ${s}`;return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:s}]}}]}}),{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 n=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),s=[];for(let o of n.ResourceRecordSets){if(t&&o.Type!==t)continue;if(o.AliasTarget)continue;for(let i of o.ResourceRecords||[]){let a=i.Value,c;if(o.Type==="MX"){let d=a.split(" ");if(d.length>=2)c=Number.parseInt(d[0],10),a=d.slice(1).join(" ")}if(o.Type==="TXT"&&a.startsWith('"')&&a.endsWith('"'))a=a.slice(1,-1);s.push({name:o.Name.replace(/\.$/,""),type:o.Type,content:a,ttl:o.TTL,priority:c})}}return{success:!0,records:s}}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:O.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=O.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 Mi(e,t){let r=[],n,s;for(;;){let o=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:n,StartRecordType:s,MaxItems:"100"});if(r.push(...o.ResourceRecordSets),!o.IsTruncated)break;if(n=o.NextRecordName,s=o.NextRecordType,!n)break}return r}function m(e){return e.replace(/\.$/,"").toLowerCase()}function T(e){return e.replace(/\.$/,"")}function y(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${T(e.content)}`;return T(e.content)}function M(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function Ui(e,t){let r=m(t),n=[],s=[],o=[],i=new Set;for(let a of e){let c=m(a.Name),d=a.Type;if(d==="SOA"||d==="NS"&&c===r){s.push({name:c,type:d,reason:"owned by the destination provider"});continue}if(a.SetIdentifier){s.push({name:c,type:d,reason:`routing policy record (SetIdentifier=${a.SetIdentifier}) has no equivalent — recreate by hand`}),o.push(`${d} ${c} is part of a Route53 routing policy and was NOT migrated`);continue}if(a.AliasTarget){if(i.has(c))continue;i.add(c);let g=m(a.AliasTarget.DNSName);if(n.push({name:c,type:"CNAME",content:g,ttl:300,translatedFrom:`${d} ALIAS → ${g}`}),a.AliasTarget.EvaluateTargetHealth)o.push(`${c} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let g of a.ResourceRecords||[]){let p=_(c,d,g.Value,a.TTL);if("reason"in p){s.push({name:c,type:d,reason:p.reason}),o.push(`${d} ${c}: ${p.reason}`);continue}n.push(p)}}return{zone:r,records:n,skipped:s,warnings:o}}function _(e,t,r,n){let s={name:e,ttl:n};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...s,type:t==="PTR"?"CNAME":t,content:m(r)};case"TXT":return{...s,type:"TXT",content:M(r)};case"MX":{let[o,...i]=r.trim().split(/\s+/);if(!i.length)return{reason:`malformed MX value "${r}"`};return{...s,type:"MX",content:m(i.join(" ")),priority:Number(o)}}case"SRV":{let o=r.trim().split(/\s+/);if(o.length<4)return{reason:`malformed SRV value "${r}"`};let[i,a,c]=o.slice(0,3).map(Number);return{...s,type:"SRV",content:m(o.slice(3).join(" ")),priority:i,weight:a,port:c}}case"NS":return{...s,type:"NS",content:m(r)};case"CAA":return{...s,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var Z=new Set(["TXT","MX","SRV","NS","CAA"]);async function Bi(e,t){let r=[],n=[],s=new Set;try{let o=await e.listRecords(t.zone);for(let i of o.records||[])s.add(`${m(i.name)}|${i.type}|${y(i)}`)}catch{}for(let o of t.records){let i={...o,proxied:!1},a=`${m(o.name)}|${o.type}|${y(o)}`;if(!Z.has(o.type)){let d=await e.upsertRecord(t.zone,i);if(d.success)r.push(o);else n.push({record:o,message:d.message||"unknown provider error"});continue}if(s.has(a)){r.push(o);continue}let c=await e.createRecord(t.zone,i);if(c.success)s.add(a),r.push(o);else n.push({record:o,message:c.message||"unknown provider error"})}return{applied:r,failed:n}}async function Fi(e,t){let r=await e.listRecords(t.zone),n=[],s=[],o=new Map;for(let i of r.records||[]){let a=`${m(i.name)}|${i.type}`,c=o.get(a)??[];c.push(y(i)),o.set(a,c)}for(let i of t.records){let a=o.get(`${m(i.name)}|${i.type}`),c=y(i);if(a?.some((d)=>d===c))n.push(i);else s.push({record:i,found:a?.join(", ")})}return{matched:n,missing:s,ok:s.length===0}}class xt{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new q(t),"provider"in e)this.dnsProvider=L(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!1,maxWaitMinutes:s=30}=e,{CertificateArn:o}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(o);let i=await this.acm.getDnsValidationRecords(o);for(let c of i){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}let a="pending";if(n)a=(await this.acm.waitForCertificateValidation(o,s*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:o,validationRecords:i.map((c)=>({domainName:c.domainName,recordName:c.recordName,recordType:c.recordType,recordValue:c.recordValue})),isNew:!0,status:a}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],s=await this.acm.getDnsValidationRecords(t);for(let o of s){let i=await this.dnsProvider.upsertRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue,ttl:300});if(!i.success)n.push(`Failed to create record for ${o.domainName}: ${i.message}`)}return{success:n.length===0,records:s.map((o)=>({domainName:o.domainName,recordName:o.recordName,recordType:o.recordType,recordValue:o.recordValue})),errors:n}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],s=await this.acm.getDnsValidationRecords(t);for(let o of s){let i=await this.dnsProvider.deleteRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue});if(!i.success)n.push(`Failed to delete record for ${o.domainName}: ${i.message}`)}return{success:n.length===0,errors:n}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!0,maxWaitMinutes:s}=e,o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED"){let i=o.SubjectAlternativeNames||[o.DomainName],a=i.some((d)=>d===`*.${t}`);if(r.every((d)=>i.includes(d)||a))return{certificateArn:o.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:n,maxWaitMinutes:s})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:n=!1,additionalSans:s=[],waitForValidation:o=!1}=e,i=[];if(r)i.push(`www.${t}`);if(n)i.push(`*.${t}`);return i.push(...s),this.requestAndValidate({domainName:t,subjectAlternativeNames:i,waitForValidation:o})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((s)=>setTimeout(s,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 L(e){switch(e.provider){case"route53":return new jr(e.region,e.hostedZoneId);case"porkbun":return new lt(e.apiKey,e.secretKey);case"godaddy":return new or(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new dt(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}class Xn{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,n=process.env.GODADDY_API_SECRET;if(r&&n){let o=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,n,o)}let s=process.env.CLOUDFLARE_API_TOKEN;if(s)this.addCloudflare(s,{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((s)=>s.provider===e);if(!r)return null;let n=L(r);return this.providers.set(e,n),n}async getProviderForDomain(e){for(let t of this.configs){let r=L(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>L(e))}}var oe=new Xn;class q{client;region;constructor(e="us-east-1"){this.client=new u,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((n)=>({DomainName:n.DomainName,ValidationDomain:n.ValidationDomain,ValidationStatus:n.ValidationStatus,ResourceRecord:n.ResourceRecord?{Name:n.ResourceRecord.Name,Type:n.ResourceRecord.Type,Value:n.ResourceRecord.Value}:void 0,ValidationMethod:n.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((n)=>({CertificateArn:n.CertificateArn,DomainName:n.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((n)=>n.DomainName===e||n.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 n=0;n<t;n++){let s=await this.describeCertificate({CertificateArn:e});if(s.Status==="ISSUED")return s;if(s.Status==="FAILED"||s.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((o)=>setTimeout(o,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 n=r.DomainName.slice(2),s=t.split("."),o=n.split(".");if(s.slice(-o.length).join(".")===n)return!0}if(r.SubjectAlternativeNames)for(let n of r.SubjectAlternativeNames){if(n===t)return!0;if(n.startsWith("*.")){let s=n.slice(2),o=t.split("."),i=s.split(".");if(o.slice(-i.length).join(".")===s)return!0}}return!1}}class ji{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new q(e),this.route53=new O,t&&t.provider!=="route53")this.dnsProvider=L(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n=[],waitForValidation:s=!1,maxWaitMinutes:o=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:n.length>0?[t,...n]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);if(this.dnsProvider)for(let c of a){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}else if(r)for(let c of a)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${c.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:c.recordName,Type:c.recordType,TTL:300,ResourceRecords:[{Value:c.recordValue}]}}]}});if(s){if(!await this.acm.waitForCertificateValidation(i,o*2,30000))throw Error(`Certificate validation timed out after ${o} minutes`)}return{certificateArn:i,validationRecords:a}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((s)=>setTimeout(s,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let s=await this.acm.getDnsValidationRecords(t),o=[];if(this.dnsProvider){let i=n||s[0]?.domainName;for(let a of s){let c=await this.dnsProvider.upsertRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue,ttl:300});o.push({...a,changeId:c.success?c.id:void 0})}}else if(r)for(let i of s){let a=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${i.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}});o.push({...i,changeId:a.ChangeInfo?.Id})}return o}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e,s=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let o=n||s[0]?.domainName;for(let i of s)try{await this.dnsProvider.deleteRecord(o,{name:i.recordName,type:i.recordType,content:i.recordValue})}catch{}}else if(r)for(let o of s)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${o.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:o.recordName,Type:o.recordType,TTL:300,ResourceRecords:[{Value:o.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:s=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED")return{certificateArn:o.CertificateArn,isNew:!1};let{certificateArn:i}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:s});return{certificateArn:i,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}
2
- export{lt,or,dt,Oi,Li,jr,Mi,Ui,Bi,Fi,q,ji,xt,L,Xn};
1
+ import{u}from"./chunk-pdw0qjq1.js";import{O}from"./chunk-p197a99s.js";var D=new Set(["A","AAAA","CNAME"]);function P(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 v(e,t){let r=t?.headers.get("retry-after"),n=r===null||r===void 0?void 0:Number(r)*1000,s=Number.isFinite(n)?Math.max(0,n):Math.min(1000*2**(e-1),30000);await new Promise((o)=>setTimeout(o,s))}class ze{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 n=1;n<=8;n+=1){let s,o=new AbortController,i=setTimeout(()=>{o.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{s=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:o.signal})}catch(c){if(r=c,n===8)throw c;await v(n);continue}finally{clearTimeout(i)}if(!s.ok){if(r=Error(`Porkbun API error: ${s.status} ${s.statusText}`),!P(s.status)||n===8)throw r;await v(n,s);continue}let a=await s.json();if(a.status==="ERROR"){if(r=Error(`Porkbun API error: ${a.message||"Unknown error"}`),!P(0,a.message)||n===8)throw r;await v(n,s);continue}return a}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"";if(r.endsWith(`.${n}`))return r.slice(0,-(n.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(!ze.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.listRecords(e);if(!s.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${s.message??"unknown provider error"}`];let o=[];for(let i of s.records){if(i.type!=="ALIAS"&&i.type!=="CNAME")continue;if(this.getSubdomain(i.name,r)!==n)continue;let a=await this.deleteRecord(e,i);if(!a.success)o.push(`could not remove conflicting ${i.type} on ${i.name}: ${a.message??"unknown provider error"}`)}return o}async addressRecordExists(e,t){let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.listRecords(e);if(!s.success)return!0;return s.records.some((o)=>o.type===t.type&&this.getSubdomain(o.name,r)===n&&o.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)s.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)s.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)s.content=`${t.weight} ${t.port} ${t.content}`;let o=await this.clearConflictingAliases(e,t),i=await this.request(`/dns/create/${r}`,s);if(ze.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${o.length>0?` (${o.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:i.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),n=this.getSubdomain(t.name,r),s=await this.listRecords(e,t.type);if(s.success){let o=s.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type);if(o?.id){let i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)i.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)i.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)i.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${o.id}`,i),{success:!0,id:o.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 n=this.getSubdomain(t.name,r),s=await this.listRecords(e);if(!s.success)return{success:!1,message:"Failed to list records"};let o=s.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type&&i.content===t.content);if(!o?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${o.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),n=`/dns/retrieve/${r}`;if(t)n=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(n)).records||[]).map((i)=>({id:i.id,name:i.name||r,type:i.type,content:i.content,ttl:Number.parseInt(i.ttl,10),priority:i.prio?Number.parseInt(i.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 xt{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 n=`${this.baseUrl}${t}`,s={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},o={method:e,headers:s};if(r)o.body=JSON.stringify(r);let i=await fetch(n,o);if(i.status===204)return{};if(i.ok){let c=await i.text();if(c)return JSON.parse(c);return{}}let a=`GoDaddy API error: ${i.status} ${i.statusText}`;try{let c=await i.json();if(c.message)a=`GoDaddy API error: ${c.message}`;if(c.fields)a+=` - Fields: ${JSON.stringify(c.fields)}`}catch{}throw Error(a)}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"@";if(r.endsWith(`.${n}`))return r.slice(0,-(n.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),n=this.getSubdomain(e.name,r),s={type:e.type,name:n,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;return s}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),n=e.name;if(n==="@")n=r;else if(!n.endsWith(r))n=`${n}.${r}`;return{name:n,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[n]),{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),n=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n.name}`,[n]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${n}`),o=s.filter((i)=>i.data!==t.content);if(o.length===s.length)return{success:!1,message:"Record not found"};if(o.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${n}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n}`,o);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),n=`/v1/domains/${r}/records`;if(t)n=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",n)).map((o)=>this.fromGoDaddyRecord(o,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 b="https://api.cloudflare.com/client/v4",w="[ts-cloud]";class qe{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 n=`${b}${t}`,s={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},o={method:e,headers:s};if(r)o.body=JSON.stringify(r);let a=await(await fetch(n,o)).json();if(!a.success){let c=a.errors.map((d)=>d.message).join(", ");throw Error(`Cloudflare API error: ${c}`)}return a}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 i=await this.resolveConfiguredZoneName();if(i&&(t===i||t.endsWith(`.${i}`)))return{id:this.configuredZoneId,name:i}}let r=this.getRootDomain(t),n=this.zoneCache.get(r);if(n)return{id:n,name:r};let s=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!s.result||s.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 o=s.result[0].id;return this.zoneCache.set(r,o),{id:o,name:s.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 n={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},s=r??e.proxied;if(s!==void 0&&D.has(e.type)){if(n.proxied=s,s)n.ttl=1}if(e.type==="MX"&&e.priority!==void 0)n.priority=e.priority;if(e.type==="SRV"){let o=I(e);if(o)n.data=o,delete n.content,delete n.priority;else if(e.priority!==void 0)n.priority=e.priority}return n}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),n=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,n)).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),n=this.getFullRecordName(t.name,r.name),o=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(n)}`)).result?.[0],i=t.proxied??o?.proxied,a=this.toCloudflareRecord(t,r.name,i);if(o)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${o.id}`,a)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,a)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),n=r.id,s=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`);if(!o.result||o.result.length===0)return{success:!1,message:"Record not found"};let i=o.result.find((a)=>a.content===t.content);if(!i)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${n}/dns_records/${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 n=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)n+=`&type=${t}`;let s=[],o=1,i=!0;while(i){let a=await this.request("GET",`${n}&page=${o}`);if(s.push(...a.result||[]),a.result_info)i=o<a.result_info.total_pages,o++;else i=!1}return{success:!0,records:s.map((a)=>this.fromCloudflareRecord(a))}}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 n=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...n.result||[]),n.result_info)r=t<n.result_info.total_pages,t++;else r=!1}return e.map((n)=>n.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),n=t.accountId??this.accountId;if(!n)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let s=await this.getZoneDetails(r);if(s)return{...s,created:!1};try{let i=(await this.request("POST","/zones",{name:r,account:{id:n},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(i.name,i.id),{id:i.id,name:i.name,status:i.status,nameServers:i.name_servers??[],created:!0}}catch(o){let i=o instanceof Error?o.message:String(o);if(!/already exists|1061/i.test(i))throw o;let a=await this.getZoneDetails(r);if(!a)throw o;return{...a,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`),n=new Set;for(let s of r.result||[]){if(s.status!=="active")continue;for(let o of s.hosts||[])n.add(o.toLowerCase())}return[...n]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),n={};if(t?.purgeEverything)n.purge_everything=!0;else{if(t?.files)n.files=t.files;if(t?.tags)n.tags=t.tags;if(t?.hosts)n.hosts=t.hosts}if(Object.keys(n).length===0)n.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,n),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),n=r.id,s=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`);if(o.result&&o.result.length>0)return o.result.find((a)=>a.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let n=await this.resolveZone(e),s=n.id,o=this.getFullRecordName(t.name,n.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!i.result||i.result.length===0)return!1;let a=i.result.find((c)=>c.content===t.content);if(!a)return!1;return await this.request("PATCH",`/zones/${s}/dns_records/${a.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`),n={};for(let s of r.result||[])n[s.id]=s.value;return n}async applyZoneSettings(e,t){let r=await this.getZoneId(e),n=await this.getZoneSettings(e).catch(()=>({})),s=[],o=[];for(let[i,a]of Object.entries(t)){if(a===void 0)continue;let c=n[i];if(c!==void 0&&A(c,a))continue;try{await this.request("PATCH",`/zones/${r}/settings/${i}`,{value:a}),s.push({id:i,from:c,to:a})}catch(d){o.push({id:i,error:d instanceof Error?d.message:String(d)})}}return{changed:s,failed:o}}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 n=await this.getZoneId(e),o=(await this.getPhaseRules(e,t)).filter((c)=>!(c.description||"").startsWith(w)),i=r.map((c)=>({...c,description:c.description?.startsWith(w)?c.description:`${w} ${c.description||t}`})),a=[...o,...i].map(({id:c,...d})=>d);return await this.request("PUT",`/zones/${n}/rulesets/phases/${t}/entrypoint`,{rules:a}),{success:!0}}catch(n){return{success:!1,message:n instanceof Error?n.message:String(n)}}}}function A(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((s,o)=>A(s,t[o]))}let r=e,n=t;return Object.keys(n).every((s)=>A(r[s],n[s]))}function I(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:N(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[n,s,o]=r.slice(0,3).map(Number);if(![n,s,o].every(Number.isFinite))return null;return{priority:n,weight:s,port:o,target:N(r.slice(3).join(" "))}}function N(e){return e.replace(/\.$/,"")}var E=new Set(["A","AAAA","CNAME","ALIAS"]);function h(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 f(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function R(e){return e.replace(/\.$/,"").toLowerCase()}function S(e,t){let r=R(t),n=(e??"@").trim();if(!n||n==="@")return r;let s=R(n);if(s===r||s.endsWith(`.${r}`))return s;return`${s}.${r}`}function Oi(e,t){return e.map((r)=>({...r,name:S(r.name,t),proxied:r.proxied??!1}))}function x(e,t){if(e.type!==t.type)return!1;if(R(e.name)!==R(t.name))return!1;if(E.has(t.type))return!0;if(t.type==="TXT"){let r=h(t.content);if(r)return h(f(e.content))===r;return f(e.content)===f(t.content)}return f(e.content)===f(t.content)}function k(e,t){if(f(e.content)!==f(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 Li(e){let{provider:t,zone:r,records:n}=e,s={outcomes:[],warnings:[]};if(n.length===0)return s;let o=await t.listRecords(r);if(!o.success)return s.warnings.push(`could not list ${r}: ${o.message||"unknown provider error"} — records not reconciled`),s;let i=o.records;for(let a of n){let c=i.filter((l)=>x(l,a));if(c.length>0&&c.every((l)=>k(l,a))){s.outcomes.push({record:a,action:"unchanged"});continue}let d={name:a.name,type:a.type,content:a.content,ttl:a.ttl??3600,...a.priority!==void 0?{priority:a.priority}:{},...a.proxied!==void 0?{proxied:a.proxied}:{}},m=a.type==="TXT"&&h(a.content)!==void 0;if(m)for(let l of c){let C=await t.deleteRecord(r,{name:l.name,type:l.type,content:l.content});if(!C.success)s.warnings.push(`could not remove superseded ${l.type} at ${l.name}: ${C.message||"unknown error"}`)}let p=m||c.length===0?await t.createRecord(r,d):await t.upsertRecord(r,d);if(p.success)s.outcomes.push({record:a,action:c.length>0?"updated":"created"});else s.outcomes.push({record:a,action:"failed",message:p.message})}for(let a of["MX"]){let c=new Set(n.filter((d)=>d.type===a).map((d)=>R(d.name)));for(let d of c){let m=new Set(n.filter((l)=>l.type===a&&R(l.name)===d).map((l)=>f(l.content).toLowerCase())),p=i.filter((l)=>l.type===a&&R(l.name)===d&&!m.has(f(l.content).toLowerCase()));for(let l of p)s.warnings.push(`${d} has an undeclared ${a} record (${l.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return s}class jr{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new O(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 n=await this.client.findHostedZoneForDomain(e);if(n){let s=n.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,s),s}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(!n||n==="@")return`${r}.`;if(n===r||n.endsWith(`.${r}`))return`${n}.`;return`${n}.${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 n=this.normalizeName(e,t.name),s=t.content;if(t.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(t.type==="MX"&&t.priority!==void 0)s=`${t.priority} ${s}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:"CREATE",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:s}]}}]}})).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 n=this.normalizeName(e,t.name),s=t.content;if(t.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(t.type==="MX"&&t.priority!==void 0)s=`${t.priority} ${s}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:s}]}}]}})).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 n=this.normalizeName(e,t.name),s=t.content;if(t.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(t.type==="MX"&&t.priority!==void 0)s=`${t.priority} ${s}`;return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:s}]}}]}}),{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 n=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),s=[];for(let o of n.ResourceRecordSets){if(t&&o.Type!==t)continue;if(o.AliasTarget)continue;for(let i of o.ResourceRecords||[]){let a=i.Value,c;if(o.Type==="MX"){let d=a.split(" ");if(d.length>=2)c=Number.parseInt(d[0],10),a=d.slice(1).join(" ")}if(o.Type==="TXT"&&a.startsWith('"')&&a.endsWith('"'))a=a.slice(1,-1);s.push({name:o.Name.replace(/\.$/,""),type:o.Type,content:a,ttl:o.TTL,priority:c})}}return{success:!0,records:s}}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:O.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=O.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 Mi(e,t){let r=[],n,s;for(;;){let o=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:n,StartRecordType:s,MaxItems:"100"});if(r.push(...o.ResourceRecordSets),!o.IsTruncated)break;if(n=o.NextRecordName,s=o.NextRecordType,!n)break}return r}function g(e){return e.replace(/\.$/,"").toLowerCase()}function T(e){return e.replace(/\.$/,"")}function y(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${T(e.content)}`;return T(e.content)}function M(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function Ui(e,t){let r=g(t),n=[],s=[],o=[],i=new Set;for(let a of e){let c=g(a.Name),d=a.Type;if(d==="SOA"||d==="NS"&&c===r){s.push({name:c,type:d,reason:"owned by the destination provider"});continue}if(a.SetIdentifier){s.push({name:c,type:d,reason:`routing policy record (SetIdentifier=${a.SetIdentifier}) has no equivalent — recreate by hand`}),o.push(`${d} ${c} is part of a Route53 routing policy and was NOT migrated`);continue}if(a.AliasTarget){if(i.has(c))continue;i.add(c);let m=g(a.AliasTarget.DNSName);if(n.push({name:c,type:"CNAME",content:m,ttl:300,translatedFrom:`${d} ALIAS → ${m}`}),a.AliasTarget.EvaluateTargetHealth)o.push(`${c} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let m of a.ResourceRecords||[]){let p=z(c,d,m.Value,a.TTL);if("reason"in p){s.push({name:c,type:d,reason:p.reason}),o.push(`${d} ${c}: ${p.reason}`);continue}n.push(p)}}return{zone:r,records:n,skipped:s,warnings:o}}function z(e,t,r,n){let s={name:e,ttl:n};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...s,type:t==="PTR"?"CNAME":t,content:g(r)};case"TXT":return{...s,type:"TXT",content:M(r)};case"MX":{let[o,...i]=r.trim().split(/\s+/);if(!i.length)return{reason:`malformed MX value "${r}"`};return{...s,type:"MX",content:g(i.join(" ")),priority:Number(o)}}case"SRV":{let o=r.trim().split(/\s+/);if(o.length<4)return{reason:`malformed SRV value "${r}"`};let[i,a,c]=o.slice(0,3).map(Number);return{...s,type:"SRV",content:g(o.slice(3).join(" ")),priority:i,weight:a,port:c}}case"NS":return{...s,type:"NS",content:g(r)};case"CAA":return{...s,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var U=new Set(["TXT","MX","SRV","NS","CAA"]);async function Bi(e,t){let r=[],n=[],s=new Set;try{let o=await e.listRecords(t.zone);for(let i of o.records||[])s.add(`${g(i.name)}|${i.type}|${y(i)}`)}catch{}for(let o of t.records){let i={...o,proxied:!1},a=`${g(o.name)}|${o.type}|${y(o)}`;if(!U.has(o.type)){let d=await e.upsertRecord(t.zone,i);if(d.success)r.push(o);else n.push({record:o,message:d.message||"unknown provider error"});continue}if(s.has(a)){r.push(o);continue}let c=await e.createRecord(t.zone,i);if(c.success)s.add(a),r.push(o);else n.push({record:o,message:c.message||"unknown provider error"})}return{applied:r,failed:n}}async function Fi(e,t){let r=await e.listRecords(t.zone),n=[],s=[],o=new Map;for(let i of r.records||[]){let a=`${g(i.name)}|${i.type}`,c=o.get(a)??[];c.push(y(i)),o.set(a,c)}for(let i of t.records){let a=o.get(`${g(i.name)}|${i.type}`),c=y(i);if(a?.some((d)=>d===c))n.push(i);else s.push({record:i,found:a?.join(", ")})}return{matched:n,missing:s,ok:s.length===0}}class _t{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new q(t),"provider"in e)this.dnsProvider=L(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!1,maxWaitMinutes:s=30}=e,{CertificateArn:o}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(o);let i=await this.acm.getDnsValidationRecords(o);for(let c of i){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}let a="pending";if(n)a=(await this.acm.waitForCertificateValidation(o,s*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:o,validationRecords:i.map((c)=>({domainName:c.domainName,recordName:c.recordName,recordType:c.recordType,recordValue:c.recordValue})),isNew:!0,status:a}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],s=await this.acm.getDnsValidationRecords(t);for(let o of s){let i=await this.dnsProvider.upsertRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue,ttl:300});if(!i.success)n.push(`Failed to create record for ${o.domainName}: ${i.message}`)}return{success:n.length===0,records:s.map((o)=>({domainName:o.domainName,recordName:o.recordName,recordType:o.recordType,recordValue:o.recordValue})),errors:n}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],s=await this.acm.getDnsValidationRecords(t);for(let o of s){let i=await this.dnsProvider.deleteRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue});if(!i.success)n.push(`Failed to delete record for ${o.domainName}: ${i.message}`)}return{success:n.length===0,errors:n}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!0,maxWaitMinutes:s}=e,o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED"){let i=o.SubjectAlternativeNames||[o.DomainName],a=i.some((d)=>d===`*.${t}`);if(r.every((d)=>i.includes(d)||a))return{certificateArn:o.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:n,maxWaitMinutes:s})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:n=!1,additionalSans:s=[],waitForValidation:o=!1}=e,i=[];if(r)i.push(`www.${t}`);if(n)i.push(`*.${t}`);return i.push(...s),this.requestAndValidate({domainName:t,subjectAlternativeNames:i,waitForValidation:o})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((s)=>setTimeout(s,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 L(e){switch(e.provider){case"route53":return new jr(e.region,e.hostedZoneId);case"porkbun":return new ze(e.apiKey,e.secretKey);case"godaddy":return new xt(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new qe(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}class Xn{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,n=process.env.GODADDY_API_SECRET;if(r&&n){let o=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,n,o)}let s=process.env.CLOUDFLARE_API_TOKEN;if(s)this.addCloudflare(s,{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((s)=>s.provider===e);if(!r)return null;let n=L(r);return this.providers.set(e,n),n}async getProviderForDomain(e){for(let t of this.configs){let r=L(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>L(e))}}var ye=new Xn;class q{client;region;constructor(e="us-east-1"){this.client=new u,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((n)=>({DomainName:n.DomainName,ValidationDomain:n.ValidationDomain,ValidationStatus:n.ValidationStatus,ResourceRecord:n.ResourceRecord?{Name:n.ResourceRecord.Name,Type:n.ResourceRecord.Type,Value:n.ResourceRecord.Value}:void 0,ValidationMethod:n.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((n)=>({CertificateArn:n.CertificateArn,DomainName:n.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((n)=>n.DomainName===e||n.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 n=0;n<t;n++){let s=await this.describeCertificate({CertificateArn:e});if(s.Status==="ISSUED")return s;if(s.Status==="FAILED"||s.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((o)=>setTimeout(o,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 n=r.DomainName.slice(2),s=t.split("."),o=n.split(".");if(s.slice(-o.length).join(".")===n)return!0}if(r.SubjectAlternativeNames)for(let n of r.SubjectAlternativeNames){if(n===t)return!0;if(n.startsWith("*.")){let s=n.slice(2),o=t.split("."),i=s.split(".");if(o.slice(-i.length).join(".")===s)return!0}}return!1}}class ji{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new q(e),this.route53=new O,t&&t.provider!=="route53")this.dnsProvider=L(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n=[],waitForValidation:s=!1,maxWaitMinutes:o=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:n.length>0?[t,...n]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);if(this.dnsProvider)for(let c of a){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}else if(r)for(let c of a)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${c.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:c.recordName,Type:c.recordType,TTL:300,ResourceRecords:[{Value:c.recordValue}]}}]}});if(s){if(!await this.acm.waitForCertificateValidation(i,o*2,30000))throw Error(`Certificate validation timed out after ${o} minutes`)}return{certificateArn:i,validationRecords:a}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((s)=>setTimeout(s,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let s=await this.acm.getDnsValidationRecords(t),o=[];if(this.dnsProvider){let i=n||s[0]?.domainName;for(let a of s){let c=await this.dnsProvider.upsertRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue,ttl:300});o.push({...a,changeId:c.success?c.id:void 0})}}else if(r)for(let i of s){let a=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${i.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}});o.push({...i,changeId:a.ChangeInfo?.Id})}return o}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e,s=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let o=n||s[0]?.domainName;for(let i of s)try{await this.dnsProvider.deleteRecord(o,{name:i.recordName,type:i.recordType,content:i.recordValue})}catch{}}else if(r)for(let o of s)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${o.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:o.recordName,Type:o.recordType,TTL:300,ResourceRecords:[{Value:o.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:s=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED")return{certificateArn:o.CertificateArn,isNew:!1};let{certificateArn:i}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:s});return{certificateArn:i,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}
2
+ export{ze,xt,qe,Oi,Li,jr,Mi,Ui,Bi,Fi,q,ji,_t,L,Xn};