@stacksjs/ts-cloud 0.16.14 → 0.16.16

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 (181) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-r7k2mkn7.js → chunk-0znhykt9.js} +5 -5
  3. package/dist/bin/{chunk-23nxkj19.js → chunk-1baj8p0r.js} +1 -1
  4. package/dist/bin/{chunk-9j7qhwe0.js → chunk-2943bszc.js} +1 -1
  5. package/dist/bin/chunk-2tn43y0d.js +1 -0
  6. package/dist/bin/{chunk-b7b87gxb.js → chunk-2v91xnqx.js} +2 -2
  7. package/dist/bin/{chunk-gwpmn3a3.js → chunk-2w591cvg.js} +1 -1
  8. package/dist/bin/{chunk-5jf6veax.js → chunk-3qfd0vnc.js} +3 -3
  9. package/dist/bin/{chunk-489c9r4g.js → chunk-3x4p2s2r.js} +3 -3
  10. package/dist/bin/chunk-4v6f496n.js +1 -0
  11. package/dist/bin/chunk-64cdtvar.js +1 -0
  12. package/dist/bin/chunk-66egshmp.js +1 -0
  13. package/dist/bin/chunk-7raskz63.js +1 -0
  14. package/dist/bin/{chunk-zm95j24a.js → chunk-80295akq.js} +3 -3
  15. package/dist/bin/{chunk-fjd8tw77.js → chunk-90c3rkd8.js} +4 -4
  16. package/dist/bin/chunk-9bxyy4th.js +1 -0
  17. package/dist/bin/{chunk-pm2vz6zp.js → chunk-b3yp7bak.js} +3 -3
  18. package/dist/bin/chunk-bbt0vyzj.js +1 -0
  19. package/dist/bin/{chunk-tb4ek3s5.js → chunk-bhay1f8a.js} +1 -1
  20. package/dist/bin/chunk-cpcae7e2.js +1 -0
  21. package/dist/bin/{chunk-cb47f0pb.js → chunk-cs6a98r1.js} +2 -2
  22. package/dist/bin/{chunk-3eht1tp2.js → chunk-dczw0nxw.js} +5 -5
  23. package/dist/bin/{chunk-3z65v87m.js → chunk-dp2fsnpe.js} +6 -6
  24. package/dist/bin/chunk-dsc7ef1w.js +1 -0
  25. package/dist/bin/{chunk-21am8b1b.js → chunk-edfh9ts2.js} +1 -1
  26. package/dist/bin/chunk-f2wn46nw.js +1 -0
  27. package/dist/bin/chunk-fddwwac7.js +1 -0
  28. package/dist/bin/chunk-ffcyj2jj.js +1 -0
  29. package/dist/bin/{chunk-2cyhks5n.js → chunk-fjz07v7g.js} +1 -1
  30. package/dist/bin/chunk-gbejgj71.js +1 -0
  31. package/dist/bin/{chunk-58phgtc8.js → chunk-grs2cwm7.js} +2 -2
  32. package/dist/bin/{chunk-p0vyt3fq.js → chunk-gv9deppc.js} +2 -2
  33. package/dist/bin/{chunk-5ffj7508.js → chunk-j0wfftk1.js} +1 -1
  34. package/dist/bin/{chunk-yas09vmt.js → chunk-j76935z3.js} +3 -3
  35. package/dist/bin/{chunk-0y4a84jm.js → chunk-khta83xb.js} +12 -12
  36. package/dist/bin/chunk-kjbkwzxd.js +1 -0
  37. package/dist/bin/chunk-knthwdhz.js +1 -0
  38. package/dist/bin/{chunk-31tmm8kx.js → chunk-m2kr333s.js} +2 -2
  39. package/dist/bin/chunk-m5wc1ent.js +1 -0
  40. package/dist/bin/{chunk-s4z1knq4.js → chunk-n02421y9.js} +1 -1
  41. package/dist/bin/{chunk-9bshng4v.js → chunk-nm000jpj.js} +81 -81
  42. package/dist/bin/{chunk-kft7wdhy.js → chunk-pd8tk3z5.js} +1 -1
  43. package/dist/bin/chunk-pjgbnk3q.js +1 -0
  44. package/dist/bin/chunk-rn0pgnt4.js +1 -0
  45. package/dist/bin/{chunk-hdr0q89a.js → chunk-tc24txss.js} +5 -5
  46. package/dist/bin/{chunk-nazx54p5.js → chunk-tfasfg4a.js} +2 -2
  47. package/dist/bin/{chunk-r0qynqff.js → chunk-tvv6vdx6.js} +5 -5
  48. package/dist/bin/chunk-v93xyx1p.js +1 -0
  49. package/dist/bin/chunk-vx9mmpaz.js +1 -0
  50. package/dist/bin/{chunk-me81g606.js → chunk-vx9qk1g1.js} +1 -1
  51. package/dist/bin/{chunk-0ed5yh3v.js → chunk-whww424p.js} +47 -47
  52. package/dist/bin/chunk-xtzy90zh.js +1 -0
  53. package/dist/bin/{chunk-4nbq68h4.js → chunk-xxf1vhfr.js} +1 -1
  54. package/dist/bin/{chunk-2a8twtvv.js → chunk-y4c26gaf.js} +1 -1
  55. package/dist/bin/{chunk-9gcmpcmq.js → chunk-yk4p2k8w.js} +1 -1
  56. package/dist/bin/chunk-z6mnhd0j.js +1 -0
  57. package/dist/bin/{chunk-4mpfdw94.js → chunk-zacbzz1w.js} +2 -2
  58. package/dist/bin/{chunk-3d8y4a6d.js → chunk-zzmk290g.js} +109 -109
  59. package/dist/bin/cli.js +150 -150
  60. package/dist/bin/dashboard-server.js +1 -1
  61. package/dist/chunk-051jwkd2.js +1 -0
  62. package/dist/{chunk-tgzp1h6j.js → chunk-0bbrbzf9.js} +4 -4
  63. package/dist/chunk-1gne7rkf.js +1 -0
  64. package/dist/chunk-38c310s1.js +1 -0
  65. package/dist/{chunk-80vxhxt5.js → chunk-4twnkjyq.js} +2 -2
  66. package/dist/{chunk-dns94gs7.js → chunk-4xta1s4z.js} +1 -1
  67. package/dist/{chunk-dxcwfj3h.js → chunk-6eq5xfcx.js} +1 -1
  68. package/dist/{chunk-g8tp1zj4.js → chunk-a21phhyj.js} +3 -3
  69. package/dist/{chunk-55cmjg49.js → chunk-a6aw2jtz.js} +6 -6
  70. package/dist/{chunk-bpvpq6w6.js → chunk-acpxtkfy.js} +90 -90
  71. package/dist/chunk-dk3t3hgq.js +1 -0
  72. package/dist/{chunk-21b8nage.js → chunk-emx1j2yt.js} +1 -1
  73. package/dist/{chunk-4yb7hf91.js → chunk-fdn4wnd8.js} +7 -7
  74. package/dist/{chunk-aesvajfc.js → chunk-fz70vxrk.js} +1 -1
  75. package/dist/{chunk-22ybphxa.js → chunk-g0yyw5k8.js} +1 -1
  76. package/dist/{chunk-pwpd6jt2.js → chunk-gn42mekr.js} +1 -1
  77. package/dist/{chunk-0hf0rdze.js → chunk-gstz8w2d.js} +2 -2
  78. package/dist/{chunk-mmdd5thg.js → chunk-jgv0x24e.js} +1 -1
  79. package/dist/{chunk-d72ddm5x.js → chunk-jncbm332.js} +130 -130
  80. package/dist/{chunk-9be2pb0b.js → chunk-pekptc1b.js} +5 -5
  81. package/dist/chunk-qc2v4h2q.js +1 -0
  82. package/dist/{chunk-kt6qnc6f.js → chunk-rgw06xbk.js} +4 -4
  83. package/dist/{chunk-7pk6cctr.js → chunk-rmn71xjb.js} +41 -41
  84. package/dist/{chunk-2jgx2s5y.js → chunk-sm5rn3db.js} +19 -19
  85. package/dist/{chunk-8a02v9gs.js → chunk-ss4q8kge.js} +2 -2
  86. package/dist/{chunk-s40cx3fh.js → chunk-v9t92ak2.js} +2 -2
  87. package/dist/{chunk-ffjc6gev.js → chunk-wdrqt329.js} +135 -135
  88. package/dist/{chunk-nw5yqgtn.js → chunk-whwg2nzb.js} +5 -5
  89. package/dist/{chunk-sw1p9qge.js → chunk-yxn6tpbg.js} +1 -1
  90. package/dist/{chunk-3bz7xz2d.js → chunk-z87dekhm.js} +1 -1
  91. package/dist/deploy/index.js +1 -1
  92. package/dist/dns/index.js +1 -1
  93. package/dist/drivers/index.js +1 -1
  94. package/dist/drivers/shared/cloudfront-origin.d.ts +15 -26
  95. package/dist/drivers/shared/deploy-script.d.ts +62 -29
  96. package/dist/index.js +39 -39
  97. package/dist/operations/index.js +1 -1
  98. package/dist/protection/index.js +1 -1
  99. package/dist/spend/index.js +1 -1
  100. package/dist/ui/404.html +1 -1
  101. package/dist/ui/accept-invitation.html +1 -1
  102. package/dist/ui/access-denied.html +1 -1
  103. package/dist/ui/account/automation.html +6 -6
  104. package/dist/ui/account/security.html +2 -2
  105. package/dist/ui/applications/compose.html +5 -5
  106. package/dist/ui/applications/new.html +2 -2
  107. package/dist/ui/data/backups.html +6 -6
  108. package/dist/ui/data/services.html +5 -5
  109. package/dist/ui/data/volumes.html +6 -6
  110. package/dist/ui/index.html +6 -6
  111. package/dist/ui/infrastructure/topology.html +6 -6
  112. package/dist/ui/integrations.html +1 -1
  113. package/dist/ui/operations/alerts.html +6 -6
  114. package/dist/ui/operations/configuration.html +6 -6
  115. package/dist/ui/operations/jobs.html +5 -5
  116. package/dist/ui/operations/maintenance.html +5 -5
  117. package/dist/ui/operations/observability.html +6 -6
  118. package/dist/ui/operations/previews.html +6 -6
  119. package/dist/ui/operations/queue.html +6 -6
  120. package/dist/ui/operations/regions.html +5 -5
  121. package/dist/ui/operations/releases.html +5 -5
  122. package/dist/ui/operations/spend.html +6 -6
  123. package/dist/ui/operations/workloads.html +6 -6
  124. package/dist/ui/security.html +1 -1
  125. package/dist/ui/server/actions.html +6 -6
  126. package/dist/ui/server/activity.html +2 -2
  127. package/dist/ui/server/capacity.html +6 -6
  128. package/dist/ui/server/database.html +6 -6
  129. package/dist/ui/server/deployments.html +5 -5
  130. package/dist/ui/server/diagnostics.html +2 -2
  131. package/dist/ui/server/firewall.html +5 -5
  132. package/dist/ui/server/fleet.html +6 -6
  133. package/dist/ui/server/logs.html +6 -6
  134. package/dist/ui/server/metrics.html +5 -5
  135. package/dist/ui/server/security.html +2 -2
  136. package/dist/ui/server/services.html +2 -2
  137. package/dist/ui/server/sites.html +6 -6
  138. package/dist/ui/server/ssh-keys.html +6 -6
  139. package/dist/ui/server/team.html +6 -6
  140. package/dist/ui/server/terminal.html +2 -2
  141. package/dist/ui/serverless/alarms.html +6 -6
  142. package/dist/ui/serverless/assets.html +1 -1
  143. package/dist/ui/serverless/cost.html +1 -1
  144. package/dist/ui/serverless/data.html +6 -6
  145. package/dist/ui/serverless/deployments.html +2 -2
  146. package/dist/ui/serverless/firewall.html +2 -2
  147. package/dist/ui/serverless/functions.html +6 -6
  148. package/dist/ui/serverless/logs.html +6 -6
  149. package/dist/ui/serverless/metrics.html +2 -2
  150. package/dist/ui/serverless/queues.html +5 -5
  151. package/dist/ui/serverless/secrets.html +6 -6
  152. package/dist/ui/serverless/traces.html +6 -6
  153. package/dist/ui/serverless.html +5 -5
  154. package/package.json +3 -3
  155. package/dist/bin/chunk-01tmdqe3.js +0 -1
  156. package/dist/bin/chunk-3bwy7atq.js +0 -1
  157. package/dist/bin/chunk-3rsvrp09.js +0 -1
  158. package/dist/bin/chunk-4gf4mk0b.js +0 -1
  159. package/dist/bin/chunk-5wms0mx3.js +0 -1
  160. package/dist/bin/chunk-c7sqa85j.js +0 -1
  161. package/dist/bin/chunk-cejjg0ts.js +0 -1
  162. package/dist/bin/chunk-e3hn6atg.js +0 -1
  163. package/dist/bin/chunk-e4gqzp7n.js +0 -1
  164. package/dist/bin/chunk-fbq61aj0.js +0 -1
  165. package/dist/bin/chunk-g4dytx12.js +0 -1
  166. package/dist/bin/chunk-hssaw82j.js +0 -1
  167. package/dist/bin/chunk-k4x1pq4t.js +0 -1
  168. package/dist/bin/chunk-kcvvpvte.js +0 -1
  169. package/dist/bin/chunk-n8a76gys.js +0 -1
  170. package/dist/bin/chunk-p1k08e45.js +0 -1
  171. package/dist/bin/chunk-ps8ev3tq.js +0 -1
  172. package/dist/bin/chunk-q8s9v9hv.js +0 -1
  173. package/dist/bin/chunk-qcvmyfp7.js +0 -1
  174. package/dist/bin/chunk-qncvqmzy.js +0 -1
  175. package/dist/bin/chunk-rt9nbrwd.js +0 -1
  176. package/dist/bin/chunk-xhwjntw1.js +0 -1
  177. package/dist/chunk-29xhksd3.js +0 -1
  178. package/dist/chunk-67wrhk75.js +0 -1
  179. package/dist/chunk-6n5wgv3d.js +0 -1
  180. package/dist/chunk-7nq2rwjs.js +0 -1
  181. package/dist/chunk-xdsaxgny.js +0 -1
@@ -1,22 +1,22 @@
1
- import{ot,Zn,ei,ti}from"./chunk-kt6qnc6f.js";function S(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mh(t,e="/var/www"){let n=`${e}/${t}-`;return["set -u",`for TS_CLOUD_DIR in ${n}*; do`,' [ -d "$TS_CLOUD_DIR" ] || continue',' [ -d "$TS_CLOUD_DIR/releases" ] || continue',` TS_CLOUD_SITE="\${TS_CLOUD_DIR#${n}}"`," TS_CLOUD_ACTIVE=no",` for TS_CLOUD_UNIT in $(ls /etc/systemd/system/ 2>/dev/null | grep -E "^${S(t)}-$TS_CLOUD_SITE[-@.]" || true); do`,' systemctl is-active "$TS_CLOUD_UNIT" >/dev/null 2>&1 && TS_CLOUD_ACTIVE=yes'," done",' TS_CLOUD_SIZE="$(du -sh "$TS_CLOUD_DIR" 2>/dev/null | cut -f1)"',' echo "site:$TS_CLOUD_SITE:$TS_CLOUD_ACTIVE:${TS_CLOUD_SIZE:-?}"',"done","exit 0"]}function hh(t){if(!t)return[];let e=[];for(let n of t.split(`
2
- `)){let r=n.trim();if(!r.startsWith("site:"))continue;let[,s,o,i]=r.split(":");if(!s||o!=="no")continue;e.push({name:s,size:i||"?"})}return e}function fh(t,e,n){let r=t.map((o)=>` ${e}-${o.name} (${o.size})`).join(`
1
+ import{ot,ei,ti,ri}from"./chunk-rgw06xbk.js";function S(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ch(t,e="/var/www"){let n=`${e}/${t}-`;return["set -u",`for TS_CLOUD_DIR in ${n}*; do`,' [ -d "$TS_CLOUD_DIR" ] || continue',' [ -d "$TS_CLOUD_DIR/releases" ] || continue',` TS_CLOUD_SITE="\${TS_CLOUD_DIR#${n}}"`," TS_CLOUD_ACTIVE=no",` for TS_CLOUD_UNIT in $(ls /etc/systemd/system/ 2>/dev/null | grep -E "^${S(t)}-$TS_CLOUD_SITE[-@.]" || true); do`,' systemctl is-active "$TS_CLOUD_UNIT" >/dev/null 2>&1 && TS_CLOUD_ACTIVE=yes'," done",' TS_CLOUD_SIZE="$(du -sh "$TS_CLOUD_DIR" 2>/dev/null | cut -f1)"',' echo "site:$TS_CLOUD_SITE:$TS_CLOUD_ACTIVE:${TS_CLOUD_SIZE:-?}"',"done","exit 0"]}function Eh(t){if(!t)return[];let e=[];for(let n of t.split(`
2
+ `)){let r=n.trim();if(!r.startsWith("site:"))continue;let[,s,o,i]=r.split(":");if(!s||o!=="no")continue;e.push({name:s,size:i||"?"})}return e}function bh(t,e,n){let r=t.map((o)=>` ${e}-${o.name} (${o.size})`).join(`
3
3
  `),s=t.length===1?"it":"them";return`This server still holds ${t.length} site tree${t.length===1?"":"s"} with nothing running for ${s}:
4
4
  ${r}
5
5
  `+"A site moved off this box keeps its files here on purpose — they are the rollback, and they are what makes "+`the move reversible until this server is destroyed. Destroying it now discards that.
6
- Verify the site is serving from its new home first, then re-run with ${n} to destroy it anyway.`}var Uu="ts-cloud/project",Qu="ts-cloud/environment",Hu="ts-cloud/role";function d(t){return typeof t==="string"&&t.trim()?t.trim():void 0}function h(t){if(typeof t==="string")return d(t);if(t&&typeof t==="object")return d(t.name);return}function Ah(t){let e={};for(let[n,r]of Object.entries(t?.labels??{}))if(typeof r==="string")e[n]=r;return{id:String(t?.id??""),name:d(t?.name)??"(unnamed)",status:d(t?.status)??"unknown",ipv4:d(t?.public_net?.ipv4?.ip)??d(t?.ipv4),ipv6:d(t?.public_net?.ipv6?.ip)??d(t?.ipv6),type:d(t?.server_type?.name)??d(t?.type),location:h(t?.location)??h(t?.datacenter?.location)??h(t?.datacenter),labels:e,project:d(e[Uu]),environment:d(e[Qu]),role:d(e[Hu])}}function w(t){return t.slug?.trim()||"app"}function Gu(t){let e=[];for(let n of t){let r=w(n);for(let s of n.proxies??[]){let o=d(s?.to);if(!o)continue;e.push({slug:r,host:o,path:d(s?.path)??"/",...x(s)})}}return e.sort((n,r)=>n.slug.localeCompare(r.slug)||n.host.localeCompare(r.host)||n.path.localeCompare(r.path))}function x(t){let e=t?.from;if(typeof e==="string"&&e.trim())return{target:e.trim(),kind:"app"};if(Array.isArray(e)&&e.length>0)return{target:e.filter((s)=>typeof s==="string").join(", "),kind:"app"};let n=t?.static;if(typeof n==="string"&&n.trim())return{target:n.trim(),kind:"static"};if(n&&typeof n==="object"&&d(n.dir))return{target:d(n.dir),kind:"static"};let r=typeof t?.redirect==="string"?d(t.redirect):d(t?.redirect?.to);if(r)return{target:r,kind:"redirect"};return{target:"(no upstream)",kind:"unknown"}}function qu(t){let e=new Map;for(let n of t){let r=e.get(n.slug);if(r)r.push(n);else e.set(n.slug,[n])}return[...e.entries()].map(([n,r])=>({slug:n,routes:r})).sort((n,r)=>r.routes.length-n.routes.length||n.slug.localeCompare(r.slug))}async function yh(t,e,n=ot){if(!t.ipv4)return{server:t.name,routes:[],unavailable:"no public IPv4 address to reach it on"};if(t.status!=="running")return{server:t.name,ip:t.ipv4,routes:[],unavailable:`server is ${t.status}`};try{let r=await e(t.ipv4,ei(n));if(r.code!==0){let s=r.stderr.trim().split(`
7
- `)[0]||`remote command exited ${r.code}`;return{server:t.name,ip:t.ipv4,routes:[],unavailable:s}}return{server:t.name,ip:t.ipv4,routes:Gu(ti(r.stdout))}}catch(r){let s=r instanceof Error?r.message.split(`
8
- `)[0]:String(r);return{server:t.name,ip:t.ipv4,routes:[],unavailable:s}}}function u(t,e){let n=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${n||"/"}`}function Ih(t,e,n){let r=new Set(e.filter((a)=>a.slug===n).map((a)=>u(a.host,a.path))),s=[],o=[],i=[];for(let a of t)if(a.loopbackOnly)i.push(a);else if(a.domain&&r.has(u(a.domain,a.path)))s.push(a);else o.push(a);return{present:s,absent:o,loopback:i,foreign:e.filter((a)=>a.slug!==n)}}function Vu(t,e,n){let r=new Set;for(let s of e)for(let o of s.routes)if(o.slug===n)r.add(u(o.host,o.path));return t.filter((s)=>!s.loopbackOnly&&s.domain!==void 0&&!r.has(u(s.domain,s.path)))}function Sh(t){let{slug:e,servers:n,probes:r,declared:s}=t,o=[];if(o.push(n.length===0?"No servers found.":`${n.length} server${n.length===1?"":"s"}:`),n.length>0)o.push("");let i=new Map(r.map((a)=>[a.server,a]));for(let a of n){let p=[a.ipv4,a.type,a.location,a.status].filter(Boolean);o.push(` ${a.name} ${p.join(" ")}`),o.push(` ${k(a)}`);let c=i.get(a.name);if(!c)o.push(" not probed, so co-tenants on this box are not listed");else if(c.unavailable)o.push(` could not read ${ot}: ${c.unavailable}`);else o.push(...P(c,e));o.push("")}return o.push(...C(t)),o}function k(t){if(!t.project)return"no ts-cloud labels: provisioned outside ts-cloud, or by a version that did not label boxes";let e=[t.environment,t.role&&`role ${t.role}`].filter(Boolean).join(", ");return`owned by '${t.project}'${e?` (${e})`:""}`}function P(t,e){let n=qu(t.routes);if(n.length===0)return[` serves nothing: ${ot} is empty or absent`];let r=[` serves ${t.routes.length} route${t.routes.length===1?"":"s"} for ${n.length} project${n.length===1?"":"s"}:`];for(let s of n){r.push(` ${s.slug}${s.slug===e?" (this project)":""}`);for(let o of s.routes)r.push(` ${o.host}${o.path==="/"?"/":o.path} -> ${O(o)}`)}return r}function O(t){if(t.kind==="redirect")return`redirect to ${t.target}`;if(t.kind==="static")return`static ${t.target}`;return t.target}function C(t){let{slug:e,declared:n,probes:r,servers:s}=t;if(n.length===0)return[`This project ('${e}') declares no sites.`];let o=[`This project ('${e}') declares ${n.length} site${n.length===1?"":"s"}: `+n.map((c)=>c.name).join(", ")],i=n.filter((c)=>c.loopbackOnly);if(i.length>0)o.push(` ${i.length} with no domain, so the gateway never routes ${i.length===1?"it":"them"} (reached through another site's proxy): ${i.map((c)=>c.name).join(", ")}`);let a=r.filter((c)=>!c.unavailable);if(a.length===0)return o.push(" Nothing to reconcile them against: no box reported what it serves."),o;let p=Vu(n,a,e);if(o.push(` ${n.length-i.length-p.length} routed by a box above`),p.length>0){o.push(` ${p.length} not routed by any box above: ${p.map((b)=>b.name).join(", ")}`);let c=r.length-a.length,g=s.length-r.length;if(c>0)o.push(` Either they were never deployed, or they are on one of the ${c} server${c===1?"":"s"} that could not be read.`);else if(g>0)o.push(` Either they were never deployed, or they are on one of the ${g} server${g===1?"":"s"} this run did not probe.`);else o.push(" Either they were never deployed, or they are on a server this listing did not cover.")}return o}async function Ch(t){let e=[];for(let n of t.steps)try{e.push({step:n,state:await n.satisfied()?"satisfied":"pending"})}catch(r){e.push({step:n,state:"unknown",reason:r instanceof Error?r.message:String(r)})}return e}function yc(t){return t.filter((e)=>e.state!=="satisfied")}function ju(t){return yc(t).some((e)=>e.step.destructive===!0)}function bh(t,e){let n=yc(e),r=[`${t.operation} ${t.target}`];if(n.length===0)return r.push(" Nothing to do — every step is already satisfied."),r;for(let{step:o,state:i,reason:a}of e){let p=i==="satisfied"?"ok ":i==="unknown"?"? ":"→ ",c=[o.destructive?"DESTRUCTIVE":"",i==="satisfied"?"already done":""].filter(Boolean);if(r.push(` ${p}${o.title}${c.length>0?` [${c.join(", ")}]`:""}`),o.change)r.push(` ${o.change.from} → ${o.change.to}`);if(a)r.push(` could not check: ${a}`)}let s=n.filter((o)=>o.step.destructive).length;return r.push(` ${n.length} step(s) would run`+(s>0?`, ${s} irreversible — re-run with --confirm ${t.target}`:"")),r}async function Eh(t,e,n={}){let r={operation:t.operation,target:t.target,steps:[],success:!0};if(ju(e)&&n.confirm!==t.target)throw Error(`${t.operation} includes an irreversible step. Re-run with --confirm ${t.target} to authorize it.`);for(let{step:s,state:o}of e){if(o==="satisfied"){r.steps.push({id:s.id,title:s.title,state:"skipped"}),n.log?.(`skip ${s.title} (already done)`);continue}n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"started"});try{await s.apply(),r.steps.push({id:s.id,title:s.title,state:"applied"}),n.log?.(`done ${s.title}`),n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"applied"})}catch(i){let a=i instanceof Error?i.message:String(i);return r.steps.push({id:s.id,title:s.title,state:"failed",error:a}),r.success=!1,n.log?.(`FAIL ${s.title}: ${a}`),n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"failed",error:a}),r}}return r}function zu(t){if(t.length===0)throw Error("A server name cannot be empty.");if(t.length>253)throw Error(`'${t}' is longer than the 253 characters a hostname allows.`);for(let e of t.split(".")){if(e.length===0)throw Error(`'${t}' has an empty label — a hostname cannot contain '..'.`);if(e.length>63)throw Error(`'${e}' is longer than the 63 characters a hostname label allows.`);if(!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(e))throw Error(`'${e}' is not a valid hostname label. Use letters, digits and hyphens, not starting or ending with a hyphen.`)}}async function vh(t,e,n){if(zu(e),t===e)throw Error(`'${t}' is already named that.`);if((await n.takenNames()).some((o)=>o===e&&o!==t))throw Error(`'${e}' is already taken. Server names have to be unique within a provider project.`);let s=[];if(n.providerName&&n.renameProvider){let{providerName:o,renameProvider:i}=n;s.push({id:"provider",title:"Rename the server at the provider",change:{from:t,to:e},satisfied:async()=>await o()===e,apply:()=>i(e)})}if(n.stateName&&n.writeStateName){let{stateName:o,writeStateName:i}=n;s.push({id:"state-pin",title:"Update the recorded name in the local driver state",change:{from:t,to:e},satisfied:async()=>{let a=await o();return a===void 0||a===e},apply:()=>i(e)})}if(n.remoteHostname&&n.setRemoteHostname){let{remoteHostname:o,setRemoteHostname:i}=n;s.push({id:"hostname",title:"Set the hostname on the box",change:{from:t,to:e},satisfied:async()=>await o()===e,apply:()=>i(e)})}return s.push({id:"inventory",title:"Rename the fleet inventory record",change:{from:t,to:e},satisfied:async()=>n.inventoryName()===e,apply:async()=>{await n.renameInventory(e)}}),{operation:"server:rename",target:t,steps:s}}function Th(t){let e=`'${t.replace(/'/g,`'"'"'`)}'`;return["set -eu",'TS_CLOUD_OLD="$(hostname)"',`hostnamectl set-hostname ${e} 2>/dev/null || { echo ${e} > /etc/hostname && hostname ${e}; }`,'if grep -q "^127.0.1.1" /etc/hosts; then',` TS_CLOUD_HOSTS="$(sed -E "s/^127\\.0\\.1\\.1.*/127.0.1.1\\t${t}/" /etc/hosts)"`,` printf '%s\\n' "$TS_CLOUD_HOSTS" > /etc/hosts`,"else",` printf '127.0.1.1\\t%s\\n' ${e} >> /etc/hosts`,"fi",'printf "%s -> %s\\n" "$TS_CLOUD_OLD" "$(hostname)"'].join(`
9
- `)}function wh(t,e,n){let r=e.trim();if(!r)return{problem:"No server named."};let[s,...o]=t.filter((c)=>c.name===r);if(s&&o.length===0)return{server:s};let i=t.filter((c)=>c.project===r);if(i.length>1&&n)i=i.filter((c)=>!c.environment||c.environment===n);let[a,...p]=i;if(a&&p.length===0)return{server:a};if(i.length>1)return{problem:`'${r}' owns ${i.length} servers (${i.map((c)=>c.name).join(", ")}). Name one of them, or narrow it by environment.`};return{problem:`No server matched '${r}'. Nothing is named that, and no box carries the label ts-cloud/project=${r}.`}}function Rh(t,e){let n=[];if(!e.project)n.push(`'${e.name}' carries no ts-cloud/project label, so it is not a box ts-cloud provisioned. Attaching to it would deploy into a host nothing manages.`);else if(e.project===t)n.push(`This project's slug is '${t}', which is also the slug that owns '${e.name}'. A tenant deploy owns the gateway fragment named after its slug, so attaching would overwrite '${e.project}'s own fragment and take its sites down. Change this project's slug first.`);if(e.status!=="running")n.push(`'${e.name}' is ${e.status}, so what it serves could not be read.`);if(!e.ipv4)n.push(`'${e.name}' has no public IPv4 address, so it cannot be reached to check what it serves.`);return n}function f(t,e){let n=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${n||"/"}`}function Dh(t,e,n){let r=[],s=Zn(n.filter((i)=>i.kind==="app").map((i)=>({slug:i.slug,proxies:[{from:i.target.split(",").map((a)=>a.trim())}]})),{ignoreSlug:t}),o=new Map;for(let i of n)if(i.slug!==t)o.set(f(i.host,i.path),i.slug);for(let i of e){if(i.port!==void 0){let a=s.get(i.port);if(a)r.push({kind:"port",site:i.name,detail:`port ${i.port}`,heldBy:a})}if(i.domain){let a=o.get(f(i.domain,i.path));if(a)r.push({kind:"route",site:i.name,detail:`${i.domain}${i.path==="/"?"/":i.path}`,heldBy:a})}}return r}function Ph(t){return t.registryRead&&t.conflicts.length===0}function Nh(t){let{slug:e,owner:n,server:r,declared:s,conflicts:o}=t,i=[];i.push(`Attach '${e}' to '${r.name}' (${r.ipv4??"no IPv4"}), owned by '${n}'.`,""),i.push(` ${s.length} site${s.length===1?"":"s"} would deploy onto this box:`);for(let a of s){let p=a.loopbackOnly?`loopback only${a.port?` on :${a.port}`:""}`:`${a.domain}${a.path==="/"?"/":a.path}${a.port?` on :${a.port}`:""}`;i.push(` ${a.name} ${p} -> ${a.installBase??"(install path unresolved)"}`)}if(i.push(""),!t.registryRead)i.push(` Could not read what '${r.name}' already serves: ${t.registryProblem??"unknown reason"}`),i.push(" So this attach is UNCHECKED: a port or hostname already taken by another"),i.push(" project would not error, it would serve that project's site from your domain.");else if(o.length>0){i.push(` ${o.length} conflict${o.length===1?"":"s"} with what the box already serves:`);for(let a of o)i.push(` site '${a.site}' wants ${a.detail}, held by '${a.heldBy}'`);i.push(""),i.push(" Two services on one port do not error: the kernel load-balances, and each"),i.push(" domain serves the other's site about half the time. Pick free ports and"),i.push(" hostnames, then re-run.")}else i.push(` No conflicts with what '${r.name}' already serves.`);return i}function Yn(t,e){return`/tmp/ts-cloud-move-${t}-${e}.tar.gz`}function Ic(t,e){return`${t}-${e}*.service`}function l(t){return`'${t.split("'").join("'\\''")}'`}function Ku(t,e){return["set -eu",`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(m(t,e))} || true); do`,' systemctl stop "$unit" 2>/dev/null || true',"done"].join(`
10
- `)}function m(t,e){return`^${t}-${e}-((queue|daemon)-.*|scheduler)\\.service$`}function Wu(t,e){return y(m(t,e))}function y(t){return[`ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(t)} | while read -r unit; do`,' systemctl is-active "$unit" >/dev/null 2>&1 && echo "active:$unit" || true',"done"].join(`
11
- `)}function Ju(t){return!t.split(`
12
- `).some((e)=>e.trim().startsWith("active:"))}function Xu(t,e,n){let r=Yn(t,e);return["set -eu",`test -d ${l(n)} || { echo "no site tree at ${n}" >&2; exit 1; }`,`rm -f ${l(r)}`,`tar czf ${l(r)} -C "$(dirname ${l(n)})" "$(basename ${l(n)})" -C /etc/systemd/system $(cd /etc/systemd/system && ls ${Ic(t,e)} 2>/dev/null | tr '\\n' ' ')`,`sha256sum ${l(r)} | cut -d' ' -f1`].join(`
13
- `)}function Yu(t,e,n){let r=Yn(t,e);return["set -eu",`test -f ${l(r)} || { echo "archive not staged at ${r}" >&2; exit 1; }`,`mkdir -p "$(dirname ${l(n)})"`,`tar xzf ${l(r)} -C "$(dirname ${l(n)})" "$(basename ${l(n)})"`,`tar xzf ${l(r)} -C /etc/systemd/system --wildcards ${l(Ic(t,e))} 2>/dev/null || true`,"systemctl daemon-reload",`systemctl enable ${t}-${e}.service 2>/dev/null || true`,`systemctl restart ${t}-${e}.service`,`rm -f ${l(r)}`].join(`
14
- `)}function Zu(t,e,n){return[`test -d ${l(n)} && echo tree:present || echo tree:absent`,`systemctl is-active ${t}-${e}.service >/dev/null 2>&1 && echo unit:active || echo unit:inactive`].join(`
15
- `)}function ep(t){return t.includes("tree:present")&&t.includes("unit:active")}function tp(t,e="/",n=10){let r=`http://127.0.0.1:${t}${e.startsWith("/")?e:`/${e}`}`;return["set -eu",`for i in $(seq 1 ${n}); do`,` if curl -fsS -o /dev/null --max-time 5 ${l(r)}; then echo healthy; exit 0; fi`," sleep 3","done",`echo "no healthy response from ${r}" >&2`,"exit 1"].join(`
16
- `)}function rp(t,e){return["set -eu",`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(v(t,e))} || true); do`,' systemctl disable --now "$unit" 2>/dev/null || true',"done",`rm -f /etc/rpx/sites.d/${t}.json 2>/dev/null || true`,"systemctl reload rpx-gateway.service 2>/dev/null || systemctl restart rpx-gateway.service 2>/dev/null || true"].join(`
17
- `)}function v(t,e){return`^${t}-${e}[-@.]`}function np(t,e){return y(v(t,e))}function ip(t){return!t.split(`
18
- `).some((e)=>e.trim().startsWith("active:"))}function kh(t,e){return`/tmp/ts-cloud-move-${t}-${e}-certs.tar.gz`}function Bh(t,e){return["set -u",...e.map((n)=>`if [ -s ${l(`${t}/${n}.crt`)} ]; then echo "cert:${n}:$(sha256sum ${l(`${t}/${n}.crt`)} | cut -d' ' -f1)"; else echo "cert:${n}:absent"; fi`)].join(`
19
- `)}function xh(t){let e=new Map;for(let n of t.split(`
20
- `)){let r=n.trim();if(!r.startsWith("cert:"))continue;let[,s,o]=r.split(":");if(s&&o)e.set(s,o)}return e}function _h(t,e){for(let[n,r]of t){if(r==="absent")continue;if(e.get(n)!==r)return!1}return!0}function Oh(t,e,n){let r=e.flatMap((s)=>[`${s}.crt`,`${s}.key`]);return["set -eu",`rm -f ${l(n)}`,`cd ${l(t)} 2>/dev/null || { echo "no certs dir at ${t}" >&2; exit 0; }`,`TS_CLOUD_CERTS="$(ls ${r.map(l).join(" ")} 2>/dev/null | tr '\\n' ' ' || true)"`,'[ -n "$TS_CLOUD_CERTS" ] || { echo "no certificates to carry"; exit 0; }',`tar czf ${l(n)} $TS_CLOUD_CERTS`].join(`
21
- `)}function Lh(t,e){return["set -eu",`[ -s ${l(e)} ] || { echo "no certificate archive staged"; exit 0; }`,`mkdir -p ${l(t)}`,`tar xzf ${l(e)} -C ${l(t)}`,`chmod 600 ${l(t)}/*.key 2>/dev/null || true`,`rm -f ${l(e)}`].join(`
22
- `)}async function $h(t,e){let{slug:n,siteName:r,appBase:s,from:o,to:i,targetAddress:a}=t;if(o===i)throw Error(`'${r}' is already on ${i}.`);if(t.database&&!e.database)throw Error(`'${r}' uses the on-box database '${t.database.name}', which lives in the engine's own data directory rather than in the site tree, and this move has no way to carry it. Moving the site without it would cut traffic over to an empty database.`);if(t.database&&e.database&&await e.database.targetHasData())throw Error(`${i} already has a database named '${t.database.name}' with tables in it. Restoring this site's dump over it would destroy that data. Rename or drop it on the target first, or point this project at a different database name.`);let p=[{id:"pause-workers",title:`Stop background work on ${o} so the snapshot is consistent`,satisfied:async()=>Ju(await e.runOnSource(Wu(n,r))),apply:async()=>{await e.runOnSource(Ku(n,r))}},...e.database?[{id:"database-dump",title:`Dump the '${t.database?.name}' database on ${o}`,satisfied:async()=>!1,apply:()=>e.database.dump()}]:[],{id:"snapshot",title:`Archive the site's tree and units on ${o}`,change:{from:`${o}:${s}`,to:Yn(n,r)},satisfied:async()=>!1,apply:async()=>{await e.runOnSource(Xu(n,r,s))}},{id:"transfer",title:`Carry the archive to ${i}`,change:{from:o,to:i},satisfied:()=>e.archiveStaged(),apply:()=>e.transferArchive()},...e.database?[{id:"database-transfer",title:`Carry the database dump to ${i}`,change:{from:o,to:i},satisfied:()=>e.database.dumpStaged(),apply:()=>e.database.transferDump()},{id:"database-restore",title:`Create and load '${t.database?.name}' on ${i}`,satisfied:async()=>!1,apply:()=>e.database.restore()}]:[],{id:"restore",title:`Unpack the site on ${i} and start it`,change:{from:Yn(n,r),to:`${i}:${s}`},satisfied:async()=>ep(await e.runOnTarget(Zu(n,r,s))),apply:async()=>{await e.runOnTarget(Yu(n,r,s))}}];if(t.port!=null){let{port:c}=t;p.push({id:"health",title:`Wait for the site to answer on ${i} (127.0.0.1:${c})`,satisfied:async()=>!1,apply:async()=>{await e.runOnTarget(tp(c,t.healthCheckPath??"/"))}})}return p.push(...e.certificates?[{id:"certificates",title:`Carry the site's TLS material to ${i}`,satisfied:()=>e.certificates.inPlace(),apply:()=>e.certificates.carry()}]:[],{id:"gateway",title:`Route the site on ${i}`,satisfied:()=>e.targetRoutesSite(),apply:()=>e.refreshTargetGateway()},{id:"dns",title:`Point DNS at ${i}`,change:{from:`${o}`,to:a},satisfied:async()=>await e.publishedAddress()===a,apply:async()=>{let c=await e.cutoverDns();if(c.length>0)throw Error(c.join("; "))}},{id:"drain-source",title:`Stop the site on ${o}, leaving its files in place`,satisfied:async()=>ip(await e.runOnSource(np(n,r))),apply:async()=>{await e.runOnSource(rp(n,r))}}),{operation:"site:move",target:r,steps:p}}export{mh,hh,fh,Uu,Qu,Hu,Ah,Gu,qu,yh,Ih,Vu,Sh,Ch,yc,ju,bh,Eh,zu,vh,Th,wh,Rh,Dh,Ph,Nh,Yn,Ic,Ku,Wu,Ju,Xu,Yu,Zu,ep,tp,rp,np,ip,kh,Bh,xh,_h,Oh,Lh,$h};
6
+ Verify the site is serving from its new home first, then re-run with ${n} to destroy it anyway.`}var zu="ts-cloud/project",Ku="ts-cloud/environment",Wu="ts-cloud/role";function d(t){return typeof t==="string"&&t.trim()?t.trim():void 0}function h(t){if(typeof t==="string")return d(t);if(t&&typeof t==="object")return d(t.name);return}function vh(t){let e={};for(let[n,r]of Object.entries(t?.labels??{}))if(typeof r==="string")e[n]=r;return{id:String(t?.id??""),name:d(t?.name)??"(unnamed)",status:d(t?.status)??"unknown",ipv4:d(t?.public_net?.ipv4?.ip)??d(t?.ipv4),ipv6:d(t?.public_net?.ipv6?.ip)??d(t?.ipv6),type:d(t?.server_type?.name)??d(t?.type),location:h(t?.location)??h(t?.datacenter?.location)??h(t?.datacenter),labels:e,project:d(e[zu]),environment:d(e[Ku]),role:d(e[Wu])}}function w(t){return t.slug?.trim()||"app"}function Ju(t){let e=[];for(let n of t){let r=w(n);for(let s of n.proxies??[]){let o=d(s?.to);if(!o)continue;e.push({slug:r,host:o,path:d(s?.path)??"/",...x(s)})}}return e.sort((n,r)=>n.slug.localeCompare(r.slug)||n.host.localeCompare(r.host)||n.path.localeCompare(r.path))}function x(t){let e=t?.from;if(typeof e==="string"&&e.trim())return{target:e.trim(),kind:"app"};if(Array.isArray(e)&&e.length>0)return{target:e.filter((s)=>typeof s==="string").join(", "),kind:"app"};let n=t?.static;if(typeof n==="string"&&n.trim())return{target:n.trim(),kind:"static"};if(n&&typeof n==="object"&&d(n.dir))return{target:d(n.dir),kind:"static"};let r=typeof t?.redirect==="string"?d(t.redirect):d(t?.redirect?.to);if(r)return{target:r,kind:"redirect"};return{target:"(no upstream)",kind:"unknown"}}function Xu(t){let e=new Map;for(let n of t){let r=e.get(n.slug);if(r)r.push(n);else e.set(n.slug,[n])}return[...e.entries()].map(([n,r])=>({slug:n,routes:r})).sort((n,r)=>r.routes.length-n.routes.length||n.slug.localeCompare(r.slug))}async function Th(t,e,n=ot){if(!t.ipv4)return{server:t.name,routes:[],unavailable:"no public IPv4 address to reach it on"};if(t.status!=="running")return{server:t.name,ip:t.ipv4,routes:[],unavailable:`server is ${t.status}`};try{let r=await e(t.ipv4,ti(n));if(r.code!==0){let s=r.stderr.trim().split(`
7
+ `)[0]||`remote command exited ${r.code}`;return{server:t.name,ip:t.ipv4,routes:[],unavailable:s}}return{server:t.name,ip:t.ipv4,routes:Ju(ri(r.stdout))}}catch(r){let s=r instanceof Error?r.message.split(`
8
+ `)[0]:String(r);return{server:t.name,ip:t.ipv4,routes:[],unavailable:s}}}function u(t,e){let n=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${n||"/"}`}function wh(t,e,n){let r=new Set(e.filter((a)=>a.slug===n).map((a)=>u(a.host,a.path))),s=[],o=[],i=[];for(let a of t)if(a.loopbackOnly)i.push(a);else if(a.domain&&r.has(u(a.domain,a.path)))s.push(a);else o.push(a);return{present:s,absent:o,loopback:i,foreign:e.filter((a)=>a.slug!==n)}}function Yu(t,e,n){let r=new Set;for(let s of e)for(let o of s.routes)if(o.slug===n)r.add(u(o.host,o.path));return t.filter((s)=>!s.loopbackOnly&&s.domain!==void 0&&!r.has(u(s.domain,s.path)))}function Rh(t){let{slug:e,servers:n,probes:r,declared:s}=t,o=[];if(o.push(n.length===0?"No servers found.":`${n.length} server${n.length===1?"":"s"}:`),n.length>0)o.push("");let i=new Map(r.map((a)=>[a.server,a]));for(let a of n){let p=[a.ipv4,a.type,a.location,a.status].filter(Boolean);o.push(` ${a.name} ${p.join(" ")}`),o.push(` ${k(a)}`);let c=i.get(a.name);if(!c)o.push(" not probed, so co-tenants on this box are not listed");else if(c.unavailable)o.push(` could not read ${ot}: ${c.unavailable}`);else o.push(...P(c,e));o.push("")}return o.push(...C(t)),o}function k(t){if(!t.project)return"no ts-cloud labels: provisioned outside ts-cloud, or by a version that did not label boxes";let e=[t.environment,t.role&&`role ${t.role}`].filter(Boolean).join(", ");return`owned by '${t.project}'${e?` (${e})`:""}`}function P(t,e){let n=Xu(t.routes);if(n.length===0)return[` serves nothing: ${ot} is empty or absent`];let r=[` serves ${t.routes.length} route${t.routes.length===1?"":"s"} for ${n.length} project${n.length===1?"":"s"}:`];for(let s of n){r.push(` ${s.slug}${s.slug===e?" (this project)":""}`);for(let o of s.routes)r.push(` ${o.host}${o.path==="/"?"/":o.path} -> ${O(o)}`)}return r}function O(t){if(t.kind==="redirect")return`redirect to ${t.target}`;if(t.kind==="static")return`static ${t.target}`;return t.target}function C(t){let{slug:e,declared:n,probes:r,servers:s}=t;if(n.length===0)return[`This project ('${e}') declares no sites.`];let o=[`This project ('${e}') declares ${n.length} site${n.length===1?"":"s"}: `+n.map((c)=>c.name).join(", ")],i=n.filter((c)=>c.loopbackOnly);if(i.length>0)o.push(` ${i.length} with no domain, so the gateway never routes ${i.length===1?"it":"them"} (reached through another site's proxy): ${i.map((c)=>c.name).join(", ")}`);let a=r.filter((c)=>!c.unavailable);if(a.length===0)return o.push(" Nothing to reconcile them against: no box reported what it serves."),o;let p=Yu(n,a,e);if(o.push(` ${n.length-i.length-p.length} routed by a box above`),p.length>0){o.push(` ${p.length} not routed by any box above: ${p.map((b)=>b.name).join(", ")}`);let c=r.length-a.length,g=s.length-r.length;if(c>0)o.push(` Either they were never deployed, or they are on one of the ${c} server${c===1?"":"s"} that could not be read.`);else if(g>0)o.push(` Either they were never deployed, or they are on one of the ${g} server${g===1?"":"s"} this run did not probe.`);else o.push(" Either they were never deployed, or they are on a server this listing did not cover.")}return o}async function Dh(t){let e=[];for(let n of t.steps)try{e.push({step:n,state:await n.satisfied()?"satisfied":"pending"})}catch(r){e.push({step:n,state:"unknown",reason:r instanceof Error?r.message:String(r)})}return e}function Sc(t){return t.filter((e)=>e.state!=="satisfied")}function Zu(t){return Sc(t).some((e)=>e.step.destructive===!0)}function Ph(t,e){let n=Sc(e),r=[`${t.operation} ${t.target}`];if(n.length===0)return r.push(" Nothing to do — every step is already satisfied."),r;for(let{step:o,state:i,reason:a}of e){let p=i==="satisfied"?"ok ":i==="unknown"?"? ":"→ ",c=[o.destructive?"DESTRUCTIVE":"",i==="satisfied"?"already done":""].filter(Boolean);if(r.push(` ${p}${o.title}${c.length>0?` [${c.join(", ")}]`:""}`),o.change)r.push(` ${o.change.from} → ${o.change.to}`);if(a)r.push(` could not check: ${a}`)}let s=n.filter((o)=>o.step.destructive).length;return r.push(` ${n.length} step(s) would run`+(s>0?`, ${s} irreversible — re-run with --confirm ${t.target}`:"")),r}async function Nh(t,e,n={}){let r={operation:t.operation,target:t.target,steps:[],success:!0};if(Zu(e)&&n.confirm!==t.target)throw Error(`${t.operation} includes an irreversible step. Re-run with --confirm ${t.target} to authorize it.`);for(let{step:s,state:o}of e){if(o==="satisfied"){r.steps.push({id:s.id,title:s.title,state:"skipped"}),n.log?.(`skip ${s.title} (already done)`);continue}n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"started"});try{await s.apply(),r.steps.push({id:s.id,title:s.title,state:"applied"}),n.log?.(`done ${s.title}`),n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"applied"})}catch(i){let a=i instanceof Error?i.message:String(i);return r.steps.push({id:s.id,title:s.title,state:"failed",error:a}),r.success=!1,n.log?.(`FAIL ${s.title}: ${a}`),n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"failed",error:a}),r}}return r}function ep(t){if(t.length===0)throw Error("A server name cannot be empty.");if(t.length>253)throw Error(`'${t}' is longer than the 253 characters a hostname allows.`);for(let e of t.split(".")){if(e.length===0)throw Error(`'${t}' has an empty label — a hostname cannot contain '..'.`);if(e.length>63)throw Error(`'${e}' is longer than the 63 characters a hostname label allows.`);if(!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(e))throw Error(`'${e}' is not a valid hostname label. Use letters, digits and hyphens, not starting or ending with a hyphen.`)}}async function kh(t,e,n){if(ep(e),t===e)throw Error(`'${t}' is already named that.`);if((await n.takenNames()).some((o)=>o===e&&o!==t))throw Error(`'${e}' is already taken. Server names have to be unique within a provider project.`);let s=[];if(n.providerName&&n.renameProvider){let{providerName:o,renameProvider:i}=n;s.push({id:"provider",title:"Rename the server at the provider",change:{from:t,to:e},satisfied:async()=>await o()===e,apply:()=>i(e)})}if(n.stateName&&n.writeStateName){let{stateName:o,writeStateName:i}=n;s.push({id:"state-pin",title:"Update the recorded name in the local driver state",change:{from:t,to:e},satisfied:async()=>{let a=await o();return a===void 0||a===e},apply:()=>i(e)})}if(n.remoteHostname&&n.setRemoteHostname){let{remoteHostname:o,setRemoteHostname:i}=n;s.push({id:"hostname",title:"Set the hostname on the box",change:{from:t,to:e},satisfied:async()=>await o()===e,apply:()=>i(e)})}return s.push({id:"inventory",title:"Rename the fleet inventory record",change:{from:t,to:e},satisfied:async()=>n.inventoryName()===e,apply:async()=>{await n.renameInventory(e)}}),{operation:"server:rename",target:t,steps:s}}function Bh(t){let e=`'${t.replace(/'/g,`'"'"'`)}'`;return["set -eu",'TS_CLOUD_OLD="$(hostname)"',`hostnamectl set-hostname ${e} 2>/dev/null || { echo ${e} > /etc/hostname && hostname ${e}; }`,'if grep -q "^127.0.1.1" /etc/hosts; then',` TS_CLOUD_HOSTS="$(sed -E "s/^127\\.0\\.1\\.1.*/127.0.1.1\\t${t}/" /etc/hosts)"`,` printf '%s\\n' "$TS_CLOUD_HOSTS" > /etc/hosts`,"else",` printf '127.0.1.1\\t%s\\n' ${e} >> /etc/hosts`,"fi",'printf "%s -> %s\\n" "$TS_CLOUD_OLD" "$(hostname)"'].join(`
9
+ `)}function _h(t,e,n){let r=e.trim();if(!r)return{problem:"No server named."};let[s,...o]=t.filter((c)=>c.name===r);if(s&&o.length===0)return{server:s};let i=t.filter((c)=>c.project===r);if(i.length>1&&n)i=i.filter((c)=>!c.environment||c.environment===n);let[a,...p]=i;if(a&&p.length===0)return{server:a};if(i.length>1)return{problem:`'${r}' owns ${i.length} servers (${i.map((c)=>c.name).join(", ")}). Name one of them, or narrow it by environment.`};return{problem:`No server matched '${r}'. Nothing is named that, and no box carries the label ts-cloud/project=${r}.`}}function xh(t,e){let n=[];if(!e.project)n.push(`'${e.name}' carries no ts-cloud/project label, so it is not a box ts-cloud provisioned. Attaching to it would deploy into a host nothing manages.`);else if(e.project===t)n.push(`This project's slug is '${t}', which is also the slug that owns '${e.name}'. A tenant deploy owns the gateway fragment named after its slug, so attaching would overwrite '${e.project}'s own fragment and take its sites down. Change this project's slug first.`);if(e.status!=="running")n.push(`'${e.name}' is ${e.status}, so what it serves could not be read.`);if(!e.ipv4)n.push(`'${e.name}' has no public IPv4 address, so it cannot be reached to check what it serves.`);return n}function f(t,e){let n=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${n||"/"}`}function Oh(t,e,n){let r=[],s=ei(n.filter((i)=>i.kind==="app").map((i)=>({slug:i.slug,proxies:[{from:i.target.split(",").map((a)=>a.trim())}]})),{ignoreSlug:t}),o=new Map;for(let i of n)if(i.slug!==t)o.set(f(i.host,i.path),i.slug);for(let i of e){if(i.port!==void 0){let a=s.get(i.port);if(a)r.push({kind:"port",site:i.name,detail:`port ${i.port}`,heldBy:a})}if(i.domain){let a=o.get(f(i.domain,i.path));if(a)r.push({kind:"route",site:i.name,detail:`${i.domain}${i.path==="/"?"/":i.path}`,heldBy:a})}}return r}function Lh(t){return t.registryRead&&t.conflicts.length===0}function $h(t){let{slug:e,owner:n,server:r,declared:s,conflicts:o}=t,i=[];i.push(`Attach '${e}' to '${r.name}' (${r.ipv4??"no IPv4"}), owned by '${n}'.`,""),i.push(` ${s.length} site${s.length===1?"":"s"} would deploy onto this box:`);for(let a of s){let p=a.loopbackOnly?`loopback only${a.port?` on :${a.port}`:""}`:`${a.domain}${a.path==="/"?"/":a.path}${a.port?` on :${a.port}`:""}`;i.push(` ${a.name} ${p} -> ${a.installBase??"(install path unresolved)"}`)}if(i.push(""),!t.registryRead)i.push(` Could not read what '${r.name}' already serves: ${t.registryProblem??"unknown reason"}`),i.push(" So this attach is UNCHECKED: a port or hostname already taken by another"),i.push(" project would not error, it would serve that project's site from your domain.");else if(o.length>0){i.push(` ${o.length} conflict${o.length===1?"":"s"} with what the box already serves:`);for(let a of o)i.push(` site '${a.site}' wants ${a.detail}, held by '${a.heldBy}'`);i.push(""),i.push(" Two services on one port do not error: the kernel load-balances, and each"),i.push(" domain serves the other's site about half the time. Pick free ports and"),i.push(" hostnames, then re-run.")}else i.push(` No conflicts with what '${r.name}' already serves.`);return i}function Zn(t,e){return`/tmp/ts-cloud-move-${t}-${e}.tar.gz`}function Cc(t,e){return`${t}-${e}*.service`}function l(t){return`'${t.split("'").join("'\\''")}'`}function tp(t,e){return["set -eu",`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(m(t,e))} || true); do`,' systemctl stop "$unit" 2>/dev/null || true',"done"].join(`
10
+ `)}function m(t,e){return`^${t}-${e}-((queue|daemon)-.*|scheduler)\\.service$`}function rp(t,e){return y(m(t,e))}function y(t){return[`ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(t)} | while read -r unit; do`,' systemctl is-active "$unit" >/dev/null 2>&1 && echo "active:$unit" || true',"done"].join(`
11
+ `)}function np(t){return!t.split(`
12
+ `).some((e)=>e.trim().startsWith("active:"))}function ip(t,e,n){let r=Zn(t,e);return["set -eu",`test -d ${l(n)} || { echo "no site tree at ${n}" >&2; exit 1; }`,`rm -f ${l(r)}`,`tar czf ${l(r)} -C "$(dirname ${l(n)})" "$(basename ${l(n)})" -C /etc/systemd/system $(cd /etc/systemd/system && ls ${Cc(t,e)} 2>/dev/null | tr '\\n' ' ')`,`sha256sum ${l(r)} | cut -d' ' -f1`].join(`
13
+ `)}function sp(t,e,n){let r=Zn(t,e);return["set -eu",`test -f ${l(r)} || { echo "archive not staged at ${r}" >&2; exit 1; }`,`mkdir -p "$(dirname ${l(n)})"`,`tar xzf ${l(r)} -C "$(dirname ${l(n)})" "$(basename ${l(n)})"`,`tar xzf ${l(r)} -C /etc/systemd/system --wildcards ${l(Cc(t,e))} 2>/dev/null || true`,"systemctl daemon-reload",`systemctl enable ${t}-${e}.service 2>/dev/null || true`,`systemctl restart ${t}-${e}.service`,`rm -f ${l(r)}`].join(`
14
+ `)}function op(t,e,n){return[`test -d ${l(n)} && echo tree:present || echo tree:absent`,`systemctl is-active ${t}-${e}.service >/dev/null 2>&1 && echo unit:active || echo unit:inactive`].join(`
15
+ `)}function ap(t){return t.includes("tree:present")&&t.includes("unit:active")}function cp(t,e="/",n=10){let r=`http://127.0.0.1:${t}${e.startsWith("/")?e:`/${e}`}`;return["set -eu",`for i in $(seq 1 ${n}); do`,` if curl -fsS -o /dev/null --max-time 5 ${l(r)}; then echo healthy; exit 0; fi`," sleep 3","done",`echo "no healthy response from ${r}" >&2`,"exit 1"].join(`
16
+ `)}function dp(t,e){return["set -eu",`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(v(t,e))} || true); do`,' systemctl disable --now "$unit" 2>/dev/null || true',"done",`rm -f /etc/rpx/sites.d/${t}.json 2>/dev/null || true`,"systemctl reload rpx-gateway.service 2>/dev/null || systemctl restart rpx-gateway.service 2>/dev/null || true"].join(`
17
+ `)}function v(t,e){return`^${t}-${e}[-@.]`}function lp(t,e){return y(v(t,e))}function up(t){return!t.split(`
18
+ `).some((e)=>e.trim().startsWith("active:"))}function Mh(t,e){return`/tmp/ts-cloud-move-${t}-${e}-certs.tar.gz`}function Fh(t,e){return["set -u",...e.map((n)=>`if [ -s ${l(`${t}/${n}.crt`)} ]; then echo "cert:${n}:$(sha256sum ${l(`${t}/${n}.crt`)} | cut -d' ' -f1)"; else echo "cert:${n}:absent"; fi`)].join(`
19
+ `)}function Uh(t){let e=new Map;for(let n of t.split(`
20
+ `)){let r=n.trim();if(!r.startsWith("cert:"))continue;let[,s,o]=r.split(":");if(s&&o)e.set(s,o)}return e}function Qh(t,e){for(let[n,r]of t){if(r==="absent")continue;if(e.get(n)!==r)return!1}return!0}function Hh(t,e,n){let r=e.flatMap((s)=>[`${s}.crt`,`${s}.key`]);return["set -eu",`rm -f ${l(n)}`,`cd ${l(t)} 2>/dev/null || { echo "no certs dir at ${t}" >&2; exit 0; }`,`TS_CLOUD_CERTS="$(ls ${r.map(l).join(" ")} 2>/dev/null | tr '\\n' ' ' || true)"`,'[ -n "$TS_CLOUD_CERTS" ] || { echo "no certificates to carry"; exit 0; }',`tar czf ${l(n)} $TS_CLOUD_CERTS`].join(`
21
+ `)}function Gh(t,e){return["set -eu",`[ -s ${l(e)} ] || { echo "no certificate archive staged"; exit 0; }`,`mkdir -p ${l(t)}`,`tar xzf ${l(e)} -C ${l(t)}`,`chmod 600 ${l(t)}/*.key 2>/dev/null || true`,`rm -f ${l(e)}`].join(`
22
+ `)}async function qh(t,e){let{slug:n,siteName:r,appBase:s,from:o,to:i,targetAddress:a}=t;if(o===i)throw Error(`'${r}' is already on ${i}.`);if(t.database&&!e.database)throw Error(`'${r}' uses the on-box database '${t.database.name}', which lives in the engine's own data directory rather than in the site tree, and this move has no way to carry it. Moving the site without it would cut traffic over to an empty database.`);if(t.database&&e.database&&await e.database.targetHasData())throw Error(`${i} already has a database named '${t.database.name}' with tables in it. Restoring this site's dump over it would destroy that data. Rename or drop it on the target first, or point this project at a different database name.`);let p=[{id:"pause-workers",title:`Stop background work on ${o} so the snapshot is consistent`,satisfied:async()=>np(await e.runOnSource(rp(n,r))),apply:async()=>{await e.runOnSource(tp(n,r))}},...e.database?[{id:"database-dump",title:`Dump the '${t.database?.name}' database on ${o}`,satisfied:async()=>!1,apply:()=>e.database.dump()}]:[],{id:"snapshot",title:`Archive the site's tree and units on ${o}`,change:{from:`${o}:${s}`,to:Zn(n,r)},satisfied:async()=>!1,apply:async()=>{await e.runOnSource(ip(n,r,s))}},{id:"transfer",title:`Carry the archive to ${i}`,change:{from:o,to:i},satisfied:()=>e.archiveStaged(),apply:()=>e.transferArchive()},...e.database?[{id:"database-transfer",title:`Carry the database dump to ${i}`,change:{from:o,to:i},satisfied:()=>e.database.dumpStaged(),apply:()=>e.database.transferDump()},{id:"database-restore",title:`Create and load '${t.database?.name}' on ${i}`,satisfied:async()=>!1,apply:()=>e.database.restore()}]:[],{id:"restore",title:`Unpack the site on ${i} and start it`,change:{from:Zn(n,r),to:`${i}:${s}`},satisfied:async()=>ap(await e.runOnTarget(op(n,r,s))),apply:async()=>{await e.runOnTarget(sp(n,r,s))}}];if(t.port!=null){let{port:c}=t;p.push({id:"health",title:`Wait for the site to answer on ${i} (127.0.0.1:${c})`,satisfied:async()=>!1,apply:async()=>{await e.runOnTarget(cp(c,t.healthCheckPath??"/"))}})}return p.push(...e.certificates?[{id:"certificates",title:`Carry the site's TLS material to ${i}`,satisfied:()=>e.certificates.inPlace(),apply:()=>e.certificates.carry()}]:[],{id:"gateway",title:`Route the site on ${i}`,satisfied:()=>e.targetRoutesSite(),apply:()=>e.refreshTargetGateway()},{id:"dns",title:`Point DNS at ${i}`,change:{from:`${o}`,to:a},satisfied:async()=>await e.publishedAddress()===a,apply:async()=>{let c=await e.cutoverDns();if(c.length>0)throw Error(c.join("; "))}},{id:"drain-source",title:`Stop the site on ${o}, leaving its files in place`,satisfied:async()=>up(await e.runOnSource(lp(n,r))),apply:async()=>{await e.runOnSource(dp(n,r))}}),{operation:"site:move",target:r,steps:p}}export{Ch,Eh,bh,zu,Ku,Wu,vh,Ju,Xu,Th,wh,Yu,Rh,Dh,Sc,Zu,Ph,Nh,ep,kh,Bh,_h,xh,Oh,Lh,$h,Zn,Cc,tp,rp,np,ip,sp,op,ap,cp,dp,lp,up,Mh,Fh,Uh,Qh,Hh,Gh,qh};
@@ -2,5 +2,5 @@ import*as T from"node:crypto";import{existsSync as W,readFileSync as J}from"node
2
2
  `),i="",s="",a="",o;for(let c of r){let h=c.trim();if(!h||h.startsWith("#"))continue;let A=h.match(/^\[([^\]]+)\]$/);if(A){i=A[1];continue}if(i===e){let[m,...f]=h.split("="),b=f.join("=").trim();if(m.trim()==="aws_access_key_id")s=b;else if(m.trim()==="aws_secret_access_key")a=b;else if(m.trim()==="aws_session_token")o=b}}return{accessKeyId:s,secretAccessKey:a,sessionToken:o}}ec2CredentialsCache;async getCredentials(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY;if(t&&e)return{accessKeyId:t,secretAccessKey:e,sessionToken:process.env.AWS_SESSION_TOKEN};let r=this.loadCredentialsFromFile();if(r)return r;if(this.ec2CredentialsCache){let i=Date.now();if(this.ec2CredentialsCache.expiration>i+300000)return this.ec2CredentialsCache.credentials}try{let s=await(await fetch("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}})).text(),o=await(await fetch("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":s}})).text(),h=await(await fetch(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${o}`,{headers:{"X-aws-ec2-metadata-token":s}})).json(),A={accessKeyId:h.AccessKeyId,secretAccessKey:h.SecretAccessKey,sessionToken:h.Token};return this.ec2CredentialsCache={credentials:A,expiration:new Date(h.Expiration).getTime()},A}catch(i){throw Error("AWS credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or run on an EC2 instance with an IAM role.")}}async request(t){if(t.method==="GET"&&this.config.cacheEnabled&&t.cacheKey){let i=this.getFromCache(t.cacheKey);if(i!==null)return i}let e=t.retries??this.config.maxRetries??3,r=null;for(let i=0;i<=e;i++)try{let s=await this.makeRequest(t);if(t.method==="GET"&&this.config.cacheEnabled&&t.cacheKey)this.setInCache(t.cacheKey,s,t.cacheTTL??this.config.defaultCacheTTL??60000);return s}catch(s){if(r=s,!this.shouldRetry(s))throw s;if(i===e)throw s;let o=this.calculateRetryDelay(i);await this.sleep(o)}throw r||Error("Request failed after retries")}async makeRequest(t){let e=t.credentials||(this.credentials?.accessKeyId?this.credentials:await this.getCredentials());if(!e||!e.accessKeyId||!e.secretAccessKey)throw Error("AWS credentials not provided");let r=this.buildUrl(t),i=this.signRequest(t,e),s=await fetch(r,{method:t.method,headers:i,body:t.body}),a=await s.text();if(!s.ok)throw this.parseError(a,s.status,s.headers);if(!a||a.trim()===""){if(t.returnHeaders)return{body:null,headers:this.headersToObject(s.headers)};return null}if(t.rawResponse){if(t.returnHeaders)return{body:a,headers:this.headersToObject(s.headers)};return a}let o;if(a.startsWith("<"))o=this.parseXmlResponse(a);else try{o=JSON.parse(a)}catch{o=a}if(t.returnHeaders)return{body:o,headers:this.headersToObject(s.headers)};return o}headersToObject(t){let e={};return t.forEach((r,i)=>{e[i]=r}),e}buildUrl(t){let{service:e,region:r,queryParams:i}=t,{path:s}=t,a,o="https";if(e==="s3"){let h=yr({region:r,path:s,bucket:t.bucket,endpoint:this.config.endpoint,forcePathStyle:this.config.forcePathStyle});o=h.protocol,a=h.host,s=h.path}else if(e==="cloudfront")a="cloudfront.amazonaws.com";else if(e==="iam")a="iam.amazonaws.com";else if(e==="route53")a="route53.amazonaws.com";else if(e==="route53domains")a="route53domains.us-east-1.amazonaws.com";else if(e==="ecr")a=`api.ecr.${r}.amazonaws.com`;else if(e==="ses")a=`email.${r}.amazonaws.com`;else a=`${e}.${r}.amazonaws.com`;let c=`${o}://${a}${s}`;if(i&&Object.keys(i).length>0){let h=Object.keys(i).map((A)=>`${this.uriEncode(A)}=${this.uriEncode(i[A])}`).join("&");c+=`?${h}`}return c}signRequest(t,e){let{service:r,region:i,method:s,queryParams:a,body:o}=t,{path:c}=t,h=new Date,A=this.getAmzDate(h),m=this.getDateStamp(h),f;if(r==="s3"){let S=yr({region:i,path:c,bucket:t.bucket,endpoint:this.config.endpoint,forcePathStyle:this.config.forcePathStyle});f=S.host,c=S.path}else if(r==="cloudfront")f="cloudfront.amazonaws.com";else if(r==="iam")f="iam.amazonaws.com";else if(r==="route53")f="route53.amazonaws.com";else if(r==="route53domains")f="route53domains.us-east-1.amazonaws.com";else if(r==="ecr")f=`api.ecr.${i}.amazonaws.com`;else if(r==="ses")f=`email.${i}.amazonaws.com`;else f=`${r}.${i}.amazonaws.com`;let b={host:f,"x-amz-date":A,...t.headers||{}};if(e.sessionToken)b["x-amz-security-token"]=e.sessionToken;if(o){if(!Object.keys(b).some((O)=>O.toLowerCase()==="content-type"))b["content-type"]="application/x-www-form-urlencoded";b["content-length"]=Buffer.byteLength(o).toString()}let p=this.sha256(o||"");b["x-amz-content-sha256"]=p;let C=c,E=a?Object.keys(a).sort().map((S)=>`${this.uriEncode(S)}=${this.uriEncode(a[S])}`).join("&"):"",d=Object.keys(b).sort((S,O)=>S.toLowerCase().localeCompare(O.toLowerCase())),u=d.map((S)=>`${S.toLowerCase()}:${b[S].trim()}
3
3
  `).join(""),g=d.map((S)=>S.toLowerCase()).join(";"),y=[s,C,E,u,g,p].join(`
4
4
  `),N="AWS4-HMAC-SHA256",w=r;if(r==="email")w="ses";let I=`${m}/${i}/${w}/aws4_request`,F=[N,A,I,this.sha256(y)].join(`
5
- `),q=this.getSignatureKey(e.secretAccessKey,m,i,w),U=this.hmac(q,F),j=`${N} Credential=${e.accessKeyId}/${I}, SignedHeaders=${g}, Signature=${U}`;return{...b,Authorization:j}}getAmzDate(t){return t.toISOString().replace(/[:-]|\.\d{3}/g,"")}getDateStamp(t){return t.toISOString().slice(0,10).replace(/-/g,"")}uriEncode(t){return encodeURIComponent(t).replace(/[!'()*]/g,(e)=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}sha256(t){return T.createHash("sha256").update(t,"utf8").digest("hex")}hmac(t,e){return T.createHmac("sha256",t).update(e,"utf8").digest("hex")}getSignatureKey(t,e,r,i){let s=T.createHmac("sha256",`AWS4${t}`).update(e).digest(),a=T.createHmac("sha256",s).update(r).digest(),o=T.createHmac("sha256",a).update(i).digest();return T.createHmac("sha256",o).update("aws4_request").digest()}parseXmlResponse(t){try{let e=this.xmlParser.parse(t);if(e.ErrorResponse)throw this.createErrorFromXml(e.ErrorResponse.Error);let r=Object.keys(e);if(r.length===1)return e[r[0]];return e}catch(e){if(e.code||e.statusCode)throw e;return{}}}parseError(t,e,r){let i=Error();if(i.statusCode=e,i.requestId=r.get("x-amzn-requestid")||r.get("x-amz-request-id")||void 0,t.startsWith("<"))try{let s=this.xmlParser.parse(t);if(s.ErrorResponse?.Error){let a=s.ErrorResponse.Error;return i.code=a.Code,i.message=`AWS Error [${a.Code}]: ${a.Message||"Unknown error"}`,i.type=a.Type,i}if(s.Error)return i.code=s.Error.Code,i.message=`AWS Error [${s.Error.Code}]: ${s.Error.Message||"Unknown error"}`,i}catch{}try{let s=JSON.parse(t);if(s.__type||s.code)return i.code=s.__type||s.code,i.message=`AWS Error [${i.code}]: ${s.message||s.Message||"Unknown error"}`,i}catch{}return i.message=`AWS API Error (${e}): ${t}`,i}createErrorFromXml(t){let e=Error();return e.code=t.Code,e.message=`AWS Error [${t.Code}]: ${t.Message||"Unknown error"}`,e.type=t.Type,e}isRetryableError(t){return["RequestTimeout","RequestTimeoutException","PriorRequestNotComplete","ConnectionError","ThrottlingException","Throttling","TooManyRequestsException","ProvisionedThroughputExceededException","RequestLimitExceeded","BandwidthLimitExceeded","SlowDown","ServiceUnavailable","ServiceUnavailableException","InternalError","InternalFailure","InternalServerError","InternalServiceException","TransientError","TransientFailure","IDPCommunicationErrorException","NetworkError","ConnectionRefusedException","EC2ThrottledException","503 Slow Down","500 InternalError"].includes(t)}isRetryableStatusCode(t){return t>=500||t===429}shouldRetry(t){if(t.name==="FetchError"||t.name==="TypeError"||t.code==="ECONNRESET")return!0;if(t.code&&this.isRetryableError(t.code))return!0;if(t.statusCode&&this.isRetryableStatusCode(t.statusCode))return!0;if(t.statusCode&&t.statusCode>=400&&t.statusCode<500&&t.statusCode!==429)return!1;if(t.statusCode)return!1;return!0}calculateRetryDelay(t){let e=this.config.retryDelay??1000,r=30000,i=Math.min(e*2**t,30000),s=Math.random()*0.3*i;return i+s}sleep(t){return new Promise((e)=>setTimeout(e,t))}getFromCache(t){let e=this.cache.get(t);if(!e)return null;if(Date.now()>e.expires)return this.cache.delete(t),null;return e.data}setInCache(t,e,r){this.cache.set(t,{data:e,expires:Date.now()+r})}clearCache(){this.cache.clear()}clearExpiredCache(){let t=Date.now();for(let[e,r]of this.cache.entries())if(t>r.expires)this.cache.delete(e)}}function l(t){let e={};for(let[r,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((s,a)=>{e[`${r}.${a+1}`]=String(s)});else if(typeof i==="object")for(let[s,a]of Object.entries(i))e[`${r}.${s}`]=String(a);else e[r]=String(i)}return e}function gh(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY,r=t==="",i=e==="";if(t&&e)return{source:"env",emptyEnvKey:r,emptyEnvSecret:i,description:"environment variables (AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY)"};let s=process.env.AWS_PROFILE||"default",a=process.env.AWS_SHARED_CREDENTIALS_FILE||K(B(),".aws","credentials");if(W(a))return{source:"file",profile:s,emptyEnvKey:r,emptyEnvSecret:i,description:`~/.aws/credentials (profile: ${s})`};return{source:"ec2",emptyEnvKey:r,emptyEnvSecret:i,description:"EC2 instance metadata service (IMDSv2)"}}
6
- export{yr,n,l,gh};
5
+ `),q=this.getSignatureKey(e.secretAccessKey,m,i,w),U=this.hmac(q,F),j=`${N} Credential=${e.accessKeyId}/${I}, SignedHeaders=${g}, Signature=${U}`;return{...b,Authorization:j}}getAmzDate(t){return t.toISOString().replace(/[:-]|\.\d{3}/g,"")}getDateStamp(t){return t.toISOString().slice(0,10).replace(/-/g,"")}uriEncode(t){return encodeURIComponent(t).replace(/[!'()*]/g,(e)=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}sha256(t){return T.createHash("sha256").update(t,"utf8").digest("hex")}hmac(t,e){return T.createHmac("sha256",t).update(e,"utf8").digest("hex")}getSignatureKey(t,e,r,i){let s=T.createHmac("sha256",`AWS4${t}`).update(e).digest(),a=T.createHmac("sha256",s).update(r).digest(),o=T.createHmac("sha256",a).update(i).digest();return T.createHmac("sha256",o).update("aws4_request").digest()}parseXmlResponse(t){try{let e=this.xmlParser.parse(t);if(e.ErrorResponse)throw this.createErrorFromXml(e.ErrorResponse.Error);let r=Object.keys(e);if(r.length===1)return e[r[0]];return e}catch(e){if(e.code||e.statusCode)throw e;return{}}}parseError(t,e,r){let i=Error();if(i.statusCode=e,i.requestId=r.get("x-amzn-requestid")||r.get("x-amz-request-id")||void 0,t.startsWith("<"))try{let s=this.xmlParser.parse(t);if(s.ErrorResponse?.Error){let a=s.ErrorResponse.Error;return i.code=a.Code,i.message=`AWS Error [${a.Code}]: ${a.Message||"Unknown error"}`,i.type=a.Type,i}if(s.Error)return i.code=s.Error.Code,i.message=`AWS Error [${s.Error.Code}]: ${s.Error.Message||"Unknown error"}`,i}catch{}try{let s=JSON.parse(t);if(s.__type||s.code)return i.code=s.__type||s.code,i.message=`AWS Error [${i.code}]: ${s.message||s.Message||"Unknown error"}`,i}catch{}return i.message=`AWS API Error (${e}): ${t}`,i}createErrorFromXml(t){let e=Error();return e.code=t.Code,e.message=`AWS Error [${t.Code}]: ${t.Message||"Unknown error"}`,e.type=t.Type,e}isRetryableError(t){return["RequestTimeout","RequestTimeoutException","PriorRequestNotComplete","ConnectionError","ThrottlingException","Throttling","TooManyRequestsException","ProvisionedThroughputExceededException","RequestLimitExceeded","BandwidthLimitExceeded","SlowDown","ServiceUnavailable","ServiceUnavailableException","InternalError","InternalFailure","InternalServerError","InternalServiceException","TransientError","TransientFailure","IDPCommunicationErrorException","NetworkError","ConnectionRefusedException","EC2ThrottledException","503 Slow Down","500 InternalError"].includes(t)}isRetryableStatusCode(t){return t>=500||t===429}shouldRetry(t){if(t.name==="FetchError"||t.name==="TypeError"||t.code==="ECONNRESET")return!0;if(t.code&&this.isRetryableError(t.code))return!0;if(t.statusCode&&this.isRetryableStatusCode(t.statusCode))return!0;if(t.statusCode&&t.statusCode>=400&&t.statusCode<500&&t.statusCode!==429)return!1;if(t.statusCode)return!1;return!0}calculateRetryDelay(t){let e=this.config.retryDelay??1000,r=30000,i=Math.min(e*2**t,30000),s=Math.random()*0.3*i;return i+s}sleep(t){return new Promise((e)=>setTimeout(e,t))}getFromCache(t){let e=this.cache.get(t);if(!e)return null;if(Date.now()>e.expires)return this.cache.delete(t),null;return e.data}setInCache(t,e,r){this.cache.set(t,{data:e,expires:Date.now()+r})}clearCache(){this.cache.clear()}clearExpiredCache(){let t=Date.now();for(let[e,r]of this.cache.entries())if(t>r.expires)this.cache.delete(e)}}function l(t){let e={};for(let[r,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((s,a)=>{e[`${r}.${a+1}`]=String(s)});else if(typeof i==="object")for(let[s,a]of Object.entries(i))e[`${r}.${s}`]=String(a);else e[r]=String(i)}return e}function Sh(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY,r=t==="",i=e==="";if(t&&e)return{source:"env",emptyEnvKey:r,emptyEnvSecret:i,description:"environment variables (AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY)"};let s=process.env.AWS_PROFILE||"default",a=process.env.AWS_SHARED_CREDENTIALS_FILE||K(B(),".aws","credentials");if(W(a))return{source:"file",profile:s,emptyEnvKey:r,emptyEnvSecret:i,description:`~/.aws/credentials (profile: ${s})`};return{source:"ec2",emptyEnvKey:r,emptyEnvSecret:i,description:"EC2 instance metadata service (IMDSv2)"}}
6
+ export{yr,n,l,Sh};
@@ -1,2 +1,2 @@
1
- import{n}from"./chunk-8a02v9gs.js";import{y}from"./chunk-21b8nage.js";var tt=new Set(["A","AAAA","CNAME"]);function Z(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 x(e,t){let r=t?.headers.get("retry-after"),s=r===null||r===void 0?void 0:Number(r)*1000,o=Number.isFinite(s)?Math.max(0,s):Math.min(1000*2**(e-1),30000);await new Promise((i)=>setTimeout(i,o))}class se{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(e,t,r=15000){this.apiKey=e,this.secretKey=t,this.requestTimeoutMs=r}async request(e,t={}){let r;for(let s=1;s<=8;s+=1){let o,i=new AbortController,a=setTimeout(()=>{i.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{o=await fetch(`https://api.porkbun.com/api/json/v3${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...t}),signal:i.signal})}catch(d){if(r=d,s===8)throw d;await x(s);continue}finally{clearTimeout(a)}if(!o.ok){let d=await o.clone().json().then((u)=>u?.message).catch(()=>{return});if(r=Error(`Porkbun API error: ${o.status} ${o.statusText}${d?`: ${d}`:""}`),!Z(o.status)||s===8)throw r;await x(s,o);continue}let c=await o.json();if(c.status==="ERROR"){if(r=Error(`Porkbun API error: ${c.message||"Unknown error"}`),!Z(0,c.message)||s===8)throw r;await x(s,o);continue}return c}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(e,t){if(!se.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${o.message??"unknown provider error"}`];let i=[];for(let a of o.records){if(a.type!=="ALIAS"&&a.type!=="CNAME")continue;if(this.getSubdomain(a.name,r)!==s)continue;let c=await this.deleteRecord(e,a);if(!c.success)i.push(`could not remove conflicting ${a.type} on ${a.name}: ${c.message??"unknown provider error"}`)}return i}async addressRecordExists(e,t){let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return!0;return o.records.some((i)=>i.type===t.type&&this.getSubdomain(i.name,r)===s&&i.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)o.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)o.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)o.content=`${t.weight} ${t.port} ${t.content}`;let i=await this.clearConflictingAliases(e,t),a=await this.request(`/dns/create/${r}`,o);if(se.ADDRESS_TYPES.has(t.type)&&!await this.addressRecordExists(e,t))return{success:!1,message:`Porkbun reported success but no ${t.type} record for ${t.name} exists${i.length>0?` (${i.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:a.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(o.success){let i=o.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type);if(i?.id&&i.content===t.content&&(t.ttl===void 0||i.ttl===t.ttl)&&(t.type!=="MX"&&t.type!=="SRV"||t.priority===void 0||i.priority===t.priority))return{success:!0,id:i.id,message:"Record already up to date"};if(i?.id){let a={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)a.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)a.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)a.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${i.id}`,a),{success:!0,id:i.id,message:"Record updated successfully"}}}return this.createRecord(e,t)}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e);if("id"in t&&t.id)return await this.request(`/dns/delete/${r}/${t.id}`),{success:!0,message:"Record deleted successfully"};let s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return{success:!1,message:"Failed to list records"};let i=o.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type&&a.content===t.content);if(!i?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${i.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/dns/retrieve/${r}`;if(t)s=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(s)).records||[]).map((a)=>({id:a.id,name:a.name||r,type:a.type,content:a.content,ttl:Number.parseInt(a.ttl,10),priority:a.prio?Number.parseInt(a.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request(`/dns/retrieve/${t}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((t)=>t.domain)}catch{return[]}}async getNameServers(e){try{let t=this.getRootDomain(e);return(await this.request(`/domain/getNs/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/domain/updateNs/${r}`,{ns:t}),!0}catch{return!1}}}class xe{name="godaddy";apiKey;apiSecret;baseUrl;constructor(e,t="",r="production"){this.apiKey=e,this.apiSecret=t,this.baseUrl=r==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}authorization(){if(!this.apiSecret||this.apiKey.startsWith("gd_pat_"))return`Bearer ${this.apiKey}`;return`sso-key ${this.apiKey}:${this.apiSecret}`}async request(e,t,r){let s=`${this.baseUrl}${t}`,o={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},i={method:e,headers:o};if(r)i.body=JSON.stringify(r);let a=await fetch(s,i);if(a.status===204)return{};if(a.ok){let d=await a.text();if(d)return JSON.parse(d);return{}}let c=`GoDaddy API error: ${a.status} ${a.statusText}`;try{let d=await a.json();if(d.message)c=`GoDaddy API error: ${d.message}`;if(d.fields)c+=` - Fields: ${JSON.stringify(d.fields)}`}catch{}throw Error(c)}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"@";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}toGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=this.getSubdomain(e.name,r),o={type:e.type,name:s,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)o.priority=e.priority;return o}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=e.name;if(s==="@")s=r;else if(!s.endsWith(r))s=`${s}.${r}`;return{name:s,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[s]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s.name}`,[s]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${s}`),i=o.filter((a)=>a.data!==t.content);if(i.length===o.length)return{success:!1,message:"Record not found"};if(i.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${s}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s}`,i);return{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/v1/domains/${r}/records`;if(t)s=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",s)).map((i)=>this.fromGoDaddyRecord(i,e))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request("GET",`/v1/domains/${t}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((t)=>t.domain)}catch{return[]}}async getDomainDetails(e){try{let t=this.getRootDomain(e),r=await this.request("GET",`/v1/domains/${t}`);return{domain:r.domain,status:r.status,nameServers:r.nameServers,expires:r.expires}}catch{return null}}async getNameServers(e){return(await this.getDomainDetails(e))?.nameServers??[]}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request("PATCH",`/v1/domains/${r}`,{nameServers:t}),!0}catch{return!1}}async checkDomainAvailability(e){try{let t=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(e)}`);return{available:t.available,price:t.price,currency:t.currency}}catch{return{available:!1}}}}var su=["js","mjs","cjs","css","map","woff","woff2","ttf","otf","eot","png","jpg","jpeg","gif","webp","avif","svg","ico","mp4","webm","ogg","mp3","wav","pdf","wasm"],F=[{name:"x-stx-router",value:"true"}];function S(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function M(e){return`{${e.map(S).join(" ")}}`}function G(e){let t=`http.request.headers[${S(e.name.toLowerCase())}]`;return e.value===void 0?`len(${t}) > 0`:`any(${t}[*] == ${S(e.value)})`}function hn(e){if(e.length===1)return`http.host eq ${S(e[0])}`;return`http.host in ${M(e)}`}function Ma(e,t={}){if(t.enabled===!1||e.length===0)return[];let r=hn(e),s=[],i=(t.bypassPaths??[]).map((A)=>`starts_with(http.request.uri.path, ${S(A)})`),c=(t.negotiatedRequestHeaders??F).map(G),d=[...i,...c],u=d.length>0?`(${d.join(" or ")})`:void 0;if(u)s.push({action:"set_cache_settings",description:"bypass cache",expression:`(${r} and ${u})`,enabled:!0,action_parameters:{cache:!1}});let p=u?`${r} and not ${u}`:r,m=t.assetExtensions??su,g=m.length>0?`lower(http.request.uri.path.extension) in ${M([...m])}`:void 0;if(g)s.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${p} and ${g})`,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.assetEdgeTtl??2592000},browser_ttl:{mode:"override_origin",default:t.assetBrowserTtl??31536000}}});let R=g?`(${p} and not ${g})`:`(${p})`;if(t.documentEdgeTtl===0)return s.push({action:"set_cache_settings",description:"bypass documents",expression:R,enabled:!0,action_parameters:{cache:!1}}),s;return s.push({action:"set_cache_settings",description:"cache documents",expression:R,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.documentEdgeTtl??3600},browser_ttl:{mode:"override_origin",default:t.documentBrowserTtl??0}}}),s}function Fa(e,t,r){if(e.length===0||!t||!r)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${hn(e)})`,enabled:!0,action_parameters:{headers:{[t]:{operation:"set",value:r}}}}]}var K="https://api.cloudflare.com/client/v4",rs="[ts-cloud]";class fe{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(e,t={}){this.apiToken=e,this.configuredZoneId=t.zoneId,this.accountId=t.accountId}async request(e,t,r){let s=`${K}${t}`,o={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},i={method:e,headers:o};if(r)i.body=JSON.stringify(r);let c=await(await fetch(s,i)).json();if(!c.success){let d=c.errors.map((u)=>u.message).join(", ");throw Error(`Cloudflare API error: ${d}`)}return c}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async resolveZone(e){let t=e.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let a=await this.resolveConfiguredZoneName();if(a&&(t===a||t.endsWith(`.${a}`)))return{id:this.configuredZoneId,name:a}}let r=this.getRootDomain(t),s=this.zoneCache.get(r);if(s)return{id:s,name:r};let o=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!o.result||o.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let i=o.result[0].id;return this.zoneCache.set(r,i),{id:i,name:o.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let t=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!t)return;return this.configuredZoneName=t,this.zoneCache.set(t,this.configuredZoneId),t}catch{return}}async getZoneId(e){return(await this.resolveZone(e)).id}getFullRecordName(e,t){let r=e.replace(/\.$/,"");if(!r||r===t||r==="@")return t;if(r.endsWith(`.${t}`))return r;return`${r}.${t}`}toCloudflareRecord(e,t,r){let s={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},o=r??e.proxied;if(o!==void 0&&tt.has(e.type)){if(s.proxied=o,o)s.ttl=1}if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;if(e.type==="SRV"){let i=X(e);if(i)s.data=i,delete s.content,delete s.priority;else if(e.priority!==void 0)s.priority=e.priority}return s}fromCloudflareRecord(e){return{id:e.id,name:e.name,type:e.type,content:e.content,ttl:e.ttl,priority:e.priority,proxied:e.proxied}}async createRecord(e,t){try{let r=await this.resolveZone(e),s=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,s)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.resolveZone(e),s=this.getFullRecordName(t.name,r.name),i=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`)).result?.[0],a=t.proxied??i?.proxied,c=this.toCloudflareRecord(t,r.name,a);if(i)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${i.id}`,c)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,c)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),s=r.id,o=this.getFullRecordName(t.name,r.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!i.result||i.result.length===0)return{success:!1,message:"Record not found"};let a=i.result.find((c)=>c.content===t.content);if(!a)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${s}/dns_records/${a.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let s=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)s+=`&type=${t}`;let o=[],i=1,a=!0;while(a){let c=await this.request("GET",`${s}&page=${i}`);if(o.push(...c.result||[]),c.result_info)a=i<c.result_info.total_pages,i++;else a=!1}return{success:!0,records:o.map((c)=>this.fromCloudflareRecord(c))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{return await this.getZoneId(e),!0}catch{return!1}}async listDomains(){try{let e=[],t=1,r=!0;while(r){let s=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...s.result||[]),s.result_info)r=t<s.result_info.total_pages,t++;else r=!1}return e.map((s)=>s.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),s=t.accountId??this.accountId;if(!s)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let o=await this.getZoneDetails(r);if(o)return{...o,created:!1};try{let a=(await this.request("POST","/zones",{name:r,account:{id:s},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(a.name,a.id),{id:a.id,name:a.name,status:a.status,nameServers:a.name_servers??[],created:!0}}catch(i){let a=i instanceof Error?i.message:String(i);if(!/already exists|1061/i.test(a))throw i;let c=await this.getZoneDetails(r);if(!c)throw i;return{...c,created:!1}}}async getZoneDetails(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}`);return{id:r.result.id,name:r.result.name,status:r.result.status,nameServers:r.result.name_servers,paused:r.result.paused}}catch{return null}}async listEdgeCertificateHosts(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/ssl/certificate_packs?per_page=50`),s=new Set;for(let o of r.result||[]){if(o.status!=="active")continue;for(let i of o.hosts||[])s.add(i.toLowerCase())}return[...s]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),s={};if(t?.purgeEverything)s.purge_everything=!0;else{if(t?.files)s.files=t.files;if(t?.tags)s.tags=t.tags;if(t?.hosts)s.hosts=t.hosts}if(Object.keys(s).length===0)s.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,s),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),s=r.id,o=this.getFullRecordName(t.name,r.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(i.result&&i.result.length>0)return i.result.find((c)=>c.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let s=await this.resolveZone(e),o=s.id,i=this.getFullRecordName(t.name,s.name),a=await this.request("GET",`/zones/${o}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);if(!a.result||a.result.length===0)return!1;let c=a.result.find((d)=>d.content===t.content);if(!c)return!1;return await this.request("PATCH",`/zones/${o}/dns_records/${c.id}`,{proxied:r}),!0}catch{return!1}}async zoneIdFor(e){return this.getZoneId(e)}get account(){return this.accountId}async getZoneSettings(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/settings`),s={};for(let o of r.result||[])s[o.id]=o.value;return s}async applyZoneSettings(e,t){let r=await this.getZoneId(e),s=await this.getZoneSettings(e).catch(()=>({})),o=[],i=[];for(let[a,c]of Object.entries(t)){if(c===void 0)continue;let d=s[a];if(d!==void 0&&k(d,c))continue;try{await this.request("PATCH",`/zones/${r}/settings/${a}`,{value:c}),o.push({id:a,from:d,to:c})}catch(u){i.push({id:a,error:u instanceof Error?u.message:String(u)})}}return{changed:o,failed:i}}async getManagedRequestHeaders(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/managed_headers`),s={};for(let o of r.result?.managed_request_headers||[])s[o.id]=o.enabled===!0;return s}async applyManagedRequestHeaders(e,t){let r=[],s=[],o=Object.entries(t).filter(([,d])=>d!==void 0);if(o.length===0)return{changed:r,failed:s};let i=await this.getZoneId(e),a;try{a=await this.getManagedRequestHeaders(e)}catch(d){let u=d instanceof Error?d.message:String(d);for(let[p]of o)s.push({id:p,error:`could not read managed headers — ${u}`});return{changed:r,failed:s}}let c=[];for(let[d,u]of o){if(!(d in a)){s.push({id:d,error:"not a managed request header transform on this zone"});continue}if(a[d]!==u)c.push([d,u])}if(c.length===0)return{changed:r,failed:s};try{await this.request("PATCH",`/zones/${i}/managed_headers`,{managed_request_headers:c.map(([d,u])=>({id:d,enabled:u})),managed_response_headers:[]});for(let[d,u]of c)r.push({id:d,from:a[d],to:u})}catch(d){let u=d instanceof Error?d.message:String(d);for(let[p]of c)s.push({id:p,error:u})}return{changed:r,failed:s}}async getPhaseRules(e,t){let r=await this.getZoneId(e);try{return(await this.request("GET",`/zones/${r}/rulesets/phases/${t}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(e,t,r){try{let s=await this.getZoneId(e),o=await this.getPhaseRules(e,t),i=r.map((d)=>({...d,description:d.description?.startsWith(rs)?d.description:`${rs} ${d.description||t}`})),c=W(o,i).map(({id:d,...u})=>u);return await this.request("PUT",`/zones/${s}/rulesets/phases/${t}/entrypoint`,{rules:c}),{success:!0}}catch(s){return{success:!1,message:s instanceof Error?s.message:String(s)}}}}var _=/http\.host (?:eq "[^"]+"|in \{[^}]*\})/;function O(e){return _.test(e)?e.replace(_,"\x00hosts\x00"):null}function q(e,t){return e.replace(_,hn(t))}function b(e){if(Array.isArray(e))return`[${e.map(b).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[s])=>r.localeCompare(s)).map(([r,s])=>`${JSON.stringify(r)}:${b(s)}`).join(",")}}`;return JSON.stringify(e)}function B(e,t){let r=O(e.expression);return r!==null&&r===O(t.expression)&&e.action===t.action&&e.description===t.description&&(e.enabled??!0)===(t.enabled??!0)&&b(e.action_parameters)===b(t.action_parameters)}function W(e,t){let r=new Set(t.flatMap((i)=>N(i.expression))),s=(i)=>(i.description||"").startsWith(rs),o=[];for(let i of e){if(!s(i)){o.push(i);continue}let a=N(i.expression);if(a.length===0){if(r.size>0)o.push(i);continue}let c=a.filter((d)=>!r.has(d));if(c.length===a.length)o.push(i);else if(c.length>0)o.push({...i,expression:q(i.expression,c)})}for(let i of t){let a=N(i.expression),c=a.length>0?o.findIndex((p)=>s(p)&&B(p,i)):-1;if(c===-1){o.push(i);continue}let d=o[c],u=[...new Set([...N(d.expression),...a])];o[c]={...d,expression:q(d.expression,u)}}return o}function N(e){let t=[];for(let r of e.matchAll(/http\.host eq "([^"]+)"/g))t.push(r[1]);for(let r of e.matchAll(/http\.host in \{([^}]*)\}/g))for(let s of r[1].matchAll(/"([^"]+)"/g))t.push(s[1]);return t}function k(e,t){if(e===t)return!0;if(typeof e!==typeof t||e===null||t===null)return!1;if(typeof e!=="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;return e.every((o,i)=>k(o,t[i]))}let r=e,s=t;return Object.keys(s).every((o)=>k(r[o],s[o]))}function X(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:L(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[s,o,i]=r.slice(0,3).map(Number);if(![s,o,i].every(Number.isFinite))return null;return{priority:s,weight:o,port:i,target:L(r.slice(3).join(" "))}}function L(e){return e.replace(/\.$/,"")}var Y=new Set(["A","AAAA","CNAME","ALIAS"]);function Tt(e){let t=e.trim().replace(/^"|"$/g,"").toLowerCase();if(t.startsWith("v=spf1"))return"v=spf1";if(t.startsWith("v=dmarc1"))return"v=dmarc1";return}function D(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function w(e){return e.replace(/\.$/,"").toLowerCase()}function fn(e,t){let r=w(t),s=(e??"@").trim();if(!s||s==="@")return r;let o=w(s);if(o===r||o.endsWith(`.${r}`))return o;return`${o}.${r}`}function ns(e,t){return e.map((r)=>({...r,name:fn(r.name,t),proxied:r.proxied??!1}))}function J(e,t){if(e.type!==t.type)return!1;if(w(e.name)!==w(t.name))return!1;if(Y.has(t.type))return!0;if(t.type==="TXT"){let r=Tt(t.content);if(r)return Tt(D(e.content))===r;return D(e.content)===D(t.content)}return D(e.content)===D(t.content)}function Q(e,t){if(D(e.content)!==D(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 is(e){let{provider:t,zone:r,records:s}=e,o={outcomes:[],warnings:[]};if(s.length===0)return o;let i=await t.listRecords(r);if(!i.success)return o.warnings.push(`could not list ${r}: ${i.message||"unknown provider error"} — records not reconciled`),o;let a=i.records;for(let c of s){let d=a.filter((g)=>J(g,c));if(d.length>0&&d.every((g)=>Q(g,c))){o.outcomes.push({record:c,action:"unchanged"});continue}let u={name:c.name,type:c.type,content:c.content,ttl:c.ttl??3600,...c.priority!==void 0?{priority:c.priority}:{},...c.proxied!==void 0?{proxied:c.proxied}:{}},p=c.type==="TXT"&&Tt(c.content)!==void 0;if(p)for(let g of d){let R=await t.deleteRecord(r,{name:g.name,type:g.type,content:g.content});if(!R.success)o.warnings.push(`could not remove superseded ${g.type} at ${g.name}: ${R.message||"unknown error"}`)}let m=p||d.length===0?await t.createRecord(r,u):await t.upsertRecord(r,u);if(m.success)o.outcomes.push({record:c,action:d.length>0?"updated":"created"});else o.outcomes.push({record:c,action:"failed",message:m.message})}for(let c of["MX"]){let d=new Set(s.filter((u)=>u.type===c).map((u)=>w(u.name)));for(let u of d){let p=new Set(s.filter((g)=>g.type===c&&w(g.name)===u).map((g)=>D(g.content).toLowerCase())),m=a.filter((g)=>g.type===c&&w(g.name)===u&&!p.has(D(g.content).toLowerCase()));for(let g of m)o.warnings.push(`${u} has an undeclared ${c} record (${g.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return o}function nr(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.getNameServers==="function"&&typeof t.updateNameServers==="function"}function ir(e){return Boolean(e&&typeof e.createZone==="function")}var ee=new Set(["NS"]);function v(e){return e.replace(/\.$/,"").toLowerCase()}function An(e,t){if(e.length===0||t.length===0)return!1;let r=new Set(e.map(v)),s=new Set(t.map(v));if(r.size!==s.size)return!1;for(let o of r)if(!s.has(o))return!1;return!0}function te(e){let t=e.content.trim(),r=t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t;return e.type==="TXT"?r:v(r)}var re=new Set(["MX","SRV"]),ne=new Set(["A","AAAA","CNAME"]);function P(e){let t=re.has(e.type)&&e.priority!==void 0&&e.priority!==null?String(Number(e.priority)):"";return`${e.type}|${v(e.name)}|${te(e)}|${t}`}function ie(e,t){return P(e)===P(t)}async function sr(e){let{domain:t,registrar:r,host:s,dryRun:o=!1}=e,i=new Set([...e.proxiedHosts??[]].map(v)),a=[],c=await s.createZone(t,{accountId:e.accountId,jumpStart:!1}),d=await r.getNameServers(t),u={status:"ready",domain:t,zoneId:c.id,targetNameservers:c.nameServers,currentNameservers:d,records:[],missing:[],warnings:a};if(An(d,c.nameServers))return u.status="already-delegated",u;if(c.nameServers.length===0)return a.push(`${s.name} did not report nameservers for ${t}; cannot delegate.`),u.status="blocked",u;let p=await r.listRecords(t);if(!p.success)return a.push(`Could not read ${t} from ${r.name}: ${p.message??"unknown error"}`),u.status="blocked",u;let m=[];for(let l of p.records){if(ee.has(l.type)){u.records.push({record:l,status:"skipped",reason:`${l.type} describes the delegation itself; ${s.name} owns it`});continue}let f=tt.has(l.type)&&i.has(v(l.name));m.push({name:l.name,type:l.type,content:l.content,ttl:l.ttl,priority:l.priority,...tt.has(l.type)?{proxied:f}:{}})}if(o){for(let l of m)u.records.push({record:l,status:"copied",reason:"dry run"});return u}let g=new Map;for(let l of m){let f=`${l.type}|${v(l.name)}`;g.set(f,(g.get(f)??0)+1)}let R=new Set;try{let l=await s.listRecords(t);for(let f of l.records??[])R.add(P(f))}catch{}for(let l of m){let f=ne.has(l.type)&&g.get(`${l.type}|${v(l.name)}`)===1;if(!f&&R.has(P(l))){u.records.push({record:l,status:"present"});continue}let C;try{C=f?await s.upsertRecord(t,l):await s.createRecord(t,l)}catch(E){C={success:!1,message:E instanceof Error?E.message:String(E)}}if(C.success)R.add(P(l));u.records.push(C.success?{record:l,status:"copied"}:{record:l,status:"failed",reason:C.message})}let A=await s.listRecords(t);if(!A.success)return a.push(`Could not read back ${t} from ${s.name}: ${A.message??"unknown error"}`),u.status="blocked",u;for(let l of m)if(!A.records.some((f)=>ie(l,f)))u.missing.push(l);if(u.missing.length>0)return a.push(`${u.missing.length} record(s) did not arrive at ${s.name}; leaving ${r.name}'s nameservers alone. Delegating now would take the domain off a complete zone and onto an incomplete one.`),u.status="blocked",u;if(!await r.updateNameServers(t,c.nameServers))return a.push(`${r.name} refused the nameserver update for ${t}.`),u.status="blocked",u;return u.status="delegated",u}var ce={add_visitor_location_headers:"visitorLocationHeaders"};function U(e){return{porkbunApiKey:e.PORKBUN_API_KEY,porkbunSecretKey:e.PORKBUN_SECRET_KEY,godaddyApiKey:e.GODADDY_API_KEY,godaddyApiSecret:e.GODADDY_API_SECRET,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID}}function de(e,t){if(e==="porkbun"){if(!t.porkbunApiKey||!t.porkbunSecretKey)return"PORKBUN_API_KEY / PORKBUN_SECRET_KEY are not set";return new se(t.porkbunApiKey,t.porkbunSecretKey)}if(!t.godaddyApiKey||!t.godaddyApiSecret)return"GODADDY_API_KEY / GODADDY_API_SECRET are not set";let r=new xe(t.godaddyApiKey,t.godaddyApiSecret);if(!nr(r))return"the GoDaddy provider cannot change nameservers";return r}async function ss(e,t={}){let r=e.registrar;if(!r)return{status:"skipped",reason:"no dns.registrar configured"};if(r.delegate===!1)return{status:"skipped",reason:"dns.registrar.delegate is false"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(!e.provider||e.provider===r.provider)return{status:"skipped",reason:`dns.provider is already ${r.provider}`};if(e.provider!=="cloudflare")return{status:"skipped",reason:`delegation to ${e.provider} is not supported yet`};let s=t.credentials??U(t.env??process.env);if(!s.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let o=de(r.provider,s);if(typeof o==="string")return{status:"skipped",reason:o};let i=new fe(s.cloudflareApiToken,{accountId:s.cloudflareAccountId});if(!ir(i))return{status:"skipped",reason:"the Cloudflare provider cannot create zones"};return sr({domain:e.domain,registrar:o,host:i,proxiedHosts:r.proxied,accountId:s.cloudflareAccountId,dryRun:r.dryRun})}function os(e){if(e.status==="skipped")return[`dns: delegation skipped — ${e.reason}`];let t=[];switch(e.status){case"already-delegated":t.push(`dns: ${e.domain} already delegated to ${e.targetNameservers.join(", ")}`);break;case"delegated":t.push(`dns: ${e.domain} delegated to ${e.targetNameservers.join(", ")} (${e.records.filter((r)=>r.status==="copied").length} record(s) copied)`),t.push("dns: nameserver changes take up to 24h to propagate; the old zone answers until then");break;case"ready":t.push(`dns: ${e.domain} would delegate to ${e.targetNameservers.join(", ")} (dry run)`);break;case"blocked":t.push(`dns: ${e.domain} NOT delegated — nameservers left at ${e.currentNameservers.join(", ")}`);for(let r of e.missing)t.push(` missing at destination: ${r.type} ${r.name}`);break}for(let r of e.warnings)t.push(` ${r}`);return t}function ue(e){let t={};if(e.ssl!==void 0)t.ssl=e.ssl;if(e.alwaysUseHttps!==void 0)t.always_use_https=e.alwaysUseHttps?"on":"off";if(e.minTlsVersion!==void 0)t.min_tls_version=e.minTlsVersion;return t}function le(e){let t={};for(let[r,s]of Object.entries(ce)){let o=e[s];if(typeof o==="boolean")t[r]=o}return t}async function as(e,t={}){if(!e.zone)return{status:"skipped",reason:"no dns.zone configured"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(e.provider!=="cloudflare")return{status:"skipped",reason:`zone settings are not supported for ${e.provider??"this provider"}`};let r=ue(e.zone),s=le(e.zone);if(Object.keys(r).length===0&&Object.keys(s).length===0)return{status:"skipped",reason:"dns.zone declares no settings"};let o=t.credentials??U(t.env??process.env);if(!o.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let i=new fe(o.cloudflareApiToken,{accountId:o.cloudflareAccountId}),a=await i.applyZoneSettings(e.domain,r),c=Object.keys(s).length>0?await i.applyManagedRequestHeaders(e.domain,s):{changed:[],failed:[]},d=[...a.changed,...c.changed],u=[...a.failed,...c.failed];return{status:d.length>0?"applied":"unchanged",domain:e.domain,changed:d,failed:u}}function cs(e){if(e.status==="skipped")return[`dns: zone settings skipped — ${e.reason}`];let t=[];for(let r of e.changed)t.push(`dns: ${e.domain} ${r.id}: ${String(r.from)} → ${String(r.to)}`);if(e.status==="unchanged"&&e.failed.length===0)t.push(`dns: ${e.domain} zone settings already as declared`);for(let r of e.failed)t.push(`dns: ${e.domain} could not set ${r.id} — ${r.error}`);return t}class z{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new y(e),this.providedHostedZoneId=t}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async getHostedZoneId(e){if(this.providedHostedZoneId)return this.providedHostedZoneId;let t=this.getRootDomain(e),r=this.hostedZoneCache.get(t);if(r)return r;let s=await this.client.findHostedZoneForDomain(e);if(s){let o=s.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,o),o}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(!s||s==="@")return`${r}.`;if(s===r||s.endsWith(`.${r}`))return`${s}.`;return`${s}.${r}.`}formatValue(e){let t=e.content;if(e.type==="TXT"&&!t.startsWith('"'))t=ge(t);if(e.type==="MX"&&e.priority!==void 0)t=`${e.priority} ${t}`;return t}sameValue(e,t,r){return e==="TXT"?V(t)===V(r):t===r}async currentSet(e,t,r){let o=(await this.client.listResourceRecordSets({HostedZoneId:e,StartRecordName:t,StartRecordType:r,MaxItems:"1"})).ResourceRecordSets?.[0];if(!o||o.Name.toLowerCase()!==t.toLowerCase()||o.Type!==r||o.AliasTarget||o.SetIdentifier)return null;return{ttl:o.TTL??300,values:(o.ResourceRecords??[]).map((i)=>i.Value)}}async createRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),o=this.formatValue(t),i=await this.currentSet(r,s,t.type);if(i?.values.some((d)=>this.sameValue(t.type,d,o)))return{success:!0,message:"Record already present"};let a=[...i?.values??[],o];return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:i?"UPSERT":"CREATE",ResourceRecordSet:{Name:s,Type:t.type,TTL:i?.ttl??t.ttl??300,ResourceRecords:a.map((d)=>({Value:d}))}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),o=this.formatValue(t);return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),o=this.formatValue(t),i=await this.currentSet(r,s,t.type);if(!i||!i.values.some((c)=>this.sameValue(t.type,c,o)))return{success:!0,message:"Record already absent"};let a=i.values.filter((c)=>!this.sameValue(t.type,c,o));return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:a.length>0?"UPSERT":"DELETE",ResourceRecordSet:{Name:s,Type:t.type,TTL:i.ttl,ResourceRecords:(a.length>0?a:i.values).map((c)=>({Value:c}))}}]}}),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,records:[],message:`No hosted zone found for domain: ${e}`};let s=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),o=[];for(let i of s.ResourceRecordSets){if(t&&i.Type!==t)continue;if(i.AliasTarget)continue;for(let a of i.ResourceRecords||[]){let c=a.Value,d;if(i.Type==="MX"){let u=c.split(" ");if(u.length>=2)d=Number.parseInt(u[0],10),c=u.slice(1).join(" ")}if(i.Type==="TXT"&&c.startsWith('"'))c=V(c);o.push({name:i.Name.replace(/\.$/,""),type:i.Type,content:c,ttl:i.TTL,priority:d})}}return{success:!0,records:o}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){return await this.getHostedZoneId(e)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((t)=>t.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(e){try{let t=await this.getHostedZoneId(e.domain);if(!t)return{success:!1,message:`No hosted zone found for domain: ${e.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:t,Name:this.normalizeName(e.domain,e.name),TargetHostedZoneId:e.targetHostedZoneId,TargetDNSName:e.targetDnsName,EvaluateTargetHealth:e.evaluateTargetHealth,Type:e.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(t){return{success:!1,message:t instanceof Error?t.message:"Unknown error"}}}async createCloudFrontAlias(e){return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:y.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=y.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})}}var j=255;function ge(e){let t=[];for(let r=0;r<e.length;r+=j)t.push(e.slice(r,r+j));if(t.length===0)t.push("");return t.map((r)=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`).join(" ")}function V(e){if(!e.startsWith('"'))return e;let t="",r=!1;for(let s=0;s<e.length;s++){let o=e[s];if(!r){if(o==='"')r=!0;continue}if(o==="\\"&&s+1<e.length){t+=e[++s];continue}if(o==='"'){r=!1;continue}t+=o}return t}async function ds(e,t){let r=[],s,o;for(;;){let i=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:s,StartRecordType:o,MaxItems:"100"});if(r.push(...i.ResourceRecordSets),!i.IsTruncated)break;if(s=i.NextRecordName,o=i.NextRecordType,!s)break}return r}function h(e){return e.replace(/\.$/,"").toLowerCase()}function H(e){return e.replace(/\.$/,"")}function I(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${H(e.content)}`;return H(e.content)}function pe(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function ls(e,t){let r=h(t),s=[],o=[],i=[],a=new Set;for(let c of e){let d=h(c.Name),u=c.Type;if(u==="SOA"||u==="NS"&&d===r){o.push({name:d,type:u,reason:"owned by the destination provider"});continue}if(c.SetIdentifier){o.push({name:d,type:u,reason:`routing policy record (SetIdentifier=${c.SetIdentifier}) has no equivalent — recreate by hand`}),i.push(`${u} ${d} is part of a Route53 routing policy and was NOT migrated`);continue}if(c.AliasTarget){if(a.has(d))continue;a.add(d);let p=h(c.AliasTarget.DNSName);if(s.push({name:d,type:"CNAME",content:p,ttl:300,translatedFrom:`${u} ALIAS → ${p}`}),c.AliasTarget.EvaluateTargetHealth)i.push(`${d} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let p of c.ResourceRecords||[]){let m=me(d,u,p.Value,c.TTL);if("reason"in m){o.push({name:d,type:u,reason:m.reason}),i.push(`${u} ${d}: ${m.reason}`);continue}s.push(m)}}return{zone:r,records:s,skipped:o,warnings:i}}function me(e,t,r,s){let o={name:e,ttl:s};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...o,type:t==="PTR"?"CNAME":t,content:h(r)};case"TXT":return{...o,type:"TXT",content:pe(r)};case"MX":{let[i,...a]=r.trim().split(/\s+/);if(!a.length)return{reason:`malformed MX value "${r}"`};return{...o,type:"MX",content:h(a.join(" ")),priority:Number(i)}}case"SRV":{let i=r.trim().split(/\s+/);if(i.length<4)return{reason:`malformed SRV value "${r}"`};let[a,c,d]=i.slice(0,3).map(Number);return{...o,type:"SRV",content:h(i.slice(3).join(" ")),priority:a,weight:c,port:d}}case"NS":return{...o,type:"NS",content:h(r)};case"CAA":return{...o,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var he=new Set(["TXT","MX","SRV","NS","CAA"]);async function us(e,t){let r=[],s=[],o=new Set;try{let i=await e.listRecords(t.zone);for(let a of i.records||[])o.add(`${h(a.name)}|${a.type}|${I(a)}`)}catch{}for(let i of t.records){let a={...i,proxied:!1},c=`${h(i.name)}|${i.type}|${I(i)}`;if(!he.has(i.type)){let u=await e.upsertRecord(t.zone,a);if(u.success)r.push(i);else s.push({record:i,message:u.message||"unknown provider error"});continue}if(o.has(c)){r.push(i);continue}let d=await e.createRecord(t.zone,a);if(d.success)o.add(c),r.push(i);else s.push({record:i,message:d.message||"unknown provider error"})}return{applied:r,failed:s}}async function ps(e,t){let r=await e.listRecords(t.zone),s=[],o=[],i=new Map;for(let a of r.records||[]){let c=`${h(a.name)}|${a.type}`,d=i.get(c)??[];d.push(I(a)),i.set(c,d)}for(let a of t.records){let c=i.get(`${h(a.name)}|${a.type}`),d=I(a);if(c?.some((u)=>u===d))s.push(a);else o.push({record:a,found:c?.join(", ")})}return{matched:s,missing:o,ok:o.length===0}}class ae{client;region;constructor(e="us-east-1"){this.client=new n,this.region=e}async requestCertificate(e){let t={DomainName:e.DomainName,ValidationMethod:e.ValidationMethod||"DNS"};if(e.SubjectAlternativeNames)t.SubjectAlternativeNames=e.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(t)})).CertificateArn||""}}async describeCertificate(e){let r=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Certificate||{};return{CertificateArn:r.CertificateArn||"",DomainName:r.DomainName||"",SubjectAlternativeNames:r.SubjectAlternativeNames,Status:r.Status||"PENDING_VALIDATION",Type:r.Type,DomainValidationOptions:r.DomainValidationOptions?.map((s)=>({DomainName:s.DomainName,ValidationDomain:s.ValidationDomain,ValidationStatus:s.ValidationStatus,ResourceRecord:s.ResourceRecord?{Name:s.ResourceRecord.Name,Type:s.ResourceRecord.Type,Value:s.ResourceRecord.Value}:void 0,ValidationMethod:s.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(e){let t={};if(e?.CertificateStatuses)t.CertificateStatuses=e.CertificateStatuses;if(e?.MaxItems)t.MaxItems=e.MaxItems;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(t)});return{CertificateSummaryList:(r.CertificateSummaryList||[]).map((s)=>({CertificateArn:s.CertificateArn,DomainName:s.DomainName})),NextToken:r.NextToken}}async deleteCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})}async listTagsForCertificate(e){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Tags||[]}}async addTagsToCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn,Tags:e.Tags})})}async resendValidationEmail(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:e.CertificateArn,Domain:e.Domain,ValidationDomain:e.ValidationDomain})})}async findCertificateByDomain(e){let r=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((s)=>s.DomainName===e||s.DomainName===`*.${e.split(".").slice(1).join(".")}`);if(!r)return null;return this.describeCertificate({CertificateArn:r.CertificateArn})}async waitForCertificateValidation(e,t=60,r=30000){for(let s=0;s<t;s++){let o=await this.describeCertificate({CertificateArn:e});if(o.Status==="ISSUED")return o;if(o.Status==="FAILED"||o.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((i)=>setTimeout(i,r))}return null}async getDnsValidationRecords(e){let t=await this.describeCertificate({CertificateArn:e});if(!t.DomainValidationOptions)return[];return t.DomainValidationOptions.filter((r)=>r.ResourceRecord&&r.ValidationMethod==="DNS").map((r)=>({domainName:r.DomainName,recordName:r.ResourceRecord.Name,recordType:r.ResourceRecord.Type,recordValue:r.ResourceRecord.Value}))}async requestCertificateWithSans(e){let t=new Set;if(t.add(e.DomainName),e.IncludeWww!==!1)t.add(`www.${e.DomainName}`);if(e.IncludeWildcard)t.add(`*.${e.DomainName}`);if(e.AdditionalSans)for(let r of e.AdditionalSans)t.add(r);return this.requestCertificate({DomainName:e.DomainName,SubjectAlternativeNames:Array.from(t),ValidationMethod:"DNS"})}async isCertificateValidForDomain(e,t){let r=await this.describeCertificate({CertificateArn:e});if(r.Status!=="ISSUED")return!1;if(r.DomainName===t)return!0;if(r.DomainName?.startsWith("*.")){let s=r.DomainName.slice(2),o=t.split("."),i=s.split(".");if(o.slice(-i.length).join(".")===s)return!0}if(r.SubjectAlternativeNames)for(let s of r.SubjectAlternativeNames){if(s===t)return!0;if(s.startsWith("*.")){let o=s.slice(2),i=t.split("."),a=o.split(".");if(i.slice(-a.length).join(".")===o)return!0}}return!1}}class or{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new ae(e),this.route53=new y,t&&t.provider!=="route53")this.dnsProvider=T(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s=[],waitForValidation:o=!1,maxWaitMinutes:i=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:a}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:s.length>0?[t,...s]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(a);let c=await this.acm.getDnsValidationRecords(a);if(this.dnsProvider)for(let d of c){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}else if(r)for(let d of c)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${d.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:d.recordName,Type:d.recordType,TTL:300,ResourceRecords:[{Value:d.recordValue}]}}]}});if(o){if(!await this.acm.waitForCertificateValidation(a,i*2,30000))throw Error(`Certificate validation timed out after ${i} minutes`)}return{certificateArn:a,validationRecords:c}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.getDnsValidationRecords(t),i=[];if(this.dnsProvider){let a=s||o[0]?.domainName;for(let c of o){let d=await this.dnsProvider.upsertRecord(a,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});i.push({...c,changeId:d.success?d.id:void 0})}}else if(r)for(let a of o){let c=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${a.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:a.recordName,Type:a.recordType,TTL:300,ResourceRecords:[{Value:a.recordValue}]}}]}});i.push({...a,changeId:c.ChangeInfo?.Id})}return i}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e,o=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let i=s||o[0]?.domainName;for(let a of o)try{await this.dnsProvider.deleteRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue})}catch{}}else if(r)for(let i of o)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${i.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:o=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let i=await this.acm.findCertificateByDomain(t);if(i&&i.Status==="ISSUED")return{certificateArn:i.CertificateArn,isNew:!1};let{certificateArn:a}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:o});return{certificateArn:a,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}class oe{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new ae(t),"provider"in e)this.dnsProvider=T(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!1,maxWaitMinutes:o=30}=e,{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);for(let d of a){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}let c="pending";if(s)c=(await this.acm.waitForCertificateValidation(i,o*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:i,validationRecords:a.map((d)=>({domainName:d.domainName,recordName:d.recordName,recordType:d.recordType,recordValue:d.recordValue})),isNew:!0,status:c}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],o=await this.acm.getDnsValidationRecords(t);for(let i of o){let a=await this.dnsProvider.upsertRecord(r,{name:i.recordName,type:i.recordType,content:i.recordValue,ttl:300});if(!a.success)s.push(`Failed to create record for ${i.domainName}: ${a.message}`)}return{success:s.length===0,records:o.map((i)=>({domainName:i.domainName,recordName:i.recordName,recordType:i.recordType,recordValue:i.recordValue})),errors:s}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],o=await this.acm.getDnsValidationRecords(t);for(let i of o){let a=await this.dnsProvider.deleteRecord(r,{name:i.recordName,type:i.recordType,content:i.recordValue});if(!a.success)s.push(`Failed to delete record for ${i.domainName}: ${a.message}`)}return{success:s.length===0,errors:s}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!0,maxWaitMinutes:o}=e,i=await this.acm.findCertificateByDomain(t);if(i&&i.Status==="ISSUED"){let a=i.SubjectAlternativeNames||[i.DomainName],c=a.some((u)=>u===`*.${t}`);if(r.every((u)=>a.includes(u)||c))return{certificateArn:i.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:t,subjectAlternativeNames:r,waitForValidation:s,maxWaitMinutes:o})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:s=!1,additionalSans:o=[],waitForValidation:i=!1}=e,a=[];if(r)a.push(`www.${t}`);if(s)a.push(`*.${t}`);return a.push(...o),this.requestAndValidate({domainName:t,subjectAlternativeNames:a,waitForValidation:i})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(e){let t=await this.acm.describeCertificate({CertificateArn:e});return{status:t.Status,domainValidations:(t.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function gs(e,t,r){return new oe({provider:"porkbun",apiKey:e,secretKey:t},r)}function ms(e,t,r,s){return new oe({provider:"godaddy",apiKey:e,apiSecret:t,environment:s},r)}function hs(e,t,r){return new oe({provider:"route53",region:e,hostedZoneId:t},r||e)}function T(e){switch(e.provider){case"route53":return new z(e.region,e.hostedZoneId);case"porkbun":return new se(e.apiKey,e.secretKey);case"godaddy":return new xe(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new fe(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}async function Ua(e,t){for(let r of t){let s=T(r);if(await s.canManageDomain(e))return s}return null}class yn{providers=new Map;configs=[];addConfig(e){return this.configs.push(e),this}addRoute53(e,t){return this.configs.push({provider:"route53",region:e,hostedZoneId:t}),this}addPorkbun(e,t){return this.configs.push({provider:"porkbun",apiKey:e,secretKey:t}),this}addGoDaddy(e,t,r){return this.configs.push({provider:"godaddy",apiKey:e,apiSecret:t,environment:r}),this}addCloudflare(e,t={}){return this.configs.push({provider:"cloudflare",apiToken:e,zoneId:t.zoneId,accountId:t.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let e=process.env.PORKBUN_API_KEY,t=process.env.PORKBUN_SECRET_KEY;if(e&&t)this.addPorkbun(e,t);let r=process.env.GODADDY_API_KEY,s=process.env.GODADDY_API_SECRET;if(r&&s){let i=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,s,i)}let o=process.env.CLOUDFLARE_API_TOKEN;if(o)this.addCloudflare(o,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(e){let t=this.providers.get(e);if(t)return t;let r=this.configs.find((o)=>o.provider===e);if(!r)return null;let s=T(r);return this.providers.set(e,s),s}async getProviderForDomain(e){for(let t of this.configs){let r=T(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>T(e))}}var Qa=new yn;
2
- export{tt,se,xe,su,hn,Ma,Fa,rs,fe,Tt,fn,ns,is,nr,ir,An,sr,ss,os,as,cs,z,ds,ls,us,ps,oe,gs,ms,hs,T,Ua,yn,Qa,ae,or};
1
+ import{n}from"./chunk-ss4q8kge.js";import{y}from"./chunk-emx1j2yt.js";var tt=new Set(["A","AAAA","CNAME"]);function Z(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 x(e,t){let r=t?.headers.get("retry-after"),s=r===null||r===void 0?void 0:Number(r)*1000,o=Number.isFinite(s)?Math.max(0,s):Math.min(1000*2**(e-1),30000);await new Promise((i)=>setTimeout(i,o))}class se{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(e,t,r=15000){this.apiKey=e,this.secretKey=t,this.requestTimeoutMs=r}async request(e,t={}){let r;for(let s=1;s<=8;s+=1){let o,i=new AbortController,a=setTimeout(()=>{i.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{o=await fetch(`https://api.porkbun.com/api/json/v3${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...t}),signal:i.signal})}catch(d){if(r=d,s===8)throw d;await x(s);continue}finally{clearTimeout(a)}if(!o.ok){let d=await o.clone().json().then((u)=>u?.message).catch(()=>{return});if(r=Error(`Porkbun API error: ${o.status} ${o.statusText}${d?`: ${d}`:""}`),!Z(o.status)||s===8)throw r;await x(s,o);continue}let c=await o.json();if(c.status==="ERROR"){if(r=Error(`Porkbun API error: ${c.message||"Unknown error"}`),!Z(0,c.message)||s===8)throw r;await x(s,o);continue}return c}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(e,t){if(!se.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${o.message??"unknown provider error"}`];let i=[];for(let a of o.records){if(a.type!=="ALIAS"&&a.type!=="CNAME")continue;if(this.getSubdomain(a.name,r)!==s)continue;let c=await this.deleteRecord(e,a);if(!c.success)i.push(`could not remove conflicting ${a.type} on ${a.name}: ${c.message??"unknown provider error"}`)}return i}async addressRecordExists(e,t){let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return!0;return o.records.some((i)=>i.type===t.type&&this.getSubdomain(i.name,r)===s&&i.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)o.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)o.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)o.content=`${t.weight} ${t.port} ${t.content}`;let i=await this.clearConflictingAliases(e,t),a=await this.request(`/dns/create/${r}`,o);if(se.ADDRESS_TYPES.has(t.type)&&!await this.addressRecordExists(e,t))return{success:!1,message:`Porkbun reported success but no ${t.type} record for ${t.name} exists${i.length>0?` (${i.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:a.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(o.success){let i=o.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type);if(i?.id&&i.content===t.content&&(t.ttl===void 0||i.ttl===t.ttl)&&(t.type!=="MX"&&t.type!=="SRV"||t.priority===void 0||i.priority===t.priority))return{success:!0,id:i.id,message:"Record already up to date"};if(i?.id){let a={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)a.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)a.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)a.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${i.id}`,a),{success:!0,id:i.id,message:"Record updated successfully"}}}return this.createRecord(e,t)}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e);if("id"in t&&t.id)return await this.request(`/dns/delete/${r}/${t.id}`),{success:!0,message:"Record deleted successfully"};let s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return{success:!1,message:"Failed to list records"};let i=o.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type&&a.content===t.content);if(!i?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${i.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/dns/retrieve/${r}`;if(t)s=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(s)).records||[]).map((a)=>({id:a.id,name:a.name||r,type:a.type,content:a.content,ttl:Number.parseInt(a.ttl,10),priority:a.prio?Number.parseInt(a.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request(`/dns/retrieve/${t}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((t)=>t.domain)}catch{return[]}}async getNameServers(e){try{let t=this.getRootDomain(e);return(await this.request(`/domain/getNs/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/domain/updateNs/${r}`,{ns:t}),!0}catch{return!1}}}class _e{name="godaddy";apiKey;apiSecret;baseUrl;constructor(e,t="",r="production"){this.apiKey=e,this.apiSecret=t,this.baseUrl=r==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}authorization(){if(!this.apiSecret||this.apiKey.startsWith("gd_pat_"))return`Bearer ${this.apiKey}`;return`sso-key ${this.apiKey}:${this.apiSecret}`}async request(e,t,r){let s=`${this.baseUrl}${t}`,o={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},i={method:e,headers:o};if(r)i.body=JSON.stringify(r);let a=await fetch(s,i);if(a.status===204)return{};if(a.ok){let d=await a.text();if(d)return JSON.parse(d);return{}}let c=`GoDaddy API error: ${a.status} ${a.statusText}`;try{let d=await a.json();if(d.message)c=`GoDaddy API error: ${d.message}`;if(d.fields)c+=` - Fields: ${JSON.stringify(d.fields)}`}catch{}throw Error(c)}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"@";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}toGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=this.getSubdomain(e.name,r),o={type:e.type,name:s,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)o.priority=e.priority;return o}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=e.name;if(s==="@")s=r;else if(!s.endsWith(r))s=`${s}.${r}`;return{name:s,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[s]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s.name}`,[s]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${s}`),i=o.filter((a)=>a.data!==t.content);if(i.length===o.length)return{success:!1,message:"Record not found"};if(i.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${s}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s}`,i);return{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/v1/domains/${r}/records`;if(t)s=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",s)).map((i)=>this.fromGoDaddyRecord(i,e))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request("GET",`/v1/domains/${t}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((t)=>t.domain)}catch{return[]}}async getDomainDetails(e){try{let t=this.getRootDomain(e),r=await this.request("GET",`/v1/domains/${t}`);return{domain:r.domain,status:r.status,nameServers:r.nameServers,expires:r.expires}}catch{return null}}async getNameServers(e){return(await this.getDomainDetails(e))?.nameServers??[]}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request("PATCH",`/v1/domains/${r}`,{nameServers:t}),!0}catch{return!1}}async checkDomainAvailability(e){try{let t=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(e)}`);return{available:t.available,price:t.price,currency:t.currency}}catch{return{available:!1}}}}var du=["js","mjs","cjs","css","map","woff","woff2","ttf","otf","eot","png","jpg","jpeg","gif","webp","avif","svg","ico","mp4","webm","ogg","mp3","wav","pdf","wasm"],F=[{name:"x-stx-router",value:"true"}];function S(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function M(e){return`{${e.map(S).join(" ")}}`}function G(e){let t=`http.request.headers[${S(e.name.toLowerCase())}]`;return e.value===void 0?`len(${t}) > 0`:`any(${t}[*] == ${S(e.value)})`}function fn(e){if(e.length===1)return`http.host eq ${S(e[0])}`;return`http.host in ${M(e)}`}function Ua(e,t={}){if(t.enabled===!1||e.length===0)return[];let r=fn(e),s=[],i=(t.bypassPaths??[]).map((A)=>`starts_with(http.request.uri.path, ${S(A)})`),c=(t.negotiatedRequestHeaders??F).map(G),d=[...i,...c],u=d.length>0?`(${d.join(" or ")})`:void 0;if(u)s.push({action:"set_cache_settings",description:"bypass cache",expression:`(${r} and ${u})`,enabled:!0,action_parameters:{cache:!1}});let p=u?`${r} and not ${u}`:r,m=t.assetExtensions??du,g=m.length>0?`lower(http.request.uri.path.extension) in ${M([...m])}`:void 0;if(g)s.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${p} and ${g})`,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.assetEdgeTtl??2592000},browser_ttl:{mode:"override_origin",default:t.assetBrowserTtl??31536000}}});let R=g?`(${p} and not ${g})`:`(${p})`;if(t.documentEdgeTtl===0)return s.push({action:"set_cache_settings",description:"bypass documents",expression:R,enabled:!0,action_parameters:{cache:!1}}),s;return s.push({action:"set_cache_settings",description:"cache documents",expression:R,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.documentEdgeTtl??3600},browser_ttl:{mode:"override_origin",default:t.documentBrowserTtl??0}}}),s}function Qa(e,t,r){if(e.length===0||!t||!r)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${fn(e)})`,enabled:!0,action_parameters:{headers:{[t]:{operation:"set",value:r}}}}]}var K="https://api.cloudflare.com/client/v4",is="[ts-cloud]";class Ae{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(e,t={}){this.apiToken=e,this.configuredZoneId=t.zoneId,this.accountId=t.accountId}async request(e,t,r){let s=`${K}${t}`,o={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},i={method:e,headers:o};if(r)i.body=JSON.stringify(r);let c=await(await fetch(s,i)).json();if(!c.success){let d=c.errors.map((u)=>u.message).join(", ");throw Error(`Cloudflare API error: ${d}`)}return c}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async resolveZone(e){let t=e.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let a=await this.resolveConfiguredZoneName();if(a&&(t===a||t.endsWith(`.${a}`)))return{id:this.configuredZoneId,name:a}}let r=this.getRootDomain(t),s=this.zoneCache.get(r);if(s)return{id:s,name:r};let o=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!o.result||o.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let i=o.result[0].id;return this.zoneCache.set(r,i),{id:i,name:o.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let t=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!t)return;return this.configuredZoneName=t,this.zoneCache.set(t,this.configuredZoneId),t}catch{return}}async getZoneId(e){return(await this.resolveZone(e)).id}getFullRecordName(e,t){let r=e.replace(/\.$/,"");if(!r||r===t||r==="@")return t;if(r.endsWith(`.${t}`))return r;return`${r}.${t}`}toCloudflareRecord(e,t,r){let s={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},o=r??e.proxied;if(o!==void 0&&tt.has(e.type)){if(s.proxied=o,o)s.ttl=1}if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;if(e.type==="SRV"){let i=X(e);if(i)s.data=i,delete s.content,delete s.priority;else if(e.priority!==void 0)s.priority=e.priority}return s}fromCloudflareRecord(e){return{id:e.id,name:e.name,type:e.type,content:e.content,ttl:e.ttl,priority:e.priority,proxied:e.proxied}}async createRecord(e,t){try{let r=await this.resolveZone(e),s=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,s)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.resolveZone(e),s=this.getFullRecordName(t.name,r.name),i=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`)).result?.[0],a=t.proxied??i?.proxied,c=this.toCloudflareRecord(t,r.name,a);if(i)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${i.id}`,c)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,c)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),s=r.id,o=this.getFullRecordName(t.name,r.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!i.result||i.result.length===0)return{success:!1,message:"Record not found"};let a=i.result.find((c)=>c.content===t.content);if(!a)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${s}/dns_records/${a.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let s=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)s+=`&type=${t}`;let o=[],i=1,a=!0;while(a){let c=await this.request("GET",`${s}&page=${i}`);if(o.push(...c.result||[]),c.result_info)a=i<c.result_info.total_pages,i++;else a=!1}return{success:!0,records:o.map((c)=>this.fromCloudflareRecord(c))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{return await this.getZoneId(e),!0}catch{return!1}}async listDomains(){try{let e=[],t=1,r=!0;while(r){let s=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...s.result||[]),s.result_info)r=t<s.result_info.total_pages,t++;else r=!1}return e.map((s)=>s.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),s=t.accountId??this.accountId;if(!s)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let o=await this.getZoneDetails(r);if(o)return{...o,created:!1};try{let a=(await this.request("POST","/zones",{name:r,account:{id:s},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(a.name,a.id),{id:a.id,name:a.name,status:a.status,nameServers:a.name_servers??[],created:!0}}catch(i){let a=i instanceof Error?i.message:String(i);if(!/already exists|1061/i.test(a))throw i;let c=await this.getZoneDetails(r);if(!c)throw i;return{...c,created:!1}}}async getZoneDetails(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}`);return{id:r.result.id,name:r.result.name,status:r.result.status,nameServers:r.result.name_servers,paused:r.result.paused}}catch{return null}}async listEdgeCertificateHosts(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/ssl/certificate_packs?per_page=50`),s=new Set;for(let o of r.result||[]){if(o.status!=="active")continue;for(let i of o.hosts||[])s.add(i.toLowerCase())}return[...s]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),s={};if(t?.purgeEverything)s.purge_everything=!0;else{if(t?.files)s.files=t.files;if(t?.tags)s.tags=t.tags;if(t?.hosts)s.hosts=t.hosts}if(Object.keys(s).length===0)s.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,s),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),s=r.id,o=this.getFullRecordName(t.name,r.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(i.result&&i.result.length>0)return i.result.find((c)=>c.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let s=await this.resolveZone(e),o=s.id,i=this.getFullRecordName(t.name,s.name),a=await this.request("GET",`/zones/${o}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);if(!a.result||a.result.length===0)return!1;let c=a.result.find((d)=>d.content===t.content);if(!c)return!1;return await this.request("PATCH",`/zones/${o}/dns_records/${c.id}`,{proxied:r}),!0}catch{return!1}}async zoneIdFor(e){return this.getZoneId(e)}get account(){return this.accountId}async getZoneSettings(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/settings`),s={};for(let o of r.result||[])s[o.id]=o.value;return s}async applyZoneSettings(e,t){let r=await this.getZoneId(e),s=await this.getZoneSettings(e).catch(()=>({})),o=[],i=[];for(let[a,c]of Object.entries(t)){if(c===void 0)continue;let d=s[a];if(d!==void 0&&k(d,c))continue;try{await this.request("PATCH",`/zones/${r}/settings/${a}`,{value:c}),o.push({id:a,from:d,to:c})}catch(u){i.push({id:a,error:u instanceof Error?u.message:String(u)})}}return{changed:o,failed:i}}async getManagedRequestHeaders(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/managed_headers`),s={};for(let o of r.result?.managed_request_headers||[])s[o.id]=o.enabled===!0;return s}async applyManagedRequestHeaders(e,t){let r=[],s=[],o=Object.entries(t).filter(([,d])=>d!==void 0);if(o.length===0)return{changed:r,failed:s};let i=await this.getZoneId(e),a;try{a=await this.getManagedRequestHeaders(e)}catch(d){let u=d instanceof Error?d.message:String(d);for(let[p]of o)s.push({id:p,error:`could not read managed headers — ${u}`});return{changed:r,failed:s}}let c=[];for(let[d,u]of o){if(!(d in a)){s.push({id:d,error:"not a managed request header transform on this zone"});continue}if(a[d]!==u)c.push([d,u])}if(c.length===0)return{changed:r,failed:s};try{await this.request("PATCH",`/zones/${i}/managed_headers`,{managed_request_headers:c.map(([d,u])=>({id:d,enabled:u})),managed_response_headers:[]});for(let[d,u]of c)r.push({id:d,from:a[d],to:u})}catch(d){let u=d instanceof Error?d.message:String(d);for(let[p]of c)s.push({id:p,error:u})}return{changed:r,failed:s}}async getPhaseRules(e,t){let r=await this.getZoneId(e);try{return(await this.request("GET",`/zones/${r}/rulesets/phases/${t}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(e,t,r){try{let s=await this.getZoneId(e),o=await this.getPhaseRules(e,t),i=r.map((d)=>({...d,description:d.description?.startsWith(is)?d.description:`${is} ${d.description||t}`})),c=W(o,i).map(({id:d,...u})=>u);return await this.request("PUT",`/zones/${s}/rulesets/phases/${t}/entrypoint`,{rules:c}),{success:!0}}catch(s){return{success:!1,message:s instanceof Error?s.message:String(s)}}}}var _=/http\.host (?:eq "[^"]+"|in \{[^}]*\})/;function O(e){return _.test(e)?e.replace(_,"\x00hosts\x00"):null}function q(e,t){return e.replace(_,fn(t))}function b(e){if(Array.isArray(e))return`[${e.map(b).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[s])=>r.localeCompare(s)).map(([r,s])=>`${JSON.stringify(r)}:${b(s)}`).join(",")}}`;return JSON.stringify(e)}function B(e,t){let r=O(e.expression);return r!==null&&r===O(t.expression)&&e.action===t.action&&e.description===t.description&&(e.enabled??!0)===(t.enabled??!0)&&b(e.action_parameters)===b(t.action_parameters)}function W(e,t){let r=new Set(t.flatMap((i)=>N(i.expression))),s=(i)=>(i.description||"").startsWith(is),o=[];for(let i of e){if(!s(i)){o.push(i);continue}let a=N(i.expression);if(a.length===0){if(r.size>0)o.push(i);continue}let c=a.filter((d)=>!r.has(d));if(c.length===a.length)o.push(i);else if(c.length>0)o.push({...i,expression:q(i.expression,c)})}for(let i of t){let a=N(i.expression),c=a.length>0?o.findIndex((p)=>s(p)&&B(p,i)):-1;if(c===-1){o.push(i);continue}let d=o[c],u=[...new Set([...N(d.expression),...a])];o[c]={...d,expression:q(d.expression,u)}}return o}function N(e){let t=[];for(let r of e.matchAll(/http\.host eq "([^"]+)"/g))t.push(r[1]);for(let r of e.matchAll(/http\.host in \{([^}]*)\}/g))for(let s of r[1].matchAll(/"([^"]+)"/g))t.push(s[1]);return t}function k(e,t){if(e===t)return!0;if(typeof e!==typeof t||e===null||t===null)return!1;if(typeof e!=="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;return e.every((o,i)=>k(o,t[i]))}let r=e,s=t;return Object.keys(s).every((o)=>k(r[o],s[o]))}function X(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:L(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[s,o,i]=r.slice(0,3).map(Number);if(![s,o,i].every(Number.isFinite))return null;return{priority:s,weight:o,port:i,target:L(r.slice(3).join(" "))}}function L(e){return e.replace(/\.$/,"")}var Y=new Set(["A","AAAA","CNAME","ALIAS"]);function Tt(e){let t=e.trim().replace(/^"|"$/g,"").toLowerCase();if(t.startsWith("v=spf1"))return"v=spf1";if(t.startsWith("v=dmarc1"))return"v=dmarc1";return}function D(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function w(e){return e.replace(/\.$/,"").toLowerCase()}function An(e,t){let r=w(t),s=(e??"@").trim();if(!s||s==="@")return r;let o=w(s);if(o===r||o.endsWith(`.${r}`))return o;return`${o}.${r}`}function ss(e,t){return e.map((r)=>({...r,name:An(r.name,t),proxied:r.proxied??!1}))}function J(e,t){if(e.type!==t.type)return!1;if(w(e.name)!==w(t.name))return!1;if(Y.has(t.type))return!0;if(t.type==="TXT"){let r=Tt(t.content);if(r)return Tt(D(e.content))===r;return D(e.content)===D(t.content)}return D(e.content)===D(t.content)}function Q(e,t){if(D(e.content)!==D(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 os(e){let{provider:t,zone:r,records:s}=e,o={outcomes:[],warnings:[]};if(s.length===0)return o;let i=await t.listRecords(r);if(!i.success)return o.warnings.push(`could not list ${r}: ${i.message||"unknown provider error"} — records not reconciled`),o;let a=i.records;for(let c of s){let d=a.filter((g)=>J(g,c));if(d.length>0&&d.every((g)=>Q(g,c))){o.outcomes.push({record:c,action:"unchanged"});continue}let u={name:c.name,type:c.type,content:c.content,ttl:c.ttl??3600,...c.priority!==void 0?{priority:c.priority}:{},...c.proxied!==void 0?{proxied:c.proxied}:{}},p=c.type==="TXT"&&Tt(c.content)!==void 0;if(p)for(let g of d){let R=await t.deleteRecord(r,{name:g.name,type:g.type,content:g.content});if(!R.success)o.warnings.push(`could not remove superseded ${g.type} at ${g.name}: ${R.message||"unknown error"}`)}let m=p||d.length===0?await t.createRecord(r,u):await t.upsertRecord(r,u);if(m.success)o.outcomes.push({record:c,action:d.length>0?"updated":"created"});else o.outcomes.push({record:c,action:"failed",message:m.message})}for(let c of["MX"]){let d=new Set(s.filter((u)=>u.type===c).map((u)=>w(u.name)));for(let u of d){let p=new Set(s.filter((g)=>g.type===c&&w(g.name)===u).map((g)=>D(g.content).toLowerCase())),m=a.filter((g)=>g.type===c&&w(g.name)===u&&!p.has(D(g.content).toLowerCase()));for(let g of m)o.warnings.push(`${u} has an undeclared ${c} record (${g.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return o}function nr(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.getNameServers==="function"&&typeof t.updateNameServers==="function"}function ir(e){return Boolean(e&&typeof e.createZone==="function")}var ee=new Set(["NS"]);function v(e){return e.replace(/\.$/,"").toLowerCase()}function yn(e,t){if(e.length===0||t.length===0)return!1;let r=new Set(e.map(v)),s=new Set(t.map(v));if(r.size!==s.size)return!1;for(let o of r)if(!s.has(o))return!1;return!0}function te(e){let t=e.content.trim(),r=t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t;return e.type==="TXT"?r:v(r)}var re=new Set(["MX","SRV"]),ne=new Set(["A","AAAA","CNAME"]);function P(e){let t=re.has(e.type)&&e.priority!==void 0&&e.priority!==null?String(Number(e.priority)):"";return`${e.type}|${v(e.name)}|${te(e)}|${t}`}function ie(e,t){return P(e)===P(t)}async function sr(e){let{domain:t,registrar:r,host:s,dryRun:o=!1}=e,i=new Set([...e.proxiedHosts??[]].map(v)),a=[],c=await s.createZone(t,{accountId:e.accountId,jumpStart:!1}),d=await r.getNameServers(t),u={status:"ready",domain:t,zoneId:c.id,targetNameservers:c.nameServers,currentNameservers:d,records:[],missing:[],warnings:a};if(yn(d,c.nameServers))return u.status="already-delegated",u;if(c.nameServers.length===0)return a.push(`${s.name} did not report nameservers for ${t}; cannot delegate.`),u.status="blocked",u;let p=await r.listRecords(t);if(!p.success)return a.push(`Could not read ${t} from ${r.name}: ${p.message??"unknown error"}`),u.status="blocked",u;let m=[];for(let l of p.records){if(ee.has(l.type)){u.records.push({record:l,status:"skipped",reason:`${l.type} describes the delegation itself; ${s.name} owns it`});continue}let f=tt.has(l.type)&&i.has(v(l.name));m.push({name:l.name,type:l.type,content:l.content,ttl:l.ttl,priority:l.priority,...tt.has(l.type)?{proxied:f}:{}})}if(o){for(let l of m)u.records.push({record:l,status:"copied",reason:"dry run"});return u}let g=new Map;for(let l of m){let f=`${l.type}|${v(l.name)}`;g.set(f,(g.get(f)??0)+1)}let R=new Set;try{let l=await s.listRecords(t);for(let f of l.records??[])R.add(P(f))}catch{}for(let l of m){let f=ne.has(l.type)&&g.get(`${l.type}|${v(l.name)}`)===1;if(!f&&R.has(P(l))){u.records.push({record:l,status:"present"});continue}let C;try{C=f?await s.upsertRecord(t,l):await s.createRecord(t,l)}catch(E){C={success:!1,message:E instanceof Error?E.message:String(E)}}if(C.success)R.add(P(l));u.records.push(C.success?{record:l,status:"copied"}:{record:l,status:"failed",reason:C.message})}let A=await s.listRecords(t);if(!A.success)return a.push(`Could not read back ${t} from ${s.name}: ${A.message??"unknown error"}`),u.status="blocked",u;for(let l of m)if(!A.records.some((f)=>ie(l,f)))u.missing.push(l);if(u.missing.length>0)return a.push(`${u.missing.length} record(s) did not arrive at ${s.name}; leaving ${r.name}'s nameservers alone. Delegating now would take the domain off a complete zone and onto an incomplete one.`),u.status="blocked",u;if(!await r.updateNameServers(t,c.nameServers))return a.push(`${r.name} refused the nameserver update for ${t}.`),u.status="blocked",u;return u.status="delegated",u}var ce={add_visitor_location_headers:"visitorLocationHeaders"};function U(e){return{porkbunApiKey:e.PORKBUN_API_KEY,porkbunSecretKey:e.PORKBUN_SECRET_KEY,godaddyApiKey:e.GODADDY_API_KEY,godaddyApiSecret:e.GODADDY_API_SECRET,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID}}function de(e,t){if(e==="porkbun"){if(!t.porkbunApiKey||!t.porkbunSecretKey)return"PORKBUN_API_KEY / PORKBUN_SECRET_KEY are not set";return new se(t.porkbunApiKey,t.porkbunSecretKey)}if(!t.godaddyApiKey||!t.godaddyApiSecret)return"GODADDY_API_KEY / GODADDY_API_SECRET are not set";let r=new _e(t.godaddyApiKey,t.godaddyApiSecret);if(!nr(r))return"the GoDaddy provider cannot change nameservers";return r}async function as(e,t={}){let r=e.registrar;if(!r)return{status:"skipped",reason:"no dns.registrar configured"};if(r.delegate===!1)return{status:"skipped",reason:"dns.registrar.delegate is false"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(!e.provider||e.provider===r.provider)return{status:"skipped",reason:`dns.provider is already ${r.provider}`};if(e.provider!=="cloudflare")return{status:"skipped",reason:`delegation to ${e.provider} is not supported yet`};let s=t.credentials??U(t.env??process.env);if(!s.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let o=de(r.provider,s);if(typeof o==="string")return{status:"skipped",reason:o};let i=new Ae(s.cloudflareApiToken,{accountId:s.cloudflareAccountId});if(!ir(i))return{status:"skipped",reason:"the Cloudflare provider cannot create zones"};return sr({domain:e.domain,registrar:o,host:i,proxiedHosts:r.proxied,accountId:s.cloudflareAccountId,dryRun:r.dryRun})}function cs(e){if(e.status==="skipped")return[`dns: delegation skipped — ${e.reason}`];let t=[];switch(e.status){case"already-delegated":t.push(`dns: ${e.domain} already delegated to ${e.targetNameservers.join(", ")}`);break;case"delegated":t.push(`dns: ${e.domain} delegated to ${e.targetNameservers.join(", ")} (${e.records.filter((r)=>r.status==="copied").length} record(s) copied)`),t.push("dns: nameserver changes take up to 24h to propagate; the old zone answers until then");break;case"ready":t.push(`dns: ${e.domain} would delegate to ${e.targetNameservers.join(", ")} (dry run)`);break;case"blocked":t.push(`dns: ${e.domain} NOT delegated — nameservers left at ${e.currentNameservers.join(", ")}`);for(let r of e.missing)t.push(` missing at destination: ${r.type} ${r.name}`);break}for(let r of e.warnings)t.push(` ${r}`);return t}function ue(e){let t={};if(e.ssl!==void 0)t.ssl=e.ssl;if(e.alwaysUseHttps!==void 0)t.always_use_https=e.alwaysUseHttps?"on":"off";if(e.minTlsVersion!==void 0)t.min_tls_version=e.minTlsVersion;return t}function le(e){let t={};for(let[r,s]of Object.entries(ce)){let o=e[s];if(typeof o==="boolean")t[r]=o}return t}async function ds(e,t={}){if(!e.zone)return{status:"skipped",reason:"no dns.zone configured"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(e.provider!=="cloudflare")return{status:"skipped",reason:`zone settings are not supported for ${e.provider??"this provider"}`};let r=ue(e.zone),s=le(e.zone);if(Object.keys(r).length===0&&Object.keys(s).length===0)return{status:"skipped",reason:"dns.zone declares no settings"};let o=t.credentials??U(t.env??process.env);if(!o.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let i=new Ae(o.cloudflareApiToken,{accountId:o.cloudflareAccountId}),a=await i.applyZoneSettings(e.domain,r),c=Object.keys(s).length>0?await i.applyManagedRequestHeaders(e.domain,s):{changed:[],failed:[]},d=[...a.changed,...c.changed],u=[...a.failed,...c.failed];return{status:d.length>0?"applied":"unchanged",domain:e.domain,changed:d,failed:u}}function ls(e){if(e.status==="skipped")return[`dns: zone settings skipped — ${e.reason}`];let t=[];for(let r of e.changed)t.push(`dns: ${e.domain} ${r.id}: ${String(r.from)} → ${String(r.to)}`);if(e.status==="unchanged"&&e.failed.length===0)t.push(`dns: ${e.domain} zone settings already as declared`);for(let r of e.failed)t.push(`dns: ${e.domain} could not set ${r.id} — ${r.error}`);return t}class z{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new y(e),this.providedHostedZoneId=t}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async getHostedZoneId(e){if(this.providedHostedZoneId)return this.providedHostedZoneId;let t=this.getRootDomain(e),r=this.hostedZoneCache.get(t);if(r)return r;let s=await this.client.findHostedZoneForDomain(e);if(s){let o=s.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,o),o}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(!s||s==="@")return`${r}.`;if(s===r||s.endsWith(`.${r}`))return`${s}.`;return`${s}.${r}.`}formatValue(e){let t=e.content;if(e.type==="TXT"&&!t.startsWith('"'))t=ge(t);if(e.type==="MX"&&e.priority!==void 0)t=`${e.priority} ${t}`;return t}sameValue(e,t,r){return e==="TXT"?V(t)===V(r):t===r}async currentSet(e,t,r){let o=(await this.client.listResourceRecordSets({HostedZoneId:e,StartRecordName:t,StartRecordType:r,MaxItems:"1"})).ResourceRecordSets?.[0];if(!o||o.Name.toLowerCase()!==t.toLowerCase()||o.Type!==r||o.AliasTarget||o.SetIdentifier)return null;return{ttl:o.TTL??300,values:(o.ResourceRecords??[]).map((i)=>i.Value)}}async createRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),o=this.formatValue(t),i=await this.currentSet(r,s,t.type);if(i?.values.some((d)=>this.sameValue(t.type,d,o)))return{success:!0,message:"Record already present"};let a=[...i?.values??[],o];return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:i?"UPSERT":"CREATE",ResourceRecordSet:{Name:s,Type:t.type,TTL:i?.ttl??t.ttl??300,ResourceRecords:a.map((d)=>({Value:d}))}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),o=this.formatValue(t);return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),o=this.formatValue(t),i=await this.currentSet(r,s,t.type);if(!i||!i.values.some((c)=>this.sameValue(t.type,c,o)))return{success:!0,message:"Record already absent"};let a=i.values.filter((c)=>!this.sameValue(t.type,c,o));return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:a.length>0?"UPSERT":"DELETE",ResourceRecordSet:{Name:s,Type:t.type,TTL:i.ttl,ResourceRecords:(a.length>0?a:i.values).map((c)=>({Value:c}))}}]}}),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,records:[],message:`No hosted zone found for domain: ${e}`};let s=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),o=[];for(let i of s.ResourceRecordSets){if(t&&i.Type!==t)continue;if(i.AliasTarget)continue;for(let a of i.ResourceRecords||[]){let c=a.Value,d;if(i.Type==="MX"){let u=c.split(" ");if(u.length>=2)d=Number.parseInt(u[0],10),c=u.slice(1).join(" ")}if(i.Type==="TXT"&&c.startsWith('"'))c=V(c);o.push({name:i.Name.replace(/\.$/,""),type:i.Type,content:c,ttl:i.TTL,priority:d})}}return{success:!0,records:o}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){return await this.getHostedZoneId(e)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((t)=>t.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(e){try{let t=await this.getHostedZoneId(e.domain);if(!t)return{success:!1,message:`No hosted zone found for domain: ${e.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:t,Name:this.normalizeName(e.domain,e.name),TargetHostedZoneId:e.targetHostedZoneId,TargetDNSName:e.targetDnsName,EvaluateTargetHealth:e.evaluateTargetHealth,Type:e.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(t){return{success:!1,message:t instanceof Error?t.message:"Unknown error"}}}async createCloudFrontAlias(e){return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:y.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=y.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})}}var j=255;function ge(e){let t=[];for(let r=0;r<e.length;r+=j)t.push(e.slice(r,r+j));if(t.length===0)t.push("");return t.map((r)=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`).join(" ")}function V(e){if(!e.startsWith('"'))return e;let t="",r=!1;for(let s=0;s<e.length;s++){let o=e[s];if(!r){if(o==='"')r=!0;continue}if(o==="\\"&&s+1<e.length){t+=e[++s];continue}if(o==='"'){r=!1;continue}t+=o}return t}async function us(e,t){let r=[],s,o;for(;;){let i=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:s,StartRecordType:o,MaxItems:"100"});if(r.push(...i.ResourceRecordSets),!i.IsTruncated)break;if(s=i.NextRecordName,o=i.NextRecordType,!s)break}return r}function h(e){return e.replace(/\.$/,"").toLowerCase()}function H(e){return e.replace(/\.$/,"")}function I(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${H(e.content)}`;return H(e.content)}function pe(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function ps(e,t){let r=h(t),s=[],o=[],i=[],a=new Set;for(let c of e){let d=h(c.Name),u=c.Type;if(u==="SOA"||u==="NS"&&d===r){o.push({name:d,type:u,reason:"owned by the destination provider"});continue}if(c.SetIdentifier){o.push({name:d,type:u,reason:`routing policy record (SetIdentifier=${c.SetIdentifier}) has no equivalent — recreate by hand`}),i.push(`${u} ${d} is part of a Route53 routing policy and was NOT migrated`);continue}if(c.AliasTarget){if(a.has(d))continue;a.add(d);let p=h(c.AliasTarget.DNSName);if(s.push({name:d,type:"CNAME",content:p,ttl:300,translatedFrom:`${u} ALIAS → ${p}`}),c.AliasTarget.EvaluateTargetHealth)i.push(`${d} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let p of c.ResourceRecords||[]){let m=me(d,u,p.Value,c.TTL);if("reason"in m){o.push({name:d,type:u,reason:m.reason}),i.push(`${u} ${d}: ${m.reason}`);continue}s.push(m)}}return{zone:r,records:s,skipped:o,warnings:i}}function me(e,t,r,s){let o={name:e,ttl:s};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...o,type:t==="PTR"?"CNAME":t,content:h(r)};case"TXT":return{...o,type:"TXT",content:pe(r)};case"MX":{let[i,...a]=r.trim().split(/\s+/);if(!a.length)return{reason:`malformed MX value "${r}"`};return{...o,type:"MX",content:h(a.join(" ")),priority:Number(i)}}case"SRV":{let i=r.trim().split(/\s+/);if(i.length<4)return{reason:`malformed SRV value "${r}"`};let[a,c,d]=i.slice(0,3).map(Number);return{...o,type:"SRV",content:h(i.slice(3).join(" ")),priority:a,weight:c,port:d}}case"NS":return{...o,type:"NS",content:h(r)};case"CAA":return{...o,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var fe=new Set(["TXT","MX","SRV","NS","CAA"]);async function gs(e,t){let r=[],s=[],o=new Set;try{let i=await e.listRecords(t.zone);for(let a of i.records||[])o.add(`${h(a.name)}|${a.type}|${I(a)}`)}catch{}for(let i of t.records){let a={...i,proxied:!1},c=`${h(i.name)}|${i.type}|${I(i)}`;if(!fe.has(i.type)){let u=await e.upsertRecord(t.zone,a);if(u.success)r.push(i);else s.push({record:i,message:u.message||"unknown provider error"});continue}if(o.has(c)){r.push(i);continue}let d=await e.createRecord(t.zone,a);if(d.success)o.add(c),r.push(i);else s.push({record:i,message:d.message||"unknown provider error"})}return{applied:r,failed:s}}async function ms(e,t){let r=await e.listRecords(t.zone),s=[],o=[],i=new Map;for(let a of r.records||[]){let c=`${h(a.name)}|${a.type}`,d=i.get(c)??[];d.push(I(a)),i.set(c,d)}for(let a of t.records){let c=i.get(`${h(a.name)}|${a.type}`),d=I(a);if(c?.some((u)=>u===d))s.push(a);else o.push({record:a,found:c?.join(", ")})}return{matched:s,missing:o,ok:o.length===0}}class ae{client;region;constructor(e="us-east-1"){this.client=new n,this.region=e}async requestCertificate(e){let t={DomainName:e.DomainName,ValidationMethod:e.ValidationMethod||"DNS"};if(e.SubjectAlternativeNames)t.SubjectAlternativeNames=e.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(t)})).CertificateArn||""}}async describeCertificate(e){let r=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Certificate||{};return{CertificateArn:r.CertificateArn||"",DomainName:r.DomainName||"",SubjectAlternativeNames:r.SubjectAlternativeNames,Status:r.Status||"PENDING_VALIDATION",Type:r.Type,DomainValidationOptions:r.DomainValidationOptions?.map((s)=>({DomainName:s.DomainName,ValidationDomain:s.ValidationDomain,ValidationStatus:s.ValidationStatus,ResourceRecord:s.ResourceRecord?{Name:s.ResourceRecord.Name,Type:s.ResourceRecord.Type,Value:s.ResourceRecord.Value}:void 0,ValidationMethod:s.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(e){let t={};if(e?.CertificateStatuses)t.CertificateStatuses=e.CertificateStatuses;if(e?.MaxItems)t.MaxItems=e.MaxItems;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(t)});return{CertificateSummaryList:(r.CertificateSummaryList||[]).map((s)=>({CertificateArn:s.CertificateArn,DomainName:s.DomainName})),NextToken:r.NextToken}}async deleteCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})}async listTagsForCertificate(e){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Tags||[]}}async addTagsToCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn,Tags:e.Tags})})}async resendValidationEmail(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:e.CertificateArn,Domain:e.Domain,ValidationDomain:e.ValidationDomain})})}async findCertificateByDomain(e){let r=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((s)=>s.DomainName===e||s.DomainName===`*.${e.split(".").slice(1).join(".")}`);if(!r)return null;return this.describeCertificate({CertificateArn:r.CertificateArn})}async waitForCertificateValidation(e,t=60,r=30000){for(let s=0;s<t;s++){let o=await this.describeCertificate({CertificateArn:e});if(o.Status==="ISSUED")return o;if(o.Status==="FAILED"||o.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((i)=>setTimeout(i,r))}return null}async getDnsValidationRecords(e){let t=await this.describeCertificate({CertificateArn:e});if(!t.DomainValidationOptions)return[];return t.DomainValidationOptions.filter((r)=>r.ResourceRecord&&r.ValidationMethod==="DNS").map((r)=>({domainName:r.DomainName,recordName:r.ResourceRecord.Name,recordType:r.ResourceRecord.Type,recordValue:r.ResourceRecord.Value}))}async requestCertificateWithSans(e){let t=new Set;if(t.add(e.DomainName),e.IncludeWww!==!1)t.add(`www.${e.DomainName}`);if(e.IncludeWildcard)t.add(`*.${e.DomainName}`);if(e.AdditionalSans)for(let r of e.AdditionalSans)t.add(r);return this.requestCertificate({DomainName:e.DomainName,SubjectAlternativeNames:Array.from(t),ValidationMethod:"DNS"})}async isCertificateValidForDomain(e,t){let r=await this.describeCertificate({CertificateArn:e});if(r.Status!=="ISSUED")return!1;if(r.DomainName===t)return!0;if(r.DomainName?.startsWith("*.")){let s=r.DomainName.slice(2),o=t.split("."),i=s.split(".");if(o.slice(-i.length).join(".")===s)return!0}if(r.SubjectAlternativeNames)for(let s of r.SubjectAlternativeNames){if(s===t)return!0;if(s.startsWith("*.")){let o=s.slice(2),i=t.split("."),a=o.split(".");if(i.slice(-a.length).join(".")===o)return!0}}return!1}}class or{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new ae(e),this.route53=new y,t&&t.provider!=="route53")this.dnsProvider=T(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s=[],waitForValidation:o=!1,maxWaitMinutes:i=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:a}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:s.length>0?[t,...s]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(a);let c=await this.acm.getDnsValidationRecords(a);if(this.dnsProvider)for(let d of c){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}else if(r)for(let d of c)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${d.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:d.recordName,Type:d.recordType,TTL:300,ResourceRecords:[{Value:d.recordValue}]}}]}});if(o){if(!await this.acm.waitForCertificateValidation(a,i*2,30000))throw Error(`Certificate validation timed out after ${i} minutes`)}return{certificateArn:a,validationRecords:c}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.getDnsValidationRecords(t),i=[];if(this.dnsProvider){let a=s||o[0]?.domainName;for(let c of o){let d=await this.dnsProvider.upsertRecord(a,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});i.push({...c,changeId:d.success?d.id:void 0})}}else if(r)for(let a of o){let c=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${a.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:a.recordName,Type:a.recordType,TTL:300,ResourceRecords:[{Value:a.recordValue}]}}]}});i.push({...a,changeId:c.ChangeInfo?.Id})}return i}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e,o=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let i=s||o[0]?.domainName;for(let a of o)try{await this.dnsProvider.deleteRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue})}catch{}}else if(r)for(let i of o)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${i.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:o=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let i=await this.acm.findCertificateByDomain(t);if(i&&i.Status==="ISSUED")return{certificateArn:i.CertificateArn,isNew:!1};let{certificateArn:a}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:o});return{certificateArn:a,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}class oe{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new ae(t),"provider"in e)this.dnsProvider=T(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!1,maxWaitMinutes:o=30}=e,{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);for(let d of a){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}let c="pending";if(s)c=(await this.acm.waitForCertificateValidation(i,o*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:i,validationRecords:a.map((d)=>({domainName:d.domainName,recordName:d.recordName,recordType:d.recordType,recordValue:d.recordValue})),isNew:!0,status:c}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],o=await this.acm.getDnsValidationRecords(t);for(let i of o){let a=await this.dnsProvider.upsertRecord(r,{name:i.recordName,type:i.recordType,content:i.recordValue,ttl:300});if(!a.success)s.push(`Failed to create record for ${i.domainName}: ${a.message}`)}return{success:s.length===0,records:o.map((i)=>({domainName:i.domainName,recordName:i.recordName,recordType:i.recordType,recordValue:i.recordValue})),errors:s}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],o=await this.acm.getDnsValidationRecords(t);for(let i of o){let a=await this.dnsProvider.deleteRecord(r,{name:i.recordName,type:i.recordType,content:i.recordValue});if(!a.success)s.push(`Failed to delete record for ${i.domainName}: ${a.message}`)}return{success:s.length===0,errors:s}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!0,maxWaitMinutes:o}=e,i=await this.acm.findCertificateByDomain(t);if(i&&i.Status==="ISSUED"){let a=i.SubjectAlternativeNames||[i.DomainName],c=a.some((u)=>u===`*.${t}`);if(r.every((u)=>a.includes(u)||c))return{certificateArn:i.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:t,subjectAlternativeNames:r,waitForValidation:s,maxWaitMinutes:o})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:s=!1,additionalSans:o=[],waitForValidation:i=!1}=e,a=[];if(r)a.push(`www.${t}`);if(s)a.push(`*.${t}`);return a.push(...o),this.requestAndValidate({domainName:t,subjectAlternativeNames:a,waitForValidation:i})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(e){let t=await this.acm.describeCertificate({CertificateArn:e});return{status:t.Status,domainValidations:(t.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function hs(e,t,r){return new oe({provider:"porkbun",apiKey:e,secretKey:t},r)}function fs(e,t,r,s){return new oe({provider:"godaddy",apiKey:e,apiSecret:t,environment:s},r)}function As(e,t,r){return new oe({provider:"route53",region:e,hostedZoneId:t},r||e)}function T(e){switch(e.provider){case"route53":return new z(e.region,e.hostedZoneId);case"porkbun":return new se(e.apiKey,e.secretKey);case"godaddy":return new _e(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new Ae(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}async function Ha(e,t){for(let r of t){let s=T(r);if(await s.canManageDomain(e))return s}return null}class In{providers=new Map;configs=[];addConfig(e){return this.configs.push(e),this}addRoute53(e,t){return this.configs.push({provider:"route53",region:e,hostedZoneId:t}),this}addPorkbun(e,t){return this.configs.push({provider:"porkbun",apiKey:e,secretKey:t}),this}addGoDaddy(e,t,r){return this.configs.push({provider:"godaddy",apiKey:e,apiSecret:t,environment:r}),this}addCloudflare(e,t={}){return this.configs.push({provider:"cloudflare",apiToken:e,zoneId:t.zoneId,accountId:t.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let e=process.env.PORKBUN_API_KEY,t=process.env.PORKBUN_SECRET_KEY;if(e&&t)this.addPorkbun(e,t);let r=process.env.GODADDY_API_KEY,s=process.env.GODADDY_API_SECRET;if(r&&s){let i=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,s,i)}let o=process.env.CLOUDFLARE_API_TOKEN;if(o)this.addCloudflare(o,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(e){let t=this.providers.get(e);if(t)return t;let r=this.configs.find((o)=>o.provider===e);if(!r)return null;let s=T(r);return this.providers.set(e,s),s}async getProviderForDomain(e){for(let t of this.configs){let r=T(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>T(e))}}var Ga=new In;
2
+ export{tt,se,_e,du,fn,Ua,Qa,is,Ae,Tt,An,ss,os,nr,ir,yn,sr,as,cs,ds,ls,z,us,ps,gs,ms,oe,hs,fs,As,T,Ha,In,Ga,ae,or};