@stacksjs/ts-cloud 0.16.32 → 0.16.33

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 (184) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/chunk-0e7bcz1c.js +3 -0
  3. package/dist/bin/{chunk-6wz04wnk.js → chunk-0wtnhxdt.js} +1 -1
  4. package/dist/bin/{chunk-zhkbdsfs.js → chunk-1ye6ky7s.js} +1 -1
  5. package/dist/bin/chunk-2njcbs0c.js +1 -0
  6. package/dist/bin/chunk-35ct309x.js +1 -0
  7. package/dist/bin/{chunk-mpq5ct10.js → chunk-3kyny1x7.js} +4 -4
  8. package/dist/bin/chunk-3ybxaehy.js +1 -0
  9. package/dist/bin/{chunk-zk3nm0td.js → chunk-47q37egd.js} +3 -3
  10. package/dist/bin/{chunk-yccdr4be.js → chunk-49y286vw.js} +1 -1
  11. package/dist/bin/{chunk-py8cvqvx.js → chunk-4c4s5yph.js} +1 -1
  12. package/dist/bin/{chunk-x56s9b7f.js → chunk-4vbnagyd.js} +1 -1
  13. package/dist/bin/{chunk-kqf19j9m.js → chunk-59f6mqkj.js} +1 -1
  14. package/dist/bin/chunk-5p9jnpg2.js +1 -0
  15. package/dist/bin/{chunk-573red0g.js → chunk-5tfxp3d9.js} +6 -6
  16. package/dist/bin/{chunk-q6z8wvvb.js → chunk-66g6jdgy.js} +3 -3
  17. package/dist/bin/{chunk-tg45thhb.js → chunk-70w9nss5.js} +1 -1
  18. package/dist/bin/{chunk-jzby2kzy.js → chunk-7k52s3qm.js} +2 -2
  19. package/dist/bin/{chunk-6yr12f64.js → chunk-7kjy2hng.js} +5 -5
  20. package/dist/bin/{chunk-9e62z9je.js → chunk-7x727gt5.js} +2 -2
  21. package/dist/bin/{chunk-f7dtn45y.js → chunk-8ba9t3hv.js} +3 -3
  22. package/dist/bin/chunk-9aram0sm.js +1 -0
  23. package/dist/bin/{chunk-tgwx5haz.js → chunk-a1zagtx1.js} +2 -2
  24. package/dist/bin/chunk-axwpxssn.js +1 -0
  25. package/dist/bin/chunk-c5qbz7ym.js +1 -0
  26. package/dist/bin/chunk-cqc4pc2h.js +1 -0
  27. package/dist/bin/chunk-d0xz1vh3.js +1 -0
  28. package/dist/bin/chunk-d2wm1zy3.js +1 -0
  29. package/dist/bin/{chunk-gcm9n6ww.js → chunk-dgad3hwh.js} +9 -9
  30. package/dist/bin/{chunk-81mt497w.js → chunk-hbrb314y.js} +1 -1
  31. package/dist/bin/chunk-hnwdjkrt.js +1 -0
  32. package/dist/bin/{chunk-kgtzvh2k.js → chunk-hpzbvc4a.js} +1 -1
  33. package/dist/bin/chunk-hrvfz72e.js +1 -0
  34. package/dist/bin/{chunk-sdy79wz7.js → chunk-hs5a6dhm.js} +4 -4
  35. package/dist/bin/chunk-j4d7h8rh.js +1 -0
  36. package/dist/bin/{chunk-yqkdyf0w.js → chunk-jsncf48k.js} +2 -2
  37. package/dist/bin/chunk-k178k5re.js +1 -0
  38. package/dist/bin/chunk-k5h2a7a8.js +1 -0
  39. package/dist/bin/{chunk-b9psp74n.js → chunk-kzh4csxz.js} +19 -19
  40. package/dist/bin/{chunk-0sht4yfg.js → chunk-mb2fh91q.js} +2 -2
  41. package/dist/bin/chunk-mzzrnkk5.js +9 -0
  42. package/dist/bin/{chunk-8mgwqpmx.js → chunk-nnxkw5pn.js} +2 -2
  43. package/dist/bin/{chunk-6k5g8b1w.js → chunk-nw8wmbmq.js} +2 -2
  44. package/dist/bin/chunk-prz0w9pq.js +1 -0
  45. package/dist/bin/chunk-rhjjdhhq.js +1 -0
  46. package/dist/bin/{chunk-fpxb97q5.js → chunk-rkd3x7fw.js} +1 -1
  47. package/dist/bin/chunk-rv7epkg1.js +1 -0
  48. package/dist/bin/{chunk-79sd00d1.js → chunk-s38txg38.js} +1 -1
  49. package/dist/bin/{chunk-qe56mnjc.js → chunk-s6qnx8a8.js} +2 -2
  50. package/dist/bin/{chunk-nnawqw34.js → chunk-sfb9q18c.js} +102 -102
  51. package/dist/bin/{chunk-8d8tdhtx.js → chunk-szpqbbyr.js} +4 -4
  52. package/dist/bin/chunk-tftcv9rt.js +1 -0
  53. package/dist/bin/{chunk-jhp53qsd.js → chunk-v0va4547.js} +2 -2
  54. package/dist/bin/{chunk-efbmb8rw.js → chunk-wc5swv1a.js} +1 -1
  55. package/dist/bin/{chunk-985ev3ns.js → chunk-wef81maa.js} +1 -1
  56. package/dist/bin/{chunk-vhz2wmb8.js → chunk-wq4hkbgj.js} +64 -64
  57. package/dist/bin/chunk-yd2155bj.js +1 -0
  58. package/dist/bin/chunk-yqefsck4.js +1 -0
  59. package/dist/bin/chunk-yzyt35ys.js +1 -0
  60. package/dist/bin/cli.js +45 -45
  61. package/dist/bin/dashboard-server.js +1 -1
  62. package/dist/{chunk-r45340yc.js → chunk-0pe1dfy0.js} +80 -80
  63. package/dist/{chunk-peeqkk92.js → chunk-29dcfx1g.js} +73 -73
  64. package/dist/{chunk-57fhsqzb.js → chunk-444h366b.js} +2 -2
  65. package/dist/{chunk-qrs912nk.js → chunk-45116tdd.js} +1 -1
  66. package/dist/chunk-4nfjkggt.js +1 -0
  67. package/dist/{chunk-kavwrxm8.js → chunk-6n72pe9x.js} +2 -2
  68. package/dist/{chunk-3harnmd6.js → chunk-7r2qc39k.js} +2 -2
  69. package/dist/chunk-8nafnyax.js +1 -0
  70. package/dist/{chunk-nq51dyxz.js → chunk-9r32w840.js} +12 -12
  71. package/dist/{chunk-xbh2vr95.js → chunk-c4kferxw.js} +95 -95
  72. package/dist/{chunk-ffxcn7mw.js → chunk-c6nw88s3.js} +1 -1
  73. package/dist/{chunk-10asqy6j.js → chunk-e08h4q50.js} +2 -2
  74. package/dist/chunk-e3831mvy.js +1 -0
  75. package/dist/{chunk-m93g67j0.js → chunk-g3f3ccdw.js} +2 -2
  76. package/dist/{chunk-9g8as6sa.js → chunk-jp57js5y.js} +1 -1
  77. package/dist/{chunk-efssa93f.js → chunk-k3azr9e3.js} +3 -3
  78. package/dist/{chunk-4hdp9ms2.js → chunk-m1jp1abp.js} +1 -1
  79. package/dist/{chunk-qjxdhb8x.js → chunk-n4gkyye3.js} +1 -1
  80. package/dist/{chunk-2mw7bjhn.js → chunk-nmm287ym.js} +3 -3
  81. package/dist/{chunk-s909414m.js → chunk-pkpmz35j.js} +1 -1
  82. package/dist/{chunk-t1gts5j9.js → chunk-qad1mjmc.js} +6 -6
  83. package/dist/{chunk-m5vwh9tb.js → chunk-s958jt49.js} +1 -1
  84. package/dist/{chunk-89rs2afj.js → chunk-tzvtq055.js} +1 -1
  85. package/dist/{chunk-wbabf3hg.js → chunk-v1wqxgra.js} +1 -1
  86. package/dist/{chunk-zesd879q.js → chunk-v9t4751b.js} +2 -2
  87. package/dist/{chunk-dm4vt53n.js → chunk-wctam3r1.js} +1 -1
  88. package/dist/chunk-xask9f1n.js +1 -0
  89. package/dist/chunk-xrr334m5.js +1 -0
  90. package/dist/{chunk-jh38v9zp.js → chunk-y3dj8xwk.js} +1 -1
  91. package/dist/{chunk-4jgy95bv.js → chunk-y3h0ybmn.js} +19 -19
  92. package/dist/deploy/index.js +1 -1
  93. package/dist/dns/index.js +1 -1
  94. package/dist/drivers/index.js +1 -1
  95. package/dist/drivers/shared/compute-ops.d.ts +1 -0
  96. package/dist/drivers/shared/releases.d.ts +43 -16
  97. package/dist/index.js +5 -5
  98. package/dist/operations/index.js +1 -1
  99. package/dist/protection/index.js +1 -1
  100. package/dist/spend/index.js +1 -1
  101. package/dist/ui/404.html +1 -1
  102. package/dist/ui/accept-invitation.html +1 -1
  103. package/dist/ui/access-denied.html +1 -1
  104. package/dist/ui/account/automation.html +6 -6
  105. package/dist/ui/account/security.html +2 -2
  106. package/dist/ui/applications/compose.html +6 -6
  107. package/dist/ui/applications/new.html +2 -2
  108. package/dist/ui/data/backups.html +6 -6
  109. package/dist/ui/data/services.html +6 -6
  110. package/dist/ui/data/volumes.html +6 -6
  111. package/dist/ui/index.html +6 -6
  112. package/dist/ui/infrastructure/topology.html +6 -6
  113. package/dist/ui/integrations.html +2 -2
  114. package/dist/ui/operations/alerts.html +6 -6
  115. package/dist/ui/operations/configuration.html +6 -6
  116. package/dist/ui/operations/jobs.html +6 -6
  117. package/dist/ui/operations/maintenance.html +6 -6
  118. package/dist/ui/operations/observability.html +6 -6
  119. package/dist/ui/operations/previews.html +6 -6
  120. package/dist/ui/operations/queue.html +5 -5
  121. package/dist/ui/operations/regions.html +6 -6
  122. package/dist/ui/operations/releases.html +6 -6
  123. package/dist/ui/operations/spend.html +6 -6
  124. package/dist/ui/operations/workloads.html +5 -5
  125. package/dist/ui/security.html +2 -2
  126. package/dist/ui/server/actions.html +6 -6
  127. package/dist/ui/server/activity.html +1 -1
  128. package/dist/ui/server/capacity.html +6 -6
  129. package/dist/ui/server/database.html +5 -5
  130. package/dist/ui/server/deployments.html +5 -5
  131. package/dist/ui/server/diagnostics.html +1 -1
  132. package/dist/ui/server/firewall.html +5 -5
  133. package/dist/ui/server/fleet.html +5 -5
  134. package/dist/ui/server/logs.html +6 -6
  135. package/dist/ui/server/metrics.html +5 -5
  136. package/dist/ui/server/security.html +1 -1
  137. package/dist/ui/server/services.html +2 -2
  138. package/dist/ui/server/sites.html +5 -5
  139. package/dist/ui/server/ssh-keys.html +6 -6
  140. package/dist/ui/server/team.html +6 -6
  141. package/dist/ui/server/terminal.html +2 -2
  142. package/dist/ui/serverless/alarms.html +6 -6
  143. package/dist/ui/serverless/assets.html +2 -2
  144. package/dist/ui/serverless/cost.html +2 -2
  145. package/dist/ui/serverless/data.html +6 -6
  146. package/dist/ui/serverless/deployments.html +2 -2
  147. package/dist/ui/serverless/firewall.html +1 -1
  148. package/dist/ui/serverless/functions.html +6 -6
  149. package/dist/ui/serverless/logs.html +6 -6
  150. package/dist/ui/serverless/metrics.html +2 -2
  151. package/dist/ui/serverless/queues.html +6 -6
  152. package/dist/ui/serverless/secrets.html +5 -5
  153. package/dist/ui/serverless/traces.html +6 -6
  154. package/dist/ui/serverless.html +5 -5
  155. package/package.json +3 -3
  156. package/dist/bin/chunk-12j17qm5.js +0 -1
  157. package/dist/bin/chunk-24473jks.js +0 -1
  158. package/dist/bin/chunk-3932p1z3.js +0 -1
  159. package/dist/bin/chunk-3eztnxgw.js +0 -1
  160. package/dist/bin/chunk-4182gadf.js +0 -1
  161. package/dist/bin/chunk-4er4ktcs.js +0 -1
  162. package/dist/bin/chunk-9eq18gds.js +0 -1
  163. package/dist/bin/chunk-9zhp2z0s.js +0 -1
  164. package/dist/bin/chunk-bmmr5mq6.js +0 -1
  165. package/dist/bin/chunk-cr56pxpt.js +0 -1
  166. package/dist/bin/chunk-dvv2z19r.js +0 -1
  167. package/dist/bin/chunk-eyrmv6c4.js +0 -1
  168. package/dist/bin/chunk-fnnv0t66.js +0 -1
  169. package/dist/bin/chunk-fwmje99n.js +0 -1
  170. package/dist/bin/chunk-gzxpkk0c.js +0 -3
  171. package/dist/bin/chunk-n775dk3f.js +0 -1
  172. package/dist/bin/chunk-ppj604c9.js +0 -1
  173. package/dist/bin/chunk-prq5gw4j.js +0 -1
  174. package/dist/bin/chunk-pt71fyem.js +0 -1
  175. package/dist/bin/chunk-qvj454fy.js +0 -1
  176. package/dist/bin/chunk-smj97rs5.js +0 -1
  177. package/dist/bin/chunk-wt7wjgcr.js +0 -9
  178. package/dist/bin/chunk-yf3zys06.js +0 -1
  179. package/dist/bin/chunk-zmjm7bmm.js +0 -1
  180. package/dist/chunk-05bmq0z1.js +0 -1
  181. package/dist/chunk-0qdgw73b.js +0 -1
  182. package/dist/chunk-983txhkg.js +0 -1
  183. package/dist/chunk-gv2m8yyg.js +0 -1
  184. package/dist/chunk-pf6sanwe.js +0 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{lg,x,ug,sA,mI,oA,hI,fI,yI,II,SI,CI,EI,bI,vI,TI,pg,gg,bd,vd,uo,L,d,Td,mg,M,wd,p,aA,Pi,Rd,Dd,ge,Pd,wI,r,t,RI,DI,g,PI,NI,kI,BI,_I,qt,Nd,po,cA,OI,xI,Re,ze,kd,hg,fg,LI,Ag,yg,Ig,Bd,Sg,De,qr,Vt,_d,jt,me,dA,Od,go,Cg,Eg,bg,vg,xd,$I,F,C,a,y,Ke,m,lA,We,U,At,MI,uA,Q,Ld,Pe,zt,mo,ee,$d,te,pA,ho,H,G,N,Ni,T,Kt,yt,q,e,fo,FI,Tg,Md,UI,QI,HI,GI,Fd,qI,VI,jI,zI,KI,WI,JI,XI,YI,ZI,eS,tS,gA,mA,hA,fA,AA,yA,IA,Wt,wg,Rg,Vr,ki,rS,Dg,nS,iS,jr,sS,oS,aS,cS,dS,lS,SA,CA,EA,bA,vA,Ao,uS,TA,wA,RA,V,pS,Je,yo,Jt,DA,Pg,PA,NA,kA,Ng,re,gS,mS,hS,fS,BA,AS,j,yS,IS,SS,kg,Bg,CS,_g,Og,ES,bS,vS,TS,wS,_A,Ud,RS,DS,PS,NS,kS,OA,xA,BS,_S,OS,xS,LS,$S,MS,FS,US,xg,Qd,QS,HS,GS,qS,Lg,$g,Mg,VS,Fg,jS,zS,KS,WS,Ug,JS,XS,YS,ZS,eC,tC,rC,nC,LA,$A,MA,FA,Qg,iC,sC,oC,aC,cC,dC,lC,uC,pC,UA,QA,HA,GA,gC,mC,Hg,hC,Gg,qg,Vg,jg,fC,AC,yC,IC,Ne,Bi,SC,CC,EC,bC,vC,TC,wC,RC,qA,DC,PC,zg,Kg,NC,kC,VA,BC,_C,OC,xC,LC,$C,MC,FC,UC,QC,HC,GC,qC,VC,jC,zC,KC,WC,JC,XC,YC,Wg,ZC,Jg,eE,Xg,tE,Yg,rE,Zg,nE,zr,iE,em,sE,Io,oE,tm,aE,rm,cE,nm,dE,im,lE,sm,uE,Kr,pE,om,gE,am,mE,cm,hE,dm,fE,lm,AE,um,yE,pm,IE,gm,SE,mm,CE,hm,EE,fm,bE,Am,vE,ym,TE,Im,wE,Sm,RE,Cm,DE,Em,PE,bm,NE,vm,kE,Tm,BE,wm,_E,Rm,OE,Dm,xE,Pm,LE,Nm,$E,jA,zA,KA,WA,km,ME,Bm,FE,_m,UE,Om,QE,_i,JA,XA,So,Hd,Wr,YA,Co,Xt,Gd,qd,ZA,ey,xm,ty,Vd,Lm,HE,GE,Eo,bo,vo,jd,Oi,zd,Kd,To,Wd,Jd,$m,ry,ny,iy,qE,sy,oy,VE,ay,Mm,cy,dy,ly,jE,uy,xi,Xd,py,zE,gy,wo,Ro,Yd,Fm,KE,Um,WE,Qm,JE,Hm,XE,Gm,YE}from"./chunk-r45340yc.js";import{_o,qm,sl,hy,Fi,ol,Oo,Vm,jm,Jr,xo,al,Xe,cl,dl,ll,Ui,Xr,zm,Ye,ul,Lo,$o,Mo,pl,gl,ml,Qi,Fo,hl,Yr,Hi,Uo,It,Km,fl,Al,Wm,yl,Qo,Yt,Il,Sl,Cl,El,Ze,Jm,bl,Zt,Ho,Go,qo,Gi,qi,Zr,vl,Vi,Vo,jo,en,Tl,tn,Xm,Ym,St,rn,zo,Zm,wl,Rl,Ko,Dl,Pl,Nl,fy,ne,kl,Ay,yy,ji,zi,Iy,he,eh,Ct,ke,Be,Et,Bl,_l,Ol,xl,th,rh,Wo,nh,ih,Jo,Ll,$l,sh,ie,oh,Ml,fe,Xo,et,bt,vt,nn,Ki,Fl,Sy,Yo,ah,ch,dh,lh,Zo,ea,Ul,sn,ta,Ql,Wi,Hl,ra,na,ia,sa,oa,aa,ca,da,Gl,er,la,ql,on,Vl,ua,pa,jl,tr,ga,ma,uh,Cy,Ji,Ey,by,vy,ha,fa,zl,ph,Aa,an,Kl,Xi,Wl,Jl,Xl,ya,gh,Ia,Yl,mh,Sa,hh,cn,dn,Zl,Yi,su,du,lu,uu,pu,gu,es,rr,Ea,ln,un,nr,tt,bh,va,vh,Th,fu,Ta,rs,Au,wa,wt,Oe,yu,Ra,Da,Iu,Pa,Na,ka,Ba,Su,Cu,gn,_a,Oa,xa,La,Eu,ns,mn,is,$a}from"./chunk-xbh2vr95.js";import{O,Nr,Mc,Fs,u,Mp,Fp}from"./chunk-kavwrxm8.js";import{pt,$c,pi,gi,mi,$p}from"./chunk-2mw7bjhn.js";import{sf,of,af,yp,Ip,Sp,cf,Cp,Ep,df,lf,bp,uf,pf,xc,vp,gf,mf,Tp,hf,ff,Af,yf,If,Sf,Cf,ui,Lc,wp,Rp,Dp,Pp,Np,kp,Bp,_p,Op,xp,Lp,Ef,bf,vf,Tf,wf,Rf,Df}from"./chunk-4jgy95bv.js";import{qe,Fc,pe,$t,Uc,D,Mt,gt,Qc,Us,kf,Up,Hc,s,hi,Qs,kr,Gc,qc,Br,Bf,Vc,lI,uI,Hs,pI,gI,jc,zc,fi,Gs,Z,c,qs,Ve,_r,_f,Of,Kc,Ft,xf,Vs,Lf,$f,js,Wc,Or,zs,Mf,Jc,Qp,Ut,xr,Ff,Ks,Uf,P,Qf,Xc,Hp,Ws,Hf,Gf,qf,Yc,Ai,Js,Zc,Qt,mt,Vf,Lr,jf,ed,Gp,qp,Xs,td,rd,ht,Vp,yi,nd,Ys,$r,jp,Ii,id,sd,Si,zp,od,ad,cd,dd,Zs,Kp,Wp,zf,Jp,ld,Ci,Xp,Yp,eo,Mr,to,ro,no,ud,Zp,pd,io,Kf,Ht,Wf,gd,Fr,md,Jf,hd,eg,Ei,Ur,so,bi,je,Xf,tg,rg,Gt,fd,Ad,yd,vi,Ti,wi,Yf,Zf,ft,oo,eA,Qr,ng,ao,tA,ig,sg,og,rA,ag,cg,nA,i,iA,Ri,co,lo}from"./chunk-nq51dyxz.js";import{n}from"./chunk-m93g67j0.js";import{Ie,st,Tn}from"./chunk-efssa93f.js";import{o}from"./chunk-qrs912nk.js";import{Ae,us,ps,Tu,Ha,Ga,gs,qa,rt,z,nt,se,b,ye,yn,Va,xe,ja,In,Sn,Cn,Rt,Dt,Pt,En,sr,za,or,ar,it,bn,Wa,Nt,cr,vn,Xa,Pu,Nu,Ya,dr}from"./chunk-t1gts5j9.js";import{ot,ce,Me,ku,wn,ec,tc,hs,Se,kt,Rn,fs,As,lr,ur,Dn,pr,ys,Is,Ss,Cs,W,Es,bs,vs,Ts,de,ws,Rs,Ds,R,rc,Pn,nc,le,gr}from"./chunk-qjxdhb8x.js";import{K}from"./chunk-4hdp9ms2.js";import{Bu,ic,Ce,sc,Nn,_u,oc,Ou,xu,$h,Bn,Ns,_n,On,xn,J,Fe,B,yr,$n,Ir,ue,dc,Mn,lc,Cr,Qn,ks,Hn,Gn,qn,Vn,Er,hc,Ue,X,Qe,He,ct,ve,br,Te,Kn,Wn,Jn,Xn,Yn,Zn,ei,vr,_,Os,op,Ec,ri,ni,ii,si,Pc,xs,Nc,Lt,oi,Ls,$s,kc,ai,Bc}from"./chunk-peeqkk92.js";import{Zd,Do,Li,$i,Po,el,tl,Mi,No,ko,nl,il,Bo}from"./chunk-89rs2afj.js";import{Ma,hn,fn,ss,os,as,cs,Fa,Ua}from"./chunk-57fhsqzb.js";import{Qa}from"./chunk-jh38v9zp.js";import{Za,Le,I}from"./chunk-s909414m.js";import{$e}from"./chunk-dm4vt53n.js";import{S}from"./chunk-ffxcn7mw.js";import{Y,ci,Ms,_c,di,Ap}from"./chunk-zesd879q.js";import{wr,we}from"./chunk-9g8as6sa.js";import{f}from"./chunk-wbabf3hg.js";import{tf,Ge}from"./chunk-3harnmd6.js";import{Id,Hr,Sd,Cd,Ed,Di,dg,Gr}from"./chunk-10asqy6j.js";import{createHmac as cc,createSign as wc,timingSafeEqual as vc}from"node:crypto";function zn(l){let h=l instanceof Date?l.getTime():l;if(!Number.isFinite(h))throw TypeError("Media access timestamp must be finite");return Math.floor(h/1000)}function uc(l){return Buffer.from(l).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function Oc(l){return Buffer.from(l).toString("base64url")}function pc(l,h=!1){if(!l||/[\r\n]/.test(l))throw TypeError("Media resource is invalid");let A=h?l.replaceAll("*","wildcard"):l,w=new URL(A);if(!["http:","https:"].includes(w.protocol))throw TypeError("Media resource must use HTTP or HTTPS");if(!h&&l.includes("*"))throw TypeError("Canned policies cannot contain wildcards")}function mc(l,h){let A=wc("RSA-SHA1");return A.update(l),A.end(),uc(A.sign(h))}function fc(l){pc(l.resource,!0);let A={DateLessThan:{"AWS:EpochTime":zn(l.expiresAt)}};if(l.activeAt!==void 0)A.DateGreaterThan={"AWS:EpochTime":zn(l.activeAt)};if(l.ipAddress)A.IpAddress={"AWS:SourceIp":l.ipAddress};return JSON.stringify({Statement:[{Resource:l.resource,Condition:A}]})}function Zu(l,h,A){pc(l);let w=zn(h),v=l.includes("?")?"&":"?",Ee=fc({resource:l,expiresAt:h}),oe=mc(Ee,A.privateKey);return`${l}${v}Expires=${w}&Signature=${encodeURIComponent(oe)}&Key-Pair-Id=${encodeURIComponent(A.keyPairId)}`}function qu(l,h){let A=fc(l);return{"CloudFront-Key-Pair-Id":h.keyPairId,"CloudFront-Policy":uc(Buffer.from(A)),"CloudFront-Signature":mc(A,h.privateKey)}}function Ju(l){if(!l.resource||/[\r\n]/.test(l.resource))throw TypeError("Media resource is invalid");let h=Oc(Buffer.from(JSON.stringify({resource:l.resource,expiresAt:zn(l.expiresAt),...l.keyId?{keyId:l.keyId}:{},...l.audience?{audience:l.audience}:{}}))),A=cc("sha256",l.secret).update(h).digest("base64url");return`${h}.${A}`}function Yu(l,h){let[A,w,v]=l.split(".");if(!A||!w||v)return null;let Ee=cc("sha256",h.secret).update(A).digest(),oe;try{oe=Buffer.from(w,"base64url")}catch{return null}if(Ee.length!==oe.length||!vc(Ee,oe))return null;try{let ae=JSON.parse(Buffer.from(A,"base64url").toString("utf8")),be=zn(h.now??Date.now());if(!ae.resource||!Number.isSafeInteger(ae.expiresAt)||ae.expiresAt<=be)return null;if(h.resource&&ae.resource!==h.resource)return null;if(h.audience&&ae.audience!==h.audience)return null;return ae}catch{return null}}function Xu(l,h=!1){let A=new URL(l,"https://media.invalid").pathname.toLowerCase(),w=/\.(?:m3u8|mpd|vtt|json)$/.test(A),v=/\.(?:key|license)$/.test(A)||A.includes("/keys/")||A.includes("/licenses/");return{"Accept-Ranges":"bytes","Cache-Control":h&&(w||v)?"private, no-store":w?"public, max-age=5, s-maxage=30, stale-while-revalidate=30":"public, max-age=31536000, immutable","Cross-Origin-Resource-Policy":"cross-origin","X-Content-Type-Options":"nosniff"}}function Qu(l){if(!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(l.bucket))throw TypeError("Media bucket is invalid");if(!/^[a-z0-9-]+$/.test(l.region))throw TypeError("Media bucket region is invalid");let h=l.prefix?`/${l.prefix.replace(/^\/+|\/+$/g,"")}`:"",A=l.protected??!1,w="public, max-age=31536000, immutable",v=A?"private, no-store":"public, max-age=5, s-maxage=30, stale-while-revalidate=30";return{originDomain:`${l.bucket}.s3.${l.region}.amazonaws.com`,originPath:h,domain:l.domain,trustedKeyGroupIds:[...new Set(l.trustedKeyGroupIds??[])],behaviors:[{pathPattern:"*.m3u8",cacheControl:v,compress:!0,signed:A},{pathPattern:"*.mpd",cacheControl:v,compress:!0,signed:A},{pathPattern:"*.vtt",cacheControl:v,compress:!0,signed:A},{pathPattern:"*",cacheControl:w,compress:!1,signed:A}],responseHeaders:{"Access-Control-Allow-Headers":"Range, If-Range","Access-Control-Allow-Methods":"GET, HEAD, OPTIONS","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Accept-Ranges, Content-Length, Content-Range, ETag","X-Content-Type-Options":"nosniff"}}}class rl{builder;config;environment;mergedConfig;serverEipLogicalIds=new Map;storageFailoverReplicas=[];constructor(l){this.config=l.config,this.environment=l.environment,this.builder=new Pd(`${this.config.project.name} - ${this.environment}`),this.mergedConfig=this.mergeEnvironmentConfig()}mergeEnvironmentConfig(){let h=this.config.environments[this.environment]?.infrastructure;if(!h)return this.config;return{...this.config,infrastructure:{...this.config.infrastructure,...h,compute:{...this.config.infrastructure?.compute,...h.compute},storage:{...this.config.infrastructure?.storage,...h.storage},functions:{...this.config.infrastructure?.functions,...h.functions},servers:{...this.config.infrastructure?.servers,...h.servers},databases:{...this.config.infrastructure?.databases,...h.databases},cdn:{...this.config.infrastructure?.cdn,...h.cdn},sftp:h.sftp??this.config.infrastructure?.sftp,queues:{...this.config.infrastructure?.queues,...h.queues},redirects:{...this.config.infrastructure?.redirects,...h.redirects},realtime:{...this.config.infrastructure?.realtime,...h.realtime},cache:{...this.config.infrastructure?.cache,...h.cache},fileSystem:{...this.config.infrastructure?.fileSystem,...h.fileSystem},email:{...this.config.infrastructure?.email,...h.email},search:{...this.config.infrastructure?.search,...h.search},ai:{...this.config.infrastructure?.ai,...h.ai}}}}shouldDeploy(l){if(l.environments&&!l.environments.includes(this.environment))return!1;if(l.requiresFeatures){let h=this.config.features||{};if(!l.requiresFeatures.every((w)=>h[w]===!0))return!1}if(l.regions){let h=this.config.environments[this.environment]?.region||this.config.project.region;if(!l.regions.includes(h))return!1}if(l.condition&&typeof l.condition==="function")return l.condition(this.config,this.environment);return!0}resolveApiOriginPort(){let l=this.mergedConfig.infrastructure?.api?.port??this.mergedConfig.ports?.api,h=Number(l||3008);return Number.isFinite(h)&&h>0?h:3008}defaultComputeCachePathPatterns(){return["/api/*","/auth/*","/publisher/api/*","/publisher/*","/publish","/publish/*","/analytics/*","/packages/*","/npm/*","/zig/*","/php/*","/commits/*","/health","/dashboard/*","/search","/login","/logout","/signup","/account","/account/*"]}shouldRouteStorageBucketToCompute(l,h){return l==="public"||h.routeCompute===!0}storageBucketName(l,h,A){return this.mergedConfig.infrastructure?.storage?.[A]?.bucket??`${l}-${h}-${A}`}fileSystemLogicalId(l,h,A){return t(r({slug:`${l}-${A}`,environment:h,resourceType:"efs"}))}resolveSftpStorage(l,h,A){let w=l.storage;if(w?.type==="efs"&&w.fileSystem){if(!this.mergedConfig.infrastructure?.fileSystem?.[w.fileSystem])throw Error(`sftp: storage.fileSystem "${w.fileSystem}" is not defined in infrastructure.fileSystem`);return{type:"efs",fileSystemId:{Ref:this.fileSystemLogicalId(h,A,w.fileSystem)},posixProfile:w.posixProfile}}if(w?.type==="s3"&&w.storageBucket){if(!this.mergedConfig.infrastructure?.storage?.[w.storageBucket])throw Error(`sftp: storage.storageBucket "${w.storageBucket}" is not defined in infrastructure.storage`);return{type:"s3",bucket:this.storageBucketName(h,A,w.storageBucket)}}return}resolveComputeCachePathPatterns(l){if(l&&l.length>0)return l;return this.defaultComputeCachePathPatterns()}createComputeCacheBehavior(l,h){return{PathPattern:l,TargetOriginId:h,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac"}}appendComputeAppOrigin(l,h,A,w,v,Ee){let oe=this.serverEipLogicalIds.get("app"),ae=this.serverEipLogicalIds.get("appInstance");if(!oe)return;let be=`EC2-${w}-${v}-api`,dt=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",_e=dt==="us-east-1"?".compute-1.amazonaws.com":`.${dt}.compute.amazonaws.com`,_t={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:oe}]}]},_e]]},ir=this.resolveApiOriginPort();if(l.push({Id:be,DomainName:_t,CustomOriginConfig:{HTTPPort:ir,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),A.push(oe),ae)A.push(ae);for(let fr of Ee)h.push(this.createComputeCacheBehavior(fr,be))}buildCaddyfile(l){let h=l.filter(([,v])=>typeof v.domain==="string"&&v.domain&&typeof v.port==="number");if(h.length===0)return;let A=new Map;for(let[,v]of h){let Ee=A.get(v.domain)??[];Ee.push({port:v.port,path:v.path}),A.set(v.domain,Ee)}let w=[];for(let[v,Ee]of A){let ae=[...Ee].sort((be,dt)=>{let _e=!be.path||be.path==="/",_t=!dt.path||dt.path==="/";if(_e&&!_t)return 1;if(!_e&&_t)return-1;return(dt.path?.length??0)-(be.path?.length??0)}).map((be)=>{let dt=!be.path||be.path==="/",_e=`reverse_proxy localhost:${be.port}`;return dt?` handle {
1
+ import{ug,x,pg,oA,hI,aA,fI,yI,II,SI,CI,EI,bI,vI,TI,wI,gg,mg,bd,vd,uo,L,d,Td,hg,M,wd,p,cA,Pi,Rd,Dd,ge,Pd,RI,r,t,DI,PI,g,NI,kI,BI,_I,OI,qt,Nd,po,dA,xI,LI,Re,ze,kd,fg,Ag,$I,yg,Ig,Sg,Bd,Cg,De,qr,Vt,_d,jt,me,lA,Od,go,Eg,bg,vg,Tg,xd,MI,F,C,a,y,Ke,m,uA,We,U,At,FI,pA,Q,Ld,Pe,zt,mo,ee,$d,te,gA,ho,H,G,N,Ni,T,Kt,yt,q,e,fo,UI,wg,Md,QI,HI,GI,qI,Fd,VI,jI,zI,KI,WI,JI,XI,YI,ZI,eS,tS,rS,mA,hA,fA,AA,yA,IA,SA,Wt,Rg,Dg,Vr,ki,nS,Pg,iS,sS,jr,oS,aS,cS,dS,lS,uS,CA,EA,bA,vA,TA,Ao,pS,wA,RA,DA,V,gS,Je,yo,Jt,PA,Ng,NA,kA,BA,kg,re,mS,hS,fS,AS,_A,yS,j,IS,SS,CS,Bg,_g,ES,Og,xg,bS,vS,TS,wS,RS,OA,Ud,DS,PS,NS,kS,BS,xA,LA,_S,OS,xS,LS,$S,MS,FS,US,QS,Lg,Qd,HS,GS,qS,VS,$g,Mg,Fg,jS,Ug,zS,KS,WS,JS,Qg,XS,YS,ZS,eC,tC,rC,nC,iC,$A,MA,FA,UA,Hg,sC,oC,aC,cC,dC,lC,uC,pC,gC,QA,HA,GA,qA,mC,hC,Gg,fC,qg,Vg,jg,zg,AC,yC,IC,SC,Ne,Bi,CC,EC,bC,vC,TC,wC,RC,DC,VA,PC,NC,Kg,Wg,kC,BC,jA,_C,OC,xC,LC,$C,MC,FC,UC,QC,HC,GC,qC,VC,jC,zC,KC,WC,JC,XC,YC,ZC,Jg,eE,Xg,tE,Yg,rE,Zg,nE,em,iE,zr,sE,tm,oE,Io,aE,rm,cE,nm,dE,im,lE,sm,uE,om,pE,Kr,gE,am,mE,cm,hE,dm,fE,lm,AE,um,yE,pm,IE,gm,SE,mm,CE,hm,EE,fm,bE,Am,vE,ym,TE,Im,wE,Sm,RE,Cm,DE,Em,PE,bm,NE,vm,kE,Tm,BE,wm,_E,Rm,OE,Dm,xE,Pm,LE,Nm,$E,km,ME,zA,KA,WA,JA,Bm,FE,_m,UE,Om,QE,xm,HE,_i,XA,YA,So,Hd,Wr,ZA,Co,Xt,Gd,qd,ey,ty,Lm,ry,Vd,$m,GE,qE,Eo,bo,vo,jd,Oi,zd,Kd,To,Wd,Jd,Mm,ny,iy,sy,VE,oy,ay,jE,cy,Fm,dy,ly,uy,zE,py,xi,Xd,gy,KE,my,wo,Ro,Yd,Um,WE,Qm,JE,Hm,XE,Gm,YE,qm,ZE}from"./chunk-0pe1dfy0.js";import{_o,Vm,sl,fy,Fi,ol,Oo,jm,zm,Jr,xo,al,Xe,cl,dl,ll,Ui,Xr,Km,Ye,ul,Lo,$o,Mo,pl,gl,ml,Qi,Fo,hl,Yr,Hi,Uo,It,Wm,fl,Al,Jm,yl,Qo,Yt,Il,Sl,Cl,El,Ze,Xm,bl,Zt,Ho,Go,qo,Gi,qi,Zr,vl,Vi,Vo,jo,en,Tl,tn,Ym,Zm,St,rn,zo,eh,wl,Rl,Ko,Dl,Pl,Nl,Ay,ne,kl,yy,Iy,ji,zi,Sy,he,th,Ct,ke,Be,Et,Bl,_l,Ol,xl,rh,nh,Wo,ih,sh,Jo,Ll,$l,oh,ie,ah,Ml,fe,Xo,et,bt,vt,nn,Ki,Fl,Cy,Yo,ch,dh,lh,uh,Zo,ea,Ul,sn,ta,Ql,Wi,Hl,ra,na,ia,sa,oa,aa,ca,da,Gl,er,la,ql,on,Vl,ua,pa,jl,tr,ga,ma,ph,Ey,Ji,by,vy,Ty,ha,fa,zl,gh,Aa,an,Kl,Xi,Wl,Jl,Xl,ya,mh,Ia,Yl,hh,Sa,fh,cn,dn,Zl,Yi,su,du,lu,uu,pu,gu,es,rr,Ea,ln,un,nr,tt,vh,va,Th,wh,fu,Ta,rs,Au,wa,wt,Oe,yu,Ra,Da,Iu,Pa,Na,ka,Ba,Su,Cu,gn,_a,Oa,xa,La,Eu,ns,mn,is,$a}from"./chunk-c4kferxw.js";import{O,Nr,Mc,Fs,u,Fp,Up}from"./chunk-6n72pe9x.js";import{pt,$c,pi,gi,mi,Mp}from"./chunk-nmm287ym.js";import{of,af,cf,Ip,Sp,Cp,df,Ep,bp,lf,uf,vp,pf,gf,xc,Tp,mf,hf,wp,ff,Af,yf,If,Sf,Cf,Ef,ui,Lc,Rp,Dp,Pp,Np,kp,Bp,_p,Op,xp,Lp,$p,bf,vf,Tf,wf,Rf,Df,Pf}from"./chunk-y3h0ybmn.js";import{qe,Fc,pe,$t,Uc,D,Mt,gt,Qc,Us,Bf,Qp,Hc,s,hi,Qs,kr,Gc,qc,Br,_f,Vc,uI,pI,Hs,gI,mI,jc,zc,fi,Gs,Z,c,qs,Ve,_r,Of,xf,Kc,Ft,Lf,Vs,$f,Mf,js,Wc,Or,zs,Ff,Jc,Hp,Ut,xr,Uf,Ks,Qf,P,Hf,Xc,Gp,Ws,Gf,qf,Vf,Yc,Ai,Js,Zc,Qt,mt,jf,Lr,zf,ed,qp,Vp,Xs,td,rd,ht,jp,yi,nd,Ys,$r,zp,Ii,id,sd,Si,Kp,od,ad,cd,dd,Zs,Wp,Jp,Kf,Xp,ld,Ci,Yp,Zp,eo,Mr,to,ro,no,ud,eg,pd,io,Wf,Ht,Jf,gd,Fr,md,Xf,hd,tg,Ei,Ur,so,bi,je,Yf,rg,ng,Gt,fd,Ad,yd,vi,Ti,wi,Zf,eA,ft,oo,tA,Qr,ig,ao,rA,sg,og,ag,nA,cg,dg,iA,i,sA,Ri,co,lo}from"./chunk-9r32w840.js";import{n}from"./chunk-g3f3ccdw.js";import{Ie,st,Tn}from"./chunk-k3azr9e3.js";import{o}from"./chunk-45116tdd.js";import{Ae,us,ps,Tu,Ha,Ga,gs,qa,rt,z,nt,se,b,ye,yn,Va,xe,ja,In,Sn,Cn,Rt,Dt,Pt,En,sr,za,or,ar,it,bn,Wa,Nt,cr,vn,Xa,Pu,Nu,Ya,dr}from"./chunk-qad1mjmc.js";import{ot,ce,Me,ku,wn,ec,tc,hs,Se,kt,Rn,fs,As,lr,ur,Dn,pr,ys,Is,Ss,Cs,W,Es,bs,vs,Ts,de,ws,Rs,Ds,R,rc,Pn,nc,le,gr}from"./chunk-n4gkyye3.js";import{K}from"./chunk-m1jp1abp.js";import{Bu,ic,Ce,sc,Nn,_u,oc,Ou,xu,Mh,Bn,Ns,_n,On,xn,J,Fe,B,yr,$n,Ir,ue,dc,Mn,lc,Cr,Qn,ks,Hn,Gn,qn,Vn,Er,hc,Ue,X,Qe,He,ct,ve,br,Te,Kn,Wn,Jn,Xn,Yn,Zn,ei,vr,_,Os,ap,Ec,ri,ni,ii,si,Pc,xs,Nc,Lt,oi,Ls,$s,kc,ai,Bc}from"./chunk-29dcfx1g.js";import{Zd,Do,Li,$i,Po,el,tl,Mi,No,ko,nl,il,Bo}from"./chunk-tzvtq055.js";import{Ma,hn,fn,ss,os,as,cs,Fa,Ua}from"./chunk-444h366b.js";import{Qa}from"./chunk-y3dj8xwk.js";import{Za,Le,I}from"./chunk-pkpmz35j.js";import{$e}from"./chunk-wctam3r1.js";import{S}from"./chunk-c6nw88s3.js";import{Y,ci,Ms,_c,di,yp}from"./chunk-v9t4751b.js";import{wr,we}from"./chunk-jp57js5y.js";import{f}from"./chunk-v1wqxgra.js";import{rf,Ge}from"./chunk-7r2qc39k.js";import{Id,Hr,Sd,Cd,Ed,Di,lg,Gr}from"./chunk-e08h4q50.js";import{createHmac as cc,createSign as wc,timingSafeEqual as vc}from"node:crypto";function zn(l){let h=l instanceof Date?l.getTime():l;if(!Number.isFinite(h))throw TypeError("Media access timestamp must be finite");return Math.floor(h/1000)}function uc(l){return Buffer.from(l).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function Oc(l){return Buffer.from(l).toString("base64url")}function pc(l,h=!1){if(!l||/[\r\n]/.test(l))throw TypeError("Media resource is invalid");let A=h?l.replaceAll("*","wildcard"):l,w=new URL(A);if(!["http:","https:"].includes(w.protocol))throw TypeError("Media resource must use HTTP or HTTPS");if(!h&&l.includes("*"))throw TypeError("Canned policies cannot contain wildcards")}function mc(l,h){let A=wc("RSA-SHA1");return A.update(l),A.end(),uc(A.sign(h))}function fc(l){pc(l.resource,!0);let A={DateLessThan:{"AWS:EpochTime":zn(l.expiresAt)}};if(l.activeAt!==void 0)A.DateGreaterThan={"AWS:EpochTime":zn(l.activeAt)};if(l.ipAddress)A.IpAddress={"AWS:SourceIp":l.ipAddress};return JSON.stringify({Statement:[{Resource:l.resource,Condition:A}]})}function Zu(l,h,A){pc(l);let w=zn(h),v=l.includes("?")?"&":"?",Ee=fc({resource:l,expiresAt:h}),oe=mc(Ee,A.privateKey);return`${l}${v}Expires=${w}&Signature=${encodeURIComponent(oe)}&Key-Pair-Id=${encodeURIComponent(A.keyPairId)}`}function qu(l,h){let A=fc(l);return{"CloudFront-Key-Pair-Id":h.keyPairId,"CloudFront-Policy":uc(Buffer.from(A)),"CloudFront-Signature":mc(A,h.privateKey)}}function Ju(l){if(!l.resource||/[\r\n]/.test(l.resource))throw TypeError("Media resource is invalid");let h=Oc(Buffer.from(JSON.stringify({resource:l.resource,expiresAt:zn(l.expiresAt),...l.keyId?{keyId:l.keyId}:{},...l.audience?{audience:l.audience}:{}}))),A=cc("sha256",l.secret).update(h).digest("base64url");return`${h}.${A}`}function Yu(l,h){let[A,w,v]=l.split(".");if(!A||!w||v)return null;let Ee=cc("sha256",h.secret).update(A).digest(),oe;try{oe=Buffer.from(w,"base64url")}catch{return null}if(Ee.length!==oe.length||!vc(Ee,oe))return null;try{let ae=JSON.parse(Buffer.from(A,"base64url").toString("utf8")),be=zn(h.now??Date.now());if(!ae.resource||!Number.isSafeInteger(ae.expiresAt)||ae.expiresAt<=be)return null;if(h.resource&&ae.resource!==h.resource)return null;if(h.audience&&ae.audience!==h.audience)return null;return ae}catch{return null}}function Xu(l,h=!1){let A=new URL(l,"https://media.invalid").pathname.toLowerCase(),w=/\.(?:m3u8|mpd|vtt|json)$/.test(A),v=/\.(?:key|license)$/.test(A)||A.includes("/keys/")||A.includes("/licenses/");return{"Accept-Ranges":"bytes","Cache-Control":h&&(w||v)?"private, no-store":w?"public, max-age=5, s-maxage=30, stale-while-revalidate=30":"public, max-age=31536000, immutable","Cross-Origin-Resource-Policy":"cross-origin","X-Content-Type-Options":"nosniff"}}function Qu(l){if(!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(l.bucket))throw TypeError("Media bucket is invalid");if(!/^[a-z0-9-]+$/.test(l.region))throw TypeError("Media bucket region is invalid");let h=l.prefix?`/${l.prefix.replace(/^\/+|\/+$/g,"")}`:"",A=l.protected??!1,w="public, max-age=31536000, immutable",v=A?"private, no-store":"public, max-age=5, s-maxage=30, stale-while-revalidate=30";return{originDomain:`${l.bucket}.s3.${l.region}.amazonaws.com`,originPath:h,domain:l.domain,trustedKeyGroupIds:[...new Set(l.trustedKeyGroupIds??[])],behaviors:[{pathPattern:"*.m3u8",cacheControl:v,compress:!0,signed:A},{pathPattern:"*.mpd",cacheControl:v,compress:!0,signed:A},{pathPattern:"*.vtt",cacheControl:v,compress:!0,signed:A},{pathPattern:"*",cacheControl:w,compress:!1,signed:A}],responseHeaders:{"Access-Control-Allow-Headers":"Range, If-Range","Access-Control-Allow-Methods":"GET, HEAD, OPTIONS","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Accept-Ranges, Content-Length, Content-Range, ETag","X-Content-Type-Options":"nosniff"}}}class rl{builder;config;environment;mergedConfig;serverEipLogicalIds=new Map;storageFailoverReplicas=[];constructor(l){this.config=l.config,this.environment=l.environment,this.builder=new Pd(`${this.config.project.name} - ${this.environment}`),this.mergedConfig=this.mergeEnvironmentConfig()}mergeEnvironmentConfig(){let h=this.config.environments[this.environment]?.infrastructure;if(!h)return this.config;return{...this.config,infrastructure:{...this.config.infrastructure,...h,compute:{...this.config.infrastructure?.compute,...h.compute},storage:{...this.config.infrastructure?.storage,...h.storage},functions:{...this.config.infrastructure?.functions,...h.functions},servers:{...this.config.infrastructure?.servers,...h.servers},databases:{...this.config.infrastructure?.databases,...h.databases},cdn:{...this.config.infrastructure?.cdn,...h.cdn},sftp:h.sftp??this.config.infrastructure?.sftp,queues:{...this.config.infrastructure?.queues,...h.queues},redirects:{...this.config.infrastructure?.redirects,...h.redirects},realtime:{...this.config.infrastructure?.realtime,...h.realtime},cache:{...this.config.infrastructure?.cache,...h.cache},fileSystem:{...this.config.infrastructure?.fileSystem,...h.fileSystem},email:{...this.config.infrastructure?.email,...h.email},search:{...this.config.infrastructure?.search,...h.search},ai:{...this.config.infrastructure?.ai,...h.ai}}}}shouldDeploy(l){if(l.environments&&!l.environments.includes(this.environment))return!1;if(l.requiresFeatures){let h=this.config.features||{};if(!l.requiresFeatures.every((w)=>h[w]===!0))return!1}if(l.regions){let h=this.config.environments[this.environment]?.region||this.config.project.region;if(!l.regions.includes(h))return!1}if(l.condition&&typeof l.condition==="function")return l.condition(this.config,this.environment);return!0}resolveApiOriginPort(){let l=this.mergedConfig.infrastructure?.api?.port??this.mergedConfig.ports?.api,h=Number(l||3008);return Number.isFinite(h)&&h>0?h:3008}defaultComputeCachePathPatterns(){return["/api/*","/auth/*","/publisher/api/*","/publisher/*","/publish","/publish/*","/analytics/*","/packages/*","/npm/*","/zig/*","/php/*","/commits/*","/health","/dashboard/*","/search","/login","/logout","/signup","/account","/account/*"]}shouldRouteStorageBucketToCompute(l,h){return l==="public"||h.routeCompute===!0}storageBucketName(l,h,A){return this.mergedConfig.infrastructure?.storage?.[A]?.bucket??`${l}-${h}-${A}`}fileSystemLogicalId(l,h,A){return t(r({slug:`${l}-${A}`,environment:h,resourceType:"efs"}))}resolveSftpStorage(l,h,A){let w=l.storage;if(w?.type==="efs"&&w.fileSystem){if(!this.mergedConfig.infrastructure?.fileSystem?.[w.fileSystem])throw Error(`sftp: storage.fileSystem "${w.fileSystem}" is not defined in infrastructure.fileSystem`);return{type:"efs",fileSystemId:{Ref:this.fileSystemLogicalId(h,A,w.fileSystem)},posixProfile:w.posixProfile}}if(w?.type==="s3"&&w.storageBucket){if(!this.mergedConfig.infrastructure?.storage?.[w.storageBucket])throw Error(`sftp: storage.storageBucket "${w.storageBucket}" is not defined in infrastructure.storage`);return{type:"s3",bucket:this.storageBucketName(h,A,w.storageBucket)}}return}resolveComputeCachePathPatterns(l){if(l&&l.length>0)return l;return this.defaultComputeCachePathPatterns()}createComputeCacheBehavior(l,h){return{PathPattern:l,TargetOriginId:h,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac"}}appendComputeAppOrigin(l,h,A,w,v,Ee){let oe=this.serverEipLogicalIds.get("app"),ae=this.serverEipLogicalIds.get("appInstance");if(!oe)return;let be=`EC2-${w}-${v}-api`,dt=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",_e=dt==="us-east-1"?".compute-1.amazonaws.com":`.${dt}.compute.amazonaws.com`,_t={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:oe}]}]},_e]]},ir=this.resolveApiOriginPort();if(l.push({Id:be,DomainName:_t,CustomOriginConfig:{HTTPPort:ir,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),A.push(oe),ae)A.push(ae);for(let fr of Ee)h.push(this.createComputeCacheBehavior(fr,be))}buildCaddyfile(l){let h=l.filter(([,v])=>typeof v.domain==="string"&&v.domain&&typeof v.port==="number");if(h.length===0)return;let A=new Map;for(let[,v]of h){let Ee=A.get(v.domain)??[];Ee.push({port:v.port,path:v.path}),A.set(v.domain,Ee)}let w=[];for(let[v,Ee]of A){let ae=[...Ee].sort((be,dt)=>{let _e=!be.path||be.path==="/",_t=!dt.path||dt.path==="/";if(_e&&!_t)return 1;if(!_e&&_t)return-1;return(dt.path?.length??0)-(be.path?.length??0)}).map((be)=>{let dt=!be.path||be.path==="/",_e=`reverse_proxy localhost:${be.port}`;return dt?` handle {
2
2
  ${_e}
3
3
  }`:` handle ${be.path} {
4
4
  ${_e}
@@ -10,8 +10,8 @@ ${ae.join(`
10
10
  `)}normalizeMountPath(l){let h=l?.mountPath||l?.path;if(!h||h==="/")return;let A=`/${h}`.replace(/\/+/g,"/").replace(/\/$/,"");return A==="/"?void 0:A}storageBucketLogicalId(l,h,A){return`${l}-${h}-s3-${A}`.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((w)=>w.charAt(0).toUpperCase()+w.slice(1)).join("")}pathMountRewriteFunctionCode(l,h="directory"){return`function handler(event) { var request = event.request; var prefix = ${JSON.stringify(l)}; var rewriteStyle = ${JSON.stringify(h)}; var uri = request.uri; if (uri === prefix) { uri = '/'; } else if (uri.indexOf(prefix + '/') === 0) { uri = uri.substring(prefix.length); } if (uri === '' || uri === '/') { request.uri = '/index.html'; return request; } if (uri.endsWith('/')) { request.uri = uri + 'index.html'; return request; } var lastSegment = uri.substring(uri.lastIndexOf('/') + 1); if (lastSegment.indexOf('.') === -1) { request.uri = rewriteStyle === 'flat' ? uri + '.html' : uri + '/index.html'; return request; } request.uri = uri; return request; }`}generate(){let l=this.mergedConfig.project.slug,h=this.environment,A=!!(this.mergedConfig.infrastructure?.functions&&Object.keys(this.mergedConfig.infrastructure.functions).length>0||this.mergedConfig.infrastructure?.api),w=!!(this.mergedConfig.infrastructure?.servers&&Object.keys(this.mergedConfig.infrastructure.servers).length>0),v=!!this.mergedConfig.infrastructure?.compute;if(!!((this.mergedConfig.mode||"server")==="serverless"&&this.mergedConfig.infrastructure?.containers&&Object.keys(this.mergedConfig.infrastructure.containers).length>0))this.generateNetworkInfrastructure(l,h),this.generateContainerInfrastructure(l,h);if(A)this.generateServerless(l,h);if(w)this.generateServer(l,h);if(v)this.generateComputeApp(l,h);if(this.mergedConfig.infrastructure?.jumpBox)this.generateJumpBox(l,h);if(this.storageFailoverReplicas=[],this.generateSharedInfrastructure(l,h),this.storageFailoverReplicas.length>0)this.builder.addMetadata(Od,this.storageFailoverReplicas);if(this.config.tags)this.applyGlobalTags(this.config.tags);return this}getStorageFailoverReplicas(){return[...this.storageFailoverReplicas]}applyGlobalTags(l){}generateNetworkInfrastructure(l,h){if(this.builder.hasResource("VPC"))return;let w=this.mergedConfig.infrastructure?.network?.cidr||"10.0.0.0/16",{vpc:v,logicalId:Ee}=y.createVpc({slug:l,environment:h,cidr:w,enableDnsHostnames:!0,enableDnsSupport:!0});this.builder.addResource("VPC",v);let oe=`${l}${h}IGW`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(oe,{Type:"AWS::EC2::InternetGateway",Properties:{Tags:[{Key:"Name",Value:`${l}-${h}-igw`},{Key:"Environment",Value:h}]}});let ae=`${l}${h}IGWAttach`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ae,{Type:"AWS::EC2::VPCGatewayAttachment",Properties:{VpcId:{Ref:"VPC"},InternetGatewayId:{Ref:oe}}});let be=`${l}${h}PublicRT`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(be,{Type:"AWS::EC2::RouteTable",Properties:{VpcId:{Ref:"VPC"},Tags:[{Key:"Name",Value:`${l}-${h}-public-rt`},{Key:"Environment",Value:h}]}}),this.builder.addResource(`${l}${h}PublicRoute`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::EC2::Route",Properties:{RouteTableId:{Ref:be},DestinationCidrBlock:"0.0.0.0/0",GatewayId:{Ref:oe}},DependsOn:ae});let dt=this.mergedConfig.environments[h]?.region||this.mergedConfig.project.region||"us-east-1",_e=["a","b"];for(let _t=0;_t<2;_t++){let ir=`PublicSubnet${_t+1}`;this.builder.addResource(ir,{Type:"AWS::EC2::Subnet",Properties:{VpcId:{Ref:"VPC"},CidrBlock:`10.0.${_t}.0/24`,AvailabilityZone:`${dt}${_e[_t]}`,MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:`${l}-${h}-public-${_e[_t]}`},{Key:"Environment",Value:h}]}}),this.builder.addResource(`${ir}RTAssoc`,{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:{Ref:ir},RouteTableId:{Ref:be}}})}}generateContainerInfrastructure(l,h){let A=this.mergedConfig.infrastructure?.containers;if(!A)return;let w=this.mergedConfig.infrastructure?.loadBalancer,v=this.mergedConfig.infrastructure?.ssl,Ee=this.mergedConfig.infrastructure?.dns,oe;if(v?.enabled&&v.domains?.length)if(v.certificateArn);else{let _e=v.domains[0],_t=v.domains.slice(1).map((ut)=>{if(ut.includes(".")&&ut.endsWith(_e))return ut.replace(`.${_e}`,"");return ut}),{certificate:ir,logicalId:fr}=C.createCertificate({domain:_e,subdomains:_t,slug:l,environment:h,validationMethod:"DNS",hostedZoneId:Ee?.hostedZoneId});oe=fr,this.builder.addResource(fr,ir)}let ae="ECSCluster";this.builder.addResource(ae,{Type:"AWS::ECS::Cluster",Properties:{ClusterName:`${l}-${h}`,ClusterSettings:[{Name:"containerInsights",Value:"enabled"}],Tags:[{Key:"Name",Value:`${l}-${h}`},{Key:"Environment",Value:h}]}});let be=`${l}${h}ALBSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(be,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ALB security group for ${l}-${h}`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:80,ToPort:80,CidrIp:"0.0.0.0/0",Description:"HTTP"},{IpProtocol:"tcp",FromPort:443,ToPort:443,CidrIp:"0.0.0.0/0",Description:"HTTPS"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${l}-${h}-alb-sg`},{Key:"Environment",Value:h}]}});let dt=`${l}${h}ECSSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");for(let[_e,_t]of Object.entries(A)){let ir=_t.port||3000;this.builder.addResource(dt,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ECS tasks security group for ${l}-${h}`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:ir,ToPort:ir,SourceSecurityGroupId:{Ref:be},Description:"Allow traffic from ALB"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${l}-${h}-ecs-sg`},{Key:"Environment",Value:h}]}});let fr=`${l}${h}TaskExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(fr,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${h}-ecs-exec-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"],Policies:[{PolicyName:"ECRPullPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["ecr:GetAuthorizationToken","ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","logs:CreateLogStream","logs:PutLogEvents"],Resource:"*"}]}}]}});let ut=`${l}${h}TaskRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ut,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${h}-ecs-task-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"TaskPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogStream","logs:PutLogEvents"],Resource:"*"},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:ListBucket"],Resource:"*"}]}}]}});let at=`${l}${h}${_e}LogGroup`.replace(/[^a-zA-Z0-9]/g,""),k=`/ecs/${l}-${h}-${_e}`;this.builder.addResource(at,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:k,RetentionInDays:30}});let Ot=`${l}${h}${_e}TaskDef`.replace(/[^a-zA-Z0-9]/g,""),E=String(_t.cpu||512),lt=String(_t.memory||1024);this.builder.addResource(Ot,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${l}-${h}-${_e}`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:E,Memory:lt,ExecutionRoleArn:{"Fn::GetAtt":[fr,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[ut,"Arn"]},ContainerDefinitions:[{Name:_e,Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${l}:latest`},Essential:!0,PortMappings:[{ContainerPort:ir,Protocol:"tcp"}],LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":k,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":_e}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${ir}${_t.healthCheck||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${l}-${h}-${_e}`},{Key:"Environment",Value:h}]},DependsOn:[fr,ut,at]});let Tt=`${l}${h}ALB`.replace(/[^a-zA-Z0-9]/g,"");if(w?.enabled!==!1){this.builder.addResource(Tt,{Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:`${l}-${h}-alb`,Scheme:"internet-facing",Type:"application",Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],SecurityGroups:[{Ref:be}],Tags:[{Key:"Name",Value:`${l}-${h}-alb`},{Key:"Environment",Value:h}]}});let xt=`${l}${h}TargetGroup`.replace(/[^a-zA-Z0-9]/g,""),Bt=w?.healthCheck?.path||_t.healthCheck||"/health";this.builder.addResource(xt,{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:`${l}-${h}-tg`,Port:ir,Protocol:"HTTP",VpcId:{Ref:"VPC"},TargetType:"ip",HealthCheckPath:Bt,HealthCheckIntervalSeconds:w?.healthCheck?.interval||30,HealthyThresholdCount:w?.healthCheck?.healthyThreshold||2,UnhealthyThresholdCount:w?.healthCheck?.unhealthyThreshold||5,HealthCheckTimeoutSeconds:10,Tags:[{Key:"Name",Value:`${l}-${h}-tg`},{Key:"Environment",Value:h}]}});let mr=`${l}${h}HTTPListener`.replace(/[^a-zA-Z0-9]/g,"");if(v?.enabled&&v?.redirectHttp)this.builder.addResource(mr,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Tt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"redirect",RedirectConfig:{Protocol:"HTTPS",Port:"443",StatusCode:"HTTP_301"}}]}});else this.builder.addResource(mr,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Tt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:xt}}]}});if(v?.enabled){let Sr=v.certificateArn||(oe?{Ref:oe}:void 0);if(Sr){let Rr=`${l}${h}HTTPSListener`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Rr,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Tt},Port:443,Protocol:"HTTPS",Certificates:[{CertificateArn:Sr}],DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:xt}}],SslPolicy:"ELBSecurityPolicy-TLS13-1-2-2021-06"}})}}let hr=`${l}${h}${_e}Service`.replace(/[^a-zA-Z0-9]/g,""),Ar=_t.desiredCount||1;this.builder.addResource(hr,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${h}-${_e}`,Cluster:{Ref:ae},TaskDefinition:{Ref:Ot},DesiredCount:Ar,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:dt}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},LoadBalancers:[{ContainerName:_e,ContainerPort:ir,TargetGroupArn:{Ref:xt}}],HealthCheckGracePeriodSeconds:120,Tags:[{Key:"Name",Value:`${l}-${h}-${_e}`},{Key:"Environment",Value:h}]},DependsOn:[Ot,mr,xt]});let Tr=_t.autoScaling;if(Tr){let Sr=`${l}${h}${_e}ScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(Sr,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:Tr.max||10,MinCapacity:Tr.min||1,ResourceId:{"Fn::Sub":`service/\${${ae}}/${l}-${h}-${_e}`},ScalableDimension:"ecs:service:DesiredCount",ServiceNamespace:"ecs",RoleARN:{"Fn::Sub":"arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService"}},DependsOn:hr}),Tr.targetCpuUtilization)this.builder.addResource(`${l}${h}${_e}CPUScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${h}-${_e}-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Sr},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:Tr.targetCpuUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}});if(Tr.targetMemoryUtilization)this.builder.addResource(`${l}${h}${_e}MemoryScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${h}-${_e}-memory-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Sr},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageMemoryUtilization"},TargetValue:Tr.targetMemoryUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(Ee?.domain&&Ee?.hostedZoneId)this.builder.addResource(`${l}${h}ApiDnsRecord`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:Ee.hostedZoneId,Name:`api.${Ee.domain}`,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[Tt,"DNSName"]},HostedZoneId:{"Fn::GetAtt":[Tt,"CanonicalHostedZoneID"]}}}});this.builder.addOutput("ECSClusterArn",{Description:"ECS Cluster ARN",Value:{"Fn::GetAtt":[ae,"Arn"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-cluster-arn"}}}),this.builder.addOutput("ECSServiceName",{Description:"ECS Service Name",Value:`${l}-${h}-${_e}`,Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-service-name"}}}),this.builder.addOutput("LoadBalancerDNS",{Description:"Application Load Balancer DNS Name",Value:{"Fn::GetAtt":[Tt,"DNSName"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-alb-dns"}}})}else{let xt=`${l}${h}${_e}Service`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(xt,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${h}-${_e}`,Cluster:{Ref:ae},TaskDefinition:{Ref:Ot},DesiredCount:_t.desiredCount||1,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:dt}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},Tags:[{Key:"Name",Value:`${l}-${h}-${_e}`},{Key:"Environment",Value:h}]},DependsOn:[Ot]})}break}}generateServerless(l,h){if(this.mergedConfig.infrastructure?.functions)for(let[A,w]of Object.entries(this.mergedConfig.infrastructure.functions)){if(!this.shouldDeploy(w))continue;let{role:v,logicalId:Ee}=ee.createRole({slug:l,environment:h,roleName:`${l}-${h}-${A}-role`,servicePrincipal:"lambda.amazonaws.com",managedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]});this.builder.addResource(Ee,v);let{lambdaFunction:oe,logicalId:ae}=a.createLambdaFunction({slug:l,environment:h,functionName:`${l}-${h}-${A}`,handler:w.handler||"index.handler",runtime:w.runtime||"nodejs20.x",code:{zipFile:w.code||"export const handler = async () => ({ statusCode: 200 });"},role:Ee,timeout:w.timeout,memorySize:w.memorySize});this.builder.addResource(ae,oe)}if(this.mergedConfig.infrastructure?.api){let{restApi:A,logicalId:w}=$d.createRestApi({slug:l,environment:h,apiName:`${l}-${h}-api`});this.builder.addResource(w,A)}}generateServer(l,h){if(!this.mergedConfig.infrastructure?.servers)return;let A=this.mergedConfig.infrastructure.servers,w=this.mergedConfig.infrastructure?.compute,v=this.mergedConfig.infrastructure?.ssl;if(Object.values(A).some((oe)=>!oe.privateNetwork||oe.privateNetwork==="create"))this.generateNetworkInfrastructure(l,h);for(let[oe,ae]of Object.entries(A)){let be=ae.instanceType||ae.size||w?.size,_e=(be?a.InstanceSize.specs[be]:void 0)?.instanceType||be||"t3.micro",_t=ae.type||"app",ir=ae.userData||ae.startupScript;if(!ir)ir=a.UserData.generateAppServerScript({runtime:"bun",runtimeVersion:ae.bunVersion||"latest",webServer:"none",domain:ae.domain,enableSsl:!!v?.enabled,sslEmail:v?.letsEncrypt?.email,installRedis:_t==="cache",installDatabaseClients:!!ae.database});let fr=ae.privateNetwork&&ae.privateNetwork!=="create"?ae.privateNetwork:{Ref:"VPC"},ut=ae.subnet||{Ref:"PublicSubnet1"},k=!!this.mergedConfig.infrastructure?.email?.server?.enabled,Ot=[22,80,443,this.resolveApiOriginPort()];if(k)Ot.push(25,465,587,143,993);let E=a.createServerModeStack({slug:`${l}-${oe}`,environment:h,vpcId:fr,subnetId:ut,instanceType:_e,keyName:ae.keyName||`${l}-${h}`,domain:ae.domain,userData:ir,volumeSize:ae.diskSize||20,imageId:ae.image,allowedPorts:Ot});for(let[lt,Tt]of Object.entries(E.resources))this.builder.addResource(lt,Tt);this.serverEipLogicalIds.set(oe,E.outputs.eipLogicalId),this.serverEipLogicalIds.set(`${oe}Instance`,E.outputs.instanceLogicalId),this.builder.addOutput(`${oe}InstanceId`,{Value:{Ref:E.outputs.instanceLogicalId},Description:`Instance ID for ${oe} server`}),this.builder.addOutput(`${oe}PublicIp`,{Value:{Ref:E.outputs.eipLogicalId},Description:`Public IP for ${oe} server`})}}generateComputeApp(l,h){let A=this.mergedConfig.infrastructure?.compute;if(!A)return;let w=this.mergedConfig.sites||{},v=Object.entries(w),oe=this.mergedConfig.infrastructure?.dns?.domain,ae=this.mergedConfig.infrastructure?.database,be=A.size,_e=(be?a.InstanceSize.specs[be]:void 0)?.instanceType||be||"t3.micro";if(!this.builder.hasResource("VPC"))this.generateNetworkInfrastructure(l,h);let _t=this.buildCaddyfile(v),ir=a.UserData.generateBunAppScript({runtime:A.runtime||"bun",runtimeVersion:A.runtimeVersion||"latest",systemPackages:A.systemPackages,database:ae,caddyfile:_t}),fr=Ns(A.appUpdates),ut=fr.length>0?`${ir}
11
11
  ${fr.join(`
12
12
  `)}
13
- `:ir,at=v.map(([,Bt])=>Bt.port).filter((Bt)=>typeof Bt==="number"&&![80,443].includes(Bt)),k=this.resolveApiOriginPort(),Ot=`${l}${h}DeployBucket`.replace(/[^a-zA-Z0-9]/g,""),E=`${l}-${h}-deploy`;this.builder.addResource(Ot,{Type:"AWS::S3::Bucket",Properties:{BucketName:E,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},LifecycleConfiguration:{Rules:[{Id:"expire-old-releases",Status:"Enabled",ExpirationInDays:7,Prefix:"releases/"}]},Tags:[{Key:"Project",Value:l},{Key:"Environment",Value:h},{Key:"ManagedBy",Value:"ts-cloud"}]}});let lt=a.createServerModeStack({slug:`${l}-app`,environment:h,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},instanceType:_e,keyName:A.allowSsh?`${l}-${h}`:void 0,domain:oe,userData:ut,volumeSize:A.disk?.size||20,imageId:A.image,allowedPorts:[...A.allowSsh?[22]:[],80,443,k,...at]}),Tt=lt.resources[lt.outputs.instanceLogicalId];if(Tt?.Properties){let Bt=Tt.Properties.Tags||[];Tt.Properties.Tags=[...Bt,{Key:"Project",Value:l},{Key:"Environment",Value:h},{Key:"Role",Value:"app"},{Key:"ManagedBy",Value:"ts-cloud"}]}let xt=lt.resources[lt.outputs.roleLogicalId];if(xt?.Properties)xt.Properties.Policies=xt.Properties.Policies||[],xt.Properties.Policies.push({PolicyName:"DeployBucketRead",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:ListBucket"],Resource:[`arn:aws:s3:::${E}`,`arn:aws:s3:::${E}/*`]}]}});for(let[Bt,mr]of Object.entries(lt.resources))this.builder.addResource(Bt,mr);this.builder.addOutput("deployBucketName",{Value:{Ref:Ot},Description:"S3 bucket where release tarballs are uploaded"}),this.builder.addOutput("appInstanceId",{Value:{Ref:lt.outputs.instanceLogicalId},Description:"EC2 instance ID for the app server"}),this.builder.addOutput("appPublicIp",{Value:{Ref:lt.outputs.eipLogicalId},Description:"Public IP for the app server"}),this.serverEipLogicalIds.set("app",lt.outputs.eipLogicalId),this.serverEipLogicalIds.set("appInstance",lt.outputs.instanceLogicalId)}generateJumpBox(l,h){let A=this.mergedConfig.infrastructure?.jumpBox;if(!A)return;let w=A===!0?{}:A;if(w.enabled===!1)return;this.generateNetworkInfrastructure(l,h);let v=w.size||"micro",oe=a.InstanceSize.specs[v]?.instanceType||v||"t3.micro",ae;if(w.mountEfs)ae={fileSystemId:typeof w.mountEfs==="string"?w.mountEfs:{Ref:"FileSystem"},mountPath:w.mountPath||"/mnt/efs"};let be;if(w.databaseTools)be=a.JumpBox.withDatabaseTools({slug:l,environment:h,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:w.keyName||`${l}-${h}`,allowedCidrs:w.allowedCidrs});else if(ae)be=a.JumpBox.withEfsMount({slug:l,environment:h,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:w.keyName||`${l}-${h}`,fileSystemId:ae.fileSystemId,mountPath:ae.mountPath,allowedCidrs:w.allowedCidrs});else be=a.createJumpBox({slug:l,environment:h,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:w.keyName||`${l}-${h}`,instanceType:oe,allowedCidrs:w.allowedCidrs,mountEfs:ae});for(let[dt,_e]of Object.entries(be.resources))this.builder.addResource(dt,_e);this.builder.addOutput("JumpBoxInstanceId",{Value:{Ref:be.instanceLogicalId},Description:"The ID of the JumpBox EC2 instance (use with SSM Session Manager or SSH)"})}generateSharedInfrastructure(l,h){let A=this.mergedConfig.infrastructure?.ssl,w=this.mergedConfig.infrastructure?.dns,v=w?.domain,Ee=w?.hostedZoneId,oe=[],ae,be;if(A?.certificateArn)be=A.certificateArn;else if(A?.enabled&&v&&Ee){let at=A.domains||[v],k=at[0],Ot=at.slice(1).map((Tt)=>{if(Tt.includes(".")&&Tt.endsWith(k))return Tt.replace(`.${k}`,"");return Tt}),{certificate:E,logicalId:lt}=C.createCertificate({domain:k,subdomains:Ot,slug:l,environment:h,validationMethod:"DNS",hostedZoneId:Ee});ae=lt,this.builder.addResource(lt,E)}if(this.mergedConfig.infrastructure?.storage){let at=Object.entries(this.mergedConfig.infrastructure.storage).some(([,E])=>E.website),k;if(at&&(ae||be))k=`${l}${h}CloudFrontOAC`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(k,{Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${l}-${h}-s3-oac`,Description:`OAC for ${l} ${h} S3 website buckets`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}});let Ot=Object.entries(this.mergedConfig.infrastructure.storage).map(([E,lt])=>({name:E,config:lt,mountPath:this.normalizeMountPath(lt),rewriteStyle:lt.pathRewriteStyle||"directory",logicalId:this.storageBucketLogicalId(l,h,E)})).filter((E)=>E.name!=="public"&&E.config.website&&E.mountPath);for(let[E,lt]of Object.entries(this.mergedConfig.infrastructure.storage)){let Tt=!!(lt.website&&k),xt=this.storageBucketName(l,h,E),{bucket:Bt,logicalId:mr}=Re.createBucket({slug:l,name:E,environment:h,bucketName:xt,versioning:lt.versioning,encryption:lt.encryption,public:Tt?!1:lt.public}),hr=this.normalizeMountPath(lt),Ar;if(lt.failover){let Sr=`infrastructure.storage.${E}`;if(!Tt||!v||hr&&E!=="public")throw Error(`${Sr}.failover needs this bucket to be served by its own CloudFront distribution: a website bucket (website: true), not mounted under the path of another site, with infrastructure.dns.domain set and SSL configured (infrastructure.ssl.certificateArn, or ssl.enabled with dns.hostedZoneId).`);if(Ar=Cg({failover:lt.failover,primaryBucket:xt,primaryRegion:this.mergedConfig.project.region||"us-east-1",where:Sr}),Ar.replicate&&Bt.Properties){let Rr=`${mr}FailoverReplicationRole`;this.builder.addResource(Rr,bg({primaryBucket:xt,replicaBucket:Ar.replicaBucket}));let ti=Bt.Properties;ti.VersioningConfiguration={Status:"Enabled"},ti.ReplicationConfiguration=vg({replicaBucket:Ar.replicaBucket,roleArn:{"Fn::GetAtt":[Rr,"Arn"]}})}}if(Tt&&Bt.Properties)Bt.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1};if(this.builder.addResource(mr,Bt),lt.website){let Sr=typeof lt.website==="object"?lt.website:{},Rr=Re.enableWebsiteHosting(Bt,Sr.indexDocument||"index.html",Sr.errorDocument);this.builder.addResource(mr,Rr)}let Tr=this.normalizeMountPath(lt);if(Tt&&k&&v&&!(Tr&&E!=="public")){let Sr=`${l}${h}${E}CDN`.replace(/[^a-zA-Z0-9]/g,""),Rr=[];if(lt.aliases&&lt.aliases.length>0)Rr.push(...lt.aliases);else if(E==="public"){if(Rr.push(v),A?.domains?.includes(`www.${v}`))Rr.push(`www.${v}`)}else if(E==="docs")Rr.push(`docs.${v}`);else if(E==="blog")Rr.push(`blog.${v}`);let ti=typeof lt.website==="object"?lt.website:{},pn=lt.spa===!0,li=ti.errorDocument||(pn?"index.html":"404.html"),Dr=[];if(pn)Dr.push({ErrorCode:403,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300});else Dr.push({ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${li}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${li}`,ErrorCachingMinTTL:300});let An=be&&Rr.length>0?{AcmCertificateArn:be,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:ae&&Rr.length>0?{AcmCertificateArn:{Ref:ae},SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},kn=`S3-${l}-${h}-${E}`,Ja=this.mergedConfig.project.region||"us-east-1",Ln;if(!pn)Ln=`${l}${h}${E}UrlRewrite`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(Ln,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${h}-${E}-url-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`URL rewrite for ${l} ${h} ${E} - appends .html to extensionless paths`,Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) { var request = event.request; var uri = request.uri; if (uri.endsWith('/')) { request.uri += 'index.html'; }
14
- else if (!uri.includes('.')) { request.uri += '.html'; } return request; }`}});let Fn=[{Id:kn,DomainName:{"Fn::Sub":`\${${mr}}.s3.${Ja}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:k}}],jn=[],ts=[];if(this.shouldRouteStorageBucketToCompute(E,lt)){this.appendComputeAppOrigin(Fn,jn,ts,l,h,this.resolveComputeCachePathPatterns(lt.computeRoutes));for(let Pr of Ot){let ba=`S3-${l}-${h}-${Pr.name}`,ds=`${l}${h}${Pr.name}PathMountRewrite`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ds,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${h}-${Pr.name}-path-mount-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`Path mount rewrite for ${l} ${h} ${Pr.name} at ${Pr.mountPath}`,Runtime:"cloudfront-js-2.0"},FunctionCode:this.pathMountRewriteFunctionCode(Pr.mountPath,Pr.rewriteStyle)}}),Fn.push({Id:ba,DomainName:{"Fn::Sub":`\${${Pr.logicalId}}.s3.${Ja}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:k}}),ts.push(Pr.logicalId,ds);for(let Dc of[Pr.mountPath,`${Pr.mountPath}/*`])jn.push({PathPattern:Dc,TargetOriginId:ba,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[ds,"FunctionARN"]}}]})}}let Ca,ac=kn;if(Ar){let Pr=`${kn}-failover`;Object.assign(Fn[0],Ar.primaryConnection),Fn.push({Id:Pr,DomainName:Eg(Ar.replicaBucket,Ar.replicaRegion),OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:k}}),Ca=qr({primaryOriginId:kn,secondaryOriginId:Pr,statusCodes:Ar.statusCodes}),ac=Ca.Items[0].Id}let ls={Type:"AWS::CloudFront::Distribution",DependsOn:[mr,k,...Ln?[Ln]:[],...ts],Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${h} ${E} site`,DefaultRootObject:"index.html",Origins:Fn,...Ca?{OriginGroups:Ca}:{},DefaultCacheBehavior:{TargetOriginId:ac,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...Ln?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[Ln,"FunctionARN"]}}]}:{}},...jn.length>0?{CacheBehaviors:jn}:{},...Rr.length>0?{Aliases:Rr}:{},ViewerCertificate:An,PriceClass:"PriceClass_100",HttpVersion:"http2and3",IPV6Enabled:!0,CustomErrorResponses:Dr}}};if(ae)ls.DependsOn.push(ae);if(Ar)jt(ls.Properties.DistributionConfig,`infrastructure.storage.${E}`),this.storageFailoverReplicas.push({name:E,primaryBucket:xt,primaryRegion:Ja,replicaBucket:Ar.replicaBucket,replicaRegion:Ar.replicaRegion,replicate:Ar.replicate,distributionArnOutput:`${E}CloudFrontDistributionArn`}),this.builder.addOutput(`${E}CloudFrontDistributionArn`,{Value:{"Fn::Sub":`arn:\${AWS::Partition}:cloudfront::\${AWS::AccountId}:distribution/\${${Sr}}`},Description:`CloudFront distribution ARN for ${E} (scopes the bucket policy of the failover replica)`}),this.builder.addOutput(`${E}FailoverBucketName`,{Value:Ar.replicaBucket,Description:`Failover replica bucket for ${E} (${Ar.replicaRegion}), outside this stack`});this.builder.addResource(Sr,ls);let Ic=`${mr}CloudFrontPolicy`;if(this.builder.addResource(Ic,{Type:"AWS::S3::BucketPolicy",DependsOn:[mr,Sr],Properties:{Bucket:{Ref:mr},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":`arn:aws:s3:::\${${mr}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${Sr}}`}}}}]}}}),this.shouldRouteStorageBucketToCompute(E,lt))for(let Pr of Ot){let ba=`${Pr.logicalId}CloudFrontPolicy`;this.builder.addResource(ba,{Type:"AWS::S3::BucketPolicy",DependsOn:[Pr.logicalId,Sr],Properties:{Bucket:{Ref:Pr.logicalId},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":`arn:aws:s3:::\${${Pr.logicalId}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${Sr}}`}}}}]}}})}if(Rr.length>0)oe.push({name:E,bucketLogicalId:mr,distLogicalId:Sr,oacLogicalId:k,aliases:Rr});this.builder.addOutput(`${E}CloudFrontDomain`,{Value:{"Fn::GetAtt":[Sr,"DomainName"]},Description:`CloudFront domain for ${E}`}),this.builder.addOutput(`${E}CloudFrontDistributionId`,{Value:{Ref:Sr},Description:`CloudFront distribution ID for ${E}`})}if(this.builder.addOutput(`${E}BucketName`,{Value:{Ref:mr},Description:`S3 bucket name for ${E}`}),E==="public")this.builder.addOutput("FrontendBucketName",{Value:{Ref:mr},Description:"Frontend S3 bucket name"});if(E==="docs")this.builder.addOutput("DocsBucketName",{Value:{Ref:mr},Description:"Documentation S3 bucket name"});if(E==="blog")this.builder.addOutput("BlogBucketName",{Value:{Ref:mr},Description:"Blog S3 bucket name"})}}if(this.mergedConfig.infrastructure?.sftp){let at=this.mergedConfig.infrastructure.sftp,k=Ld.create({...at,storage:this.resolveSftpStorage(at,l,h)??at.storage,slug:l,environment:h});for(let[Ot,E]of Object.entries(k.resources))this.builder.addResource(Ot,E);this.builder.addOutput("SftpServerId",{Value:{Ref:k.serverLogicalId},Description:"AWS Transfer Family SFTP server ID"}),this.builder.addOutput("SftpEndpoint",{Value:{"Fn::Sub":`\${${k.serverLogicalId}}.server.transfer.\${AWS::Region}.amazonaws.com`},Description:"AWS Transfer Family SFTP endpoint"}),this.builder.addOutput("SftpStorageDomain",{Value:k.domain,Description:"Storage backing the SFTP server (EFS or S3)"})}if(Ee&&oe.length>0)for(let{name:at,distLogicalId:k,aliases:Ot}of oe)for(let E of Ot){let lt=E.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${lt}ARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[k],Properties:{HostedZoneId:Ee,Name:E,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[k,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}}),this.builder.addResource(`${lt}AAAARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[k],Properties:{HostedZoneId:Ee,Name:E,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":[k,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}})}if(this.mergedConfig.infrastructure?.databases){for(let[at,k]of Object.entries(this.mergedConfig.infrastructure.databases))if(k.engine==="dynamodb"){let{table:Ot,logicalId:E}=zt.createTable({slug:l,environment:h,tableName:`${l}-${h}-${at}`,partitionKey:k.partitionKey||{name:"id",type:"S"},sortKey:k.sortKey});this.builder.addResource(E,Ot)}else if(k.engine==="postgres"){let{dbInstance:Ot,logicalId:E}=zt.createPostgres({slug:l,environment:h,dbInstanceIdentifier:`${l}-${h}-${at}`,masterUsername:k.username||"admin",masterUserPassword:k.password||"changeme123",allocatedStorage:k.storage||20,dbInstanceClass:k.instanceClass||"db.t3.micro"});this.builder.addResource(E,Ot)}else if(k.engine==="mysql"){let{dbInstance:Ot,logicalId:E}=zt.createMysql({slug:l,environment:h,dbInstanceIdentifier:`${l}-${h}-${at}`,masterUsername:k.username||"admin",masterUserPassword:k.password||"changeme123",allocatedStorage:k.storage||20,dbInstanceClass:k.instanceClass||"db.t3.micro"});this.builder.addResource(E,Ot)}}if(this.mergedConfig.infrastructure?.cdn)for(let[at,k]of Object.entries(this.mergedConfig.infrastructure.cdn)){if(!k.origin)continue;let Ot=typeof k.customDomain==="string"?k.customDomain:k.customDomain?.domain||k.domain,E=typeof k.customDomain==="object"?k.customDomain?.certificateArn:k.certificateArn,lt=E||be,Tt=`${l}${h}${at}CDN`.replace(/[^a-zA-Z0-9]/g,""),xt=`S3-${l}-${h}-${at}-cdn`,Bt=[{Id:xt,DomainName:k.origin,OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginShield:k.originShield?{Enabled:!0,OriginShieldRegion:k.originShieldRegion||this.mergedConfig.environments[h]?.region||this.mergedConfig.project.region||"us-east-1"}:{Enabled:!1},...De(k,`infrastructure.cdn.${at}`)}],mr=[],hr=[],Ar=["GET","HEAD","OPTIONS"],Tr=xt,Sr;if(k.failoverOrigin){Vt(Ar,`the default cache behavior of infrastructure.cdn.${at}`);let li=`${xt}-failover`,Dr=typeof k.failoverOrigin==="string"?{domain:k.failoverOrigin}:k.failoverOrigin;if(!Dr.domain)throw Error(`infrastructure.cdn.${at}.failoverOrigin.domain is required`);if(Dr.domain===k.origin)throw Error(`infrastructure.cdn.${at}: failoverOrigin must differ from origin (both are ${k.origin})`);Bt.push({Id:li,DomainName:Dr.domain,OriginPath:Dr.originPath||"",..._d(Dr.domain)?{S3OriginConfig:{OriginAccessIdentity:""}}:{CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"}},OriginShield:{Enabled:!1},...De(Dr,`infrastructure.cdn.${at}.failoverOrigin`)}),Sr=qr({primaryOriginId:xt,secondaryOriginId:li,statusCodes:k.failoverStatusCodes}),Tr=Sr.Items[0].Id}else if(k.failoverStatusCodes)throw Error(`infrastructure.cdn.${at}: failoverStatusCodes needs failoverOrigin to fail over to`);if(k.routeCompute)this.appendComputeAppOrigin(Bt,mr,hr,l,h,this.resolveComputeCachePathPatterns(k.computeRoutes));let Rr=lt&&Ot?{AcmCertificateArn:ae&&!E?{Ref:ae}:lt,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},ti=[...hr];if(ae&&!E&&Ot)ti.push(ae);let pn={Type:"AWS::CloudFront::Distribution",...ti.length>0?{DependsOn:ti}:{},Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${h} ${at} CDN`,DefaultRootObject:"index.html",Origins:Bt,...Sr?{OriginGroups:Sr}:{},DefaultCacheBehavior:{TargetOriginId:Tr,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:Ar,CachedMethods:["GET","HEAD","OPTIONS"],Compress:k.compress!==!1,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},...mr.length>0?{CacheBehaviors:mr}:{},...Ot&&lt?{Aliases:[Ot]}:{},ViewerCertificate:Rr,PriceClass:"PriceClass_100",HttpVersion:k.http3?"http2and3":"http2"}}};if(jt(pn.Properties.DistributionConfig,`infrastructure.cdn.${at}`),this.builder.addResource(Tt,pn),Ee&&Ot&&lt){let li=Ot.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${li}CdnARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[Tt,...ae&&!E?[ae]:[]],Properties:{HostedZoneId:Ee,Name:Ot,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:{"Fn::GetAtt":[Tt,"DomainName"]}}}})}}if(this.mergedConfig.infrastructure?.queues)for(let[at,k]of Object.entries(this.mergedConfig.infrastructure.queues)){if(!this.shouldDeploy(k))continue;let{queue:Ot,logicalId:E}=U.createQueue({slug:l,environment:h,name:`${l}-${h}-${at}`,fifo:k.fifo,visibilityTimeout:k.visibilityTimeout,messageRetentionPeriod:k.messageRetentionPeriod,delaySeconds:k.delaySeconds,maxMessageSize:k.maxMessageSize,receiveMessageWaitTime:k.receiveMessageWaitTime,contentBasedDeduplication:k.contentBasedDeduplication,encrypted:k.encrypted,kmsKeyId:k.kmsKeyId});this.builder.addResource(E,Ot);let lt;if(k.deadLetterQueue){let{deadLetterQueue:Tt,updatedSourceQueue:xt,deadLetterLogicalId:Bt}=U.createDeadLetterQueue(E,{slug:l,environment:h,maxReceiveCount:k.maxReceiveCount});lt=Bt,this.builder.addResource(Bt,Tt);let hr=this.builder.getResources()[E];if(hr?.Properties)hr.Properties.RedrivePolicy=xt.Properties?.RedrivePolicy}if(k.trigger){let Tt=k.trigger,xt=`${l}${h}${Tt.functionName}`.replace(/[^a-zA-Z0-9]/g,""),Bt={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:{"Fn::GetAtt":[E,"Arn"]},FunctionName:{Ref:xt},BatchSize:Tt.batchSize||10,MaximumBatchingWindowInSeconds:Tt.batchWindow||0,Enabled:!0,...Tt.reportBatchItemFailures!==!1&&{FunctionResponseTypes:["ReportBatchItemFailures"]},...Tt.maxConcurrency&&{ScalingConfig:{MaximumConcurrency:Tt.maxConcurrency}},...Tt.filterPattern&&{FilterCriteria:{Filters:[{Pattern:JSON.stringify(Tt.filterPattern)}]}}},DependsOn:[E,xt]};this.builder.addResource(`${E}Trigger`,Bt)}if(k.alarms?.enabled){let Tt=k.alarms,xt=Tt.notificationTopicArn;if(!xt&&Tt.notificationEmails?.length){let hr=`${E}AlarmTopic`;this.builder.addResource(hr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${h}-${at}-alarms`,DisplayName:`${at} Queue Alarms`}}),Tt.notificationEmails.forEach((Ar,Tr)=>{this.builder.addResource(`${hr}Sub${Tr}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:hr},Protocol:"email",Endpoint:Ar}})}),xt={Ref:hr}}let Bt=Tt.queueDepthThreshold||1000;this.builder.addResource(`${E}DepthAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${h}-${at}-queue-depth`,AlarmDescription:`Queue ${at} depth exceeds ${Bt} messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:Bt,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[E,"QueueName"]}}],...xt&&{AlarmActions:[xt],OKActions:[xt]}}});let mr=Tt.messageAgeThreshold||3600;if(this.builder.addResource(`${E}AgeAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${h}-${at}-message-age`,AlarmDescription:`Queue ${at} oldest message exceeds ${mr} seconds`,MetricName:"ApproximateAgeOfOldestMessage",Namespace:"AWS/SQS",Statistic:"Maximum",Period:300,EvaluationPeriods:2,Threshold:mr,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[E,"QueueName"]}}],...xt&&{AlarmActions:[xt],OKActions:[xt]}}}),lt&&Tt.dlqAlarm!==!1)this.builder.addResource(`${lt}Alarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${h}-${at}-dlq-messages`,AlarmDescription:`Dead letter queue for ${at} has messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Sum",Period:300,EvaluationPeriods:1,Threshold:0,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[lt,"QueueName"]}}],...xt&&{AlarmActions:[xt]}}})}if(k.subscribe){let Tt=k.subscribe,xt=Tt.topicArn;if(!xt&&Tt.topicName)xt={Ref:Tt.topicName};if(xt){this.builder.addResource(`${E}SnsPolicy`,{Type:"AWS::SQS::QueuePolicy",Properties:{Queues:[{Ref:E}],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"sns.amazonaws.com"},Action:"sqs:SendMessage",Resource:{"Fn::GetAtt":[E,"Arn"]},Condition:{ArnEquals:{"aws:SourceArn":xt}}}]}}});let Bt={TopicArn:xt,Protocol:"sqs",Endpoint:{"Fn::GetAtt":[E,"Arn"]},RawMessageDelivery:Tt.rawMessageDelivery||!1};if(Tt.filterPolicy)Bt.FilterPolicy=Tt.filterPolicy,Bt.FilterPolicyScope=Tt.filterPolicyScope||"MessageAttributes";this.builder.addResource(`${E}SnsSub`,{Type:"AWS::SNS::Subscription",Properties:Bt,DependsOn:`${E}SnsPolicy`})}}}if(this.mergedConfig.infrastructure?.realtime?.enabled)if((this.mergedConfig.infrastructure.realtime.mode||"serverless")==="server")this.generateRealtimeServerResources(l,h);else this.generateRealtimeResources(l,h);let dt=this.mergedConfig.infrastructure?.redirects;if(dt){let at=dt.target||this.mergedConfig.infrastructure?.dns?.domain||"",k=dt.protocol||"https";if(dt.domains?.length&&at)for(let Ot of dt.domains){let{bucket:E,bucketPolicy:lt,logicalId:Tt,policyLogicalId:xt}=yt.createDomainRedirectBucket({slug:l,environment:h,sourceDomain:Ot,targetDomain:at,protocol:k});this.builder.addResource(Tt,E),this.builder.addResource(xt,lt)}if(dt.paths&&Object.keys(dt.paths).length>0){let Ot=yt.fromMapping(dt.paths,{statusCode:dt.statusCode||301}),{function:E,logicalId:lt}=yt.createPathRedirectFunction({slug:l,environment:h,rules:Ot});this.builder.addResource(lt,E)}}if(this.mergedConfig.infrastructure?.monitoring?.alarms)for(let[at,k]of Object.entries(this.mergedConfig.infrastructure.monitoring.alarms)){let{alarm:Ot,logicalId:E}=ho.createAlarm({slug:l,environment:h,alarmName:`${l}-${h}-${at}`,metricName:k.metricName||"Errors",namespace:k.namespace||"AWS/Lambda",threshold:k.threshold||1,comparisonOperator:k.comparisonOperator||"GreaterThanThreshold"});this.builder.addResource(E,Ot)}let _e=this.mergedConfig.infrastructure?.cache;if(_e){let at=_e.type||"redis";if(at==="redis"){this.generateNetworkInfrastructure(l,h);let k=_e.redis||{},{replicationGroup:Ot,subnetGroup:E,logicalId:lt,subnetGroupId:Tt}=mo.createRedis({slug:l,environment:h,nodeType:k.nodeType||_e.nodeType||"cache.t3.micro",engineVersion:k.engineVersion||"7.1",port:k.port||6379,numCacheClusters:k.numCacheNodes||2,automaticFailover:k.automaticFailoverEnabled!==!1,atRestEncryption:!0,transitEncryption:!0,snapshotRetentionDays:k.snapshotRetentionLimit||7,snapshotWindow:k.snapshotWindow,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(lt,Ot),E&&Tt)this.builder.addResource(Tt,E);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[lt,"PrimaryEndPoint.Address"]},Description:"Redis primary endpoint address"}),this.builder.addOutput("CachePort",{Value:{"Fn::GetAtt":[lt,"PrimaryEndPoint.Port"]},Description:"Redis primary endpoint port"})}else if(at==="memcached"){this.generateNetworkInfrastructure(l,h);let k=_e.elasticache||{},{cluster:Ot,subnetGroup:E,logicalId:lt,subnetGroupId:Tt}=mo.createMemcached({slug:l,environment:h,nodeType:k.nodeType||_e.nodeType||"cache.t3.micro",engineVersion:k.engineVersion||"1.6.22",numCacheNodes:k.numCacheNodes||2,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(lt,Ot),E&&Tt)this.builder.addResource(Tt,E);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[lt,"ConfigurationEndpoint.Address"]},Description:"Memcached configuration endpoint address"})}}let _t=this.mergedConfig.infrastructure?.email;if(_t){let at=_t.domain||this.mergedConfig.infrastructure?.dns?.domain;if(at){let{emailIdentity:k,logicalId:Ot}=m.verifyDomain({domain:at,slug:l,environment:h,enableDkim:_t.enableDkim!==!1,dkimKeyLength:_t.dkimKeyLength||"RSA_2048_BIT"});if(this.builder.addResource(Ot,k),_t.configurationSet!==!1){let{configurationSet:Tt,logicalId:xt}=m.createConfigurationSet({slug:l,environment:h});this.builder.addResource(xt,Tt)}let E=_t.hostedZoneId||this.mergedConfig.infrastructure?.dns?.hostedZoneId;if(E){if(_t.enableDkim!==!1)for(let hr=1;hr<=3;hr++){let Ar=`DkimRecord${hr}${at.replace(/\./g,"")}`;this.builder.addResource(Ar,{Type:"AWS::Route53::RecordSet",DependsOn:[Ot],Properties:{HostedZoneId:E,Name:{"Fn::GetAtt":[Ot,`DkimDNSTokenName${hr}`]},Type:"CNAME",TTL:1800,ResourceRecords:[{"Fn::GetAtt":[Ot,`DkimDNSTokenValue${hr}`]}]}})}let{record:Tt,logicalId:xt}=m.createSpfRecord(at,E);this.builder.addResource(xt,Tt);let{record:Bt,logicalId:mr}=m.createDmarcRecord(at,E,{policy:"none",reportingEmail:_t.dmarcReportingEmail||`dmarc-reports@${at}`});this.builder.addResource(mr,Bt)}this.builder.addOutput("EmailDomain",{Value:at,Description:"SES verified email domain"});let lt=_t.server;if(lt?.enabled&&E){let Tt=this.mergedConfig.environments[h]?.region||this.mergedConfig.project.region||"us-east-1",xt=`${l}-${h}-email`,{role:Bt,policy:mr,roleLogicalId:hr,policyLogicalId:Ar}=m.createEmailLambdaRole({slug:l,environment:h,s3BucketArn:`arn:aws:s3:::${xt}`,sesIdentityArn:`arn:aws:ses:${Tt}:*:identity/${at}`});this.builder.addResource(hr,Bt),this.builder.addResource(Ar,mr);let{function:Tr,permission:Sr,logicalId:Rr,permissionLogicalId:ti}=m.createInboundEmailLambda({slug:l,environment:h,roleArn:{"Fn::GetAtt":[hr,"Arn"]},s3BucketName:xt,organizedPrefix:"mailboxes/"});this.builder.addResource(Rr,Tr),this.builder.addResource(ti,Sr);let pn=m.createInboundEmailSetup({slug:l,environment:h,domain:at,s3BucketName:xt,s3KeyPrefix:"inbox/",region:Tt,hostedZoneId:E,lambdaFunctionArn:{"Fn::GetAtt":[Rr,"Arn"]}});for(let[Dr,An]of Object.entries(pn.resources)){if(An.Type==="AWS::SES::ReceiptRule")An.DependsOn=[ti,Rr];this.builder.addResource(Dr,An)}this.builder.addOutput("InboundEmailLambda",{Value:{Ref:Rr},Description:"Inbound email processing Lambda function"}),this.builder.addOutput("EmailBucket",{Value:xt,Description:"S3 bucket for email storage"});let li=this.serverEipLogicalIds.get("app");if(li&&E){let An=`${lt?.subdomain||"mail"}.${at}`,kn=An.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${kn}ARecord`,{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:E,Name:An,Type:"A",TTL:"300",ResourceRecords:[{Ref:li}]}})}this.builder.addOutput("MailHost",{Value:`mail.${at}`,Description:"Mail server hostname for SMTP/IMAP clients"})}}}let ir=this.mergedConfig.infrastructure?.search;if(ir){let at=ir.vpc?{subnetIds:[{Ref:"PublicSubnet1"}],securityGroupIds:[]}:void 0;if(at)this.generateNetworkInfrastructure(l,h);let{domain:k,logicalId:Ot}=Kt.createDomain({slug:l,environment:h,engineVersion:ir.engineVersion||"OpenSearch_2.11",instanceType:ir.instanceType||"t3.small.search",instanceCount:ir.instanceCount||1,volumeSize:ir.volumeSize||10,volumeType:ir.volumeType||"gp3",dedicatedMaster:ir.dedicatedMaster||!1,dedicatedMasterType:ir.dedicatedMasterType,dedicatedMasterCount:ir.dedicatedMasterCount||3,multiAz:ir.multiAz||!1,encryption:ir.encryption||{atRest:!0,nodeToNode:!0},advancedSecurity:ir.advancedSecurity,autoTune:ir.autoTune!==!1,vpc:at});this.builder.addResource(Ot,k),this.builder.addOutput("SearchDomainEndpoint",{Value:{"Fn::GetAtt":[Ot,"DomainEndpoint"]},Description:"OpenSearch domain endpoint"}),this.builder.addOutput("SearchDomainArn",{Value:{"Fn::GetAtt":[Ot,"Arn"]},Description:"OpenSearch domain ARN"})}let fr=this.mergedConfig.infrastructure?.fileSystem;if(fr&&Object.keys(fr).length>0){this.generateNetworkInfrastructure(l,h);for(let[at,k]of Object.entries(fr)){let{fileSystem:Ot,logicalId:E}=Ke.createFileSystem({slug:`${l}-${at}`,environment:h,encrypted:k.encrypted!==!1,performanceMode:k.performanceMode||"generalPurpose",throughputMode:k.throughputMode||"bursting",enableBackup:!0});this.builder.addResource(E,Ot);let{securityGroup:lt,logicalId:Tt}=Ke.createEfsSecurityGroup({slug:`${l}-${at}`,environment:h,vpcId:{Ref:"VPC"},sourceCidrBlocks:["10.0.0.0/16"]});this.builder.addResource(Tt,lt);let{mountTargets:xt,logicalIds:Bt}=Ke.createMultiAzMountTargets(E,{slug:`${l}-${at}`,environment:h,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],securityGroupId:{Ref:Tt}});for(let mr=0;mr<xt.length;mr++)this.builder.addResource(Bt[mr],xt[mr]);this.builder.addOutput(`${at}FileSystemId`,{Value:{Ref:E},Description:`EFS file system ID for ${at}`})}}let ut=this.mergedConfig.infrastructure?.ai;if(ut){let at=ut.service||"ecs",k=ut.models||["*"],Ot=ut.allowStreaming!==!1,E;if(at==="ecs")E=Pe.enableBedrockForEcs({slug:l,environment:h,models:k,allowStreaming:Ot});else if(at==="ec2")E=Pe.enableBedrockForEc2({slug:l,environment:h,models:k,allowStreaming:Ot});else if(at==="lambda")E=Pe.enableBedrockForLambda({slug:l,environment:h,models:k,allowStreaming:Ot});else E=Pe.createBedrockRole(at,{slug:l,environment:h,models:k,allowStreaming:Ot});if(this.builder.addResource(E.logicalId,E.role),ut.allowAsync){let{policy:lt,logicalId:Tt}=Pe.createBedrockPolicy({slug:l,environment:h,models:k,allowStreaming:Ot,allowAsync:!0});this.builder.addResource(Tt,lt)}this.builder.addOutput("BedrockRoleArn",{Value:{"Fn::GetAtt":[E.logicalId,"Arn"]},Description:"IAM role ARN with Bedrock permissions"})}}generateRealtimeResources(l,h){let A=this.mergedConfig.infrastructure?.realtime;if(!A)return;let w=A.name||`${l}-${h}-realtime`,v=A.scaling||{},Ee=A.storage||{type:"dynamodb"},oe=v.handlerMemory||256,ae=v.handlerTimeout||30,be=`${l}${h}RealtimeConnections`.replace(/[^a-zA-Z0-9]/g,""),dt=`${l}${h}RealtimeChannels`.replace(/[^a-zA-Z0-9]/g,"");if(Ee.type==="dynamodb"){let Bt=Ee.dynamodb||{},mr=Bt.billingMode||"PAY_PER_REQUEST";this.builder.addResource(be,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${l}-${h}-realtime-connections`,BillingMode:mr,AttributeDefinitions:[{AttributeName:"connectionId",AttributeType:"S"},{AttributeName:"userId",AttributeType:"S"}],KeySchema:[{AttributeName:"connectionId",KeyType:"HASH"}],GlobalSecondaryIndexes:[{IndexName:"userId-index",KeySchema:[{AttributeName:"userId",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"},...mr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Bt.readCapacity||5,WriteCapacityUnits:Bt.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...mr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Bt.readCapacity||5,WriteCapacityUnits:Bt.writeCapacity||5}},...Bt.pointInTimeRecovery&&{PointInTimeRecoverySpecification:{PointInTimeRecoveryEnabled:!0}},Tags:[{Key:"Name",Value:`${l}-${h}-realtime-connections`},{Key:"Environment",Value:h}]}}),this.builder.addResource(dt,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${l}-${h}-realtime-channels`,BillingMode:mr,AttributeDefinitions:[{AttributeName:"channel",AttributeType:"S"},{AttributeName:"connectionId",AttributeType:"S"}],KeySchema:[{AttributeName:"channel",KeyType:"HASH"},{AttributeName:"connectionId",KeyType:"RANGE"}],GlobalSecondaryIndexes:[{IndexName:"connectionId-index",KeySchema:[{AttributeName:"connectionId",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"},...mr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Bt.readCapacity||5,WriteCapacityUnits:Bt.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...mr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Bt.readCapacity||5,WriteCapacityUnits:Bt.writeCapacity||5}},Tags:[{Key:"Name",Value:`${l}-${h}-realtime-channels`},{Key:"Environment",Value:h}]}})}let _e=`${l}${h}RealtimeRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(_e,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${h}-realtime-handler-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Policies:[{PolicyName:"RealtimeHandlerPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:UpdateItem"],Resource:[{"Fn::GetAtt":[be,"Arn"]},{"Fn::Sub":`\${${be}.Arn}/index/*`},{"Fn::GetAtt":[dt,"Arn"]},{"Fn::Sub":`\${${dt}.Arn}/index/*`}]},{Effect:"Allow",Action:"execute-api:ManageConnections",Resource:{"Fn::Sub":"arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:*/*"}}]}}]}});let _t=`${l}${h}RealtimeConnect`.replace(/[^a-zA-Z0-9]/g,""),ir=`${l}${h}RealtimeDisconnect`.replace(/[^a-zA-Z0-9]/g,""),fr=`${l}${h}RealtimeMessage`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(_t,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${h}-realtime-connect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[_e,"Arn"]},MemorySize:oe,Timeout:ae,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:be},CHANNELS_TABLE:{Ref:dt},ENVIRONMENT:h}},Code:{ZipFile:this.generateConnectHandlerCode()}},DependsOn:[_e,be]}),this.builder.addResource(ir,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${h}-realtime-disconnect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[_e,"Arn"]},MemorySize:oe,Timeout:ae,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:be},CHANNELS_TABLE:{Ref:dt},ENVIRONMENT:h}},Code:{ZipFile:this.generateDisconnectHandlerCode()}},DependsOn:[_e,be,dt]}),this.builder.addResource(fr,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${h}-realtime-message`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[_e,"Arn"]},MemorySize:oe,Timeout:ae,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:be},CHANNELS_TABLE:{Ref:dt},ENVIRONMENT:h}},Code:{ZipFile:this.generateMessageHandlerCode()}},DependsOn:[_e,be,dt]});let ut=`${l}${h}RealtimeApi`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ut,{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:w,ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action",Tags:{Name:w,Environment:h}}});let at=`${_t}Permission`,k=`${ir}Permission`,Ot=`${fr}Permission`;this.builder.addResource(at,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:_t},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${ut}}/*/$connect`}}}),this.builder.addResource(k,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:ir},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${ut}}/*/$disconnect`}}}),this.builder.addResource(Ot,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:fr},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${ut}}/*/$default`}}});let E=`${ut}ConnectInteg`,lt=`${ut}DisconnectInteg`,Tt=`${ut}MessageInteg`;this.builder.addResource(E,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:ut},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${_t}.Arn}/invocations`}}}),this.builder.addResource(lt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:ut},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${ir}.Arn}/invocations`}}}),this.builder.addResource(Tt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:ut},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${fr}.Arn}/invocations`}}}),this.builder.addResource(`${ut}ConnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:ut},RouteKey:"$connect",AuthorizationType:"NONE",Target:{"Fn::Sub":`integrations/\${${E}}`}}}),this.builder.addResource(`${ut}DisconnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:ut},RouteKey:"$disconnect",Target:{"Fn::Sub":`integrations/\${${lt}}`}}}),this.builder.addResource(`${ut}DefaultRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:ut},RouteKey:"$default",Target:{"Fn::Sub":`integrations/\${${Tt}}`}}});let xt=`${ut}Stage`;if(this.builder.addResource(xt,{Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:{Ref:ut},StageName:h,AutoDeploy:!0,DefaultRouteSettings:{ThrottlingBurstLimit:v.messagesPerSecond||1000,ThrottlingRateLimit:v.messagesPerSecond||1000}}}),A.monitoring?.enabled){let Bt=A.monitoring,mr=Bt.notificationTopicArn;if(!mr&&Bt.notificationEmails?.length){let hr=`${ut}AlarmTopic`;this.builder.addResource(hr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${h}-realtime-alarms`,DisplayName:"Realtime WebSocket Alarms"}}),Bt.notificationEmails.forEach((Ar,Tr)=>{this.builder.addResource(`${hr}Sub${Tr}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:hr},Protocol:"email",Endpoint:Ar}})}),mr={Ref:hr}}if(Bt.connectionThreshold)this.builder.addResource(`${ut}ConnectionAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${h}-realtime-connections`,AlarmDescription:`WebSocket connections exceed ${Bt.connectionThreshold}`,MetricName:"ConnectCount",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:300,EvaluationPeriods:2,Threshold:Bt.connectionThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:ut}}],...mr&&{AlarmActions:[mr]}}});if(Bt.errorThreshold)this.builder.addResource(`${ut}ErrorAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${h}-realtime-errors`,AlarmDescription:`WebSocket errors exceed ${Bt.errorThreshold}/min`,MetricName:"ExecutionError",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:60,EvaluationPeriods:3,Threshold:Bt.errorThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:ut}}],...mr&&{AlarmActions:[mr]}}})}this.builder.addOutput(`${ut}Endpoint`,{Description:"WebSocket API endpoint URL",Value:{"Fn::Sub":`wss://\${${ut}}.execute-api.\${AWS::Region}.amazonaws.com/${h}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}}),this.builder.addOutput(`${ut}Id`,{Description:"WebSocket API ID",Value:{Ref:ut},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-api-id"}}})}generateConnectHandlerCode(){return`
13
+ `:ir,at=v.map(([,Bt])=>Bt.port).filter((Bt)=>typeof Bt==="number"&&![80,443].includes(Bt)),k=this.resolveApiOriginPort(),Ot=`${l}${h}DeployBucket`.replace(/[^a-zA-Z0-9]/g,""),E=`${l}-${h}-deploy`;this.builder.addResource(Ot,{Type:"AWS::S3::Bucket",Properties:{BucketName:E,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},LifecycleConfiguration:{Rules:[{Id:"expire-old-releases",Status:"Enabled",ExpirationInDays:7,Prefix:"releases/"}]},Tags:[{Key:"Project",Value:l},{Key:"Environment",Value:h},{Key:"ManagedBy",Value:"ts-cloud"}]}});let lt=a.createServerModeStack({slug:`${l}-app`,environment:h,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},instanceType:_e,keyName:A.allowSsh?`${l}-${h}`:void 0,domain:oe,userData:ut,volumeSize:A.disk?.size||20,imageId:A.image,allowedPorts:[...A.allowSsh?[22]:[],80,443,k,...at]}),Tt=lt.resources[lt.outputs.instanceLogicalId];if(Tt?.Properties){let Bt=Tt.Properties.Tags||[];Tt.Properties.Tags=[...Bt,{Key:"Project",Value:l},{Key:"Environment",Value:h},{Key:"Role",Value:"app"},{Key:"ManagedBy",Value:"ts-cloud"}]}let xt=lt.resources[lt.outputs.roleLogicalId];if(xt?.Properties)xt.Properties.Policies=xt.Properties.Policies||[],xt.Properties.Policies.push({PolicyName:"DeployBucketRead",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:ListBucket"],Resource:[`arn:aws:s3:::${E}`,`arn:aws:s3:::${E}/*`]}]}});for(let[Bt,mr]of Object.entries(lt.resources))this.builder.addResource(Bt,mr);this.builder.addOutput("deployBucketName",{Value:{Ref:Ot},Description:"S3 bucket where release tarballs are uploaded"}),this.builder.addOutput("appInstanceId",{Value:{Ref:lt.outputs.instanceLogicalId},Description:"EC2 instance ID for the app server"}),this.builder.addOutput("appPublicIp",{Value:{Ref:lt.outputs.eipLogicalId},Description:"Public IP for the app server"}),this.serverEipLogicalIds.set("app",lt.outputs.eipLogicalId),this.serverEipLogicalIds.set("appInstance",lt.outputs.instanceLogicalId)}generateJumpBox(l,h){let A=this.mergedConfig.infrastructure?.jumpBox;if(!A)return;let w=A===!0?{}:A;if(w.enabled===!1)return;this.generateNetworkInfrastructure(l,h);let v=w.size||"micro",oe=a.InstanceSize.specs[v]?.instanceType||v||"t3.micro",ae;if(w.mountEfs)ae={fileSystemId:typeof w.mountEfs==="string"?w.mountEfs:{Ref:"FileSystem"},mountPath:w.mountPath||"/mnt/efs"};let be;if(w.databaseTools)be=a.JumpBox.withDatabaseTools({slug:l,environment:h,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:w.keyName||`${l}-${h}`,allowedCidrs:w.allowedCidrs});else if(ae)be=a.JumpBox.withEfsMount({slug:l,environment:h,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:w.keyName||`${l}-${h}`,fileSystemId:ae.fileSystemId,mountPath:ae.mountPath,allowedCidrs:w.allowedCidrs});else be=a.createJumpBox({slug:l,environment:h,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:w.keyName||`${l}-${h}`,instanceType:oe,allowedCidrs:w.allowedCidrs,mountEfs:ae});for(let[dt,_e]of Object.entries(be.resources))this.builder.addResource(dt,_e);this.builder.addOutput("JumpBoxInstanceId",{Value:{Ref:be.instanceLogicalId},Description:"The ID of the JumpBox EC2 instance (use with SSM Session Manager or SSH)"})}generateSharedInfrastructure(l,h){let A=this.mergedConfig.infrastructure?.ssl,w=this.mergedConfig.infrastructure?.dns,v=w?.domain,Ee=w?.hostedZoneId,oe=[],ae,be;if(A?.certificateArn)be=A.certificateArn;else if(A?.enabled&&v&&Ee){let at=A.domains||[v],k=at[0],Ot=at.slice(1).map((Tt)=>{if(Tt.includes(".")&&Tt.endsWith(k))return Tt.replace(`.${k}`,"");return Tt}),{certificate:E,logicalId:lt}=C.createCertificate({domain:k,subdomains:Ot,slug:l,environment:h,validationMethod:"DNS",hostedZoneId:Ee});ae=lt,this.builder.addResource(lt,E)}if(this.mergedConfig.infrastructure?.storage){let at=Object.entries(this.mergedConfig.infrastructure.storage).some(([,E])=>E.website),k;if(at&&(ae||be))k=`${l}${h}CloudFrontOAC`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(k,{Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${l}-${h}-s3-oac`,Description:`OAC for ${l} ${h} S3 website buckets`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}});let Ot=Object.entries(this.mergedConfig.infrastructure.storage).map(([E,lt])=>({name:E,config:lt,mountPath:this.normalizeMountPath(lt),rewriteStyle:lt.pathRewriteStyle||"directory",logicalId:this.storageBucketLogicalId(l,h,E)})).filter((E)=>E.name!=="public"&&E.config.website&&E.mountPath);for(let[E,lt]of Object.entries(this.mergedConfig.infrastructure.storage)){let Tt=!!(lt.website&&k),xt=this.storageBucketName(l,h,E),{bucket:Bt,logicalId:mr}=Re.createBucket({slug:l,name:E,environment:h,bucketName:xt,versioning:lt.versioning,encryption:lt.encryption,public:Tt?!1:lt.public}),hr=this.normalizeMountPath(lt),Ar;if(lt.failover){let Sr=`infrastructure.storage.${E}`;if(!Tt||!v||hr&&E!=="public")throw Error(`${Sr}.failover needs this bucket to be served by its own CloudFront distribution: a website bucket (website: true), not mounted under the path of another site, with infrastructure.dns.domain set and SSL configured (infrastructure.ssl.certificateArn, or ssl.enabled with dns.hostedZoneId).`);if(Ar=Eg({failover:lt.failover,primaryBucket:xt,primaryRegion:this.mergedConfig.project.region||"us-east-1",where:Sr}),Ar.replicate&&Bt.Properties){let Rr=`${mr}FailoverReplicationRole`;this.builder.addResource(Rr,vg({primaryBucket:xt,replicaBucket:Ar.replicaBucket}));let ti=Bt.Properties;ti.VersioningConfiguration={Status:"Enabled"},ti.ReplicationConfiguration=Tg({replicaBucket:Ar.replicaBucket,roleArn:{"Fn::GetAtt":[Rr,"Arn"]}})}}if(Tt&&Bt.Properties)Bt.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1};if(this.builder.addResource(mr,Bt),lt.website){let Sr=typeof lt.website==="object"?lt.website:{},Rr=Re.enableWebsiteHosting(Bt,Sr.indexDocument||"index.html",Sr.errorDocument);this.builder.addResource(mr,Rr)}let Tr=this.normalizeMountPath(lt);if(Tt&&k&&v&&!(Tr&&E!=="public")){let Sr=`${l}${h}${E}CDN`.replace(/[^a-zA-Z0-9]/g,""),Rr=[];if(lt.aliases&&lt.aliases.length>0)Rr.push(...lt.aliases);else if(E==="public"){if(Rr.push(v),A?.domains?.includes(`www.${v}`))Rr.push(`www.${v}`)}else if(E==="docs")Rr.push(`docs.${v}`);else if(E==="blog")Rr.push(`blog.${v}`);let ti=typeof lt.website==="object"?lt.website:{},pn=lt.spa===!0,li=ti.errorDocument||(pn?"index.html":"404.html"),Dr=[];if(pn)Dr.push({ErrorCode:403,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300});else Dr.push({ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${li}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${li}`,ErrorCachingMinTTL:300});let An=be&&Rr.length>0?{AcmCertificateArn:be,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:ae&&Rr.length>0?{AcmCertificateArn:{Ref:ae},SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},kn=`S3-${l}-${h}-${E}`,Ja=this.mergedConfig.project.region||"us-east-1",Ln;if(!pn)Ln=`${l}${h}${E}UrlRewrite`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(Ln,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${h}-${E}-url-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`URL rewrite for ${l} ${h} ${E} - appends .html to extensionless paths`,Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) { var request = event.request; var uri = request.uri; if (uri.endsWith('/')) { request.uri += 'index.html'; }
14
+ else if (!uri.includes('.')) { request.uri += '.html'; } return request; }`}});let Fn=[{Id:kn,DomainName:{"Fn::Sub":`\${${mr}}.s3.${Ja}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:k}}],jn=[],ts=[];if(this.shouldRouteStorageBucketToCompute(E,lt)){this.appendComputeAppOrigin(Fn,jn,ts,l,h,this.resolveComputeCachePathPatterns(lt.computeRoutes));for(let Pr of Ot){let ba=`S3-${l}-${h}-${Pr.name}`,ds=`${l}${h}${Pr.name}PathMountRewrite`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ds,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${h}-${Pr.name}-path-mount-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`Path mount rewrite for ${l} ${h} ${Pr.name} at ${Pr.mountPath}`,Runtime:"cloudfront-js-2.0"},FunctionCode:this.pathMountRewriteFunctionCode(Pr.mountPath,Pr.rewriteStyle)}}),Fn.push({Id:ba,DomainName:{"Fn::Sub":`\${${Pr.logicalId}}.s3.${Ja}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:k}}),ts.push(Pr.logicalId,ds);for(let Dc of[Pr.mountPath,`${Pr.mountPath}/*`])jn.push({PathPattern:Dc,TargetOriginId:ba,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[ds,"FunctionARN"]}}]})}}let Ca,ac=kn;if(Ar){let Pr=`${kn}-failover`;Object.assign(Fn[0],Ar.primaryConnection),Fn.push({Id:Pr,DomainName:bg(Ar.replicaBucket,Ar.replicaRegion),OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:k}}),Ca=qr({primaryOriginId:kn,secondaryOriginId:Pr,statusCodes:Ar.statusCodes}),ac=Ca.Items[0].Id}let ls={Type:"AWS::CloudFront::Distribution",DependsOn:[mr,k,...Ln?[Ln]:[],...ts],Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${h} ${E} site`,DefaultRootObject:"index.html",Origins:Fn,...Ca?{OriginGroups:Ca}:{},DefaultCacheBehavior:{TargetOriginId:ac,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...Ln?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[Ln,"FunctionARN"]}}]}:{}},...jn.length>0?{CacheBehaviors:jn}:{},...Rr.length>0?{Aliases:Rr}:{},ViewerCertificate:An,PriceClass:"PriceClass_100",HttpVersion:"http2and3",IPV6Enabled:!0,CustomErrorResponses:Dr}}};if(ae)ls.DependsOn.push(ae);if(Ar)jt(ls.Properties.DistributionConfig,`infrastructure.storage.${E}`),this.storageFailoverReplicas.push({name:E,primaryBucket:xt,primaryRegion:Ja,replicaBucket:Ar.replicaBucket,replicaRegion:Ar.replicaRegion,replicate:Ar.replicate,distributionArnOutput:`${E}CloudFrontDistributionArn`}),this.builder.addOutput(`${E}CloudFrontDistributionArn`,{Value:{"Fn::Sub":`arn:\${AWS::Partition}:cloudfront::\${AWS::AccountId}:distribution/\${${Sr}}`},Description:`CloudFront distribution ARN for ${E} (scopes the bucket policy of the failover replica)`}),this.builder.addOutput(`${E}FailoverBucketName`,{Value:Ar.replicaBucket,Description:`Failover replica bucket for ${E} (${Ar.replicaRegion}), outside this stack`});this.builder.addResource(Sr,ls);let Ic=`${mr}CloudFrontPolicy`;if(this.builder.addResource(Ic,{Type:"AWS::S3::BucketPolicy",DependsOn:[mr,Sr],Properties:{Bucket:{Ref:mr},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":`arn:aws:s3:::\${${mr}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${Sr}}`}}}}]}}}),this.shouldRouteStorageBucketToCompute(E,lt))for(let Pr of Ot){let ba=`${Pr.logicalId}CloudFrontPolicy`;this.builder.addResource(ba,{Type:"AWS::S3::BucketPolicy",DependsOn:[Pr.logicalId,Sr],Properties:{Bucket:{Ref:Pr.logicalId},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":`arn:aws:s3:::\${${Pr.logicalId}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${Sr}}`}}}}]}}})}if(Rr.length>0)oe.push({name:E,bucketLogicalId:mr,distLogicalId:Sr,oacLogicalId:k,aliases:Rr});this.builder.addOutput(`${E}CloudFrontDomain`,{Value:{"Fn::GetAtt":[Sr,"DomainName"]},Description:`CloudFront domain for ${E}`}),this.builder.addOutput(`${E}CloudFrontDistributionId`,{Value:{Ref:Sr},Description:`CloudFront distribution ID for ${E}`})}if(this.builder.addOutput(`${E}BucketName`,{Value:{Ref:mr},Description:`S3 bucket name for ${E}`}),E==="public")this.builder.addOutput("FrontendBucketName",{Value:{Ref:mr},Description:"Frontend S3 bucket name"});if(E==="docs")this.builder.addOutput("DocsBucketName",{Value:{Ref:mr},Description:"Documentation S3 bucket name"});if(E==="blog")this.builder.addOutput("BlogBucketName",{Value:{Ref:mr},Description:"Blog S3 bucket name"})}}if(this.mergedConfig.infrastructure?.sftp){let at=this.mergedConfig.infrastructure.sftp,k=Ld.create({...at,storage:this.resolveSftpStorage(at,l,h)??at.storage,slug:l,environment:h});for(let[Ot,E]of Object.entries(k.resources))this.builder.addResource(Ot,E);this.builder.addOutput("SftpServerId",{Value:{Ref:k.serverLogicalId},Description:"AWS Transfer Family SFTP server ID"}),this.builder.addOutput("SftpEndpoint",{Value:{"Fn::Sub":`\${${k.serverLogicalId}}.server.transfer.\${AWS::Region}.amazonaws.com`},Description:"AWS Transfer Family SFTP endpoint"}),this.builder.addOutput("SftpStorageDomain",{Value:k.domain,Description:"Storage backing the SFTP server (EFS or S3)"})}if(Ee&&oe.length>0)for(let{name:at,distLogicalId:k,aliases:Ot}of oe)for(let E of Ot){let lt=E.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${lt}ARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[k],Properties:{HostedZoneId:Ee,Name:E,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[k,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}}),this.builder.addResource(`${lt}AAAARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[k],Properties:{HostedZoneId:Ee,Name:E,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":[k,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}})}if(this.mergedConfig.infrastructure?.databases){for(let[at,k]of Object.entries(this.mergedConfig.infrastructure.databases))if(k.engine==="dynamodb"){let{table:Ot,logicalId:E}=zt.createTable({slug:l,environment:h,tableName:`${l}-${h}-${at}`,partitionKey:k.partitionKey||{name:"id",type:"S"},sortKey:k.sortKey});this.builder.addResource(E,Ot)}else if(k.engine==="postgres"){let{dbInstance:Ot,logicalId:E}=zt.createPostgres({slug:l,environment:h,dbInstanceIdentifier:`${l}-${h}-${at}`,masterUsername:k.username||"admin",masterUserPassword:k.password||"changeme123",allocatedStorage:k.storage||20,dbInstanceClass:k.instanceClass||"db.t3.micro"});this.builder.addResource(E,Ot)}else if(k.engine==="mysql"){let{dbInstance:Ot,logicalId:E}=zt.createMysql({slug:l,environment:h,dbInstanceIdentifier:`${l}-${h}-${at}`,masterUsername:k.username||"admin",masterUserPassword:k.password||"changeme123",allocatedStorage:k.storage||20,dbInstanceClass:k.instanceClass||"db.t3.micro"});this.builder.addResource(E,Ot)}}if(this.mergedConfig.infrastructure?.cdn)for(let[at,k]of Object.entries(this.mergedConfig.infrastructure.cdn)){if(!k.origin)continue;let Ot=typeof k.customDomain==="string"?k.customDomain:k.customDomain?.domain||k.domain,E=typeof k.customDomain==="object"?k.customDomain?.certificateArn:k.certificateArn,lt=E||be,Tt=`${l}${h}${at}CDN`.replace(/[^a-zA-Z0-9]/g,""),xt=`S3-${l}-${h}-${at}-cdn`,Bt=[{Id:xt,DomainName:k.origin,OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginShield:k.originShield?{Enabled:!0,OriginShieldRegion:k.originShieldRegion||this.mergedConfig.environments[h]?.region||this.mergedConfig.project.region||"us-east-1"}:{Enabled:!1},...De(k,`infrastructure.cdn.${at}`)}],mr=[],hr=[],Ar=["GET","HEAD","OPTIONS"],Tr=xt,Sr;if(k.failoverOrigin){Vt(Ar,`the default cache behavior of infrastructure.cdn.${at}`);let li=`${xt}-failover`,Dr=typeof k.failoverOrigin==="string"?{domain:k.failoverOrigin}:k.failoverOrigin;if(!Dr.domain)throw Error(`infrastructure.cdn.${at}.failoverOrigin.domain is required`);if(Dr.domain===k.origin)throw Error(`infrastructure.cdn.${at}: failoverOrigin must differ from origin (both are ${k.origin})`);Bt.push({Id:li,DomainName:Dr.domain,OriginPath:Dr.originPath||"",..._d(Dr.domain)?{S3OriginConfig:{OriginAccessIdentity:""}}:{CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"}},OriginShield:{Enabled:!1},...De(Dr,`infrastructure.cdn.${at}.failoverOrigin`)}),Sr=qr({primaryOriginId:xt,secondaryOriginId:li,statusCodes:k.failoverStatusCodes}),Tr=Sr.Items[0].Id}else if(k.failoverStatusCodes)throw Error(`infrastructure.cdn.${at}: failoverStatusCodes needs failoverOrigin to fail over to`);if(k.routeCompute)this.appendComputeAppOrigin(Bt,mr,hr,l,h,this.resolveComputeCachePathPatterns(k.computeRoutes));let Rr=lt&&Ot?{AcmCertificateArn:ae&&!E?{Ref:ae}:lt,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},ti=[...hr];if(ae&&!E&&Ot)ti.push(ae);let pn={Type:"AWS::CloudFront::Distribution",...ti.length>0?{DependsOn:ti}:{},Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${h} ${at} CDN`,DefaultRootObject:"index.html",Origins:Bt,...Sr?{OriginGroups:Sr}:{},DefaultCacheBehavior:{TargetOriginId:Tr,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:Ar,CachedMethods:["GET","HEAD","OPTIONS"],Compress:k.compress!==!1,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},...mr.length>0?{CacheBehaviors:mr}:{},...Ot&&lt?{Aliases:[Ot]}:{},ViewerCertificate:Rr,PriceClass:"PriceClass_100",HttpVersion:k.http3?"http2and3":"http2"}}};if(jt(pn.Properties.DistributionConfig,`infrastructure.cdn.${at}`),this.builder.addResource(Tt,pn),Ee&&Ot&&lt){let li=Ot.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${li}CdnARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[Tt,...ae&&!E?[ae]:[]],Properties:{HostedZoneId:Ee,Name:Ot,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:{"Fn::GetAtt":[Tt,"DomainName"]}}}})}}if(this.mergedConfig.infrastructure?.queues)for(let[at,k]of Object.entries(this.mergedConfig.infrastructure.queues)){if(!this.shouldDeploy(k))continue;let{queue:Ot,logicalId:E}=U.createQueue({slug:l,environment:h,name:`${l}-${h}-${at}`,fifo:k.fifo,visibilityTimeout:k.visibilityTimeout,messageRetentionPeriod:k.messageRetentionPeriod,delaySeconds:k.delaySeconds,maxMessageSize:k.maxMessageSize,receiveMessageWaitTime:k.receiveMessageWaitTime,contentBasedDeduplication:k.contentBasedDeduplication,encrypted:k.encrypted,kmsKeyId:k.kmsKeyId});this.builder.addResource(E,Ot);let lt;if(k.deadLetterQueue){let{deadLetterQueue:Tt,updatedSourceQueue:xt,deadLetterLogicalId:Bt}=U.createDeadLetterQueue(E,{slug:l,environment:h,maxReceiveCount:k.maxReceiveCount});lt=Bt,this.builder.addResource(Bt,Tt);let hr=this.builder.getResources()[E];if(hr?.Properties)hr.Properties.RedrivePolicy=xt.Properties?.RedrivePolicy}if(k.trigger){let Tt=k.trigger,xt=`${l}${h}${Tt.functionName}`.replace(/[^a-zA-Z0-9]/g,""),Bt={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:{"Fn::GetAtt":[E,"Arn"]},FunctionName:{Ref:xt},BatchSize:Tt.batchSize||10,MaximumBatchingWindowInSeconds:Tt.batchWindow||0,Enabled:!0,...Tt.reportBatchItemFailures!==!1&&{FunctionResponseTypes:["ReportBatchItemFailures"]},...Tt.maxConcurrency&&{ScalingConfig:{MaximumConcurrency:Tt.maxConcurrency}},...Tt.filterPattern&&{FilterCriteria:{Filters:[{Pattern:JSON.stringify(Tt.filterPattern)}]}}},DependsOn:[E,xt]};this.builder.addResource(`${E}Trigger`,Bt)}if(k.alarms?.enabled){let Tt=k.alarms,xt=Tt.notificationTopicArn;if(!xt&&Tt.notificationEmails?.length){let hr=`${E}AlarmTopic`;this.builder.addResource(hr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${h}-${at}-alarms`,DisplayName:`${at} Queue Alarms`}}),Tt.notificationEmails.forEach((Ar,Tr)=>{this.builder.addResource(`${hr}Sub${Tr}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:hr},Protocol:"email",Endpoint:Ar}})}),xt={Ref:hr}}let Bt=Tt.queueDepthThreshold||1000;this.builder.addResource(`${E}DepthAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${h}-${at}-queue-depth`,AlarmDescription:`Queue ${at} depth exceeds ${Bt} messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:Bt,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[E,"QueueName"]}}],...xt&&{AlarmActions:[xt],OKActions:[xt]}}});let mr=Tt.messageAgeThreshold||3600;if(this.builder.addResource(`${E}AgeAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${h}-${at}-message-age`,AlarmDescription:`Queue ${at} oldest message exceeds ${mr} seconds`,MetricName:"ApproximateAgeOfOldestMessage",Namespace:"AWS/SQS",Statistic:"Maximum",Period:300,EvaluationPeriods:2,Threshold:mr,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[E,"QueueName"]}}],...xt&&{AlarmActions:[xt],OKActions:[xt]}}}),lt&&Tt.dlqAlarm!==!1)this.builder.addResource(`${lt}Alarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${h}-${at}-dlq-messages`,AlarmDescription:`Dead letter queue for ${at} has messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Sum",Period:300,EvaluationPeriods:1,Threshold:0,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[lt,"QueueName"]}}],...xt&&{AlarmActions:[xt]}}})}if(k.subscribe){let Tt=k.subscribe,xt=Tt.topicArn;if(!xt&&Tt.topicName)xt={Ref:Tt.topicName};if(xt){this.builder.addResource(`${E}SnsPolicy`,{Type:"AWS::SQS::QueuePolicy",Properties:{Queues:[{Ref:E}],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"sns.amazonaws.com"},Action:"sqs:SendMessage",Resource:{"Fn::GetAtt":[E,"Arn"]},Condition:{ArnEquals:{"aws:SourceArn":xt}}}]}}});let Bt={TopicArn:xt,Protocol:"sqs",Endpoint:{"Fn::GetAtt":[E,"Arn"]},RawMessageDelivery:Tt.rawMessageDelivery||!1};if(Tt.filterPolicy)Bt.FilterPolicy=Tt.filterPolicy,Bt.FilterPolicyScope=Tt.filterPolicyScope||"MessageAttributes";this.builder.addResource(`${E}SnsSub`,{Type:"AWS::SNS::Subscription",Properties:Bt,DependsOn:`${E}SnsPolicy`})}}}if(this.mergedConfig.infrastructure?.realtime?.enabled)if((this.mergedConfig.infrastructure.realtime.mode||"serverless")==="server")this.generateRealtimeServerResources(l,h);else this.generateRealtimeResources(l,h);let dt=this.mergedConfig.infrastructure?.redirects;if(dt){let at=dt.target||this.mergedConfig.infrastructure?.dns?.domain||"",k=dt.protocol||"https";if(dt.domains?.length&&at)for(let Ot of dt.domains){let{bucket:E,bucketPolicy:lt,logicalId:Tt,policyLogicalId:xt}=yt.createDomainRedirectBucket({slug:l,environment:h,sourceDomain:Ot,targetDomain:at,protocol:k});this.builder.addResource(Tt,E),this.builder.addResource(xt,lt)}if(dt.paths&&Object.keys(dt.paths).length>0){let Ot=yt.fromMapping(dt.paths,{statusCode:dt.statusCode||301}),{function:E,logicalId:lt}=yt.createPathRedirectFunction({slug:l,environment:h,rules:Ot});this.builder.addResource(lt,E)}}if(this.mergedConfig.infrastructure?.monitoring?.alarms)for(let[at,k]of Object.entries(this.mergedConfig.infrastructure.monitoring.alarms)){let{alarm:Ot,logicalId:E}=ho.createAlarm({slug:l,environment:h,alarmName:`${l}-${h}-${at}`,metricName:k.metricName||"Errors",namespace:k.namespace||"AWS/Lambda",threshold:k.threshold||1,comparisonOperator:k.comparisonOperator||"GreaterThanThreshold"});this.builder.addResource(E,Ot)}let _e=this.mergedConfig.infrastructure?.cache;if(_e){let at=_e.type||"redis";if(at==="redis"){this.generateNetworkInfrastructure(l,h);let k=_e.redis||{},{replicationGroup:Ot,subnetGroup:E,logicalId:lt,subnetGroupId:Tt}=mo.createRedis({slug:l,environment:h,nodeType:k.nodeType||_e.nodeType||"cache.t3.micro",engineVersion:k.engineVersion||"7.1",port:k.port||6379,numCacheClusters:k.numCacheNodes||2,automaticFailover:k.automaticFailoverEnabled!==!1,atRestEncryption:!0,transitEncryption:!0,snapshotRetentionDays:k.snapshotRetentionLimit||7,snapshotWindow:k.snapshotWindow,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(lt,Ot),E&&Tt)this.builder.addResource(Tt,E);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[lt,"PrimaryEndPoint.Address"]},Description:"Redis primary endpoint address"}),this.builder.addOutput("CachePort",{Value:{"Fn::GetAtt":[lt,"PrimaryEndPoint.Port"]},Description:"Redis primary endpoint port"})}else if(at==="memcached"){this.generateNetworkInfrastructure(l,h);let k=_e.elasticache||{},{cluster:Ot,subnetGroup:E,logicalId:lt,subnetGroupId:Tt}=mo.createMemcached({slug:l,environment:h,nodeType:k.nodeType||_e.nodeType||"cache.t3.micro",engineVersion:k.engineVersion||"1.6.22",numCacheNodes:k.numCacheNodes||2,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(lt,Ot),E&&Tt)this.builder.addResource(Tt,E);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[lt,"ConfigurationEndpoint.Address"]},Description:"Memcached configuration endpoint address"})}}let _t=this.mergedConfig.infrastructure?.email;if(_t){let at=_t.domain||this.mergedConfig.infrastructure?.dns?.domain;if(at){let{emailIdentity:k,logicalId:Ot}=m.verifyDomain({domain:at,slug:l,environment:h,enableDkim:_t.enableDkim!==!1,dkimKeyLength:_t.dkimKeyLength||"RSA_2048_BIT"});if(this.builder.addResource(Ot,k),_t.configurationSet!==!1){let{configurationSet:Tt,logicalId:xt}=m.createConfigurationSet({slug:l,environment:h});this.builder.addResource(xt,Tt)}let E=_t.hostedZoneId||this.mergedConfig.infrastructure?.dns?.hostedZoneId;if(E){if(_t.enableDkim!==!1)for(let hr=1;hr<=3;hr++){let Ar=`DkimRecord${hr}${at.replace(/\./g,"")}`;this.builder.addResource(Ar,{Type:"AWS::Route53::RecordSet",DependsOn:[Ot],Properties:{HostedZoneId:E,Name:{"Fn::GetAtt":[Ot,`DkimDNSTokenName${hr}`]},Type:"CNAME",TTL:1800,ResourceRecords:[{"Fn::GetAtt":[Ot,`DkimDNSTokenValue${hr}`]}]}})}let{record:Tt,logicalId:xt}=m.createSpfRecord(at,E);this.builder.addResource(xt,Tt);let{record:Bt,logicalId:mr}=m.createDmarcRecord(at,E,{policy:"none",reportingEmail:_t.dmarcReportingEmail||`dmarc-reports@${at}`});this.builder.addResource(mr,Bt)}this.builder.addOutput("EmailDomain",{Value:at,Description:"SES verified email domain"});let lt=_t.server;if(lt?.enabled&&E){let Tt=this.mergedConfig.environments[h]?.region||this.mergedConfig.project.region||"us-east-1",xt=`${l}-${h}-email`,{role:Bt,policy:mr,roleLogicalId:hr,policyLogicalId:Ar}=m.createEmailLambdaRole({slug:l,environment:h,s3BucketArn:`arn:aws:s3:::${xt}`,sesIdentityArn:`arn:aws:ses:${Tt}:*:identity/${at}`});this.builder.addResource(hr,Bt),this.builder.addResource(Ar,mr);let{function:Tr,permission:Sr,logicalId:Rr,permissionLogicalId:ti}=m.createInboundEmailLambda({slug:l,environment:h,roleArn:{"Fn::GetAtt":[hr,"Arn"]},s3BucketName:xt,organizedPrefix:"mailboxes/"});this.builder.addResource(Rr,Tr),this.builder.addResource(ti,Sr);let pn=m.createInboundEmailSetup({slug:l,environment:h,domain:at,s3BucketName:xt,s3KeyPrefix:"inbox/",region:Tt,hostedZoneId:E,lambdaFunctionArn:{"Fn::GetAtt":[Rr,"Arn"]}});for(let[Dr,An]of Object.entries(pn.resources)){if(An.Type==="AWS::SES::ReceiptRule")An.DependsOn=[ti,Rr];this.builder.addResource(Dr,An)}this.builder.addOutput("InboundEmailLambda",{Value:{Ref:Rr},Description:"Inbound email processing Lambda function"}),this.builder.addOutput("EmailBucket",{Value:xt,Description:"S3 bucket for email storage"});let li=this.serverEipLogicalIds.get("app");if(li&&E){let An=`${lt?.subdomain||"mail"}.${at}`,kn=An.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${kn}ARecord`,{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:E,Name:An,Type:"A",TTL:"300",ResourceRecords:[{Ref:li}]}})}this.builder.addOutput("MailHost",{Value:`mail.${at}`,Description:"Mail server hostname for SMTP/IMAP clients"})}}}let ir=this.mergedConfig.infrastructure?.search;if(ir){let at=ir.vpc?{subnetIds:[{Ref:"PublicSubnet1"}],securityGroupIds:[]}:void 0;if(at)this.generateNetworkInfrastructure(l,h);let{domain:k,logicalId:Ot}=Kt.createDomain({slug:l,environment:h,engineVersion:ir.engineVersion||"OpenSearch_2.11",instanceType:ir.instanceType||"t3.small.search",instanceCount:ir.instanceCount||1,volumeSize:ir.volumeSize||10,volumeType:ir.volumeType||"gp3",dedicatedMaster:ir.dedicatedMaster||!1,dedicatedMasterType:ir.dedicatedMasterType,dedicatedMasterCount:ir.dedicatedMasterCount||3,multiAz:ir.multiAz||!1,encryption:ir.encryption||{atRest:!0,nodeToNode:!0},advancedSecurity:ir.advancedSecurity,autoTune:ir.autoTune!==!1,vpc:at});this.builder.addResource(Ot,k),this.builder.addOutput("SearchDomainEndpoint",{Value:{"Fn::GetAtt":[Ot,"DomainEndpoint"]},Description:"OpenSearch domain endpoint"}),this.builder.addOutput("SearchDomainArn",{Value:{"Fn::GetAtt":[Ot,"Arn"]},Description:"OpenSearch domain ARN"})}let fr=this.mergedConfig.infrastructure?.fileSystem;if(fr&&Object.keys(fr).length>0){this.generateNetworkInfrastructure(l,h);for(let[at,k]of Object.entries(fr)){let{fileSystem:Ot,logicalId:E}=Ke.createFileSystem({slug:`${l}-${at}`,environment:h,encrypted:k.encrypted!==!1,performanceMode:k.performanceMode||"generalPurpose",throughputMode:k.throughputMode||"bursting",enableBackup:!0});this.builder.addResource(E,Ot);let{securityGroup:lt,logicalId:Tt}=Ke.createEfsSecurityGroup({slug:`${l}-${at}`,environment:h,vpcId:{Ref:"VPC"},sourceCidrBlocks:["10.0.0.0/16"]});this.builder.addResource(Tt,lt);let{mountTargets:xt,logicalIds:Bt}=Ke.createMultiAzMountTargets(E,{slug:`${l}-${at}`,environment:h,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],securityGroupId:{Ref:Tt}});for(let mr=0;mr<xt.length;mr++)this.builder.addResource(Bt[mr],xt[mr]);this.builder.addOutput(`${at}FileSystemId`,{Value:{Ref:E},Description:`EFS file system ID for ${at}`})}}let ut=this.mergedConfig.infrastructure?.ai;if(ut){let at=ut.service||"ecs",k=ut.models||["*"],Ot=ut.allowStreaming!==!1,E;if(at==="ecs")E=Pe.enableBedrockForEcs({slug:l,environment:h,models:k,allowStreaming:Ot});else if(at==="ec2")E=Pe.enableBedrockForEc2({slug:l,environment:h,models:k,allowStreaming:Ot});else if(at==="lambda")E=Pe.enableBedrockForLambda({slug:l,environment:h,models:k,allowStreaming:Ot});else E=Pe.createBedrockRole(at,{slug:l,environment:h,models:k,allowStreaming:Ot});if(this.builder.addResource(E.logicalId,E.role),ut.allowAsync){let{policy:lt,logicalId:Tt}=Pe.createBedrockPolicy({slug:l,environment:h,models:k,allowStreaming:Ot,allowAsync:!0});this.builder.addResource(Tt,lt)}this.builder.addOutput("BedrockRoleArn",{Value:{"Fn::GetAtt":[E.logicalId,"Arn"]},Description:"IAM role ARN with Bedrock permissions"})}}generateRealtimeResources(l,h){let A=this.mergedConfig.infrastructure?.realtime;if(!A)return;let w=A.name||`${l}-${h}-realtime`,v=A.scaling||{},Ee=A.storage||{type:"dynamodb"},oe=v.handlerMemory||256,ae=v.handlerTimeout||30,be=`${l}${h}RealtimeConnections`.replace(/[^a-zA-Z0-9]/g,""),dt=`${l}${h}RealtimeChannels`.replace(/[^a-zA-Z0-9]/g,"");if(Ee.type==="dynamodb"){let Bt=Ee.dynamodb||{},mr=Bt.billingMode||"PAY_PER_REQUEST";this.builder.addResource(be,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${l}-${h}-realtime-connections`,BillingMode:mr,AttributeDefinitions:[{AttributeName:"connectionId",AttributeType:"S"},{AttributeName:"userId",AttributeType:"S"}],KeySchema:[{AttributeName:"connectionId",KeyType:"HASH"}],GlobalSecondaryIndexes:[{IndexName:"userId-index",KeySchema:[{AttributeName:"userId",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"},...mr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Bt.readCapacity||5,WriteCapacityUnits:Bt.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...mr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Bt.readCapacity||5,WriteCapacityUnits:Bt.writeCapacity||5}},...Bt.pointInTimeRecovery&&{PointInTimeRecoverySpecification:{PointInTimeRecoveryEnabled:!0}},Tags:[{Key:"Name",Value:`${l}-${h}-realtime-connections`},{Key:"Environment",Value:h}]}}),this.builder.addResource(dt,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${l}-${h}-realtime-channels`,BillingMode:mr,AttributeDefinitions:[{AttributeName:"channel",AttributeType:"S"},{AttributeName:"connectionId",AttributeType:"S"}],KeySchema:[{AttributeName:"channel",KeyType:"HASH"},{AttributeName:"connectionId",KeyType:"RANGE"}],GlobalSecondaryIndexes:[{IndexName:"connectionId-index",KeySchema:[{AttributeName:"connectionId",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"},...mr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Bt.readCapacity||5,WriteCapacityUnits:Bt.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...mr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Bt.readCapacity||5,WriteCapacityUnits:Bt.writeCapacity||5}},Tags:[{Key:"Name",Value:`${l}-${h}-realtime-channels`},{Key:"Environment",Value:h}]}})}let _e=`${l}${h}RealtimeRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(_e,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${h}-realtime-handler-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Policies:[{PolicyName:"RealtimeHandlerPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:UpdateItem"],Resource:[{"Fn::GetAtt":[be,"Arn"]},{"Fn::Sub":`\${${be}.Arn}/index/*`},{"Fn::GetAtt":[dt,"Arn"]},{"Fn::Sub":`\${${dt}.Arn}/index/*`}]},{Effect:"Allow",Action:"execute-api:ManageConnections",Resource:{"Fn::Sub":"arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:*/*"}}]}}]}});let _t=`${l}${h}RealtimeConnect`.replace(/[^a-zA-Z0-9]/g,""),ir=`${l}${h}RealtimeDisconnect`.replace(/[^a-zA-Z0-9]/g,""),fr=`${l}${h}RealtimeMessage`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(_t,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${h}-realtime-connect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[_e,"Arn"]},MemorySize:oe,Timeout:ae,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:be},CHANNELS_TABLE:{Ref:dt},ENVIRONMENT:h}},Code:{ZipFile:this.generateConnectHandlerCode()}},DependsOn:[_e,be]}),this.builder.addResource(ir,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${h}-realtime-disconnect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[_e,"Arn"]},MemorySize:oe,Timeout:ae,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:be},CHANNELS_TABLE:{Ref:dt},ENVIRONMENT:h}},Code:{ZipFile:this.generateDisconnectHandlerCode()}},DependsOn:[_e,be,dt]}),this.builder.addResource(fr,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${h}-realtime-message`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[_e,"Arn"]},MemorySize:oe,Timeout:ae,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:be},CHANNELS_TABLE:{Ref:dt},ENVIRONMENT:h}},Code:{ZipFile:this.generateMessageHandlerCode()}},DependsOn:[_e,be,dt]});let ut=`${l}${h}RealtimeApi`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ut,{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:w,ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action",Tags:{Name:w,Environment:h}}});let at=`${_t}Permission`,k=`${ir}Permission`,Ot=`${fr}Permission`;this.builder.addResource(at,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:_t},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${ut}}/*/$connect`}}}),this.builder.addResource(k,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:ir},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${ut}}/*/$disconnect`}}}),this.builder.addResource(Ot,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:fr},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${ut}}/*/$default`}}});let E=`${ut}ConnectInteg`,lt=`${ut}DisconnectInteg`,Tt=`${ut}MessageInteg`;this.builder.addResource(E,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:ut},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${_t}.Arn}/invocations`}}}),this.builder.addResource(lt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:ut},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${ir}.Arn}/invocations`}}}),this.builder.addResource(Tt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:ut},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${fr}.Arn}/invocations`}}}),this.builder.addResource(`${ut}ConnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:ut},RouteKey:"$connect",AuthorizationType:"NONE",Target:{"Fn::Sub":`integrations/\${${E}}`}}}),this.builder.addResource(`${ut}DisconnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:ut},RouteKey:"$disconnect",Target:{"Fn::Sub":`integrations/\${${lt}}`}}}),this.builder.addResource(`${ut}DefaultRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:ut},RouteKey:"$default",Target:{"Fn::Sub":`integrations/\${${Tt}}`}}});let xt=`${ut}Stage`;if(this.builder.addResource(xt,{Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:{Ref:ut},StageName:h,AutoDeploy:!0,DefaultRouteSettings:{ThrottlingBurstLimit:v.messagesPerSecond||1000,ThrottlingRateLimit:v.messagesPerSecond||1000}}}),A.monitoring?.enabled){let Bt=A.monitoring,mr=Bt.notificationTopicArn;if(!mr&&Bt.notificationEmails?.length){let hr=`${ut}AlarmTopic`;this.builder.addResource(hr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${h}-realtime-alarms`,DisplayName:"Realtime WebSocket Alarms"}}),Bt.notificationEmails.forEach((Ar,Tr)=>{this.builder.addResource(`${hr}Sub${Tr}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:hr},Protocol:"email",Endpoint:Ar}})}),mr={Ref:hr}}if(Bt.connectionThreshold)this.builder.addResource(`${ut}ConnectionAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${h}-realtime-connections`,AlarmDescription:`WebSocket connections exceed ${Bt.connectionThreshold}`,MetricName:"ConnectCount",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:300,EvaluationPeriods:2,Threshold:Bt.connectionThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:ut}}],...mr&&{AlarmActions:[mr]}}});if(Bt.errorThreshold)this.builder.addResource(`${ut}ErrorAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${h}-realtime-errors`,AlarmDescription:`WebSocket errors exceed ${Bt.errorThreshold}/min`,MetricName:"ExecutionError",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:60,EvaluationPeriods:3,Threshold:Bt.errorThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:ut}}],...mr&&{AlarmActions:[mr]}}})}this.builder.addOutput(`${ut}Endpoint`,{Description:"WebSocket API endpoint URL",Value:{"Fn::Sub":`wss://\${${ut}}.execute-api.\${AWS::Region}.amazonaws.com/${h}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}}),this.builder.addOutput(`${ut}Id`,{Description:"WebSocket API ID",Value:{Ref:ut},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-api-id"}}})}generateConnectHandlerCode(){return`
15
15
  const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
16
16
  const { DynamoDBDocumentClient, PutCommand } = require('@aws-sdk/lib-dynamodb');
17
17
 
@@ -601,5 +601,5 @@ async function handleRequest(request: Request): Promise<Response> {
601
601
  // Implement your request handling here
602
602
  return new Response('Hello from Stacks!')
603
603
  }
604
- `}async function $u(l,h,A){let w=`_acme-challenge.${h}`;if(await wu(l,h,w,A))return;let v=await l.createRecord(h,{name:w,type:"TXT",content:A,ttl:60});if(!v.success)throw Error(`Failed to create DNS challenge record: ${v.message}`)}async function Du(l,h,A){let w=await l.deleteRecord(h,{name:`_acme-challenge.${h}`,type:"TXT",content:A});if(!w.success)console.warn(`Failed to delete DNS challenge record: ${w.message}`)}async function wu(l,h,A,w){try{let v=await l.listRecords(h,"TXT"),Ee=A.replace(/\.$/,"").toLowerCase();return(v.records??[]).some((oe)=>oe.name.replace(/\.$/,"").toLowerCase()===Ee&&oe.content.replace(/^"|"$/g,"")===w)}catch{return!1}}function gc(l){let{hostedZoneId:h,dnsProvider:A,region:w="us-east-1"}=l;if(A)return R(A);if(h)return new W(w,h);throw Error("Either dnsProvider or hostedZoneId must be provided")}async function hp(l){await $u(gc(l),l.domain,l.challengeValue)}async function ef(l){await Du(gc(l),l.domain,l.challengeValue)}function rf(l){try{let{execSync:h}=Ge("node:child_process"),A=h(`openssl x509 -checkend 2592000 -noout -in ${l}/cert.pem`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return!1}catch{return!0}}import{createHash as yc,createSign as vu,generateKeyPairSync as Cc}from"node:crypto";var Sc={production:"https://acme-v02.api.letsencrypt.org/directory",staging:"https://acme-staging-v02.api.letsencrypt.org/directory"};class Lu{directoryUrl;email;accountKey;accountUrl=null;directory=null;nonce=null;constructor(l){this.directoryUrl=l.staging?Sc.staging:Sc.production,this.email=l.email,this.accountKey=l.accountKey||this.generateAccountKey()}generateAccountKey(){let{privateKey:l}=Cc("ec",{namedCurve:"P-256"});return l.export({type:"pkcs8",format:"pem"})}async getDirectory(){if(this.directory)return this.directory;let l=await fetch(this.directoryUrl);if(!l.ok)throw Error(`Failed to fetch ACME directory: ${l.status}`);return this.directory=await l.json(),this.directory}async getNonce(){if(this.nonce){let w=this.nonce;return this.nonce=null,w}let l=await this.getDirectory(),A=(await fetch(l.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!A)throw Error("Failed to get nonce from ACME server");return A}getJwk(){let l=this.accountKey.split(`
605
- `).filter((Ee)=>!Ee.startsWith("-----")).join(""),h=Buffer.from(l,"base64"),A=h.length-65,w=h.subarray(A+1,A+33),v=h.subarray(A+33,A+65);return{kty:"EC",crv:"P-256",x:this.base64UrlEncode(w),y:this.base64UrlEncode(v)}}getJwkThumbprint(){let l=this.getJwk(),h=JSON.stringify({crv:l.crv,kty:l.kty,x:l.x,y:l.y}),A=yc("sha256").update(h).digest();return this.base64UrlEncode(A)}base64UrlEncode(l){return(typeof l==="string"?Buffer.from(l):l).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async signPayload(l,h){let A=await this.getNonce(),w=this.getJwk(),v={alg:"ES256",nonce:A,url:l};if(this.accountUrl)v.kid=this.accountUrl;else v.jwk=w;let Ee=this.base64UrlEncode(JSON.stringify(v)),oe=h===""?"":this.base64UrlEncode(JSON.stringify(h)),ae=`${Ee}.${oe}`,be=vu("SHA256");be.update(ae);let dt=be.sign(this.accountKey),_e=dt.subarray(4,4+dt[3]),_t=4+dt[3]+2,ir=dt.subarray(_t,_t+dt[_t-1]),fr=Buffer.alloc(32),ut=Buffer.alloc(32);_e.copy(fr,32-_e.length),ir.copy(ut,32-ir.length);let at=Buffer.concat([fr,ut]);return JSON.stringify({protected:Ee,payload:oe,signature:this.base64UrlEncode(at)})}async acmeRequest(l,h){let A=await this.signPayload(l,h),w=await fetch(l,{method:"POST",headers:{"Content-Type":"application/jose+json"},body:A}),v=w.headers.get("replay-nonce");if(v)this.nonce=v;let Ee,oe=w.headers.get("content-type");if(oe?.includes("application/json")||oe?.includes("application/problem+json"))Ee=await w.json();else Ee=await w.text();if(!w.ok)throw Error(`ACME request failed: ${JSON.stringify(Ee)}`);return{body:Ee,headers:w.headers}}async registerAccount(){let l=await this.getDirectory(),{body:h,headers:A}=await this.acmeRequest(l.newAccount,{termsOfServiceAgreed:!0,contact:[`mailto:${this.email}`]}),w=A.get("location");if(!w)throw Error("No account URL returned");return this.accountUrl=w,w}async createOrder(l){if(!this.accountUrl)await this.registerAccount();let h=await this.getDirectory(),{body:A,headers:w}=await this.acmeRequest(h.newOrder,{identifiers:l.map((Ee)=>({type:"dns",value:Ee}))}),v=w.get("location");if(!v)throw Error("No order URL returned");return{orderUrl:v,authorizations:A.authorizations,finalize:A.finalize}}async getAuthorization(l){let{body:h}=await this.acmeRequest(l,""),A=h.identifier.value,w=this.getJwkThumbprint(),v=h.challenges.filter((Ee)=>Ee.type==="http-01"||Ee.type==="dns-01").map((Ee)=>{let oe=`${Ee.token}.${w}`;if(Ee.type==="http-01")return{type:"http-01",token:Ee.token,keyAuthorization:oe,identifier:`/.well-known/acme-challenge/${Ee.token}`};else{let ae=this.base64UrlEncode(yc("sha256").update(oe).digest());return{type:"dns-01",token:Ee.token,keyAuthorization:oe,identifier:`_acme-challenge.${A}`,dnsValue:ae}}});return{domain:A,challenges:v}}async respondToChallenge(l){await this.acmeRequest(l,{})}async waitForAuthorization(l,h=30){for(let A=0;A<h;A++){let{body:w}=await this.acmeRequest(l,"");if(w.status==="valid")return;if(w.status==="invalid")throw Error(`Authorization failed: ${JSON.stringify(w)}`);await new Promise((v)=>setTimeout(v,2000))}throw Error("Authorization timed out")}generateCsr(l){let{privateKey:h}=Cc("rsa",{modulusLength:2048}),A=h.export({type:"pkcs8",format:"pem"});return{csr:this.createSimpleCsr(l,h),privateKey:A}}createSimpleCsr(l,h){throw Error("CSR generation requires additional implementation. Consider using the shell-based certbot approach instead.")}async finalizeOrder(l,h){let{csr:A,privateKey:w}=this.generateCsr(h),{body:v}=await this.acmeRequest(l,{csr:this.base64UrlEncode(Buffer.from(A,"base64"))}),Ee=v.certificate;if(!Ee)throw Error("Certificate not immediately available - polling not implemented");let ae=await(await fetch(Ee)).text(),be=ae.split(/(?=-----BEGIN CERTIFICATE-----)/g),dt=be[0],_e=be.slice(1).join("");return{certificate:dt,privateKey:w,chain:_e,fullchain:ae,expiresAt:new Date(Date.now()+7776000000)}}getAccountKey(){return this.accountKey}}var Zi=(l)=>l===void 0?void 0:l?"on":"off";function Bs(l){let h={ssl:l.ssl,always_use_https:Zi(l.alwaysUseHttps),automatic_https_rewrites:Zi(l.automaticHttpsRewrites),min_tls_version:l.minTlsVersion,tls_1_3:Zi(l.tls13),brotli:Zi(l.brotli),http3:Zi(l.http3),"0rtt":Zi(l.zeroRtt),early_hints:Zi(l.earlyHints),browser_cache_ttl:l.browserCacheTtl,always_online:Zi(l.alwaysOnline),websockets:Zi(l.websockets),email_obfuscation:Zi(l.emailObfuscation)};if(l.hsts)h.security_header={strict_transport_security:{enabled:l.hsts.enabled,max_age:l.hsts.maxAge??31536000,include_subdomains:l.hsts.includeSubdomains??!1,preload:l.hsts.preload??!1,nosniff:l.hsts.noSniff??!0}};for(let A of Object.keys(h))if(h[A]===void 0)delete h[A];return{...h,...l.raw??{}}}var Un={ssl:"strict",alwaysUseHttps:!0,automaticHttpsRewrites:!0,minTlsVersion:"1.2",tls13:!0,brotli:!0,http3:!0,earlyHints:!0,alwaysOnline:!0,emailObfuscation:!1,browserCacheTtl:0};import{connect as Fu}from"node:tls";async function _s(l){let{address:h,serverName:A,port:w=443,timeoutMs:v=5000}=l;return new Promise((Ee)=>{let oe=!1,ae=(dt)=>{if(oe)return;oe=!0;try{be.destroy()}catch{}Ee(dt)},be=Fu({host:h,port:w,servername:A,rejectUnauthorized:!1,timeout:v});be.once("secureConnect",()=>{if(be.authorized){ae({reachable:!0,trusted:!0});return}ae({reachable:!0,trusted:!1,reason:be.authorizationError?String(be.authorizationError):"origin certificate is not trusted for this hostname"})}),be.once("timeout",()=>{ae({reachable:!1,trusted:!1,reason:`no TLS handshake within ${v}ms`})}),be.once("error",(dt)=>{ae({reachable:!1,trusted:!1,reason:dt.message})})})}function Mu(l,h){let A=h.replace(/\.$/,"").toLowerCase();return l.some((w)=>{let v=w.replace(/\.$/,"").toLowerCase();if(v===A)return!0;if(!v.startsWith("*."))return!1;let Ee=v.slice(2);if(!A.endsWith(`.${Ee}`))return!1;return!A.slice(0,A.length-Ee.length-1).includes(".")})}async function Vu(l){let{provider:h,zone:A,hosts:w,ipv4:v,ipv6:Ee,proxied:oe=!0,settings:ae=Un,cache:be,originGuard:dt,purge:_e=!0,ttl:_t=300,skipOriginProbe:ir=!1,skipEdgeCertificateCheck:fr=!1}=l,ut={records:[],settingsChanged:[],cacheRules:0,originGuard:!1,purged:!1,deferredProxy:[],warnings:[]};if(w.length===0)return ut;let at=[],k=oe&&!fr?await h.listEdgeCertificateHosts(A):null;for(let E of w){let lt=oe;if(lt&&k&&!Mu(k,E)){lt=!1;let xt=k.length===0?"the zone has no active edge certificate yet":`no active edge certificate covers it (${k.join(", ")})`;ut.deferredProxy.push({host:E,reason:xt}),ut.warnings.push(`${E}: publishing DNS-only — ${xt}. Proxying it would make Cloudflare terminate TLS with no certificate for the name, which fails the handshake outright rather than degrading. Universal SSL covers the apex and ONE level of subdomain, so a deeper name needs its own certificate; otherwise re-run the deploy once the certificate is active.`)}if(lt&&!ir){let xt=await _s({address:v,serverName:E});if(!xt.trusted){lt=!1;let Bt=xt.reason||"origin is not serving a trusted certificate";ut.deferredProxy.push({host:E,reason:Bt}),ut.warnings.push(`${E}: publishing DNS-only for now — the origin does not yet serve a certificate this proxy can verify (${Bt}). The origin issues certificates over HTTP-01, which needs the name to reach it directly; re-run the deploy once it has one and the record will be proxied.`)}}if(lt)at.push(E);let Tt=[{type:"A",content:v}];if(Ee&&Nn(E))Tt.push({type:"AAAA",content:Ee});for(let{type:xt,content:Bt}of Tt){let mr=await h.upsertRecord(A,{name:E,type:xt,content:Bt,ttl:_t,proxied:lt});if(mr.success)ut.records.push({host:E,type:xt,content:Bt,proxied:lt});else ut.warnings.push(`${E} ${xt} → ${Bt} failed: ${mr.message||"unknown provider error"}`)}}if(at.length===0){if(oe)ut.warnings.push("No host is proxied yet, so zone settings, cache rules and purge were skipped — they only take effect through the proxy.");return ut}try{let E=Bs(ae),lt=await h.applyZoneSettings(A,E);ut.settingsChanged=lt.changed;for(let Tt of lt.failed)ut.warnings.push(`zone setting '${Tt.id}' could not be applied: ${Tt.error}`)}catch(E){ut.warnings.push(`zone settings could not be read: ${E instanceof Error?E.message:String(E)}`)}let Ot=ec(at,be);if(Ot.length>0){let E=await h.putManagedPhaseRules(A,"http_request_cache_settings",Ot);if(E.success)ut.cacheRules=Ot.length;else ut.warnings.push(`cache rules could not be written: ${E.message}`)}if(dt){let E=tc(at,dt.header,dt.value);if(E.length>0){let lt=await h.putManagedPhaseRules(A,"http_request_late_transform",E);if(lt.success)ut.originGuard=!0;else ut.warnings.push(`origin guard header could not be written: ${lt.message}. `+"The gateway will reject requests that lack it — disable the guard or grant the token Transform Rules: Edit.")}}if(_e){if(ut.purged=await h.purgeCache(A,{hosts:at}),!ut.purged)ut.warnings.push("edge cache purge failed — new content may take until TTL expiry to appear.")}return ut}var Wu=(l)=>process.env[l];function Ac(l,h){let A=l.replace(/\.$/,"").toLowerCase();if(h){let w=h.replace(/\.$/,"").toLowerCase();if(A===w||A.endsWith(`.${w}`))return w}return A.split(".").slice(-2).join(".")}function Hu(l,h={}){let A=h.env??Wu,w=l.infrastructure?.compute?.proxy?.cdn,v=[];if(!w||w.provider!=="cloudflare")return{plan:null,errors:v};if(w.originDomain)v.push(`compute.proxy.cdn.originDomain (${w.originDomain}) is ignored for Cloudflare: the proxy forwards to the address in the record it fronts, `+"so no separate origin hostname is needed — and publishing one gives clients a documented way around the edge.");let Ee=A("CLOUDFLARE_API_TOKEN");if(!Ee)return v.push("CLOUDFLARE_API_TOKEN is not set — the Cloudflare CDN cannot be reconciled."),{plan:null,errors:v};let oe=l.sites??{},ae=w.frontedHosts?.length?[...new Set(w.frontedHosts.map((ir)=>ir.toLowerCase()))]:xn(oe,{autoWww:l.infrastructure?.compute?.proxy?.autoWww!==!1});if(ae.length===0)return v.push("No hostnames to front — set compute.proxy.cdn.frontedHosts, or give a site a domain."),{plan:null,errors:v};let be=l.infrastructure?.dns?.domain,dt=new Set(ae.map((ir)=>Ac(ir,be)));if(dt.size>1)return v.push(`Fronted hosts span more than one zone (${[...dt].join(", ")}). A Cloudflare zone is configured as a unit, so run one CDN config per zone.`),{plan:null,errors:v};let _e=w.cloudflare??{},_t=w.secret?{header:w.secretHeader??"X-Origin-Verify",value:w.secret}:void 0;return{plan:{zone:[...dt][0],hosts:ae,apiToken:Ee,zoneId:_e.zoneId??A("CLOUDFLARE_ZONE_ID"),accountId:_e.accountId??A("CLOUDFLARE_ACCOUNT_ID"),proxied:_e.proxied!==!1,settings:_e.settings??Un,cache:_e.cache,originGuard:_t,purge:_e.purgeOnDeploy!==!1,skipOriginProbe:_e.skipOriginProbe===!0},errors:v}}var Gu=26214400;var zu=new Set(["/_headers","/_redirects","/_routes.json","/_worker.js"]);class bc{name="cloudflare-pages";apiToken;accountId;constructor(l){if(!l.apiToken)throw Error("Cloudflare Pages needs an API token");if(!l.accountId)throw Error("Cloudflare Pages needs an account id");this.apiToken=l.apiToken,this.accountId=l.accountId}async request(l,h,A){return Ka(l,`/accounts/${this.accountId}${h}`,`Bearer ${this.apiToken}`,A)}async getProject(l){try{return await this.request("GET",`/pages/projects/${l}`)}catch(h){if(h instanceof Error&&/\b8000007\b|not found/i.test(h.message))return null;throw h}}async ensureProject(l,h="main"){let A=await this.getProject(l);if(A)return A;return this.request("POST","/pages/projects",{name:l,production_branch:h})}async uploadToken(l){return(await this.request("GET",`/pages/projects/${l}/upload-token`)).jwt}async missingHashes(l,h){let A=await Ka("POST","/pages/assets/check-missing",`Bearer ${l}`,{hashes:h});return new Set(A)}async upsertHashes(l,h){await Ka("POST","/pages/assets/upsert-hashes",`Bearer ${l}`,{hashes:h})}async uploadBatch(l,h){let A=h.map((w)=>({key:w.hash,value:w.base64,metadata:{contentType:Ku(w.extension)},base64:!0}));await Ka("POST","/pages/assets/upload",`Bearer ${l}`,A)}async createDeployment(l,h,A){let w={};for(let Ee of h)w[Ee.path]=Ee.hash;let v=new FormData;if(v.append("manifest",JSON.stringify(w)),A)v.append("branch",A);return this.request("POST",`/pages/projects/${l}/deployments`,v)}async deployDirectory(l){let h=await Tc(l.directory);if(h.length===0)throw Error(`No files to deploy in ${l.directory}`);let A=await this.uploadToken(l.project),w=await this.missingHashes(A,h.map((be)=>be.hash)),v=h.filter((be)=>w.has(be.hash)),Ee=[];for(let be=0;be<v.length;be+=100)Ee.push(v.slice(be,be+100));let oe=0;for(let be=0;be<Ee.length;be+=4){let dt=Ee.slice(be,be+4);await Promise.all(dt.map((_e)=>this.uploadBatch(A,_e))),oe+=dt.reduce((_e,_t)=>_e+_t.length,0),l.onProgress?.(oe,v.length)}return await this.upsertHashes(A,h.map((be)=>be.hash)),{deployment:await this.createDeployment(l.project,h,l.branch),total:h.length,uploaded:v.length,uploadedBytes:v.reduce((be,dt)=>be+dt.size,0)}}async listCustomDomains(l){return(await this.request("GET",`/pages/projects/${l}/domains`)).map((A)=>A.name)}async attachCustomDomain(l,h){if((await this.listCustomDomains(l)).includes(h))return!1;return await this.request("POST",`/pages/projects/${l}/domains`,{name:h}),!0}}function Uu(l,h){return{type:"CNAME",name:l,value:h.endsWith(".pages.dev")?h:`${h}.pages.dev`,ttl:1,proxied:!0}}async function Rc(l,h){let{blake3:A}=await import("./chunk-m5vwh9tb.js").then((m)=>tf(m.default,1));return(await A(l+h)).slice(0,32)}async function Tc(l){let{readdir:h}=await import("node:fs/promises"),{join:A,relative:w,sep:v}=await import("node:path"),Ee=[];async function oe(ae){let be=await h(ae,{withFileTypes:!0});for(let dt of be){let _e=A(ae,dt.name);if(dt.isDirectory()){await oe(_e);continue}if(!dt.isFile())continue;let _t=`/${w(l,_e).split(v).join("/")}`;if(zu.has(_t))continue;let ir=await Bun.file(_e).bytes();if(ir.byteLength>26214400)throw Error(`${_t} is ${ir.byteLength} bytes, over the Cloudflare Pages limit of 26214400`);let fr=Buffer.from(ir).toString("base64"),ut=dt.name.lastIndexOf("."),at=ut>0?dt.name.slice(ut+1):"";Ee.push({path:_t,hash:await Rc(fr,at),base64:fr,extension:at,size:ir.byteLength})}}return await oe(l),Ee.sort((ae,be)=>ae.path.localeCompare(be.path)),Ee}function Ku(l){return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",mjs:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",map:"application/json; charset=utf-8",xml:"application/xml; charset=utf-8",txt:"text/plain; charset=utf-8",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",ico:"image/x-icon",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",pdf:"application/pdf",webmanifest:"application/manifest+json"}[l.toLowerCase()]||"application/octet-stream"}async function Ka(l,h,A,w){let v={Authorization:A},Ee;if(w instanceof FormData)Ee=w;else if(w!==void 0)v["Content-Type"]="application/json",Ee=JSON.stringify(w);let oe=await fetch(`https://api.cloudflare.com/client/v4${h}`,{method:l,headers:v,body:Ee}),ae=await oe.text(),be;try{be=JSON.parse(ae)}catch{throw Error(`Cloudflare Pages API returned ${oe.status} with a non-JSON body: ${ae.slice(0,200)}`)}if(!be.success){let dt=(be.errors??[]).map((_e)=>`${_e.code}: ${_e.message}`).join(", ");throw Error(`Cloudflare Pages API error (${oe.status}): ${dt||ae.slice(0,200)}`)}return be.result}export{tm as ABTestManager,le as ACMClient,gr as ACMDnsValidator,Sc as ACME_DIRECTORIES,Pe as AI,ml as API_IDEMPOTENCY_TTL_MS,pl as API_TOKEN_DEFAULT_TTL_MS,gl as API_TOKEN_MAX_TTL_MS,Vi as API_VERSION,pe as AUTHORIZATION_CAPABILITIES,cl as AUTH_ACTION_TOKEN_TTL_MS,dl as AUTH_MFA_CHALLENGE_TTL_MS,ll as AUTH_OIDC_TRANSACTION_TTL_MS,Xe as AUTH_SESSION_ABSOLUTE_TTL_MS,al as AUTH_SESSION_IDLE_TTL_MS,PA as AWSAPIError,n as AWSClient,f as AWSCloudFormationClient,I as AWSCloudFrontClient,Xg as AWSConfigManager,FI as AWS_PSEUDO_PARAMETERS,Ne as AWS_REGIONS,Lu as AcmeClient,Ur as AlertEvaluator,Ei as AlertStore,eo as AnomalyConfigStore,$d as ApiGateway,i as ApiServiceError,Wa as ApplicationAutoScalingClient,fo as Arn,N as AssetHasher,H as Auth,Ui as AuthenticationStore,Ri as AutomationApiService,Qi as AutomationIdentityStore,na as AwsAuroraDataAdapter,ca as AwsAuroraTransport,wa as AwsDatabaseBackupSource,yr as AwsDriver,ia as AwsElastiCacheDataAdapter,da as AwsElastiCacheTransport,Zm as AwsIamCapabilityScanner,ka as AwsInfrastructureBackupSource,ra as AwsRdsDataAdapter,aa as AwsRdsTransport,ph as AwsRegionalDriver,_a as AwsSecretsManagerConfigurationBackend,ag as AwsSpendTransport,Oa as AwsSsmConfigurationBackend,rs as BackupCoordinator,Wg as BackupManager,va as BackupStore,_m as BatchProcessingManager,Cn as BedrockClient,Sn as BedrockRuntimeClient,Cl as BitbucketSourceAdapter,em as BlueGreenManager,Rm as BounceComplaintHandler,hm as BuildOptimizationManager,Gl as BunDockerRuntime,Iu as BunDockerVolumeRuntime,yu as BunFilesystemArchiveRuntime,me as CDN,bo as CHAIN_HEADER,hs as CLOUDFLARE_MANAGED_RULE_PREFIX,kd as CLOUDFRONT_FAILOVER_STATUS_CODES,_C as COMMON_CROSS_ACCOUNT_ROLES,qe as CONTROL_PLANE_SCHEMA_VERSION,mo as Cache,Io as CanaryManager,pm as CertificateManager,Mf as CloudBlockVolumeDriver,Os as CloudDriverFactory,Je as CloudError,Tg as CloudFormationBuilder,f as CloudFormationClient,I as CloudFrontClient,Yg as CloudTrailManager,ye as CloudWatchLogsClient,bc as CloudflarePagesProvider,Se as CloudflareProvider,GA as CommandHistory,q as Communication,xr as ComposeApplicationService,Ut as ComposeApplicationStore,Rt as ComprehendClient,a as Compute,cg as ComputeSpendTransport,yo as ConfigurationError,La as ConfigurationService,Ba as ConfigurationStore,yn as ConnectClient,oa as ContainerDataAdapter,fm as ContainerRegistryManager,Na as ControlPlaneBackupSource,Sa as ControlPlaneCleanupDriver,hi as ControlPlaneStore,Xs as CounterTracker,Jt as CredentialError,Gg as CrossRegionReferenceManager,mA as DASHBOARD_ENTRY,hA as DASHBOARD_PORT_BASE,fA as DASHBOARD_PORT_SPAN,gA as DASHBOARD_STATE_DIR,No as DEFAULT_ATTACK_MODE_HOURS,Id as DEFAULT_DDOS_THRESHOLDS,hg as DEFAULT_FAILOVER_STATUS_CODES,ed as DEFAULT_METER_MAPPINGS,Yc as DEFAULT_PRICE_BOOK,Oi as DEFAULT_RECURSION_LIMITS,_n as DEFAULT_RPX_CERTS_DIR,j as DEFAULT_SERVICE_LIMITS,pg as DEFAULT_STATE_DIR,ku as DEFAULT_STATIC_ASSET_EXTENSIONS,dA as DEFAULT_STORAGE_FAILOVER_STATUS_CODES,Xf as DEFAULT_TELEMETRY_POLICY,Vp as DEFAULT_THRESHOLDS,_f as DEPLOYMENT_QUEUE_KINDS,Eo as DEPTH_HEADER,Mr as DETECTABLE_SIGNALS,Ml as DIAGNOSTIC_PRESETS,Bm as DLQMonitoringManager,F as DNS,Tm as DNSSECManager,Wi as DataServiceLifecycle,ta as DataServiceStore,zt as Database,dm as DatabaseUserManager,re as DebugLogger,cA as DependencyGraph,G as Deployment,DA as DeploymentError,Jg as DisasterRecoveryManager,Pn as DnsProviderFactory,er as DockerDataTransport,Wo as DockerDiscoveryAdapter,Or as DockerNamedVolumeDriver,Pa as DockerVolumeBackupSource,c as DurableOperationQueue,qs as DurableQueueWorker,xe as DynamoDBClient,wr as EC2Client,$e as ECRClient,rt as ECSClient,dr as EFSClient,Va as ELBv2Client,Uf as ENFORCEMENT_ACTIONS,Si as ENFORCEMENT_DESCRIPTIONS,P as ENFORCEMENT_SEVERITY,Ip as ENVIRONMENT_LABEL,Ll as EcsRuntimeAdapter,Po as EdgeRateLimiter,it as ElastiCacheClient,m as Email,jA as EmailAdvanced,Dm as EmailAnalyticsManager,Tn as EmailClient,zA as EmailHandlers,Nm as EmailTemplateManager,la as EncryptedDataSecretStore,NA as ErrorCodes,ar as EventBridgeClient,dh as EventBridgeJobAdapter,xa as ExternalConfigurationBackend,go as FAILOVER_REPLICA_POLICY_SID,km as FIFOQueueManager,Zp as FOCUS_VERSION,kg as FileCache,Ke as FileSystem,Ra as FilesystemBackupSource,pa as FleetService,ua as FleetStore,e as Fn,El as GiteaSourceAdapter,Il as GithubSourceAdapter,Sl as GitlabSourceAdapter,qg as GlobalResourceManager,Me as GoDaddyProvider,Zg as GuardDutyManager,pt as HOST_SITES_DIR,_A as HashCache,Qm as HealthCheckManager,je as HealthCheckRunner,Er as HetznerClient,ve as HetznerDriver,Ie as IAMClient,sc as IPV6_EXCLUDED_HOST_LABELS,mm as ImageScanningManager,rl as InfrastructureGenerator,Qc as InvalidOperationTransitionError,At as JobLoader,lh as JobProviderReconciler,ea as JobService,Yo as JobStore,or as KendraClient,py as LARAVEL_SERVERLESS_BUILD_STEPS,b as LambdaClient,Sm as LambdaConcurrencyManager,bm as LambdaDLQManager,Cm as LambdaDestinationsManager,ym as LambdaLayersManager,$l as LambdaRuntimeAdapter,Em as LambdaVPCManager,Im as LambdaVersionsManager,gn as LocalEncryptedConfigurationBackend,Da as LogicalDatabaseBackupSource,sm as LogsManager,YA as MANAGED_NODE_VERSIONS,Pc as MANAGEMENT_DASHBOARD_SITE,wg as MANAGEMENT_DASHBOARD_SITE_PREFIX,Mi as MAX_CONTROL_HOURS,Hc as MAX_CONTROL_PLANE_ERROR_BYTES,Up as MAX_CONTROL_PLANE_JSON_BYTES,Ks as METERS,Ff as METER_KEYS,Qf as MICRO_CENTS,jp as MIN_PROJECTION_CONFIDENCE,xu as MTA_STS_PORT,Ia as MaintenanceService,ya as MaintenanceStore,te as Messaging,im as MetricsManager,om as MigrationManager,Lg as MockCloudFormation,Mg as MockDynamoDB,$g as MockS3,ho as Monitoring,zg as MultiAccountManager,Hg as MultiRegionManager,$A as MultiStepProgress,y as Network,Hm as NetworkSecurityManager,bi as NotificationRouter,yg as ORIGIN_CONNECTION_ATTEMPTS,Ig as ORIGIN_CONNECTION_TIMEOUT,fg as ORIGIN_GROUP_ALLOWED_METHODS,LI as ORIGIN_GROUP_ID_SUFFIX,Ag as ORIGIN_GROUP_SELECTION_CRITERIA,ja as OpenSearchClient,gt as OptimisticConcurrencyError,Kg as OrganizationManager,Gu as PAGES_MAX_FILE_BYTES,gy as PHP_DEFAULT_EXCLUDES,ZA as PHP_LAYER_EXTENSIONS,yp as PROJECT_LABEL,ot as PROXIABLE_RECORD_TYPES,T as ParameterStore,cm as PerformanceManager,ee as Permissions,za as PersonalizeClient,We as Phone,KA as PhoneAdvanced,lA as PhoneHandlers,ma as PlacementService,ga as PlacementStore,En as PollyClient,ce as PorkbunProvider,tn as PreDeployScanner,Fg as PreviewEnvironmentManager,_r as PreviewEnvironmentService,Ve as PreviewEnvironmentStore,Ug as PreviewNotificationService,LA as ProgressBar,rm as ProgressiveDeploymentManager,ko as ProtectionControlStore,wI as Pseudo,U as Queue,fi as QueueCancellationError,Om as QueueManagementManager,vI as QueuePresets,Gs as QueueTimeoutError,Zd as RATE_LIMIT_KEY_SEPARATOR,K as RDSClient,VA as RECOMMENDED_ACCOUNT_STRUCTURES,BC as RECOMMENDED_SCPS,Wm as RELEASE_QUEUE_KINDS,UA as REPL,HA as REPLCommandBuilder,QA as REPLContext,Sp as ROLE_LABEL,OA as RateLimiter,TI as RealtimePresets,eg as RecordingSpendTransport,To as RecursionGuard,yt as Redirects,Vg as RegionPairManager,fa as RegionService,ha as RegionStore,ze as Registry,Dt as RekognitionClient,It as ReleaseService,Uo as ReleaseStore,uh as RemoteBuildService,am as ReplicaManager,Gm as ResourceManagementManager,Z as RetryableOperationError,S as Route53Client,qa as Route53DomainsClient,W as Route53Provider,wm as Route53ResolverManager,vm as Route53RoutingManager,fe as RuntimeOperationService,Xo as RuntimeStreamRegistry,Ta as S3BackupDestinationAdapter,o as S3Client,V as S3Error,Tl as SECRET_PATTERNS,Xp as SENSITIVITY_THRESHOLDS,st as SESClient,Q as SMS,nt as SNSClient,og as SPEND_CYCLE_SECONDS,gd as SPEND_GATE_SETTING,tA as SPEND_LEASE_SETTING,se as SQSClient,Te as SSH_BOOTSTRAP_VERSION,Jn as SSH_PREFLIGHT_SCRIPT,we as SSMClient,gg as STATE_DIR_ENV_VAR,Un as STATIC_SITE_ZONE_SETTINGS,Od as STORAGE_FAILOVER_METADATA_KEY,Ae as STSClient,bn as SchedulerClient,Kt as Search,rn as SecretFindingScanner,Ni as Secrets,um as SecretsManager,z as SecretsManagerClient,lm as SecretsRotationManager,C as Security,zr as SecurityHubManager,en as SecurityPostureStore,St as SecurityScannerRunner,gm as SecurityScanningManager,Pm as SenderReputationManager,ch as ServerCronJobAdapter,sa as ServerDataAdapter,zs as ServerPathVolumeDriver,Am as ServiceMeshManager,Ld as Sftp,ro as SignalSource,WA as SmsAdvanced,Nt as SmsClient,uA as SmsHandlers,Ya as SmsVoiceClient,Qo as SourceConnectionStore,Yt as SourceProviderError,md as SpendCapError,Fr as SpendGate,ig as SpendLoopLease,ao as SpendNotificationRouter,sg as SpendRunner,Ht as SpendService,yi as SpendStore,MA as Spinner,vr as SshDriver,on as SshFleetDriver,jg as StackDependencyManager,MI as StacksIntegration,Fm as StaticSiteManager,Re as Storage,Um as StorageAdvancedManager,vn as SupportClient,Kr as SyntheticsManager,ql as SystemFleetSshTransport,br as SystemSshTransport,Jo as SystemdDiscoveryAdapter,vo as TRACE_HEADER,FA as TaskList,ft as TelemetryStore,Pd as TemplateBuilder,Bg as TemplateCache,Pt as TextractClient,In as TranscribeClient,sr as TranslateClient,hh as TransportDisasterRecoveryDriver,mh as TransportPlatformMaintenanceDriver,Ji as TransportRemoteBuildDriver,zo as TrivyImageScanner,Fo as TsCloudApiError,hl as TsCloudClient,eA as URGENT_SPEND_EVENTS,zp as USER_VISIBLE_ACTIONS,Aa as UnavailableRegionalDriver,de as UnifiedDnsValidator,Us as UnsupportedSchemaVersionError,Pg as ValidationError,cr as VoiceClient,js as VolumeService,Ft as VolumeStore,pA as Workflow,nm as XRayManager,aE as abTestManager,fl as activateImmutableRelease,$u as addDns01ChallengeRecord,cn as addSiteToCloudConfig,Et as ageSeconds,rd as aggregateDeltas,$p as allocateSitePorts,OI as analyzeStackDiff,Ci as anomalyOptionsForSignal,Bo as applyControlsToDdos,il as applyControlsToRateLimits,Ss as applyDeclaredZoneSettings,Gr as applyMitigationFactor,mf as applyPlan,vs as applyZoneMigration,Hd as artifactKey,Vt as assertOriginGroupMethods,Hi as assertReleaseStrategy,Jf as assertSpendAllows,If as attachConflicts,Sf as attachIsViable,yf as attachPreconditions,Nl as attachProvenanceToRelease,Ko as attachSbomToRelease,Dl as attachVulnerabilitySummary,zm as authEncryptionKeyFile,D as authorizeOrganization,oh as authorizeRuntimePath,cC as autocomplete,tE as awsConfigManager,fu as backupCredentialStatus,ZC as backupManager,RS as batch,UE as batchProcessingManager,$o as beginOidcAuthorization,sE as blueGreenManager,OE as bounceComplaintHandler,mt as budgetWindow,Qa as buildAndPushServerlessImage,GE as buildBunRuntimeLayerZip,wf as buildCertificatePackScript,bf as buildCertificateStateScript,Rf as buildCertificateUnpackScript,Md as buildCloudFormationTemplate,Ec as buildCloudInitFirstBoot,jc as buildComposeLogsCommand,pI as buildComposeRuntimeCommand,gI as buildComposeScaleCommand,zc as buildComposeShellCommand,Op as buildDrainSourceScript,sf as buildDrainedSiteScanScript,xd as buildFailoverReplicaPolicyStatement,rr as buildFunctionEnv,_p as buildHealthGateScript,Hn as buildHostCleanupDeployScript,ks as buildHostCleanupInstallScript,Qn as buildHostCleanupScript,gi as buildHostSitePortsScript,Dd as buildMailEnv,Ls as buildManagementDashboardArtifact,Qu as buildMediaCdnPlan,Ou as buildMtaStsPolicy,$h as buildMtaStsServer,HE as buildNodeRuntimeLayerZip,EE as buildOptimizationManager,Sg as buildOriginGroup,qr as buildOriginGroups,tc as buildOriginGuardRule,wp as buildPauseWorkersScript,zE as buildPhpRuntimeLayerZip,vg as buildReplicationConfiguration,bg as buildReplicationRole,Np as buildRestoreScript,J as buildRpxConfig,Fe as buildRpxFragmentRefreshScript,ff as buildSetHostnameScript,qn as buildSiteDeployScript,Pp as buildSnapshotScript,xp as buildSourceStateScript,$n as buildSshArgs,Kn as buildSshBootstrapScript,ec as buildStaticSiteCacheRules,Vn as buildStaticSiteDeployScript,kp as buildTargetStateScript,Rp as buildWorkersStateScript,Bl as bytes,oE as canaryManager,an as canonicalJson,Ct as capabilities,tr as capacity,LS as categorizeChanges,IE as certificateManager,Tf as certificatesMatch,fS as checkIAMPermissions,sy as checkInvocation,yS as checkServiceQuotas,xA as chunk,ef as cleanupDns01Challenge,SI as clearSigningKeyCache,Go as cloneSourceBinding,FS as cloudConfigSchema,op as cloudDrivers,rE as cloudTrailManager,Tc as collectAssets,Ro as collectPhpAppEntries,Bu as collectServerDnsDomains,Qp as completeComposeVolumeDeletion,Mo as completeOidcAuthorization,nS as composePresets,Hs as composeProjectName,qd as composeServerlessAppTemplate,nA as compositeSpendTransport,wt as compressBackup,hy as config,Za as configOrigins,Ql as connectionGuidance,bE as containerRegistryManager,kf as controlPlaneDatabaseFile,Fc as controlPlaneMigrations,VI as createApiBackendPreset,jo as createApiV1Handler,vy as createAsgBuildDriver,Au as createBackupQueueHandlers,ly as createCliHandler,_ as createCloudDriver,fc as createCloudFrontPolicy,uS as createCredentialProvider,tS as createDashboardSite,JI as createDataPipelinePreset,Hl as createDataServiceQueueHandlers,Kc as createDeploymentQueueHandlers,R as createDnsProvider,by as createEcsBuildDriver,hd as createEnforcementHandlers,Ng as createError,Fd as createExistingStaticFullStackPreset,Vl as createFleetQueueHandlers,qI as createFullStackAppPreset,Rs as createGoDaddyValidator,jE as createHandlers,cy as createHttpHandler,zI as createJamstackPreset,Ul as createJobQueueHandlers,ZI as createLaravelPreset,XI as createMLApiPreset,Yl as createMaintenanceQueueHandlers,Ju as createMediaAccessToken,KI as createMicroservicesPreset,VS as createMockAWS,QI as createNodeJsServerPreset,HI as createNodeJsServerlessPreset,gs as createObjectStorageClient,ws as createPorkbunValidator,iS as createPreset,sA as createPresignedUrl,mI as createPresignedUrlAsync,dy as createQueueHandler,WI as createRealtimeAppPreset,zl as createRegionQueueHandlers,Pl as createReleaseProvenance,yl as createReleaseQueueHandlers,Cy as createRemoteBuildQueueHandlers,Ds as createRoute53Validator,sh as createRuntimeAdapters,pS as createS3Client,Ey as createServerBuildDriver,eS as createServerlessLaravelPreset,GI as createServerlessNodePreset,Nu as createSmsInfrastructure,Ze as createSourceAdapter,UI as createStaticSitePreset,YI as createTraditionalWebAppPreset,Wc as createVolumeQueueHandlers,jI as createWordPressPreset,_i as createZip,fC as crossRegionReferenceManager,mn as dashboardActions,xs as dashboardCredentialsFile,sn as dataServiceCapabilities,fE as databaseUserManager,ol as decodeBase32,Oe as decompressBackup,Th as decryptBackup,_o as defaultConfig,xg as defaultLocalConfig,tl as defaultRateLimitRules,pr as delegateZone,ys as delegateZoneFromConfig,pu as deleteFailoverReplicaBuckets,Fa as deleteStaticSite,kc as deployAllComputeSites,Ea as deployServerlessApp,gu as deploySite,$s as deploySiteRelease,os as deployStaticSite,Ua as deployStaticSiteFull,hn as deployStaticSiteWithExternalDns,fn as deployStaticSiteWithExternalDnsFull,wd as deploymentCoexistenceError,AA as deriveManagementDashboardPort,Is as describeDelegation,nl as describePosture,Cs as describeZoneSettings,ah as desiredJobProviderState,Jp as detectAnomalies,mg as detectDeploymentTargets,rc as detectDnsProvider,ld as detectLatestAnomaly,mS as detectMisconfigurations,lg as detectServiceRegion,qc as diffCompose,_S as diffTemplates,Ho as discoverGitRefs,Lo as discoverOidcProvider,_l as discoverRuntimeInventory,FE as dlqMonitoringManager,nc as dnsProviders,BE as dnssecManager,rh as dockerWorkloads,Xi as documentDigest,eE as drManager,Qe as driverStatePath,Ol as ecsWorkloads,Mt as effectiveCapabilities,xE as emailAnalyticsManager,$E as emailTemplateManager,Fi as encodeBase32,vh as encryptBackup,kl as ensureDefaultSecurityPolicies,du as ensureFailoverReplicaBuckets,ni as ensureFirewall,oi as ensureManagementDashboard,ii as ensureServer,ri as ensureSshKey,Y as escapeSecLang,id as evaluateBudget,Yn as evaluatePreflight,oo as evaluateTelemetryAlertRules,Fl as eventBridgeScheduleInput,ay as eventToRequest,zf as ewma,Gc as exportCompose,Es as exportRoute53Zone,Dg as extendPreset,ME as fifoQueueManager,wS as findChangedFiles,Gp as findMapping,Hp as findPriceEntry,$C as formatAccountStructure,Cf as formatAttachPlan,eC as formatBytes,Qr as formatCents,xI as formatDiff,af as formatDrainedSiteRefusal,tC as formatDuration,lC as formatFlagSuggestions,gC as formatHistory,mC as formatHistoryStats,uf as formatInventory,nC as formatKeyValue,rC as formatList,gf as formatPlan,ei as formatPreflightFindings,ZS as formatProgressBar,qA as formatRegion,DC as formatRegionList,Ym as formatScanResults,iC as formatSuggestion,XS as formatTable,$r as formatTimeToExhaustion,YS as formatTree,EA as fromEC2Metadata,bA as fromECSMetadata,SA as fromEnvironment,CA as fromSharedCredentials,vA as fromWebIdentity,jd as functionFingerprint,xn as gatewayHostnames,Vd as generateAppImageDockerfile,XC as generateApprovalConfig,JA as generateBootstrap,KS as generateCleanupWorkflow,WS as generateCostReportWorkflow,xC as generateCrossAccountRoleCF,wl as generateCycloneDxSbom,KC as generateDeploymentConfig,GC as generateDeploymentPipeline,MC as generateDeploymentWorkflow,Ma as generateExternalDnsStaticSiteTemplate,gp as generateHttpsServerCode,Rl as generateImageSbom,fp as generateLetsEncryptUserData,t as generateLogicalId,zC as generateManualPipeline,HC as generateMatrixWorkflow,WC as generateMultiEnvConfig,qC as generateMultiEnvPipeline,FC as generateMultiEnvWorkflow,UC as generatePRPreviewWorkflow,YC as generateParallelConfig,uy as generatePhpFpmConfig,ty as generatePhpLayerDockerfile,VC as generatePreviewPipeline,zS as generatePreviewWorkflow,r as generateResourceName,JC as generateScheduledConfig,jC as generateScheduledPipeline,QC as generateScheduledWorkflow,ss as generateStaticSiteTemplate,B as generateUbuntuAppCloudInit,RA as getAccountId,SC as getAllRegions,TC as getClosestRegion,uC as getCommandUsage,Bf as getComposeTemplate,qm as getConfig,oC as getContextualHelp,Ao as getCredentials,$S as getDeploymentStrategy,MS as getDiffStats,OS as getDiffSummary,kA as getErrorDetails,Qd as getLocalConfig,GS as getLocalCredentials,HS as getLocalEndpoint,qS as getLocalEnvVars,IS as getQuotaUsageSummary,OC as getRecommendedStructure,Bi as getRegion,PC as getRegionStats,EC as getRegionsByCompliance,CC as getRegionsByLocation,bC as getRegionsByPricingTier,BA as getRequiredPermissions,CI as getSigningKeyCacheSize,Pu as getSmsInfrastructureStatus,RI as getTimestamp,Do as globMatches,Ms as globToRegex,AC as globalResourceManager,Ii as governingLimitCents,lu as grantFailoverReplicaAccess,nE as guardDutyManager,co as handleSpendRequest,On as hasAutoWwwVariant,Wt as hasManagementDashboardSite,Mc as hasProxyUpstream,ES as hashBuffer,bS as hashDirectory,_g as hashFile,vS as hashManifest,Og as hashString,JE as healthCheckManager,Nn as hostAcceptsIpv6,wn as hostCondition,Oo as hotp,Lr as hourBucket,jf as hourBucketsBetween,CE as imageScanningManager,es as infraEnvFromOutputs,Kd as inspectInvocation,ny as installRecursionFetch,cs as invalidateCache,$m as invocationContext,sC as isLikelyTypo,Bn as isLocalDatabase,QS as isLocalDevelopment,Vr as isManagementDashboardSiteName,lr as isNameserverRegistrar,EI as isNodeCryptoAvailable,dd as isOperationAllowed,so as isQuietHours,_d as isS3RestEndpoint,ci as isSafePattern,vd as isStateDirConfigured,Td as isStatePath,Hr as isValidCidr,vC as isValidRegion,Ai as isValidTimeZone,bI as isWebCryptoAvailable,ur as isZoneHost,nn as jobProviderCapability,ps as keyMatchesFilters,RE as lambdaConcurrencyManager,NE as lambdaDLQManager,DE as lambdaDestinationsManager,TE as lambdaLayersManager,PE as lambdaVPCManager,wE as lambdaVersionsManager,xl as lambdaWorkloads,Xd as laravelServerlessEnvDefaults,Br as listComposeTemplates,qi as listSourceReferences,sl as loadCloudConfig,Gt as loadTelemetryPolicy,uE as logsManager,ud as lookbackHoursForSignal,aA as mailEnabled,Rd as mailFirewallPorts,gh as maintenanceWindowOpen,oA as makeAWSRequest,fI as makeAWSRequestAsync,hI as makeAWSRequestOnce,Rg as managementDashboardSiteName,Kl as manifestDigest,Jr as matchTotpCounter,Xu as mediaObjectHeaders,Zs as median,Kp as medianAbsoluteDeviation,sd as mergeDecisions,jr as mergeInfrastructure,qf as mergePriceBooks,td as meterTelemetry,lE as metricsManager,Tu as migrateObjectStorage,gE as migrationManager,NC as multiAccountManager,hC as multiRegionManager,rf as needsRenewal,XE as networkSecurityManager,bt as nextScheduleRuns,Ce as normalizePublicIpv6,ke as normalizeRuntimeStatus,et as normalizeScheduleExpression,Jm as normalizeSourceEvent,Ue as normalizeSshPublicKey,tg as normalizeTelemetryPolicy,pi as occupiedHostPorts,Vo as openApiDocument,no as optionsForSignal,kC as organizationManager,Yd as packagePhpApp,Wr as packageServerlessApp,Rc as pagesAssetHash,Uu as pagesDnsRecord,Ud as parallel,DS as parallelMap,PS as parallelWithRetry,vf as parseCertificateState,zd as parseChain,kr as parseCompose,lI as parseComposeCatalog,th as parseDockerInspect,Su as parseDotenv,of as parseDrainedSites,mi as parseHostSiteFragments,II as parseJSONResponse,Xn as parsePreflightFacts,Lp as parseSourceDrained,nh as parseSystemdRecords,Bp as parseTargetReady,$c as parseUpstreamPort,Dp as parseWorkersPaused,yI as parseXMLResponse,Ti as pathTemplate,xc as pendingSteps,Ys as percentOfLimit,hE as performanceManager,xm as phpLayerBuildStage,ey as phpLayerPackages,xi as phpRuntimeLayerAssets,uI as planComposeTemplateUpgrade,od as planEnforcement,vp as planIsDestructive,dg as planMitigation,hf as planServerRename,Df as planSiteMove,bs as planZoneMigration,kt as policyTag,Zn as preflightFailed,jS as previewManager,JS as previewNotifications,vt as previewSchedule,Vf as previousBudgetWindow,Ws as priceUsage,Hf as priceUsageLines,df as probeHostRoutes,_s as probeOriginTls,BS as processInChunks,bl as processSourceWebhook,zi as productionChangeReview,cE as progressiveDeploymentManager,nd as projectSpend,Wd as propagationHeaders,Ha as providerEndpoint,Wl as publicKeyFingerprint,Rn as qualifyName,QE as queueManagementManager,TS as quickHash,el as rateLimitHeaders,$i as rateLimitKey,He as readDriverState,lf as reconcile,_u as reconcileAddressRecords,Vu as reconcileCloudflareCdn,As as reconcileDeclaredRecords,Sy as reconcileJobObservation,Zr as reconcileSourceWebhook,ji as recordDashboardHostPosture,Ay as recordPreDeploySecretScan,yy as recordSkippedSecretScan,Jd as recursionBlockedResponse,Be as redactRuntimeConfig,yd as redactTelemetryText,vi as redactTelemetryValue,ln as redeployServerlessApp,yC as regionPairManager,Yr as releaseStrategyCapabilities,Km as releaseTrafficPlan,ai as reloadRpxGateway,us as remapKey,Du as removeDns01ChallengeRecord,dn as removeSiteFromCloudConfig,vl as removeSourceWebhook,ic as removeStaleServerAddressRecords,Vc as renderComposeTemplate,Di as renderDdosInstallScript,Ed as renderNftablesRuleset,Ki as renderServerCron,Cd as renderSysctlFile,_c as renderWafConfig,di as renderWafInstallScript,Bc as renewRpxCertificates,mE as replicaManager,iA as requestHash,xS as requiresReplacement,qE as resetRecursionRuntime,VE as resolveApp,p as resolveAppDatabase,Af as resolveAttachTarget,Ye as resolveAuthEncryptionKey,ge as resolveCloudProvider,Hu as resolveCloudflareCdnPlan,TA as resolveCredentials,is as resolveDashboardAction,Nc as resolveDashboardAuth,yA as resolveDashboardDomain,IA as resolveDashboardDomains,fs as resolveDeclaredRecords,_I as resolveDeployBucketName,M as resolveDeploymentMode,Gn as resolveExecStart,Bd as resolveFailoverStatusCodes,hc as resolveHetznerApiToken,Cr as resolveHostCleanupConfig,Pi as resolveMailService,rS as resolveManagementDashboardSite,ki as resolveManagementDashboardSites,Ga as resolveObjectStorage,De as resolveOriginConnection,pf as resolvePlan,g as resolveProjectStackName,Nr as resolveProxyUpstreams,Gd as resolveQueueNames,Of as resolveQueuedDeploymentCommand,Xt as resolveQueues,ry as resolveRecursionConfig,wA as resolveRegion,ie as resolveRuntimeInventory,qt as resolveServerlessAppStackName,Nd as resolveServerlessArtifactBucketName,po as resolveServerlessAssetBucketName,Co as resolveServerlessRuntime,kI as resolveSiteBucketName,Fs as resolveSiteDeployTarget,u as resolveSiteKind,NI as resolveSiteResourceName,PI as resolveSiteStackName,Wn as resolveSshSettings,d as resolveStatePath,BI as resolveStorageBucketName,Cg as resolveStorageFailover,Lt as resolveUiSource,Ac as resolveZoneApex,YE as resourceManagementManager,Mm as responseToResult,Wp as robustZScore,$t as roleCapabilities,Al as rollbackImmutableRelease,un as rollbackServerlessApp,Gf as roundCents,_E as route53ResolverManager,kE as route53RoutingManager,Yp as routeMatches,Cp as routesFromFragments,Li as ruleMatches,XA as runBuildHooks,ad as runEnforcement,wo as runPhpBuildHooks,tt as runRemoteCommand,he as runtimeId,Le as s3OriginBucket,Eg as s3RegionalDomain,Dn as sameNameservers,ns as sanitizeCloudConfig,s as sanitizeControlPlaneValue,DI as sanitizeName,ul as sanitizeOidcReturnPath,fd as saveTelemetryPolicy,Xm as scanForSecrets,Uc as scopeContains,ht as scopeKey,dc as scpUpload,aC as searchCommands,Qs as searchControlPlane,yE as secretsManager,AE as secretsRotationManager,Iy as secureContainerRelease,iE as securityHubManager,SE as securityScanningManager,ne as securityScope,uu as seedFailoverReplicas,Xr as sendAuthenticationEmail,LE as senderReputationManager,NS as sequence,Cu as serializeDotenv,si as serverPublicIpv4,vE as serviceMeshManager,su as setAttachToInCloudConfig,nr as setMaintenance,Yi as setSitePropertyInCloudConfig,bd as setStateDir,hp as setupDns01Challenge,Xa as setupSmsInfrastructure,So as sha256,iy as sharedRecursionGuard,Lm as sharedRuntimeLoop,Fp as shipsARelease,qu as signCloudFrontCookies,Zu as signCloudFrontUrl,x as signRequest,ug as signRequestAsync,to as signalDefinition,O as siteInstallBase,ui as siteMoveArchivePath,Ef as siteMoveCertArchivePath,Lc as siteUnitGlob,ng as spendNotificationText,lo as spendOpenApiPaths,Ir as sshExec,ue as sshExecOrThrow,IC as stackDependencyManager,$a as startLocalDashboardServer,rA as startSpendLoop,uo as stateDir,L as statePath,KE as staticSiteManager,WE as storageAdvancedManager,$I as storageFailoverReplicasFromTemplate,Kf as streamFocusJsonl,cd as strongestActiveAction,Qg as suggestCommand,dC as suggestFlags,AS as suggestIAMPolicy,SS as suggestQuotaIncrease,RC as suggestRegionPairs,wC as suggestRegions,Gi as syncSourceRepositories,Jc as synchronizeComposeVolumes,Eu as synchronizeConfiguredConfiguration,Zo as synchronizeConfiguredJobs,pE as syntheticsManager,Sd as sysctlHardening,ih as systemdWorkloads,Zf as telemetryBucketLabel,wi as telemetryCursor,Ad as telemetryEstimatedMonthlyCost,Yf as telemetryPercentile,rg as telemetryPolicyKey,CS as templateCache,Ep as tenantsOf,qo as testSourceConnection,Xc as tieredMicroCents,Bs as toCloudflareZoneSettings,io as toFocusJsonl,pd as toFocusRecords,cf as toInventoryServer,Vm as totp,xo as totpUri,bp as unaccountedSites,eh as unsupportedCapabilities,xf as unsupportedVolumeCapabilities,Xl as updateCompatibility,Zl as updateSiteInCloudConfig,as as uploadStaticFiles,qp as usageDeltaKey,Qt as utcInstantOfLocal,LC as validateAccountStructure,US as validateAgainstSchema,$f as validateAttachment,bh as validateBackupDestination,pC as validateCommand,gS as validateConfiguration,hS as validateCredentials,Mp as validateDeploymentConfig,Lf as validateMountPath,jt as validateOriginGroups,au as validateResourceLimits,Tp as validateServerName,eu as validateTemplate,ou as validateTemplateSize,oc as verifyAddressRecord,fy as verifyArtifactSignature,Yu as verifyMediaAccessToken,jm as verifyTotp,Jl as verifyUpdateSignature,Ts as verifyZoneParity,Vs as volumeCapabilities,Ap as wafEventTelemetry,lc as waitForCloudInit,Mn as waitForSsh,Zt as webhookEndpoint,dS as withCDN,cS as withCache,aS as withDatabase,oy as withInvocation,sS as withMonitoring,lS as withQueue,oS as withSecurity,kS as withTimeout,X as wrapCloudInitUserData,ct as writeDriverState,dE as xrayManager,jl as zeroCapacity,Wf as zeroFill,Zc as zoneOffsetMs,Js as zonedParts};
604
+ `}async function $u(l,h,A){let w=`_acme-challenge.${h}`;if(await wu(l,h,w,A))return;let v=await l.createRecord(h,{name:w,type:"TXT",content:A,ttl:60});if(!v.success)throw Error(`Failed to create DNS challenge record: ${v.message}`)}async function Du(l,h,A){let w=await l.deleteRecord(h,{name:`_acme-challenge.${h}`,type:"TXT",content:A});if(!w.success)console.warn(`Failed to delete DNS challenge record: ${w.message}`)}async function wu(l,h,A,w){try{let v=await l.listRecords(h,"TXT"),Ee=A.replace(/\.$/,"").toLowerCase();return(v.records??[]).some((oe)=>oe.name.replace(/\.$/,"").toLowerCase()===Ee&&oe.content.replace(/^"|"$/g,"")===w)}catch{return!1}}function gc(l){let{hostedZoneId:h,dnsProvider:A,region:w="us-east-1"}=l;if(A)return R(A);if(h)return new W(w,h);throw Error("Either dnsProvider or hostedZoneId must be provided")}async function hp(l){await $u(gc(l),l.domain,l.challengeValue)}async function Ap(l){await Du(gc(l),l.domain,l.challengeValue)}function ef(l){try{let{execSync:h}=Ge("node:child_process"),A=h(`openssl x509 -checkend 2592000 -noout -in ${l}/cert.pem`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return!1}catch{return!0}}import{createHash as yc,createSign as vu,generateKeyPairSync as Cc}from"node:crypto";var Sc={production:"https://acme-v02.api.letsencrypt.org/directory",staging:"https://acme-staging-v02.api.letsencrypt.org/directory"};class Lu{directoryUrl;email;accountKey;accountUrl=null;directory=null;nonce=null;constructor(l){this.directoryUrl=l.staging?Sc.staging:Sc.production,this.email=l.email,this.accountKey=l.accountKey||this.generateAccountKey()}generateAccountKey(){let{privateKey:l}=Cc("ec",{namedCurve:"P-256"});return l.export({type:"pkcs8",format:"pem"})}async getDirectory(){if(this.directory)return this.directory;let l=await fetch(this.directoryUrl);if(!l.ok)throw Error(`Failed to fetch ACME directory: ${l.status}`);return this.directory=await l.json(),this.directory}async getNonce(){if(this.nonce){let w=this.nonce;return this.nonce=null,w}let l=await this.getDirectory(),A=(await fetch(l.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!A)throw Error("Failed to get nonce from ACME server");return A}getJwk(){let l=this.accountKey.split(`
605
+ `).filter((Ee)=>!Ee.startsWith("-----")).join(""),h=Buffer.from(l,"base64"),A=h.length-65,w=h.subarray(A+1,A+33),v=h.subarray(A+33,A+65);return{kty:"EC",crv:"P-256",x:this.base64UrlEncode(w),y:this.base64UrlEncode(v)}}getJwkThumbprint(){let l=this.getJwk(),h=JSON.stringify({crv:l.crv,kty:l.kty,x:l.x,y:l.y}),A=yc("sha256").update(h).digest();return this.base64UrlEncode(A)}base64UrlEncode(l){return(typeof l==="string"?Buffer.from(l):l).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async signPayload(l,h){let A=await this.getNonce(),w=this.getJwk(),v={alg:"ES256",nonce:A,url:l};if(this.accountUrl)v.kid=this.accountUrl;else v.jwk=w;let Ee=this.base64UrlEncode(JSON.stringify(v)),oe=h===""?"":this.base64UrlEncode(JSON.stringify(h)),ae=`${Ee}.${oe}`,be=vu("SHA256");be.update(ae);let dt=be.sign(this.accountKey),_e=dt.subarray(4,4+dt[3]),_t=4+dt[3]+2,ir=dt.subarray(_t,_t+dt[_t-1]),fr=Buffer.alloc(32),ut=Buffer.alloc(32);_e.copy(fr,32-_e.length),ir.copy(ut,32-ir.length);let at=Buffer.concat([fr,ut]);return JSON.stringify({protected:Ee,payload:oe,signature:this.base64UrlEncode(at)})}async acmeRequest(l,h){let A=await this.signPayload(l,h),w=await fetch(l,{method:"POST",headers:{"Content-Type":"application/jose+json"},body:A}),v=w.headers.get("replay-nonce");if(v)this.nonce=v;let Ee,oe=w.headers.get("content-type");if(oe?.includes("application/json")||oe?.includes("application/problem+json"))Ee=await w.json();else Ee=await w.text();if(!w.ok)throw Error(`ACME request failed: ${JSON.stringify(Ee)}`);return{body:Ee,headers:w.headers}}async registerAccount(){let l=await this.getDirectory(),{body:h,headers:A}=await this.acmeRequest(l.newAccount,{termsOfServiceAgreed:!0,contact:[`mailto:${this.email}`]}),w=A.get("location");if(!w)throw Error("No account URL returned");return this.accountUrl=w,w}async createOrder(l){if(!this.accountUrl)await this.registerAccount();let h=await this.getDirectory(),{body:A,headers:w}=await this.acmeRequest(h.newOrder,{identifiers:l.map((Ee)=>({type:"dns",value:Ee}))}),v=w.get("location");if(!v)throw Error("No order URL returned");return{orderUrl:v,authorizations:A.authorizations,finalize:A.finalize}}async getAuthorization(l){let{body:h}=await this.acmeRequest(l,""),A=h.identifier.value,w=this.getJwkThumbprint(),v=h.challenges.filter((Ee)=>Ee.type==="http-01"||Ee.type==="dns-01").map((Ee)=>{let oe=`${Ee.token}.${w}`;if(Ee.type==="http-01")return{type:"http-01",token:Ee.token,keyAuthorization:oe,identifier:`/.well-known/acme-challenge/${Ee.token}`};else{let ae=this.base64UrlEncode(yc("sha256").update(oe).digest());return{type:"dns-01",token:Ee.token,keyAuthorization:oe,identifier:`_acme-challenge.${A}`,dnsValue:ae}}});return{domain:A,challenges:v}}async respondToChallenge(l){await this.acmeRequest(l,{})}async waitForAuthorization(l,h=30){for(let A=0;A<h;A++){let{body:w}=await this.acmeRequest(l,"");if(w.status==="valid")return;if(w.status==="invalid")throw Error(`Authorization failed: ${JSON.stringify(w)}`);await new Promise((v)=>setTimeout(v,2000))}throw Error("Authorization timed out")}generateCsr(l){let{privateKey:h}=Cc("rsa",{modulusLength:2048}),A=h.export({type:"pkcs8",format:"pem"});return{csr:this.createSimpleCsr(l,h),privateKey:A}}createSimpleCsr(l,h){throw Error("CSR generation requires additional implementation. Consider using the shell-based certbot approach instead.")}async finalizeOrder(l,h){let{csr:A,privateKey:w}=this.generateCsr(h),{body:v}=await this.acmeRequest(l,{csr:this.base64UrlEncode(Buffer.from(A,"base64"))}),Ee=v.certificate;if(!Ee)throw Error("Certificate not immediately available - polling not implemented");let ae=await(await fetch(Ee)).text(),be=ae.split(/(?=-----BEGIN CERTIFICATE-----)/g),dt=be[0],_e=be.slice(1).join("");return{certificate:dt,privateKey:w,chain:_e,fullchain:ae,expiresAt:new Date(Date.now()+7776000000)}}getAccountKey(){return this.accountKey}}var Zi=(l)=>l===void 0?void 0:l?"on":"off";function Bs(l){let h={ssl:l.ssl,always_use_https:Zi(l.alwaysUseHttps),automatic_https_rewrites:Zi(l.automaticHttpsRewrites),min_tls_version:l.minTlsVersion,tls_1_3:Zi(l.tls13),brotli:Zi(l.brotli),http3:Zi(l.http3),"0rtt":Zi(l.zeroRtt),early_hints:Zi(l.earlyHints),browser_cache_ttl:l.browserCacheTtl,always_online:Zi(l.alwaysOnline),websockets:Zi(l.websockets),email_obfuscation:Zi(l.emailObfuscation)};if(l.hsts)h.security_header={strict_transport_security:{enabled:l.hsts.enabled,max_age:l.hsts.maxAge??31536000,include_subdomains:l.hsts.includeSubdomains??!1,preload:l.hsts.preload??!1,nosniff:l.hsts.noSniff??!0}};for(let A of Object.keys(h))if(h[A]===void 0)delete h[A];return{...h,...l.raw??{}}}var Un={ssl:"strict",alwaysUseHttps:!0,automaticHttpsRewrites:!0,minTlsVersion:"1.2",tls13:!0,brotli:!0,http3:!0,earlyHints:!0,alwaysOnline:!0,emailObfuscation:!1,browserCacheTtl:0};import{connect as Fu}from"node:tls";async function _s(l){let{address:h,serverName:A,port:w=443,timeoutMs:v=5000}=l;return new Promise((Ee)=>{let oe=!1,ae=(dt)=>{if(oe)return;oe=!0;try{be.destroy()}catch{}Ee(dt)},be=Fu({host:h,port:w,servername:A,rejectUnauthorized:!1,timeout:v});be.once("secureConnect",()=>{if(be.authorized){ae({reachable:!0,trusted:!0});return}ae({reachable:!0,trusted:!1,reason:be.authorizationError?String(be.authorizationError):"origin certificate is not trusted for this hostname"})}),be.once("timeout",()=>{ae({reachable:!1,trusted:!1,reason:`no TLS handshake within ${v}ms`})}),be.once("error",(dt)=>{ae({reachable:!1,trusted:!1,reason:dt.message})})})}function Mu(l,h){let A=h.replace(/\.$/,"").toLowerCase();return l.some((w)=>{let v=w.replace(/\.$/,"").toLowerCase();if(v===A)return!0;if(!v.startsWith("*."))return!1;let Ee=v.slice(2);if(!A.endsWith(`.${Ee}`))return!1;return!A.slice(0,A.length-Ee.length-1).includes(".")})}async function Vu(l){let{provider:h,zone:A,hosts:w,ipv4:v,ipv6:Ee,proxied:oe=!0,settings:ae=Un,cache:be,originGuard:dt,purge:_e=!0,ttl:_t=300,skipOriginProbe:ir=!1,skipEdgeCertificateCheck:fr=!1}=l,ut={records:[],settingsChanged:[],cacheRules:0,originGuard:!1,purged:!1,deferredProxy:[],warnings:[]};if(w.length===0)return ut;let at=[],k=oe&&!fr?await h.listEdgeCertificateHosts(A):null;for(let E of w){let lt=oe;if(lt&&k&&!Mu(k,E)){lt=!1;let xt=k.length===0?"the zone has no active edge certificate yet":`no active edge certificate covers it (${k.join(", ")})`;ut.deferredProxy.push({host:E,reason:xt}),ut.warnings.push(`${E}: publishing DNS-only — ${xt}. Proxying it would make Cloudflare terminate TLS with no certificate for the name, which fails the handshake outright rather than degrading. Universal SSL covers the apex and ONE level of subdomain, so a deeper name needs its own certificate; otherwise re-run the deploy once the certificate is active.`)}if(lt&&!ir){let xt=await _s({address:v,serverName:E});if(!xt.trusted){lt=!1;let Bt=xt.reason||"origin is not serving a trusted certificate";ut.deferredProxy.push({host:E,reason:Bt}),ut.warnings.push(`${E}: publishing DNS-only for now — the origin does not yet serve a certificate this proxy can verify (${Bt}). The origin issues certificates over HTTP-01, which needs the name to reach it directly; re-run the deploy once it has one and the record will be proxied.`)}}if(lt)at.push(E);let Tt=[{type:"A",content:v}];if(Ee&&Nn(E))Tt.push({type:"AAAA",content:Ee});for(let{type:xt,content:Bt}of Tt){let mr=await h.upsertRecord(A,{name:E,type:xt,content:Bt,ttl:_t,proxied:lt});if(mr.success)ut.records.push({host:E,type:xt,content:Bt,proxied:lt});else ut.warnings.push(`${E} ${xt} → ${Bt} failed: ${mr.message||"unknown provider error"}`)}}if(at.length===0){if(oe)ut.warnings.push("No host is proxied yet, so zone settings, cache rules and purge were skipped — they only take effect through the proxy.");return ut}try{let E=Bs(ae),lt=await h.applyZoneSettings(A,E);ut.settingsChanged=lt.changed;for(let Tt of lt.failed)ut.warnings.push(`zone setting '${Tt.id}' could not be applied: ${Tt.error}`)}catch(E){ut.warnings.push(`zone settings could not be read: ${E instanceof Error?E.message:String(E)}`)}let Ot=ec(at,be);if(Ot.length>0){let E=await h.putManagedPhaseRules(A,"http_request_cache_settings",Ot);if(E.success)ut.cacheRules=Ot.length;else ut.warnings.push(`cache rules could not be written: ${E.message}`)}if(dt){let E=tc(at,dt.header,dt.value);if(E.length>0){let lt=await h.putManagedPhaseRules(A,"http_request_late_transform",E);if(lt.success)ut.originGuard=!0;else ut.warnings.push(`origin guard header could not be written: ${lt.message}. `+"The gateway will reject requests that lack it — disable the guard or grant the token Transform Rules: Edit.")}}if(_e){if(ut.purged=await h.purgeCache(A,{hosts:at}),!ut.purged)ut.warnings.push("edge cache purge failed — new content may take until TTL expiry to appear.")}return ut}var Wu=(l)=>process.env[l];function Ac(l,h){let A=l.replace(/\.$/,"").toLowerCase();if(h){let w=h.replace(/\.$/,"").toLowerCase();if(A===w||A.endsWith(`.${w}`))return w}return A.split(".").slice(-2).join(".")}function Hu(l,h={}){let A=h.env??Wu,w=l.infrastructure?.compute?.proxy?.cdn,v=[];if(!w||w.provider!=="cloudflare")return{plan:null,errors:v};if(w.originDomain)v.push(`compute.proxy.cdn.originDomain (${w.originDomain}) is ignored for Cloudflare: the proxy forwards to the address in the record it fronts, `+"so no separate origin hostname is needed — and publishing one gives clients a documented way around the edge.");let Ee=A("CLOUDFLARE_API_TOKEN");if(!Ee)return v.push("CLOUDFLARE_API_TOKEN is not set — the Cloudflare CDN cannot be reconciled."),{plan:null,errors:v};let oe=l.sites??{},ae=w.frontedHosts?.length?[...new Set(w.frontedHosts.map((ir)=>ir.toLowerCase()))]:xn(oe,{autoWww:l.infrastructure?.compute?.proxy?.autoWww!==!1});if(ae.length===0)return v.push("No hostnames to front — set compute.proxy.cdn.frontedHosts, or give a site a domain."),{plan:null,errors:v};let be=l.infrastructure?.dns?.domain,dt=new Set(ae.map((ir)=>Ac(ir,be)));if(dt.size>1)return v.push(`Fronted hosts span more than one zone (${[...dt].join(", ")}). A Cloudflare zone is configured as a unit, so run one CDN config per zone.`),{plan:null,errors:v};let _e=w.cloudflare??{},_t=w.secret?{header:w.secretHeader??"X-Origin-Verify",value:w.secret}:void 0;return{plan:{zone:[...dt][0],hosts:ae,apiToken:Ee,zoneId:_e.zoneId??A("CLOUDFLARE_ZONE_ID"),accountId:_e.accountId??A("CLOUDFLARE_ACCOUNT_ID"),proxied:_e.proxied!==!1,settings:_e.settings??Un,cache:_e.cache,originGuard:_t,purge:_e.purgeOnDeploy!==!1,skipOriginProbe:_e.skipOriginProbe===!0},errors:v}}var Gu=26214400;var zu=new Set(["/_headers","/_redirects","/_routes.json","/_worker.js"]);class bc{name="cloudflare-pages";apiToken;accountId;constructor(l){if(!l.apiToken)throw Error("Cloudflare Pages needs an API token");if(!l.accountId)throw Error("Cloudflare Pages needs an account id");this.apiToken=l.apiToken,this.accountId=l.accountId}async request(l,h,A){return Ka(l,`/accounts/${this.accountId}${h}`,`Bearer ${this.apiToken}`,A)}async getProject(l){try{return await this.request("GET",`/pages/projects/${l}`)}catch(h){if(h instanceof Error&&/\b8000007\b|not found/i.test(h.message))return null;throw h}}async ensureProject(l,h="main"){let A=await this.getProject(l);if(A)return A;return this.request("POST","/pages/projects",{name:l,production_branch:h})}async uploadToken(l){return(await this.request("GET",`/pages/projects/${l}/upload-token`)).jwt}async missingHashes(l,h){let A=await Ka("POST","/pages/assets/check-missing",`Bearer ${l}`,{hashes:h});return new Set(A)}async upsertHashes(l,h){await Ka("POST","/pages/assets/upsert-hashes",`Bearer ${l}`,{hashes:h})}async uploadBatch(l,h){let A=h.map((w)=>({key:w.hash,value:w.base64,metadata:{contentType:Ku(w.extension)},base64:!0}));await Ka("POST","/pages/assets/upload",`Bearer ${l}`,A)}async createDeployment(l,h,A){let w={};for(let Ee of h)w[Ee.path]=Ee.hash;let v=new FormData;if(v.append("manifest",JSON.stringify(w)),A)v.append("branch",A);return this.request("POST",`/pages/projects/${l}/deployments`,v)}async deployDirectory(l){let h=await Tc(l.directory);if(h.length===0)throw Error(`No files to deploy in ${l.directory}`);let A=await this.uploadToken(l.project),w=await this.missingHashes(A,h.map((be)=>be.hash)),v=h.filter((be)=>w.has(be.hash)),Ee=[];for(let be=0;be<v.length;be+=100)Ee.push(v.slice(be,be+100));let oe=0;for(let be=0;be<Ee.length;be+=4){let dt=Ee.slice(be,be+4);await Promise.all(dt.map((_e)=>this.uploadBatch(A,_e))),oe+=dt.reduce((_e,_t)=>_e+_t.length,0),l.onProgress?.(oe,v.length)}return await this.upsertHashes(A,h.map((be)=>be.hash)),{deployment:await this.createDeployment(l.project,h,l.branch),total:h.length,uploaded:v.length,uploadedBytes:v.reduce((be,dt)=>be+dt.size,0)}}async listCustomDomains(l){return(await this.request("GET",`/pages/projects/${l}/domains`)).map((A)=>A.name)}async attachCustomDomain(l,h){if((await this.listCustomDomains(l)).includes(h))return!1;return await this.request("POST",`/pages/projects/${l}/domains`,{name:h}),!0}}function Uu(l,h){return{type:"CNAME",name:l,value:h.endsWith(".pages.dev")?h:`${h}.pages.dev`,ttl:1,proxied:!0}}async function Rc(l,h){let{blake3:A}=await import("./chunk-s958jt49.js").then((m)=>rf(m.default,1));return(await A(l+h)).slice(0,32)}async function Tc(l){let{readdir:h}=await import("node:fs/promises"),{join:A,relative:w,sep:v}=await import("node:path"),Ee=[];async function oe(ae){let be=await h(ae,{withFileTypes:!0});for(let dt of be){let _e=A(ae,dt.name);if(dt.isDirectory()){await oe(_e);continue}if(!dt.isFile())continue;let _t=`/${w(l,_e).split(v).join("/")}`;if(zu.has(_t))continue;let ir=await Bun.file(_e).bytes();if(ir.byteLength>26214400)throw Error(`${_t} is ${ir.byteLength} bytes, over the Cloudflare Pages limit of 26214400`);let fr=Buffer.from(ir).toString("base64"),ut=dt.name.lastIndexOf("."),at=ut>0?dt.name.slice(ut+1):"";Ee.push({path:_t,hash:await Rc(fr,at),base64:fr,extension:at,size:ir.byteLength})}}return await oe(l),Ee.sort((ae,be)=>ae.path.localeCompare(be.path)),Ee}function Ku(l){return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",mjs:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",map:"application/json; charset=utf-8",xml:"application/xml; charset=utf-8",txt:"text/plain; charset=utf-8",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",ico:"image/x-icon",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",pdf:"application/pdf",webmanifest:"application/manifest+json"}[l.toLowerCase()]||"application/octet-stream"}async function Ka(l,h,A,w){let v={Authorization:A},Ee;if(w instanceof FormData)Ee=w;else if(w!==void 0)v["Content-Type"]="application/json",Ee=JSON.stringify(w);let oe=await fetch(`https://api.cloudflare.com/client/v4${h}`,{method:l,headers:v,body:Ee}),ae=await oe.text(),be;try{be=JSON.parse(ae)}catch{throw Error(`Cloudflare Pages API returned ${oe.status} with a non-JSON body: ${ae.slice(0,200)}`)}if(!be.success){let dt=(be.errors??[]).map((_e)=>`${_e.code}: ${_e.message}`).join(", ");throw Error(`Cloudflare Pages API error (${oe.status}): ${dt||ae.slice(0,200)}`)}return be.result}export{rm as ABTestManager,le as ACMClient,gr as ACMDnsValidator,Sc as ACME_DIRECTORIES,Pe as AI,ml as API_IDEMPOTENCY_TTL_MS,pl as API_TOKEN_DEFAULT_TTL_MS,gl as API_TOKEN_MAX_TTL_MS,Vi as API_VERSION,pe as AUTHORIZATION_CAPABILITIES,cl as AUTH_ACTION_TOKEN_TTL_MS,dl as AUTH_MFA_CHALLENGE_TTL_MS,ll as AUTH_OIDC_TRANSACTION_TTL_MS,Xe as AUTH_SESSION_ABSOLUTE_TTL_MS,al as AUTH_SESSION_IDLE_TTL_MS,NA as AWSAPIError,n as AWSClient,f as AWSCloudFormationClient,I as AWSCloudFrontClient,Yg as AWSConfigManager,UI as AWS_PSEUDO_PARAMETERS,Ne as AWS_REGIONS,Lu as AcmeClient,Ur as AlertEvaluator,Ei as AlertStore,eo as AnomalyConfigStore,$d as ApiGateway,i as ApiServiceError,Wa as ApplicationAutoScalingClient,fo as Arn,N as AssetHasher,H as Auth,Ui as AuthenticationStore,Ri as AutomationApiService,Qi as AutomationIdentityStore,na as AwsAuroraDataAdapter,ca as AwsAuroraTransport,wa as AwsDatabaseBackupSource,yr as AwsDriver,ia as AwsElastiCacheDataAdapter,da as AwsElastiCacheTransport,eh as AwsIamCapabilityScanner,ka as AwsInfrastructureBackupSource,ra as AwsRdsDataAdapter,aa as AwsRdsTransport,gh as AwsRegionalDriver,_a as AwsSecretsManagerConfigurationBackend,cg as AwsSpendTransport,Oa as AwsSsmConfigurationBackend,rs as BackupCoordinator,Jg as BackupManager,va as BackupStore,Om as BatchProcessingManager,Cn as BedrockClient,Sn as BedrockRuntimeClient,Cl as BitbucketSourceAdapter,tm as BlueGreenManager,Dm as BounceComplaintHandler,fm as BuildOptimizationManager,Gl as BunDockerRuntime,Iu as BunDockerVolumeRuntime,yu as BunFilesystemArchiveRuntime,me as CDN,bo as CHAIN_HEADER,hs as CLOUDFLARE_MANAGED_RULE_PREFIX,kd as CLOUDFRONT_FAILOVER_STATUS_CODES,OC as COMMON_CROSS_ACCOUNT_ROLES,qe as CONTROL_PLANE_SCHEMA_VERSION,mo as Cache,Io as CanaryManager,gm as CertificateManager,Ff as CloudBlockVolumeDriver,Os as CloudDriverFactory,Je as CloudError,wg as CloudFormationBuilder,f as CloudFormationClient,I as CloudFrontClient,Zg as CloudTrailManager,ye as CloudWatchLogsClient,bc as CloudflarePagesProvider,Se as CloudflareProvider,qA as CommandHistory,q as Communication,xr as ComposeApplicationService,Ut as ComposeApplicationStore,Rt as ComprehendClient,a as Compute,dg as ComputeSpendTransport,yo as ConfigurationError,La as ConfigurationService,Ba as ConfigurationStore,yn as ConnectClient,oa as ContainerDataAdapter,Am as ContainerRegistryManager,Na as ControlPlaneBackupSource,Sa as ControlPlaneCleanupDriver,hi as ControlPlaneStore,Xs as CounterTracker,Jt as CredentialError,qg as CrossRegionReferenceManager,hA as DASHBOARD_ENTRY,fA as DASHBOARD_PORT_BASE,AA as DASHBOARD_PORT_SPAN,mA as DASHBOARD_STATE_DIR,No as DEFAULT_ATTACK_MODE_HOURS,Id as DEFAULT_DDOS_THRESHOLDS,fg as DEFAULT_FAILOVER_STATUS_CODES,ed as DEFAULT_METER_MAPPINGS,Yc as DEFAULT_PRICE_BOOK,Oi as DEFAULT_RECURSION_LIMITS,_n as DEFAULT_RPX_CERTS_DIR,j as DEFAULT_SERVICE_LIMITS,gg as DEFAULT_STATE_DIR,ku as DEFAULT_STATIC_ASSET_EXTENSIONS,lA as DEFAULT_STORAGE_FAILOVER_STATUS_CODES,Yf as DEFAULT_TELEMETRY_POLICY,jp as DEFAULT_THRESHOLDS,Of as DEPLOYMENT_QUEUE_KINDS,Eo as DEPTH_HEADER,Mr as DETECTABLE_SIGNALS,Ml as DIAGNOSTIC_PRESETS,_m as DLQMonitoringManager,F as DNS,wm as DNSSECManager,Wi as DataServiceLifecycle,ta as DataServiceStore,zt as Database,lm as DatabaseUserManager,re as DebugLogger,dA as DependencyGraph,G as Deployment,PA as DeploymentError,Xg as DisasterRecoveryManager,Pn as DnsProviderFactory,er as DockerDataTransport,Wo as DockerDiscoveryAdapter,Or as DockerNamedVolumeDriver,Pa as DockerVolumeBackupSource,c as DurableOperationQueue,qs as DurableQueueWorker,xe as DynamoDBClient,wr as EC2Client,$e as ECRClient,rt as ECSClient,dr as EFSClient,Va as ELBv2Client,Qf as ENFORCEMENT_ACTIONS,Si as ENFORCEMENT_DESCRIPTIONS,P as ENFORCEMENT_SEVERITY,Sp as ENVIRONMENT_LABEL,Ll as EcsRuntimeAdapter,Po as EdgeRateLimiter,it as ElastiCacheClient,m as Email,zA as EmailAdvanced,Pm as EmailAnalyticsManager,Tn as EmailClient,KA as EmailHandlers,km as EmailTemplateManager,la as EncryptedDataSecretStore,kA as ErrorCodes,ar as EventBridgeClient,lh as EventBridgeJobAdapter,xa as ExternalConfigurationBackend,go as FAILOVER_REPLICA_POLICY_SID,Bm as FIFOQueueManager,eg as FOCUS_VERSION,Bg as FileCache,Ke as FileSystem,Ra as FilesystemBackupSource,pa as FleetService,ua as FleetStore,e as Fn,El as GiteaSourceAdapter,Il as GithubSourceAdapter,Sl as GitlabSourceAdapter,Vg as GlobalResourceManager,Me as GoDaddyProvider,em as GuardDutyManager,pt as HOST_SITES_DIR,OA as HashCache,Hm as HealthCheckManager,je as HealthCheckRunner,Er as HetznerClient,ve as HetznerDriver,Ie as IAMClient,sc as IPV6_EXCLUDED_HOST_LABELS,hm as ImageScanningManager,rl as InfrastructureGenerator,Qc as InvalidOperationTransitionError,At as JobLoader,uh as JobProviderReconciler,ea as JobService,Yo as JobStore,or as KendraClient,gy as LARAVEL_SERVERLESS_BUILD_STEPS,b as LambdaClient,Cm as LambdaConcurrencyManager,vm as LambdaDLQManager,Em as LambdaDestinationsManager,Im as LambdaLayersManager,$l as LambdaRuntimeAdapter,bm as LambdaVPCManager,Sm as LambdaVersionsManager,gn as LocalEncryptedConfigurationBackend,Da as LogicalDatabaseBackupSource,om as LogsManager,ZA as MANAGED_NODE_VERSIONS,Pc as MANAGEMENT_DASHBOARD_SITE,Rg as MANAGEMENT_DASHBOARD_SITE_PREFIX,Mi as MAX_CONTROL_HOURS,Hc as MAX_CONTROL_PLANE_ERROR_BYTES,Qp as MAX_CONTROL_PLANE_JSON_BYTES,Ks as METERS,Uf as METER_KEYS,Hf as MICRO_CENTS,zp as MIN_PROJECTION_CONFIDENCE,xu as MTA_STS_PORT,Ia as MaintenanceService,ya as MaintenanceStore,te as Messaging,sm as MetricsManager,am as MigrationManager,$g as MockCloudFormation,Fg as MockDynamoDB,Mg as MockS3,ho as Monitoring,Kg as MultiAccountManager,Gg as MultiRegionManager,MA as MultiStepProgress,y as Network,Gm as NetworkSecurityManager,bi as NotificationRouter,Ig as ORIGIN_CONNECTION_ATTEMPTS,Sg as ORIGIN_CONNECTION_TIMEOUT,Ag as ORIGIN_GROUP_ALLOWED_METHODS,$I as ORIGIN_GROUP_ID_SUFFIX,yg as ORIGIN_GROUP_SELECTION_CRITERIA,ja as OpenSearchClient,gt as OptimisticConcurrencyError,Wg as OrganizationManager,Gu as PAGES_MAX_FILE_BYTES,my as PHP_DEFAULT_EXCLUDES,ey as PHP_LAYER_EXTENSIONS,Ip as PROJECT_LABEL,ot as PROXIABLE_RECORD_TYPES,T as ParameterStore,dm as PerformanceManager,ee as Permissions,za as PersonalizeClient,We as Phone,WA as PhoneAdvanced,uA as PhoneHandlers,ma as PlacementService,ga as PlacementStore,En as PollyClient,ce as PorkbunProvider,tn as PreDeployScanner,Ug as PreviewEnvironmentManager,_r as PreviewEnvironmentService,Ve as PreviewEnvironmentStore,Qg as PreviewNotificationService,$A as ProgressBar,nm as ProgressiveDeploymentManager,ko as ProtectionControlStore,RI as Pseudo,U as Queue,fi as QueueCancellationError,xm as QueueManagementManager,TI as QueuePresets,Gs as QueueTimeoutError,Zd as RATE_LIMIT_KEY_SEPARATOR,K as RDSClient,jA as RECOMMENDED_ACCOUNT_STRUCTURES,_C as RECOMMENDED_SCPS,Jm as RELEASE_QUEUE_KINDS,QA as REPL,GA as REPLCommandBuilder,HA as REPLContext,Cp as ROLE_LABEL,xA as RateLimiter,wI as RealtimePresets,tg as RecordingSpendTransport,To as RecursionGuard,yt as Redirects,jg as RegionPairManager,fa as RegionService,ha as RegionStore,ze as Registry,Dt as RekognitionClient,It as ReleaseService,Uo as ReleaseStore,ph as RemoteBuildService,cm as ReplicaManager,qm as ResourceManagementManager,Z as RetryableOperationError,S as Route53Client,qa as Route53DomainsClient,W as Route53Provider,Rm as Route53ResolverManager,Tm as Route53RoutingManager,fe as RuntimeOperationService,Xo as RuntimeStreamRegistry,Ta as S3BackupDestinationAdapter,o as S3Client,V as S3Error,Tl as SECRET_PATTERNS,Yp as SENSITIVITY_THRESHOLDS,st as SESClient,Q as SMS,nt as SNSClient,ag as SPEND_CYCLE_SECONDS,gd as SPEND_GATE_SETTING,rA as SPEND_LEASE_SETTING,se as SQSClient,Te as SSH_BOOTSTRAP_VERSION,Jn as SSH_PREFLIGHT_SCRIPT,we as SSMClient,mg as STATE_DIR_ENV_VAR,Un as STATIC_SITE_ZONE_SETTINGS,Od as STORAGE_FAILOVER_METADATA_KEY,Ae as STSClient,bn as SchedulerClient,Kt as Search,rn as SecretFindingScanner,Ni as Secrets,pm as SecretsManager,z as SecretsManagerClient,um as SecretsRotationManager,C as Security,zr as SecurityHubManager,en as SecurityPostureStore,St as SecurityScannerRunner,mm as SecurityScanningManager,Nm as SenderReputationManager,dh as ServerCronJobAdapter,sa as ServerDataAdapter,zs as ServerPathVolumeDriver,ym as ServiceMeshManager,Ld as Sftp,ro as SignalSource,JA as SmsAdvanced,Nt as SmsClient,pA as SmsHandlers,Ya as SmsVoiceClient,Qo as SourceConnectionStore,Yt as SourceProviderError,md as SpendCapError,Fr as SpendGate,sg as SpendLoopLease,ao as SpendNotificationRouter,og as SpendRunner,Ht as SpendService,yi as SpendStore,FA as Spinner,vr as SshDriver,on as SshFleetDriver,zg as StackDependencyManager,FI as StacksIntegration,Um as StaticSiteManager,Re as Storage,Qm as StorageAdvancedManager,vn as SupportClient,Kr as SyntheticsManager,ql as SystemFleetSshTransport,br as SystemSshTransport,Jo as SystemdDiscoveryAdapter,vo as TRACE_HEADER,UA as TaskList,ft as TelemetryStore,Pd as TemplateBuilder,_g as TemplateCache,Pt as TextractClient,In as TranscribeClient,sr as TranslateClient,fh as TransportDisasterRecoveryDriver,hh as TransportPlatformMaintenanceDriver,Ji as TransportRemoteBuildDriver,zo as TrivyImageScanner,Fo as TsCloudApiError,hl as TsCloudClient,tA as URGENT_SPEND_EVENTS,Kp as USER_VISIBLE_ACTIONS,Aa as UnavailableRegionalDriver,de as UnifiedDnsValidator,Us as UnsupportedSchemaVersionError,Ng as ValidationError,cr as VoiceClient,js as VolumeService,Ft as VolumeStore,gA as Workflow,im as XRayManager,cE as abTestManager,fl as activateImmutableRelease,$u as addDns01ChallengeRecord,cn as addSiteToCloudConfig,Et as ageSeconds,rd as aggregateDeltas,Mp as allocateSitePorts,xI as analyzeStackDiff,Ci as anomalyOptionsForSignal,Bo as applyControlsToDdos,il as applyControlsToRateLimits,Ss as applyDeclaredZoneSettings,Gr as applyMitigationFactor,hf as applyPlan,vs as applyZoneMigration,Hd as artifactKey,Vt as assertOriginGroupMethods,Hi as assertReleaseStrategy,Xf as assertSpendAllows,Sf as attachConflicts,Cf as attachIsViable,If as attachPreconditions,Nl as attachProvenanceToRelease,Ko as attachSbomToRelease,Dl as attachVulnerabilitySummary,Km as authEncryptionKeyFile,D as authorizeOrganization,ah as authorizeRuntimePath,dC as autocomplete,rE as awsConfigManager,fu as backupCredentialStatus,eE as backupManager,DS as batch,QE as batchProcessingManager,$o as beginOidcAuthorization,oE as blueGreenManager,xE as bounceComplaintHandler,mt as budgetWindow,Qa as buildAndPushServerlessImage,qE as buildBunRuntimeLayerZip,Rf as buildCertificatePackScript,vf as buildCertificateStateScript,Df as buildCertificateUnpackScript,Md as buildCloudFormationTemplate,Ec as buildCloudInitFirstBoot,jc as buildComposeLogsCommand,gI as buildComposeRuntimeCommand,mI as buildComposeScaleCommand,zc as buildComposeShellCommand,xp as buildDrainSourceScript,of as buildDrainedSiteScanScript,xd as buildFailoverReplicaPolicyStatement,rr as buildFunctionEnv,Op as buildHealthGateScript,Hn as buildHostCleanupDeployScript,ks as buildHostCleanupInstallScript,Qn as buildHostCleanupScript,gi as buildHostSitePortsScript,Dd as buildMailEnv,Ls as buildManagementDashboardArtifact,Qu as buildMediaCdnPlan,Ou as buildMtaStsPolicy,Mh as buildMtaStsServer,GE as buildNodeRuntimeLayerZip,bE as buildOptimizationManager,Cg as buildOriginGroup,qr as buildOriginGroups,tc as buildOriginGuardRule,Rp as buildPauseWorkersScript,KE as buildPhpRuntimeLayerZip,Tg as buildReplicationConfiguration,vg as buildReplicationRole,kp as buildRestoreScript,J as buildRpxConfig,Fe as buildRpxFragmentRefreshScript,Af as buildSetHostnameScript,qn as buildSiteDeployScript,Np as buildSnapshotScript,Lp as buildSourceStateScript,$n as buildSshArgs,Kn as buildSshBootstrapScript,ec as buildStaticSiteCacheRules,Vn as buildStaticSiteDeployScript,Bp as buildTargetStateScript,Dp as buildWorkersStateScript,Bl as bytes,aE as canaryManager,an as canonicalJson,Ct as capabilities,tr as capacity,$S as categorizeChanges,SE as certificateManager,wf as certificatesMatch,AS as checkIAMPermissions,oy as checkInvocation,IS as checkServiceQuotas,LA as chunk,Ap as cleanupDns01Challenge,CI as clearSigningKeyCache,Go as cloneSourceBinding,US as cloudConfigSchema,ap as cloudDrivers,nE as cloudTrailManager,Tc as collectAssets,Ro as collectPhpAppEntries,Bu as collectServerDnsDomains,Hp as completeComposeVolumeDeletion,Mo as completeOidcAuthorization,iS as composePresets,Hs as composeProjectName,qd as composeServerlessAppTemplate,iA as compositeSpendTransport,wt as compressBackup,fy as config,Za as configOrigins,Ql as connectionGuidance,vE as containerRegistryManager,Bf as controlPlaneDatabaseFile,Fc as controlPlaneMigrations,jI as createApiBackendPreset,jo as createApiV1Handler,Ty as createAsgBuildDriver,Au as createBackupQueueHandlers,uy as createCliHandler,_ as createCloudDriver,fc as createCloudFrontPolicy,pS as createCredentialProvider,rS as createDashboardSite,XI as createDataPipelinePreset,Hl as createDataServiceQueueHandlers,Kc as createDeploymentQueueHandlers,R as createDnsProvider,vy as createEcsBuildDriver,hd as createEnforcementHandlers,kg as createError,Fd as createExistingStaticFullStackPreset,Vl as createFleetQueueHandlers,VI as createFullStackAppPreset,Rs as createGoDaddyValidator,zE as createHandlers,dy as createHttpHandler,KI as createJamstackPreset,Ul as createJobQueueHandlers,eS as createLaravelPreset,YI as createMLApiPreset,Yl as createMaintenanceQueueHandlers,Ju as createMediaAccessToken,WI as createMicroservicesPreset,jS as createMockAWS,HI as createNodeJsServerPreset,GI as createNodeJsServerlessPreset,gs as createObjectStorageClient,ws as createPorkbunValidator,sS as createPreset,oA as createPresignedUrl,hI as createPresignedUrlAsync,ly as createQueueHandler,JI as createRealtimeAppPreset,zl as createRegionQueueHandlers,Pl as createReleaseProvenance,yl as createReleaseQueueHandlers,Ey as createRemoteBuildQueueHandlers,Ds as createRoute53Validator,oh as createRuntimeAdapters,gS as createS3Client,by as createServerBuildDriver,tS as createServerlessLaravelPreset,qI as createServerlessNodePreset,Nu as createSmsInfrastructure,Ze as createSourceAdapter,QI as createStaticSitePreset,ZI as createTraditionalWebAppPreset,Wc as createVolumeQueueHandlers,zI as createWordPressPreset,_i as createZip,AC as crossRegionReferenceManager,mn as dashboardActions,xs as dashboardCredentialsFile,sn as dataServiceCapabilities,AE as databaseUserManager,ol as decodeBase32,Oe as decompressBackup,wh as decryptBackup,_o as defaultConfig,Lg as defaultLocalConfig,tl as defaultRateLimitRules,pr as delegateZone,ys as delegateZoneFromConfig,pu as deleteFailoverReplicaBuckets,Fa as deleteStaticSite,kc as deployAllComputeSites,Ea as deployServerlessApp,gu as deploySite,$s as deploySiteRelease,os as deployStaticSite,Ua as deployStaticSiteFull,hn as deployStaticSiteWithExternalDns,fn as deployStaticSiteWithExternalDnsFull,wd as deploymentCoexistenceError,yA as deriveManagementDashboardPort,Is as describeDelegation,nl as describePosture,Cs as describeZoneSettings,ch as desiredJobProviderState,Xp as detectAnomalies,hg as detectDeploymentTargets,rc as detectDnsProvider,ld as detectLatestAnomaly,hS as detectMisconfigurations,ug as detectServiceRegion,qc as diffCompose,OS as diffTemplates,Ho as discoverGitRefs,Lo as discoverOidcProvider,_l as discoverRuntimeInventory,UE as dlqMonitoringManager,nc as dnsProviders,_E as dnssecManager,nh as dockerWorkloads,Xi as documentDigest,tE as drManager,Qe as driverStatePath,Ol as ecsWorkloads,Mt as effectiveCapabilities,LE as emailAnalyticsManager,ME as emailTemplateManager,Fi as encodeBase32,Th as encryptBackup,kl as ensureDefaultSecurityPolicies,du as ensureFailoverReplicaBuckets,ni as ensureFirewall,oi as ensureManagementDashboard,ii as ensureServer,ri as ensureSshKey,Y as escapeSecLang,id as evaluateBudget,Yn as evaluatePreflight,oo as evaluateTelemetryAlertRules,Fl as eventBridgeScheduleInput,cy as eventToRequest,Kf as ewma,Gc as exportCompose,Es as exportRoute53Zone,Pg as extendPreset,FE as fifoQueueManager,RS as findChangedFiles,qp as findMapping,Gp as findPriceEntry,MC as formatAccountStructure,Ef as formatAttachPlan,tC as formatBytes,Qr as formatCents,LI as formatDiff,cf as formatDrainedSiteRefusal,rC as formatDuration,uC as formatFlagSuggestions,mC as formatHistory,hC as formatHistoryStats,pf as formatInventory,iC as formatKeyValue,nC as formatList,mf as formatPlan,ei as formatPreflightFindings,eC as formatProgressBar,VA as formatRegion,PC as formatRegionList,Zm as formatScanResults,sC as formatSuggestion,YS as formatTable,$r as formatTimeToExhaustion,ZS as formatTree,bA as fromEC2Metadata,vA as fromECSMetadata,CA as fromEnvironment,EA as fromSharedCredentials,TA as fromWebIdentity,jd as functionFingerprint,xn as gatewayHostnames,Vd as generateAppImageDockerfile,YC as generateApprovalConfig,XA as generateBootstrap,WS as generateCleanupWorkflow,JS as generateCostReportWorkflow,LC as generateCrossAccountRoleCF,wl as generateCycloneDxSbom,WC as generateDeploymentConfig,qC as generateDeploymentPipeline,FC as generateDeploymentWorkflow,Ma as generateExternalDnsStaticSiteTemplate,gp as generateHttpsServerCode,Rl as generateImageSbom,fp as generateLetsEncryptUserData,t as generateLogicalId,KC as generateManualPipeline,GC as generateMatrixWorkflow,JC as generateMultiEnvConfig,VC as generateMultiEnvPipeline,UC as generateMultiEnvWorkflow,QC as generatePRPreviewWorkflow,ZC as generateParallelConfig,py as generatePhpFpmConfig,ry as generatePhpLayerDockerfile,jC as generatePreviewPipeline,KS as generatePreviewWorkflow,r as generateResourceName,XC as generateScheduledConfig,zC as generateScheduledPipeline,HC as generateScheduledWorkflow,ss as generateStaticSiteTemplate,B as generateUbuntuAppCloudInit,DA as getAccountId,CC as getAllRegions,wC as getClosestRegion,pC as getCommandUsage,_f as getComposeTemplate,Vm as getConfig,aC as getContextualHelp,Ao as getCredentials,MS as getDeploymentStrategy,FS as getDiffStats,xS as getDiffSummary,BA as getErrorDetails,Qd as getLocalConfig,qS as getLocalCredentials,GS as getLocalEndpoint,VS as getLocalEnvVars,SS as getQuotaUsageSummary,xC as getRecommendedStructure,Bi as getRegion,NC as getRegionStats,bC as getRegionsByCompliance,EC as getRegionsByLocation,vC as getRegionsByPricingTier,_A as getRequiredPermissions,EI as getSigningKeyCacheSize,Pu as getSmsInfrastructureStatus,DI as getTimestamp,Do as globMatches,Ms as globToRegex,yC as globalResourceManager,Ii as governingLimitCents,lu as grantFailoverReplicaAccess,iE as guardDutyManager,co as handleSpendRequest,On as hasAutoWwwVariant,Wt as hasManagementDashboardSite,Mc as hasProxyUpstream,bS as hashBuffer,vS as hashDirectory,Og as hashFile,TS as hashManifest,xg as hashString,XE as healthCheckManager,Nn as hostAcceptsIpv6,wn as hostCondition,Oo as hotp,Lr as hourBucket,zf as hourBucketsBetween,EE as imageScanningManager,es as infraEnvFromOutputs,Kd as inspectInvocation,iy as installRecursionFetch,cs as invalidateCache,Mm as invocationContext,oC as isLikelyTypo,Bn as isLocalDatabase,HS as isLocalDevelopment,Vr as isManagementDashboardSiteName,lr as isNameserverRegistrar,bI as isNodeCryptoAvailable,dd as isOperationAllowed,so as isQuietHours,_d as isS3RestEndpoint,ci as isSafePattern,vd as isStateDirConfigured,Td as isStatePath,Hr as isValidCidr,TC as isValidRegion,Ai as isValidTimeZone,vI as isWebCryptoAvailable,ur as isZoneHost,nn as jobProviderCapability,ps as keyMatchesFilters,DE as lambdaConcurrencyManager,kE as lambdaDLQManager,PE as lambdaDestinationsManager,wE as lambdaLayersManager,NE as lambdaVPCManager,RE as lambdaVersionsManager,xl as lambdaWorkloads,Xd as laravelServerlessEnvDefaults,Br as listComposeTemplates,qi as listSourceReferences,sl as loadCloudConfig,Gt as loadTelemetryPolicy,pE as logsManager,ud as lookbackHoursForSignal,cA as mailEnabled,Rd as mailFirewallPorts,mh as maintenanceWindowOpen,aA as makeAWSRequest,yI as makeAWSRequestAsync,fI as makeAWSRequestOnce,Dg as managementDashboardSiteName,Kl as manifestDigest,Jr as matchTotpCounter,Xu as mediaObjectHeaders,Zs as median,Wp as medianAbsoluteDeviation,sd as mergeDecisions,jr as mergeInfrastructure,Vf as mergePriceBooks,td as meterTelemetry,uE as metricsManager,Tu as migrateObjectStorage,mE as migrationManager,kC as multiAccountManager,fC as multiRegionManager,ef as needsRenewal,YE as networkSecurityManager,bt as nextScheduleRuns,Ce as normalizePublicIpv6,ke as normalizeRuntimeStatus,et as normalizeScheduleExpression,Xm as normalizeSourceEvent,Ue as normalizeSshPublicKey,rg as normalizeTelemetryPolicy,pi as occupiedHostPorts,Vo as openApiDocument,no as optionsForSignal,BC as organizationManager,Yd as packagePhpApp,Wr as packageServerlessApp,Rc as pagesAssetHash,Uu as pagesDnsRecord,Ud as parallel,PS as parallelMap,NS as parallelWithRetry,Tf as parseCertificateState,zd as parseChain,kr as parseCompose,uI as parseComposeCatalog,rh as parseDockerInspect,Su as parseDotenv,af as parseDrainedSites,mi as parseHostSiteFragments,SI as parseJSONResponse,Xn as parsePreflightFacts,$p as parseSourceDrained,ih as parseSystemdRecords,_p as parseTargetReady,$c as parseUpstreamPort,Pp as parseWorkersPaused,II as parseXMLResponse,Ti as pathTemplate,xc as pendingSteps,Ys as percentOfLimit,fE as performanceManager,Lm as phpLayerBuildStage,ty as phpLayerPackages,xi as phpRuntimeLayerAssets,pI as planComposeTemplateUpgrade,od as planEnforcement,Tp as planIsDestructive,lg as planMitigation,ff as planServerRename,Pf as planSiteMove,bs as planZoneMigration,kt as policyTag,Zn as preflightFailed,zS as previewManager,XS as previewNotifications,vt as previewSchedule,jf as previousBudgetWindow,Ws as priceUsage,Gf as priceUsageLines,lf as probeHostRoutes,_s as probeOriginTls,_S as processInChunks,bl as processSourceWebhook,zi as productionChangeReview,dE as progressiveDeploymentManager,nd as projectSpend,Wd as propagationHeaders,Ha as providerEndpoint,Wl as publicKeyFingerprint,Rn as qualifyName,HE as queueManagementManager,wS as quickHash,el as rateLimitHeaders,$i as rateLimitKey,He as readDriverState,uf as reconcile,_u as reconcileAddressRecords,Vu as reconcileCloudflareCdn,As as reconcileDeclaredRecords,Cy as reconcileJobObservation,Zr as reconcileSourceWebhook,ji as recordDashboardHostPosture,yy as recordPreDeploySecretScan,Iy as recordSkippedSecretScan,Jd as recursionBlockedResponse,Be as redactRuntimeConfig,yd as redactTelemetryText,vi as redactTelemetryValue,ln as redeployServerlessApp,IC as regionPairManager,Yr as releaseStrategyCapabilities,Wm as releaseTrafficPlan,ai as reloadRpxGateway,us as remapKey,Du as removeDns01ChallengeRecord,dn as removeSiteFromCloudConfig,vl as removeSourceWebhook,ic as removeStaleServerAddressRecords,Vc as renderComposeTemplate,Di as renderDdosInstallScript,Ed as renderNftablesRuleset,Ki as renderServerCron,Cd as renderSysctlFile,_c as renderWafConfig,di as renderWafInstallScript,Bc as renewRpxCertificates,hE as replicaManager,sA as requestHash,LS as requiresReplacement,VE as resetRecursionRuntime,jE as resolveApp,p as resolveAppDatabase,yf as resolveAttachTarget,Ye as resolveAuthEncryptionKey,ge as resolveCloudProvider,Hu as resolveCloudflareCdnPlan,wA as resolveCredentials,is as resolveDashboardAction,Nc as resolveDashboardAuth,IA as resolveDashboardDomain,SA as resolveDashboardDomains,fs as resolveDeclaredRecords,OI as resolveDeployBucketName,M as resolveDeploymentMode,Gn as resolveExecStart,Bd as resolveFailoverStatusCodes,hc as resolveHetznerApiToken,Cr as resolveHostCleanupConfig,Pi as resolveMailService,nS as resolveManagementDashboardSite,ki as resolveManagementDashboardSites,Ga as resolveObjectStorage,De as resolveOriginConnection,gf as resolvePlan,g as resolveProjectStackName,Nr as resolveProxyUpstreams,Gd as resolveQueueNames,xf as resolveQueuedDeploymentCommand,Xt as resolveQueues,ny as resolveRecursionConfig,RA as resolveRegion,ie as resolveRuntimeInventory,qt as resolveServerlessAppStackName,Nd as resolveServerlessArtifactBucketName,po as resolveServerlessAssetBucketName,Co as resolveServerlessRuntime,BI as resolveSiteBucketName,Fs as resolveSiteDeployTarget,u as resolveSiteKind,kI as resolveSiteResourceName,NI as resolveSiteStackName,Wn as resolveSshSettings,d as resolveStatePath,_I as resolveStorageBucketName,Eg as resolveStorageFailover,Lt as resolveUiSource,Ac as resolveZoneApex,ZE as resourceManagementManager,Fm as responseToResult,Jp as robustZScore,$t as roleCapabilities,Al as rollbackImmutableRelease,un as rollbackServerlessApp,qf as roundCents,OE as route53ResolverManager,BE as route53RoutingManager,Zp as routeMatches,Ep as routesFromFragments,Li as ruleMatches,YA as runBuildHooks,ad as runEnforcement,wo as runPhpBuildHooks,tt as runRemoteCommand,he as runtimeId,Le as s3OriginBucket,bg as s3RegionalDomain,Dn as sameNameservers,ns as sanitizeCloudConfig,s as sanitizeControlPlaneValue,PI as sanitizeName,ul as sanitizeOidcReturnPath,fd as saveTelemetryPolicy,Ym as scanForSecrets,Uc as scopeContains,ht as scopeKey,dc as scpUpload,cC as searchCommands,Qs as searchControlPlane,IE as secretsManager,yE as secretsRotationManager,Sy as secureContainerRelease,sE as securityHubManager,CE as securityScanningManager,ne as securityScope,uu as seedFailoverReplicas,Xr as sendAuthenticationEmail,$E as senderReputationManager,kS as sequence,Cu as serializeDotenv,si as serverPublicIpv4,TE as serviceMeshManager,su as setAttachToInCloudConfig,nr as setMaintenance,Yi as setSitePropertyInCloudConfig,bd as setStateDir,hp as setupDns01Challenge,Xa as setupSmsInfrastructure,So as sha256,sy as sharedRecursionGuard,$m as sharedRuntimeLoop,Up as shipsARelease,qu as signCloudFrontCookies,Zu as signCloudFrontUrl,x as signRequest,pg as signRequestAsync,to as signalDefinition,O as siteInstallBase,ui as siteMoveArchivePath,bf as siteMoveCertArchivePath,Lc as siteUnitGlob,ig as spendNotificationText,lo as spendOpenApiPaths,Ir as sshExec,ue as sshExecOrThrow,SC as stackDependencyManager,$a as startLocalDashboardServer,nA as startSpendLoop,uo as stateDir,L as statePath,WE as staticSiteManager,JE as storageAdvancedManager,MI as storageFailoverReplicasFromTemplate,Wf as streamFocusJsonl,cd as strongestActiveAction,Hg as suggestCommand,lC as suggestFlags,yS as suggestIAMPolicy,CS as suggestQuotaIncrease,DC as suggestRegionPairs,RC as suggestRegions,Gi as syncSourceRepositories,Jc as synchronizeComposeVolumes,Eu as synchronizeConfiguredConfiguration,Zo as synchronizeConfiguredJobs,gE as syntheticsManager,Sd as sysctlHardening,sh as systemdWorkloads,eA as telemetryBucketLabel,wi as telemetryCursor,Ad as telemetryEstimatedMonthlyCost,Zf as telemetryPercentile,ng as telemetryPolicyKey,ES as templateCache,bp as tenantsOf,qo as testSourceConnection,Xc as tieredMicroCents,Bs as toCloudflareZoneSettings,io as toFocusJsonl,pd as toFocusRecords,df as toInventoryServer,jm as totp,xo as totpUri,vp as unaccountedSites,th as unsupportedCapabilities,Lf as unsupportedVolumeCapabilities,Xl as updateCompatibility,Zl as updateSiteInCloudConfig,as as uploadStaticFiles,Vp as usageDeltaKey,Qt as utcInstantOfLocal,$C as validateAccountStructure,QS as validateAgainstSchema,Mf as validateAttachment,vh as validateBackupDestination,gC as validateCommand,mS as validateConfiguration,fS as validateCredentials,Fp as validateDeploymentConfig,$f as validateMountPath,jt as validateOriginGroups,au as validateResourceLimits,wp as validateServerName,eu as validateTemplate,ou as validateTemplateSize,oc as verifyAddressRecord,Ay as verifyArtifactSignature,Yu as verifyMediaAccessToken,zm as verifyTotp,Jl as verifyUpdateSignature,Ts as verifyZoneParity,Vs as volumeCapabilities,yp as wafEventTelemetry,lc as waitForCloudInit,Mn as waitForSsh,Zt as webhookEndpoint,lS as withCDN,dS as withCache,cS as withDatabase,ay as withInvocation,oS as withMonitoring,uS as withQueue,aS as withSecurity,BS as withTimeout,X as wrapCloudInitUserData,ct as writeDriverState,lE as xrayManager,jl as zeroCapacity,Jf as zeroFill,Zc as zoneOffsetMs,Js as zonedParts};
@@ -1 +1 @@
1
- import{sf,of,af,yp,Ip,Sp,cf,Cp,Ep,df,lf,bp,uf,pf,xc,vp,gf,mf,Tp,hf,ff,Af,yf,If,Sf,Cf,ui,Lc,wp,Rp,Dp,Pp,Np,kp,Bp,_p,Op,xp,Lp,Ef,bf,vf,Tf,wf,Rf,Df}from"../chunk-4jgy95bv.js";import"../chunk-2mw7bjhn.js";import"../chunk-kavwrxm8.js";import"../chunk-r45340yc.js";export{Ip as ENVIRONMENT_LABEL,yp as PROJECT_LABEL,Sp as ROLE_LABEL,mf as applyPlan,If as attachConflicts,Sf as attachIsViable,yf as attachPreconditions,wf as buildCertificatePackScript,bf as buildCertificateStateScript,Rf as buildCertificateUnpackScript,Op as buildDrainSourceScript,sf as buildDrainedSiteScanScript,_p as buildHealthGateScript,wp as buildPauseWorkersScript,Np as buildRestoreScript,ff as buildSetHostnameScript,Pp as buildSnapshotScript,xp as buildSourceStateScript,kp as buildTargetStateScript,Rp as buildWorkersStateScript,Tf as certificatesMatch,Cf as formatAttachPlan,af as formatDrainedSiteRefusal,uf as formatInventory,gf as formatPlan,vf as parseCertificateState,of as parseDrainedSites,Lp as parseSourceDrained,Bp as parseTargetReady,Dp as parseWorkersPaused,xc as pendingSteps,vp as planIsDestructive,hf as planServerRename,Df as planSiteMove,df as probeHostRoutes,lf as reconcile,Af as resolveAttachTarget,pf as resolvePlan,Cp as routesFromFragments,ui as siteMoveArchivePath,Ef as siteMoveCertArchivePath,Lc as siteUnitGlob,Ep as tenantsOf,cf as toInventoryServer,bp as unaccountedSites,Tp as validateServerName};
1
+ import{of,af,cf,Ip,Sp,Cp,df,Ep,bp,lf,uf,vp,pf,gf,xc,Tp,mf,hf,wp,ff,Af,yf,If,Sf,Cf,Ef,ui,Lc,Rp,Dp,Pp,Np,kp,Bp,_p,Op,xp,Lp,$p,bf,vf,Tf,wf,Rf,Df,Pf}from"../chunk-y3h0ybmn.js";import"../chunk-nmm287ym.js";import"../chunk-6n72pe9x.js";import"../chunk-0pe1dfy0.js";export{Sp as ENVIRONMENT_LABEL,Ip as PROJECT_LABEL,Cp as ROLE_LABEL,hf as applyPlan,Sf as attachConflicts,Cf as attachIsViable,If as attachPreconditions,Rf as buildCertificatePackScript,vf as buildCertificateStateScript,Df as buildCertificateUnpackScript,xp as buildDrainSourceScript,of as buildDrainedSiteScanScript,Op as buildHealthGateScript,Rp as buildPauseWorkersScript,kp as buildRestoreScript,Af as buildSetHostnameScript,Np as buildSnapshotScript,Lp as buildSourceStateScript,Bp as buildTargetStateScript,Dp as buildWorkersStateScript,wf as certificatesMatch,Ef as formatAttachPlan,cf as formatDrainedSiteRefusal,pf as formatInventory,mf as formatPlan,Tf as parseCertificateState,af as parseDrainedSites,$p as parseSourceDrained,_p as parseTargetReady,Pp as parseWorkersPaused,xc as pendingSteps,Tp as planIsDestructive,ff as planServerRename,Pf as planSiteMove,lf as probeHostRoutes,uf as reconcile,yf as resolveAttachTarget,gf as resolvePlan,Ep as routesFromFragments,ui as siteMoveArchivePath,bf as siteMoveCertArchivePath,Lc as siteUnitGlob,bp as tenantsOf,df as toInventoryServer,vp as unaccountedSites,wp as validateServerName};
@@ -1 +1 @@
1
- import{Zd,Do,Li,$i,Po,el,tl,rl,Mi,No,ko,nl,il,Bo,my}from"../chunk-89rs2afj.js";import{Y,ci,Ms,_c,di,Ap}from"../chunk-zesd879q.js";import{Id,Hr,Sd,Cd,Ed,Di,dg,Gr}from"../chunk-10asqy6j.js";import{Eo,bo,vo,jd,Oi,zd,Kd,To,Wd,Jd}from"../chunk-r45340yc.js";export{bo as CHAIN_HEADER,No as DEFAULT_ATTACK_MODE_HOURS,Id as DEFAULT_DDOS_THRESHOLDS,Oi as DEFAULT_RECURSION_LIMITS,Eo as DEPTH_HEADER,Mi as MAX_CONTROL_HOURS,rl as PROTECTION_SETTING,ko as ProtectionControlStore,Zd as RATE_LIMIT_KEY_SEPARATOR,Po as RateLimiter,To as RecursionGuard,vo as TRACE_HEADER,Bo as applyControlsToDdos,il as applyControlsToRateLimits,Gr as applyMitigationFactor,tl as defaultRateLimitRules,nl as describePosture,Y as escapeSecLang,jd as functionFingerprint,Do as globMatches,Ms as globToRegex,Kd as inspectInvocation,ci as isSafePattern,Hr as isValidCidr,my as mergeControlsIntoConfig,zd as parseChain,dg as planMitigation,Wd as propagationHeaders,el as rateLimitHeaders,$i as rateLimitKey,Jd as recursionBlockedResponse,Di as renderDdosInstallScript,Ed as renderNftablesRuleset,Cd as renderSysctlFile,_c as renderWafConfig,di as renderWafInstallScript,Li as ruleMatches,Sd as sysctlHardening,Ap as wafEventTelemetry};
1
+ import{Zd,Do,Li,$i,Po,el,tl,rl,Mi,No,ko,nl,il,Bo,hy}from"../chunk-tzvtq055.js";import{Y,ci,Ms,_c,di,yp}from"../chunk-v9t4751b.js";import{Id,Hr,Sd,Cd,Ed,Di,lg,Gr}from"../chunk-e08h4q50.js";import{Eo,bo,vo,jd,Oi,zd,Kd,To,Wd,Jd}from"../chunk-0pe1dfy0.js";export{bo as CHAIN_HEADER,No as DEFAULT_ATTACK_MODE_HOURS,Id as DEFAULT_DDOS_THRESHOLDS,Oi as DEFAULT_RECURSION_LIMITS,Eo as DEPTH_HEADER,Mi as MAX_CONTROL_HOURS,rl as PROTECTION_SETTING,ko as ProtectionControlStore,Zd as RATE_LIMIT_KEY_SEPARATOR,Po as RateLimiter,To as RecursionGuard,vo as TRACE_HEADER,Bo as applyControlsToDdos,il as applyControlsToRateLimits,Gr as applyMitigationFactor,tl as defaultRateLimitRules,nl as describePosture,Y as escapeSecLang,jd as functionFingerprint,Do as globMatches,Ms as globToRegex,Kd as inspectInvocation,ci as isSafePattern,Hr as isValidCidr,hy as mergeControlsIntoConfig,zd as parseChain,lg as planMitigation,Wd as propagationHeaders,el as rateLimitHeaders,$i as rateLimitKey,Jd as recursionBlockedResponse,Di as renderDdosInstallScript,Ed as renderNftablesRuleset,Cd as renderSysctlFile,_c as renderWafConfig,di as renderWafInstallScript,Li as ruleMatches,Sd as sysctlHardening,yp as wafEventTelemetry};