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