@stacksjs/ts-cloud 0.16.21 → 0.16.23

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 (198) hide show
  1. package/dist/aws/elasticache.d.ts +11 -9
  2. package/dist/aws/index.js +1 -1
  3. package/dist/aws/xml-result.d.ts +20 -0
  4. package/dist/bin/{chunk-k7wh1wr5.js → chunk-0d98bem8.js} +2 -2
  5. package/dist/bin/chunk-0r45d0s3.js +2 -0
  6. package/dist/{chunk-g6g33pt9.js → bin/chunk-21zhm1mk.js} +7 -7
  7. package/dist/bin/chunk-2g1j00yc.js +1 -0
  8. package/dist/bin/{chunk-6kx50dyc.js → chunk-2tk8egg8.js} +1 -1
  9. package/dist/bin/{chunk-90102shh.js → chunk-33e0t7e5.js} +2 -2
  10. package/dist/bin/{chunk-ngyqqy6d.js → chunk-34kwhmbt.js} +5 -5
  11. package/dist/bin/chunk-4xmhrvfa.js +1 -0
  12. package/dist/bin/{chunk-gfr2215x.js → chunk-65rndjtr.js} +63 -63
  13. package/dist/bin/{chunk-t10e32an.js → chunk-6cfpdb35.js} +7 -7
  14. package/dist/bin/chunk-6crapvp1.js +1 -0
  15. package/dist/bin/chunk-7b4gf64x.js +1 -0
  16. package/dist/bin/chunk-818tj49e.js +1 -0
  17. package/dist/bin/{chunk-9vmtm7nq.js → chunk-8vm7tpyv.js} +2 -2
  18. package/dist/bin/{chunk-e24bscb0.js → chunk-90kpnjdm.js} +16 -16
  19. package/dist/bin/chunk-92qsww97.js +1 -0
  20. package/dist/bin/chunk-9947rscj.js +1 -0
  21. package/dist/bin/{chunk-2mv692y4.js → chunk-9h7yjtz2.js} +5 -5
  22. package/dist/bin/{chunk-tq172j2x.js → chunk-btr6zq53.js} +3 -3
  23. package/dist/bin/chunk-cas0bp91.js +2 -0
  24. package/dist/bin/{chunk-6wqjk007.js → chunk-cpwk0pbg.js} +134 -134
  25. package/dist/bin/chunk-cyap08qg.js +1 -0
  26. package/dist/bin/chunk-dk92s260.js +1 -0
  27. package/dist/bin/chunk-ejxp74ks.js +1 -0
  28. package/dist/bin/{chunk-dyh0vndw.js → chunk-en7sf83z.js} +4 -4
  29. package/dist/bin/{chunk-djjj62c0.js → chunk-f2yhthd1.js} +2 -2
  30. package/dist/bin/{chunk-z1dtdw3j.js → chunk-f3sd1hpa.js} +5 -5
  31. package/dist/bin/chunk-gfwkmttt.js +1 -0
  32. package/dist/bin/chunk-gx98tkpf.js +1 -0
  33. package/dist/bin/{chunk-apnhhfkj.js → chunk-gzpwf3n4.js} +2 -2
  34. package/dist/bin/{chunk-dmdg23a5.js → chunk-h90azajz.js} +2 -2
  35. package/dist/bin/chunk-hcdbw9j1.js +1 -0
  36. package/dist/bin/chunk-hdsgfgnz.js +34 -0
  37. package/dist/bin/{chunk-1j8b1d58.js → chunk-hqmkfh4a.js} +2 -2
  38. package/dist/bin/{chunk-x63yz8xg.js → chunk-ht318ydv.js} +1 -1
  39. package/dist/bin/{chunk-h1rb8qvt.js → chunk-ht6tpmqw.js} +2 -2
  40. package/dist/bin/{chunk-e55fdn0r.js → chunk-j0zg3mbm.js} +3 -3
  41. package/dist/bin/{chunk-0f1qpmd6.js → chunk-jbpkwxht.js} +5 -5
  42. package/dist/bin/{chunk-5a7sxtwn.js → chunk-jtnv8nwz.js} +2 -2
  43. package/dist/bin/{chunk-ys5n5c84.js → chunk-k052rtd5.js} +5 -5
  44. package/dist/bin/{chunk-148x1zq8.js → chunk-k1eezsj1.js} +2 -2
  45. package/dist/bin/chunk-kay11qc7.js +1 -0
  46. package/dist/bin/chunk-n28a9a9c.js +1 -0
  47. package/dist/bin/chunk-n298azax.js +2 -0
  48. package/dist/bin/chunk-q8w7fa56.js +1 -0
  49. package/dist/bin/chunk-qdnx952p.js +1 -0
  50. package/dist/bin/chunk-t1jpqn4x.js +6 -0
  51. package/dist/bin/chunk-tr0pkm4p.js +1 -0
  52. package/dist/bin/{chunk-mxvekmdx.js → chunk-tyqxz92e.js} +114 -114
  53. package/dist/bin/chunk-tytvrehe.js +1 -0
  54. package/dist/bin/{chunk-3n733cgx.js → chunk-v002yxaf.js} +2 -2
  55. package/dist/bin/chunk-wpp0fa94.js +1 -0
  56. package/dist/bin/{chunk-0trtkv9g.js → chunk-wyanqf91.js} +7 -7
  57. package/dist/bin/{chunk-rbtt23vx.js → chunk-xs6afjat.js} +3 -3
  58. package/dist/bin/chunk-xzgxwnb7.js +1 -0
  59. package/dist/bin/chunk-y21yk6zv.js +1 -0
  60. package/dist/bin/chunk-yt1t5ct8.js +1 -0
  61. package/dist/bin/chunk-yxyvhqhr.js +2 -0
  62. package/dist/bin/{chunk-290bzm2m.js → chunk-zcabmq4p.js} +3 -3
  63. package/dist/bin/chunk-zs8ddeaz.js +1 -0
  64. package/dist/bin/cli.js +355 -355
  65. package/dist/bin/dashboard-server.js +1 -1
  66. package/dist/{chunk-k53agv2m.js → chunk-01rbgche.js} +2 -2
  67. package/dist/{chunk-3m9ghthh.js → chunk-14zcywnp.js} +2 -2
  68. package/dist/chunk-2hy7ny4k.js +5 -0
  69. package/dist/{chunk-aw1tp3p3.js → chunk-4apkvhsc.js} +88 -88
  70. package/dist/chunk-4rb7stp5.js +92 -0
  71. package/dist/chunk-5vxpgw8q.js +6 -0
  72. package/dist/{chunk-bxrzsth8.js → chunk-60fn008g.js} +2 -2
  73. package/dist/{chunk-z3wynefj.js → chunk-92gn9ght.js} +19 -19
  74. package/dist/{chunk-hyeeqga9.js → chunk-b5xjjz3y.js} +6 -6
  75. package/dist/{chunk-e52me1c6.js → chunk-bz1hp7es.js} +1 -1
  76. package/dist/{chunk-kczzc599.js → chunk-c836kdrx.js} +38 -38
  77. package/dist/{chunk-srrscggm.js → chunk-ckwdjb5q.js} +5 -5
  78. package/dist/chunk-cpyrhh52.js +709 -0
  79. package/dist/chunk-cwgy9pvc.js +34 -0
  80. package/dist/{chunk-v2p7c7s4.js → chunk-ds2v2xpb.js} +134 -134
  81. package/dist/chunk-e4qh4c2n.js +1 -0
  82. package/dist/{chunk-vs0qrm09.js → chunk-g6aev693.js} +1 -1
  83. package/dist/chunk-gm0qysea.js +114 -0
  84. package/dist/chunk-hpq0rrve.js +2 -0
  85. package/dist/{chunk-5far81q7.js → chunk-j2w0cvnr.js} +2 -2
  86. package/dist/{chunk-31tvc877.js → chunk-nfkdgsgh.js} +18 -18
  87. package/dist/{chunk-qcaqc5b8.js → chunk-pdmfmsm9.js} +3 -3
  88. package/dist/chunk-pj9z4fjv.js +1 -0
  89. package/dist/{chunk-w9jhyy09.js → chunk-rq0wrpz6.js} +4 -4
  90. package/dist/{chunk-9wmer0zx.js → chunk-t7q4awss.js} +2 -2
  91. package/dist/chunk-twhbns31.js +1 -0
  92. package/dist/chunk-wkg22nj5.js +1 -0
  93. package/dist/{bin/chunk-8jbkphmg.js → chunk-xassxhvq.js} +7 -7
  94. package/dist/{chunk-e8e1h2h9.js → chunk-xkqx98bx.js} +2 -2
  95. package/dist/chunk-xtd0s5ep.js +1 -0
  96. package/dist/deploy/index.js +1 -1
  97. package/dist/dns/index.js +1 -1
  98. package/dist/drivers/index.js +1 -1
  99. package/dist/index.js +86 -86
  100. package/dist/operations/index.js +1 -1
  101. package/dist/protection/index.js +1 -1
  102. package/dist/spend/index.js +1 -1
  103. package/dist/ui/404.html +1 -1
  104. package/dist/ui/accept-invitation.html +1 -1
  105. package/dist/ui/access-denied.html +1 -1
  106. package/dist/ui/account/automation.html +5 -5
  107. package/dist/ui/account/security.html +2 -2
  108. package/dist/ui/applications/compose.html +6 -6
  109. package/dist/ui/applications/new.html +2 -2
  110. package/dist/ui/data/backups.html +5 -5
  111. package/dist/ui/data/services.html +6 -6
  112. package/dist/ui/data/volumes.html +6 -6
  113. package/dist/ui/index.html +6 -6
  114. package/dist/ui/infrastructure/topology.html +6 -6
  115. package/dist/ui/integrations.html +2 -2
  116. package/dist/ui/operations/alerts.html +6 -6
  117. package/dist/ui/operations/configuration.html +6 -6
  118. package/dist/ui/operations/jobs.html +6 -6
  119. package/dist/ui/operations/maintenance.html +5 -5
  120. package/dist/ui/operations/observability.html +6 -6
  121. package/dist/ui/operations/previews.html +6 -6
  122. package/dist/ui/operations/queue.html +6 -6
  123. package/dist/ui/operations/regions.html +5 -5
  124. package/dist/ui/operations/releases.html +6 -6
  125. package/dist/ui/operations/spend.html +6 -6
  126. package/dist/ui/operations/workloads.html +6 -6
  127. package/dist/ui/security.html +2 -2
  128. package/dist/ui/server/actions.html +6 -6
  129. package/dist/ui/server/activity.html +2 -2
  130. package/dist/ui/server/capacity.html +6 -6
  131. package/dist/ui/server/database.html +6 -6
  132. package/dist/ui/server/deployments.html +6 -6
  133. package/dist/ui/server/diagnostics.html +2 -2
  134. package/dist/ui/server/firewall.html +6 -6
  135. package/dist/ui/server/fleet.html +6 -6
  136. package/dist/ui/server/logs.html +6 -6
  137. package/dist/ui/server/metrics.html +6 -6
  138. package/dist/ui/server/security.html +2 -2
  139. package/dist/ui/server/services.html +2 -2
  140. package/dist/ui/server/sites.html +6 -6
  141. package/dist/ui/server/ssh-keys.html +5 -5
  142. package/dist/ui/server/team.html +6 -6
  143. package/dist/ui/server/terminal.html +2 -2
  144. package/dist/ui/serverless/alarms.html +6 -6
  145. package/dist/ui/serverless/assets.html +2 -2
  146. package/dist/ui/serverless/cost.html +2 -2
  147. package/dist/ui/serverless/data.html +6 -6
  148. package/dist/ui/serverless/deployments.html +2 -2
  149. package/dist/ui/serverless/firewall.html +1 -1
  150. package/dist/ui/serverless/functions.html +6 -6
  151. package/dist/ui/serverless/logs.html +6 -6
  152. package/dist/ui/serverless/metrics.html +2 -2
  153. package/dist/ui/serverless/queues.html +6 -6
  154. package/dist/ui/serverless/secrets.html +6 -6
  155. package/dist/ui/serverless/traces.html +6 -6
  156. package/dist/ui/serverless.html +6 -6
  157. package/package.json +3 -3
  158. package/dist/bin/chunk-0h6cggyt.js +0 -1
  159. package/dist/bin/chunk-2g2zrtjs.js +0 -2
  160. package/dist/bin/chunk-35rkh66r.js +0 -1
  161. package/dist/bin/chunk-4cs098d1.js +0 -1
  162. package/dist/bin/chunk-52fhq35h.js +0 -1
  163. package/dist/bin/chunk-6se7ygxa.js +0 -1
  164. package/dist/bin/chunk-72g1hr4z.js +0 -1
  165. package/dist/bin/chunk-840arz58.js +0 -34
  166. package/dist/bin/chunk-c7vxdwth.js +0 -1
  167. package/dist/bin/chunk-e0c3agf2.js +0 -1
  168. package/dist/bin/chunk-egn33pr9.js +0 -2
  169. package/dist/bin/chunk-gf7yavs5.js +0 -1
  170. package/dist/bin/chunk-gp5w7e4c.js +0 -1
  171. package/dist/bin/chunk-gt7g41js.js +0 -1
  172. package/dist/bin/chunk-hagakkgm.js +0 -1
  173. package/dist/bin/chunk-hr3vbg6y.js +0 -1
  174. package/dist/bin/chunk-hyb5v8wr.js +0 -1
  175. package/dist/bin/chunk-mx9ppkmn.js +0 -6
  176. package/dist/bin/chunk-nqb1faqj.js +0 -1
  177. package/dist/bin/chunk-p831sptd.js +0 -1
  178. package/dist/bin/chunk-qxx1a51w.js +0 -1
  179. package/dist/bin/chunk-sh248v2y.js +0 -1
  180. package/dist/bin/chunk-swfmx4f8.js +0 -1
  181. package/dist/bin/chunk-vjkyj3xy.js +0 -2
  182. package/dist/bin/chunk-w78chy9x.js +0 -1
  183. package/dist/bin/chunk-w8k1gyzr.js +0 -1
  184. package/dist/bin/chunk-wagzxm7z.js +0 -1
  185. package/dist/bin/chunk-xdxk6baf.js +0 -1
  186. package/dist/bin/chunk-ysv52qcc.js +0 -1
  187. package/dist/chunk-07rjctzz.js +0 -1
  188. package/dist/chunk-3rahpgb9.js +0 -709
  189. package/dist/chunk-49vvjfrd.js +0 -1
  190. package/dist/chunk-6kcmbymp.js +0 -1
  191. package/dist/chunk-7xnwa0s8.js +0 -5
  192. package/dist/chunk-89p8mshq.js +0 -114
  193. package/dist/chunk-9asn5fpt.js +0 -92
  194. package/dist/chunk-d46p0h6t.js +0 -34
  195. package/dist/chunk-dak9hfrd.js +0 -1
  196. package/dist/chunk-ptq9v346.js +0 -2
  197. package/dist/chunk-z4xzd43p.js +0 -1
  198. package/dist/chunk-zx8ecz8b.js +0 -6
package/dist/index.js CHANGED
@@ -1,17 +1,17 @@
1
- import{rg,_,ng,Xf,oI,Yf,aI,cI,dI,lI,uI,pI,gI,mI,hI,fI,ig,sg,hd,fd,io,O,d,Ad,og,x,yd,p,Zf,bi,Id,Sd,le,Cd,yI,r,t,II,SI,g,CI,EI,bI,vI,TI,Ut,Ed,so,eA,wI,RI,ve,Ge,bd,ag,cg,DI,dg,lg,ug,vd,pg,Te,Fr,Qt,Td,Ht,ue,tA,wd,oo,gg,mg,hg,fg,Rd,PI,L,I,a,f,qe,m,rA,Ve,M,pt,NI,nA,F,Dd,we,Gt,ao,Y,Pd,Z,iA,co,U,Q,D,vi,b,qt,gt,H,e,lo,kI,Ag,Nd,BI,_I,OI,xI,kd,LI,$I,MI,FI,UI,QI,HI,GI,qI,VI,jI,zI,sA,oA,aA,cA,dA,lA,uA,Vt,yg,Ig,Ur,Ti,KI,Sg,WI,JI,Qr,XI,YI,ZI,eS,tS,rS,pA,gA,mA,hA,fA,uo,nS,AA,yA,IA,G,iS,je,po,jt,SA,Cg,CA,EA,bA,Eg,ee,sS,oS,aS,cS,vA,dS,q,lS,uS,pS,bg,vg,gS,Tg,wg,mS,hS,fS,AS,yS,TA,Bd,IS,SS,CS,ES,bS,wA,RA,vS,TS,wS,RS,DS,PS,NS,kS,BS,Rg,_d,_S,OS,xS,LS,Dg,Pg,Ng,$S,kg,MS,FS,US,QS,Bg,HS,GS,qS,VS,jS,zS,KS,WS,DA,PA,NA,kA,_g,JS,XS,YS,ZS,eC,tC,rC,nC,iC,BA,_A,OA,xA,sC,oC,Og,aC,xg,Lg,$g,Mg,cC,dC,lC,uC,Re,wi,pC,gC,mC,hC,fC,AC,yC,IC,LA,SC,CC,Fg,Ug,EC,bC,$A,vC,TC,wC,RC,DC,PC,NC,kC,BC,_C,OC,xC,LC,$C,MC,FC,UC,QC,HC,GC,qC,Qg,VC,Hg,jC,Gg,zC,qg,KC,Vg,WC,Hr,JC,jg,XC,go,YC,zg,ZC,Kg,eE,Wg,tE,Jg,rE,Xg,nE,Gr,iE,Yg,sE,Zg,oE,em,aE,tm,cE,rm,dE,nm,lE,im,uE,sm,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,MA,FA,UA,QA,bm,NE,vm,kE,Tm,BE,wm,_E,Ri,HA,GA,mo,Od,qr,qA,ho,zt,xd,Ld,VA,jA,Rm,zA,$d,Dm,OE,xE,fo,Ao,yo,Md,Di,Fd,Ud,Io,Qd,Hd,Pm,KA,WA,JA,LE,XA,YA,$E,ZA,Nm,ey,ty,ry,ME,ny,Pi,Gd,iy,FE,sy,So,Co,qd,km,UE,Bm,QE,_m,HE,Om,GE,xm,qE}from"./chunk-v2p7c7s4.js";import{Ro,Lm,Xd,ay,_i,Yd,Do,$m,Mm,Vr,Po,Zd,ze,el,tl,rl,Oi,jr,Fm,Ke,nl,No,ko,Bo,il,sl,ol,xi,_o,al,zr,Li,Oo,mt,Um,cl,dl,Qm,ll,xo,Kt,ul,pl,gl,ml,We,Hm,hl,Wt,Lo,$o,Mo,$i,Mi,Kr,fl,Fi,Fo,Uo,Wr,Al,Jr,Gm,qm,ht,Xr,Qo,Vm,yl,Il,Ho,Sl,Cl,El,cy,te,bl,dy,ly,Ui,Qi,uy,pe,jm,ft,De,Pe,At,vl,Tl,wl,Rl,zm,Km,Go,Wm,Jm,qo,Dl,Pl,Xm,re,Ym,Nl,ge,Vo,Je,yt,It,Yr,Hi,kl,py,jo,Zm,eh,th,rh,zo,Ko,Bl,Zr,Wo,_l,Gi,Ol,Jo,Xo,Yo,Zo,ea,ta,ra,na,xl,Jt,ia,Ll,en,$l,sa,oa,Ml,Xt,aa,ca,nh,gy,qi,my,hy,fy,da,la,Fl,ih,ua,tn,Ul,Vi,Ql,Hl,Gl,pa,sh,ga,ql,oh,ma,ah,rn,nn,Vl,ji,Xl,tu,ru,nu,iu,su,Ki,Yt,fa,sn,on,Zt,Xe,hh,ya,fh,Ah,cu,Ia,Ji,du,Sa,Ct,ke,lu,Ca,Ea,uu,ba,va,Ta,wa,pu,gu,cn,Ra,Da,Pa,Na,mu,Xi,dn,Yi,ka}from"./chunk-3rahpgb9.js";import{B,Tr,Nc,_s,u,Np,kp}from"./chunk-3m9ghthh.js";import{at,Pc,oi,ai,ci,Pp}from"./chunk-w9jhyy09.js";import{Jh,Xh,Yh,lp,up,pp,Zh,gp,mp,ef,tf,hp,rf,nf,Rc,fp,sf,of,Ap,af,cf,df,lf,uf,pf,gf,si,Dc,yp,Ip,Sp,Cp,Ep,bp,vp,Tp,wp,Rp,Dp,mf,hf,ff,Af,yf,If,Sf}from"./chunk-z3wynefj.js";import{Ue,kc,de,_t,Bc,w,Ot,ct,_c,Os,bf,Bp,Oc,s,di,xs,wr,xc,Lc,Rr,vf,$c,rI,nI,Ls,iI,sI,Mc,Fc,li,$s,X,c,Ms,Qe,Dr,Tf,wf,Uc,xt,Rf,Fs,Df,Pf,Us,Qc,Pr,Qs,Nf,Hc,_p,Lt,Nr,kf,Hs,Bf,R,_f,Gc,Op,Gs,Of,xf,Lf,qc,ui,qs,Vc,$t,dt,$f,kr,Mf,jc,xp,Lp,Vs,zc,Kc,lt,$p,pi,Wc,js,Br,Mp,gi,Jc,Xc,mi,Fp,Yc,Zc,ed,td,zs,Up,Qp,Ff,Hp,rd,hi,Gp,qp,Ks,_r,Ws,Js,Xs,nd,Vp,id,Ys,Uf,Mt,Qf,sd,Or,od,Hf,ad,jp,fi,xr,Zs,Ai,He,Gf,zp,Kp,Ft,cd,dd,ld,yi,Ii,Si,qf,Vf,ut,eo,jf,Lr,Wp,to,zf,Jp,Xp,Yp,Kf,Zp,eg,Wf,i,Jf,Ci,ro,no}from"./chunk-kczzc599.js";import{n}from"./chunk-zx8ecz8b.js";import{o}from"./chunk-9asn5fpt.js";import{me,ss,os,Au,La,$a,as,Ma,Ye,V,Ze,ne,C,he,gn,Fa,Be,Ua,mn,hn,fn,Et,bt,vt,An,tr,Qa,rr,nr,et,yn,Ga,Tt,ir,In,Va,Cu,Eu,ja,sr}from"./chunk-89p8mshq.js";import{rt,se,Oe,bu,Cn,za,Ka,ds,Ae,wt,En,ls,us,or,ar,bn,cr,ps,gs,ms,hs,z,fs,As,ys,Is,oe,Ss,Cs,Es,T,Wa,vn,Ja,ae,dr}from"./chunk-e8e1h2h9.js";import{fe,tt,Sn}from"./chunk-d46p0h6t.js";import{j}from"./chunk-k53agv2m.js";import{vu,Xa,ye,Ya,Tn,Tu,Za,wu,Ru,Ph,Rn,vs,Dn,Pn,Nn,K,xe,N,mr,Bn,hr,ce,rc,_n,nc,Ar,xn,Ts,Ln,$n,Mn,Un,yr,cc,Le,W,$e,Me,it,Ce,Ir,Ee,Gn,qn,Vn,jn,zn,Kn,Wn,Sr,k,Ds,Yu,hc,Xn,Yn,Zn,ei,Ec,Ps,bc,kt,ti,Ns,ks,vc,ri,Tc}from"./chunk-aw1tp3p3.js";import{Vd,Eo,Ni,ki,bo,jd,zd,Bi,vo,To,Wd,Jd,wo}from"./chunk-e52me1c6.js";import{Ba,ln,un,Zi,es,ts,rs,_a,Oa}from"./chunk-hyeeqga9.js";import{xa}from"./chunk-7xnwa0s8.js";import{A}from"./chunk-31tvc877.js";import{_e}from"./chunk-5far81q7.js";import{y}from"./chunk-9wmer0zx.js";import{J,ni,Bs,wc,ii,dp}from"./chunk-srrscggm.js";import{Er,be}from"./chunk-qcaqc5b8.js";import{h}from"./chunk-ptq9v346.js";import{zh,Fe}from"./chunk-bxrzsth8.js";import{ud,$r,pd,gd,md,Ei,tg,Mr}from"./chunk-g6g33pt9.js";import{createHmac as lc,createSign as jl,timingSafeEqual as Zl}from"node:crypto";function Aa(l){let S=l instanceof Date?l.getTime():l;if(!Number.isFinite(S))throw TypeError("Media access timestamp must be finite");return Math.floor(S/1000)}function dc(l){return Buffer.from(l).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function Jl(l){return Buffer.from(l).toString("base64url")}function uc(l,S=!1){if(!l||/[\r\n]/.test(l))throw TypeError("Media resource is invalid");let P=S?l.replaceAll("*","wildcard"):l,v=new URL(P);if(!["http:","https:"].includes(v.protocol))throw TypeError("Media resource must use HTTP or HTTPS");if(!S&&l.includes("*"))throw TypeError("Canned policies cannot contain wildcards")}function pc(l,S){let P=jl("RSA-SHA1");return P.update(l),P.end(),dc(P.sign(S))}function mc(l){uc(l.resource,!0);let P={DateLessThan:{"AWS:EpochTime":Aa(l.expiresAt)}};if(l.activeAt!==void 0)P.DateGreaterThan={"AWS:EpochTime":Aa(l.activeAt)};if(l.ipAddress)P.IpAddress={"AWS:SourceIp":l.ipAddress};return JSON.stringify({Statement:[{Resource:l.resource,Condition:P}]})}function Ku(l,S,P){uc(l);let v=Aa(S),E=l.includes("?")?"&":"?",ot=mc({resource:l,expiresAt:S}),Ie=pc(ot,P.privateKey);return`${l}${E}Expires=${v}&Signature=${encodeURIComponent(Ie)}&Key-Pair-Id=${encodeURIComponent(P.keyPairId)}`}function ju(l,S){let P=mc(l);return{"CloudFront-Key-Pair-Id":S.keyPairId,"CloudFront-Policy":dc(Buffer.from(P)),"CloudFront-Signature":pc(P,S.privateKey)}}function Zu(l){if(!l.resource||/[\r\n]/.test(l.resource))throw TypeError("Media resource is invalid");let S=Jl(Buffer.from(JSON.stringify({resource:l.resource,expiresAt:Aa(l.expiresAt),...l.keyId?{keyId:l.keyId}:{},...l.audience?{audience:l.audience}:{}}))),P=lc("sha256",l.secret).update(S).digest("base64url");return`${S}.${P}`}function qu(l,S){let[P,v,E]=l.split(".");if(!P||!v||E)return null;let ot=lc("sha256",S.secret).update(P).digest(),Ie;try{Ie=Buffer.from(v,"base64url")}catch{return null}if(ot.length!==Ie.length||!Zl(ot,Ie))return null;try{let Ne=JSON.parse(Buffer.from(P,"base64url").toString("utf8")),nt=Aa(S.now??Date.now());if(!Ne.resource||!Number.isSafeInteger(Ne.expiresAt)||Ne.expiresAt<=nt)return null;if(S.resource&&Ne.resource!==S.resource)return null;if(S.audience&&Ne.audience!==S.audience)return null;return Ne}catch{return null}}function Ju(l,S=!1){let P=new URL(l,"https://media.invalid").pathname.toLowerCase(),v=/\.(?:m3u8|mpd|vtt|json)$/.test(P),E=/\.(?:key|license)$/.test(P)||P.includes("/keys/")||P.includes("/licenses/");return{"Accept-Ranges":"bytes","Cache-Control":S&&(v||E)?"private, no-store":v?"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 Xu(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 S=l.prefix?`/${l.prefix.replace(/^\/+|\/+$/g,"")}`:"",P=l.protected??!1,v="public, max-age=31536000, immutable",E=P?"private, no-store":"public, max-age=5, s-maxage=30, stale-while-revalidate=30";return{originDomain:`${l.bucket}.s3.${l.region}.amazonaws.com`,originPath:S,domain:l.domain,trustedKeyGroupIds:[...new Set(l.trustedKeyGroupIds??[])],behaviors:[{pathPattern:"*.m3u8",cacheControl:E,compress:!0,signed:P},{pathPattern:"*.mpd",cacheControl:E,compress:!0,signed:P},{pathPattern:"*.vtt",cacheControl:E,compress:!0,signed:P},{pathPattern:"*",cacheControl:v,compress:!1,signed:P}],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 Yl{builder;config;environment;mergedConfig;serverEipLogicalIds=new Map;storageFailoverReplicas=[];constructor(l){this.config=l.config,this.environment=l.environment,this.builder=new Cd(`${this.config.project.name} - ${this.environment}`),this.mergedConfig=this.mergeEnvironmentConfig()}mergeEnvironmentConfig(){let S=this.config.environments[this.environment]?.infrastructure;if(!S)return this.config;return{...this.config,infrastructure:{...this.config.infrastructure,...S,compute:{...this.config.infrastructure?.compute,...S.compute},storage:{...this.config.infrastructure?.storage,...S.storage},functions:{...this.config.infrastructure?.functions,...S.functions},servers:{...this.config.infrastructure?.servers,...S.servers},databases:{...this.config.infrastructure?.databases,...S.databases},cdn:{...this.config.infrastructure?.cdn,...S.cdn},sftp:S.sftp??this.config.infrastructure?.sftp,queues:{...this.config.infrastructure?.queues,...S.queues},redirects:{...this.config.infrastructure?.redirects,...S.redirects},realtime:{...this.config.infrastructure?.realtime,...S.realtime},cache:{...this.config.infrastructure?.cache,...S.cache},fileSystem:{...this.config.infrastructure?.fileSystem,...S.fileSystem},email:{...this.config.infrastructure?.email,...S.email},search:{...this.config.infrastructure?.search,...S.search},ai:{...this.config.infrastructure?.ai,...S.ai}}}}shouldDeploy(l){if(l.environments&&!l.environments.includes(this.environment))return!1;if(l.requiresFeatures){let S=this.config.features||{};if(!l.requiresFeatures.every((v)=>S[v]===!0))return!1}if(l.regions){let S=this.config.environments[this.environment]?.region||this.config.project.region;if(!l.regions.includes(S))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,S=Number(l||3008);return Number.isFinite(S)&&S>0?S: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,S){return l==="public"||S.routeCompute===!0}storageBucketName(l,S,P){return this.mergedConfig.infrastructure?.storage?.[P]?.bucket??`${l}-${S}-${P}`}fileSystemLogicalId(l,S,P){return t(r({slug:`${l}-${P}`,environment:S,resourceType:"efs"}))}resolveSftpStorage(l,S,P){let v=l.storage;if(v?.type==="efs"&&v.fileSystem){if(!this.mergedConfig.infrastructure?.fileSystem?.[v.fileSystem])throw Error(`sftp: storage.fileSystem "${v.fileSystem}" is not defined in infrastructure.fileSystem`);return{type:"efs",fileSystemId:{Ref:this.fileSystemLogicalId(S,P,v.fileSystem)},posixProfile:v.posixProfile}}if(v?.type==="s3"&&v.storageBucket){if(!this.mergedConfig.infrastructure?.storage?.[v.storageBucket])throw Error(`sftp: storage.storageBucket "${v.storageBucket}" is not defined in infrastructure.storage`);return{type:"s3",bucket:this.storageBucketName(S,P,v.storageBucket)}}return}resolveComputeCachePathPatterns(l){if(l&&l.length>0)return l;return this.defaultComputeCachePathPatterns()}createComputeCacheBehavior(l,S){return{PathPattern:l,TargetOriginId:S,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,S,P,v,E,ot){let Ie=this.serverEipLogicalIds.get("app"),Ne=this.serverEipLogicalIds.get("appInstance");if(!Ie)return;let nt=`EC2-${v}-${E}-api`,Pt=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",st=Pt==="us-east-1"?".compute-1.amazonaws.com":`.${Pt}.compute.amazonaws.com`,ur={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:Ie}]}]},st]]},pr=this.resolveApiOriginPort();if(l.push({Id:nt,DomainName:ur,CustomOriginConfig:{HTTPPort:pr,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),P.push(Ie),Ne)P.push(Ne);for(let gr of ot)S.push(this.createComputeCacheBehavior(gr,nt))}buildCaddyfile(l){let S=l.filter(([,E])=>typeof E.domain==="string"&&E.domain&&typeof E.port==="number");if(S.length===0)return;let P=new Map;for(let[,E]of S){let ot=P.get(E.domain)??[];ot.push({port:E.port,path:E.path}),P.set(E.domain,ot)}let v=[];for(let[E,ot]of P){let Ne=[...ot].sort((nt,Pt)=>{let st=!nt.path||nt.path==="/",ur=!Pt.path||Pt.path==="/";if(st&&!ur)return 1;if(!st&&ur)return-1;return(Pt.path?.length??0)-(nt.path?.length??0)}).map((nt)=>{let Pt=!nt.path||nt.path==="/",st=`reverse_proxy localhost:${nt.port}`;return Pt?` handle {
2
- ${st}
3
- }`:` handle ${nt.path} {
4
- ${st}
5
- }`});v.push(`${E} {
6
- ${Ne.join(`
1
+ import{ag,O,cg,rA,uI,nA,pI,gI,mI,hI,fI,yI,II,SI,CI,EI,dg,lg,Sd,Cd,co,L,d,Ed,ug,M,bd,p,iA,Ri,vd,Td,ge,wd,bI,r,t,vI,TI,g,wI,RI,DI,PI,NI,Gt,Rd,lo,sA,kI,BI,Re,je,Dd,pg,gg,_I,mg,hg,fg,Pd,Ag,De,Gr,qt,Nd,Vt,me,oA,kd,uo,yg,Ig,Sg,Cg,Bd,xI,F,S,a,A,ze,m,aA,Ke,U,ft,OI,cA,Q,_d,Pe,jt,po,ee,xd,te,dA,go,H,G,P,Di,v,zt,At,q,e,mo,LI,Eg,Od,$I,MI,FI,UI,Ld,QI,HI,GI,qI,VI,jI,zI,KI,WI,JI,XI,YI,lA,uA,pA,gA,mA,hA,fA,Kt,bg,vg,qr,Pi,ZI,Tg,eS,tS,Vr,rS,nS,iS,sS,oS,aS,AA,yA,IA,SA,CA,ho,cS,EA,bA,vA,V,dS,We,fo,Wt,TA,wg,wA,RA,DA,Rg,re,lS,uS,pS,gS,PA,mS,j,hS,fS,AS,Dg,Pg,yS,Ng,kg,IS,SS,CS,ES,bS,NA,$d,vS,TS,wS,RS,DS,kA,BA,PS,NS,kS,BS,_S,xS,OS,LS,$S,Bg,Md,MS,FS,US,QS,_g,xg,Og,HS,Lg,GS,qS,VS,jS,$g,zS,KS,WS,JS,XS,YS,ZS,eC,_A,xA,OA,LA,Mg,tC,rC,nC,iC,sC,oC,aC,cC,dC,$A,MA,FA,UA,lC,uC,Fg,pC,Ug,Qg,Hg,Gg,gC,mC,hC,fC,Ne,Ni,AC,yC,IC,SC,CC,EC,bC,vC,QA,TC,wC,qg,Vg,RC,DC,HA,PC,NC,kC,BC,_C,xC,OC,LC,$C,MC,FC,UC,QC,HC,GC,qC,VC,jC,zC,KC,WC,jg,JC,zg,XC,Kg,YC,Wg,ZC,Jg,eE,jr,tE,Xg,rE,Ao,nE,Yg,iE,Zg,sE,em,oE,tm,aE,rm,cE,zr,dE,nm,lE,im,uE,sm,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,xE,GA,qA,VA,jA,Dm,OE,Pm,LE,Nm,$E,km,ME,ki,zA,KA,yo,Fd,Kr,WA,Io,Jt,Ud,Qd,JA,XA,Bm,YA,Hd,_m,FE,UE,So,Co,Eo,Gd,Bi,qd,Vd,bo,jd,zd,xm,ZA,ey,ty,QE,ry,ny,HE,iy,Om,sy,oy,ay,GE,cy,_i,Kd,dy,qE,ly,vo,To,Wd,Lm,VE,$m,jE,Mm,zE,Fm,KE,Um,WE}from"./chunk-ds2v2xpb.js";import{ko,Qm,rl,py,$i,nl,Bo,Hm,Gm,Wr,_o,il,Je,sl,ol,al,Mi,Jr,qm,Xe,cl,xo,Oo,Lo,dl,ll,ul,Fi,$o,pl,Xr,Ui,Mo,yt,Vm,gl,ml,jm,hl,Fo,Xt,fl,Al,yl,Il,Ye,zm,Sl,Yt,Uo,Qo,Ho,Qi,Hi,Yr,Cl,Gi,Go,qo,Zr,El,en,Km,Wm,It,tn,Vo,Jm,bl,vl,jo,Tl,wl,Rl,gy,ne,Dl,my,hy,qi,Vi,fy,he,Xm,St,ke,Be,Ct,Pl,Nl,kl,Bl,Ym,Zm,zo,eh,th,Ko,_l,xl,rh,ie,nh,Ol,fe,Wo,Ze,Et,bt,rn,ji,Ll,Ay,Jo,ih,sh,oh,ah,Xo,Yo,$l,nn,Zo,Ml,zi,Fl,ea,ta,ra,na,ia,sa,oa,aa,Ul,Zt,ca,Ql,sn,Hl,da,la,Gl,er,ua,pa,ch,yy,Ki,Iy,Sy,Cy,ga,ma,ql,dh,ha,on,Vl,Wi,jl,zl,Kl,fa,lh,Aa,Wl,uh,ya,ph,an,cn,Jl,Ji,ru,ou,au,cu,du,lu,Yi,tr,Sa,dn,ln,rr,et,Sh,Ea,Ch,Eh,gu,ba,es,mu,va,Tt,xe,hu,Ta,wa,fu,Ra,Da,Pa,Na,Au,yu,pn,ka,Ba,_a,xa,Iu,ts,gn,rs,Oa}from"./chunk-cpyrhh52.js";import{x,Pr,Oc,$s,u,Op,Lp}from"./chunk-14zcywnp.js";import{ut,xc,li,ui,pi,xp}from"./chunk-rq0wrpz6.js";import{tf,rf,nf,hp,fp,Ap,sf,yp,Ip,of,af,Sp,cf,df,Bc,Cp,lf,uf,Ep,pf,gf,mf,hf,ff,Af,yf,di,_c,bp,vp,Tp,wp,Rp,Dp,Pp,Np,kp,Bp,_p,If,Sf,Cf,Ef,bf,vf,Tf}from"./chunk-92gn9ght.js";import{Ge,Lc,pe,Lt,$c,R,$t,pt,Mc,Ms,Df,$p,Fc,s,gi,Fs,Nr,Uc,Qc,kr,Pf,Hc,aI,cI,Us,dI,lI,Gc,qc,mi,Qs,Z,c,Hs,qe,Br,Nf,kf,Vc,Mt,Bf,Gs,_f,xf,qs,jc,_r,Vs,Of,zc,Mp,Ft,xr,Lf,js,$f,D,Mf,Kc,Fp,zs,Ff,Uf,Qf,Wc,hi,Ks,Jc,Ut,gt,Hf,Or,Gf,Xc,Up,Qp,Ws,Yc,Zc,mt,Hp,fi,ed,Js,Lr,Gp,Ai,td,rd,yi,qp,nd,id,sd,od,Xs,Vp,jp,qf,zp,ad,Ii,Kp,Wp,Ys,$r,Zs,eo,to,cd,Jp,dd,ro,Vf,Qt,jf,ld,Mr,ud,zf,pd,Xp,Si,Fr,no,Ci,Ve,Kf,Yp,Zp,Ht,gd,md,hd,Ei,bi,vi,Wf,Jf,ht,io,Xf,Ur,eg,so,Yf,tg,rg,ng,Zf,ig,sg,eA,i,tA,Ti,oo,ao}from"./chunk-c836kdrx.js";import{n}from"./chunk-5vxpgw8q.js";import{Ie,it,vn}from"./chunk-cwgy9pvc.js";import{o}from"./chunk-4rb7stp5.js";import{Ae,ds,ls,Eu,Ua,Qa,us,Ha,tt,z,rt,se,E,ye,An,Ga,Oe,qa,yn,In,Sn,wt,Rt,Dt,Cn,ir,Va,sr,or,nt,En,za,Pt,ar,bn,Wa,wu,Ru,Ja,cr}from"./chunk-gm0qysea.js";import{st,ce,$e,Du,Tn,Xa,Ya,gs,Se,Nt,wn,ms,hs,dr,lr,Rn,ur,fs,As,ys,Is,W,Ss,Cs,Es,bs,de,vs,Ts,ws,w,Za,Dn,ec,le,pr}from"./chunk-xkqx98bx.js";import{K}from"./chunk-01rbgche.js";import{Pu,tc,Ce,rc,Pn,Nu,nc,ku,Bu,xh,kn,Ds,Bn,_n,xn,J,Me,k,Ar,Ln,yr,ue,oc,$n,ac,Sr,Un,Ps,Qn,Hn,Gn,qn,Cr,pc,Fe,X,Ue,Qe,at,ve,Er,Te,zn,Kn,Wn,Jn,Xn,Yn,Zn,br,B,Bs,np,Ic,ti,ri,ni,ii,wc,_s,Rc,Ot,si,xs,Os,Dc,oi,Pc}from"./chunk-4apkvhsc.js";import{Jd,wo,xi,Oi,Ro,Xd,Yd,Li,Do,Po,el,tl,No}from"./chunk-bz1hp7es.js";import{La,mn,hn,ns,is,ss,os,$a,Ma}from"./chunk-b5xjjz3y.js";import{Fa}from"./chunk-2hy7ny4k.js";import{y}from"./chunk-nfkdgsgh.js";import{Le}from"./chunk-j2w0cvnr.js";import{I}from"./chunk-t7q4awss.js";import{Y,ai,Ls,Nc,ci,mp}from"./chunk-ckwdjb5q.js";import{Tr,we}from"./chunk-pdmfmsm9.js";import{f}from"./chunk-hpq0rrve.js";import{Yh,He}from"./chunk-60fn008g.js";import{fd,Qr,Ad,yd,Id,wi,og,Hr}from"./chunk-xassxhvq.js";import{createHmac as cc,createSign as Ec,timingSafeEqual as kc}from"node:crypto";function Mn(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 lc(l){return Buffer.from(l).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function Zl(l){return Buffer.from(l).toString("base64url")}function dc(l,h=!1){if(!l||/[\r\n]/.test(l))throw TypeError("Media resource is invalid");let C=h?l.replaceAll("*","wildcard"):l,b=new URL(C);if(!["http:","https:"].includes(b.protocol))throw TypeError("Media resource must use HTTP or HTTPS");if(!h&&l.includes("*"))throw TypeError("Canned policies cannot contain wildcards")}function uc(l,h){let C=Ec("RSA-SHA1");return C.update(l),C.end(),lc(C.sign(h))}function mc(l){dc(l.resource,!0);let C={DateLessThan:{"AWS:EpochTime":Mn(l.expiresAt)}};if(l.activeAt!==void 0)C.DateGreaterThan={"AWS:EpochTime":Mn(l.activeAt)};if(l.ipAddress)C.IpAddress={"AWS:SourceIp":l.ipAddress};return JSON.stringify({Statement:[{Resource:l.resource,Condition:C}]})}function Ku(l,h,C){dc(l);let b=Mn(h),T=l.includes("?")?"&":"?",Ee=mc({resource:l,expiresAt:h}),oe=uc(Ee,C.privateKey);return`${l}${T}Expires=${b}&Signature=${encodeURIComponent(oe)}&Key-Pair-Id=${encodeURIComponent(C.keyPairId)}`}function ju(l,h){let C=mc(l);return{"CloudFront-Key-Pair-Id":h.keyPairId,"CloudFront-Policy":lc(Buffer.from(C)),"CloudFront-Signature":uc(C,h.privateKey)}}function Zu(l){if(!l.resource||/[\r\n]/.test(l.resource))throw TypeError("Media resource is invalid");let h=Zl(Buffer.from(JSON.stringify({resource:l.resource,expiresAt:Mn(l.expiresAt),...l.keyId?{keyId:l.keyId}:{},...l.audience?{audience:l.audience}:{}}))),C=cc("sha256",l.secret).update(h).digest("base64url");return`${h}.${C}`}function qu(l,h){let[C,b,T]=l.split(".");if(!C||!b||T)return null;let Ee=cc("sha256",h.secret).update(C).digest(),oe;try{oe=Buffer.from(b,"base64url")}catch{return null}if(Ee.length!==oe.length||!kc(Ee,oe))return null;try{let ae=JSON.parse(Buffer.from(C,"base64url").toString("utf8")),be=Mn(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 Ju(l,h=!1){let C=new URL(l,"https://media.invalid").pathname.toLowerCase(),b=/\.(?:m3u8|mpd|vtt|json)$/.test(C),T=/\.(?:key|license)$/.test(C)||C.includes("/keys/")||C.includes("/licenses/");return{"Accept-Ranges":"bytes","Cache-Control":h&&(b||T)?"private, no-store":b?"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 Yu(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,"")}`:"",C=l.protected??!1,b="public, max-age=31536000, immutable",T=C?"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:T,compress:!0,signed:C},{pathPattern:"*.mpd",cacheControl:T,compress:!0,signed:C},{pathPattern:"*.vtt",cacheControl:T,compress:!0,signed:C},{pathPattern:"*",cacheControl:b,compress:!1,signed:C}],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 Yl{builder;config;environment;mergedConfig;serverEipLogicalIds=new Map;storageFailoverReplicas=[];constructor(l){this.config=l.config,this.environment=l.environment,this.builder=new wd(`${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((b)=>h[b]===!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,C){return this.mergedConfig.infrastructure?.storage?.[C]?.bucket??`${l}-${h}-${C}`}fileSystemLogicalId(l,h,C){return t(r({slug:`${l}-${C}`,environment:h,resourceType:"efs"}))}resolveSftpStorage(l,h,C){let b=l.storage;if(b?.type==="efs"&&b.fileSystem){if(!this.mergedConfig.infrastructure?.fileSystem?.[b.fileSystem])throw Error(`sftp: storage.fileSystem "${b.fileSystem}" is not defined in infrastructure.fileSystem`);return{type:"efs",fileSystemId:{Ref:this.fileSystemLogicalId(h,C,b.fileSystem)},posixProfile:b.posixProfile}}if(b?.type==="s3"&&b.storageBucket){if(!this.mergedConfig.infrastructure?.storage?.[b.storageBucket])throw Error(`sftp: storage.storageBucket "${b.storageBucket}" is not defined in infrastructure.storage`);return{type:"s3",bucket:this.storageBucketName(h,C,b.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,C,b,T,Ee){let oe=this.serverEipLogicalIds.get("app"),ae=this.serverEipLogicalIds.get("appInstance");if(!oe)return;let be=`EC2-${b}-${T}-api`,lt=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",_e=lt==="us-east-1"?".compute-1.amazonaws.com":`.${lt}.compute.amazonaws.com`,_t={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:oe}]}]},_e]]},nr=this.resolveApiOriginPort();if(l.push({Id:be,DomainName:_t,CustomOriginConfig:{HTTPPort:nr,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),C.push(oe),ae)C.push(ae);for(let fr of Ee)h.push(this.createComputeCacheBehavior(fr,be))}buildCaddyfile(l){let h=l.filter(([,T])=>typeof T.domain==="string"&&T.domain&&typeof T.port==="number");if(h.length===0)return;let C=new Map;for(let[,T]of h){let Ee=C.get(T.domain)??[];Ee.push({port:T.port,path:T.path}),C.set(T.domain,Ee)}let b=[];for(let[T,Ee]of C){let ae=[...Ee].sort((be,lt)=>{let _e=!be.path||be.path==="/",_t=!lt.path||lt.path==="/";if(_e&&!_t)return 1;if(!_e&&_t)return-1;return(lt.path?.length??0)-(be.path?.length??0)}).map((be)=>{let lt=!be.path||be.path==="/",_e=`reverse_proxy localhost:${be.port}`;return lt?` handle {
2
+ ${_e}
3
+ }`:` handle ${be.path} {
4
+ ${_e}
5
+ }`});b.push(`${T} {
6
+ ${ae.join(`
7
7
  `)}
8
- }`)}return v.join(`
8
+ }`)}return b.join(`
9
9
 
10
- `)}normalizeMountPath(l){let S=l?.mountPath||l?.path;if(!S||S==="/")return;let P=`/${S}`.replace(/\/+/g,"/").replace(/\/$/,"");return P==="/"?void 0:P}storageBucketLogicalId(l,S,P){return`${l}-${S}-s3-${P}`.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((v)=>v.charAt(0).toUpperCase()+v.slice(1)).join("")}pathMountRewriteFunctionCode(l,S="directory"){return`function handler(event) { var request = event.request; var prefix = ${JSON.stringify(l)}; var rewriteStyle = ${JSON.stringify(S)}; 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,S=this.environment,P=!!(this.mergedConfig.infrastructure?.functions&&Object.keys(this.mergedConfig.infrastructure.functions).length>0||this.mergedConfig.infrastructure?.api),v=!!(this.mergedConfig.infrastructure?.servers&&Object.keys(this.mergedConfig.infrastructure.servers).length>0),E=!!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,S),this.generateContainerInfrastructure(l,S);if(P)this.generateServerless(l,S);if(v)this.generateServer(l,S);if(E)this.generateComputeApp(l,S);if(this.mergedConfig.infrastructure?.jumpBox)this.generateJumpBox(l,S);if(this.storageFailoverReplicas=[],this.generateSharedInfrastructure(l,S),this.storageFailoverReplicas.length>0)this.builder.addMetadata(wd,this.storageFailoverReplicas);if(this.config.tags)this.applyGlobalTags(this.config.tags);return this}getStorageFailoverReplicas(){return[...this.storageFailoverReplicas]}applyGlobalTags(l){}generateNetworkInfrastructure(l,S){if(this.builder.hasResource("VPC"))return;let v=this.mergedConfig.infrastructure?.network?.cidr||"10.0.0.0/16",{vpc:E,logicalId:ot}=f.createVpc({slug:l,environment:S,cidr:v,enableDnsHostnames:!0,enableDnsSupport:!0});this.builder.addResource("VPC",E);let Ie=`${l}${S}IGW`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ie,{Type:"AWS::EC2::InternetGateway",Properties:{Tags:[{Key:"Name",Value:`${l}-${S}-igw`},{Key:"Environment",Value:S}]}});let Ne=`${l}${S}IGWAttach`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ne,{Type:"AWS::EC2::VPCGatewayAttachment",Properties:{VpcId:{Ref:"VPC"},InternetGatewayId:{Ref:Ie}}});let nt=`${l}${S}PublicRT`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(nt,{Type:"AWS::EC2::RouteTable",Properties:{VpcId:{Ref:"VPC"},Tags:[{Key:"Name",Value:`${l}-${S}-public-rt`},{Key:"Environment",Value:S}]}}),this.builder.addResource(`${l}${S}PublicRoute`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::EC2::Route",Properties:{RouteTableId:{Ref:nt},DestinationCidrBlock:"0.0.0.0/0",GatewayId:{Ref:Ie}},DependsOn:Ne});let Pt=this.mergedConfig.environments[S]?.region||this.mergedConfig.project.region||"us-east-1",st=["a","b"];for(let ur=0;ur<2;ur++){let pr=`PublicSubnet${ur+1}`;this.builder.addResource(pr,{Type:"AWS::EC2::Subnet",Properties:{VpcId:{Ref:"VPC"},CidrBlock:`10.0.${ur}.0/24`,AvailabilityZone:`${Pt}${st[ur]}`,MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:`${l}-${S}-public-${st[ur]}`},{Key:"Environment",Value:S}]}}),this.builder.addResource(`${pr}RTAssoc`,{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:{Ref:pr},RouteTableId:{Ref:nt}}})}}generateContainerInfrastructure(l,S){let P=this.mergedConfig.infrastructure?.containers;if(!P)return;let v=this.mergedConfig.infrastructure?.loadBalancer,E=this.mergedConfig.infrastructure?.ssl,ot=this.mergedConfig.infrastructure?.dns,Ie;if(E?.enabled&&E.domains?.length)if(E.certificateArn);else{let st=E.domains[0],ur=E.domains.slice(1).map((Dt)=>{if(Dt.includes(".")&&Dt.endsWith(st))return Dt.replace(`.${st}`,"");return Dt}),{certificate:pr,logicalId:gr}=I.createCertificate({domain:st,subdomains:ur,slug:l,environment:S,validationMethod:"DNS",hostedZoneId:ot?.hostedZoneId});Ie=gr,this.builder.addResource(gr,pr)}let Ne="ECSCluster";this.builder.addResource(Ne,{Type:"AWS::ECS::Cluster",Properties:{ClusterName:`${l}-${S}`,ClusterSettings:[{Name:"containerInsights",Value:"enabled"}],Tags:[{Key:"Name",Value:`${l}-${S}`},{Key:"Environment",Value:S}]}});let nt=`${l}${S}ALBSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(nt,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ALB security group for ${l}-${S}`,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}-${S}-alb-sg`},{Key:"Environment",Value:S}]}});let Pt=`${l}${S}ECSSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");for(let[st,ur]of Object.entries(P)){let pr=ur.port||3000;this.builder.addResource(Pt,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ECS tasks security group for ${l}-${S}`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:pr,ToPort:pr,SourceSecurityGroupId:{Ref:nt},Description:"Allow traffic from ALB"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${l}-${S}-ecs-sg`},{Key:"Environment",Value:S}]}});let gr=`${l}${S}TaskExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(gr,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${S}-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 Dt=`${l}${S}TaskRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Dt,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${S}-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 St=`${l}${S}${st}LogGroup`.replace(/[^a-zA-Z0-9]/g,""),Se=`/ecs/${l}-${S}-${st}`;this.builder.addResource(St,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:Se,RetentionInDays:30}});let Bt=`${l}${S}${st}TaskDef`.replace(/[^a-zA-Z0-9]/g,""),ie=String(ur.cpu||512),Rt=String(ur.memory||1024);this.builder.addResource(Bt,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${l}-${S}-${st}`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:ie,Memory:Rt,ExecutionRoleArn:{"Fn::GetAtt":[gr,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[Dt,"Arn"]},ContainerDefinitions:[{Name:st,Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${l}:latest`},Essential:!0,PortMappings:[{ContainerPort:pr,Protocol:"tcp"}],LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":Se,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":st}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${pr}${ur.healthCheck||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${l}-${S}-${st}`},{Key:"Environment",Value:S}]},DependsOn:[gr,Dt,St]});let Nt=`${l}${S}ALB`.replace(/[^a-zA-Z0-9]/g,"");if(v?.enabled!==!1){this.builder.addResource(Nt,{Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:`${l}-${S}-alb`,Scheme:"internet-facing",Type:"application",Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],SecurityGroups:[{Ref:nt}],Tags:[{Key:"Name",Value:`${l}-${S}-alb`},{Key:"Environment",Value:S}]}});let er=`${l}${S}TargetGroup`.replace(/[^a-zA-Z0-9]/g,""),lr=v?.healthCheck?.path||ur.healthCheck||"/health";this.builder.addResource(er,{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:`${l}-${S}-tg`,Port:pr,Protocol:"HTTP",VpcId:{Ref:"VPC"},TargetType:"ip",HealthCheckPath:lr,HealthCheckIntervalSeconds:v?.healthCheck?.interval||30,HealthyThresholdCount:v?.healthCheck?.healthyThreshold||2,UnhealthyThresholdCount:v?.healthCheck?.unhealthyThreshold||5,HealthCheckTimeoutSeconds:10,Tags:[{Key:"Name",Value:`${l}-${S}-tg`},{Key:"Environment",Value:S}]}});let fr=`${l}${S}HTTPListener`.replace(/[^a-zA-Z0-9]/g,"");if(E?.enabled&&E?.redirectHttp)this.builder.addResource(fr,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Nt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"redirect",RedirectConfig:{Protocol:"HTTPS",Port:"443",StatusCode:"HTTP_301"}}]}});else this.builder.addResource(fr,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Nt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:er}}]}});if(E?.enabled){let br=E.certificateArn||(Ie?{Ref:Ie}:void 0);if(br){let Wi=`${l}${S}HTTPSListener`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Wi,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Nt},Port:443,Protocol:"HTTPS",Certificates:[{CertificateArn:br}],DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:er}}],SslPolicy:"ELBSecurityPolicy-TLS13-1-2-2021-06"}})}}let Cr=`${l}${S}${st}Service`.replace(/[^a-zA-Z0-9]/g,""),vr=ur.desiredCount||1;this.builder.addResource(Cr,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${S}-${st}`,Cluster:{Ref:Ne},TaskDefinition:{Ref:Bt},DesiredCount:vr,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:Pt}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},LoadBalancers:[{ContainerName:st,ContainerPort:pr,TargetGroupArn:{Ref:er}}],HealthCheckGracePeriodSeconds:120,Tags:[{Key:"Name",Value:`${l}-${S}-${st}`},{Key:"Environment",Value:S}]},DependsOn:[Bt,fr,er]});let an=ur.autoScaling;if(an){let br=`${l}${S}${st}ScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(br,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:an.max||10,MinCapacity:an.min||1,ResourceId:{"Fn::Sub":`service/\${${Ne}}/${l}-${S}-${st}`},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:Cr}),an.targetCpuUtilization)this.builder.addResource(`${l}${S}${st}CPUScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${S}-${st}-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:br},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:an.targetCpuUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}});if(an.targetMemoryUtilization)this.builder.addResource(`${l}${S}${st}MemoryScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${S}-${st}-memory-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:br},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageMemoryUtilization"},TargetValue:an.targetMemoryUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(ot?.domain&&ot?.hostedZoneId)this.builder.addResource(`${l}${S}ApiDnsRecord`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:ot.hostedZoneId,Name:`api.${ot.domain}`,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[Nt,"DNSName"]},HostedZoneId:{"Fn::GetAtt":[Nt,"CanonicalHostedZoneID"]}}}});this.builder.addOutput("ECSClusterArn",{Description:"ECS Cluster ARN",Value:{"Fn::GetAtt":[Ne,"Arn"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-cluster-arn"}}}),this.builder.addOutput("ECSServiceName",{Description:"ECS Service Name",Value:`${l}-${S}-${st}`,Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-service-name"}}}),this.builder.addOutput("LoadBalancerDNS",{Description:"Application Load Balancer DNS Name",Value:{"Fn::GetAtt":[Nt,"DNSName"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-alb-dns"}}})}else{let er=`${l}${S}${st}Service`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(er,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${S}-${st}`,Cluster:{Ref:Ne},TaskDefinition:{Ref:Bt},DesiredCount:ur.desiredCount||1,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:Pt}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},Tags:[{Key:"Name",Value:`${l}-${S}-${st}`},{Key:"Environment",Value:S}]},DependsOn:[Bt]})}break}}generateServerless(l,S){if(this.mergedConfig.infrastructure?.functions)for(let[P,v]of Object.entries(this.mergedConfig.infrastructure.functions)){if(!this.shouldDeploy(v))continue;let{role:E,logicalId:ot}=Y.createRole({slug:l,environment:S,roleName:`${l}-${S}-${P}-role`,servicePrincipal:"lambda.amazonaws.com",managedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]});this.builder.addResource(ot,E);let{lambdaFunction:Ie,logicalId:Ne}=a.createLambdaFunction({slug:l,environment:S,functionName:`${l}-${S}-${P}`,handler:v.handler||"index.handler",runtime:v.runtime||"nodejs20.x",code:{zipFile:v.code||"export const handler = async () => ({ statusCode: 200 });"},role:ot,timeout:v.timeout,memorySize:v.memorySize});this.builder.addResource(Ne,Ie)}if(this.mergedConfig.infrastructure?.api){let{restApi:P,logicalId:v}=Pd.createRestApi({slug:l,environment:S,apiName:`${l}-${S}-api`});this.builder.addResource(v,P)}}generateServer(l,S){if(!this.mergedConfig.infrastructure?.servers)return;let P=this.mergedConfig.infrastructure.servers,v=this.mergedConfig.infrastructure?.compute,E=this.mergedConfig.infrastructure?.ssl;if(Object.values(P).some((Ie)=>!Ie.privateNetwork||Ie.privateNetwork==="create"))this.generateNetworkInfrastructure(l,S);for(let[Ie,Ne]of Object.entries(P)){let nt=Ne.instanceType||Ne.size||v?.size,st=(nt?a.InstanceSize.specs[nt]:void 0)?.instanceType||nt||"t3.micro",ur=Ne.type||"app",pr=Ne.userData||Ne.startupScript;if(!pr)pr=a.UserData.generateAppServerScript({runtime:"bun",runtimeVersion:Ne.bunVersion||"latest",webServer:"none",domain:Ne.domain,enableSsl:!!E?.enabled,sslEmail:E?.letsEncrypt?.email,installRedis:ur==="cache",installDatabaseClients:!!Ne.database});let gr=Ne.privateNetwork&&Ne.privateNetwork!=="create"?Ne.privateNetwork:{Ref:"VPC"},Dt=Ne.subnet||{Ref:"PublicSubnet1"},Se=!!this.mergedConfig.infrastructure?.email?.server?.enabled,Bt=[22,80,443,this.resolveApiOriginPort()];if(Se)Bt.push(25,465,587,143,993);let ie=a.createServerModeStack({slug:`${l}-${Ie}`,environment:S,vpcId:gr,subnetId:Dt,instanceType:st,keyName:Ne.keyName||`${l}-${S}`,domain:Ne.domain,userData:pr,volumeSize:Ne.diskSize||20,imageId:Ne.image,allowedPorts:Bt});for(let[Rt,Nt]of Object.entries(ie.resources))this.builder.addResource(Rt,Nt);this.serverEipLogicalIds.set(Ie,ie.outputs.eipLogicalId),this.serverEipLogicalIds.set(`${Ie}Instance`,ie.outputs.instanceLogicalId),this.builder.addOutput(`${Ie}InstanceId`,{Value:{Ref:ie.outputs.instanceLogicalId},Description:`Instance ID for ${Ie} server`}),this.builder.addOutput(`${Ie}PublicIp`,{Value:{Ref:ie.outputs.eipLogicalId},Description:`Public IP for ${Ie} server`})}}generateComputeApp(l,S){let P=this.mergedConfig.infrastructure?.compute;if(!P)return;let v=this.mergedConfig.sites||{},E=Object.entries(v),Ie=this.mergedConfig.infrastructure?.dns?.domain,Ne=this.mergedConfig.infrastructure?.database,nt=P.size,st=(nt?a.InstanceSize.specs[nt]:void 0)?.instanceType||nt||"t3.micro";if(!this.builder.hasResource("VPC"))this.generateNetworkInfrastructure(l,S);let ur=this.buildCaddyfile(E),pr=a.UserData.generateBunAppScript({runtime:P.runtime||"bun",runtimeVersion:P.runtimeVersion||"latest",systemPackages:P.systemPackages,database:Ne,caddyfile:ur}),gr=vs(P.appUpdates),Dt=gr.length>0?`${pr}
11
- ${gr.join(`
10
+ `)}normalizeMountPath(l){let h=l?.mountPath||l?.path;if(!h||h==="/")return;let C=`/${h}`.replace(/\/+/g,"/").replace(/\/$/,"");return C==="/"?void 0:C}storageBucketLogicalId(l,h,C){return`${l}-${h}-s3-${C}`.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.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,C=!!(this.mergedConfig.infrastructure?.functions&&Object.keys(this.mergedConfig.infrastructure.functions).length>0||this.mergedConfig.infrastructure?.api),b=!!(this.mergedConfig.infrastructure?.servers&&Object.keys(this.mergedConfig.infrastructure.servers).length>0),T=!!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(C)this.generateServerless(l,h);if(b)this.generateServer(l,h);if(T)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(kd,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 b=this.mergedConfig.infrastructure?.network?.cidr||"10.0.0.0/16",{vpc:T,logicalId:Ee}=A.createVpc({slug:l,environment:h,cidr:b,enableDnsHostnames:!0,enableDnsSupport:!0});this.builder.addResource("VPC",T);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 lt=this.mergedConfig.environments[h]?.region||this.mergedConfig.project.region||"us-east-1",_e=["a","b"];for(let _t=0;_t<2;_t++){let nr=`PublicSubnet${_t+1}`;this.builder.addResource(nr,{Type:"AWS::EC2::Subnet",Properties:{VpcId:{Ref:"VPC"},CidrBlock:`10.0.${_t}.0/24`,AvailabilityZone:`${lt}${_e[_t]}`,MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:`${l}-${h}-public-${_e[_t]}`},{Key:"Environment",Value:h}]}}),this.builder.addResource(`${nr}RTAssoc`,{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:{Ref:nr},RouteTableId:{Ref:be}}})}}generateContainerInfrastructure(l,h){let C=this.mergedConfig.infrastructure?.containers;if(!C)return;let b=this.mergedConfig.infrastructure?.loadBalancer,T=this.mergedConfig.infrastructure?.ssl,Ee=this.mergedConfig.infrastructure?.dns,oe;if(T?.enabled&&T.domains?.length)if(T.certificateArn);else{let _e=T.domains[0],_t=T.domains.slice(1).map((dt)=>{if(dt.includes(".")&&dt.endsWith(_e))return dt.replace(`.${_e}`,"");return dt}),{certificate:nr,logicalId:fr}=S.createCertificate({domain:_e,subdomains:_t,slug:l,environment:h,validationMethod:"DNS",hostedZoneId:Ee?.hostedZoneId});oe=fr,this.builder.addResource(fr,nr)}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 lt=`${l}${h}ECSSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");for(let[_e,_t]of Object.entries(C)){let nr=_t.port||3000;this.builder.addResource(lt,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ECS tasks security group for ${l}-${h}`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:nr,ToPort:nr,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 dt=`${l}${h}TaskRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(dt,{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 ot=`${l}${h}${_e}LogGroup`.replace(/[^a-zA-Z0-9]/g,""),_=`/ecs/${l}-${h}-${_e}`;this.builder.addResource(ot,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:_,RetentionInDays:30}});let kt=`${l}${h}${_e}TaskDef`.replace(/[^a-zA-Z0-9]/g,""),N=String(_t.cpu||512),ct=String(_t.memory||1024);this.builder.addResource(kt,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${l}-${h}-${_e}`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:N,Memory:ct,ExecutionRoleArn:{"Fn::GetAtt":[fr,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[dt,"Arn"]},ContainerDefinitions:[{Name:_e,Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${l}:latest`},Essential:!0,PortMappings:[{ContainerPort:nr,Protocol:"tcp"}],LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":_,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":_e}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${nr}${_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,dt,ot]});let vt=`${l}${h}ALB`.replace(/[^a-zA-Z0-9]/g,"");if(b?.enabled!==!1){this.builder.addResource(vt,{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=b?.healthCheck?.path||_t.healthCheck||"/health";this.builder.addResource(xt,{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:`${l}-${h}-tg`,Port:nr,Protocol:"HTTP",VpcId:{Ref:"VPC"},TargetType:"ip",HealthCheckPath:Bt,HealthCheckIntervalSeconds:b?.healthCheck?.interval||30,HealthyThresholdCount:b?.healthCheck?.healthyThreshold||2,UnhealthyThresholdCount:b?.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(T?.enabled&&T?.redirectHttp)this.builder.addResource(mr,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:vt},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:vt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:xt}}]}});if(T?.enabled){let hr=T.certificateArn||(oe?{Ref:oe}:void 0);if(hr){let Ir=`${l}${h}HTTPSListener`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ir,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:vt},Port:443,Protocol:"HTTPS",Certificates:[{CertificateArn:hr}],DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:xt}}],SslPolicy:"ELBSecurityPolicy-TLS13-1-2-2021-06"}})}}let gr=`${l}${h}${_e}Service`.replace(/[^a-zA-Z0-9]/g,""),Rr=_t.desiredCount||1;this.builder.addResource(gr,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${h}-${_e}`,Cluster:{Ref:ae},TaskDefinition:{Ref:kt},DesiredCount:Rr,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:lt}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},LoadBalancers:[{ContainerName:_e,ContainerPort:nr,TargetGroupArn:{Ref:xt}}],HealthCheckGracePeriodSeconds:120,Tags:[{Key:"Name",Value:`${l}-${h}-${_e}`},{Key:"Environment",Value:h}]},DependsOn:[kt,mr,xt]});let wr=_t.autoScaling;if(wr){let hr=`${l}${h}${_e}ScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(hr,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:wr.max||10,MinCapacity:wr.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:gr}),wr.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:hr},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:wr.targetCpuUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}});if(wr.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:hr},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageMemoryUtilization"},TargetValue:wr.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":[vt,"DNSName"]},HostedZoneId:{"Fn::GetAtt":[vt,"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":[vt,"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:kt},DesiredCount:_t.desiredCount||1,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:lt}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},Tags:[{Key:"Name",Value:`${l}-${h}-${_e}`},{Key:"Environment",Value:h}]},DependsOn:[kt]})}break}}generateServerless(l,h){if(this.mergedConfig.infrastructure?.functions)for(let[C,b]of Object.entries(this.mergedConfig.infrastructure.functions)){if(!this.shouldDeploy(b))continue;let{role:T,logicalId:Ee}=ee.createRole({slug:l,environment:h,roleName:`${l}-${h}-${C}-role`,servicePrincipal:"lambda.amazonaws.com",managedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]});this.builder.addResource(Ee,T);let{lambdaFunction:oe,logicalId:ae}=a.createLambdaFunction({slug:l,environment:h,functionName:`${l}-${h}-${C}`,handler:b.handler||"index.handler",runtime:b.runtime||"nodejs20.x",code:{zipFile:b.code||"export const handler = async () => ({ statusCode: 200 });"},role:Ee,timeout:b.timeout,memorySize:b.memorySize});this.builder.addResource(ae,oe)}if(this.mergedConfig.infrastructure?.api){let{restApi:C,logicalId:b}=xd.createRestApi({slug:l,environment:h,apiName:`${l}-${h}-api`});this.builder.addResource(b,C)}}generateServer(l,h){if(!this.mergedConfig.infrastructure?.servers)return;let C=this.mergedConfig.infrastructure.servers,b=this.mergedConfig.infrastructure?.compute,T=this.mergedConfig.infrastructure?.ssl;if(Object.values(C).some((oe)=>!oe.privateNetwork||oe.privateNetwork==="create"))this.generateNetworkInfrastructure(l,h);for(let[oe,ae]of Object.entries(C)){let be=ae.instanceType||ae.size||b?.size,_e=(be?a.InstanceSize.specs[be]:void 0)?.instanceType||be||"t3.micro",_t=ae.type||"app",nr=ae.userData||ae.startupScript;if(!nr)nr=a.UserData.generateAppServerScript({runtime:"bun",runtimeVersion:ae.bunVersion||"latest",webServer:"none",domain:ae.domain,enableSsl:!!T?.enabled,sslEmail:T?.letsEncrypt?.email,installRedis:_t==="cache",installDatabaseClients:!!ae.database});let fr=ae.privateNetwork&&ae.privateNetwork!=="create"?ae.privateNetwork:{Ref:"VPC"},dt=ae.subnet||{Ref:"PublicSubnet1"},_=!!this.mergedConfig.infrastructure?.email?.server?.enabled,kt=[22,80,443,this.resolveApiOriginPort()];if(_)kt.push(25,465,587,143,993);let N=a.createServerModeStack({slug:`${l}-${oe}`,environment:h,vpcId:fr,subnetId:dt,instanceType:_e,keyName:ae.keyName||`${l}-${h}`,domain:ae.domain,userData:nr,volumeSize:ae.diskSize||20,imageId:ae.image,allowedPorts:kt});for(let[ct,vt]of Object.entries(N.resources))this.builder.addResource(ct,vt);this.serverEipLogicalIds.set(oe,N.outputs.eipLogicalId),this.serverEipLogicalIds.set(`${oe}Instance`,N.outputs.instanceLogicalId),this.builder.addOutput(`${oe}InstanceId`,{Value:{Ref:N.outputs.instanceLogicalId},Description:`Instance ID for ${oe} server`}),this.builder.addOutput(`${oe}PublicIp`,{Value:{Ref:N.outputs.eipLogicalId},Description:`Public IP for ${oe} server`})}}generateComputeApp(l,h){let C=this.mergedConfig.infrastructure?.compute;if(!C)return;let b=this.mergedConfig.sites||{},T=Object.entries(b),oe=this.mergedConfig.infrastructure?.dns?.domain,ae=this.mergedConfig.infrastructure?.database,be=C.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(T),nr=a.UserData.generateBunAppScript({runtime:C.runtime||"bun",runtimeVersion:C.runtimeVersion||"latest",systemPackages:C.systemPackages,database:ae,caddyfile:_t}),fr=Ds(C.appUpdates),dt=fr.length>0?`${nr}
11
+ ${fr.join(`
12
12
  `)}
13
- `:pr,St=E.map(([,lr])=>lr.port).filter((lr)=>typeof lr==="number"&&![80,443].includes(lr)),Se=this.resolveApiOriginPort(),Bt=`${l}${S}DeployBucket`.replace(/[^a-zA-Z0-9]/g,""),ie=`${l}-${S}-deploy`;this.builder.addResource(Bt,{Type:"AWS::S3::Bucket",Properties:{BucketName:ie,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:S},{Key:"ManagedBy",Value:"ts-cloud"}]}});let Rt=a.createServerModeStack({slug:`${l}-app`,environment:S,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},instanceType:st,keyName:P.allowSsh?`${l}-${S}`:void 0,domain:Ie,userData:Dt,volumeSize:P.disk?.size||20,imageId:P.image,allowedPorts:[...P.allowSsh?[22]:[],80,443,Se,...St]}),Nt=Rt.resources[Rt.outputs.instanceLogicalId];if(Nt?.Properties){let lr=Nt.Properties.Tags||[];Nt.Properties.Tags=[...lr,{Key:"Project",Value:l},{Key:"Environment",Value:S},{Key:"Role",Value:"app"},{Key:"ManagedBy",Value:"ts-cloud"}]}let er=Rt.resources[Rt.outputs.roleLogicalId];if(er?.Properties)er.Properties.Policies=er.Properties.Policies||[],er.Properties.Policies.push({PolicyName:"DeployBucketRead",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:ListBucket"],Resource:[`arn:aws:s3:::${ie}`,`arn:aws:s3:::${ie}/*`]}]}});for(let[lr,fr]of Object.entries(Rt.resources))this.builder.addResource(lr,fr);this.builder.addOutput("deployBucketName",{Value:{Ref:Bt},Description:"S3 bucket where release tarballs are uploaded"}),this.builder.addOutput("appInstanceId",{Value:{Ref:Rt.outputs.instanceLogicalId},Description:"EC2 instance ID for the app server"}),this.builder.addOutput("appPublicIp",{Value:{Ref:Rt.outputs.eipLogicalId},Description:"Public IP for the app server"}),this.serverEipLogicalIds.set("app",Rt.outputs.eipLogicalId),this.serverEipLogicalIds.set("appInstance",Rt.outputs.instanceLogicalId)}generateJumpBox(l,S){let P=this.mergedConfig.infrastructure?.jumpBox;if(!P)return;let v=P===!0?{}:P;if(v.enabled===!1)return;this.generateNetworkInfrastructure(l,S);let E=v.size||"micro",Ie=a.InstanceSize.specs[E]?.instanceType||E||"t3.micro",Ne;if(v.mountEfs)Ne={fileSystemId:typeof v.mountEfs==="string"?v.mountEfs:{Ref:"FileSystem"},mountPath:v.mountPath||"/mnt/efs"};let nt;if(v.databaseTools)nt=a.JumpBox.withDatabaseTools({slug:l,environment:S,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:v.keyName||`${l}-${S}`,allowedCidrs:v.allowedCidrs});else if(Ne)nt=a.JumpBox.withEfsMount({slug:l,environment:S,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:v.keyName||`${l}-${S}`,fileSystemId:Ne.fileSystemId,mountPath:Ne.mountPath,allowedCidrs:v.allowedCidrs});else nt=a.createJumpBox({slug:l,environment:S,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:v.keyName||`${l}-${S}`,instanceType:Ie,allowedCidrs:v.allowedCidrs,mountEfs:Ne});for(let[Pt,st]of Object.entries(nt.resources))this.builder.addResource(Pt,st);this.builder.addOutput("JumpBoxInstanceId",{Value:{Ref:nt.instanceLogicalId},Description:"The ID of the JumpBox EC2 instance (use with SSM Session Manager or SSH)"})}generateSharedInfrastructure(l,S){let P=this.mergedConfig.infrastructure?.ssl,v=this.mergedConfig.infrastructure?.dns,E=v?.domain,ot=v?.hostedZoneId,Ie=[],Ne,nt;if(P?.certificateArn)nt=P.certificateArn;else if(P?.enabled&&E&&ot){let St=P.domains||[E],Se=St[0],Bt=St.slice(1).map((Nt)=>{if(Nt.includes(".")&&Nt.endsWith(Se))return Nt.replace(`.${Se}`,"");return Nt}),{certificate:ie,logicalId:Rt}=I.createCertificate({domain:Se,subdomains:Bt,slug:l,environment:S,validationMethod:"DNS",hostedZoneId:ot});Ne=Rt,this.builder.addResource(Rt,ie)}if(this.mergedConfig.infrastructure?.storage){let St=Object.entries(this.mergedConfig.infrastructure.storage).some(([,ie])=>ie.website),Se;if(St&&(Ne||nt))Se=`${l}${S}CloudFrontOAC`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(Se,{Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${l}-${S}-s3-oac`,Description:`OAC for ${l} ${S} S3 website buckets`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}});let Bt=Object.entries(this.mergedConfig.infrastructure.storage).map(([ie,Rt])=>({name:ie,config:Rt,mountPath:this.normalizeMountPath(Rt),rewriteStyle:Rt.pathRewriteStyle||"directory",logicalId:this.storageBucketLogicalId(l,S,ie)})).filter((ie)=>ie.name!=="public"&&ie.config.website&&ie.mountPath);for(let[ie,Rt]of Object.entries(this.mergedConfig.infrastructure.storage)){let Nt=!!(Rt.website&&Se),er=this.storageBucketName(l,S,ie),{bucket:lr,logicalId:fr}=ve.createBucket({slug:l,name:ie,environment:S,bucketName:er,versioning:Rt.versioning,encryption:Rt.encryption,public:Nt?!1:Rt.public}),Cr=this.normalizeMountPath(Rt),vr;if(Rt.failover){let br=`infrastructure.storage.${ie}`;if(!Nt||!E||Cr&&ie!=="public")throw Error(`${br}.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(vr=gg({failover:Rt.failover,primaryBucket:er,primaryRegion:this.mergedConfig.project.region||"us-east-1",where:br}),vr.replicate&&lr.Properties){let Wi=`${fr}FailoverReplicationRole`;this.builder.addResource(Wi,hg({primaryBucket:er,replicaBucket:vr.replicaBucket}));let wn=lr.Properties;wn.VersioningConfiguration={Status:"Enabled"},wn.ReplicationConfiguration=fg({replicaBucket:vr.replicaBucket,roleArn:{"Fn::GetAtt":[Wi,"Arn"]}})}}if(Nt&&lr.Properties)lr.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1};if(this.builder.addResource(fr,lr),Rt.website){let br=typeof Rt.website==="object"?Rt.website:{},Wi=ve.enableWebsiteHosting(lr,br.indexDocument||"index.html",br.errorDocument);this.builder.addResource(fr,Wi)}let an=this.normalizeMountPath(Rt);if(Nt&&Se&&E&&!(an&&ie!=="public")){let br=`${l}${S}${ie}CDN`.replace(/[^a-zA-Z0-9]/g,""),Wi=[];if(Rt.aliases&&Rt.aliases.length>0)Wi.push(...Rt.aliases);else if(ie==="public"){if(Wi.push(E),P?.domains?.includes(`www.${E}`))Wi.push(`www.${E}`)}else if(ie==="docs")Wi.push(`docs.${E}`);else if(ie==="blog")Wi.push(`blog.${E}`);let wn=typeof Rt.website==="object"?Rt.website:{},Fn=Rt.spa===!0,On=wn.errorDocument||(Fn?"index.html":"404.html"),pn=[];if(Fn)pn.push({ErrorCode:403,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300});else pn.push({ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${On}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${On}`,ErrorCachingMinTTL:300});let Hn=nt&&Wi.length>0?{AcmCertificateArn:nt,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:Ne&&Wi.length>0?{AcmCertificateArn:{Ref:Ne},SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},Jn=`S3-${l}-${S}-${ie}`,bs=this.mergedConfig.project.region||"us-east-1",Qn;if(!Fn)Qn=`${l}${S}${ie}UrlRewrite`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(Qn,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${S}-${ie}-url-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`URL rewrite for ${l} ${S} ${ie} - 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 ha=[{Id:Jn,DomainName:{"Fn::Sub":`\${${fr}}.s3.${bs}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:Se}}],qa=[],Rs=[];if(this.shouldRouteStorageBucketToCompute(ie,Rt)){this.appendComputeAppOrigin(ha,qa,Rs,l,S,this.resolveComputeCachePathPatterns(Rt.computeRoutes));for(let zi of Bt){let ns=`S3-${l}-${S}-${zi.name}`,ec=`${l}${S}${zi.name}PathMountRewrite`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ec,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${S}-${zi.name}-path-mount-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`Path mount rewrite for ${l} ${S} ${zi.name} at ${zi.mountPath}`,Runtime:"cloudfront-js-2.0"},FunctionCode:this.pathMountRewriteFunctionCode(zi.mountPath,zi.rewriteStyle)}}),ha.push({Id:ns,DomainName:{"Fn::Sub":`\${${zi.logicalId}}.s3.${bs}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:Se}}),Rs.push(zi.logicalId,ec);for(let Kl of[zi.mountPath,`${zi.mountPath}/*`])qa.push({PathPattern:Kl,TargetOriginId:ns,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":[ec,"FunctionARN"]}}]})}}let is,sc=Jn;if(vr){let zi=`${Jn}-failover`;Object.assign(ha[0],vr.primaryConnection),ha.push({Id:zi,DomainName:mg(vr.replicaBucket,vr.replicaRegion),OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:Se}}),is=Fr({primaryOriginId:Jn,secondaryOriginId:zi,statusCodes:vr.statusCodes}),sc=is.Items[0].Id}let ws={Type:"AWS::CloudFront::Distribution",DependsOn:[fr,Se,...Qn?[Qn]:[],...Rs],Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${S} ${ie} site`,DefaultRootObject:"index.html",Origins:ha,...is?{OriginGroups:is}:{},DefaultCacheBehavior:{TargetOriginId:sc,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...Qn?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[Qn,"FunctionARN"]}}]}:{}},...qa.length>0?{CacheBehaviors:qa}:{},...Wi.length>0?{Aliases:Wi}:{},ViewerCertificate:Hn,PriceClass:"PriceClass_100",HttpVersion:"http2and3",IPV6Enabled:!0,CustomErrorResponses:pn}}};if(Ne)ws.DependsOn.push(Ne);if(vr)Ht(ws.Properties.DistributionConfig,`infrastructure.storage.${ie}`),this.storageFailoverReplicas.push({name:ie,primaryBucket:er,primaryRegion:bs,replicaBucket:vr.replicaBucket,replicaRegion:vr.replicaRegion,replicate:vr.replicate,distributionArnOutput:`${ie}CloudFrontDistributionArn`}),this.builder.addOutput(`${ie}CloudFrontDistributionArn`,{Value:{"Fn::Sub":`arn:\${AWS::Partition}:cloudfront::\${AWS::AccountId}:distribution/\${${br}}`},Description:`CloudFront distribution ARN for ${ie} (scopes the bucket policy of the failover replica)`}),this.builder.addOutput(`${ie}FailoverBucketName`,{Value:vr.replicaBucket,Description:`Failover replica bucket for ${ie} (${vr.replicaRegion}), outside this stack`});this.builder.addResource(br,ws);let zl=`${fr}CloudFrontPolicy`;if(this.builder.addResource(zl,{Type:"AWS::S3::BucketPolicy",DependsOn:[fr,br],Properties:{Bucket:{Ref:fr},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":`arn:aws:s3:::\${${fr}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${br}}`}}}}]}}}),this.shouldRouteStorageBucketToCompute(ie,Rt))for(let zi of Bt){let ns=`${zi.logicalId}CloudFrontPolicy`;this.builder.addResource(ns,{Type:"AWS::S3::BucketPolicy",DependsOn:[zi.logicalId,br],Properties:{Bucket:{Ref:zi.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:::\${${zi.logicalId}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${br}}`}}}}]}}})}if(Wi.length>0)Ie.push({name:ie,bucketLogicalId:fr,distLogicalId:br,oacLogicalId:Se,aliases:Wi});this.builder.addOutput(`${ie}CloudFrontDomain`,{Value:{"Fn::GetAtt":[br,"DomainName"]},Description:`CloudFront domain for ${ie}`}),this.builder.addOutput(`${ie}CloudFrontDistributionId`,{Value:{Ref:br},Description:`CloudFront distribution ID for ${ie}`})}if(this.builder.addOutput(`${ie}BucketName`,{Value:{Ref:fr},Description:`S3 bucket name for ${ie}`}),ie==="public")this.builder.addOutput("FrontendBucketName",{Value:{Ref:fr},Description:"Frontend S3 bucket name"});if(ie==="docs")this.builder.addOutput("DocsBucketName",{Value:{Ref:fr},Description:"Documentation S3 bucket name"});if(ie==="blog")this.builder.addOutput("BlogBucketName",{Value:{Ref:fr},Description:"Blog S3 bucket name"})}}if(this.mergedConfig.infrastructure?.sftp){let St=this.mergedConfig.infrastructure.sftp,Se=Dd.create({...St,storage:this.resolveSftpStorage(St,l,S)??St.storage,slug:l,environment:S});for(let[Bt,ie]of Object.entries(Se.resources))this.builder.addResource(Bt,ie);this.builder.addOutput("SftpServerId",{Value:{Ref:Se.serverLogicalId},Description:"AWS Transfer Family SFTP server ID"}),this.builder.addOutput("SftpEndpoint",{Value:{"Fn::Sub":`\${${Se.serverLogicalId}}.server.transfer.\${AWS::Region}.amazonaws.com`},Description:"AWS Transfer Family SFTP endpoint"}),this.builder.addOutput("SftpStorageDomain",{Value:Se.domain,Description:"Storage backing the SFTP server (EFS or S3)"})}if(ot&&Ie.length>0)for(let{name:St,distLogicalId:Se,aliases:Bt}of Ie)for(let ie of Bt){let Rt=ie.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Rt}ARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[Se],Properties:{HostedZoneId:ot,Name:ie,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[Se,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}}),this.builder.addResource(`${Rt}AAAARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[Se],Properties:{HostedZoneId:ot,Name:ie,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":[Se,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}})}if(this.mergedConfig.infrastructure?.databases){for(let[St,Se]of Object.entries(this.mergedConfig.infrastructure.databases))if(Se.engine==="dynamodb"){let{table:Bt,logicalId:ie}=Gt.createTable({slug:l,environment:S,tableName:`${l}-${S}-${St}`,partitionKey:Se.partitionKey||{name:"id",type:"S"},sortKey:Se.sortKey});this.builder.addResource(ie,Bt)}else if(Se.engine==="postgres"){let{dbInstance:Bt,logicalId:ie}=Gt.createPostgres({slug:l,environment:S,dbInstanceIdentifier:`${l}-${S}-${St}`,masterUsername:Se.username||"admin",masterUserPassword:Se.password||"changeme123",allocatedStorage:Se.storage||20,dbInstanceClass:Se.instanceClass||"db.t3.micro"});this.builder.addResource(ie,Bt)}else if(Se.engine==="mysql"){let{dbInstance:Bt,logicalId:ie}=Gt.createMysql({slug:l,environment:S,dbInstanceIdentifier:`${l}-${S}-${St}`,masterUsername:Se.username||"admin",masterUserPassword:Se.password||"changeme123",allocatedStorage:Se.storage||20,dbInstanceClass:Se.instanceClass||"db.t3.micro"});this.builder.addResource(ie,Bt)}}if(this.mergedConfig.infrastructure?.cdn)for(let[St,Se]of Object.entries(this.mergedConfig.infrastructure.cdn)){if(!Se.origin)continue;let Bt=typeof Se.customDomain==="string"?Se.customDomain:Se.customDomain?.domain||Se.domain,ie=typeof Se.customDomain==="object"?Se.customDomain?.certificateArn:Se.certificateArn,Rt=ie||nt,Nt=`${l}${S}${St}CDN`.replace(/[^a-zA-Z0-9]/g,""),er=`S3-${l}-${S}-${St}-cdn`,lr=[{Id:er,DomainName:Se.origin,OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginShield:Se.originShield?{Enabled:!0,OriginShieldRegion:Se.originShieldRegion||this.mergedConfig.environments[S]?.region||this.mergedConfig.project.region||"us-east-1"}:{Enabled:!1},...Te(Se,`infrastructure.cdn.${St}`)}],fr=[],Cr=[],vr=["GET","HEAD","OPTIONS"],an=er,br;if(Se.failoverOrigin){Qt(vr,`the default cache behavior of infrastructure.cdn.${St}`);let On=`${er}-failover`,pn=typeof Se.failoverOrigin==="string"?{domain:Se.failoverOrigin}:Se.failoverOrigin;if(!pn.domain)throw Error(`infrastructure.cdn.${St}.failoverOrigin.domain is required`);if(pn.domain===Se.origin)throw Error(`infrastructure.cdn.${St}: failoverOrigin must differ from origin (both are ${Se.origin})`);lr.push({Id:On,DomainName:pn.domain,OriginPath:pn.originPath||"",...Td(pn.domain)?{S3OriginConfig:{OriginAccessIdentity:""}}:{CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"}},OriginShield:{Enabled:!1},...Te(pn,`infrastructure.cdn.${St}.failoverOrigin`)}),br=Fr({primaryOriginId:er,secondaryOriginId:On,statusCodes:Se.failoverStatusCodes}),an=br.Items[0].Id}else if(Se.failoverStatusCodes)throw Error(`infrastructure.cdn.${St}: failoverStatusCodes needs failoverOrigin to fail over to`);if(Se.routeCompute)this.appendComputeAppOrigin(lr,fr,Cr,l,S,this.resolveComputeCachePathPatterns(Se.computeRoutes));let Wi=Rt&&Bt?{AcmCertificateArn:Ne&&!ie?{Ref:Ne}:Rt,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},wn=[...Cr];if(Ne&&!ie&&Bt)wn.push(Ne);let Fn={Type:"AWS::CloudFront::Distribution",...wn.length>0?{DependsOn:wn}:{},Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${S} ${St} CDN`,DefaultRootObject:"index.html",Origins:lr,...br?{OriginGroups:br}:{},DefaultCacheBehavior:{TargetOriginId:an,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:vr,CachedMethods:["GET","HEAD","OPTIONS"],Compress:Se.compress!==!1,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},...fr.length>0?{CacheBehaviors:fr}:{},...Bt&&Rt?{Aliases:[Bt]}:{},ViewerCertificate:Wi,PriceClass:"PriceClass_100",HttpVersion:Se.http3?"http2and3":"http2"}}};if(Ht(Fn.Properties.DistributionConfig,`infrastructure.cdn.${St}`),this.builder.addResource(Nt,Fn),ot&&Bt&&Rt){let On=Bt.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${On}CdnARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[Nt,...Ne&&!ie?[Ne]:[]],Properties:{HostedZoneId:ot,Name:Bt,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:{"Fn::GetAtt":[Nt,"DomainName"]}}}})}}if(this.mergedConfig.infrastructure?.queues)for(let[St,Se]of Object.entries(this.mergedConfig.infrastructure.queues)){if(!this.shouldDeploy(Se))continue;let{queue:Bt,logicalId:ie}=M.createQueue({slug:l,environment:S,name:`${l}-${S}-${St}`,fifo:Se.fifo,visibilityTimeout:Se.visibilityTimeout,messageRetentionPeriod:Se.messageRetentionPeriod,delaySeconds:Se.delaySeconds,maxMessageSize:Se.maxMessageSize,receiveMessageWaitTime:Se.receiveMessageWaitTime,contentBasedDeduplication:Se.contentBasedDeduplication,encrypted:Se.encrypted,kmsKeyId:Se.kmsKeyId});this.builder.addResource(ie,Bt);let Rt;if(Se.deadLetterQueue){let{deadLetterQueue:Nt,updatedSourceQueue:er,deadLetterLogicalId:lr}=M.createDeadLetterQueue(ie,{slug:l,environment:S,maxReceiveCount:Se.maxReceiveCount});Rt=lr,this.builder.addResource(lr,Nt);let Cr=this.builder.getResources()[ie];if(Cr?.Properties)Cr.Properties.RedrivePolicy=er.Properties?.RedrivePolicy}if(Se.trigger){let Nt=Se.trigger,er=`${l}${S}${Nt.functionName}`.replace(/[^a-zA-Z0-9]/g,""),lr={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:{"Fn::GetAtt":[ie,"Arn"]},FunctionName:{Ref:er},BatchSize:Nt.batchSize||10,MaximumBatchingWindowInSeconds:Nt.batchWindow||0,Enabled:!0,...Nt.reportBatchItemFailures!==!1&&{FunctionResponseTypes:["ReportBatchItemFailures"]},...Nt.maxConcurrency&&{ScalingConfig:{MaximumConcurrency:Nt.maxConcurrency}},...Nt.filterPattern&&{FilterCriteria:{Filters:[{Pattern:JSON.stringify(Nt.filterPattern)}]}}},DependsOn:[ie,er]};this.builder.addResource(`${ie}Trigger`,lr)}if(Se.alarms?.enabled){let Nt=Se.alarms,er=Nt.notificationTopicArn;if(!er&&Nt.notificationEmails?.length){let Cr=`${ie}AlarmTopic`;this.builder.addResource(Cr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${S}-${St}-alarms`,DisplayName:`${St} Queue Alarms`}}),Nt.notificationEmails.forEach((vr,an)=>{this.builder.addResource(`${Cr}Sub${an}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:Cr},Protocol:"email",Endpoint:vr}})}),er={Ref:Cr}}let lr=Nt.queueDepthThreshold||1000;this.builder.addResource(`${ie}DepthAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-${St}-queue-depth`,AlarmDescription:`Queue ${St} depth exceeds ${lr} messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:lr,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[ie,"QueueName"]}}],...er&&{AlarmActions:[er],OKActions:[er]}}});let fr=Nt.messageAgeThreshold||3600;if(this.builder.addResource(`${ie}AgeAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-${St}-message-age`,AlarmDescription:`Queue ${St} oldest message exceeds ${fr} seconds`,MetricName:"ApproximateAgeOfOldestMessage",Namespace:"AWS/SQS",Statistic:"Maximum",Period:300,EvaluationPeriods:2,Threshold:fr,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[ie,"QueueName"]}}],...er&&{AlarmActions:[er],OKActions:[er]}}}),Rt&&Nt.dlqAlarm!==!1)this.builder.addResource(`${Rt}Alarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-${St}-dlq-messages`,AlarmDescription:`Dead letter queue for ${St} has messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Sum",Period:300,EvaluationPeriods:1,Threshold:0,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[Rt,"QueueName"]}}],...er&&{AlarmActions:[er]}}})}if(Se.subscribe){let Nt=Se.subscribe,er=Nt.topicArn;if(!er&&Nt.topicName)er={Ref:Nt.topicName};if(er){this.builder.addResource(`${ie}SnsPolicy`,{Type:"AWS::SQS::QueuePolicy",Properties:{Queues:[{Ref:ie}],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"sns.amazonaws.com"},Action:"sqs:SendMessage",Resource:{"Fn::GetAtt":[ie,"Arn"]},Condition:{ArnEquals:{"aws:SourceArn":er}}}]}}});let lr={TopicArn:er,Protocol:"sqs",Endpoint:{"Fn::GetAtt":[ie,"Arn"]},RawMessageDelivery:Nt.rawMessageDelivery||!1};if(Nt.filterPolicy)lr.FilterPolicy=Nt.filterPolicy,lr.FilterPolicyScope=Nt.filterPolicyScope||"MessageAttributes";this.builder.addResource(`${ie}SnsSub`,{Type:"AWS::SNS::Subscription",Properties:lr,DependsOn:`${ie}SnsPolicy`})}}}if(this.mergedConfig.infrastructure?.realtime?.enabled)if((this.mergedConfig.infrastructure.realtime.mode||"serverless")==="server")this.generateRealtimeServerResources(l,S);else this.generateRealtimeResources(l,S);let Pt=this.mergedConfig.infrastructure?.redirects;if(Pt){let St=Pt.target||this.mergedConfig.infrastructure?.dns?.domain||"",Se=Pt.protocol||"https";if(Pt.domains?.length&&St)for(let Bt of Pt.domains){let{bucket:ie,bucketPolicy:Rt,logicalId:Nt,policyLogicalId:er}=gt.createDomainRedirectBucket({slug:l,environment:S,sourceDomain:Bt,targetDomain:St,protocol:Se});this.builder.addResource(Nt,ie),this.builder.addResource(er,Rt)}if(Pt.paths&&Object.keys(Pt.paths).length>0){let Bt=gt.fromMapping(Pt.paths,{statusCode:Pt.statusCode||301}),{function:ie,logicalId:Rt}=gt.createPathRedirectFunction({slug:l,environment:S,rules:Bt});this.builder.addResource(Rt,ie)}}if(this.mergedConfig.infrastructure?.monitoring?.alarms)for(let[St,Se]of Object.entries(this.mergedConfig.infrastructure.monitoring.alarms)){let{alarm:Bt,logicalId:ie}=co.createAlarm({slug:l,environment:S,alarmName:`${l}-${S}-${St}`,metricName:Se.metricName||"Errors",namespace:Se.namespace||"AWS/Lambda",threshold:Se.threshold||1,comparisonOperator:Se.comparisonOperator||"GreaterThanThreshold"});this.builder.addResource(ie,Bt)}let st=this.mergedConfig.infrastructure?.cache;if(st){let St=st.type||"redis";if(St==="redis"){this.generateNetworkInfrastructure(l,S);let Se=st.redis||{},{replicationGroup:Bt,subnetGroup:ie,logicalId:Rt,subnetGroupId:Nt}=ao.createRedis({slug:l,environment:S,nodeType:Se.nodeType||st.nodeType||"cache.t3.micro",engineVersion:Se.engineVersion||"7.1",port:Se.port||6379,numCacheClusters:Se.numCacheNodes||2,automaticFailover:Se.automaticFailoverEnabled!==!1,atRestEncryption:!0,transitEncryption:!0,snapshotRetentionDays:Se.snapshotRetentionLimit||7,snapshotWindow:Se.snapshotWindow,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(Rt,Bt),ie&&Nt)this.builder.addResource(Nt,ie);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[Rt,"PrimaryEndPoint.Address"]},Description:"Redis primary endpoint address"}),this.builder.addOutput("CachePort",{Value:{"Fn::GetAtt":[Rt,"PrimaryEndPoint.Port"]},Description:"Redis primary endpoint port"})}else if(St==="memcached"){this.generateNetworkInfrastructure(l,S);let Se=st.elasticache||{},{cluster:Bt,subnetGroup:ie,logicalId:Rt,subnetGroupId:Nt}=ao.createMemcached({slug:l,environment:S,nodeType:Se.nodeType||st.nodeType||"cache.t3.micro",engineVersion:Se.engineVersion||"1.6.22",numCacheNodes:Se.numCacheNodes||2,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(Rt,Bt),ie&&Nt)this.builder.addResource(Nt,ie);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[Rt,"ConfigurationEndpoint.Address"]},Description:"Memcached configuration endpoint address"})}}let ur=this.mergedConfig.infrastructure?.email;if(ur){let St=ur.domain||this.mergedConfig.infrastructure?.dns?.domain;if(St){let{emailIdentity:Se,logicalId:Bt}=m.verifyDomain({domain:St,slug:l,environment:S,enableDkim:ur.enableDkim!==!1,dkimKeyLength:ur.dkimKeyLength||"RSA_2048_BIT"});if(this.builder.addResource(Bt,Se),ur.configurationSet!==!1){let{configurationSet:Nt,logicalId:er}=m.createConfigurationSet({slug:l,environment:S});this.builder.addResource(er,Nt)}let ie=ur.hostedZoneId||this.mergedConfig.infrastructure?.dns?.hostedZoneId;if(ie){if(ur.enableDkim!==!1)for(let Cr=1;Cr<=3;Cr++){let vr=`DkimRecord${Cr}${St.replace(/\./g,"")}`;this.builder.addResource(vr,{Type:"AWS::Route53::RecordSet",DependsOn:[Bt],Properties:{HostedZoneId:ie,Name:{"Fn::GetAtt":[Bt,`DkimDNSTokenName${Cr}`]},Type:"CNAME",TTL:1800,ResourceRecords:[{"Fn::GetAtt":[Bt,`DkimDNSTokenValue${Cr}`]}]}})}let{record:Nt,logicalId:er}=m.createSpfRecord(St,ie);this.builder.addResource(er,Nt);let{record:lr,logicalId:fr}=m.createDmarcRecord(St,ie,{policy:"none",reportingEmail:ur.dmarcReportingEmail||`dmarc-reports@${St}`});this.builder.addResource(fr,lr)}this.builder.addOutput("EmailDomain",{Value:St,Description:"SES verified email domain"});let Rt=ur.server;if(Rt?.enabled&&ie){let Nt=this.mergedConfig.environments[S]?.region||this.mergedConfig.project.region||"us-east-1",er=`${l}-${S}-email`,{role:lr,policy:fr,roleLogicalId:Cr,policyLogicalId:vr}=m.createEmailLambdaRole({slug:l,environment:S,s3BucketArn:`arn:aws:s3:::${er}`,sesIdentityArn:`arn:aws:ses:${Nt}:*:identity/${St}`});this.builder.addResource(Cr,lr),this.builder.addResource(vr,fr);let{function:an,permission:br,logicalId:Wi,permissionLogicalId:wn}=m.createInboundEmailLambda({slug:l,environment:S,roleArn:{"Fn::GetAtt":[Cr,"Arn"]},s3BucketName:er,organizedPrefix:"mailboxes/"});this.builder.addResource(Wi,an),this.builder.addResource(wn,br);let Fn=m.createInboundEmailSetup({slug:l,environment:S,domain:St,s3BucketName:er,s3KeyPrefix:"inbox/",region:Nt,hostedZoneId:ie,lambdaFunctionArn:{"Fn::GetAtt":[Wi,"Arn"]}});for(let[pn,Hn]of Object.entries(Fn.resources)){if(Hn.Type==="AWS::SES::ReceiptRule")Hn.DependsOn=[wn,Wi];this.builder.addResource(pn,Hn)}this.builder.addOutput("InboundEmailLambda",{Value:{Ref:Wi},Description:"Inbound email processing Lambda function"}),this.builder.addOutput("EmailBucket",{Value:er,Description:"S3 bucket for email storage"});let On=this.serverEipLogicalIds.get("app");if(On&&ie){let Hn=`${Rt?.subdomain||"mail"}.${St}`,Jn=Hn.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Jn}ARecord`,{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:ie,Name:Hn,Type:"A",TTL:"300",ResourceRecords:[{Ref:On}]}})}this.builder.addOutput("MailHost",{Value:`mail.${St}`,Description:"Mail server hostname for SMTP/IMAP clients"})}}}let pr=this.mergedConfig.infrastructure?.search;if(pr){let St=pr.vpc?{subnetIds:[{Ref:"PublicSubnet1"}],securityGroupIds:[]}:void 0;if(St)this.generateNetworkInfrastructure(l,S);let{domain:Se,logicalId:Bt}=qt.createDomain({slug:l,environment:S,engineVersion:pr.engineVersion||"OpenSearch_2.11",instanceType:pr.instanceType||"t3.small.search",instanceCount:pr.instanceCount||1,volumeSize:pr.volumeSize||10,volumeType:pr.volumeType||"gp3",dedicatedMaster:pr.dedicatedMaster||!1,dedicatedMasterType:pr.dedicatedMasterType,dedicatedMasterCount:pr.dedicatedMasterCount||3,multiAz:pr.multiAz||!1,encryption:pr.encryption||{atRest:!0,nodeToNode:!0},advancedSecurity:pr.advancedSecurity,autoTune:pr.autoTune!==!1,vpc:St});this.builder.addResource(Bt,Se),this.builder.addOutput("SearchDomainEndpoint",{Value:{"Fn::GetAtt":[Bt,"DomainEndpoint"]},Description:"OpenSearch domain endpoint"}),this.builder.addOutput("SearchDomainArn",{Value:{"Fn::GetAtt":[Bt,"Arn"]},Description:"OpenSearch domain ARN"})}let gr=this.mergedConfig.infrastructure?.fileSystem;if(gr&&Object.keys(gr).length>0){this.generateNetworkInfrastructure(l,S);for(let[St,Se]of Object.entries(gr)){let{fileSystem:Bt,logicalId:ie}=qe.createFileSystem({slug:`${l}-${St}`,environment:S,encrypted:Se.encrypted!==!1,performanceMode:Se.performanceMode||"generalPurpose",throughputMode:Se.throughputMode||"bursting",enableBackup:!0});this.builder.addResource(ie,Bt);let{securityGroup:Rt,logicalId:Nt}=qe.createEfsSecurityGroup({slug:`${l}-${St}`,environment:S,vpcId:{Ref:"VPC"},sourceCidrBlocks:["10.0.0.0/16"]});this.builder.addResource(Nt,Rt);let{mountTargets:er,logicalIds:lr}=qe.createMultiAzMountTargets(ie,{slug:`${l}-${St}`,environment:S,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],securityGroupId:{Ref:Nt}});for(let fr=0;fr<er.length;fr++)this.builder.addResource(lr[fr],er[fr]);this.builder.addOutput(`${St}FileSystemId`,{Value:{Ref:ie},Description:`EFS file system ID for ${St}`})}}let Dt=this.mergedConfig.infrastructure?.ai;if(Dt){let St=Dt.service||"ecs",Se=Dt.models||["*"],Bt=Dt.allowStreaming!==!1,ie;if(St==="ecs")ie=we.enableBedrockForEcs({slug:l,environment:S,models:Se,allowStreaming:Bt});else if(St==="ec2")ie=we.enableBedrockForEc2({slug:l,environment:S,models:Se,allowStreaming:Bt});else if(St==="lambda")ie=we.enableBedrockForLambda({slug:l,environment:S,models:Se,allowStreaming:Bt});else ie=we.createBedrockRole(St,{slug:l,environment:S,models:Se,allowStreaming:Bt});if(this.builder.addResource(ie.logicalId,ie.role),Dt.allowAsync){let{policy:Rt,logicalId:Nt}=we.createBedrockPolicy({slug:l,environment:S,models:Se,allowStreaming:Bt,allowAsync:!0});this.builder.addResource(Nt,Rt)}this.builder.addOutput("BedrockRoleArn",{Value:{"Fn::GetAtt":[ie.logicalId,"Arn"]},Description:"IAM role ARN with Bedrock permissions"})}}generateRealtimeResources(l,S){let P=this.mergedConfig.infrastructure?.realtime;if(!P)return;let v=P.name||`${l}-${S}-realtime`,E=P.scaling||{},ot=P.storage||{type:"dynamodb"},Ie=E.handlerMemory||256,Ne=E.handlerTimeout||30,nt=`${l}${S}RealtimeConnections`.replace(/[^a-zA-Z0-9]/g,""),Pt=`${l}${S}RealtimeChannels`.replace(/[^a-zA-Z0-9]/g,"");if(ot.type==="dynamodb"){let lr=ot.dynamodb||{},fr=lr.billingMode||"PAY_PER_REQUEST";this.builder.addResource(nt,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${l}-${S}-realtime-connections`,BillingMode:fr,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"},...fr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:lr.readCapacity||5,WriteCapacityUnits:lr.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...fr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:lr.readCapacity||5,WriteCapacityUnits:lr.writeCapacity||5}},...lr.pointInTimeRecovery&&{PointInTimeRecoverySpecification:{PointInTimeRecoveryEnabled:!0}},Tags:[{Key:"Name",Value:`${l}-${S}-realtime-connections`},{Key:"Environment",Value:S}]}}),this.builder.addResource(Pt,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${l}-${S}-realtime-channels`,BillingMode:fr,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"},...fr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:lr.readCapacity||5,WriteCapacityUnits:lr.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...fr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:lr.readCapacity||5,WriteCapacityUnits:lr.writeCapacity||5}},Tags:[{Key:"Name",Value:`${l}-${S}-realtime-channels`},{Key:"Environment",Value:S}]}})}let st=`${l}${S}RealtimeRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(st,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${S}-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":[nt,"Arn"]},{"Fn::Sub":`\${${nt}.Arn}/index/*`},{"Fn::GetAtt":[Pt,"Arn"]},{"Fn::Sub":`\${${Pt}.Arn}/index/*`}]},{Effect:"Allow",Action:"execute-api:ManageConnections",Resource:{"Fn::Sub":"arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:*/*"}}]}}]}});let ur=`${l}${S}RealtimeConnect`.replace(/[^a-zA-Z0-9]/g,""),pr=`${l}${S}RealtimeDisconnect`.replace(/[^a-zA-Z0-9]/g,""),gr=`${l}${S}RealtimeMessage`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ur,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${S}-realtime-connect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[st,"Arn"]},MemorySize:Ie,Timeout:Ne,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:nt},CHANNELS_TABLE:{Ref:Pt},ENVIRONMENT:S}},Code:{ZipFile:this.generateConnectHandlerCode()}},DependsOn:[st,nt]}),this.builder.addResource(pr,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${S}-realtime-disconnect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[st,"Arn"]},MemorySize:Ie,Timeout:Ne,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:nt},CHANNELS_TABLE:{Ref:Pt},ENVIRONMENT:S}},Code:{ZipFile:this.generateDisconnectHandlerCode()}},DependsOn:[st,nt,Pt]}),this.builder.addResource(gr,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${S}-realtime-message`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[st,"Arn"]},MemorySize:Ie,Timeout:Ne,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:nt},CHANNELS_TABLE:{Ref:Pt},ENVIRONMENT:S}},Code:{ZipFile:this.generateMessageHandlerCode()}},DependsOn:[st,nt,Pt]});let Dt=`${l}${S}RealtimeApi`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Dt,{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:v,ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action",Tags:{Name:v,Environment:S}}});let St=`${ur}Permission`,Se=`${pr}Permission`,Bt=`${gr}Permission`;this.builder.addResource(St,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:ur},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Dt}}/*/$connect`}}}),this.builder.addResource(Se,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:pr},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Dt}}/*/$disconnect`}}}),this.builder.addResource(Bt,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:gr},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Dt}}/*/$default`}}});let ie=`${Dt}ConnectInteg`,Rt=`${Dt}DisconnectInteg`,Nt=`${Dt}MessageInteg`;this.builder.addResource(ie,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Dt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${ur}.Arn}/invocations`}}}),this.builder.addResource(Rt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Dt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${pr}.Arn}/invocations`}}}),this.builder.addResource(Nt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Dt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${gr}.Arn}/invocations`}}}),this.builder.addResource(`${Dt}ConnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Dt},RouteKey:"$connect",AuthorizationType:"NONE",Target:{"Fn::Sub":`integrations/\${${ie}}`}}}),this.builder.addResource(`${Dt}DisconnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Dt},RouteKey:"$disconnect",Target:{"Fn::Sub":`integrations/\${${Rt}}`}}}),this.builder.addResource(`${Dt}DefaultRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Dt},RouteKey:"$default",Target:{"Fn::Sub":`integrations/\${${Nt}}`}}});let er=`${Dt}Stage`;if(this.builder.addResource(er,{Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:{Ref:Dt},StageName:S,AutoDeploy:!0,DefaultRouteSettings:{ThrottlingBurstLimit:E.messagesPerSecond||1000,ThrottlingRateLimit:E.messagesPerSecond||1000}}}),P.monitoring?.enabled){let lr=P.monitoring,fr=lr.notificationTopicArn;if(!fr&&lr.notificationEmails?.length){let Cr=`${Dt}AlarmTopic`;this.builder.addResource(Cr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${S}-realtime-alarms`,DisplayName:"Realtime WebSocket Alarms"}}),lr.notificationEmails.forEach((vr,an)=>{this.builder.addResource(`${Cr}Sub${an}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:Cr},Protocol:"email",Endpoint:vr}})}),fr={Ref:Cr}}if(lr.connectionThreshold)this.builder.addResource(`${Dt}ConnectionAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-realtime-connections`,AlarmDescription:`WebSocket connections exceed ${lr.connectionThreshold}`,MetricName:"ConnectCount",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:300,EvaluationPeriods:2,Threshold:lr.connectionThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:Dt}}],...fr&&{AlarmActions:[fr]}}});if(lr.errorThreshold)this.builder.addResource(`${Dt}ErrorAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-realtime-errors`,AlarmDescription:`WebSocket errors exceed ${lr.errorThreshold}/min`,MetricName:"ExecutionError",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:60,EvaluationPeriods:3,Threshold:lr.errorThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:Dt}}],...fr&&{AlarmActions:[fr]}}})}this.builder.addOutput(`${Dt}Endpoint`,{Description:"WebSocket API endpoint URL",Value:{"Fn::Sub":`wss://\${${Dt}}.execute-api.\${AWS::Region}.amazonaws.com/${S}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}}),this.builder.addOutput(`${Dt}Id`,{Description:"WebSocket API ID",Value:{Ref:Dt},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-api-id"}}})}generateConnectHandlerCode(){return`
13
+ `:nr,ot=T.map(([,Bt])=>Bt.port).filter((Bt)=>typeof Bt==="number"&&![80,443].includes(Bt)),_=this.resolveApiOriginPort(),kt=`${l}${h}DeployBucket`.replace(/[^a-zA-Z0-9]/g,""),N=`${l}-${h}-deploy`;this.builder.addResource(kt,{Type:"AWS::S3::Bucket",Properties:{BucketName:N,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 ct=a.createServerModeStack({slug:`${l}-app`,environment:h,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},instanceType:_e,keyName:C.allowSsh?`${l}-${h}`:void 0,domain:oe,userData:dt,volumeSize:C.disk?.size||20,imageId:C.image,allowedPorts:[...C.allowSsh?[22]:[],80,443,_,...ot]}),vt=ct.resources[ct.outputs.instanceLogicalId];if(vt?.Properties){let Bt=vt.Properties.Tags||[];vt.Properties.Tags=[...Bt,{Key:"Project",Value:l},{Key:"Environment",Value:h},{Key:"Role",Value:"app"},{Key:"ManagedBy",Value:"ts-cloud"}]}let xt=ct.resources[ct.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:::${N}`,`arn:aws:s3:::${N}/*`]}]}});for(let[Bt,mr]of Object.entries(ct.resources))this.builder.addResource(Bt,mr);this.builder.addOutput("deployBucketName",{Value:{Ref:kt},Description:"S3 bucket where release tarballs are uploaded"}),this.builder.addOutput("appInstanceId",{Value:{Ref:ct.outputs.instanceLogicalId},Description:"EC2 instance ID for the app server"}),this.builder.addOutput("appPublicIp",{Value:{Ref:ct.outputs.eipLogicalId},Description:"Public IP for the app server"}),this.serverEipLogicalIds.set("app",ct.outputs.eipLogicalId),this.serverEipLogicalIds.set("appInstance",ct.outputs.instanceLogicalId)}generateJumpBox(l,h){let C=this.mergedConfig.infrastructure?.jumpBox;if(!C)return;let b=C===!0?{}:C;if(b.enabled===!1)return;this.generateNetworkInfrastructure(l,h);let T=b.size||"micro",oe=a.InstanceSize.specs[T]?.instanceType||T||"t3.micro",ae;if(b.mountEfs)ae={fileSystemId:typeof b.mountEfs==="string"?b.mountEfs:{Ref:"FileSystem"},mountPath:b.mountPath||"/mnt/efs"};let be;if(b.databaseTools)be=a.JumpBox.withDatabaseTools({slug:l,environment:h,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:b.keyName||`${l}-${h}`,allowedCidrs:b.allowedCidrs});else if(ae)be=a.JumpBox.withEfsMount({slug:l,environment:h,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:b.keyName||`${l}-${h}`,fileSystemId:ae.fileSystemId,mountPath:ae.mountPath,allowedCidrs:b.allowedCidrs});else be=a.createJumpBox({slug:l,environment:h,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:b.keyName||`${l}-${h}`,instanceType:oe,allowedCidrs:b.allowedCidrs,mountEfs:ae});for(let[lt,_e]of Object.entries(be.resources))this.builder.addResource(lt,_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 C=this.mergedConfig.infrastructure?.ssl,b=this.mergedConfig.infrastructure?.dns,T=b?.domain,Ee=b?.hostedZoneId,oe=[],ae,be;if(C?.certificateArn)be=C.certificateArn;else if(C?.enabled&&T&&Ee){let ot=C.domains||[T],_=ot[0],kt=ot.slice(1).map((vt)=>{if(vt.includes(".")&&vt.endsWith(_))return vt.replace(`.${_}`,"");return vt}),{certificate:N,logicalId:ct}=S.createCertificate({domain:_,subdomains:kt,slug:l,environment:h,validationMethod:"DNS",hostedZoneId:Ee});ae=ct,this.builder.addResource(ct,N)}if(this.mergedConfig.infrastructure?.storage){let ot=Object.entries(this.mergedConfig.infrastructure.storage).some(([,N])=>N.website),_;if(ot&&(ae||be))_=`${l}${h}CloudFrontOAC`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(_,{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 kt=Object.entries(this.mergedConfig.infrastructure.storage).map(([N,ct])=>({name:N,config:ct,mountPath:this.normalizeMountPath(ct),rewriteStyle:ct.pathRewriteStyle||"directory",logicalId:this.storageBucketLogicalId(l,h,N)})).filter((N)=>N.name!=="public"&&N.config.website&&N.mountPath);for(let[N,ct]of Object.entries(this.mergedConfig.infrastructure.storage)){let vt=!!(ct.website&&_),xt=this.storageBucketName(l,h,N),{bucket:Bt,logicalId:mr}=Re.createBucket({slug:l,name:N,environment:h,bucketName:xt,versioning:ct.versioning,encryption:ct.encryption,public:vt?!1:ct.public}),gr=this.normalizeMountPath(ct),Rr;if(ct.failover){let hr=`infrastructure.storage.${N}`;if(!vt||!T||gr&&N!=="public")throw Error(`${hr}.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(Rr=yg({failover:ct.failover,primaryBucket:xt,primaryRegion:this.mergedConfig.project.region||"us-east-1",where:hr}),Rr.replicate&&Bt.Properties){let Ir=`${mr}FailoverReplicationRole`;this.builder.addResource(Ir,Sg({primaryBucket:xt,replicaBucket:Rr.replicaBucket}));let ei=Bt.Properties;ei.VersioningConfiguration={Status:"Enabled"},ei.ReplicationConfiguration=Cg({replicaBucket:Rr.replicaBucket,roleArn:{"Fn::GetAtt":[Ir,"Arn"]}})}}if(vt&&Bt.Properties)Bt.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1};if(this.builder.addResource(mr,Bt),ct.website){let hr=typeof ct.website==="object"?ct.website:{},Ir=Re.enableWebsiteHosting(Bt,hr.indexDocument||"index.html",hr.errorDocument);this.builder.addResource(mr,Ir)}let wr=this.normalizeMountPath(ct);if(vt&&_&&T&&!(wr&&N!=="public")){let hr=`${l}${h}${N}CDN`.replace(/[^a-zA-Z0-9]/g,""),Ir=[];if(ct.aliases&&ct.aliases.length>0)Ir.push(...ct.aliases);else if(N==="public"){if(Ir.push(T),C?.domains?.includes(`www.${T}`))Ir.push(`www.${T}`)}else if(N==="docs")Ir.push(`docs.${T}`);else if(N==="blog")Ir.push(`blog.${T}`);let ei=typeof ct.website==="object"?ct.website:{},un=ct.spa===!0,Zi=ei.errorDocument||(un?"index.html":"404.html"),vr=[];if(un)vr.push({ErrorCode:403,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300});else vr.push({ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${Zi}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${Zi}`,ErrorCachingMinTTL:300});let fn=be&&Ir.length>0?{AcmCertificateArn:be,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:ae&&Ir.length>0?{AcmCertificateArn:{Ref:ae},SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},On=`S3-${l}-${h}-${N}`,ja=this.mergedConfig.project.region||"us-east-1",Nn;if(!un)Nn=`${l}${h}${N}UrlRewrite`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(Nn,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${h}-${N}-url-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`URL rewrite for ${l} ${h} ${N} - 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:On,DomainName:{"Fn::Sub":`\${${mr}}.s3.${ja}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:_}}],jn=[],as=[];if(this.shouldRouteStorageBucketToCompute(N,ct)){this.appendComputeAppOrigin(Fn,jn,as,l,h,this.resolveComputeCachePathPatterns(ct.computeRoutes));for(let Dr of kt){let Ia=`S3-${l}-${h}-${Dr.name}`,ps=`${l}${h}${Dr.name}PathMountRewrite`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ps,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${h}-${Dr.name}-path-mount-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`Path mount rewrite for ${l} ${h} ${Dr.name} at ${Dr.mountPath}`,Runtime:"cloudfront-js-2.0"},FunctionCode:this.pathMountRewriteFunctionCode(Dr.mountPath,Dr.rewriteStyle)}}),Fn.push({Id:Ia,DomainName:{"Fn::Sub":`\${${Dr.logicalId}}.s3.${ja}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:_}}),as.push(Dr.logicalId,ps);for(let vc of[Dr.mountPath,`${Dr.mountPath}/*`])jn.push({PathPattern:vc,TargetOriginId:Ia,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":[ps,"FunctionARN"]}}]})}}let Ca,sc=On;if(Rr){let Dr=`${On}-failover`;Object.assign(Fn[0],Rr.primaryConnection),Fn.push({Id:Dr,DomainName:Ig(Rr.replicaBucket,Rr.replicaRegion),OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:_}}),Ca=Gr({primaryOriginId:On,secondaryOriginId:Dr,statusCodes:Rr.statusCodes}),sc=Ca.Items[0].Id}let cs={Type:"AWS::CloudFront::Distribution",DependsOn:[mr,_,...Nn?[Nn]:[],...as],Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${h} ${N} site`,DefaultRootObject:"index.html",Origins:Fn,...Ca?{OriginGroups:Ca}:{},DefaultCacheBehavior:{TargetOriginId:sc,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...Nn?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[Nn,"FunctionARN"]}}]}:{}},...jn.length>0?{CacheBehaviors:jn}:{},...Ir.length>0?{Aliases:Ir}:{},ViewerCertificate:fn,PriceClass:"PriceClass_100",HttpVersion:"http2and3",IPV6Enabled:!0,CustomErrorResponses:vr}}};if(ae)cs.DependsOn.push(ae);if(Rr)Vt(cs.Properties.DistributionConfig,`infrastructure.storage.${N}`),this.storageFailoverReplicas.push({name:N,primaryBucket:xt,primaryRegion:ja,replicaBucket:Rr.replicaBucket,replicaRegion:Rr.replicaRegion,replicate:Rr.replicate,distributionArnOutput:`${N}CloudFrontDistributionArn`}),this.builder.addOutput(`${N}CloudFrontDistributionArn`,{Value:{"Fn::Sub":`arn:\${AWS::Partition}:cloudfront::\${AWS::AccountId}:distribution/\${${hr}}`},Description:`CloudFront distribution ARN for ${N} (scopes the bucket policy of the failover replica)`}),this.builder.addOutput(`${N}FailoverBucketName`,{Value:Rr.replicaBucket,Description:`Failover replica bucket for ${N} (${Rr.replicaRegion}), outside this stack`});this.builder.addResource(hr,cs);let Tc=`${mr}CloudFrontPolicy`;if(this.builder.addResource(Tc,{Type:"AWS::S3::BucketPolicy",DependsOn:[mr,hr],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/\${${hr}}`}}}}]}}}),this.shouldRouteStorageBucketToCompute(N,ct))for(let Dr of kt){let Ia=`${Dr.logicalId}CloudFrontPolicy`;this.builder.addResource(Ia,{Type:"AWS::S3::BucketPolicy",DependsOn:[Dr.logicalId,hr],Properties:{Bucket:{Ref:Dr.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:::\${${Dr.logicalId}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${hr}}`}}}}]}}})}if(Ir.length>0)oe.push({name:N,bucketLogicalId:mr,distLogicalId:hr,oacLogicalId:_,aliases:Ir});this.builder.addOutput(`${N}CloudFrontDomain`,{Value:{"Fn::GetAtt":[hr,"DomainName"]},Description:`CloudFront domain for ${N}`}),this.builder.addOutput(`${N}CloudFrontDistributionId`,{Value:{Ref:hr},Description:`CloudFront distribution ID for ${N}`})}if(this.builder.addOutput(`${N}BucketName`,{Value:{Ref:mr},Description:`S3 bucket name for ${N}`}),N==="public")this.builder.addOutput("FrontendBucketName",{Value:{Ref:mr},Description:"Frontend S3 bucket name"});if(N==="docs")this.builder.addOutput("DocsBucketName",{Value:{Ref:mr},Description:"Documentation S3 bucket name"});if(N==="blog")this.builder.addOutput("BlogBucketName",{Value:{Ref:mr},Description:"Blog S3 bucket name"})}}if(this.mergedConfig.infrastructure?.sftp){let ot=this.mergedConfig.infrastructure.sftp,_=_d.create({...ot,storage:this.resolveSftpStorage(ot,l,h)??ot.storage,slug:l,environment:h});for(let[kt,N]of Object.entries(_.resources))this.builder.addResource(kt,N);this.builder.addOutput("SftpServerId",{Value:{Ref:_.serverLogicalId},Description:"AWS Transfer Family SFTP server ID"}),this.builder.addOutput("SftpEndpoint",{Value:{"Fn::Sub":`\${${_.serverLogicalId}}.server.transfer.\${AWS::Region}.amazonaws.com`},Description:"AWS Transfer Family SFTP endpoint"}),this.builder.addOutput("SftpStorageDomain",{Value:_.domain,Description:"Storage backing the SFTP server (EFS or S3)"})}if(Ee&&oe.length>0)for(let{name:ot,distLogicalId:_,aliases:kt}of oe)for(let N of kt){let ct=N.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${ct}ARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[_],Properties:{HostedZoneId:Ee,Name:N,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[_,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}}),this.builder.addResource(`${ct}AAAARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[_],Properties:{HostedZoneId:Ee,Name:N,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":[_,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}})}if(this.mergedConfig.infrastructure?.databases){for(let[ot,_]of Object.entries(this.mergedConfig.infrastructure.databases))if(_.engine==="dynamodb"){let{table:kt,logicalId:N}=jt.createTable({slug:l,environment:h,tableName:`${l}-${h}-${ot}`,partitionKey:_.partitionKey||{name:"id",type:"S"},sortKey:_.sortKey});this.builder.addResource(N,kt)}else if(_.engine==="postgres"){let{dbInstance:kt,logicalId:N}=jt.createPostgres({slug:l,environment:h,dbInstanceIdentifier:`${l}-${h}-${ot}`,masterUsername:_.username||"admin",masterUserPassword:_.password||"changeme123",allocatedStorage:_.storage||20,dbInstanceClass:_.instanceClass||"db.t3.micro"});this.builder.addResource(N,kt)}else if(_.engine==="mysql"){let{dbInstance:kt,logicalId:N}=jt.createMysql({slug:l,environment:h,dbInstanceIdentifier:`${l}-${h}-${ot}`,masterUsername:_.username||"admin",masterUserPassword:_.password||"changeme123",allocatedStorage:_.storage||20,dbInstanceClass:_.instanceClass||"db.t3.micro"});this.builder.addResource(N,kt)}}if(this.mergedConfig.infrastructure?.cdn)for(let[ot,_]of Object.entries(this.mergedConfig.infrastructure.cdn)){if(!_.origin)continue;let kt=typeof _.customDomain==="string"?_.customDomain:_.customDomain?.domain||_.domain,N=typeof _.customDomain==="object"?_.customDomain?.certificateArn:_.certificateArn,ct=N||be,vt=`${l}${h}${ot}CDN`.replace(/[^a-zA-Z0-9]/g,""),xt=`S3-${l}-${h}-${ot}-cdn`,Bt=[{Id:xt,DomainName:_.origin,OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginShield:_.originShield?{Enabled:!0,OriginShieldRegion:_.originShieldRegion||this.mergedConfig.environments[h]?.region||this.mergedConfig.project.region||"us-east-1"}:{Enabled:!1},...De(_,`infrastructure.cdn.${ot}`)}],mr=[],gr=[],Rr=["GET","HEAD","OPTIONS"],wr=xt,hr;if(_.failoverOrigin){qt(Rr,`the default cache behavior of infrastructure.cdn.${ot}`);let Zi=`${xt}-failover`,vr=typeof _.failoverOrigin==="string"?{domain:_.failoverOrigin}:_.failoverOrigin;if(!vr.domain)throw Error(`infrastructure.cdn.${ot}.failoverOrigin.domain is required`);if(vr.domain===_.origin)throw Error(`infrastructure.cdn.${ot}: failoverOrigin must differ from origin (both are ${_.origin})`);Bt.push({Id:Zi,DomainName:vr.domain,OriginPath:vr.originPath||"",...Nd(vr.domain)?{S3OriginConfig:{OriginAccessIdentity:""}}:{CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"}},OriginShield:{Enabled:!1},...De(vr,`infrastructure.cdn.${ot}.failoverOrigin`)}),hr=Gr({primaryOriginId:xt,secondaryOriginId:Zi,statusCodes:_.failoverStatusCodes}),wr=hr.Items[0].Id}else if(_.failoverStatusCodes)throw Error(`infrastructure.cdn.${ot}: failoverStatusCodes needs failoverOrigin to fail over to`);if(_.routeCompute)this.appendComputeAppOrigin(Bt,mr,gr,l,h,this.resolveComputeCachePathPatterns(_.computeRoutes));let Ir=ct&&kt?{AcmCertificateArn:ae&&!N?{Ref:ae}:ct,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},ei=[...gr];if(ae&&!N&&kt)ei.push(ae);let un={Type:"AWS::CloudFront::Distribution",...ei.length>0?{DependsOn:ei}:{},Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${h} ${ot} CDN`,DefaultRootObject:"index.html",Origins:Bt,...hr?{OriginGroups:hr}:{},DefaultCacheBehavior:{TargetOriginId:wr,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:Rr,CachedMethods:["GET","HEAD","OPTIONS"],Compress:_.compress!==!1,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},...mr.length>0?{CacheBehaviors:mr}:{},...kt&&ct?{Aliases:[kt]}:{},ViewerCertificate:Ir,PriceClass:"PriceClass_100",HttpVersion:_.http3?"http2and3":"http2"}}};if(Vt(un.Properties.DistributionConfig,`infrastructure.cdn.${ot}`),this.builder.addResource(vt,un),Ee&&kt&&ct){let Zi=kt.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Zi}CdnARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[vt,...ae&&!N?[ae]:[]],Properties:{HostedZoneId:Ee,Name:kt,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:{"Fn::GetAtt":[vt,"DomainName"]}}}})}}if(this.mergedConfig.infrastructure?.queues)for(let[ot,_]of Object.entries(this.mergedConfig.infrastructure.queues)){if(!this.shouldDeploy(_))continue;let{queue:kt,logicalId:N}=U.createQueue({slug:l,environment:h,name:`${l}-${h}-${ot}`,fifo:_.fifo,visibilityTimeout:_.visibilityTimeout,messageRetentionPeriod:_.messageRetentionPeriod,delaySeconds:_.delaySeconds,maxMessageSize:_.maxMessageSize,receiveMessageWaitTime:_.receiveMessageWaitTime,contentBasedDeduplication:_.contentBasedDeduplication,encrypted:_.encrypted,kmsKeyId:_.kmsKeyId});this.builder.addResource(N,kt);let ct;if(_.deadLetterQueue){let{deadLetterQueue:vt,updatedSourceQueue:xt,deadLetterLogicalId:Bt}=U.createDeadLetterQueue(N,{slug:l,environment:h,maxReceiveCount:_.maxReceiveCount});ct=Bt,this.builder.addResource(Bt,vt);let gr=this.builder.getResources()[N];if(gr?.Properties)gr.Properties.RedrivePolicy=xt.Properties?.RedrivePolicy}if(_.trigger){let vt=_.trigger,xt=`${l}${h}${vt.functionName}`.replace(/[^a-zA-Z0-9]/g,""),Bt={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:{"Fn::GetAtt":[N,"Arn"]},FunctionName:{Ref:xt},BatchSize:vt.batchSize||10,MaximumBatchingWindowInSeconds:vt.batchWindow||0,Enabled:!0,...vt.reportBatchItemFailures!==!1&&{FunctionResponseTypes:["ReportBatchItemFailures"]},...vt.maxConcurrency&&{ScalingConfig:{MaximumConcurrency:vt.maxConcurrency}},...vt.filterPattern&&{FilterCriteria:{Filters:[{Pattern:JSON.stringify(vt.filterPattern)}]}}},DependsOn:[N,xt]};this.builder.addResource(`${N}Trigger`,Bt)}if(_.alarms?.enabled){let vt=_.alarms,xt=vt.notificationTopicArn;if(!xt&&vt.notificationEmails?.length){let gr=`${N}AlarmTopic`;this.builder.addResource(gr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${h}-${ot}-alarms`,DisplayName:`${ot} Queue Alarms`}}),vt.notificationEmails.forEach((Rr,wr)=>{this.builder.addResource(`${gr}Sub${wr}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:gr},Protocol:"email",Endpoint:Rr}})}),xt={Ref:gr}}let Bt=vt.queueDepthThreshold||1000;this.builder.addResource(`${N}DepthAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${h}-${ot}-queue-depth`,AlarmDescription:`Queue ${ot} 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":[N,"QueueName"]}}],...xt&&{AlarmActions:[xt],OKActions:[xt]}}});let mr=vt.messageAgeThreshold||3600;if(this.builder.addResource(`${N}AgeAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${h}-${ot}-message-age`,AlarmDescription:`Queue ${ot} 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":[N,"QueueName"]}}],...xt&&{AlarmActions:[xt],OKActions:[xt]}}}),ct&&vt.dlqAlarm!==!1)this.builder.addResource(`${ct}Alarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${h}-${ot}-dlq-messages`,AlarmDescription:`Dead letter queue for ${ot} has messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Sum",Period:300,EvaluationPeriods:1,Threshold:0,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[ct,"QueueName"]}}],...xt&&{AlarmActions:[xt]}}})}if(_.subscribe){let vt=_.subscribe,xt=vt.topicArn;if(!xt&&vt.topicName)xt={Ref:vt.topicName};if(xt){this.builder.addResource(`${N}SnsPolicy`,{Type:"AWS::SQS::QueuePolicy",Properties:{Queues:[{Ref:N}],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"sns.amazonaws.com"},Action:"sqs:SendMessage",Resource:{"Fn::GetAtt":[N,"Arn"]},Condition:{ArnEquals:{"aws:SourceArn":xt}}}]}}});let Bt={TopicArn:xt,Protocol:"sqs",Endpoint:{"Fn::GetAtt":[N,"Arn"]},RawMessageDelivery:vt.rawMessageDelivery||!1};if(vt.filterPolicy)Bt.FilterPolicy=vt.filterPolicy,Bt.FilterPolicyScope=vt.filterPolicyScope||"MessageAttributes";this.builder.addResource(`${N}SnsSub`,{Type:"AWS::SNS::Subscription",Properties:Bt,DependsOn:`${N}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 lt=this.mergedConfig.infrastructure?.redirects;if(lt){let ot=lt.target||this.mergedConfig.infrastructure?.dns?.domain||"",_=lt.protocol||"https";if(lt.domains?.length&&ot)for(let kt of lt.domains){let{bucket:N,bucketPolicy:ct,logicalId:vt,policyLogicalId:xt}=At.createDomainRedirectBucket({slug:l,environment:h,sourceDomain:kt,targetDomain:ot,protocol:_});this.builder.addResource(vt,N),this.builder.addResource(xt,ct)}if(lt.paths&&Object.keys(lt.paths).length>0){let kt=At.fromMapping(lt.paths,{statusCode:lt.statusCode||301}),{function:N,logicalId:ct}=At.createPathRedirectFunction({slug:l,environment:h,rules:kt});this.builder.addResource(ct,N)}}if(this.mergedConfig.infrastructure?.monitoring?.alarms)for(let[ot,_]of Object.entries(this.mergedConfig.infrastructure.monitoring.alarms)){let{alarm:kt,logicalId:N}=go.createAlarm({slug:l,environment:h,alarmName:`${l}-${h}-${ot}`,metricName:_.metricName||"Errors",namespace:_.namespace||"AWS/Lambda",threshold:_.threshold||1,comparisonOperator:_.comparisonOperator||"GreaterThanThreshold"});this.builder.addResource(N,kt)}let _e=this.mergedConfig.infrastructure?.cache;if(_e){let ot=_e.type||"redis";if(ot==="redis"){this.generateNetworkInfrastructure(l,h);let _=_e.redis||{},{replicationGroup:kt,subnetGroup:N,logicalId:ct,subnetGroupId:vt}=po.createRedis({slug:l,environment:h,nodeType:_.nodeType||_e.nodeType||"cache.t3.micro",engineVersion:_.engineVersion||"7.1",port:_.port||6379,numCacheClusters:_.numCacheNodes||2,automaticFailover:_.automaticFailoverEnabled!==!1,atRestEncryption:!0,transitEncryption:!0,snapshotRetentionDays:_.snapshotRetentionLimit||7,snapshotWindow:_.snapshotWindow,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(ct,kt),N&&vt)this.builder.addResource(vt,N);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[ct,"PrimaryEndPoint.Address"]},Description:"Redis primary endpoint address"}),this.builder.addOutput("CachePort",{Value:{"Fn::GetAtt":[ct,"PrimaryEndPoint.Port"]},Description:"Redis primary endpoint port"})}else if(ot==="memcached"){this.generateNetworkInfrastructure(l,h);let _=_e.elasticache||{},{cluster:kt,subnetGroup:N,logicalId:ct,subnetGroupId:vt}=po.createMemcached({slug:l,environment:h,nodeType:_.nodeType||_e.nodeType||"cache.t3.micro",engineVersion:_.engineVersion||"1.6.22",numCacheNodes:_.numCacheNodes||2,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(ct,kt),N&&vt)this.builder.addResource(vt,N);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[ct,"ConfigurationEndpoint.Address"]},Description:"Memcached configuration endpoint address"})}}let _t=this.mergedConfig.infrastructure?.email;if(_t){let ot=_t.domain||this.mergedConfig.infrastructure?.dns?.domain;if(ot){let{emailIdentity:_,logicalId:kt}=m.verifyDomain({domain:ot,slug:l,environment:h,enableDkim:_t.enableDkim!==!1,dkimKeyLength:_t.dkimKeyLength||"RSA_2048_BIT"});if(this.builder.addResource(kt,_),_t.configurationSet!==!1){let{configurationSet:vt,logicalId:xt}=m.createConfigurationSet({slug:l,environment:h});this.builder.addResource(xt,vt)}let N=_t.hostedZoneId||this.mergedConfig.infrastructure?.dns?.hostedZoneId;if(N){if(_t.enableDkim!==!1)for(let gr=1;gr<=3;gr++){let Rr=`DkimRecord${gr}${ot.replace(/\./g,"")}`;this.builder.addResource(Rr,{Type:"AWS::Route53::RecordSet",DependsOn:[kt],Properties:{HostedZoneId:N,Name:{"Fn::GetAtt":[kt,`DkimDNSTokenName${gr}`]},Type:"CNAME",TTL:1800,ResourceRecords:[{"Fn::GetAtt":[kt,`DkimDNSTokenValue${gr}`]}]}})}let{record:vt,logicalId:xt}=m.createSpfRecord(ot,N);this.builder.addResource(xt,vt);let{record:Bt,logicalId:mr}=m.createDmarcRecord(ot,N,{policy:"none",reportingEmail:_t.dmarcReportingEmail||`dmarc-reports@${ot}`});this.builder.addResource(mr,Bt)}this.builder.addOutput("EmailDomain",{Value:ot,Description:"SES verified email domain"});let ct=_t.server;if(ct?.enabled&&N){let vt=this.mergedConfig.environments[h]?.region||this.mergedConfig.project.region||"us-east-1",xt=`${l}-${h}-email`,{role:Bt,policy:mr,roleLogicalId:gr,policyLogicalId:Rr}=m.createEmailLambdaRole({slug:l,environment:h,s3BucketArn:`arn:aws:s3:::${xt}`,sesIdentityArn:`arn:aws:ses:${vt}:*:identity/${ot}`});this.builder.addResource(gr,Bt),this.builder.addResource(Rr,mr);let{function:wr,permission:hr,logicalId:Ir,permissionLogicalId:ei}=m.createInboundEmailLambda({slug:l,environment:h,roleArn:{"Fn::GetAtt":[gr,"Arn"]},s3BucketName:xt,organizedPrefix:"mailboxes/"});this.builder.addResource(Ir,wr),this.builder.addResource(ei,hr);let un=m.createInboundEmailSetup({slug:l,environment:h,domain:ot,s3BucketName:xt,s3KeyPrefix:"inbox/",region:vt,hostedZoneId:N,lambdaFunctionArn:{"Fn::GetAtt":[Ir,"Arn"]}});for(let[vr,fn]of Object.entries(un.resources)){if(fn.Type==="AWS::SES::ReceiptRule")fn.DependsOn=[ei,Ir];this.builder.addResource(vr,fn)}this.builder.addOutput("InboundEmailLambda",{Value:{Ref:Ir},Description:"Inbound email processing Lambda function"}),this.builder.addOutput("EmailBucket",{Value:xt,Description:"S3 bucket for email storage"});let Zi=this.serverEipLogicalIds.get("app");if(Zi&&N){let fn=`${ct?.subdomain||"mail"}.${ot}`,On=fn.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${On}ARecord`,{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:N,Name:fn,Type:"A",TTL:"300",ResourceRecords:[{Ref:Zi}]}})}this.builder.addOutput("MailHost",{Value:`mail.${ot}`,Description:"Mail server hostname for SMTP/IMAP clients"})}}}let nr=this.mergedConfig.infrastructure?.search;if(nr){let ot=nr.vpc?{subnetIds:[{Ref:"PublicSubnet1"}],securityGroupIds:[]}:void 0;if(ot)this.generateNetworkInfrastructure(l,h);let{domain:_,logicalId:kt}=zt.createDomain({slug:l,environment:h,engineVersion:nr.engineVersion||"OpenSearch_2.11",instanceType:nr.instanceType||"t3.small.search",instanceCount:nr.instanceCount||1,volumeSize:nr.volumeSize||10,volumeType:nr.volumeType||"gp3",dedicatedMaster:nr.dedicatedMaster||!1,dedicatedMasterType:nr.dedicatedMasterType,dedicatedMasterCount:nr.dedicatedMasterCount||3,multiAz:nr.multiAz||!1,encryption:nr.encryption||{atRest:!0,nodeToNode:!0},advancedSecurity:nr.advancedSecurity,autoTune:nr.autoTune!==!1,vpc:ot});this.builder.addResource(kt,_),this.builder.addOutput("SearchDomainEndpoint",{Value:{"Fn::GetAtt":[kt,"DomainEndpoint"]},Description:"OpenSearch domain endpoint"}),this.builder.addOutput("SearchDomainArn",{Value:{"Fn::GetAtt":[kt,"Arn"]},Description:"OpenSearch domain ARN"})}let fr=this.mergedConfig.infrastructure?.fileSystem;if(fr&&Object.keys(fr).length>0){this.generateNetworkInfrastructure(l,h);for(let[ot,_]of Object.entries(fr)){let{fileSystem:kt,logicalId:N}=ze.createFileSystem({slug:`${l}-${ot}`,environment:h,encrypted:_.encrypted!==!1,performanceMode:_.performanceMode||"generalPurpose",throughputMode:_.throughputMode||"bursting",enableBackup:!0});this.builder.addResource(N,kt);let{securityGroup:ct,logicalId:vt}=ze.createEfsSecurityGroup({slug:`${l}-${ot}`,environment:h,vpcId:{Ref:"VPC"},sourceCidrBlocks:["10.0.0.0/16"]});this.builder.addResource(vt,ct);let{mountTargets:xt,logicalIds:Bt}=ze.createMultiAzMountTargets(N,{slug:`${l}-${ot}`,environment:h,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],securityGroupId:{Ref:vt}});for(let mr=0;mr<xt.length;mr++)this.builder.addResource(Bt[mr],xt[mr]);this.builder.addOutput(`${ot}FileSystemId`,{Value:{Ref:N},Description:`EFS file system ID for ${ot}`})}}let dt=this.mergedConfig.infrastructure?.ai;if(dt){let ot=dt.service||"ecs",_=dt.models||["*"],kt=dt.allowStreaming!==!1,N;if(ot==="ecs")N=Pe.enableBedrockForEcs({slug:l,environment:h,models:_,allowStreaming:kt});else if(ot==="ec2")N=Pe.enableBedrockForEc2({slug:l,environment:h,models:_,allowStreaming:kt});else if(ot==="lambda")N=Pe.enableBedrockForLambda({slug:l,environment:h,models:_,allowStreaming:kt});else N=Pe.createBedrockRole(ot,{slug:l,environment:h,models:_,allowStreaming:kt});if(this.builder.addResource(N.logicalId,N.role),dt.allowAsync){let{policy:ct,logicalId:vt}=Pe.createBedrockPolicy({slug:l,environment:h,models:_,allowStreaming:kt,allowAsync:!0});this.builder.addResource(vt,ct)}this.builder.addOutput("BedrockRoleArn",{Value:{"Fn::GetAtt":[N.logicalId,"Arn"]},Description:"IAM role ARN with Bedrock permissions"})}}generateRealtimeResources(l,h){let C=this.mergedConfig.infrastructure?.realtime;if(!C)return;let b=C.name||`${l}-${h}-realtime`,T=C.scaling||{},Ee=C.storage||{type:"dynamodb"},oe=T.handlerMemory||256,ae=T.handlerTimeout||30,be=`${l}${h}RealtimeConnections`.replace(/[^a-zA-Z0-9]/g,""),lt=`${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(lt,{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":[lt,"Arn"]},{"Fn::Sub":`\${${lt}.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,""),nr=`${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:lt},ENVIRONMENT:h}},Code:{ZipFile:this.generateConnectHandlerCode()}},DependsOn:[_e,be]}),this.builder.addResource(nr,{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:lt},ENVIRONMENT:h}},Code:{ZipFile:this.generateDisconnectHandlerCode()}},DependsOn:[_e,be,lt]}),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:lt},ENVIRONMENT:h}},Code:{ZipFile:this.generateMessageHandlerCode()}},DependsOn:[_e,be,lt]});let dt=`${l}${h}RealtimeApi`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(dt,{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:b,ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action",Tags:{Name:b,Environment:h}}});let ot=`${_t}Permission`,_=`${nr}Permission`,kt=`${fr}Permission`;this.builder.addResource(ot,{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}:\${${dt}}/*/$connect`}}}),this.builder.addResource(_,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:nr},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${dt}}/*/$disconnect`}}}),this.builder.addResource(kt,{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}:\${${dt}}/*/$default`}}});let N=`${dt}ConnectInteg`,ct=`${dt}DisconnectInteg`,vt=`${dt}MessageInteg`;this.builder.addResource(N,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:dt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${_t}.Arn}/invocations`}}}),this.builder.addResource(ct,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:dt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${nr}.Arn}/invocations`}}}),this.builder.addResource(vt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:dt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${fr}.Arn}/invocations`}}}),this.builder.addResource(`${dt}ConnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:dt},RouteKey:"$connect",AuthorizationType:"NONE",Target:{"Fn::Sub":`integrations/\${${N}}`}}}),this.builder.addResource(`${dt}DisconnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:dt},RouteKey:"$disconnect",Target:{"Fn::Sub":`integrations/\${${ct}}`}}}),this.builder.addResource(`${dt}DefaultRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:dt},RouteKey:"$default",Target:{"Fn::Sub":`integrations/\${${vt}}`}}});let xt=`${dt}Stage`;if(this.builder.addResource(xt,{Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:{Ref:dt},StageName:h,AutoDeploy:!0,DefaultRouteSettings:{ThrottlingBurstLimit:T.messagesPerSecond||1000,ThrottlingRateLimit:T.messagesPerSecond||1000}}}),C.monitoring?.enabled){let Bt=C.monitoring,mr=Bt.notificationTopicArn;if(!mr&&Bt.notificationEmails?.length){let gr=`${dt}AlarmTopic`;this.builder.addResource(gr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${h}-realtime-alarms`,DisplayName:"Realtime WebSocket Alarms"}}),Bt.notificationEmails.forEach((Rr,wr)=>{this.builder.addResource(`${gr}Sub${wr}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:gr},Protocol:"email",Endpoint:Rr}})}),mr={Ref:gr}}if(Bt.connectionThreshold)this.builder.addResource(`${dt}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:dt}}],...mr&&{AlarmActions:[mr]}}});if(Bt.errorThreshold)this.builder.addResource(`${dt}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:dt}}],...mr&&{AlarmActions:[mr]}}})}this.builder.addOutput(`${dt}Endpoint`,{Description:"WebSocket API endpoint URL",Value:{"Fn::Sub":`wss://\${${dt}}.execute-api.\${AWS::Region}.amazonaws.com/${h}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}}),this.builder.addOutput(`${dt}Id`,{Description:"WebSocket API ID",Value:{Ref:dt},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
 
@@ -170,56 +170,56 @@ catch (error) {
170
170
  return { statusCode: 500, body: JSON.stringify({ error: 'Internal error' }) };
171
171
  }
172
172
  };
173
- `.trim()}generateRealtimeServerResources(l,S){let P=this.mergedConfig.infrastructure?.realtime;if(!P)return;let v=P.server||{},E=v.port||6001,ot=v.instances||1,Ie=`${l}${S}RealtimeSG`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ie,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`Security group for ${l} realtime WebSocket server`,GroupName:`${l}-${S}-realtime-sg`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:E,ToPort:E,CidrIp:"0.0.0.0/0",Description:"WebSocket connections"},{IpProtocol:"tcp",FromPort:443,ToPort:443,CidrIp:"0.0.0.0/0",Description:"HTTPS/WSS connections"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${l}-${S}-realtime-sg`},{Key:"Environment",Value:S}]}});let Ne=`${l}${S}RealtimeTaskDef`.replace(/[^a-zA-Z0-9]/g,""),nt=`${l}${S}RealtimeTaskRole`.replace(/[^a-zA-Z0-9]/g,""),Pt=`${l}${S}RealtimeExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Pt,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${S}-realtime-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"]}}),this.builder.addResource(nt,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${S}-realtime-task-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"RealtimeTaskPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogStream","logs:PutLogEvents"],Resource:"*"},...v.redis?.enabled?[{Effect:"Allow",Action:["elasticache:DescribeCacheClusters","elasticache:DescribeReplicationGroups"],Resource:"*"}]:[]]}}]}});let st=[{Name:"BROADCAST_HOST",Value:v.host||"0.0.0.0"},{Name:"BROADCAST_PORT",Value:String(E)},{Name:"NODE_ENV",Value:S==="production"?"production":"development"}];if(v.redis?.enabled){if(v.redis.useElastiCache)st.push({Name:"REDIS_HOST",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Address"]}}),st.push({Name:"REDIS_PORT",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Port"]}});else st.push({Name:"REDIS_HOST",Value:v.redis.host||"localhost"}),st.push({Name:"REDIS_PORT",Value:String(v.redis.port||6379)});if(v.redis.keyPrefix)st.push({Name:"REDIS_KEY_PREFIX",Value:v.redis.keyPrefix})}this.builder.addResource(Ne,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${l}-${S}-realtime`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:"512",Memory:"1024",ExecutionRoleArn:{"Fn::GetAtt":[Pt,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[nt,"Arn"]},ContainerDefinitions:[{Name:"realtime",Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${l}-realtime:latest`},Essential:!0,PortMappings:[{ContainerPort:E,Protocol:"tcp"}],Environment:st,LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":`/ecs/${l}-${S}-realtime`,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":"realtime"}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${E}${v.healthCheckPath||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${l}-${S}-realtime`},{Key:"Environment",Value:S}]},DependsOn:[Pt,nt]});let ur=`${l}${S}RealtimeLogs`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ur,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/ecs/${l}-${S}-realtime`,RetentionInDays:30}});let pr=`${l}${S}RealtimeService`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(pr,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${S}-realtime`,Cluster:{Ref:"ECSCluster"},TaskDefinition:{Ref:Ne},DesiredCount:ot,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:Ie}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},HealthCheckGracePeriodSeconds:60,Tags:[{Key:"Name",Value:`${l}-${S}-realtime`},{Key:"Environment",Value:S}]},DependsOn:[Ne,Ie,ur]}),v.autoScaling){let gr=v.autoScaling,Dt=`${l}${S}RealtimeScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(Dt,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:gr.max||10,MinCapacity:gr.min||1,ResourceId:{"Fn::Sub":`service/\${ECSCluster}/${l}-${S}-realtime`},RoleARN:{"Fn::Sub":"arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService"},ScalableDimension:"ecs:service:DesiredCount",ServiceNamespace:"ecs"},DependsOn:pr}),gr.targetCPU)this.builder.addResource(`${l}${S}RealtimeCPUPolicy`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${S}-realtime-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Dt},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:gr.targetCPU,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(P.monitoring?.enabled){let gr=P.monitoring,Dt=gr.notificationTopicArn;if(!Dt&&gr.notificationEmails?.length){let St=`${l}${S}RealtimeAlarmTopic`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(St,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${S}-realtime-alarms`,DisplayName:"Realtime Server Alarms"}}),gr.notificationEmails.forEach((Se,Bt)=>{this.builder.addResource(`${St}Sub${Bt}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:St},Protocol:"email",Endpoint:Se}})}),Dt={Ref:St}}this.builder.addResource(`${l}${S}RealtimeCPUAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-realtime-high-cpu`,AlarmDescription:"Realtime server CPU utilization is high",MetricName:"CPUUtilization",Namespace:"AWS/ECS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:80,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ClusterName",Value:{Ref:"ECSCluster"}},{Name:"ServiceName",Value:`${l}-${S}-realtime`}],...Dt&&{AlarmActions:[Dt]}},DependsOn:pr}),this.builder.addResource(`${l}${S}RealtimeMemoryAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-realtime-high-memory`,AlarmDescription:"Realtime server memory utilization is high",MetricName:"MemoryUtilization",Namespace:"AWS/ECS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:80,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ClusterName",Value:{Ref:"ECSCluster"}},{Name:"ServiceName",Value:`${l}-${S}-realtime`}],...Dt&&{AlarmActions:[Dt]}},DependsOn:pr})}this.builder.addOutput(`${l}${S}RealtimeEndpoint`.replace(/[^a-zA-Z0-9]/g,""),{Description:"Realtime WebSocket server endpoint",Value:{"Fn::Sub":`wss://${l}-${S}-realtime.\${AWS::Region}.elb.amazonaws.com:${E}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}})}generateBroadcastConfig(){let l=this.mergedConfig.infrastructure?.realtime;if(!l||l.mode!=="server")return"";let S=l.server||{};return`import type { BroadcastConfig } from 'ts-broadcasting'
173
+ `.trim()}generateRealtimeServerResources(l,h){let C=this.mergedConfig.infrastructure?.realtime;if(!C)return;let b=C.server||{},T=b.port||6001,Ee=b.instances||1,oe=`${l}${h}RealtimeSG`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(oe,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`Security group for ${l} realtime WebSocket server`,GroupName:`${l}-${h}-realtime-sg`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:T,ToPort:T,CidrIp:"0.0.0.0/0",Description:"WebSocket connections"},{IpProtocol:"tcp",FromPort:443,ToPort:443,CidrIp:"0.0.0.0/0",Description:"HTTPS/WSS connections"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${l}-${h}-realtime-sg`},{Key:"Environment",Value:h}]}});let ae=`${l}${h}RealtimeTaskDef`.replace(/[^a-zA-Z0-9]/g,""),be=`${l}${h}RealtimeTaskRole`.replace(/[^a-zA-Z0-9]/g,""),lt=`${l}${h}RealtimeExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(lt,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${h}-realtime-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"]}}),this.builder.addResource(be,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${h}-realtime-task-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"RealtimeTaskPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogStream","logs:PutLogEvents"],Resource:"*"},...b.redis?.enabled?[{Effect:"Allow",Action:["elasticache:DescribeCacheClusters","elasticache:DescribeReplicationGroups"],Resource:"*"}]:[]]}}]}});let _e=[{Name:"BROADCAST_HOST",Value:b.host||"0.0.0.0"},{Name:"BROADCAST_PORT",Value:String(T)},{Name:"NODE_ENV",Value:h==="production"?"production":"development"}];if(b.redis?.enabled){if(b.redis.useElastiCache)_e.push({Name:"REDIS_HOST",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Address"]}}),_e.push({Name:"REDIS_PORT",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Port"]}});else _e.push({Name:"REDIS_HOST",Value:b.redis.host||"localhost"}),_e.push({Name:"REDIS_PORT",Value:String(b.redis.port||6379)});if(b.redis.keyPrefix)_e.push({Name:"REDIS_KEY_PREFIX",Value:b.redis.keyPrefix})}this.builder.addResource(ae,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${l}-${h}-realtime`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:"512",Memory:"1024",ExecutionRoleArn:{"Fn::GetAtt":[lt,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[be,"Arn"]},ContainerDefinitions:[{Name:"realtime",Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${l}-realtime:latest`},Essential:!0,PortMappings:[{ContainerPort:T,Protocol:"tcp"}],Environment:_e,LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":`/ecs/${l}-${h}-realtime`,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":"realtime"}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${T}${b.healthCheckPath||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${l}-${h}-realtime`},{Key:"Environment",Value:h}]},DependsOn:[lt,be]});let _t=`${l}${h}RealtimeLogs`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(_t,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/ecs/${l}-${h}-realtime`,RetentionInDays:30}});let nr=`${l}${h}RealtimeService`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(nr,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${h}-realtime`,Cluster:{Ref:"ECSCluster"},TaskDefinition:{Ref:ae},DesiredCount:Ee,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:oe}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},HealthCheckGracePeriodSeconds:60,Tags:[{Key:"Name",Value:`${l}-${h}-realtime`},{Key:"Environment",Value:h}]},DependsOn:[ae,oe,_t]}),b.autoScaling){let fr=b.autoScaling,dt=`${l}${h}RealtimeScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(dt,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:fr.max||10,MinCapacity:fr.min||1,ResourceId:{"Fn::Sub":`service/\${ECSCluster}/${l}-${h}-realtime`},RoleARN:{"Fn::Sub":"arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService"},ScalableDimension:"ecs:service:DesiredCount",ServiceNamespace:"ecs"},DependsOn:nr}),fr.targetCPU)this.builder.addResource(`${l}${h}RealtimeCPUPolicy`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${h}-realtime-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:dt},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:fr.targetCPU,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(C.monitoring?.enabled){let fr=C.monitoring,dt=fr.notificationTopicArn;if(!dt&&fr.notificationEmails?.length){let ot=`${l}${h}RealtimeAlarmTopic`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ot,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${h}-realtime-alarms`,DisplayName:"Realtime Server Alarms"}}),fr.notificationEmails.forEach((_,kt)=>{this.builder.addResource(`${ot}Sub${kt}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:ot},Protocol:"email",Endpoint:_}})}),dt={Ref:ot}}this.builder.addResource(`${l}${h}RealtimeCPUAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${h}-realtime-high-cpu`,AlarmDescription:"Realtime server CPU utilization is high",MetricName:"CPUUtilization",Namespace:"AWS/ECS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:80,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ClusterName",Value:{Ref:"ECSCluster"}},{Name:"ServiceName",Value:`${l}-${h}-realtime`}],...dt&&{AlarmActions:[dt]}},DependsOn:nr}),this.builder.addResource(`${l}${h}RealtimeMemoryAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${h}-realtime-high-memory`,AlarmDescription:"Realtime server memory utilization is high",MetricName:"MemoryUtilization",Namespace:"AWS/ECS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:80,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ClusterName",Value:{Ref:"ECSCluster"}},{Name:"ServiceName",Value:`${l}-${h}-realtime`}],...dt&&{AlarmActions:[dt]}},DependsOn:nr})}this.builder.addOutput(`${l}${h}RealtimeEndpoint`.replace(/[^a-zA-Z0-9]/g,""),{Description:"Realtime WebSocket server endpoint",Value:{"Fn::Sub":`wss://${l}-${h}-realtime.\${AWS::Region}.elb.amazonaws.com:${T}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}})}generateBroadcastConfig(){let l=this.mergedConfig.infrastructure?.realtime;if(!l||l.mode!=="server")return"";let h=l.server||{};return`import type { BroadcastConfig } from 'ts-broadcasting'
174
174
 
175
175
  export default {
176
176
  verbose: ${this.environment!=="production"},
177
- driver: '${S.driver||"bun"}',
177
+ driver: '${h.driver||"bun"}',
178
178
  default: 'bun',
179
179
 
180
180
  connections: {
181
181
  bun: {
182
182
  driver: 'bun',
183
- host: process.env.BROADCAST_HOST || '${S.host||"0.0.0.0"}',
184
- port: Number(process.env.BROADCAST_PORT) || ${S.port||6001},
185
- scheme: '${S.scheme||"wss"}',
183
+ host: process.env.BROADCAST_HOST || '${h.host||"0.0.0.0"}',
184
+ port: Number(process.env.BROADCAST_PORT) || ${h.port||6001},
185
+ scheme: '${h.scheme||"wss"}',
186
186
  options: {
187
- idleTimeout: ${S.idleTimeout||120},
188
- maxPayloadLength: ${S.maxPayloadLength||16777216},
189
- backpressureLimit: ${S.backpressureLimit||1048576},
190
- closeOnBackpressureLimit: ${S.closeOnBackpressureLimit||!1},
191
- sendPings: ${S.sendPings!==!1},
192
- perMessageDeflate: ${S.perMessageDeflate!==!1},
187
+ idleTimeout: ${h.idleTimeout||120},
188
+ maxPayloadLength: ${h.maxPayloadLength||16777216},
189
+ backpressureLimit: ${h.backpressureLimit||1048576},
190
+ closeOnBackpressureLimit: ${h.closeOnBackpressureLimit||!1},
191
+ sendPings: ${h.sendPings!==!1},
192
+ perMessageDeflate: ${h.perMessageDeflate!==!1},
193
193
  },
194
194
  },
195
195
  },
196
- ${S.redis?.enabled?`
196
+ ${h.redis?.enabled?`
197
197
  redis: {
198
- host: process.env.REDIS_HOST || '${S.redis.host||"localhost"}',
199
- port: Number(process.env.REDIS_PORT) || ${S.redis.port||6379},
200
- ${S.redis.password?`password: process.env.REDIS_PASSWORD || '${S.redis.password}',`:""}
201
- database: ${S.redis.database||0},
202
- keyPrefix: '${S.redis.keyPrefix||"broadcasting:"}',
198
+ host: process.env.REDIS_HOST || '${h.redis.host||"localhost"}',
199
+ port: Number(process.env.REDIS_PORT) || ${h.redis.port||6379},
200
+ ${h.redis.password?`password: process.env.REDIS_PASSWORD || '${h.redis.password}',`:""}
201
+ database: ${h.redis.database||0},
202
+ keyPrefix: '${h.redis.keyPrefix||"broadcasting:"}',
203
203
  },
204
204
  `:""}
205
- ${S.rateLimit?.enabled?`
205
+ ${h.rateLimit?.enabled?`
206
206
  rateLimit: {
207
- max: ${S.rateLimit.max||100},
208
- window: ${S.rateLimit.window||60000},
209
- perChannel: ${S.rateLimit.perChannel!==!1},
210
- perUser: ${S.rateLimit.perUser!==!1},
207
+ max: ${h.rateLimit.max||100},
208
+ window: ${h.rateLimit.window||60000},
209
+ perChannel: ${h.rateLimit.perChannel!==!1},
210
+ perUser: ${h.rateLimit.perUser!==!1},
211
211
  },
212
212
  `:""}
213
- ${S.loadManagement?.enabled?`
213
+ ${h.loadManagement?.enabled?`
214
214
  loadManagement: {
215
215
  enabled: true,
216
- maxConnections: ${S.loadManagement.maxConnections||1e4},
217
- maxSubscriptionsPerConnection: ${S.loadManagement.maxSubscriptionsPerConnection||100},
218
- shedLoadThreshold: ${S.loadManagement.shedLoadThreshold||0.8},
216
+ maxConnections: ${h.loadManagement.maxConnections||1e4},
217
+ maxSubscriptionsPerConnection: ${h.loadManagement.maxSubscriptionsPerConnection||100},
218
+ shedLoadThreshold: ${h.loadManagement.shedLoadThreshold||0.8},
219
219
  },
220
220
  `:""}
221
221
  } satisfies BroadcastConfig
222
- `}toYAML(){return this.builder.toYAML()}toJSON(){return this.builder.toJSON()}getBuilder(){return this.builder}}function Kd(l){let S=[],P=[];if(!l.AWSTemplateFormatVersion)S.push({path:"AWSTemplateFormatVersion",message:"AWSTemplateFormatVersion is required",severity:"error"});else if(l.AWSTemplateFormatVersion!=="2010-09-09")P.push({path:"AWSTemplateFormatVersion",message:'AWSTemplateFormatVersion should be "2010-09-09"',severity:"warning"});if(!l.Resources||Object.keys(l.Resources).length===0)S.push({path:"Resources",message:"At least one resource is required",severity:"error"});else for(let[v,E]of Object.entries(l.Resources))eu(v,E,S,P);if(l.Resources){let v=fu(l.Resources);if(v.length>0)S.push({path:"Resources",message:`Circular dependencies detected: ${v.join(" -> ")}`,severity:"error"})}if(l.Parameters)for(let[v,E]of Object.entries(l.Parameters))ou(v,E,S,P);if(l.Outputs)for(let[v,E]of Object.entries(l.Outputs))au(v,E,S,P);return{valid:S.length===0,errors:S,warnings:P}}function eu(l,S,P,v){if(!S.Type)P.push({path:`Resources.${l}.Type`,message:"Resource Type is required",severity:"error"});if(!/^[a-zA-Z0-9]+$/.test(l))v.push({path:`Resources.${l}`,message:"Logical ID should only contain alphanumeric characters",severity:"warning"});if(S.Type&&!S.Type.startsWith("AWS::")&&!S.Type.startsWith("Custom::"))P.push({path:`Resources.${l}.Type`,message:'Resource Type must start with "AWS::" or "Custom::"',severity:"error"});if(S.Properties){for(let[E,ot]of Object.entries(S.Properties))if(ot===void 0||ot===null)v.push({path:`Resources.${l}.Properties.${E}`,message:"Property has undefined or null value",severity:"warning"})}if(S.DependsOn){if(typeof S.DependsOn==="string"){if(S.DependsOn===l)P.push({path:`Resources.${l}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}else if(Array.isArray(S.DependsOn)){if(S.DependsOn.includes(l))P.push({path:`Resources.${l}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}}}function ou(l,S,P,v){if(!S.Type)P.push({path:`Parameters.${l}.Type`,message:"Parameter Type is required",severity:"error"});let E=["String","Number","List<Number>","CommaDelimitedList","AWS::SSM::Parameter::Value<String>"];if(S.Type&&!E.includes(S.Type)&&!S.Type.startsWith("AWS::"))v.push({path:`Parameters.${l}.Type`,message:`Uncommon parameter type: ${S.Type}`,severity:"warning"});if(S.NoEcho&&S.Default)v.push({path:`Parameters.${l}`,message:"NoEcho parameters should not have default values",severity:"warning"})}function au(l,S,P,v){if(!S.Value)P.push({path:`Outputs.${l}.Value`,message:"Output Value is required",severity:"error"})}function fu(l){let S={};for(let[Ie,Ne]of Object.entries(l)){if(S[Ie]=[],Ne.DependsOn){if(typeof Ne.DependsOn==="string")S[Ie].push(Ne.DependsOn);else if(Array.isArray(Ne.DependsOn))S[Ie].push(...Ne.DependsOn)}let nt=tc(Ne);S[Ie].push(...nt)}let P=new Set,v=new Set,E=[];function ot(Ie,Ne){P.add(Ie),v.add(Ie),Ne.push(Ie);let nt=S[Ie]||[];for(let Pt of nt)if(!P.has(Pt)){if(ot(Pt,Ne))return!0}else if(v.has(Pt)){let st=Ne.indexOf(Pt);return E.push(...Ne.slice(st),Pt),!0}return Ne.pop(),v.delete(Ie),!1}for(let Ie of Object.keys(S))if(!P.has(Ie)){if(ot(Ie,[]))return E}return[]}function tc(l,S=[]){if(typeof l!=="object"||l===null)return S;if(Array.isArray(l)){for(let P of l)tc(P,S);return S}if(l.Ref&&typeof l.Ref==="string"&&!l.Ref.startsWith("AWS::"))S.push(l.Ref);if(l["Fn::GetAtt"]){let P=l["Fn::GetAtt"];if(Array.isArray(P)&&P.length>0)S.push(P[0])}for(let P of Object.values(l))tc(P,S);return S}function hu(l){let S=[],P=[],v=new TextEncoder().encode(l).length,E=51200,ot=460800;if(v>51200)if(v>460800)S.push({path:"template",message:`Template size (${v} bytes) exceeds maximum allowed size of 460800 bytes`,severity:"error"});else P.push({path:"template",message:`Template size (${v} bytes) exceeds direct upload limit (51200 bytes). You must upload to S3 first.`,severity:"warning"});return{valid:S.length===0,errors:S,warnings:P}}function yu(l){let S=[],P=[],v=l.Resources?Object.keys(l.Resources).length:0,E=l.Parameters?Object.keys(l.Parameters).length:0,ot=l.Outputs?Object.keys(l.Outputs).length:0;if(v>500)S.push({path:"Resources",message:`Template has ${v} resources, exceeding the limit of 500`,severity:"error"});else if(v>200)P.push({path:"Resources",message:`Template has ${v} resources. Consider using nested stacks for better organization.`,severity:"warning"});if(E>200)S.push({path:"Parameters",message:`Template has ${E} parameters, exceeding the limit of 200`,severity:"error"});if(ot>200)S.push({path:"Outputs",message:`Template has ${ot} outputs, exceeding the limit of 200`,severity:"error"});return{valid:S.length===0,errors:S,warnings:P}}function lh(l){let{domains:S,email:P,staging:v=!1,challengeType:E="http-01",certPath:ot="/etc/letsencrypt/live",autoRenew:Ie=!0}=l,Ne=S[0],nt=S.map((st)=>`-d ${st}`).join(" "),Pt=v?"--staging":"";if(E==="http-01")return Su({domains:S,email:P,staging:v,certPath:ot,autoRenew:Ie,domainFlags:nt,stagingFlag:Pt,primaryDomain:Ne});else{let st=l.dnsProvider?.provider||(l.hostedZoneId?"route53":void 0);return Pu({domains:S,email:P,staging:v,certPath:ot,autoRenew:Ie,domainFlags:nt,stagingFlag:Pt,primaryDomain:Ne,hostedZoneId:l.hostedZoneId,dnsProvider:l.dnsProvider,dnsProviderType:st})}}function Su(l){let{email:S,certPath:P,autoRenew:v,domainFlags:E,stagingFlag:ot,primaryDomain:Ie}=l;return`
222
+ `}toYAML(){return this.builder.toYAML()}toJSON(){return this.builder.toJSON()}getBuilder(){return this.builder}}function Xl(l){let h=[],C=[];if(!l.AWSTemplateFormatVersion)h.push({path:"AWSTemplateFormatVersion",message:"AWSTemplateFormatVersion is required",severity:"error"});else if(l.AWSTemplateFormatVersion!=="2010-09-09")C.push({path:"AWSTemplateFormatVersion",message:'AWSTemplateFormatVersion should be "2010-09-09"',severity:"warning"});if(!l.Resources||Object.keys(l.Resources).length===0)h.push({path:"Resources",message:"At least one resource is required",severity:"error"});else for(let[b,T]of Object.entries(l.Resources))Zd(b,T,h,C);if(l.Resources){let b=iu(l.Resources);if(b.length>0)h.push({path:"Resources",message:`Circular dependencies detected: ${b.join(" -> ")}`,severity:"error"})}if(l.Parameters)for(let[b,T]of Object.entries(l.Parameters))eu(b,T,h,C);if(l.Outputs)for(let[b,T]of Object.entries(l.Outputs))tu(b,T,h,C);return{valid:h.length===0,errors:h,warnings:C}}function Zd(l,h,C,b){if(!h.Type)C.push({path:`Resources.${l}.Type`,message:"Resource Type is required",severity:"error"});if(!/^[a-zA-Z0-9]+$/.test(l))b.push({path:`Resources.${l}`,message:"Logical ID should only contain alphanumeric characters",severity:"warning"});if(h.Type&&!h.Type.startsWith("AWS::")&&!h.Type.startsWith("Custom::"))C.push({path:`Resources.${l}.Type`,message:'Resource Type must start with "AWS::" or "Custom::"',severity:"error"});if(h.Properties){for(let[T,Ee]of Object.entries(h.Properties))if(Ee===void 0||Ee===null)b.push({path:`Resources.${l}.Properties.${T}`,message:"Property has undefined or null value",severity:"warning"})}if(h.DependsOn){if(typeof h.DependsOn==="string"){if(h.DependsOn===l)C.push({path:`Resources.${l}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}else if(Array.isArray(h.DependsOn)){if(h.DependsOn.includes(l))C.push({path:`Resources.${l}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}}}function eu(l,h,C,b){if(!h.Type)C.push({path:`Parameters.${l}.Type`,message:"Parameter Type is required",severity:"error"});let T=["String","Number","List<Number>","CommaDelimitedList","AWS::SSM::Parameter::Value<String>"];if(h.Type&&!T.includes(h.Type)&&!h.Type.startsWith("AWS::"))b.push({path:`Parameters.${l}.Type`,message:`Uncommon parameter type: ${h.Type}`,severity:"warning"});if(h.NoEcho&&h.Default)b.push({path:`Parameters.${l}`,message:"NoEcho parameters should not have default values",severity:"warning"})}function tu(l,h,C,b){if(!h.Value)C.push({path:`Outputs.${l}.Value`,message:"Output Value is required",severity:"error"})}function iu(l){let h={};for(let[oe,ae]of Object.entries(l)){if(h[oe]=[],ae.DependsOn){if(typeof ae.DependsOn==="string")h[oe].push(ae.DependsOn);else if(Array.isArray(ae.DependsOn))h[oe].push(...ae.DependsOn)}let be=Rs(ae);h[oe].push(...be)}let C=new Set,b=new Set,T=[];function Ee(oe,ae){C.add(oe),b.add(oe),ae.push(oe);let be=h[oe]||[];for(let lt of be)if(!C.has(lt)){if(Ee(lt,ae))return!0}else if(b.has(lt)){let _e=ae.indexOf(lt);return T.push(...ae.slice(_e),lt),!0}return ae.pop(),b.delete(oe),!1}for(let oe of Object.keys(h))if(!C.has(oe)){if(Ee(oe,[]))return T}return[]}function Rs(l,h=[]){if(typeof l!=="object"||l===null)return h;if(Array.isArray(l)){for(let C of l)Rs(C,h);return h}if(l.Ref&&typeof l.Ref==="string"&&!l.Ref.startsWith("AWS::"))h.push(l.Ref);if(l["Fn::GetAtt"]){let C=l["Fn::GetAtt"];if(Array.isArray(C)&&C.length>0)h.push(C[0])}for(let C of Object.values(l))Rs(C,h);return h}function nu(l){let h=[],C=[],b=new TextEncoder().encode(l).length,T=51200,Ee=460800;if(b>51200)if(b>460800)h.push({path:"template",message:`Template size (${b} bytes) exceeds maximum allowed size of 460800 bytes`,severity:"error"});else C.push({path:"template",message:`Template size (${b} bytes) exceeds direct upload limit (51200 bytes). You must upload to S3 first.`,severity:"warning"});return{valid:h.length===0,errors:h,warnings:C}}function su(l){let h=[],C=[],b=l.Resources?Object.keys(l.Resources).length:0,T=l.Parameters?Object.keys(l.Parameters).length:0,Ee=l.Outputs?Object.keys(l.Outputs).length:0;if(b>500)h.push({path:"Resources",message:`Template has ${b} resources, exceeding the limit of 500`,severity:"error"});else if(b>200)C.push({path:"Resources",message:`Template has ${b} resources. Consider using nested stacks for better organization.`,severity:"warning"});if(T>200)h.push({path:"Parameters",message:`Template has ${T} parameters, exceeding the limit of 200`,severity:"error"});if(Ee>200)h.push({path:"Outputs",message:`Template has ${Ee} outputs, exceeding the limit of 200`,severity:"error"});return{valid:h.length===0,errors:h,warnings:C}}function pp(l){let{domains:h,email:C,staging:b=!1,challengeType:T="http-01",certPath:Ee="/etc/letsencrypt/live",autoRenew:oe=!0}=l,ae=h[0],be=h.map((_e)=>`-d ${_e}`).join(" "),lt=b?"--staging":"";if(T==="http-01")return uu({domains:h,email:C,staging:b,certPath:Ee,autoRenew:oe,domainFlags:be,stagingFlag:lt,primaryDomain:ae});else{let _e=l.dnsProvider?.provider||(l.hostedZoneId?"route53":void 0);return pu({domains:h,email:C,staging:b,certPath:Ee,autoRenew:oe,domainFlags:be,stagingFlag:lt,primaryDomain:ae,hostedZoneId:l.hostedZoneId,dnsProvider:l.dnsProvider,dnsProviderType:_e})}}function uu(l){let{email:h,certPath:C,autoRenew:b,domainFlags:T,stagingFlag:Ee,primaryDomain:oe}=l;return`
223
223
  # ==========================================
224
224
  # Let's Encrypt Certificate Setup (HTTP-01)
225
225
  # ==========================================
@@ -235,29 +235,29 @@ certbot certonly \\
235
235
  --standalone \\
236
236
  --non-interactive \\
237
237
  --agree-tos \\
238
- --email ${S} \\
239
- ${ot} \\
240
- ${E}
238
+ --email ${h} \\
239
+ ${Ee} \\
240
+ ${T}
241
241
 
242
242
  # Check if certificate was obtained
243
- if [ -f "${P}/${Ie}/fullchain.pem" ]; then
243
+ if [ -f "${C}/${oe}/fullchain.pem" ]; then
244
244
  echo "Certificate obtained successfully!"
245
245
 
246
246
  # Create symlinks for easier access
247
247
  mkdir -p /etc/ssl/stacks
248
- ln -sf ${P}/${Ie}/fullchain.pem /etc/ssl/stacks/fullchain.pem
249
- ln -sf ${P}/${Ie}/privkey.pem /etc/ssl/stacks/privkey.pem
250
- ln -sf ${P}/${Ie}/cert.pem /etc/ssl/stacks/cert.pem
251
- ln -sf ${P}/${Ie}/chain.pem /etc/ssl/stacks/chain.pem
248
+ ln -sf ${C}/${oe}/fullchain.pem /etc/ssl/stacks/fullchain.pem
249
+ ln -sf ${C}/${oe}/privkey.pem /etc/ssl/stacks/privkey.pem
250
+ ln -sf ${C}/${oe}/cert.pem /etc/ssl/stacks/cert.pem
251
+ ln -sf ${C}/${oe}/chain.pem /etc/ssl/stacks/chain.pem
252
252
  else
253
253
  echo "Failed to obtain certificate!"
254
254
  fi
255
255
 
256
- ${v?ic(Ie):"# Auto-renewal disabled"}
256
+ ${b?Ns(oe):"# Auto-renewal disabled"}
257
257
 
258
258
  # Restart the application
259
259
  systemctl start stacks
260
- `}function Pu(l){let{email:S,certPath:P,autoRenew:v,domainFlags:E,stagingFlag:ot,primaryDomain:Ie,hostedZoneId:Ne,dnsProvider:nt,dnsProviderType:Pt}=l;if(Pt==="route53"||Ne){if(!Ne)throw Error("hostedZoneId is required for DNS-01 challenge with Route53");return`
260
+ `}function pu(l){let{email:h,certPath:C,autoRenew:b,domainFlags:T,stagingFlag:Ee,primaryDomain:oe,hostedZoneId:ae,dnsProvider:be,dnsProviderType:lt}=l;if(lt==="route53"||ae){if(!ae)throw Error("hostedZoneId is required for DNS-01 challenge with Route53");return`
261
261
  # ==========================================
262
262
  # Let's Encrypt Certificate Setup (DNS-01 via Route53)
263
263
  # ==========================================
@@ -270,49 +270,49 @@ certbot certonly \\
270
270
  --dns-route53 \\
271
271
  --non-interactive \\
272
272
  --agree-tos \\
273
- --email ${S} \\
274
- ${ot} \\
275
- ${E}
273
+ --email ${h} \\
274
+ ${Ee} \\
275
+ ${T}
276
276
 
277
277
  # Check if certificate was obtained
278
- if [ -f "${P}/${Ie}/fullchain.pem" ]; then
278
+ if [ -f "${C}/${oe}/fullchain.pem" ]; then
279
279
  echo "Certificate obtained successfully!"
280
280
 
281
281
  # Create symlinks for easier access
282
282
  mkdir -p /etc/ssl/stacks
283
- ln -sf ${P}/${Ie}/fullchain.pem /etc/ssl/stacks/fullchain.pem
284
- ln -sf ${P}/${Ie}/privkey.pem /etc/ssl/stacks/privkey.pem
285
- ln -sf ${P}/${Ie}/cert.pem /etc/ssl/stacks/cert.pem
286
- ln -sf ${P}/${Ie}/chain.pem /etc/ssl/stacks/chain.pem
283
+ ln -sf ${C}/${oe}/fullchain.pem /etc/ssl/stacks/fullchain.pem
284
+ ln -sf ${C}/${oe}/privkey.pem /etc/ssl/stacks/privkey.pem
285
+ ln -sf ${C}/${oe}/cert.pem /etc/ssl/stacks/cert.pem
286
+ ln -sf ${C}/${oe}/chain.pem /etc/ssl/stacks/chain.pem
287
287
  else
288
288
  echo "Failed to obtain certificate!"
289
289
  fi
290
290
 
291
- ${v?ic(Ie):"# Auto-renewal disabled"}
292
- `}if(!nt)throw Error("dnsProvider configuration is required for DNS-01 challenge with external DNS providers");let st=nt.provider.toUpperCase(),ur=$u(nt);return`
291
+ ${b?Ns(oe):"# Auto-renewal disabled"}
292
+ `}if(!be)throw Error("dnsProvider configuration is required for DNS-01 challenge with external DNS providers");let _e=be.provider.toUpperCase(),_t=Cu(be);return`
293
293
  # ==========================================
294
- # Let's Encrypt Certificate Setup (DNS-01 via ${st})
294
+ # Let's Encrypt Certificate Setup (DNS-01 via ${_e})
295
295
  # ==========================================
296
296
 
297
297
  # Install certbot
298
298
  dnf install -y certbot jq curl
299
299
 
300
- ${ur}
300
+ ${_t}
301
301
 
302
302
  # Create DNS challenge hook scripts directory
303
303
  mkdir -p /etc/letsencrypt/hooks
304
304
 
305
- # Create authenticator hook for ${st}
305
+ # Create authenticator hook for ${_e}
306
306
  cat > /etc/letsencrypt/hooks/auth-hook.sh << 'AUTHHOOK'
307
307
  #!/bin/bash
308
- # DNS-01 authenticator hook for ${st}
308
+ # DNS-01 authenticator hook for ${_e}
309
309
  # This creates the TXT record for ACME challenge
310
310
 
311
311
  DOMAIN="$CERTBOT_DOMAIN"
312
312
  VALIDATION="$CERTBOT_VALIDATION"
313
313
  RECORD_NAME="_acme-challenge.$DOMAIN"
314
314
 
315
- ${Iu(nt)}
315
+ ${Su(be)}
316
316
 
317
317
  # Wait for DNS propagation
318
318
  echo "Waiting 60 seconds for DNS propagation..."
@@ -321,17 +321,17 @@ AUTHHOOK
321
321
 
322
322
  chmod +x /etc/letsencrypt/hooks/auth-hook.sh
323
323
 
324
- # Create cleanup hook for ${st}
324
+ # Create cleanup hook for ${_e}
325
325
  cat > /etc/letsencrypt/hooks/cleanup-hook.sh << 'CLEANUPHOOK'
326
326
  #!/bin/bash
327
- # DNS-01 cleanup hook for ${st}
327
+ # DNS-01 cleanup hook for ${_e}
328
328
  # This removes the TXT record after validation
329
329
 
330
330
  DOMAIN="$CERTBOT_DOMAIN"
331
331
  VALIDATION="$CERTBOT_VALIDATION"
332
332
  RECORD_NAME="_acme-challenge.$DOMAIN"
333
333
 
334
- ${Du(nt)}
334
+ ${bu(be)}
335
335
  CLEANUPHOOK
336
336
 
337
337
  chmod +x /etc/letsencrypt/hooks/cleanup-hook.sh
@@ -344,26 +344,26 @@ certbot certonly \\
344
344
  --manual-cleanup-hook /etc/letsencrypt/hooks/cleanup-hook.sh \\
345
345
  --non-interactive \\
346
346
  --agree-tos \\
347
- --email ${S} \\
348
- ${ot} \\
349
- ${E}
347
+ --email ${h} \\
348
+ ${Ee} \\
349
+ ${T}
350
350
 
351
351
  # Check if certificate was obtained
352
- if [ -f "${P}/${Ie}/fullchain.pem" ]; then
352
+ if [ -f "${C}/${oe}/fullchain.pem" ]; then
353
353
  echo "Certificate obtained successfully!"
354
354
 
355
355
  # Create symlinks for easier access
356
356
  mkdir -p /etc/ssl/stacks
357
- ln -sf ${P}/${Ie}/fullchain.pem /etc/ssl/stacks/fullchain.pem
358
- ln -sf ${P}/${Ie}/privkey.pem /etc/ssl/stacks/privkey.pem
359
- ln -sf ${P}/${Ie}/cert.pem /etc/ssl/stacks/cert.pem
360
- ln -sf ${P}/${Ie}/chain.pem /etc/ssl/stacks/chain.pem
357
+ ln -sf ${C}/${oe}/fullchain.pem /etc/ssl/stacks/fullchain.pem
358
+ ln -sf ${C}/${oe}/privkey.pem /etc/ssl/stacks/privkey.pem
359
+ ln -sf ${C}/${oe}/cert.pem /etc/ssl/stacks/cert.pem
360
+ ln -sf ${C}/${oe}/chain.pem /etc/ssl/stacks/chain.pem
361
361
  else
362
362
  echo "Failed to obtain certificate!"
363
363
  fi
364
364
 
365
- ${v?ic(Ie):"# Auto-renewal disabled"}
366
- `}function $u(l){switch(l.provider){case"porkbun":return`
365
+ ${b?Ns(oe):"# Auto-renewal disabled"}
366
+ `}function Cu(l){switch(l.provider){case"porkbun":return`
367
367
  # Porkbun API credentials
368
368
  export PORKBUN_API_KEY="${l.apiKey}"
369
369
  export PORKBUN_SECRET_KEY="${l.secretKey}"
@@ -374,7 +374,7 @@ export GODADDY_API_SECRET="${l.apiSecret}"
374
374
  export GODADDY_ENV="${l.environment||"production"}"
375
375
  `;case"route53":return`
376
376
  # Route53 uses IAM role credentials
377
- `;default:return""}}function Iu(l){switch(l.provider){case"porkbun":return`
377
+ `;default:return""}}function Su(l){switch(l.provider){case"porkbun":return`
378
378
  # Extract root domain (last two parts)
379
379
  ROOT_DOMAIN=$(echo "$DOMAIN" | awk -F. '{print $(NF-1)"."$NF}')
380
380
  SUBDOMAIN="_acme-challenge"
@@ -418,7 +418,7 @@ curl -s -X PATCH "$API_URL/v1/domains/$ROOT_DOMAIN/records" \\
418
418
  "data": "'"$VALIDATION"'",
419
419
  "ttl": 600
420
420
  }]'
421
- `;default:return'echo "Unsupported DNS provider"'}}function Du(l){switch(l.provider){case"porkbun":return`
421
+ `;default:return'echo "Unsupported DNS provider"'}}function bu(l){switch(l.provider){case"porkbun":return`
422
422
  # Extract root domain, and the challenge's subdomain the way the auth hook did
423
423
  ROOT_DOMAIN=$(echo "$DOMAIN" | awk -F. '{print $(NF-1)"."$NF}')
424
424
  SUBDOMAIN="_acme-challenge"
@@ -470,7 +470,7 @@ fi
470
470
 
471
471
  curl -s -X DELETE "$API_URL/v1/domains/$ROOT_DOMAIN/records/TXT/$RECORD_NAME" \\
472
472
  -H "Authorization: sso-key $GODADDY_API_KEY:$GODADDY_API_SECRET"
473
- `;default:return'echo "Unsupported DNS provider"'}}function ic(l){return`
473
+ `;default:return'echo "Unsupported DNS provider"'}}function Ns(l){return`
474
474
  # ==========================================
475
475
  # Certificate Auto-Renewal Setup
476
476
  # ==========================================
@@ -515,13 +515,13 @@ systemctl enable certbot-renewal.timer
515
515
  systemctl start certbot-renewal.timer
516
516
 
517
517
  echo "Certificate auto-renewal configured"
518
- `}function dh(l){let{httpPort:S=80,httpsPort:P=443,certPath:v="/etc/ssl/stacks",redirectHttp:E=!0}=l;return`
518
+ `}function gp(l){let{httpPort:h=80,httpsPort:C=443,certPath:b="/etc/ssl/stacks",redirectHttp:T=!0}=l;return`
519
519
  // HTTPS Server with Let's Encrypt certificates
520
520
  import { readFileSync, existsSync } from 'node:fs'
521
521
 
522
- const CERT_PATH = '${v}'
523
- const HTTP_PORT = ${S}
524
- const HTTPS_PORT = ${P}
522
+ const CERT_PATH = '${b}'
523
+ const HTTP_PORT = ${h}
524
+ const HTTPS_PORT = ${C}
525
525
 
526
526
  // Check if certificates exist
527
527
  const hasCerts = existsSync(\`\${CERT_PATH}/fullchain.pem\`) && existsSync(\`\${CERT_PATH}/privkey.pem\`)
@@ -541,7 +541,7 @@ if (hasCerts) {
541
541
  })
542
542
  console.log(\`HTTPS server running on port \${HTTPS_PORT}\`)
543
543
 
544
- ${E?`
544
+ ${T?`
545
545
  // Start HTTP server for redirect
546
546
  const httpServer = Bun.serve({
547
547
  port: HTTP_PORT,
@@ -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 Ou(l,S,P){let v=`_acme-challenge.${S}`;if(await ku(l,S,v,P))return;let E=await l.createRecord(S,{name:v,type:"TXT",content:P,ttl:60});if(!E.success)throw Error(`Failed to create DNS challenge record: ${E.message}`)}async function Nu(l,S,P){let v=await l.deleteRecord(S,{name:`_acme-challenge.${S}`,type:"TXT",content:P});if(!v.success)console.warn(`Failed to delete DNS challenge record: ${v.message}`)}async function ku(l,S,P,v){try{let E=await l.listRecords(S,"TXT"),ot=P.replace(/\.$/,"").toLowerCase();return(E.records??[]).some((Ie)=>Ie.name.replace(/\.$/,"").toLowerCase()===ot&&Ie.content.replace(/^"|"$/g,"")===v)}catch{return!1}}function fc(l){let{hostedZoneId:S,dnsProvider:P,region:v="us-east-1"}=l;if(P)return T(P);if(S)return new z(v,S);throw Error("Either dnsProvider or hostedZoneId must be provided")}async function uh(l){await Ou(fc(l),l.domain,l.challengeValue)}async function ph(l){await Nu(fc(l),l.domain,l.challengeValue)}function mh(l){try{let{execSync:S}=Fe("node:child_process"),P=S(`openssl x509 -checkend 2592000 -noout -in ${l}/cert.pem`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return!1}catch{return!0}}import{createHash as gc,createSign as xu,generateKeyPairSync as yc}from"node:crypto";var Cc={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?Cc.staging:Cc.production,this.email=l.email,this.accountKey=l.accountKey||this.generateAccountKey()}generateAccountKey(){let{privateKey:l}=yc("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 v=this.nonce;return this.nonce=null,v}let l=await this.getDirectory(),P=(await fetch(l.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!P)throw Error("Failed to get nonce from ACME server");return P}getJwk(){let l=this.accountKey.split(`
605
- `).filter((ot)=>!ot.startsWith("-----")).join(""),S=Buffer.from(l,"base64"),P=S.length-65,v=S.subarray(P+1,P+33),E=S.subarray(P+33,P+65);return{kty:"EC",crv:"P-256",x:this.base64UrlEncode(v),y:this.base64UrlEncode(E)}}getJwkThumbprint(){let l=this.getJwk(),S=JSON.stringify({crv:l.crv,kty:l.kty,x:l.x,y:l.y}),P=gc("sha256").update(S).digest();return this.base64UrlEncode(P)}base64UrlEncode(l){return(typeof l==="string"?Buffer.from(l):l).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async signPayload(l,S){let P=await this.getNonce(),v=this.getJwk(),E={alg:"ES256",nonce:P,url:l};if(this.accountUrl)E.kid=this.accountUrl;else E.jwk=v;let ot=this.base64UrlEncode(JSON.stringify(E)),Ie=S===""?"":this.base64UrlEncode(JSON.stringify(S)),Ne=`${ot}.${Ie}`,nt=xu("SHA256");nt.update(Ne);let Pt=nt.sign(this.accountKey),st=Pt.subarray(4,4+Pt[3]),ur=4+Pt[3]+2,pr=Pt.subarray(ur,ur+Pt[ur-1]),gr=Buffer.alloc(32),Dt=Buffer.alloc(32);st.copy(gr,32-st.length),pr.copy(Dt,32-pr.length);let St=Buffer.concat([gr,Dt]);return JSON.stringify({protected:ot,payload:Ie,signature:this.base64UrlEncode(St)})}async acmeRequest(l,S){let P=await this.signPayload(l,S),v=await fetch(l,{method:"POST",headers:{"Content-Type":"application/jose+json"},body:P}),E=v.headers.get("replay-nonce");if(E)this.nonce=E;let ot,Ie=v.headers.get("content-type");if(Ie?.includes("application/json")||Ie?.includes("application/problem+json"))ot=await v.json();else ot=await v.text();if(!v.ok)throw Error(`ACME request failed: ${JSON.stringify(ot)}`);return{body:ot,headers:v.headers}}async registerAccount(){let l=await this.getDirectory(),{body:S,headers:P}=await this.acmeRequest(l.newAccount,{termsOfServiceAgreed:!0,contact:[`mailto:${this.email}`]}),v=P.get("location");if(!v)throw Error("No account URL returned");return this.accountUrl=v,v}async createOrder(l){if(!this.accountUrl)await this.registerAccount();let S=await this.getDirectory(),{body:P,headers:v}=await this.acmeRequest(S.newOrder,{identifiers:l.map((ot)=>({type:"dns",value:ot}))}),E=v.get("location");if(!E)throw Error("No order URL returned");return{orderUrl:E,authorizations:P.authorizations,finalize:P.finalize}}async getAuthorization(l){let{body:S}=await this.acmeRequest(l,""),P=S.identifier.value,v=this.getJwkThumbprint(),E=S.challenges.filter((ot)=>ot.type==="http-01"||ot.type==="dns-01").map((ot)=>{let Ie=`${ot.token}.${v}`;if(ot.type==="http-01")return{type:"http-01",token:ot.token,keyAuthorization:Ie,identifier:`/.well-known/acme-challenge/${ot.token}`};else{let Ne=this.base64UrlEncode(gc("sha256").update(Ie).digest());return{type:"dns-01",token:ot.token,keyAuthorization:Ie,identifier:`_acme-challenge.${P}`,dnsValue:Ne}}});return{domain:P,challenges:E}}async respondToChallenge(l){await this.acmeRequest(l,{})}async waitForAuthorization(l,S=30){for(let P=0;P<S;P++){let{body:v}=await this.acmeRequest(l,"");if(v.status==="valid")return;if(v.status==="invalid")throw Error(`Authorization failed: ${JSON.stringify(v)}`);await new Promise((E)=>setTimeout(E,2000))}throw Error("Authorization timed out")}generateCsr(l){let{privateKey:S}=yc("rsa",{modulusLength:2048}),P=S.export({type:"pkcs8",format:"pem"});return{csr:this.createSimpleCsr(l,S),privateKey:P}}createSimpleCsr(l,S){throw Error("CSR generation requires additional implementation. Consider using the shell-based certbot approach instead.")}async finalizeOrder(l,S){let{csr:P,privateKey:v}=this.generateCsr(S),{body:E}=await this.acmeRequest(l,{csr:this.base64UrlEncode(Buffer.from(P,"base64"))}),ot=E.certificate;if(!ot)throw Error("Certificate not immediately available - polling not implemented");let Ne=await(await fetch(ot)).text(),nt=Ne.split(/(?=-----BEGIN CERTIFICATE-----)/g),Pt=nt[0],st=nt.slice(1).join("");return{certificate:Pt,privateKey:v,chain:st,fullchain:Ne,expiresAt:new Date(Date.now()+7776000000)}}getAccountKey(){return this.accountKey}}var kn=(l)=>l===void 0?void 0:l?"on":"off";function oc(l){let S={ssl:l.ssl,always_use_https:kn(l.alwaysUseHttps),automatic_https_rewrites:kn(l.automaticHttpsRewrites),min_tls_version:l.minTlsVersion,tls_1_3:kn(l.tls13),brotli:kn(l.brotli),http3:kn(l.http3),"0rtt":kn(l.zeroRtt),early_hints:kn(l.earlyHints),browser_cache_ttl:l.browserCacheTtl,always_online:kn(l.alwaysOnline),websockets:kn(l.websockets),email_obfuscation:kn(l.emailObfuscation)};if(l.hsts)S.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 P of Object.keys(S))if(S[P]===void 0)delete S[P];return{...S,...l.raw??{}}}var Ha={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 ac(l){let{address:S,serverName:P,port:v=443,timeoutMs:E=5000}=l;return new Promise((ot)=>{let Ie=!1,Ne=(Pt)=>{if(Ie)return;Ie=!0;try{nt.destroy()}catch{}ot(Pt)},nt=Fu({host:S,port:v,servername:P,rejectUnauthorized:!1,timeout:E});nt.once("secureConnect",()=>{if(nt.authorized){Ne({reachable:!0,trusted:!0});return}Ne({reachable:!0,trusted:!1,reason:nt.authorizationError?String(nt.authorizationError):"origin certificate is not trusted for this hostname"})}),nt.once("timeout",()=>{Ne({reachable:!1,trusted:!1,reason:`no TLS handshake within ${E}ms`})}),nt.once("error",(Pt)=>{Ne({reachable:!1,trusted:!1,reason:Pt.message})})})}function Mu(l,S){let P=S.replace(/\.$/,"").toLowerCase();return l.some((v)=>{let E=v.replace(/\.$/,"").toLowerCase();if(E===P)return!0;if(!E.startsWith("*."))return!1;let ot=E.slice(2);if(!P.endsWith(`.${ot}`))return!1;return!P.slice(0,P.length-ot.length-1).includes(".")})}async function Bu(l){let{provider:S,zone:P,hosts:v,ipv4:E,ipv6:ot,proxied:Ie=!0,settings:Ne=Ha,cache:nt,originGuard:Pt,purge:st=!0,ttl:ur=300,skipOriginProbe:pr=!1,skipEdgeCertificateCheck:gr=!1}=l,Dt={records:[],settingsChanged:[],cacheRules:0,originGuard:!1,purged:!1,deferredProxy:[],warnings:[]};if(v.length===0)return Dt;let St=[],Se=Ie&&!gr?await S.listEdgeCertificateHosts(P):null;for(let ie of v){let Rt=Ie;if(Rt&&Se&&!Mu(Se,ie)){Rt=!1;let er=Se.length===0?"the zone has no active edge certificate yet":`no active edge certificate covers it (${Se.join(", ")})`;Dt.deferredProxy.push({host:ie,reason:er}),Dt.warnings.push(`${ie}: publishing DNS-only — ${er}. 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(Rt&&!pr){let er=await ac({address:E,serverName:ie});if(!er.trusted){Rt=!1;let lr=er.reason||"origin is not serving a trusted certificate";Dt.deferredProxy.push({host:ie,reason:lr}),Dt.warnings.push(`${ie}: publishing DNS-only for now — the origin does not yet serve a certificate this proxy can verify (${lr}). 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(Rt)St.push(ie);let Nt=[{type:"A",content:E}];if(ot&&Tn(ie))Nt.push({type:"AAAA",content:ot});for(let{type:er,content:lr}of Nt){let fr=await S.upsertRecord(P,{name:ie,type:er,content:lr,ttl:ur,proxied:Rt});if(fr.success)Dt.records.push({host:ie,type:er,content:lr,proxied:Rt});else Dt.warnings.push(`${ie} ${er} → ${lr} failed: ${fr.message||"unknown provider error"}`)}}if(St.length===0){if(Ie)Dt.warnings.push("No host is proxied yet, so zone settings, cache rules and purge were skipped — they only take effect through the proxy.");return Dt}try{let ie=oc(Ne),Rt=await S.applyZoneSettings(P,ie);Dt.settingsChanged=Rt.changed;for(let Nt of Rt.failed)Dt.warnings.push(`zone setting '${Nt.id}' could not be applied: ${Nt.error}`)}catch(ie){Dt.warnings.push(`zone settings could not be read: ${ie instanceof Error?ie.message:String(ie)}`)}let Bt=za(St,nt);if(Bt.length>0){let ie=await S.putManagedPhaseRules(P,"http_request_cache_settings",Bt);if(ie.success)Dt.cacheRules=Bt.length;else Dt.warnings.push(`cache rules could not be written: ${ie.message}`)}if(Pt){let ie=Ka(St,Pt.header,Pt.value);if(ie.length>0){let Rt=await S.putManagedPhaseRules(P,"http_request_late_transform",ie);if(Rt.success)Dt.originGuard=!0;else Dt.warnings.push(`origin guard header could not be written: ${Rt.message}. `+"The gateway will reject requests that lack it — disable the guard or grant the token Transform Rules: Edit.")}}if(st){if(Dt.purged=await S.purgeCache(P,{hosts:St}),!Dt.purged)Dt.warnings.push("edge cache purge failed — new content may take until TTL expiry to appear.")}return Dt}var _u=(l)=>process.env[l];function Sc(l,S){let P=l.replace(/\.$/,"").toLowerCase();if(S){let v=S.replace(/\.$/,"").toLowerCase();if(P===v||P.endsWith(`.${v}`))return v}return P.split(".").slice(-2).join(".")}function Vu(l,S={}){let P=S.env??_u,v=l.infrastructure?.compute?.proxy?.cdn,E=[];if(!v||v.provider!=="cloudflare")return{plan:null,errors:E};if(v.originDomain)E.push(`compute.proxy.cdn.originDomain (${v.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 ot=P("CLOUDFLARE_API_TOKEN");if(!ot)return E.push("CLOUDFLARE_API_TOKEN is not set — the Cloudflare CDN cannot be reconciled."),{plan:null,errors:E};let Ie=l.sites??{},Ne=v.frontedHosts?.length?[...new Set(v.frontedHosts.map((pr)=>pr.toLowerCase()))]:Nn(Ie,{autoWww:l.infrastructure?.compute?.proxy?.autoWww!==!1});if(Ne.length===0)return E.push("No hostnames to front — set compute.proxy.cdn.frontedHosts, or give a site a domain."),{plan:null,errors:E};let nt=l.infrastructure?.dns?.domain,Pt=new Set(Ne.map((pr)=>Sc(pr,nt)));if(Pt.size>1)return E.push(`Fronted hosts span more than one zone (${[...Pt].join(", ")}). A Cloudflare zone is configured as a unit, so run one CDN config per zone.`),{plan:null,errors:E};let st=v.cloudflare??{},ur=v.secret?{header:v.secretHeader??"X-Origin-Verify",value:v.secret}:void 0;return{plan:{zone:[...Pt][0],hosts:Ne,apiToken:ot,zoneId:st.zoneId??P("CLOUDFLARE_ZONE_ID"),accountId:st.accountId??P("CLOUDFLARE_ACCOUNT_ID"),proxied:st.proxied!==!1,settings:st.settings??Ha,cache:st.cache,originGuard:ur,purge:st.purgeOnDeploy!==!1,skipOriginProbe:st.skipOriginProbe===!0},errors:E}}var Wu=26214400;var Hu=new Set(["/_headers","/_redirects","/_routes.json","/_worker.js"]);class Ac{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,S,P){return cs(l,`/accounts/${this.accountId}${S}`,`Bearer ${this.apiToken}`,P)}async getProject(l){try{return await this.request("GET",`/pages/projects/${l}`)}catch(S){if(S instanceof Error&&/\b8000007\b|not found/i.test(S.message))return null;throw S}}async ensureProject(l,S="main"){let P=await this.getProject(l);if(P)return P;return this.request("POST","/pages/projects",{name:l,production_branch:S})}async uploadToken(l){return(await this.request("GET",`/pages/projects/${l}/upload-token`)).jwt}async missingHashes(l,S){let P=await cs("POST","/pages/assets/check-missing",`Bearer ${l}`,{hashes:S});return new Set(P)}async upsertHashes(l,S){await cs("POST","/pages/assets/upsert-hashes",`Bearer ${l}`,{hashes:S})}async uploadBatch(l,S){let P=S.map((v)=>({key:v.hash,value:v.base64,metadata:{contentType:zu(v.extension)},base64:!0}));await cs("POST","/pages/assets/upload",`Bearer ${l}`,P)}async createDeployment(l,S,P){let v={};for(let ot of S)v[ot.path]=ot.hash;let E=new FormData;if(E.append("manifest",JSON.stringify(v)),P)E.append("branch",P);return this.request("POST",`/pages/projects/${l}/deployments`,E)}async deployDirectory(l){let S=await Wl(l.directory);if(S.length===0)throw Error(`No files to deploy in ${l.directory}`);let P=await this.uploadToken(l.project),v=await this.missingHashes(P,S.map((nt)=>nt.hash)),E=S.filter((nt)=>v.has(nt.hash)),ot=[];for(let nt=0;nt<E.length;nt+=100)ot.push(E.slice(nt,nt+100));let Ie=0;for(let nt=0;nt<ot.length;nt+=4){let Pt=ot.slice(nt,nt+4);await Promise.all(Pt.map((st)=>this.uploadBatch(P,st))),Ie+=Pt.reduce((st,ur)=>st+ur.length,0),l.onProgress?.(Ie,E.length)}return await this.upsertHashes(P,S.map((nt)=>nt.hash)),{deployment:await this.createDeployment(l.project,S,l.branch),total:S.length,uploaded:E.length,uploadedBytes:E.reduce((nt,Pt)=>nt+Pt.size,0)}}async listCustomDomains(l){return(await this.request("GET",`/pages/projects/${l}/domains`)).map((P)=>P.name)}async attachCustomDomain(l,S){if((await this.listCustomDomains(l)).includes(S))return!1;return await this.request("POST",`/pages/projects/${l}/domains`,{name:S}),!0}}function Gu(l,S){return{type:"CNAME",name:l,value:S.endsWith(".pages.dev")?S:`${S}.pages.dev`,ttl:1,proxied:!0}}async function Ic(l,S){let{blake3:P}=await import("./chunk-vs0qrm09.js").then((m)=>zh(m.default,1));return(await P(l+S)).slice(0,32)}async function Wl(l){let{readdir:S}=await import("node:fs/promises"),{join:P,relative:v,sep:E}=await import("node:path"),ot=[];async function Ie(Ne){let nt=await S(Ne,{withFileTypes:!0});for(let Pt of nt){let st=P(Ne,Pt.name);if(Pt.isDirectory()){await Ie(st);continue}if(!Pt.isFile())continue;let ur=`/${v(l,st).split(E).join("/")}`;if(Hu.has(ur))continue;let pr=await Bun.file(st).bytes();if(pr.byteLength>26214400)throw Error(`${ur} is ${pr.byteLength} bytes, over the Cloudflare Pages limit of 26214400`);let gr=Buffer.from(pr).toString("base64"),Dt=Pt.name.lastIndexOf("."),St=Dt>0?Pt.name.slice(Dt+1):"";ot.push({path:ur,hash:await Ic(gr,St),base64:gr,extension:St,size:pr.byteLength})}}return await Ie(l),ot.sort((Ne,nt)=>Ne.path.localeCompare(nt.path)),ot}function zu(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 cs(l,S,P,v){let E={Authorization:P},ot;if(v instanceof FormData)ot=v;else if(v!==void 0)E["Content-Type"]="application/json",ot=JSON.stringify(v);let Ie=await fetch(`https://api.cloudflare.com/client/v4${S}`,{method:l,headers:E,body:ot}),Ne=await Ie.text(),nt;try{nt=JSON.parse(Ne)}catch{throw Error(`Cloudflare Pages API returned ${Ie.status} with a non-JSON body: ${Ne.slice(0,200)}`)}if(!nt.success){let Pt=(nt.errors??[]).map((st)=>`${st.code}: ${st.message}`).join(", ");throw Error(`Cloudflare Pages API error (${Ie.status}): ${Pt||Ne.slice(0,200)}`)}return nt.result}export{zg as ABTestManager,ae as ACMClient,dr as ACMDnsValidator,Cc as ACME_DIRECTORIES,we as AI,ol as API_IDEMPOTENCY_TTL_MS,il as API_TOKEN_DEFAULT_TTL_MS,sl as API_TOKEN_MAX_TTL_MS,Fi as API_VERSION,de as AUTHORIZATION_CAPABILITIES,el as AUTH_ACTION_TOKEN_TTL_MS,tl as AUTH_MFA_CHALLENGE_TTL_MS,rl as AUTH_OIDC_TRANSACTION_TTL_MS,ze as AUTH_SESSION_ABSOLUTE_TTL_MS,Zd as AUTH_SESSION_IDLE_TTL_MS,CA as AWSAPIError,n as AWSClient,h as AWSCloudFormationClient,A as AWSCloudFrontClient,Gg as AWSConfigManager,kI as AWS_PSEUDO_PARAMETERS,Re as AWS_REGIONS,Lu as AcmeClient,xr as AlertEvaluator,fi as AlertStore,Ks as AnomalyConfigStore,Pd as ApiGateway,i as ApiServiceError,Ga as ApplicationAutoScalingClient,lo as Arn,D as AssetHasher,U as Auth,Oi as AuthenticationStore,Ci as AutomationApiService,xi as AutomationIdentityStore,Xo as AwsAuroraDataAdapter,ra as AwsAuroraTransport,Sa as AwsDatabaseBackupSource,mr as AwsDriver,Yo as AwsElastiCacheDataAdapter,na as AwsElastiCacheTransport,Vm as AwsIamCapabilityScanner,Ta as AwsInfrastructureBackupSource,Jo as AwsRdsDataAdapter,ta as AwsRdsTransport,ih as AwsRegionalDriver,Ra as AwsSecretsManagerConfigurationBackend,Zp as AwsSpendTransport,Da as AwsSsmConfigurationBackend,Ji as BackupCoordinator,Qg as BackupManager,ya as BackupStore,Tm as BatchProcessingManager,fn as BedrockClient,hn as BedrockRuntimeClient,gl as BitbucketSourceAdapter,jg as BlueGreenManager,Im as BounceComplaintHandler,am as BuildOptimizationManager,xl as BunDockerRuntime,uu as BunDockerVolumeRuntime,lu as BunFilesystemArchiveRuntime,ue as CDN,Ao as CHAIN_HEADER,ds as CLOUDFLARE_MANAGED_RULE_PREFIX,bd as CLOUDFRONT_FAILOVER_STATUS_CODES,TC as COMMON_CROSS_ACCOUNT_ROLES,Ue as CONTROL_PLANE_SCHEMA_VERSION,ao as Cache,go as CanaryManager,im as CertificateManager,Nf as CloudBlockVolumeDriver,Ds as CloudDriverFactory,je as CloudError,Ag as CloudFormationBuilder,h as CloudFormationClient,A as CloudFrontClient,qg as CloudTrailManager,he as CloudWatchLogsClient,Ac as CloudflarePagesProvider,Ae as CloudflareProvider,xA as CommandHistory,H as Communication,Nr as ComposeApplicationService,Lt as ComposeApplicationStore,Et as ComprehendClient,a as Compute,eg as ComputeSpendTransport,po as ConfigurationError,Na as ConfigurationService,wa as ConfigurationStore,gn as ConnectClient,ea as ContainerDataAdapter,cm as ContainerRegistryManager,va as ControlPlaneBackupSource,ma as ControlPlaneCleanupDriver,di as ControlPlaneStore,Vs as CounterTracker,jt as CredentialError,xg as CrossRegionReferenceManager,oA as DASHBOARD_ENTRY,aA as DASHBOARD_PORT_BASE,cA as DASHBOARD_PORT_SPAN,sA as DASHBOARD_STATE_DIR,vo as DEFAULT_ATTACK_MODE_HOURS,ud as DEFAULT_DDOS_THRESHOLDS,ag as DEFAULT_FAILOVER_STATUS_CODES,jc as DEFAULT_METER_MAPPINGS,qc as DEFAULT_PRICE_BOOK,Di as DEFAULT_RECURSION_LIMITS,Dn as DEFAULT_RPX_CERTS_DIR,q as DEFAULT_SERVICE_LIMITS,ig as DEFAULT_STATE_DIR,bu as DEFAULT_STATIC_ASSET_EXTENSIONS,tA as DEFAULT_STORAGE_FAILOVER_STATUS_CODES,Gf as DEFAULT_TELEMETRY_POLICY,$p as DEFAULT_THRESHOLDS,Tf as DEPLOYMENT_QUEUE_KINDS,fo as DEPTH_HEADER,_r as DETECTABLE_SIGNALS,Nl as DIAGNOSTIC_PRESETS,vm as DLQMonitoringManager,L as DNS,Am as DNSSECManager,Gi as DataServiceLifecycle,Wo as DataServiceStore,Gt as Database,tm as DatabaseUserManager,ee as DebugLogger,eA as DependencyGraph,Q as Deployment,SA as DeploymentError,Hg as DisasterRecoveryManager,vn as DnsProviderFactory,Jt as DockerDataTransport,Go as DockerDiscoveryAdapter,Pr as DockerNamedVolumeDriver,ba as DockerVolumeBackupSource,c as DurableOperationQueue,Ms as DurableQueueWorker,Be as DynamoDBClient,Er as EC2Client,_e as ECRClient,Ye as ECSClient,sr as EFSClient,Fa as ELBv2Client,Bf as ENFORCEMENT_ACTIONS,mi as ENFORCEMENT_DESCRIPTIONS,R as ENFORCEMENT_SEVERITY,up as ENVIRONMENT_LABEL,Dl as EcsRuntimeAdapter,bo as EdgeRateLimiter,et as ElastiCacheClient,m as Email,MA as EmailAdvanced,Sm as EmailAnalyticsManager,Sn as EmailClient,FA as EmailHandlers,Em as EmailTemplateManager,ia as EncryptedDataSecretStore,EA as ErrorCodes,nr as EventBridgeClient,th as EventBridgeJobAdapter,Pa as ExternalConfigurationBackend,oo as FAILOVER_REPLICA_POLICY_SID,bm as FIFOQueueManager,Vp as FOCUS_VERSION,bg as FileCache,qe as FileSystem,Ca as FilesystemBackupSource,oa as FleetService,sa as FleetStore,e as Fn,ml as GiteaSourceAdapter,ul as GithubSourceAdapter,pl as GitlabSourceAdapter,Lg as GlobalResourceManager,Oe as GoDaddyProvider,Vg as GuardDutyManager,at as HOST_SITES_DIR,TA as HashCache,_m as HealthCheckManager,He as HealthCheckRunner,yr as HetznerClient,Ce as HetznerDriver,fe as IAMClient,Ya as IPV6_EXCLUDED_HOST_LABELS,om as ImageScanningManager,Yl as InfrastructureGenerator,_c as InvalidOperationTransitionError,pt as JobLoader,rh as JobProviderReconciler,Ko as JobService,jo as JobStore,rr as KendraClient,iy as LARAVEL_SERVERLESS_BUILD_STEPS,C as LambdaClient,pm as LambdaConcurrencyManager,hm as LambdaDLQManager,gm as LambdaDestinationsManager,lm as LambdaLayersManager,Pl as LambdaRuntimeAdapter,mm as LambdaVPCManager,um as LambdaVersionsManager,cn as LocalEncryptedConfigurationBackend,Ea as LogicalDatabaseBackupSource,Xg as LogsManager,qA as MANAGED_NODE_VERSIONS,Ec as MANAGEMENT_DASHBOARD_SITE,yg as MANAGEMENT_DASHBOARD_SITE_PREFIX,Bi as MAX_CONTROL_HOURS,Oc as MAX_CONTROL_PLANE_ERROR_BYTES,Bp as MAX_CONTROL_PLANE_JSON_BYTES,Hs as METERS,kf as METER_KEYS,_f as MICRO_CENTS,Mp as MIN_PROJECTION_CONFIDENCE,Ru as MTA_STS_PORT,ga as MaintenanceService,pa as MaintenanceStore,Z as Messaging,Jg as MetricsManager,Yg as MigrationManager,Dg as MockCloudFormation,Ng as MockDynamoDB,Pg as MockS3,co as Monitoring,Fg as MultiAccountManager,Og as MultiRegionManager,PA as MultiStepProgress,f as Network,Om as NetworkSecurityManager,Ai as NotificationRouter,lg as ORIGIN_CONNECTION_ATTEMPTS,ug as ORIGIN_CONNECTION_TIMEOUT,cg as ORIGIN_GROUP_ALLOWED_METHODS,DI as ORIGIN_GROUP_ID_SUFFIX,dg as ORIGIN_GROUP_SELECTION_CRITERIA,Ua as OpenSearchClient,ct as OptimisticConcurrencyError,Ug as OrganizationManager,Wu as PAGES_MAX_FILE_BYTES,sy as PHP_DEFAULT_EXCLUDES,VA as PHP_LAYER_EXTENSIONS,lp as PROJECT_LABEL,rt as PROXIABLE_RECORD_TYPES,b as ParameterStore,em as PerformanceManager,Y as Permissions,Qa as PersonalizeClient,Ve as Phone,UA as PhoneAdvanced,rA as PhoneHandlers,ca as PlacementService,aa as PlacementStore,An as PollyClient,se as PorkbunProvider,Jr as PreDeployScanner,kg as PreviewEnvironmentManager,Dr as PreviewEnvironmentService,Qe as PreviewEnvironmentStore,Bg as PreviewNotificationService,DA as ProgressBar,Kg as ProgressiveDeploymentManager,To as ProtectionControlStore,yI as Pseudo,M as Queue,li as QueueCancellationError,wm as QueueManagementManager,hI as QueuePresets,$s as QueueTimeoutError,Vd as RATE_LIMIT_KEY_SEPARATOR,j as RDSClient,$A as RECOMMENDED_ACCOUNT_STRUCTURES,vC as RECOMMENDED_SCPS,Qm as RELEASE_QUEUE_KINDS,BA as REPL,OA as REPLCommandBuilder,_A as REPLContext,pp as ROLE_LABEL,wA as RateLimiter,fI as RealtimePresets,jp as RecordingSpendTransport,Io as RecursionGuard,gt as Redirects,$g as RegionPairManager,la as RegionService,da as RegionStore,Ge as Registry,bt as RekognitionClient,mt as ReleaseService,Oo as ReleaseStore,nh as RemoteBuildService,Zg as ReplicaManager,xm as ResourceManagementManager,X as RetryableOperationError,y as Route53Client,Ma as Route53DomainsClient,z as Route53Provider,ym as Route53ResolverManager,fm as Route53RoutingManager,ge as RuntimeOperationService,Vo as RuntimeStreamRegistry,Ia as S3BackupDestinationAdapter,o as S3Client,G as S3Error,Al as SECRET_PATTERNS,Gp as SENSITIVITY_THRESHOLDS,tt as SESClient,F as SMS,Ze as SNSClient,Yp as SPEND_CYCLE_SECONDS,sd as SPEND_GATE_SETTING,zf as SPEND_LEASE_SETTING,ne as SQSClient,Ee as SSH_BOOTSTRAP_VERSION,Vn as SSH_PREFLIGHT_SCRIPT,be as SSMClient,sg as STATE_DIR_ENV_VAR,Ha as STATIC_SITE_ZONE_SETTINGS,wd as STORAGE_FAILOVER_METADATA_KEY,me as STSClient,yn as SchedulerClient,qt as Search,Xr as SecretFindingScanner,vi as Secrets,nm as SecretsManager,V as SecretsManagerClient,rm as SecretsRotationManager,I as Security,Hr as SecurityHubManager,Wr as SecurityPostureStore,ht as SecurityScannerRunner,sm as SecurityScanningManager,Cm as SenderReputationManager,eh as ServerCronJobAdapter,Zo as ServerDataAdapter,Qs as ServerPathVolumeDriver,dm as ServiceMeshManager,Dd as Sftp,Js as SignalSource,QA as SmsAdvanced,Tt as SmsClient,nA as SmsHandlers,ja as SmsVoiceClient,xo as SourceConnectionStore,Kt as SourceProviderError,od as SpendCapError,Or as SpendGate,Jp as SpendLoopLease,to as SpendNotificationRouter,Xp as SpendRunner,Mt as SpendService,pi as SpendStore,NA as Spinner,Sr as SshDriver,en as SshFleetDriver,Mg as StackDependencyManager,NI as StacksIntegration,km as StaticSiteManager,ve as Storage,Bm as StorageAdvancedManager,In as SupportClient,Gr as SyntheticsManager,Ll as SystemFleetSshTransport,Ir as SystemSshTransport,qo as SystemdDiscoveryAdapter,yo as TRACE_HEADER,kA as TaskList,ut as TelemetryStore,Cd as TemplateBuilder,vg as TemplateCache,vt as TextractClient,mn as TranscribeClient,tr as TranslateClient,ah as TransportDisasterRecoveryDriver,oh as TransportPlatformMaintenanceDriver,qi as TransportRemoteBuildDriver,Qo as TrivyImageScanner,_o as TsCloudApiError,al as TsCloudClient,jf as URGENT_SPEND_EVENTS,Fp as USER_VISIBLE_ACTIONS,ua as UnavailableRegionalDriver,oe as UnifiedDnsValidator,Os as UnsupportedSchemaVersionError,Cg as ValidationError,ir as VoiceClient,Us as VolumeService,xt as VolumeStore,iA as Workflow,Wg as XRayManager,ZC as abTestManager,cl as activateImmutableRelease,Ou as addDns01ChallengeRecord,rn as addSiteToCloudConfig,At as ageSeconds,Kc as aggregateDeltas,Pp as allocateSitePorts,wI as analyzeStackDiff,hi as anomalyOptionsForSignal,wo as applyControlsToDdos,Jd as applyControlsToRateLimits,ms as applyDeclaredZoneSettings,Mr as applyMitigationFactor,of as applyPlan,ys as applyZoneMigration,Od as artifactKey,Qt as assertOriginGroupMethods,Li as assertReleaseStrategy,Hf as assertSpendAllows,uf as attachConflicts,pf as attachIsViable,lf as attachPreconditions,El as attachProvenanceToRelease,Ho as attachSbomToRelease,Sl as attachVulnerabilitySummary,Fm as authEncryptionKeyFile,w as authorizeOrganization,Ym as authorizeRuntimePath,eC as autocomplete,zC as awsConfigManager,cu as backupCredentialStatus,VC as backupManager,IS as batch,BE as batchProcessingManager,ko as beginOidcAuthorization,XC as blueGreenManager,wE as bounceComplaintHandler,dt as budgetWindow,xa as buildAndPushServerlessImage,xE as buildBunRuntimeLayerZip,yf as buildCertificatePackScript,hf as buildCertificateStateScript,If as buildCertificateUnpackScript,Nd as buildCloudFormationTemplate,hc as buildCloudInitFirstBoot,Mc as buildComposeLogsCommand,iI as buildComposeRuntimeCommand,sI as buildComposeScaleCommand,Fc as buildComposeShellCommand,wp as buildDrainSourceScript,Jh as buildDrainedSiteScanScript,Rd as buildFailoverReplicaPolicyStatement,Yt as buildFunctionEnv,Tp as buildHealthGateScript,Ln as buildHostCleanupDeployScript,Ts as buildHostCleanupInstallScript,xn as buildHostCleanupScript,ai as buildHostSitePortsScript,Sd as buildMailEnv,Ns as buildManagementDashboardArtifact,Xu as buildMediaCdnPlan,wu as buildMtaStsPolicy,Ph as buildMtaStsServer,OE as buildNodeRuntimeLayerZip,mE as buildOptimizationManager,pg as buildOriginGroup,Fr as buildOriginGroups,Ka as buildOriginGuardRule,yp as buildPauseWorkersScript,FE as buildPhpRuntimeLayerZip,fg as buildReplicationConfiguration,hg as buildReplicationRole,Ep as buildRestoreScript,K as buildRpxConfig,xe as buildRpxFragmentRefreshScript,cf as buildSetHostnameScript,Mn as buildSiteDeployScript,Cp as buildSnapshotScript,Rp as buildSourceStateScript,Bn as buildSshArgs,Gn as buildSshBootstrapScript,za as buildStaticSiteCacheRules,Un as buildStaticSiteDeployScript,bp as buildTargetStateScript,Ip as buildWorkersStateScript,vl as bytes,YC as canaryManager,tn as canonicalJson,ft as capabilities,Xt as capacity,DS as categorizeChanges,uE as certificateManager,Af as certificatesMatch,cS as checkIAMPermissions,XA as checkInvocation,lS as checkServiceQuotas,RA as chunk,ph as cleanupDns01Challenge,uI as clearSigningKeyCache,$o as cloneSourceBinding,kS as cloudConfigSchema,Yu as cloudDrivers,KC as cloudTrailManager,Wl as collectAssets,Co as collectPhpAppEntries,vu as collectServerDnsDomains,_p as completeComposeVolumeDeletion,Bo as completeOidcAuthorization,WI as composePresets,Ls as composeProjectName,Ld as composeServerlessAppTemplate,Wf as compositeSpendTransport,Ct as compressBackup,ay as config,_l as connectionGuidance,hE as containerRegistryManager,bf as controlPlaneDatabaseFile,kc as controlPlaneMigrations,$I as createApiBackendPreset,Uo as createApiV1Handler,fy as createAsgBuildDriver,du as createBackupQueueHandlers,ry as createCliHandler,k as createCloudDriver,mc as createCloudFrontPolicy,nS as createCredentialProvider,zI as createDashboardSite,HI as createDataPipelinePreset,Ol as createDataServiceQueueHandlers,Uc as createDeploymentQueueHandlers,T as createDnsProvider,hy as createEcsBuildDriver,ad as createEnforcementHandlers,Eg as createError,kd as createExistingStaticFullStackPreset,$l as createFleetQueueHandlers,LI as createFullStackAppPreset,Cs as createGoDaddyValidator,ME as createHandlers,ey as createHttpHandler,FI as createJamstackPreset,Bl as createJobQueueHandlers,VI as createLaravelPreset,GI as createMLApiPreset,ql as createMaintenanceQueueHandlers,Zu as createMediaAccessToken,UI as createMicroservicesPreset,$S as createMockAWS,_I as createNodeJsServerPreset,OI as createNodeJsServerlessPreset,as as createObjectStorageClient,Ss as createPorkbunValidator,JI as createPreset,Xf as createPresignedUrl,oI as createPresignedUrlAsync,ty as createQueueHandler,QI as createRealtimeAppPreset,Fl as createRegionQueueHandlers,Cl as createReleaseProvenance,ll as createReleaseQueueHandlers,gy as createRemoteBuildQueueHandlers,Es as createRoute53Validator,Xm as createRuntimeAdapters,iS as createS3Client,my as createServerBuildDriver,jI as createServerlessLaravelPreset,xI as createServerlessNodePreset,Eu as createSmsInfrastructure,We as createSourceAdapter,BI as createStaticSitePreset,qI as createTraditionalWebAppPreset,Qc as createVolumeQueueHandlers,MI as createWordPressPreset,Ri as createZip,cC as crossRegionReferenceManager,dn as dashboardActions,Ps as dashboardCredentialsFile,Zr as dataServiceCapabilities,cE as databaseUserManager,Yd as decodeBase32,ke as decompressBackup,Ah as decryptBackup,Ro as defaultConfig,Rg as defaultLocalConfig,zd as defaultRateLimitRules,cr as delegateZone,ps as delegateZoneFromConfig,iu as deleteFailoverReplicaBuckets,_a as deleteStaticSite,vc as deployAllComputeSites,fa as deployServerlessApp,su as deploySite,ks as deploySiteRelease,es as deployStaticSite,Oa as deployStaticSiteFull,ln as deployStaticSiteWithExternalDns,un as deployStaticSiteWithExternalDnsFull,yd as deploymentCoexistenceError,dA as deriveManagementDashboardPort,gs as describeDelegation,Wd as describePosture,hs as describeZoneSettings,Zm as desiredJobProviderState,Hp as detectAnomalies,og as detectDeploymentTargets,Wa as detectDnsProvider,rd as detectLatestAnomaly,oS as detectMisconfigurations,rg as detectServiceRegion,Lc as diffCompose,TS as diffTemplates,Lo as discoverGitRefs,No as discoverOidcProvider,Tl as discoverRuntimeInventory,kE as dlqMonitoringManager,Ja as dnsProviders,vE as dnssecManager,Km as dockerWorkloads,Vi as documentDigest,jC as drManager,$e as driverStatePath,wl as ecsWorkloads,Ot as effectiveCapabilities,RE as emailAnalyticsManager,PE as emailTemplateManager,_i as encodeBase32,fh as encryptBackup,bl as ensureDefaultSecurityPolicies,tu as ensureFailoverReplicaBuckets,Yn as ensureFirewall,ti as ensureManagementDashboard,Zn as ensureServer,Xn as ensureSshKey,J as escapeSecLang,Jc as evaluateBudget,zn as evaluatePreflight,eo as evaluateTelemetryAlertRules,kl as eventBridgeScheduleInput,ZA as eventToRequest,Ff as ewma,xc as exportCompose,fs as exportRoute53Zone,Sg as extendPreset,NE as fifoQueueManager,yS as findChangedFiles,xp as findMapping,Op as findPriceEntry,PC as formatAccountStructure,gf as formatAttachPlan,jS as formatBytes,Lr as formatCents,RI as formatDiff,Yh as formatDrainedSiteRefusal,zS as formatDuration,rC as formatFlagSuggestions,sC as formatHistory,oC as formatHistoryStats,rf as formatInventory,WS as formatKeyValue,KS as formatList,sf as formatPlan,Wn as formatPreflightFindings,VS as formatProgressBar,LA as formatRegion,SC as formatRegionList,qm as formatScanResults,JS as formatSuggestion,GS as formatTable,Br as formatTimeToExhaustion,qS as formatTree,mA as fromEC2Metadata,hA as fromECSMetadata,pA as fromEnvironment,gA as fromSharedCredentials,fA as fromWebIdentity,Md as functionFingerprint,Nn as gatewayHostnames,$d as generateAppImageDockerfile,GC as generateApprovalConfig,HA as generateBootstrap,US as generateCleanupWorkflow,QS as generateCostReportWorkflow,RC as generateCrossAccountRoleCF,yl as generateCycloneDxSbom,UC as generateDeploymentConfig,xC as generateDeploymentPipeline,NC as generateDeploymentWorkflow,Ba as generateExternalDnsStaticSiteTemplate,dh as generateHttpsServerCode,Il as generateImageSbom,lh as generateLetsEncryptUserData,t as generateLogicalId,FC as generateManualPipeline,OC as generateMatrixWorkflow,QC as generateMultiEnvConfig,LC as generateMultiEnvPipeline,kC as generateMultiEnvWorkflow,BC as generatePRPreviewWorkflow,qC as generateParallelConfig,ny as generatePhpFpmConfig,zA as generatePhpLayerDockerfile,$C as generatePreviewPipeline,FS as generatePreviewWorkflow,r as generateResourceName,HC as generateScheduledConfig,MC as generateScheduledPipeline,_C as generateScheduledWorkflow,Zi as generateStaticSiteTemplate,N as generateUbuntuAppCloudInit,IA as getAccountId,pC as getAllRegions,AC as getClosestRegion,nC as getCommandUsage,vf as getComposeTemplate,Lm as getConfig,YS as getContextualHelp,uo as getCredentials,PS as getDeploymentStrategy,NS as getDiffStats,wS as getDiffSummary,bA as getErrorDetails,_d as getLocalConfig,xS as getLocalCredentials,OS as getLocalEndpoint,LS as getLocalEnvVars,uS as getQuotaUsageSummary,wC as getRecommendedStructure,wi as getRegion,CC as getRegionStats,mC as getRegionsByCompliance,gC as getRegionsByLocation,hC as getRegionsByPricingTier,vA as getRequiredPermissions,pI as getSigningKeyCacheSize,Cu as getSmsInfrastructureStatus,II as getTimestamp,Eo as globMatches,Bs as globToRegex,dC as globalResourceManager,gi as governingLimitCents,ru as grantFailoverReplicaAccess,WC as guardDutyManager,ro as handleSpendRequest,Pn as hasAutoWwwVariant,Vt as hasManagementDashboardSite,Nc as hasProxyUpstream,mS as hashBuffer,hS as hashDirectory,Tg as hashFile,fS as hashManifest,wg as hashString,HE as healthCheckManager,Tn as hostAcceptsIpv6,Cn as hostCondition,Do as hotp,kr as hourBucket,Mf as hourBucketsBetween,gE as imageScanningManager,Ki as infraEnvFromOutputs,Ud as inspectInvocation,WA as installRecursionFetch,rs as invalidateCache,Pm as invocationContext,XS as isLikelyTypo,Rn as isLocalDatabase,_S as isLocalDevelopment,Ur as isManagementDashboardSiteName,or as isNameserverRegistrar,gI as isNodeCryptoAvailable,td as isOperationAllowed,Zs as isQuietHours,Td as isS3RestEndpoint,ni as isSafePattern,fd as isStateDirConfigured,Ad as isStatePath,$r as isValidCidr,fC as isValidRegion,ui as isValidTimeZone,mI as isWebCryptoAvailable,ar as isZoneHost,Yr as jobProviderCapability,os as keyMatchesFilters,IE as lambdaConcurrencyManager,EE as lambdaDLQManager,SE as lambdaDestinationsManager,AE as lambdaLayersManager,CE as lambdaVPCManager,yE as lambdaVersionsManager,Rl as lambdaWorkloads,Gd as laravelServerlessEnvDefaults,Rr as listComposeTemplates,Mi as listSourceReferences,Xd as loadCloudConfig,Ft as loadTelemetryPolicy,nE as logsManager,nd as lookbackHoursForSignal,Zf as mailEnabled,Id as mailFirewallPorts,sh as maintenanceWindowOpen,Yf as makeAWSRequest,cI as makeAWSRequestAsync,aI as makeAWSRequestOnce,Ig as managementDashboardSiteName,Ul as manifestDigest,Vr as matchTotpCounter,Ju as mediaObjectHeaders,zs as median,Up as medianAbsoluteDeviation,Xc as mergeDecisions,Qr as mergeInfrastructure,Lf as mergePriceBooks,zc as meterTelemetry,rE as metricsManager,Au as migrateObjectStorage,sE as migrationManager,EC as multiAccountManager,aC as multiRegionManager,mh as needsRenewal,GE as networkSecurityManager,yt as nextScheduleRuns,ye as normalizePublicIpv6,De as normalizeRuntimeStatus,Je as normalizeScheduleExpression,Hm as normalizeSourceEvent,Le as normalizeSshPublicKey,zp as normalizeTelemetryPolicy,oi as occupiedHostPorts,Fo as openApiDocument,Xs as optionsForSignal,bC as organizationManager,qd as packagePhpApp,qr as packageServerlessApp,Ic as pagesAssetHash,Gu as pagesDnsRecord,Bd as parallel,SS as parallelMap,CS as parallelWithRetry,ff as parseCertificateState,Fd as parseChain,wr as parseCompose,rI as parseComposeCatalog,zm as parseDockerInspect,pu as parseDotenv,Xh as parseDrainedSites,ci as parseHostSiteFragments,lI as parseJSONResponse,jn as parsePreflightFacts,Dp as parseSourceDrained,Wm as parseSystemdRecords,vp as parseTargetReady,Pc as parseUpstreamPort,Sp as parseWorkersPaused,dI as parseXMLResponse,Ii as pathTemplate,Rc as pendingSteps,js as percentOfLimit,aE as performanceManager,Rm as phpLayerBuildStage,jA as phpLayerPackages,Pi as phpRuntimeLayerAssets,nI as planComposeTemplateUpgrade,Yc as planEnforcement,fp as planIsDestructive,tg as planMitigation,af as planServerRename,Sf as planSiteMove,As as planZoneMigration,wt as policyTag,Kn as preflightFailed,MS as previewManager,HS as previewNotifications,It as previewSchedule,$f as previousBudgetWindow,Gs as priceUsage,Of as priceUsageLines,ef as probeHostRoutes,ac as probeOriginTls,vS as processInChunks,hl as processSourceWebhook,Qi as productionChangeReview,eE as progressiveDeploymentManager,Wc as projectSpend,Qd as propagationHeaders,La as providerEndpoint,Ql as publicKeyFingerprint,En as qualifyName,_E as queueManagementManager,AS as quickHash,jd as rateLimitHeaders,ki as rateLimitKey,Me as readDriverState,tf as reconcile,Tu as reconcileAddressRecords,Bu as reconcileCloudflareCdn,us as reconcileDeclaredRecords,py as reconcileJobObservation,Kr as reconcileSourceWebhook,Ui as recordDashboardHostPosture,dy as recordPreDeploySecretScan,ly as recordSkippedSecretScan,Hd as recursionBlockedResponse,Pe as redactRuntimeConfig,ld as redactTelemetryText,yi as redactTelemetryValue,sn as redeployServerlessApp,lC as regionPairManager,zr as releaseStrategyCapabilities,Um as releaseTrafficPlan,ri as reloadRpxGateway,ss as remapKey,Nu as removeDns01ChallengeRecord,nn as removeSiteFromCloudConfig,fl as removeSourceWebhook,Xa as removeStaleServerAddressRecords,$c as renderComposeTemplate,Ei as renderDdosInstallScript,md as renderNftablesRuleset,Hi as renderServerCron,gd as renderSysctlFile,wc as renderWafConfig,ii as renderWafInstallScript,Tc as renewRpxCertificates,oE as replicaManager,Jf as requestHash,RS as requiresReplacement,LE as resetRecursionRuntime,$E as resolveApp,p as resolveAppDatabase,df as resolveAttachTarget,Ke as resolveAuthEncryptionKey,le as resolveCloudProvider,Vu as resolveCloudflareCdnPlan,AA as resolveCredentials,Yi as resolveDashboardAction,bc as resolveDashboardAuth,lA as resolveDashboardDomain,uA as resolveDashboardDomains,ls as resolveDeclaredRecords,TI as resolveDeployBucketName,x as resolveDeploymentMode,$n as resolveExecStart,vd as resolveFailoverStatusCodes,cc as resolveHetznerApiToken,Ar as resolveHostCleanupConfig,bi as resolveMailService,KI as resolveManagementDashboardSite,Ti as resolveManagementDashboardSites,$a as resolveObjectStorage,Te as resolveOriginConnection,nf as resolvePlan,g as resolveProjectStackName,Tr as resolveProxyUpstreams,xd as resolveQueueNames,wf as resolveQueuedDeploymentCommand,zt as resolveQueues,KA as resolveRecursionConfig,yA as resolveRegion,re as resolveRuntimeInventory,Ut as resolveServerlessAppStackName,Ed as resolveServerlessArtifactBucketName,so as resolveServerlessAssetBucketName,ho as resolveServerlessRuntime,bI as resolveSiteBucketName,_s as resolveSiteDeployTarget,u as resolveSiteKind,EI as resolveSiteResourceName,CI as resolveSiteStackName,qn as resolveSshSettings,d as resolveStatePath,vI as resolveStorageBucketName,gg as resolveStorageFailover,kt as resolveUiSource,Sc as resolveZoneApex,qE as resourceManagementManager,Nm as responseToResult,Qp as robustZScore,_t as roleCapabilities,dl as rollbackImmutableRelease,on as rollbackServerlessApp,xf as roundCents,TE as route53ResolverManager,bE as route53RoutingManager,qp as routeMatches,gp as routesFromFragments,Ni as ruleMatches,GA as runBuildHooks,Zc as runEnforcement,So as runPhpBuildHooks,Xe as runRemoteCommand,pe as runtimeId,mg as s3RegionalDomain,bn as sameNameservers,Xi as sanitizeCloudConfig,s as sanitizeControlPlaneValue,SI as sanitizeName,nl as sanitizeOidcReturnPath,cd as saveTelemetryPolicy,Gm as scanForSecrets,Bc as scopeContains,lt as scopeKey,rc as scpUpload,ZS as searchCommands,xs as searchControlPlane,lE as secretsManager,dE as secretsRotationManager,uy as secureContainerRelease,JC as securityHubManager,pE as securityScanningManager,te as securityScope,nu as seedFailoverReplicas,jr as sendAuthenticationEmail,DE as senderReputationManager,ES as sequence,gu as serializeDotenv,ei as serverPublicIpv4,fE as serviceMeshManager,Xl as setAttachToInCloudConfig,Zt as setMaintenance,ji as setSitePropertyInCloudConfig,hd as setStateDir,uh as setupDns01Challenge,Va as setupSmsInfrastructure,mo as sha256,JA as sharedRecursionGuard,Dm as sharedRuntimeLoop,kp as shipsARelease,ju as signCloudFrontCookies,Ku as signCloudFrontUrl,_ as signRequest,ng as signRequestAsync,Ws as signalDefinition,B as siteInstallBase,si as siteMoveArchivePath,mf as siteMoveCertArchivePath,Dc as siteUnitGlob,Wp as spendNotificationText,no as spendOpenApiPaths,hr as sshExec,ce as sshExecOrThrow,uC as stackDependencyManager,ka as startLocalDashboardServer,Kf as startSpendLoop,io as stateDir,O as statePath,UE as staticSiteManager,QE as storageAdvancedManager,PI as storageFailoverReplicasFromTemplate,Uf as streamFocusJsonl,ed as strongestActiveAction,_g as suggestCommand,tC as suggestFlags,dS as suggestIAMPolicy,pS as suggestQuotaIncrease,IC as suggestRegionPairs,yC as suggestRegions,$i as syncSourceRepositories,Hc as synchronizeComposeVolumes,mu as synchronizeConfiguredConfiguration,zo as synchronizeConfiguredJobs,iE as syntheticsManager,pd as sysctlHardening,Jm as systemdWorkloads,Vf as telemetryBucketLabel,Si as telemetryCursor,dd as telemetryEstimatedMonthlyCost,qf as telemetryPercentile,Kp as telemetryPolicyKey,gS as templateCache,mp as tenantsOf,Mo as testSourceConnection,Gc as tieredMicroCents,oc as toCloudflareZoneSettings,Ys as toFocusJsonl,id as toFocusRecords,Zh as toInventoryServer,$m as totp,Po as totpUri,hp as unaccountedSites,jm as unsupportedCapabilities,Rf as unsupportedVolumeCapabilities,Gl as updateCompatibility,Vl as updateSiteInCloudConfig,ts as uploadStaticFiles,Lp as usageDeltaKey,$t as utcInstantOfLocal,DC as validateAccountStructure,BS as validateAgainstSchema,Pf as validateAttachment,hh as validateBackupDestination,iC as validateCommand,sS as validateConfiguration,aS as validateCredentials,Np as validateDeploymentConfig,Df as validateMountPath,Ht as validateOriginGroups,yu as validateResourceLimits,Ap as validateServerName,Kd as validateTemplate,hu as validateTemplateSize,Za as verifyAddressRecord,cy as verifyArtifactSignature,qu as verifyMediaAccessToken,Mm as verifyTotp,Hl as verifyUpdateSignature,Is as verifyZoneParity,Fs as volumeCapabilities,dp as wafEventTelemetry,nc as waitForCloudInit,_n as waitForSsh,Wt as webhookEndpoint,tS as withCDN,eS as withCache,ZI as withDatabase,YA as withInvocation,XI as withMonitoring,rS as withQueue,YI as withSecurity,bS as withTimeout,W as wrapCloudInitUserData,it as writeDriverState,tE as xrayManager,Ml as zeroCapacity,Qf as zeroFill,Vc as zoneOffsetMs,qs as zonedParts};
604
+ `}async function Tu(l,h,C){let b=`_acme-challenge.${h}`;if(await vu(l,h,b,C))return;let T=await l.createRecord(h,{name:b,type:"TXT",content:C,ttl:60});if(!T.success)throw Error(`Failed to create DNS challenge record: ${T.message}`)}async function $u(l,h,C){let b=await l.deleteRecord(h,{name:`_acme-challenge.${h}`,type:"TXT",content:C});if(!b.success)console.warn(`Failed to delete DNS challenge record: ${b.message}`)}async function vu(l,h,C,b){try{let T=await l.listRecords(h,"TXT"),Ee=C.replace(/\.$/,"").toLowerCase();return(T.records??[]).some((oe)=>oe.name.replace(/\.$/,"").toLowerCase()===Ee&&oe.content.replace(/^"|"$/g,"")===b)}catch{return!1}}function fc(l){let{hostedZoneId:h,dnsProvider:C,region:b="us-east-1"}=l;if(C)return w(C);if(h)return new W(b,h);throw Error("Either dnsProvider or hostedZoneId must be provided")}async function ef(l){await Tu(fc(l),l.domain,l.challengeValue)}async function Rf(l){await $u(fc(l),l.domain,l.challengeValue)}function wf(l){try{let{execSync:h}=He("node:child_process"),C=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 gc,createSign as Ou,generateKeyPairSync as hc}from"node:crypto";var yc={production:"https://acme-v02.api.letsencrypt.org/directory",staging:"https://acme-staging-v02.api.letsencrypt.org/directory"};class xu{directoryUrl;email;accountKey;accountUrl=null;directory=null;nonce=null;constructor(l){this.directoryUrl=l.staging?yc.staging:yc.production,this.email=l.email,this.accountKey=l.accountKey||this.generateAccountKey()}generateAccountKey(){let{privateKey:l}=hc("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 b=this.nonce;return this.nonce=null,b}let l=await this.getDirectory(),C=(await fetch(l.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!C)throw Error("Failed to get nonce from ACME server");return C}getJwk(){let l=this.accountKey.split(`
605
+ `).filter((Ee)=>!Ee.startsWith("-----")).join(""),h=Buffer.from(l,"base64"),C=h.length-65,b=h.subarray(C+1,C+33),T=h.subarray(C+33,C+65);return{kty:"EC",crv:"P-256",x:this.base64UrlEncode(b),y:this.base64UrlEncode(T)}}getJwkThumbprint(){let l=this.getJwk(),h=JSON.stringify({crv:l.crv,kty:l.kty,x:l.x,y:l.y}),C=gc("sha256").update(h).digest();return this.base64UrlEncode(C)}base64UrlEncode(l){return(typeof l==="string"?Buffer.from(l):l).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async signPayload(l,h){let C=await this.getNonce(),b=this.getJwk(),T={alg:"ES256",nonce:C,url:l};if(this.accountUrl)T.kid=this.accountUrl;else T.jwk=b;let Ee=this.base64UrlEncode(JSON.stringify(T)),oe=h===""?"":this.base64UrlEncode(JSON.stringify(h)),ae=`${Ee}.${oe}`,be=Ou("SHA256");be.update(ae);let lt=be.sign(this.accountKey),_e=lt.subarray(4,4+lt[3]),_t=4+lt[3]+2,nr=lt.subarray(_t,_t+lt[_t-1]),fr=Buffer.alloc(32),dt=Buffer.alloc(32);_e.copy(fr,32-_e.length),nr.copy(dt,32-nr.length);let ot=Buffer.concat([fr,dt]);return JSON.stringify({protected:Ee,payload:oe,signature:this.base64UrlEncode(ot)})}async acmeRequest(l,h){let C=await this.signPayload(l,h),b=await fetch(l,{method:"POST",headers:{"Content-Type":"application/jose+json"},body:C}),T=b.headers.get("replay-nonce");if(T)this.nonce=T;let Ee,oe=b.headers.get("content-type");if(oe?.includes("application/json")||oe?.includes("application/problem+json"))Ee=await b.json();else Ee=await b.text();if(!b.ok)throw Error(`ACME request failed: ${JSON.stringify(Ee)}`);return{body:Ee,headers:b.headers}}async registerAccount(){let l=await this.getDirectory(),{body:h,headers:C}=await this.acmeRequest(l.newAccount,{termsOfServiceAgreed:!0,contact:[`mailto:${this.email}`]}),b=C.get("location");if(!b)throw Error("No account URL returned");return this.accountUrl=b,b}async createOrder(l){if(!this.accountUrl)await this.registerAccount();let h=await this.getDirectory(),{body:C,headers:b}=await this.acmeRequest(h.newOrder,{identifiers:l.map((Ee)=>({type:"dns",value:Ee}))}),T=b.get("location");if(!T)throw Error("No order URL returned");return{orderUrl:T,authorizations:C.authorizations,finalize:C.finalize}}async getAuthorization(l){let{body:h}=await this.acmeRequest(l,""),C=h.identifier.value,b=this.getJwkThumbprint(),T=h.challenges.filter((Ee)=>Ee.type==="http-01"||Ee.type==="dns-01").map((Ee)=>{let oe=`${Ee.token}.${b}`;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(gc("sha256").update(oe).digest());return{type:"dns-01",token:Ee.token,keyAuthorization:oe,identifier:`_acme-challenge.${C}`,dnsValue:ae}}});return{domain:C,challenges:T}}async respondToChallenge(l){await this.acmeRequest(l,{})}async waitForAuthorization(l,h=30){for(let C=0;C<h;C++){let{body:b}=await this.acmeRequest(l,"");if(b.status==="valid")return;if(b.status==="invalid")throw Error(`Authorization failed: ${JSON.stringify(b)}`);await new Promise((T)=>setTimeout(T,2000))}throw Error("Authorization timed out")}generateCsr(l){let{privateKey:h}=hc("rsa",{modulusLength:2048}),C=h.export({type:"pkcs8",format:"pem"});return{csr:this.createSimpleCsr(l,h),privateKey:C}}createSimpleCsr(l,h){throw Error("CSR generation requires additional implementation. Consider using the shell-based certbot approach instead.")}async finalizeOrder(l,h){let{csr:C,privateKey:b}=this.generateCsr(h),{body:T}=await this.acmeRequest(l,{csr:this.base64UrlEncode(Buffer.from(C,"base64"))}),Ee=T.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),lt=be[0],_e=be.slice(1).join("");return{certificate:lt,privateKey:b,chain:_e,fullchain:ae,expiresAt:new Date(Date.now()+7776000000)}}getAccountKey(){return this.accountKey}}var Xi=(l)=>l===void 0?void 0:l?"on":"off";function ks(l){let h={ssl:l.ssl,always_use_https:Xi(l.alwaysUseHttps),automatic_https_rewrites:Xi(l.automaticHttpsRewrites),min_tls_version:l.minTlsVersion,tls_1_3:Xi(l.tls13),brotli:Xi(l.brotli),http3:Xi(l.http3),"0rtt":Xi(l.zeroRtt),early_hints:Xi(l.earlyHints),browser_cache_ttl:l.browserCacheTtl,always_online:Xi(l.alwaysOnline),websockets:Xi(l.websockets),email_obfuscation:Xi(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 C of Object.keys(h))if(h[C]===void 0)delete h[C];return{...h,...l.raw??{}}}var Vn={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 Lu}from"node:tls";async function ic(l){let{address:h,serverName:C,port:b=443,timeoutMs:T=5000}=l;return new Promise((Ee)=>{let oe=!1,ae=(lt)=>{if(oe)return;oe=!0;try{be.destroy()}catch{}Ee(lt)},be=Lu({host:h,port:b,servername:C,rejectUnauthorized:!1,timeout:T});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 ${T}ms`})}),be.once("error",(lt)=>{ae({reachable:!1,trusted:!1,reason:lt.message})})})}function Fu(l,h){let C=h.replace(/\.$/,"").toLowerCase();return l.some((b)=>{let T=b.replace(/\.$/,"").toLowerCase();if(T===C)return!0;if(!T.startsWith("*."))return!1;let Ee=T.slice(2);if(!C.endsWith(`.${Ee}`))return!1;return!C.slice(0,C.length-Ee.length-1).includes(".")})}async function Mu(l){let{provider:h,zone:C,hosts:b,ipv4:T,ipv6:Ee,proxied:oe=!0,settings:ae=Vn,cache:be,originGuard:lt,purge:_e=!0,ttl:_t=300,skipOriginProbe:nr=!1,skipEdgeCertificateCheck:fr=!1}=l,dt={records:[],settingsChanged:[],cacheRules:0,originGuard:!1,purged:!1,deferredProxy:[],warnings:[]};if(b.length===0)return dt;let ot=[],_=oe&&!fr?await h.listEdgeCertificateHosts(C):null;for(let N of b){let ct=oe;if(ct&&_&&!Fu(_,N)){ct=!1;let xt=_.length===0?"the zone has no active edge certificate yet":`no active edge certificate covers it (${_.join(", ")})`;dt.deferredProxy.push({host:N,reason:xt}),dt.warnings.push(`${N}: 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(ct&&!nr){let xt=await ic({address:T,serverName:N});if(!xt.trusted){ct=!1;let Bt=xt.reason||"origin is not serving a trusted certificate";dt.deferredProxy.push({host:N,reason:Bt}),dt.warnings.push(`${N}: 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(ct)ot.push(N);let vt=[{type:"A",content:T}];if(Ee&&Pn(N))vt.push({type:"AAAA",content:Ee});for(let{type:xt,content:Bt}of vt){let mr=await h.upsertRecord(C,{name:N,type:xt,content:Bt,ttl:_t,proxied:ct});if(mr.success)dt.records.push({host:N,type:xt,content:Bt,proxied:ct});else dt.warnings.push(`${N} ${xt} → ${Bt} failed: ${mr.message||"unknown provider error"}`)}}if(ot.length===0){if(oe)dt.warnings.push("No host is proxied yet, so zone settings, cache rules and purge were skipped — they only take effect through the proxy.");return dt}try{let N=ks(ae),ct=await h.applyZoneSettings(C,N);dt.settingsChanged=ct.changed;for(let vt of ct.failed)dt.warnings.push(`zone setting '${vt.id}' could not be applied: ${vt.error}`)}catch(N){dt.warnings.push(`zone settings could not be read: ${N instanceof Error?N.message:String(N)}`)}let kt=Xa(ot,be);if(kt.length>0){let N=await h.putManagedPhaseRules(C,"http_request_cache_settings",kt);if(N.success)dt.cacheRules=kt.length;else dt.warnings.push(`cache rules could not be written: ${N.message}`)}if(lt){let N=Ya(ot,lt.header,lt.value);if(N.length>0){let ct=await h.putManagedPhaseRules(C,"http_request_late_transform",N);if(ct.success)dt.originGuard=!0;else dt.warnings.push(`origin guard header could not be written: ${ct.message}. `+"The gateway will reject requests that lack it — disable the guard or grant the token Transform Rules: Edit.")}}if(_e){if(dt.purged=await h.purgeCache(C,{hosts:ot}),!dt.purged)dt.warnings.push("edge cache purge failed — new content may take until TTL expiry to appear.")}return dt}var _u=(l)=>process.env[l];function Cc(l,h){let C=l.replace(/\.$/,"").toLowerCase();if(h){let b=h.replace(/\.$/,"").toLowerCase();if(C===b||C.endsWith(`.${b}`))return b}return C.split(".").slice(-2).join(".")}function Vu(l,h={}){let C=h.env??_u,b=l.infrastructure?.compute?.proxy?.cdn,T=[];if(!b||b.provider!=="cloudflare")return{plan:null,errors:T};if(b.originDomain)T.push(`compute.proxy.cdn.originDomain (${b.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=C("CLOUDFLARE_API_TOKEN");if(!Ee)return T.push("CLOUDFLARE_API_TOKEN is not set — the Cloudflare CDN cannot be reconciled."),{plan:null,errors:T};let oe=l.sites??{},ae=b.frontedHosts?.length?[...new Set(b.frontedHosts.map((nr)=>nr.toLowerCase()))]:xn(oe,{autoWww:l.infrastructure?.compute?.proxy?.autoWww!==!1});if(ae.length===0)return T.push("No hostnames to front — set compute.proxy.cdn.frontedHosts, or give a site a domain."),{plan:null,errors:T};let be=l.infrastructure?.dns?.domain,lt=new Set(ae.map((nr)=>Cc(nr,be)));if(lt.size>1)return T.push(`Fronted hosts span more than one zone (${[...lt].join(", ")}). A Cloudflare zone is configured as a unit, so run one CDN config per zone.`),{plan:null,errors:T};let _e=b.cloudflare??{},_t=b.secret?{header:b.secretHeader??"X-Origin-Verify",value:b.secret}:void 0;return{plan:{zone:[...lt][0],hosts:ae,apiToken:Ee,zoneId:_e.zoneId??C("CLOUDFLARE_ZONE_ID"),accountId:_e.accountId??C("CLOUDFLARE_ACCOUNT_ID"),proxied:_e.proxied!==!1,settings:_e.settings??Vn,cache:_e.cache,originGuard:_t,purge:_e.purgeOnDeploy!==!1,skipOriginProbe:_e.skipOriginProbe===!0},errors:T}}var Wu=26214400;var Hu=new Set(["/_headers","/_redirects","/_routes.json","/_worker.js"]);class Sc{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,C){return Ka(l,`/accounts/${this.accountId}${h}`,`Bearer ${this.apiToken}`,C)}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 C=await this.getProject(l);if(C)return C;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 C=await Ka("POST","/pages/assets/check-missing",`Bearer ${l}`,{hashes:h});return new Set(C)}async upsertHashes(l,h){await Ka("POST","/pages/assets/upsert-hashes",`Bearer ${l}`,{hashes:h})}async uploadBatch(l,h){let C=h.map((b)=>({key:b.hash,value:b.base64,metadata:{contentType:zu(b.extension)},base64:!0}));await Ka("POST","/pages/assets/upload",`Bearer ${l}`,C)}async createDeployment(l,h,C){let b={};for(let Ee of h)b[Ee.path]=Ee.hash;let T=new FormData;if(T.append("manifest",JSON.stringify(b)),C)T.append("branch",C);return this.request("POST",`/pages/projects/${l}/deployments`,T)}async deployDirectory(l){let h=await bc(l.directory);if(h.length===0)throw Error(`No files to deploy in ${l.directory}`);let C=await this.uploadToken(l.project),b=await this.missingHashes(C,h.map((be)=>be.hash)),T=h.filter((be)=>b.has(be.hash)),Ee=[];for(let be=0;be<T.length;be+=100)Ee.push(T.slice(be,be+100));let oe=0;for(let be=0;be<Ee.length;be+=4){let lt=Ee.slice(be,be+4);await Promise.all(lt.map((_e)=>this.uploadBatch(C,_e))),oe+=lt.reduce((_e,_t)=>_e+_t.length,0),l.onProgress?.(oe,T.length)}return await this.upsertHashes(C,h.map((be)=>be.hash)),{deployment:await this.createDeployment(l.project,h,l.branch),total:h.length,uploaded:T.length,uploadedBytes:T.reduce((be,lt)=>be+lt.size,0)}}async listCustomDomains(l){return(await this.request("GET",`/pages/projects/${l}/domains`)).map((C)=>C.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 Gu(l,h){return{type:"CNAME",name:l,value:h.endsWith(".pages.dev")?h:`${h}.pages.dev`,ttl:1,proxied:!0}}async function Ac(l,h){let{blake3:C}=await import("./chunk-g6aev693.js").then((m)=>Yh(m.default,1));return(await C(l+h)).slice(0,32)}async function bc(l){let{readdir:h}=await import("node:fs/promises"),{join:C,relative:b,sep:T}=await import("node:path"),Ee=[];async function oe(ae){let be=await h(ae,{withFileTypes:!0});for(let lt of be){let _e=C(ae,lt.name);if(lt.isDirectory()){await oe(_e);continue}if(!lt.isFile())continue;let _t=`/${b(l,_e).split(T).join("/")}`;if(Hu.has(_t))continue;let nr=await Bun.file(_e).bytes();if(nr.byteLength>26214400)throw Error(`${_t} is ${nr.byteLength} bytes, over the Cloudflare Pages limit of 26214400`);let fr=Buffer.from(nr).toString("base64"),dt=lt.name.lastIndexOf("."),ot=dt>0?lt.name.slice(dt+1):"";Ee.push({path:_t,hash:await Ac(fr,ot),base64:fr,extension:ot,size:nr.byteLength})}}return await oe(l),Ee.sort((ae,be)=>ae.path.localeCompare(be.path)),Ee}function zu(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,C,b){let T={Authorization:C},Ee;if(b instanceof FormData)Ee=b;else if(b!==void 0)T["Content-Type"]="application/json",Ee=JSON.stringify(b);let oe=await fetch(`https://api.cloudflare.com/client/v4${h}`,{method:l,headers:T,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 lt=(be.errors??[]).map((_e)=>`${_e.code}: ${_e.message}`).join(", ");throw Error(`Cloudflare Pages API error (${oe.status}): ${lt||ae.slice(0,200)}`)}return be.result}export{Yg as ABTestManager,le as ACMClient,pr as ACMDnsValidator,yc as ACME_DIRECTORIES,Pe as AI,ul as API_IDEMPOTENCY_TTL_MS,dl as API_TOKEN_DEFAULT_TTL_MS,ll as API_TOKEN_MAX_TTL_MS,Gi as API_VERSION,pe as AUTHORIZATION_CAPABILITIES,sl as AUTH_ACTION_TOKEN_TTL_MS,ol as AUTH_MFA_CHALLENGE_TTL_MS,al as AUTH_OIDC_TRANSACTION_TTL_MS,Je as AUTH_SESSION_ABSOLUTE_TTL_MS,il as AUTH_SESSION_IDLE_TTL_MS,wA as AWSAPIError,n as AWSClient,f as AWSCloudFormationClient,y as AWSCloudFrontClient,Kg as AWSConfigManager,LI as AWS_PSEUDO_PARAMETERS,Ne as AWS_REGIONS,xu as AcmeClient,Fr as AlertEvaluator,Si as AlertStore,Ys as AnomalyConfigStore,xd as ApiGateway,i as ApiServiceError,za as ApplicationAutoScalingClient,mo as Arn,P as AssetHasher,H as Auth,Mi as AuthenticationStore,Ti as AutomationApiService,Fi as AutomationIdentityStore,ta as AwsAuroraDataAdapter,oa as AwsAuroraTransport,va as AwsDatabaseBackupSource,Ar as AwsDriver,ra as AwsElastiCacheDataAdapter,aa as AwsElastiCacheTransport,Jm as AwsIamCapabilityScanner,Pa as AwsInfrastructureBackupSource,ea as AwsRdsDataAdapter,sa as AwsRdsTransport,dh as AwsRegionalDriver,ka as AwsSecretsManagerConfigurationBackend,ig as AwsSpendTransport,Ba as AwsSsmConfigurationBackend,es as BackupCoordinator,jg as BackupManager,Ea as BackupStore,Nm as BatchProcessingManager,Sn as BedrockClient,In as BedrockRuntimeClient,yl as BitbucketSourceAdapter,Xg as BlueGreenManager,vm as BounceComplaintHandler,pm as BuildOptimizationManager,Ul as BunDockerRuntime,fu as BunDockerVolumeRuntime,hu as BunFilesystemArchiveRuntime,me as CDN,Co as CHAIN_HEADER,gs as CLOUDFLARE_MANAGED_RULE_PREFIX,Dd as CLOUDFRONT_FAILOVER_STATUS_CODES,NC as COMMON_CROSS_ACCOUNT_ROLES,Ge as CONTROL_PLANE_SCHEMA_VERSION,po as Cache,Ao as CanaryManager,dm as CertificateManager,Of as CloudBlockVolumeDriver,Bs as CloudDriverFactory,We as CloudError,Eg as CloudFormationBuilder,f as CloudFormationClient,y as CloudFrontClient,Wg as CloudTrailManager,ye as CloudWatchLogsClient,Sc as CloudflarePagesProvider,Se as CloudflareProvider,UA as CommandHistory,q as Communication,xr as ComposeApplicationService,Ft as ComposeApplicationStore,wt as ComprehendClient,a as Compute,sg as ComputeSpendTransport,fo as ConfigurationError,xa as ConfigurationService,Na as ConfigurationStore,An as ConnectClient,ia as ContainerDataAdapter,gm as ContainerRegistryManager,Da as ControlPlaneBackupSource,ya as ControlPlaneCleanupDriver,gi as ControlPlaneStore,Ws as CounterTracker,Wt as CredentialError,Ug as CrossRegionReferenceManager,uA as DASHBOARD_ENTRY,pA as DASHBOARD_PORT_BASE,gA as DASHBOARD_PORT_SPAN,lA as DASHBOARD_STATE_DIR,Do as DEFAULT_ATTACK_MODE_HOURS,fd as DEFAULT_DDOS_THRESHOLDS,pg as DEFAULT_FAILOVER_STATUS_CODES,Xc as DEFAULT_METER_MAPPINGS,Wc as DEFAULT_PRICE_BOOK,Bi as DEFAULT_RECURSION_LIMITS,Bn as DEFAULT_RPX_CERTS_DIR,j as DEFAULT_SERVICE_LIMITS,dg as DEFAULT_STATE_DIR,Du as DEFAULT_STATIC_ASSET_EXTENSIONS,oA as DEFAULT_STORAGE_FAILOVER_STATUS_CODES,Kf as DEFAULT_TELEMETRY_POLICY,Hp as DEFAULT_THRESHOLDS,Nf as DEPLOYMENT_QUEUE_KINDS,So as DEPTH_HEADER,$r as DETECTABLE_SIGNALS,Ol as DIAGNOSTIC_PRESETS,Pm as DLQMonitoringManager,F as DNS,Em as DNSSECManager,zi as DataServiceLifecycle,Zo as DataServiceStore,jt as Database,om as DatabaseUserManager,re as DebugLogger,sA as DependencyGraph,G as Deployment,TA as DeploymentError,zg as DisasterRecoveryManager,Dn as DnsProviderFactory,Zt as DockerDataTransport,zo as DockerDiscoveryAdapter,_r as DockerNamedVolumeDriver,Ra as DockerVolumeBackupSource,c as DurableOperationQueue,Hs as DurableQueueWorker,Oe as DynamoDBClient,Tr as EC2Client,Le as ECRClient,tt as ECSClient,cr as EFSClient,Ga as ELBv2Client,$f as ENFORCEMENT_ACTIONS,yi as ENFORCEMENT_DESCRIPTIONS,D as ENFORCEMENT_SEVERITY,fp as ENVIRONMENT_LABEL,_l as EcsRuntimeAdapter,Ro as EdgeRateLimiter,nt as ElastiCacheClient,m as Email,GA as EmailAdvanced,Tm as EmailAnalyticsManager,vn as EmailClient,qA as EmailHandlers,Rm as EmailTemplateManager,ca as EncryptedDataSecretStore,RA as ErrorCodes,or as EventBridgeClient,oh as EventBridgeJobAdapter,_a as ExternalConfigurationBackend,uo as FAILOVER_REPLICA_POLICY_SID,Dm as FIFOQueueManager,Jp as FOCUS_VERSION,Dg as FileCache,ze as FileSystem,Ta as FilesystemBackupSource,la as FleetService,da as FleetStore,e as Fn,Il as GiteaSourceAdapter,fl as GithubSourceAdapter,Al as GitlabSourceAdapter,Qg as GlobalResourceManager,$e as GoDaddyProvider,Jg as GuardDutyManager,ut as HOST_SITES_DIR,NA as HashCache,Mm as HealthCheckManager,Ve as HealthCheckRunner,Cr as HetznerClient,ve as HetznerDriver,Ie as IAMClient,rc as IPV6_EXCLUDED_HOST_LABELS,um as ImageScanningManager,Yl as InfrastructureGenerator,Mc as InvalidOperationTransitionError,ft as JobLoader,ah as JobProviderReconciler,Yo as JobService,Jo as JobStore,sr as KendraClient,dy as LARAVEL_SERVERLESS_BUILD_STEPS,E as LambdaClient,Am as LambdaConcurrencyManager,Sm as LambdaDLQManager,ym as LambdaDestinationsManager,hm as LambdaLayersManager,xl as LambdaRuntimeAdapter,Im as LambdaVPCManager,fm as LambdaVersionsManager,pn as LocalEncryptedConfigurationBackend,wa as LogicalDatabaseBackupSource,rm as LogsManager,WA as MANAGED_NODE_VERSIONS,wc as MANAGEMENT_DASHBOARD_SITE,bg as MANAGEMENT_DASHBOARD_SITE_PREFIX,Li as MAX_CONTROL_HOURS,Fc as MAX_CONTROL_PLANE_ERROR_BYTES,$p as MAX_CONTROL_PLANE_JSON_BYTES,js as METERS,Lf as METER_KEYS,Mf as MICRO_CENTS,Gp as MIN_PROJECTION_CONFIDENCE,Bu as MTA_STS_PORT,Aa as MaintenanceService,fa as MaintenanceStore,te as Messaging,tm as MetricsManager,nm as MigrationManager,_g as MockCloudFormation,Og as MockDynamoDB,xg as MockS3,go as Monitoring,qg as MultiAccountManager,Fg as MultiRegionManager,xA as MultiStepProgress,A as Network,Fm as NetworkSecurityManager,Ci as NotificationRouter,hg as ORIGIN_CONNECTION_ATTEMPTS,fg as ORIGIN_CONNECTION_TIMEOUT,gg as ORIGIN_GROUP_ALLOWED_METHODS,_I as ORIGIN_GROUP_ID_SUFFIX,mg as ORIGIN_GROUP_SELECTION_CRITERIA,qa as OpenSearchClient,pt as OptimisticConcurrencyError,Vg as OrganizationManager,Wu as PAGES_MAX_FILE_BYTES,ly as PHP_DEFAULT_EXCLUDES,JA as PHP_LAYER_EXTENSIONS,hp as PROJECT_LABEL,st as PROXIABLE_RECORD_TYPES,v as ParameterStore,sm as PerformanceManager,ee as Permissions,Va as PersonalizeClient,Ke as Phone,VA as PhoneAdvanced,aA as PhoneHandlers,pa as PlacementService,ua as PlacementStore,Cn as PollyClient,ce as PorkbunProvider,en as PreDeployScanner,Lg as PreviewEnvironmentManager,Br as PreviewEnvironmentService,qe as PreviewEnvironmentStore,$g as PreviewNotificationService,_A as ProgressBar,Zg as ProgressiveDeploymentManager,Po as ProtectionControlStore,bI as Pseudo,U as Queue,mi as QueueCancellationError,km as QueueManagementManager,CI as QueuePresets,Qs as QueueTimeoutError,Jd as RATE_LIMIT_KEY_SEPARATOR,K as RDSClient,HA as RECOMMENDED_ACCOUNT_STRUCTURES,PC as RECOMMENDED_SCPS,jm as RELEASE_QUEUE_KINDS,$A as REPL,FA as REPLCommandBuilder,MA as REPLContext,Ap as ROLE_LABEL,kA as RateLimiter,EI as RealtimePresets,Xp as RecordingSpendTransport,bo as RecursionGuard,At as Redirects,Hg as RegionPairManager,ma as RegionService,ga as RegionStore,je as Registry,Rt as RekognitionClient,yt as ReleaseService,Mo as ReleaseStore,ch as RemoteBuildService,im as ReplicaManager,Um as ResourceManagementManager,Z as RetryableOperationError,I as Route53Client,Ha as Route53DomainsClient,W as Route53Provider,bm as Route53ResolverManager,Cm as Route53RoutingManager,fe as RuntimeOperationService,Wo as RuntimeStreamRegistry,ba as S3BackupDestinationAdapter,o as S3Client,V as S3Error,El as SECRET_PATTERNS,Kp as SENSITIVITY_THRESHOLDS,it as SESClient,Q as SMS,rt as SNSClient,ng as SPEND_CYCLE_SECONDS,ld as SPEND_GATE_SETTING,Yf as SPEND_LEASE_SETTING,se as SQSClient,Te as SSH_BOOTSTRAP_VERSION,Wn as SSH_PREFLIGHT_SCRIPT,we as SSMClient,lg as STATE_DIR_ENV_VAR,Vn as STATIC_SITE_ZONE_SETTINGS,kd as STORAGE_FAILOVER_METADATA_KEY,Ae as STSClient,En as SchedulerClient,zt as Search,tn as SecretFindingScanner,Di as Secrets,cm as SecretsManager,z as SecretsManagerClient,am as SecretsRotationManager,S as Security,jr as SecurityHubManager,Zr as SecurityPostureStore,It as SecurityScannerRunner,lm as SecurityScanningManager,wm as SenderReputationManager,sh as ServerCronJobAdapter,na as ServerDataAdapter,Vs as ServerPathVolumeDriver,mm as ServiceMeshManager,_d as Sftp,eo as SignalSource,jA as SmsAdvanced,Pt as SmsClient,cA as SmsHandlers,Ja as SmsVoiceClient,Fo as SourceConnectionStore,Xt as SourceProviderError,ud as SpendCapError,Mr as SpendGate,tg as SpendLoopLease,so as SpendNotificationRouter,rg as SpendRunner,Qt as SpendService,fi as SpendStore,OA as Spinner,br as SshDriver,sn as SshFleetDriver,Gg as StackDependencyManager,OI as StacksIntegration,Lm as StaticSiteManager,Re as Storage,$m as StorageAdvancedManager,bn as SupportClient,zr as SyntheticsManager,Ql as SystemFleetSshTransport,Er as SystemSshTransport,Ko as SystemdDiscoveryAdapter,Eo as TRACE_HEADER,LA as TaskList,ht as TelemetryStore,wd as TemplateBuilder,Pg as TemplateCache,Dt as TextractClient,yn as TranscribeClient,ir as TranslateClient,ph as TransportDisasterRecoveryDriver,uh as TransportPlatformMaintenanceDriver,Ki as TransportRemoteBuildDriver,Vo as TrivyImageScanner,$o as TsCloudApiError,pl as TsCloudClient,Xf as URGENT_SPEND_EVENTS,qp as USER_VISIBLE_ACTIONS,ha as UnavailableRegionalDriver,de as UnifiedDnsValidator,Ms as UnsupportedSchemaVersionError,wg as ValidationError,ar as VoiceClient,qs as VolumeService,Mt as VolumeStore,dA as Workflow,em as XRayManager,iE as abTestManager,gl as activateImmutableRelease,Tu as addDns01ChallengeRecord,an as addSiteToCloudConfig,Ct as ageSeconds,Zc as aggregateDeltas,xp as allocateSitePorts,kI as analyzeStackDiff,Ii as anomalyOptionsForSignal,No as applyControlsToDdos,tl as applyControlsToRateLimits,ys as applyDeclaredZoneSettings,Hr as applyMitigationFactor,uf as applyPlan,Es as applyZoneMigration,Fd as artifactKey,qt as assertOriginGroupMethods,Ui as assertReleaseStrategy,zf as assertSpendAllows,ff as attachConflicts,Af as attachIsViable,hf as attachPreconditions,Rl as attachProvenanceToRelease,jo as attachSbomToRelease,Tl as attachVulnerabilitySummary,qm as authEncryptionKeyFile,R as authorizeOrganization,nh as authorizeRuntimePath,sC as autocomplete,YC as awsConfigManager,gu as backupCredentialStatus,JC as backupManager,vS as batch,$E as batchProcessingManager,Oo as beginOidcAuthorization,rE as blueGreenManager,kE as bounceComplaintHandler,gt as budgetWindow,Fa as buildAndPushServerlessImage,UE as buildBunRuntimeLayerZip,bf as buildCertificatePackScript,Sf as buildCertificateStateScript,vf as buildCertificateUnpackScript,Od as buildCloudFormationTemplate,Ic as buildCloudInitFirstBoot,Gc as buildComposeLogsCommand,dI as buildComposeRuntimeCommand,lI as buildComposeScaleCommand,qc as buildComposeShellCommand,kp as buildDrainSourceScript,tf as buildDrainedSiteScanScript,Bd as buildFailoverReplicaPolicyStatement,tr as buildFunctionEnv,Np as buildHealthGateScript,Qn as buildHostCleanupDeployScript,Ps as buildHostCleanupInstallScript,Un as buildHostCleanupScript,ui as buildHostSitePortsScript,Td as buildMailEnv,xs as buildManagementDashboardArtifact,Yu as buildMediaCdnPlan,ku as buildMtaStsPolicy,xh as buildMtaStsServer,FE as buildNodeRuntimeLayerZip,IE as buildOptimizationManager,Ag as buildOriginGroup,Gr as buildOriginGroups,Ya as buildOriginGuardRule,bp as buildPauseWorkersScript,qE as buildPhpRuntimeLayerZip,Cg as buildReplicationConfiguration,Sg as buildReplicationRole,Rp as buildRestoreScript,J as buildRpxConfig,Me as buildRpxFragmentRefreshScript,gf as buildSetHostnameScript,Gn as buildSiteDeployScript,wp as buildSnapshotScript,Bp as buildSourceStateScript,Ln as buildSshArgs,zn as buildSshBootstrapScript,Xa as buildStaticSiteCacheRules,qn as buildStaticSiteDeployScript,Dp as buildTargetStateScript,vp as buildWorkersStateScript,Pl as bytes,nE as canaryManager,on as canonicalJson,St as capabilities,er as capacity,_S as categorizeChanges,fE as certificateManager,Ef as certificatesMatch,gS as checkIAMPermissions,ry as checkInvocation,hS as checkServiceQuotas,BA as chunk,Rf as cleanupDns01Challenge,fI as clearSigningKeyCache,Qo as cloneSourceBinding,LS as cloudConfigSchema,np as cloudDrivers,ZC as cloudTrailManager,bc as collectAssets,To as collectPhpAppEntries,Pu as collectServerDnsDomains,Mp as completeComposeVolumeDeletion,Lo as completeOidcAuthorization,eS as composePresets,Us as composeProjectName,Qd as composeServerlessAppTemplate,eA as compositeSpendTransport,Tt as compressBackup,py as config,Ml as connectionGuidance,SE as containerRegistryManager,Df as controlPlaneDatabaseFile,Lc as controlPlaneMigrations,HI as createApiBackendPreset,qo as createApiV1Handler,Cy as createAsgBuildDriver,mu as createBackupQueueHandlers,ay as createCliHandler,B as createCloudDriver,mc as createCloudFrontPolicy,cS as createCredentialProvider,YI as createDashboardSite,zI as createDataPipelinePreset,Fl as createDataServiceQueueHandlers,Vc as createDeploymentQueueHandlers,w as createDnsProvider,Sy as createEcsBuildDriver,pd as createEnforcementHandlers,Rg as createError,Ld as createExistingStaticFullStackPreset,Hl as createFleetQueueHandlers,QI as createFullStackAppPreset,Ts as createGoDaddyValidator,GE as createHandlers,sy as createHttpHandler,qI as createJamstackPreset,$l as createJobQueueHandlers,JI as createLaravelPreset,KI as createMLApiPreset,Wl as createMaintenanceQueueHandlers,Zu as createMediaAccessToken,VI as createMicroservicesPreset,HS as createMockAWS,MI as createNodeJsServerPreset,FI as createNodeJsServerlessPreset,us as createObjectStorageClient,vs as createPorkbunValidator,tS as createPreset,rA as createPresignedUrl,uI as createPresignedUrlAsync,oy as createQueueHandler,jI as createRealtimeAppPreset,ql as createRegionQueueHandlers,wl as createReleaseProvenance,hl as createReleaseQueueHandlers,yy as createRemoteBuildQueueHandlers,ws as createRoute53Validator,rh as createRuntimeAdapters,dS as createS3Client,Iy as createServerBuildDriver,XI as createServerlessLaravelPreset,UI as createServerlessNodePreset,Ru as createSmsInfrastructure,Ye as createSourceAdapter,$I as createStaticSitePreset,WI as createTraditionalWebAppPreset,jc as createVolumeQueueHandlers,GI as createWordPressPreset,ki as createZip,gC as crossRegionReferenceManager,gn as dashboardActions,_s as dashboardCredentialsFile,nn as dataServiceCapabilities,gE as databaseUserManager,nl as decodeBase32,xe as decompressBackup,Eh as decryptBackup,ko as defaultConfig,Bg as defaultLocalConfig,Yd as defaultRateLimitRules,ur as delegateZone,fs as delegateZoneFromConfig,du as deleteFailoverReplicaBuckets,$a as deleteStaticSite,Dc as deployAllComputeSites,Sa as deployServerlessApp,lu as deploySite,Os as deploySiteRelease,is as deployStaticSite,Ma as deployStaticSiteFull,mn as deployStaticSiteWithExternalDns,hn as deployStaticSiteWithExternalDnsFull,bd as deploymentCoexistenceError,mA as deriveManagementDashboardPort,As as describeDelegation,el as describePosture,Is as describeZoneSettings,ih as desiredJobProviderState,zp as detectAnomalies,ug as detectDeploymentTargets,Za as detectDnsProvider,ad as detectLatestAnomaly,uS as detectMisconfigurations,ag as detectServiceRegion,Qc as diffCompose,NS as diffTemplates,Uo as discoverGitRefs,xo as discoverOidcProvider,Nl as discoverRuntimeInventory,LE as dlqMonitoringManager,ec as dnsProviders,PE as dnssecManager,Zm as dockerWorkloads,Wi as documentDigest,XC as drManager,Ue as driverStatePath,kl as ecsWorkloads,$t as effectiveCapabilities,BE as emailAnalyticsManager,xE as emailTemplateManager,$i as encodeBase32,Ch as encryptBackup,Dl as ensureDefaultSecurityPolicies,ou as ensureFailoverReplicaBuckets,ri as ensureFirewall,si as ensureManagementDashboard,ni as ensureServer,ti as ensureSshKey,Y as escapeSecLang,td as evaluateBudget,Xn as evaluatePreflight,io as evaluateTelemetryAlertRules,Ll as eventBridgeScheduleInput,iy as eventToRequest,qf as ewma,Uc as exportCompose,Ss as exportRoute53Zone,Tg as extendPreset,OE as fifoQueueManager,bS as findChangedFiles,Up as findMapping,Fp as findPriceEntry,xC as formatAccountStructure,yf as formatAttachPlan,XS as formatBytes,Ur as formatCents,BI as formatDiff,nf as formatDrainedSiteRefusal,YS as formatDuration,aC as formatFlagSuggestions,lC as formatHistory,uC as formatHistoryStats,cf as formatInventory,eC as formatKeyValue,ZS as formatList,lf as formatPlan,Zn as formatPreflightFindings,JS as formatProgressBar,QA as formatRegion,TC as formatRegionList,Wm as formatScanResults,tC as formatSuggestion,KS as formatTable,Lr as formatTimeToExhaustion,WS as formatTree,IA as fromEC2Metadata,SA as fromECSMetadata,AA as fromEnvironment,yA as fromSharedCredentials,CA as fromWebIdentity,Gd as functionFingerprint,xn as gatewayHostnames,Hd as generateAppImageDockerfile,KC as generateApprovalConfig,zA as generateBootstrap,VS as generateCleanupWorkflow,jS as generateCostReportWorkflow,BC as generateCrossAccountRoleCF,bl as generateCycloneDxSbom,VC as generateDeploymentConfig,UC as generateDeploymentPipeline,OC as generateDeploymentWorkflow,La as generateExternalDnsStaticSiteTemplate,gp as generateHttpsServerCode,vl as generateImageSbom,pp as generateLetsEncryptUserData,t as generateLogicalId,qC as generateManualPipeline,FC as generateMatrixWorkflow,jC as generateMultiEnvConfig,QC as generateMultiEnvPipeline,LC as generateMultiEnvWorkflow,$C as generatePRPreviewWorkflow,WC as generateParallelConfig,cy as generatePhpFpmConfig,YA as generatePhpLayerDockerfile,HC as generatePreviewPipeline,qS as generatePreviewWorkflow,r as generateResourceName,zC as generateScheduledConfig,GC as generateScheduledPipeline,MC as generateScheduledWorkflow,ns as generateStaticSiteTemplate,k as generateUbuntuAppCloudInit,vA as getAccountId,AC as getAllRegions,EC as getClosestRegion,cC as getCommandUsage,Pf as getComposeTemplate,Qm as getConfig,nC as getContextualHelp,ho as getCredentials,xS as getDeploymentStrategy,OS as getDiffStats,kS as getDiffSummary,DA as getErrorDetails,Md as getLocalConfig,US as getLocalCredentials,FS as getLocalEndpoint,QS as getLocalEnvVars,fS as getQuotaUsageSummary,kC as getRecommendedStructure,Ni as getRegion,wC as getRegionStats,IC as getRegionsByCompliance,yC as getRegionsByLocation,SC as getRegionsByPricingTier,PA as getRequiredPermissions,yI as getSigningKeyCacheSize,wu as getSmsInfrastructureStatus,vI as getTimestamp,wo as globMatches,Ls as globToRegex,mC as globalResourceManager,Ai as governingLimitCents,au as grantFailoverReplicaAccess,eE as guardDutyManager,oo as handleSpendRequest,_n as hasAutoWwwVariant,Kt as hasManagementDashboardSite,Oc as hasProxyUpstream,IS as hashBuffer,SS as hashDirectory,Ng as hashFile,CS as hashManifest,kg as hashString,zE as healthCheckManager,Pn as hostAcceptsIpv6,Tn as hostCondition,Bo as hotp,Or as hourBucket,Gf as hourBucketsBetween,yE as imageScanningManager,Yi as infraEnvFromOutputs,Vd as inspectInvocation,ey as installRecursionFetch,os as invalidateCache,xm as invocationContext,rC as isLikelyTypo,kn as isLocalDatabase,MS as isLocalDevelopment,qr as isManagementDashboardSiteName,dr as isNameserverRegistrar,II as isNodeCryptoAvailable,od as isOperationAllowed,no as isQuietHours,Nd as isS3RestEndpoint,ai as isSafePattern,Cd as isStateDirConfigured,Ed as isStatePath,Qr as isValidCidr,CC as isValidRegion,hi as isValidTimeZone,SI as isWebCryptoAvailable,lr as isZoneHost,rn as jobProviderCapability,ls as keyMatchesFilters,vE as lambdaConcurrencyManager,RE as lambdaDLQManager,TE as lambdaDestinationsManager,EE as lambdaLayersManager,wE as lambdaVPCManager,bE as lambdaVersionsManager,Bl as lambdaWorkloads,Kd as laravelServerlessEnvDefaults,kr as listComposeTemplates,Hi as listSourceReferences,rl as loadCloudConfig,Ht as loadTelemetryPolicy,cE as logsManager,cd as lookbackHoursForSignal,iA as mailEnabled,vd as mailFirewallPorts,lh as maintenanceWindowOpen,nA as makeAWSRequest,gI as makeAWSRequestAsync,pI as makeAWSRequestOnce,vg as managementDashboardSiteName,Vl as manifestDigest,Wr as matchTotpCounter,Ju as mediaObjectHeaders,Xs as median,Vp as medianAbsoluteDeviation,rd as mergeDecisions,Vr as mergeInfrastructure,Qf as mergePriceBooks,Yc as meterTelemetry,aE as metricsManager,Eu as migrateObjectStorage,lE as migrationManager,RC as multiAccountManager,pC as multiRegionManager,wf as needsRenewal,KE as networkSecurityManager,Et as nextScheduleRuns,Ce as normalizePublicIpv6,ke as normalizeRuntimeStatus,Ze as normalizeScheduleExpression,zm as normalizeSourceEvent,Fe as normalizeSshPublicKey,Yp as normalizeTelemetryPolicy,li as occupiedHostPorts,Go as openApiDocument,to as optionsForSignal,DC as organizationManager,Wd as packagePhpApp,Kr as packageServerlessApp,Ac as pagesAssetHash,Gu as pagesDnsRecord,$d as parallel,TS as parallelMap,wS as parallelWithRetry,Cf as parseCertificateState,qd as parseChain,Nr as parseCompose,aI as parseComposeCatalog,Ym as parseDockerInspect,Au as parseDotenv,rf as parseDrainedSites,pi as parseHostSiteFragments,hI as parseJSONResponse,Jn as parsePreflightFacts,_p as parseSourceDrained,eh as parseSystemdRecords,Pp as parseTargetReady,xc as parseUpstreamPort,Tp as parseWorkersPaused,mI as parseXMLResponse,bi as pathTemplate,Bc as pendingSteps,Js as percentOfLimit,pE as performanceManager,Bm as phpLayerBuildStage,XA as phpLayerPackages,_i as phpRuntimeLayerAssets,cI as planComposeTemplateUpgrade,nd as planEnforcement,Cp as planIsDestructive,og as planMitigation,pf as planServerRename,Tf as planSiteMove,Cs as planZoneMigration,Nt as policyTag,Yn as preflightFailed,GS as previewManager,zS as previewNotifications,bt as previewSchedule,Hf as previousBudgetWindow,zs as priceUsage,Ff as priceUsageLines,of as probeHostRoutes,ic as probeOriginTls,PS as processInChunks,Sl as processSourceWebhook,Vi as productionChangeReview,sE as progressiveDeploymentManager,ed as projectSpend,jd as propagationHeaders,Ua as providerEndpoint,jl as publicKeyFingerprint,wn as qualifyName,ME as queueManagementManager,ES as quickHash,Xd as rateLimitHeaders,Oi as rateLimitKey,Qe as readDriverState,af as reconcile,Nu as reconcileAddressRecords,Mu as reconcileCloudflareCdn,hs as reconcileDeclaredRecords,Ay as reconcileJobObservation,Yr as reconcileSourceWebhook,qi as recordDashboardHostPosture,my as recordPreDeploySecretScan,hy as recordSkippedSecretScan,zd as recursionBlockedResponse,Be as redactRuntimeConfig,hd as redactTelemetryText,Ei as redactTelemetryValue,dn as redeployServerlessApp,hC as regionPairManager,Xr as releaseStrategyCapabilities,Vm as releaseTrafficPlan,oi as reloadRpxGateway,ds as remapKey,$u as removeDns01ChallengeRecord,cn as removeSiteFromCloudConfig,Cl as removeSourceWebhook,tc as removeStaleServerAddressRecords,Hc as renderComposeTemplate,wi as renderDdosInstallScript,Id as renderNftablesRuleset,ji as renderServerCron,yd as renderSysctlFile,Nc as renderWafConfig,ci as renderWafInstallScript,Pc as renewRpxCertificates,uE as replicaManager,tA as requestHash,BS as requiresReplacement,QE as resetRecursionRuntime,HE as resolveApp,p as resolveAppDatabase,mf as resolveAttachTarget,Xe as resolveAuthEncryptionKey,ge as resolveCloudProvider,Vu as resolveCloudflareCdnPlan,EA as resolveCredentials,rs as resolveDashboardAction,Rc as resolveDashboardAuth,hA as resolveDashboardDomain,fA as resolveDashboardDomains,ms as resolveDeclaredRecords,NI as resolveDeployBucketName,M as resolveDeploymentMode,Hn as resolveExecStart,Pd as resolveFailoverStatusCodes,pc as resolveHetznerApiToken,Sr as resolveHostCleanupConfig,Ri as resolveMailService,ZI as resolveManagementDashboardSite,Pi as resolveManagementDashboardSites,Qa as resolveObjectStorage,De as resolveOriginConnection,df as resolvePlan,g as resolveProjectStackName,Pr as resolveProxyUpstreams,Ud as resolveQueueNames,kf as resolveQueuedDeploymentCommand,Jt as resolveQueues,ZA as resolveRecursionConfig,bA as resolveRegion,ie as resolveRuntimeInventory,Gt as resolveServerlessAppStackName,Rd as resolveServerlessArtifactBucketName,lo as resolveServerlessAssetBucketName,Io as resolveServerlessRuntime,DI as resolveSiteBucketName,$s as resolveSiteDeployTarget,u as resolveSiteKind,RI as resolveSiteResourceName,wI as resolveSiteStackName,Kn as resolveSshSettings,d as resolveStatePath,PI as resolveStorageBucketName,yg as resolveStorageFailover,Ot as resolveUiSource,Cc as resolveZoneApex,WE as resourceManagementManager,Om as responseToResult,jp as robustZScore,Lt as roleCapabilities,ml as rollbackImmutableRelease,ln as rollbackServerlessApp,Uf as roundCents,NE as route53ResolverManager,DE as route53RoutingManager,Wp as routeMatches,yp as routesFromFragments,xi as ruleMatches,KA as runBuildHooks,id as runEnforcement,vo as runPhpBuildHooks,et as runRemoteCommand,he as runtimeId,Ig as s3RegionalDomain,Rn as sameNameservers,ts as sanitizeCloudConfig,s as sanitizeControlPlaneValue,TI as sanitizeName,cl as sanitizeOidcReturnPath,gd as saveTelemetryPolicy,Km as scanForSecrets,$c as scopeContains,mt as scopeKey,oc as scpUpload,iC as searchCommands,Fs as searchControlPlane,hE as secretsManager,mE as secretsRotationManager,fy as secureContainerRelease,tE as securityHubManager,AE as securityScanningManager,ne as securityScope,cu as seedFailoverReplicas,Jr as sendAuthenticationEmail,_E as senderReputationManager,RS as sequence,yu as serializeDotenv,ii as serverPublicIpv4,CE as serviceMeshManager,ru as setAttachToInCloudConfig,rr as setMaintenance,Ji as setSitePropertyInCloudConfig,Sd as setStateDir,ef as setupDns01Challenge,Wa as setupSmsInfrastructure,yo as sha256,ty as sharedRecursionGuard,_m as sharedRuntimeLoop,Lp as shipsARelease,ju as signCloudFrontCookies,Ku as signCloudFrontUrl,O as signRequest,cg as signRequestAsync,Zs as signalDefinition,x as siteInstallBase,di as siteMoveArchivePath,If as siteMoveCertArchivePath,_c as siteUnitGlob,eg as spendNotificationText,ao as spendOpenApiPaths,yr as sshExec,ue as sshExecOrThrow,fC as stackDependencyManager,Oa as startLocalDashboardServer,Zf as startSpendLoop,co as stateDir,L as statePath,VE as staticSiteManager,jE as storageAdvancedManager,xI as storageFailoverReplicasFromTemplate,Vf as streamFocusJsonl,sd as strongestActiveAction,Mg as suggestCommand,oC as suggestFlags,mS as suggestIAMPolicy,AS as suggestQuotaIncrease,vC as suggestRegionPairs,bC as suggestRegions,Qi as syncSourceRepositories,zc as synchronizeComposeVolumes,Iu as synchronizeConfiguredConfiguration,Xo as synchronizeConfiguredJobs,dE as syntheticsManager,Ad as sysctlHardening,th as systemdWorkloads,Jf as telemetryBucketLabel,vi as telemetryCursor,md as telemetryEstimatedMonthlyCost,Wf as telemetryPercentile,Zp as telemetryPolicyKey,yS as templateCache,Ip as tenantsOf,Ho as testSourceConnection,Kc as tieredMicroCents,ks as toCloudflareZoneSettings,ro as toFocusJsonl,dd as toFocusRecords,sf as toInventoryServer,Hm as totp,_o as totpUri,Sp as unaccountedSites,Xm as unsupportedCapabilities,Bf as unsupportedVolumeCapabilities,Kl as updateCompatibility,Jl as updateSiteInCloudConfig,ss as uploadStaticFiles,Qp as usageDeltaKey,Ut as utcInstantOfLocal,_C as validateAccountStructure,$S as validateAgainstSchema,xf as validateAttachment,Sh as validateBackupDestination,dC as validateCommand,lS as validateConfiguration,pS as validateCredentials,Op as validateDeploymentConfig,_f as validateMountPath,Vt as validateOriginGroups,su as validateResourceLimits,Ep as validateServerName,Xl as validateTemplate,nu as validateTemplateSize,nc as verifyAddressRecord,gy as verifyArtifactSignature,qu as verifyMediaAccessToken,Gm as verifyTotp,zl as verifyUpdateSignature,bs as verifyZoneParity,Gs as volumeCapabilities,mp as wafEventTelemetry,ac as waitForCloudInit,$n as waitForSsh,Yt as webhookEndpoint,oS as withCDN,sS as withCache,iS as withDatabase,ny as withInvocation,rS as withMonitoring,aS as withQueue,nS as withSecurity,DS as withTimeout,X as wrapCloudInitUserData,at as writeDriverState,oE as xrayManager,Gl as zeroCapacity,jf as zeroFill,Jc as zoneOffsetMs,Ks as zonedParts};