@stacksjs/ts-cloud 0.16.49 → 0.16.50
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-z8k9mcn5.js → chunk-0wtshht7.js} +2 -2
- package/dist/bin/{chunk-v7t6f8aw.js → chunk-11y7yang.js} +2 -2
- package/dist/bin/chunk-2wh45zhk.js +2 -0
- package/dist/bin/chunk-334jngt2.js +1 -0
- package/dist/bin/{chunk-4yym8xm4.js → chunk-33ntxz01.js} +5 -5
- package/dist/bin/chunk-3k7y1h18.js +1 -0
- package/dist/bin/chunk-512ecg6y.js +1 -0
- package/dist/bin/{chunk-vhyp4xj0.js → chunk-5ny7rggt.js} +1 -1
- package/dist/bin/chunk-626npmtj.js +1 -0
- package/dist/bin/{chunk-zvbc92pc.js → chunk-734n0gkw.js} +1 -1
- package/dist/bin/chunk-74wppexz.js +1 -0
- package/dist/bin/chunk-7cs9nnjy.js +111 -0
- package/dist/bin/{chunk-q4dywv80.js → chunk-7czb1kgg.js} +2 -2
- package/dist/bin/chunk-7ewbxsan.js +1 -0
- package/dist/bin/{chunk-ynwbzsz8.js → chunk-7jj0g6jk.js} +158 -158
- package/dist/bin/{chunk-kbwm0sqv.js → chunk-811k54jq.js} +2 -2
- package/dist/bin/chunk-8ya34jz7.js +1 -0
- package/dist/bin/chunk-964xmgb6.js +1 -0
- package/dist/bin/{chunk-gyvkravq.js → chunk-9ehb4hc6.js} +5 -5
- package/dist/bin/chunk-azarn24c.js +1 -0
- package/dist/bin/chunk-cw3rhg1c.js +1 -0
- package/dist/bin/chunk-d2fq60kd.js +1 -0
- package/dist/bin/{chunk-01w4zbex.js → chunk-da6dmacg.js} +2 -2
- package/dist/bin/chunk-dpk5r544.js +1 -0
- package/dist/bin/{chunk-12x968en.js → chunk-dv2he3vc.js} +3 -3
- package/dist/bin/chunk-e6ewfmbp.js +1 -0
- package/dist/bin/{chunk-psmpw0ap.js → chunk-e7pce8jb.js} +3 -3
- package/dist/bin/{chunk-cf3jn2ey.js → chunk-f2t67d76.js} +3 -3
- package/dist/bin/chunk-f4mpkpbf.js +1 -0
- package/dist/bin/chunk-f9469h6q.js +1 -0
- package/dist/bin/chunk-fjbhvhqb.js +1 -0
- package/dist/bin/{chunk-nj9x0tb8.js → chunk-gr1ra9nj.js} +2 -2
- package/dist/bin/{chunk-3pazrfsf.js → chunk-hdqxyxs0.js} +7 -7
- package/dist/bin/{chunk-xdk0gmxt.js → chunk-hhmqsrfc.js} +1 -1
- package/dist/bin/{chunk-4mecfcjk.js → chunk-j2wkxp7d.js} +3 -3
- package/dist/bin/{chunk-dj03v81n.js → chunk-k9f94hg4.js} +113 -113
- package/dist/bin/{chunk-znd507q9.js → chunk-kmpvqby6.js} +8 -8
- package/dist/bin/{chunk-n7yefy09.js → chunk-m3xap663.js} +5 -5
- package/dist/bin/chunk-m7pbssep.js +1 -0
- package/dist/{chunk-6rcj3km0.js → bin/chunk-mcg4wg4j.js} +7 -7
- package/dist/bin/{chunk-03gqra5e.js → chunk-mdkd46c5.js} +83 -83
- package/dist/bin/chunk-n7xadeqe.js +1 -0
- package/dist/bin/{chunk-xe527q1k.js → chunk-ppd463ev.js} +2 -2
- package/dist/bin/{chunk-23m8kbwh.js → chunk-q2rqmc2x.js} +3 -3
- package/dist/bin/chunk-q9awn1n3.js +1 -0
- package/dist/bin/chunk-qsfhb3x7.js +1 -0
- package/dist/bin/chunk-r524t8v8.js +1 -0
- package/dist/bin/{chunk-7qbxq0be.js → chunk-rwbdtxte.js} +1 -1
- package/dist/bin/{chunk-v09tfezh.js → chunk-sa9c8vb5.js} +5 -5
- package/dist/bin/{chunk-6y6g726g.js → chunk-t970yjvz.js} +5 -5
- package/dist/bin/{chunk-cz2wq0tf.js → chunk-tcj1z34y.js} +5 -5
- package/dist/bin/{chunk-q8b77zgw.js → chunk-te52z1wk.js} +1 -1
- package/dist/bin/chunk-v2qk9jeb.js +1 -0
- package/dist/bin/{chunk-rdkr74y2.js → chunk-vavwhhrp.js} +1 -1
- package/dist/bin/chunk-w89fyres.js +1 -0
- package/dist/bin/{chunk-frzpqsbj.js → chunk-we2raqk3.js} +2 -2
- package/dist/bin/chunk-wgh66c5r.js +1 -0
- package/dist/bin/chunk-xaqkj8fn.js +1 -0
- package/dist/bin/{chunk-w29z877b.js → chunk-y12vn1h1.js} +2 -2
- package/dist/bin/{chunk-xx9mrcfs.js → chunk-yfa84s0c.js} +1 -1
- package/dist/bin/{chunk-5nmt4s5w.js → chunk-ytzcsskk.js} +2 -2
- package/dist/bin/{chunk-psvqpztv.js → chunk-z06jkvvr.js} +5 -5
- package/dist/bin/cli.js +203 -203
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/chunk-09d6pdgx.js +1 -0
- package/dist/{chunk-yme6q7k4.js → chunk-0cz2s19h.js} +2 -2
- package/dist/{chunk-nryh43p1.js → chunk-0qgfe5ff.js} +3 -3
- package/dist/{chunk-kr8aeva1.js → chunk-18h7na1g.js} +549 -549
- package/dist/chunk-21mmcmm7.js +1 -0
- package/dist/{bin/chunk-k343q24p.js → chunk-3ncnrrvm.js} +7 -7
- package/dist/chunk-4abbccq7.js +2 -0
- package/dist/{chunk-rpng90t9.js → chunk-4yqd62rd.js} +1 -1
- package/dist/chunk-5hgcr7r2.js +709 -0
- package/dist/{chunk-x0ep5ybv.js → chunk-6m8p1n88.js} +13 -13
- package/dist/chunk-85fyadq0.js +448 -0
- package/dist/{chunk-fpkpwbv3.js → chunk-8b2mxhcm.js} +5 -5
- package/dist/{chunk-r3m1fjd4.js → chunk-9ggg2ktx.js} +2 -2
- package/dist/chunk-a8hs75xd.js +5 -0
- package/dist/chunk-ca191b00.js +6 -0
- package/dist/{chunk-jhtp3m31.js → chunk-cpba1hz2.js} +2 -2
- package/dist/{chunk-ynprwawa.js → chunk-erfh93dq.js} +2 -2
- package/dist/{chunk-22hfejjs.js → chunk-ffyx50xx.js} +1 -1
- package/dist/chunk-fqgvackc.js +138 -0
- package/dist/{chunk-jpdpr7k6.js → chunk-j99nkav5.js} +3 -3
- package/dist/chunk-jgsey18z.js +1 -0
- package/dist/{chunk-vb4t2r4r.js → chunk-jtvw9d4x.js} +1 -1
- package/dist/chunk-jytama4e.js +111 -0
- package/dist/chunk-m9r0a1v9.js +2 -0
- package/dist/{chunk-6mp1fyxe.js → chunk-nmnf1ha6.js} +4 -4
- package/dist/{chunk-e8k29wen.js → chunk-nnnhq6sx.js} +19 -19
- package/dist/chunk-qbsrs1gp.js +1 -0
- package/dist/{chunk-xzcpzxtj.js → chunk-qcj3hkba.js} +2 -2
- package/dist/chunk-r4kedmas.js +1 -0
- package/dist/{chunk-p7myt05d.js → chunk-r5mk071y.js} +5 -5
- package/dist/{chunk-xxq1ygp9.js → chunk-thdfk76k.js} +3 -3
- package/dist/chunk-tnqj2en4.js +1 -0
- package/dist/{chunk-da62knsv.js → chunk-zbx9yehq.js} +83 -83
- package/dist/{chunk-vjph4eh0.js → chunk-zf5wdx6v.js} +1 -1
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/aws/provision.d.ts +2 -2
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/mail-provision.d.ts +2 -18
- package/dist/drivers/shared/rpx-gateway.d.ts +3 -1
- package/dist/index.js +60 -60
- package/dist/mail/index.d.ts +5 -0
- package/dist/mail/index.js +3 -0
- package/dist/mail/webmail.d.ts +35 -0
- package/dist/mail/webmail.test.d.ts +1 -0
- 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 +6 -6
- 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 +6 -6
- package/dist/ui/infrastructure/topology.html +6 -6
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- 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 +1 -1
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +2 -2
- 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 +5 -5
- package/dist/ui/server/metrics.html +6 -6
- package/dist/ui/server/security.html +1 -1
- package/dist/ui/server/services.html +1 -1
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +5 -5
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- 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 +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- 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 +7 -3
- package/dist/bin/chunk-1fj03993.js +0 -1
- package/dist/bin/chunk-1xxmyx0r.js +0 -1
- package/dist/bin/chunk-2pzh0wxc.js +0 -1
- package/dist/bin/chunk-45qr2bd3.js +0 -1
- package/dist/bin/chunk-4nn00brw.js +0 -1
- package/dist/bin/chunk-52w33yma.js +0 -1
- package/dist/bin/chunk-5f1n5d80.js +0 -1
- package/dist/bin/chunk-5mm6qn6m.js +0 -1
- package/dist/bin/chunk-5xr76cms.js +0 -1
- package/dist/bin/chunk-65yvjecx.js +0 -2
- package/dist/bin/chunk-d0tmmzy5.js +0 -1
- package/dist/bin/chunk-fqghdpvr.js +0 -1
- package/dist/bin/chunk-gkdr09xx.js +0 -1
- package/dist/bin/chunk-hhhrze6m.js +0 -1
- package/dist/bin/chunk-jrztbsnb.js +0 -1
- package/dist/bin/chunk-kqxk1pds.js +0 -1
- package/dist/bin/chunk-m8p7mw67.js +0 -1
- package/dist/bin/chunk-n2c6y0k1.js +0 -1
- package/dist/bin/chunk-pr1dg1km.js +0 -1
- package/dist/bin/chunk-pzj1ac7x.js +0 -1
- package/dist/bin/chunk-rgcrsd5m.js +0 -1
- package/dist/bin/chunk-thph4z3k.js +0 -1
- package/dist/bin/chunk-txykq6f1.js +0 -1
- package/dist/bin/chunk-vjg2fymw.js +0 -1
- package/dist/bin/chunk-ym9h629y.js +0 -111
- package/dist/bin/chunk-z8scg2vy.js +0 -1
- package/dist/bin/chunk-zjvg5pg8.js +0 -1
- package/dist/chunk-25sw2s70.js +0 -1
- package/dist/chunk-2pns2rkf.js +0 -111
- package/dist/chunk-2sc0s7pc.js +0 -6
- package/dist/chunk-7v7dwev4.js +0 -584
- package/dist/chunk-bdv3gpzb.js +0 -709
- package/dist/chunk-fh7apa5n.js +0 -2
- package/dist/chunk-gh0ghb21.js +0 -2
- package/dist/chunk-gqadvddh.js +0 -1
- package/dist/chunk-kpmxvpcv.js +0 -1
- package/dist/chunk-ksqhsz52.js +0 -1
- package/dist/chunk-p588apka.js +0 -1
- package/dist/chunk-vnarc5gc.js +0 -5
- package/dist/chunk-x7d93rxb.js +0 -1
package/dist/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import{lI,uI,Od,jp,_d,Ld,Jr,L,d,$d,zp,Q,Md,g,kA,Mi,Fd,Ud,fe,Qd,BA,r,t,gI,pI,p,mI,fI,hI,yI,SI,Xt,Hd,Fi,xA,II,bI,De,je,Gd,Kp,Wp,CI,Jp,Xp,Yp,vo,Vd,re,Xr,yt,To,St,he,OA,qd,wo,Zp,em,tm,rm,jd,EI,H,b,_A,LA,nm,a,y,ze,m,im,Ke,G,It,vI,sm,V,zd,Pe,Yt,Ro,ne,Kd,ie,$A,Do,q,j,k,Ui,T,Zt,bt,z,e,Yr,TI,om,Wd,wI,RI,DI,PI,Jd,NI,kI,BI,xI,OI,_I,LI,$I,MI,FI,UI,QI,MA,FA,UA,QA,HA,GA,VA,er,am,cm,Zr,Qi,HI,dm,GI,VI,en,qI,jI,zI,KI,WI,JI,qA,jA,zA,KA,WA,Hi,XI,Po,JA,lm,F,XA,We,No,Ct,YA,um,ZA,ey,ty,gm,U,YI,ZI,eb,tb,ry,rb,K,nb,ib,sb,Xd,Yd,ny,pm,mm,ob,ab,cb,db,lb,iy,Zd,ub,gb,pb,mb,fb,sy,oy,hb,Ab,yb,Sb,Ib,bb,Cb,ay,Eb,fm,el,vb,Tb,wb,Rb,hm,Am,ym,Db,tl,cy,dy,ly,uy,rl,gy,Pb,Nb,kb,Bb,xb,Ob,_b,py,my,fy,hy,Sm,Lb,$b,Mb,Fb,Ub,Qb,Hb,Gb,Vb,Ay,yy,Sy,Iy,qb,jb,Im,zb,bm,Cm,Em,vm,Kb,Wb,Jb,Xb,Ne,Gi,Yb,Zb,eC,tC,rC,nC,iC,sC,by,oC,aC,Tm,wm,cC,dC,Cy,lC,uC,gC,pC,mC,fC,hC,AC,yC,SC,IC,bC,CC,EC,vC,TC,wC,RC,DC,PC,NC,nl,Ey,il,vy,sl,Ty,ol,wy,al,Ry,tr,Dy,cl,Py,Vi,Ny,dl,ky,ll,By,Rm,kC,Dm,BC,ul,xy,rr,Oy,Pm,xC,gl,_y,Nm,OC,km,_C,Bm,LC,pl,Ly,xm,$C,Om,MC,_m,FC,Lm,UC,ml,$y,fl,My,$m,QC,Mm,HC,Fm,GC,Um,VC,Qm,qC,Hm,jC,hl,Fy,Gm,zC,Vm,KC,qm,WC,jm,JC,zm,XC,Km,YC,Wm,Jm,Xm,Ym,Zm,ZC,ef,eE,tf,tE,rf,rE,Je,nf,Uy,ko,Al,tn,Qy,qi,nr,yl,Sl,Hy,Gy,Il,sf,bl,of,nE,iE,Bo,xo,Oo,Cl,rn,El,vl,ji,_o,Lo,af,Vy,qy,jy,sE,cf,df,oE,zy,lf,Ky,Wy,Jy,aE,uf,nn,Tl,gf,cE,Xy,$o,Mo,wl,pf,dE,Rl,Yy,mf,lE,ff,uE,hf,gE}from"./chunk-kr8aeva1.js";import{Dl,R,Pl,Fo,Zy,Af,eS,tS,rS,nS,iS,sS,oS,aS}from"./chunk-x0ep5ybv.js";import{qo,yf,Ll,uS,Ji,$l,jo,Sf,If,on,zo,Ml,Ye,Fl,Ul,Ql,Xi,an,bf,Ze,Hl,Ko,Wo,Jo,Gl,Vl,ql,Yi,Xo,jl,cn,Zi,Yo,Et,Cf,zl,Kl,Ef,Wl,Zo,ir,Jl,Xl,Yl,Zl,et,vf,eu,sr,ea,ta,ra,es,ts,dn,tu,rs,na,ia,ln,ru,un,Tf,wf,vt,gn,sa,Rf,nu,iu,oa,su,ou,au,gS,se,cu,pS,mS,ns,is,fS,Ae,Df,Tt,ke,Be,wt,du,lu,uu,gu,Pf,Nf,aa,kf,Bf,ca,pu,mu,xf,oe,Of,fu,ye,da,tt,Rt,Dt,pn,ss,hu,hS,la,_f,Lf,$f,Mf,ua,ga,Au,mn,pa,yu,os,Su,ma,fa,ha,Aa,ya,Sa,Ia,ba,Iu,or,Ca,bu,fn,Cu,Ea,va,Eu,ar,Ta,wa,Ff,AS,as,yS,SS,IS,Ra,Da,vu,Uf,Pa,hn,Tu,cs,wu,Ru,Du,Na,Qf,ka,Pu,Hf,Ba,Gf,An,yn,Nu,ds,Lu,Uu,Qu,Hu,Gu,Vu,us,cr,Oa,Sn,In,dr,rt,Xf,La,Yf,Zf,zu,$a,ps,Ku,Ma,Nt,Oe,Wu,Fa,Ua,Ju,Qa,Ha,Ga,Va,Xu,Yu,Cn,qa,ja,za,Ka,Zu,ms,En,fs,Wa}from"./chunk-bdv3gpzb.js";import{_,Lr,Wc,Ys,u,Ip,bp}from"./chunk-jhtp3m31.js";import{pt,Kc,bi,Ci,Ei,Sp}from"./chunk-6mp1fyxe.js";import{kh,Bh,xh,ep,tp,rp,Oh,np,ip,_h,Lh,sp,$h,Mh,jc,op,Fh,Uh,ap,Qh,Hh,Gh,Vh,qh,jh,zh,Ii,zc,cp,dp,lp,up,gp,pp,mp,fp,hp,Ap,yp,Kh,Wh,Jh,Xh,Yh,Zh,eA}from"./chunk-e8k29wen.js";import{Ge,Jc,me,Vt,Xc,P,qt,mt,Yc,Zs,nA,Cp,Zc,s,vi,eo,$r,ed,td,Mr,iA,rd,oI,aI,to,cI,dI,nd,id,Ti,ro,te,c,no,Ve,Fr,sA,oA,sd,jt,aA,io,cA,dA,so,od,Ur,oo,lA,ad,Ep,zt,Qr,uA,ao,gA,N,pA,cd,vp,co,mA,fA,hA,dd,wi,lo,ld,Kt,ft,AA,Hr,yA,ud,Tp,wp,uo,gd,pd,ht,Rp,Ri,md,go,Gr,Dp,Di,fd,hd,Pi,Pp,Ad,yd,Sd,Id,po,Np,kp,SA,Bp,bd,Ni,xp,Op,mo,Vr,fo,ho,Ao,Cd,_p,Ed,yo,IA,Wt,bA,vd,qr,Td,CA,wd,Lp,ki,jr,So,Bi,qe,EA,$p,Mp,Jt,Rd,Dd,Pd,xi,Oi,_i,vA,TA,At,Io,wA,zr,Fp,bo,RA,Up,Qp,Hp,DA,Gp,Vp,PA,i,NA,Li,Co,Eo}from"./chunk-da62knsv.js";import{n}from"./chunk-2sc0s7pc.js";import{be,ot,On}from"./chunk-nryh43p1.js";import{o}from"./chunk-jpdpr7k6.js";import{Se,Cs,Es,rg,ec,tc,vs,rc,nt,W,it,ae,E,Ie,Rn,nc,_e,ic,Dn,Pn,Nn,kt,Bt,xt,kn,ur,sc,gr,pr,st,Bn,ac,Ot,mr,xn,dc,ag,cg,lc,fr}from"./chunk-2pns2rkf.js";import{at,le,Me,dg,_t,gc,pc,Lt,M,_n,$t,Mt,Ln,Ds,Ps,hr,Ar,$n,yr,Ns,ks,Bs,xs,X,Os,_s,Ls,$s,ue,Ms,Fs,Us,D,mc,Mn,fc,ge,Sr}from"./chunk-gh0ghb21.js";import{J}from"./chunk-fh7apa5n.js";import{lg,hc,ug,Ce,Ac,Un,gg,yc,pg,mg,gh,Hn,Hs,Gn,Vn,qn,Y,Fe,x,vr,zn,Tr,pe,Ic,Kn,bc,Rr,Jn,Vs,Xn,Yn,Zn,ei,Dr,wc,Ue,Z,Qe,He,dt,Te,Pr,we,ni,ii,si,oi,ai,ci,di,Nr,O,zs,Ug,xc,ui,gi,pi,mi,Uc,Ks,Qc,Gt,fi,Ws,Js,Hc,hi,Gc}from"./chunk-7v7dwev4.js";import{Nl,Uo,zi,Ki,Qo,kl,Bl,Wi,Ho,Go,Ol,_l,Vo}from"./chunk-22hfejjs.js";import{Ja,vn,Tn,hs,As,ys,Ss,Xa,Ya}from"./chunk-fpkpwbv3.js";import{Za}from"./chunk-vnarc5gc.js";import{uc,Le,S}from"./chunk-yme6q7k4.js";import{$e}from"./chunk-xzcpzxtj.js";import{I}from"./chunk-vb4t2r4r.js";import{ee,Ai,Xs,Vc,yi,Xg}from"./chunk-p7myt05d.js";import{Br,Re}from"./chunk-xxq1ygp9.js";import{h}from"./chunk-vjph4eh0.js";import{Nd,Kr,kd,Bd,xd,$i,qp,Wr}from"./chunk-6rcj3km0.js";import{cS,Xe}from"./chunk-ynprwawa.js";var $S="https://api.machines.dev/v1";class _a extends Error{status;path;constructor(l,f,C){super(l);this.status=f;this.path=C;this.name="FlyApiError"}}function Ou(l){let f=l.ip.includes(":");if(f&&l.ip.startsWith("fdaa:"))return"private_v6";if(l.shared)return"shared_v4";return f?"v6":"v4"}class kg{token;fetch;constructor(l){if(!l.token)throw Error("Fly.io needs an API token: set FLY_API_TOKEN (`fly tokens create deploy` makes one scoped to an app).");this.token=l.token,this.fetch=l.fetch??fetch}async rest(l,f,C={}){let A=new URL(`https://api.machines.dev/v1${f}`);for(let[ce,de]of Object.entries(C.query??{}))A.searchParams.set(ce,de);let w=await this.fetch(A,{method:l,headers:{Authorization:`Bearer ${this.token}`,...C.body!==void 0?{"Content-Type":"application/json"}:{},...C.headers},body:C.body===void 0?void 0:JSON.stringify(C.body)});if(w.status===404&&C.notFound==="null")return null;let B=await w.text(),v=B?vg(B):void 0;if(!w.ok){let ce=typeof v==="object"&&v&&"error"in v?String(v.error):B||w.statusText;throw new _a(`Fly.io ${l} ${f} failed (${w.status}): ${ce}`,w.status,f)}return v}getApp(l){return this.rest("GET",`/apps/${encodeURIComponent(l)}`,{notFound:"null"})}createApp(l,f){return this.rest("POST","/apps",{body:{app_name:l,org_slug:f}})}async listMachines(l){return await this.rest("GET",`/apps/${encodeURIComponent(l)}/machines`)??[]}createMachine(l,f){return this.rest("POST",`/apps/${encodeURIComponent(l)}/machines`,{body:f})}updateMachine(l,f,C,A){return this.rest("POST",`/apps/${encodeURIComponent(l)}/machines/${encodeURIComponent(f)}`,{body:C,headers:{"fly-machine-lease-nonce":A}})}async acquireLease(l,f,C=120){let w=(await this.rest("POST",`/apps/${encodeURIComponent(l)}/machines/${encodeURIComponent(f)}/lease`,{body:{ttl:C}})).data?.nonce;if(!w)throw new _a(`Fly.io gave no lease nonce for Machine ${f}`,200,`/machines/${f}/lease`);return w}async releaseLease(l,f,C){await this.rest("DELETE",`/apps/${encodeURIComponent(l)}/machines/${encodeURIComponent(f)}/lease`,{headers:{"fly-machine-lease-nonce":C}})}async waitForState(l,f,C,A={}){await this.rest("GET",`/apps/${encodeURIComponent(l)}/machines/${encodeURIComponent(f)}/wait`,{query:{state:C,timeout:String(A.timeoutSeconds??60),...A.instanceId?{instance_id:A.instanceId}:{}}})}async listVolumes(l){return await this.rest("GET",`/apps/${encodeURIComponent(l)}/volumes`)??[]}createVolume(l,f){return this.rest("POST",`/apps/${encodeURIComponent(l)}/volumes`,{body:{...f,encrypted:!0}})}async setSecrets(l,f){return(await this.rest("POST",`/apps/${encodeURIComponent(l)}/secrets`,{body:{values:f}})).version}async listIpAssignments(l){return(await this.rest("GET",`/apps/${encodeURIComponent(l)}/ip_assignments`)).ips??[]}async assignIp(l,f){let C=await this.rest("POST",`/apps/${encodeURIComponent(l)}/ip_assignments`,{body:{type:f}});if(!C.ip)throw new _a(`Fly.io assigned no ${f} address to ${l}`,200,`/apps/${l}/ip_assignments`);return{ip:C.ip,shared:C.shared??f==="shared_v4",region:C.region}}async requestCertificate(l,f){return this.rest("POST",`/apps/${encodeURIComponent(l)}/certificates/acme`,{body:{hostname:f}})}}function vg(l){try{return JSON.parse(l)}catch{return}}var Ec="ts-cloud-role";function kS(l,f){let C=l.fly??{},A=C.app??`${l.project.slug}-${f.environment}`;if(!/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(A))throw Error(`"${A}" is not a valid Fly app name: lowercase letters, digits and dashes, 3 to 63 characters.`);let w=C.internalPort??3000,B=C.count??1;if(!Number.isInteger(B)||B<1)throw Error(`fly.count must be a whole number of at least 1, got ${B}.`);return{app:A,org:C.org??"personal",image:f.image,regions:C.regions?.length?C.regions:["iad"],count:B,internalPort:w,healthPath:C.healthPath??"/",vm:{cpuKind:C.vm?.cpuKind??"shared",cpus:C.vm?.cpus??1,memoryMb:C.vm?.memoryMb??512},...C.volume?{volume:{name:C.volume.name??"data",sizeGb:C.volume.sizeGb,path:C.volume.path}}:{},autoStop:C.autoStop??!1,env:{...f.env,PORT:String(w)},secrets:f.secrets??{},hostnames:C.hostnames??[],release:f.release}}function Eg(l){return{image:l.image,env:l.env,guest:{cpu_kind:l.vm.cpuKind,cpus:l.vm.cpus,memory_mb:l.vm.memoryMb},services:[{protocol:"tcp",internal_port:l.internalPort,ports:[{port:80,handlers:["http"],force_https:!0},{port:443,handlers:["tls","http"]}],autostop:l.autoStop?"stop":"off",autostart:!0,...l.autoStop?{min_machines_running:0}:{},checks:[{type:"http",method:"GET",path:l.healthPath,interval:"15s",timeout:"5s",grace_period:"10s"}]}],restart:{policy:"on-failure",max_retries:10},metadata:{[Ec]:"app","ts-cloud-release":l.release}}}async function vS(l,f,C=()=>{}){let A=!1;if(!await l.getApp(f.app))C(`Creating Fly app ${f.app} in ${f.org}`),await l.createApp(f.app,f.org),A=!0;let w;if(Object.keys(f.secrets).length>0)w=await l.setSecrets(f.app,f.secrets),C(`Set ${Object.keys(f.secrets).length} secret(s) (version ${w})`);let B=await l.listIpAssignments(f.app),v=new Set(B.map(Ou));if(!v.has("v6"))B.push(await l.assignIp(f.app,"v6")),C("Assigned a dedicated IPv6");if(!v.has("v4")&&!v.has("shared_v4"))B.push(await l.assignIp(f.app,"shared_v4")),C("Assigned a shared IPv4");let ce=Eg(f),de=(await l.listMachines(f.app)).filter((lt)=>{let ut=lt.config?.metadata??{};if(ut[Ec])return ut[Ec]==="app";return!ut.fly_process_group||ut.fly_process_group==="app"}),ct=f.volume?await l.listVolumes(f.app):[],xe=[],Ut=[],Qt=new Set;for(let lt of f.regions){let ut=de.filter((Ee)=>Ee.region===lt).sort((Ee,Ft)=>Ee.id.localeCompare(Ft.id));for(let Ee=0;Ee<f.count;Ee++){let Ft=ut[Ee];if(Ft){Qt.add(Ft.id),await Og(l,f.app,Ft,ce,w),Ut.push(Ft.id),C(`Updated ${Ft.id} (${lt}) to ${f.image}`);continue}let ve=f.volume?[{volume:(await Ng(l,f,lt,ct)).id,path:f.volume.path}]:void 0,Pt=await l.createMachine(f.app,{region:lt,name:`${f.app}-${lt}-${Ee+1}`,config:{...ce,...ve?{mounts:ve}:{}},...w!==void 0?{min_secrets_version:w}:{}});await l.waitForState(f.app,Pt.id,"started",{instanceId:Pt.instance_id}),xe.push(Pt.id),C(`Created ${Pt.id} in ${lt}`)}}let gt=[];for(let lt of f.hostnames)gt.push(await l.requestCertificate(f.app,lt));return{app:f.app,url:`https://${f.app}.fly.dev`,createdApp:A,created:xe,updated:Ut,untouched:de.filter((lt)=>!Qt.has(lt.id)).map((lt)=>lt.id),ips:B,certificates:gt}}async function Og(l,f,C,A,w){let B=await l.acquireLease(f,C.id);try{let v=await l.updateMachine(f,C.id,{config:{...A,...C.config?.mounts?.length?{mounts:C.config.mounts}:{}},...w!==void 0?{min_secrets_version:w}:{}},B);await l.waitForState(f,C.id,"started",{instanceId:v.instance_id})}finally{await l.releaseLease(f,C.id,B)}}async function Ng(l,f,C,A){let w=A.find((v)=>v.region===C&&v.name===f.volume.name&&!v.attached_machine_id);if(w)return w.attached_machine_id="pending",w;let B=await l.createVolume(f.app,{name:f.volume.name,region:C,size_gb:f.volume.sizeGb});return A.push({...B,attached_machine_id:"pending"}),B}import{createHmac as xu,createSign as xg,timingSafeEqual as Lg}from"node:crypto";function bs(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 Fu(l){return Buffer.from(l).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function Fg(l){return Buffer.from(l).toString("base64url")}function _u(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 Mu(l,f){let C=xg("RSA-SHA1");return C.update(l),C.end(),Fu(C.sign(f))}function Bu(l){_u(l.resource,!0);let C={DateLessThan:{"AWS:EpochTime":bs(l.expiresAt)}};if(l.activeAt!==void 0)C.DateGreaterThan={"AWS:EpochTime":bs(l.activeAt)};if(l.ipAddress)C.IpAddress={"AWS:SourceIp":l.ipAddress};return JSON.stringify({Statement:[{Resource:l.resource,Condition:C}]})}function FS(l,f,C){_u(l);let A=bs(f),w=l.includes("?")?"&":"?",B=Bu({resource:l,expiresAt:f}),v=Mu(B,C.privateKey);return`${l}${w}Expires=${A}&Signature=${encodeURIComponent(v)}&Key-Pair-Id=${encodeURIComponent(C.keyPairId)}`}function _S(l,f){let C=Bu(l);return{"CloudFront-Key-Pair-Id":f.keyPairId,"CloudFront-Policy":Fu(Buffer.from(C)),"CloudFront-Signature":Mu(C,f.privateKey)}}function MS(l){if(!l.resource||/[\r\n]/.test(l.resource))throw TypeError("Media resource is invalid");let f=Fg(Buffer.from(JSON.stringify({resource:l.resource,expiresAt:bs(l.expiresAt),...l.keyId?{keyId:l.keyId}:{},...l.audience?{audience:l.audience}:{}}))),C=xu("sha256",l.secret).update(f).digest("base64url");return`${f}.${C}`}function BS(l,f){let[C,A,w]=l.split(".");if(!C||!A||w)return null;let B=xu("sha256",f.secret).update(C).digest(),v;try{v=Buffer.from(A,"base64url")}catch{return null}if(B.length!==v.length||!Lg(B,v))return null;try{let ce=JSON.parse(Buffer.from(C,"base64url").toString("utf8")),de=bs(f.now??Date.now());if(!ce.resource||!Number.isSafeInteger(ce.expiresAt)||ce.expiresAt<=de)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 WS(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 VS(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 _g{builder;config;environment;mergedConfig;serverEipLogicalIds=new Map;storageFailoverReplicas=[];constructor(l){this.config=l.config,this.environment=l.environment,this.builder=new Qd(`${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,B){let v=this.serverEipLogicalIds.get("app"),ce=this.serverEipLogicalIds.get("appInstance");if(!v)return;let de=`EC2-${A}-${w}-api`,ct=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",xe=ct==="us-east-1"?".compute-1.amazonaws.com":`.${ct}.compute.amazonaws.com`,Ut={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:v}]}]},xe]]},Qt=this.resolveApiOriginPort();if(l.push({Id:de,DomainName:Ut,CustomOriginConfig:{HTTPPort:Qt,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),C.push(v),ce)C.push(ce);for(let gt of B)f.push(this.createComputeCacheBehavior(gt,de))}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 B=C.get(w.domain)??[];B.push({port:w.port,path:w.path}),C.set(w.domain,B)}let A=[];for(let[w,B]of C){let ce=[...B].sort((de,ct)=>{let xe=!de.path||de.path==="/",Ut=!ct.path||ct.path==="/";if(xe&&!Ut)return 1;if(!xe&&Ut)return-1;return(ct.path?.length??0)-(de.path?.length??0)}).map((de)=>{let ct=!de.path||de.path==="/",xe=`reverse_proxy localhost:${de.port}`;return ct?` handle {
|
|
2
|
-
${
|
|
3
|
-
}`:` handle ${
|
|
4
|
-
${
|
|
5
|
-
}`});A.push(`${
|
|
6
|
-
${
|
|
1
|
+
import{EI,vI,qd,nm,jd,zd,sn,Q,l,Kd,im,K,Wd,g,HA,b,Xe,Hi,on,w,be,Jd,GA,r,t,TI,wI,p,RI,DI,PI,NI,kI,sr,Xd,Gi,VA,BI,xI,xe,Ye,Yd,sm,om,OI,am,cm,dm,Bo,Zd,ce,an,Tt,xo,wt,Ce,qA,el,Oo,lm,um,gm,pm,tl,_I,W,C,jA,zA,mm,a,y,Ze,m,fm,et,J,Rt,LI,hm,X,rl,Oe,or,_o,de,nl,le,KA,Lo,Y,Z,_,Vi,D,ar,Dt,ee,e,cn,$I,Am,il,MI,FI,UI,QI,sl,HI,GI,VI,qI,jI,zI,KI,WI,JI,XI,YI,ZI,WA,JA,XA,YA,ZA,ey,ty,cr,ym,Sm,dr,qi,eb,Im,tb,rb,dn,nb,ib,sb,ob,ab,cb,ry,ny,iy,sy,oy,ji,db,$o,ay,bm,V,cy,tt,Mo,Pt,dy,Cm,ly,uy,gy,Em,q,lb,ub,gb,pb,py,mb,te,fb,hb,Ab,ol,al,my,vm,Tm,yb,Sb,Ib,bb,Cb,fy,cl,Eb,vb,Tb,wb,Rb,hy,Ay,Db,Pb,Nb,kb,Bb,xb,Ob,yy,_b,wm,dl,Lb,$b,Mb,Fb,Rm,Dm,Pm,Ub,ll,Sy,Iy,by,Cy,ul,Ey,Qb,Hb,Gb,Vb,qb,jb,zb,vy,Ty,wy,Ry,Nm,Kb,Wb,Jb,Xb,Yb,Zb,eC,tC,rC,Dy,Py,Ny,ky,nC,iC,km,sC,Bm,xm,Om,_m,oC,aC,cC,dC,_e,zi,lC,uC,gC,pC,mC,fC,hC,AC,By,yC,SC,Lm,$m,IC,bC,xy,CC,EC,vC,TC,wC,RC,DC,PC,NC,kC,BC,xC,OC,_C,LC,$C,MC,FC,UC,QC,HC,gl,Oy,pl,_y,ml,Ly,fl,$y,hl,My,lr,Fy,Al,Uy,Ki,Qy,yl,Hy,Sl,Gy,Mm,GC,Fm,VC,Il,Vy,ur,qy,Um,qC,bl,jy,Qm,jC,Hm,zC,Gm,KC,Cl,zy,Vm,WC,qm,JC,jm,XC,zm,YC,El,Ky,vl,Wy,Km,ZC,Wm,eE,Jm,tE,Xm,rE,Ym,nE,Zm,iE,Tl,Jy,ef,sE,tf,oE,rf,aE,nf,cE,sf,dE,of,lE,af,cf,df,lf,uf,uE,gf,gE,pf,pE,mf,mE,rt,ff,Xy,Fo,wl,ln,Yy,Wi,gr,Rl,Dl,Zy,eS,Pl,hf,Nl,Af,fE,hE,Uo,Qo,Ho,kl,un,Bl,xl,Ji,Go,Vo,yf,tS,rS,nS,AE,Sf,If,yE,iS,bf,sS,oS,aS,SE,Cf,gn,Ol,Ef,IE,cS,qo,jo,_l,vf,bE,Ll,dS,Tf,CE,wf,EE,Rf,vE}from"./chunk-18h7na1g.js";import{$l,N,Ml,zo,lS,Df,uS,gS,pS,mS,fS,hS,AS,yS}from"./chunk-6m8p1n88.js";import{Zo,Pf,ql,CS,es,jl,ea,Nf,kf,mn,ta,zl,it,Kl,Wl,Jl,ts,fn,Bf,st,Xl,ra,na,ia,Yl,Zl,eu,rs,sa,tu,hn,ns,oa,Nt,xf,ru,nu,Of,iu,aa,pr,su,ou,au,cu,ot,_f,du,mr,ca,da,la,is,ss,An,lu,os,ua,ga,yn,uu,Sn,Lf,$f,kt,In,pa,Mf,gu,pu,ma,mu,fu,hu,ES,ue,Au,vS,TS,as,cs,wS,Ee,Ff,Bt,Le,$e,xt,yu,Su,Iu,bu,Uf,Qf,fa,Hf,Gf,ha,Cu,Eu,Vf,ge,qf,vu,ve,Aa,at,Ot,_t,bn,ds,Tu,RS,jf,zf,Kf,Wf,ya,Sa,wu,Ia,Cn,ba,Ru,ls,Du,Ca,Ea,va,Ta,wa,Ra,Da,Pa,Pu,fr,Na,Nu,En,ku,ka,Ba,Bu,hr,xa,Oa,Jf,DS,us,PS,NS,kS,_a,La,xu,Xf,$a,vn,Ou,gs,_u,Lu,$u,Ma,Yf,Fa,Mu,Zf,Ua,eh,Tn,wn,Fu,ps,qu,Wu,Ju,Xu,Yu,Zu,fs,Ar,Ha,Rn,Dn,yr,ct,ch,Va,dh,lh,rg,qa,As,ng,ja,$t,Fe,ig,za,Ka,sg,Wa,Ja,Xa,Ya,og,ag,Nn,Za,ec,tc,rc,cg,ys,kn,Ss,nc}from"./chunk-5hgcr7r2.js";import{U,Vr,od,oo,d,kp,Bp}from"./chunk-cpba1hz2.js";import{It,sd,Ti,wi,Ri,Np}from"./chunk-nmnf1ha6.js";import{Hh,Gh,Vh,up,gp,pp,qh,mp,fp,jh,zh,hp,Kh,Wh,nd,Ap,Jh,Xh,yp,Yh,Zh,eA,tA,rA,nA,iA,vi,id,Sp,Ip,bp,Cp,Ep,vp,Tp,wp,Rp,Dp,Pp,sA,oA,aA,cA,dA,lA,uA}from"./chunk-nnnhq6sx.js";import{Ke,ad,Ie,Yt,cd,x,Zt,bt,dd,ao,mA,xp,ld,s,Di,co,qr,ud,gd,jr,fA,pd,SI,II,lo,bI,CI,md,fd,Pi,uo,ae,c,go,We,zr,hA,AA,hd,yA,po,SA,IA,mo,Ad,Kr,fo,bA,er,yd,Op,tr,Wr,CA,ho,EA,O,vA,Sd,_p,Ao,TA,wA,RA,Id,Ni,yo,bd,rr,Ct,DA,Jr,PA,Cd,Lp,$p,So,Ed,vd,Et,Mp,ki,Td,Io,Xr,Fp,Bi,wd,Rd,xi,Up,Dd,Pd,Nd,kd,bo,Qp,Hp,NA,Gp,Bd,Oi,Vp,qp,Co,Yr,Eo,vo,To,xd,jp,Od,wo,kA,nr,BA,_d,Zr,Ld,xA,$d,zp,_i,en,Ro,Li,Je,OA,Kp,Wp,ir,Md,Fd,Ud,$i,Mi,Fi,_A,LA,vt,Do,$A,tn,Jp,Po,MA,Xp,Yp,Zp,FA,em,tm,UA,i,QA,Ui,No,ko}from"./chunk-zbx9yehq.js";import{n}from"./chunk-ca191b00.js";import{Re,gt,Gn}from"./chunk-0qgfe5ff.js";import{o}from"./chunk-j99nkav5.js";import{Te,ws,Rs,ug,cc,dc,Ds,lc,dt,re,lt,pe,v,we,_n,uc,Ue,gc,Ln,$n,Mn,Mt,Ft,Ut,Un,Ir,pc,br,Cr,ut,Qn,fc,Qt,Er,Hn,Ac,hg,Ag,yc,vr}from"./chunk-jytama4e.js";import{pt,he,Ge,yg,Ht,Ic,bc,Gt,H,Vn,Vt,qt,qn,Bs,xs,Tr,wr,jn,Rr,Os,_s,Ls,$s,ie,Ms,Fs,Us,Qs,Ae,Hs,Gs,Vs,k,Cc,zn,Ec,ye,Dr}from"./chunk-m9r0a1v9.js";import{ne}from"./chunk-4abbccq7.js";import{Sg,vc,Ig,De,Tc,Kn,bg,wc,Cg,Eg,Eh,Jn,js,M,Br,Xn,xr,Se,Rc,Yn,Dc,_r,ei,zs,ti,ri,ni,ii,Lr,xc,Ve,se,qe,je,ft,Pe,$r,Ne,ai,ci,di,li,ui,gi,pi,Mr,F,Js,Kg,Uc,fi,hi,Ai,yi,zc,Xs,Kc,Jt,Si,Ys,Zs,Wc,Ii,Jc}from"./chunk-85fyadq0.js";import{to,no,io,B,ke}from"./chunk-fqgvackc.js";import{Fl,Ko,Xi,Yi,Wo,Ul,Ql,Zi,Jo,Xo,Gl,Vl,Yo}from"./chunk-ffyx50xx.js";import{ic,Bn,xn,Is,bs,Cs,Es,sc,oc}from"./chunk-8b2mxhcm.js";import{ac}from"./chunk-a8hs75xd.js";import{Sc,Qe,S}from"./chunk-0cz2s19h.js";import{He}from"./chunk-qcj3hkba.js";import{I}from"./chunk-jtvw9d4x.js";import{oe,bi,eo,Xc,Ci,sp}from"./chunk-r5mk071y.js";import{Ur,Be}from"./chunk-thdfk76k.js";import{h}from"./chunk-zf5wdx6v.js";import{Qd,rn,Hd,Gd,Vd,Qi,rm,nn}from"./chunk-3ncnrrvm.js";import{SS,nt}from"./chunk-erfh93dq.js";var Uh="https://api.machines.dev/v1";class Ws extends Error{status;path;constructor(u,f,R){super(u);this.status=f;this.path=R;this.name="FlyApiError"}}function Qc(u){let f=u.ip.includes(":");if(f&&u.ip.startsWith("fdaa:"))return"private_v6";if(u.shared)return"shared_v4";return f?"v6":"v4"}class mg{token;fetch;constructor(u){if(!u.token)throw Error("Fly.io needs an API token: set FLY_API_TOKEN (`fly tokens create deploy` makes one scoped to an app).");this.token=u.token,this.fetch=u.fetch??fetch}async rest(u,f,R={}){let A=new URL(`https://api.machines.dev/v1${f}`);for(let[L,z]of Object.entries(R.query??{}))A.searchParams.set(L,z);let T=await this.fetch(A,{method:u,headers:{Authorization:`Bearer ${this.token}`,...R.body!==void 0?{"Content-Type":"application/json"}:{},...R.headers},body:R.body===void 0?void 0:JSON.stringify(R.body)});if(T.status===404&&R.notFound==="null")return null;let E=await T.text(),P=E?gg(E):void 0;if(!T.ok){let L=typeof P==="object"&&P&&"error"in P?String(P.error):E||T.statusText;throw new Ws(`Fly.io ${u} ${f} failed (${T.status}): ${L}`,T.status,f)}return P}getApp(u){return this.rest("GET",`/apps/${encodeURIComponent(u)}`,{notFound:"null"})}createApp(u,f){return this.rest("POST","/apps",{body:{app_name:u,org_slug:f}})}async listMachines(u){return await this.rest("GET",`/apps/${encodeURIComponent(u)}/machines`)??[]}createMachine(u,f){return this.rest("POST",`/apps/${encodeURIComponent(u)}/machines`,{body:f})}updateMachine(u,f,R,A){return this.rest("POST",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(f)}`,{body:R,headers:{"fly-machine-lease-nonce":A}})}async acquireLease(u,f,R=120){let T=(await this.rest("POST",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(f)}/lease`,{body:{ttl:R}})).data?.nonce;if(!T)throw new Ws(`Fly.io gave no lease nonce for Machine ${f}`,200,`/machines/${f}/lease`);return T}async releaseLease(u,f,R){await this.rest("DELETE",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(f)}/lease`,{headers:{"fly-machine-lease-nonce":R}})}async waitForState(u,f,R,A={}){await this.rest("GET",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(f)}/wait`,{query:{state:R,timeout:String(A.timeoutSeconds??60),...A.instanceId?{instance_id:A.instanceId}:{}}})}async listVolumes(u){return await this.rest("GET",`/apps/${encodeURIComponent(u)}/volumes`)??[]}createVolume(u,f){return this.rest("POST",`/apps/${encodeURIComponent(u)}/volumes`,{body:{...f,encrypted:!0}})}async setSecrets(u,f){return(await this.rest("POST",`/apps/${encodeURIComponent(u)}/secrets`,{body:{values:f}})).version}async listIpAssignments(u){return(await this.rest("GET",`/apps/${encodeURIComponent(u)}/ip_assignments`)).ips??[]}async assignIp(u,f){let R=await this.rest("POST",`/apps/${encodeURIComponent(u)}/ip_assignments`,{body:{type:f}});if(!R.ip)throw new Ws(`Fly.io assigned no ${f} address to ${u}`,200,`/apps/${u}/ip_assignments`);return{ip:R.ip,shared:R.shared??f==="shared_v4",region:R.region}}async requestCertificate(u,f){return this.rest("POST",`/apps/${encodeURIComponent(u)}/certificates/acme`,{body:{hostname:f}})}}function gg(u){try{return JSON.parse(u)}catch{return}}var Lc="ts-cloud-role";function $S(u,f){let R=u.fly??{},A=R.app??`${u.project.slug}-${f.environment}`;if(!/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(A))throw Error(`"${A}" is not a valid Fly app name: lowercase letters, digits and dashes, 3 to 63 characters.`);let T=R.internalPort??3000,E=R.count??1;if(!Number.isInteger(E)||E<1)throw Error(`fly.count must be a whole number of at least 1, got ${E}.`);return{app:A,org:R.org??"personal",image:f.image,regions:R.regions?.length?R.regions:["iad"],count:E,internalPort:T,healthPath:R.healthPath??"/",vm:{cpuKind:R.vm?.cpuKind??"shared",cpus:R.vm?.cpus??1,memoryMb:R.vm?.memoryMb??512},...R.volume?{volume:{name:R.volume.name??"data",sizeGb:R.volume.sizeGb,path:R.volume.path}}:{},autoStop:R.autoStop??!1,env:{...f.env,PORT:String(T)},secrets:f.secrets??{},hostnames:R.hostnames??[],release:f.release}}function fg(u){return{image:u.image,env:u.env,guest:{cpu_kind:u.vm.cpuKind,cpus:u.vm.cpus,memory_mb:u.vm.memoryMb},services:[{protocol:"tcp",internal_port:u.internalPort,ports:[{port:80,handlers:["http"],force_https:!0},{port:443,handlers:["tls","http"]}],autostop:u.autoStop?"stop":"off",autostart:!0,...u.autoStop?{min_machines_running:0}:{},checks:[{type:"http",method:"GET",path:u.healthPath,interval:"15s",timeout:"5s",grace_period:"10s"}]}],restart:{policy:"on-failure",max_retries:10},metadata:{[Lc]:"app","ts-cloud-release":u.release}}}async function IS(u,f,R=()=>{}){let A=!1;if(!await u.getApp(f.app))R(`Creating Fly app ${f.app} in ${f.org}`),await u.createApp(f.app,f.org),A=!0;let T;if(Object.keys(f.secrets).length>0)T=await u.setSecrets(f.app,f.secrets),R(`Set ${Object.keys(f.secrets).length} secret(s) (version ${T})`);let E=await u.listIpAssignments(f.app),P=new Set(E.map(Qc));if(!P.has("v6"))E.push(await u.assignIp(f.app,"v6")),R("Assigned a dedicated IPv6");if(!P.has("v4")&&!P.has("shared_v4"))E.push(await u.assignIp(f.app,"shared_v4")),R("Assigned a shared IPv4");let L=fg(f),z=(await u.listMachines(f.app)).filter((Me)=>{let ze=Me.config?.metadata??{};if(ze[Lc])return ze[Lc]==="app";return!ze.fly_process_group||ze.fly_process_group==="app"}),fe=f.volume?await u.listVolumes(f.app):[],me=[],At=[],Lt=new Set;for(let Me of f.regions){let ze=z.filter((j)=>j.region===Me).sort((j,yt)=>j.id.localeCompare(yt.id));for(let j=0;j<f.count;j++){let yt=ze[j];if(yt){Lt.add(yt.id),await Rg(u,f.app,yt,L,T),At.push(yt.id),R(`Updated ${yt.id} (${Me}) to ${f.image}`);continue}let G=f.volume?[{volume:(await Tg(u,f,Me,fe)).id,path:f.volume.path}]:void 0,ht=await u.createMachine(f.app,{region:Me,name:`${f.app}-${Me}-${j+1}`,config:{...L,...G?{mounts:G}:{}},...T!==void 0?{min_secrets_version:T}:{}});await u.waitForState(f.app,ht.id,"started",{instanceId:ht.instance_id}),me.push(ht.id),R(`Created ${ht.id} in ${Me}`)}}let mt=[];for(let Me of f.hostnames)mt.push(await u.requestCertificate(f.app,Me));return{app:f.app,url:`https://${f.app}.fly.dev`,createdApp:A,created:me,updated:At,untouched:z.filter((Me)=>!Lt.has(Me.id)).map((Me)=>Me.id),ips:E,certificates:mt}}async function Rg(u,f,R,A,T){let E=await u.acquireLease(f,R.id);try{let P=await u.updateMachine(f,R.id,{config:{...A,...R.config?.mounts?.length?{mounts:R.config.mounts}:{}},...T!==void 0?{min_secrets_version:T}:{}},E);await u.waitForState(f,R.id,"started",{instanceId:P.instance_id})}finally{await u.releaseLease(f,R.id,E)}}async function Tg(u,f,R,A){let T=A.find((P)=>P.region===R&&P.name===f.volume.name&&!P.attached_machine_id);if(T)return T.attached_machine_id="pending",T;let E=await u.createVolume(f.app,{name:f.volume.name,region:R,size_gb:f.volume.sizeGb});return A.push({...E,attached_machine_id:"pending"}),E}import{createHmac as Hl,createSign as Pg,timingSafeEqual as $g}from"node:crypto";function ro(u){let f=u instanceof Date?u.getTime():u;if(!Number.isFinite(f))throw TypeError("Media access timestamp must be finite");return Math.floor(f/1000)}function Vu(u){return Buffer.from(u).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function wg(u){return Buffer.from(u).toString("base64url")}function zu(u,f=!1){if(!u||/[\r\n]/.test(u))throw TypeError("Media resource is invalid");let R=f?u.replaceAll("*","wildcard"):u,A=new URL(R);if(!["http:","https:"].includes(A.protocol))throw TypeError("Media resource must use HTTP or HTTPS");if(!f&&u.includes("*"))throw TypeError("Canned policies cannot contain wildcards")}function Hu(u,f){let R=Pg("RSA-SHA1");return R.update(u),R.end(),Vu(R.sign(f))}function Uu(u){zu(u.resource,!0);let R={DateLessThan:{"AWS:EpochTime":ro(u.expiresAt)}};if(u.activeAt!==void 0)R.DateGreaterThan={"AWS:EpochTime":ro(u.activeAt)};if(u.ipAddress)R.IpAddress={"AWS:SourceIp":u.ipAddress};return JSON.stringify({Statement:[{Resource:u.resource,Condition:R}]})}function MS(u,f,R){zu(u);let A=ro(f),T=u.includes("?")?"&":"?",E=Uu({resource:u,expiresAt:f}),P=Hu(E,R.privateKey);return`${u}${T}Expires=${A}&Signature=${encodeURIComponent(P)}&Key-Pair-Id=${encodeURIComponent(R.keyPairId)}`}function BS(u,f){let R=Uu(u);return{"CloudFront-Key-Pair-Id":f.keyPairId,"CloudFront-Policy":Vu(Buffer.from(R)),"CloudFront-Signature":Hu(R,f.privateKey)}}function WS(u){if(!u.resource||/[\r\n]/.test(u.resource))throw TypeError("Media resource is invalid");let f=wg(Buffer.from(JSON.stringify({resource:u.resource,expiresAt:ro(u.expiresAt),...u.keyId?{keyId:u.keyId}:{},...u.audience?{audience:u.audience}:{}}))),R=Hl("sha256",u.secret).update(f).digest("base64url");return`${f}.${R}`}function VS(u,f){let[R,A,T]=u.split(".");if(!R||!A||T)return null;let E=Hl("sha256",f.secret).update(R).digest(),P;try{P=Buffer.from(A,"base64url")}catch{return null}if(E.length!==P.length||!$g(E,P))return null;try{let L=JSON.parse(Buffer.from(R,"base64url").toString("utf8")),z=ro(f.now??Date.now());if(!L.resource||!Number.isSafeInteger(L.expiresAt)||L.expiresAt<=z)return null;if(f.resource&&L.resource!==f.resource)return null;if(f.audience&&L.audience!==f.audience)return null;return L}catch{return null}}function zS(u,f=!1){let R=new URL(u,"https://media.invalid").pathname.toLowerCase(),A=/\.(?:m3u8|mpd|vtt|json)$/.test(R),T=/\.(?:key|license)$/.test(R)||R.includes("/keys/")||R.includes("/licenses/");return{"Accept-Ranges":"bytes","Cache-Control":f&&(A||T)?"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 HS(u){if(!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(u.bucket))throw TypeError("Media bucket is invalid");if(!/^[a-z0-9-]+$/.test(u.region))throw TypeError("Media bucket region is invalid");let f=u.prefix?`/${u.prefix.replace(/^\/+|\/+$/g,"")}`:"",R=u.protected??!1,A="public, max-age=31536000, immutable",T=R?"private, no-store":"public, max-age=5, s-maxage=30, stale-while-revalidate=30";return{originDomain:`${u.bucket}.s3.${u.region}.amazonaws.com`,originPath:f,domain:u.domain,trustedKeyGroupIds:[...new Set(u.trustedKeyGroupIds??[])],behaviors:[{pathPattern:"*.m3u8",cacheControl:T,compress:!0,signed:R},{pathPattern:"*.mpd",cacheControl:T,compress:!0,signed:R},{pathPattern:"*.vtt",cacheControl:T,compress:!0,signed:R},{pathPattern:"*",cacheControl:A,compress:!1,signed:R}],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 Dg{builder;config;environment;mergedConfig;serverEipLogicalIds=new Map;storageFailoverReplicas=[];constructor(u){this.config=u.config,this.environment=u.environment,this.builder=new Jd(`${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(u){if(u.environments&&!u.environments.includes(this.environment))return!1;if(u.requiresFeatures){let f=this.config.features||{};if(!u.requiresFeatures.every((A)=>f[A]===!0))return!1}if(u.regions){let f=this.config.environments[this.environment]?.region||this.config.project.region;if(!u.regions.includes(f))return!1}if(u.condition&&typeof u.condition==="function")return u.condition(this.config,this.environment);return!0}resolveApiOriginPort(){let u=this.mergedConfig.infrastructure?.api?.port??this.mergedConfig.ports?.api,f=Number(u||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(u,f){return u==="public"||f.routeCompute===!0}storageBucketName(u,f,R){return this.mergedConfig.infrastructure?.storage?.[R]?.bucket??`${u}-${f}-${R}`}fileSystemLogicalId(u,f,R){return t(r({slug:`${u}-${R}`,environment:f,resourceType:"efs"}))}resolveSftpStorage(u,f,R){let A=u.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,R,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,R,A.storageBucket)}}return}resolveComputeCachePathPatterns(u){if(u&&u.length>0)return u;return this.defaultComputeCachePathPatterns()}createComputeCacheBehavior(u,f){return{PathPattern:u,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(u,f,R,A,T,E){let P=this.serverEipLogicalIds.get("app"),L=this.serverEipLogicalIds.get("appInstance");if(!P)return;let z=`EC2-${A}-${T}-api`,fe=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",me=fe==="us-east-1"?".compute-1.amazonaws.com":`.${fe}.compute.amazonaws.com`,At={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:P}]}]},me]]},Lt=this.resolveApiOriginPort();if(u.push({Id:z,DomainName:At,CustomOriginConfig:{HTTPPort:Lt,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),R.push(P),L)R.push(L);for(let mt of E)f.push(this.createComputeCacheBehavior(mt,z))}buildCaddyfile(u){let f=u.filter(([,T])=>typeof T.domain==="string"&&T.domain&&typeof T.port==="number");if(f.length===0)return;let R=new Map;for(let[,T]of f){let E=R.get(T.domain)??[];E.push({port:T.port,path:T.path}),R.set(T.domain,E)}let A=[];for(let[T,E]of R){let L=[...E].sort((z,fe)=>{let me=!z.path||z.path==="/",At=!fe.path||fe.path==="/";if(me&&!At)return 1;if(!me&&At)return-1;return(fe.path?.length??0)-(z.path?.length??0)}).map((z)=>{let fe=!z.path||z.path==="/",me=`reverse_proxy localhost:${z.port}`;return fe?` handle {
|
|
2
|
+
${me}
|
|
3
|
+
}`:` handle ${z.path} {
|
|
4
|
+
${me}
|
|
5
|
+
}`});A.push(`${T} {
|
|
6
|
+
${L.join(`
|
|
7
7
|
`)}
|
|
8
8
|
}`)}return A.join(`
|
|
9
9
|
|
|
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:B}=y.createVpc({slug:l,environment:f,cidr:A,enableDnsHostnames:!0,enableDnsSupport:!0});this.builder.addResource("VPC",w);let v=`${l}${f}IGW`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(v,{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:v}}});let de=`${l}${f}PublicRT`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(de,{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:de},DestinationCidrBlock:"0.0.0.0/0",GatewayId:{Ref:v}},DependsOn:ce});let ct=this.mergedConfig.environments[f]?.region||this.mergedConfig.project.region||"us-east-1",xe=["a","b"];for(let Ut=0;Ut<2;Ut++){let Qt=`PublicSubnet${Ut+1}`;this.builder.addResource(Qt,{Type:"AWS::EC2::Subnet",Properties:{VpcId:{Ref:"VPC"},CidrBlock:`10.0.${Ut}.0/24`,AvailabilityZone:`${ct}${xe[Ut]}`,MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:`${l}-${f}-public-${xe[Ut]}`},{Key:"Environment",Value:f}]}}),this.builder.addResource(`${Qt}RTAssoc`,{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:{Ref:Qt},RouteTableId:{Ref:de}}})}}generateContainerInfrastructure(l,f){let C=this.mergedConfig.infrastructure?.containers;if(!C)return;let A=this.mergedConfig.infrastructure?.loadBalancer,w=this.mergedConfig.infrastructure?.ssl,B=this.mergedConfig.infrastructure?.dns,v;if(w?.enabled&&w.domains?.length)if(w.certificateArn);else{let xe=w.domains[0],Ut=w.domains.slice(1).map((lt)=>{if(lt.includes(".")&<.endsWith(xe))return lt.replace(`.${xe}`,"");return lt}),{certificate:Qt,logicalId:gt}=b.createCertificate({domain:xe,subdomains:Ut,slug:l,environment:f,validationMethod:"DNS",hostedZoneId:B?.hostedZoneId});v=gt,this.builder.addResource(gt,Qt)}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 de=`${l}${f}ALBSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(de,{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 ct=`${l}${f}ECSSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");for(let[xe,Ut]of Object.entries(C)){let Qt=Ut.port||3000;this.builder.addResource(ct,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ECS tasks security group for ${l}-${f}`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:Qt,ToPort:Qt,SourceSecurityGroupId:{Ref:de},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 gt=`${l}${f}TaskExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(gt,{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 lt=`${l}${f}TaskRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(lt,{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 ut=`${l}${f}${xe}LogGroup`.replace(/[^a-zA-Z0-9]/g,""),Ee=`/ecs/${l}-${f}-${xe}`;this.builder.addResource(ut,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:Ee,RetentionInDays:30}});let Ft=`${l}${f}${xe}TaskDef`.replace(/[^a-zA-Z0-9]/g,""),ve=String(Ut.cpu||512),Pt=String(Ut.memory||1024);this.builder.addResource(Ft,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${l}-${f}-${xe}`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:ve,Memory:Pt,ExecutionRoleArn:{"Fn::GetAtt":[gt,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[lt,"Arn"]},ContainerDefinitions:[{Name:xe,Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${l}:latest`},Essential:!0,PortMappings:[{ContainerPort:Qt,Protocol:"tcp"}],LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":Ee,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":xe}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${Qt}${Ut.healthCheck||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${l}-${f}-${xe}`},{Key:"Environment",Value:f}]},DependsOn:[gt,lt,ut]});let Ht=`${l}${f}ALB`.replace(/[^a-zA-Z0-9]/g,"");if(A?.enabled!==!1){this.builder.addResource(Ht,{Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:`${l}-${f}-alb`,Scheme:"internet-facing",Type:"application",Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],SecurityGroups:[{Ref:de}],Tags:[{Key:"Name",Value:`${l}-${f}-alb`},{Key:"Environment",Value:f}]}});let lr=`${l}${f}TargetGroup`.replace(/[^a-zA-Z0-9]/g,""),Cr=A?.healthCheck?.path||Ut.healthCheck||"/health";this.builder.addResource(lr,{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:`${l}-${f}-tg`,Port:Qt,Protocol:"HTTP",VpcId:{Ref:"VPC"},TargetType:"ip",HealthCheckPath:Cr,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 br=`${l}${f}HTTPListener`.replace(/[^a-zA-Z0-9]/g,"");if(w?.enabled&&w?.redirectHttp)this.builder.addResource(br,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Ht},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"redirect",RedirectConfig:{Protocol:"HTTPS",Port:"443",StatusCode:"HTTP_301"}}]}});else this.builder.addResource(br,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Ht},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:lr}}]}});if(w?.enabled){let Ir=w.certificateArn||(v?{Ref:v}: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:Ht},Port:443,Protocol:"HTTPS",Certificates:[{CertificateArn:Ir}],DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:lr}}],SslPolicy:"ELBSecurityPolicy-TLS13-1-2-2021-06"}})}}let wr=`${l}${f}${xe}Service`.replace(/[^a-zA-Z0-9]/g,""),kr=Ut.desiredCount||1;this.builder.addResource(wr,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${f}-${xe}`,Cluster:{Ref:ce},TaskDefinition:{Ref:Ft},DesiredCount:kr,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:ct}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},LoadBalancers:[{ContainerName:xe,ContainerPort:Qt,TargetGroupArn:{Ref:lr}}],HealthCheckGracePeriodSeconds:120,Tags:[{Key:"Name",Value:`${l}-${f}-${xe}`},{Key:"Environment",Value:f}]},DependsOn:[Ft,br,lr]});let xr=Ut.autoScaling;if(xr){let Ir=`${l}${f}${xe}ScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(Ir,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:xr.max||10,MinCapacity:xr.min||1,ResourceId:{"Fn::Sub":`service/\${${ce}}/${l}-${f}-${xe}`},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:wr}),xr.targetCpuUtilization)this.builder.addResource(`${l}${f}${xe}CPUScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${f}-${xe}-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Ir},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:xr.targetCpuUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}});if(xr.targetMemoryUtilization)this.builder.addResource(`${l}${f}${xe}MemoryScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${f}-${xe}-memory-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Ir},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageMemoryUtilization"},TargetValue:xr.targetMemoryUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(B?.domain&&B?.hostedZoneId)this.builder.addResource(`${l}${f}ApiDnsRecord`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:B.hostedZoneId,Name:`api.${B.domain}`,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[Ht,"DNSName"]},HostedZoneId:{"Fn::GetAtt":[Ht,"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}-${xe}`,Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-service-name"}}}),this.builder.addOutput("LoadBalancerDNS",{Description:"Application Load Balancer DNS Name",Value:{"Fn::GetAtt":[Ht,"DNSName"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-alb-dns"}}})}else{let lr=`${l}${f}${xe}Service`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(lr,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${f}-${xe}`,Cluster:{Ref:ce},TaskDefinition:{Ref:Ft},DesiredCount:Ut.desiredCount||1,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:ct}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},Tags:[{Key:"Name",Value:`${l}-${f}-${xe}`},{Key:"Environment",Value:f}]},DependsOn:[Ft]})}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:B}=ne.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(B,w);let{lambdaFunction:v,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:B,timeout:A.timeout,memorySize:A.memorySize});this.builder.addResource(ce,v)}if(this.mergedConfig.infrastructure?.api){let{restApi:C,logicalId:A}=Kd.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((v)=>!v.privateNetwork||v.privateNetwork==="create"))this.generateNetworkInfrastructure(l,f);for(let[v,ce]of Object.entries(C)){let de=ce.instanceType||ce.size||A?.size,xe=(de?a.InstanceSize.specs[de]:void 0)?.instanceType||de||"t3.micro",Ut=ce.type||"app",Qt=ce.userData||ce.startupScript;if(!Qt)Qt=a.UserData.generateAppServerScript({runtime:"bun",runtimeVersion:ce.bunVersion||"latest",webServer:"none",domain:ce.domain,enableSsl:!!w?.enabled,sslEmail:w?.letsEncrypt?.email,installRedis:Ut==="cache",installDatabaseClients:!!ce.database});let gt=ce.privateNetwork&&ce.privateNetwork!=="create"?ce.privateNetwork:{Ref:"VPC"},lt=ce.subnet||{Ref:"PublicSubnet1"},Ee=!!this.mergedConfig.infrastructure?.email?.server?.enabled,Ft=[22,80,443,this.resolveApiOriginPort()];if(Ee)Ft.push(25,465,587,143,993);let ve=a.createServerModeStack({slug:`${l}-${v}`,environment:f,vpcId:gt,subnetId:lt,instanceType:xe,keyName:ce.keyName||`${l}-${f}`,domain:ce.domain,userData:Qt,volumeSize:ce.diskSize||20,imageId:ce.image,allowedPorts:Ft});for(let[Pt,Ht]of Object.entries(ve.resources))this.builder.addResource(Pt,Ht);this.serverEipLogicalIds.set(v,ve.outputs.eipLogicalId),this.serverEipLogicalIds.set(`${v}Instance`,ve.outputs.instanceLogicalId),this.builder.addOutput(`${v}InstanceId`,{Value:{Ref:ve.outputs.instanceLogicalId},Description:`Instance ID for ${v} server`}),this.builder.addOutput(`${v}PublicIp`,{Value:{Ref:ve.outputs.eipLogicalId},Description:`Public IP for ${v} server`})}}generateComputeApp(l,f){let C=this.mergedConfig.infrastructure?.compute;if(!C)return;let A=this.mergedConfig.sites||{},w=Object.entries(A),v=this.mergedConfig.infrastructure?.dns?.domain,ce=this.mergedConfig.infrastructure?.database,de=C.size,xe=(de?a.InstanceSize.specs[de]:void 0)?.instanceType||de||"t3.micro";if(!this.builder.hasResource("VPC"))this.generateNetworkInfrastructure(l,f);let Ut=this.buildCaddyfile(w),Qt=a.UserData.generateBunAppScript({runtime:C.runtime||"bun",runtimeVersion:C.runtimeVersion||"latest",systemPackages:C.systemPackages,database:ce,caddyfile:Ut}),gt=Hs(C.appUpdates),lt=gt.length>0?`${Qt}
|
|
11
|
-
${
|
|
10
|
+
`)}normalizeMountPath(u){let f=u?.mountPath||u?.path;if(!f||f==="/")return;let R=`/${f}`.replace(/\/+/g,"/").replace(/\/$/,"");return R==="/"?void 0:R}storageBucketLogicalId(u,f,R){return`${u}-${f}-s3-${R}`.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((A)=>A.charAt(0).toUpperCase()+A.slice(1)).join("")}pathMountRewriteFunctionCode(u,f="directory"){return`function handler(event) { var request = event.request; var prefix = ${JSON.stringify(u)}; 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 u=this.mergedConfig.project.slug,f=this.environment,R=!!(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),T=!!this.mergedConfig.infrastructure?.compute;if(!!((this.mergedConfig.mode||"server")==="serverless"&&this.mergedConfig.infrastructure?.containers&&Object.keys(this.mergedConfig.infrastructure.containers).length>0))this.generateNetworkInfrastructure(u,f),this.generateContainerInfrastructure(u,f);if(R)this.generateServerless(u,f);if(A)this.generateServer(u,f);if(T)this.generateComputeApp(u,f);if(this.mergedConfig.infrastructure?.jumpBox)this.generateJumpBox(u,f);if(this.storageFailoverReplicas=[],this.generateSharedInfrastructure(u,f),this.storageFailoverReplicas.length>0)this.builder.addMetadata(el,this.storageFailoverReplicas);if(this.config.tags)this.applyGlobalTags(this.config.tags);return this}getStorageFailoverReplicas(){return[...this.storageFailoverReplicas]}applyGlobalTags(u){}generateNetworkInfrastructure(u,f){if(this.builder.hasResource("VPC"))return;let A=this.mergedConfig.infrastructure?.network?.cidr||"10.0.0.0/16",{vpc:T,logicalId:E}=y.createVpc({slug:u,environment:f,cidr:A,enableDnsHostnames:!0,enableDnsSupport:!0});this.builder.addResource("VPC",T);let P=`${u}${f}IGW`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(P,{Type:"AWS::EC2::InternetGateway",Properties:{Tags:[{Key:"Name",Value:`${u}-${f}-igw`},{Key:"Environment",Value:f}]}});let L=`${u}${f}IGWAttach`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(L,{Type:"AWS::EC2::VPCGatewayAttachment",Properties:{VpcId:{Ref:"VPC"},InternetGatewayId:{Ref:P}}});let z=`${u}${f}PublicRT`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(z,{Type:"AWS::EC2::RouteTable",Properties:{VpcId:{Ref:"VPC"},Tags:[{Key:"Name",Value:`${u}-${f}-public-rt`},{Key:"Environment",Value:f}]}}),this.builder.addResource(`${u}${f}PublicRoute`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::EC2::Route",Properties:{RouteTableId:{Ref:z},DestinationCidrBlock:"0.0.0.0/0",GatewayId:{Ref:P}},DependsOn:L});let fe=this.mergedConfig.environments[f]?.region||this.mergedConfig.project.region||"us-east-1",me=["a","b"];for(let At=0;At<2;At++){let Lt=`PublicSubnet${At+1}`;this.builder.addResource(Lt,{Type:"AWS::EC2::Subnet",Properties:{VpcId:{Ref:"VPC"},CidrBlock:`10.0.${At}.0/24`,AvailabilityZone:`${fe}${me[At]}`,MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:`${u}-${f}-public-${me[At]}`},{Key:"Environment",Value:f}]}}),this.builder.addResource(`${Lt}RTAssoc`,{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:{Ref:Lt},RouteTableId:{Ref:z}}})}}generateContainerInfrastructure(u,f){let R=this.mergedConfig.infrastructure?.containers;if(!R)return;let A=this.mergedConfig.infrastructure?.loadBalancer,T=this.mergedConfig.infrastructure?.ssl,E=this.mergedConfig.infrastructure?.dns,P;if(T?.enabled&&T.domains?.length)if(T.certificateArn);else{let me=T.domains[0],At=T.domains.slice(1).map((Me)=>{if(Me.includes(".")&&Me.endsWith(me))return Me.replace(`.${me}`,"");return Me}),{certificate:Lt,logicalId:mt}=C.createCertificate({domain:me,subdomains:At,slug:u,environment:f,validationMethod:"DNS",hostedZoneId:E?.hostedZoneId});P=mt,this.builder.addResource(mt,Lt)}let L="ECSCluster";this.builder.addResource(L,{Type:"AWS::ECS::Cluster",Properties:{ClusterName:`${u}-${f}`,ClusterSettings:[{Name:"containerInsights",Value:"enabled"}],Tags:[{Key:"Name",Value:`${u}-${f}`},{Key:"Environment",Value:f}]}});let z=`${u}${f}ALBSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(z,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ALB security group for ${u}-${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:`${u}-${f}-alb-sg`},{Key:"Environment",Value:f}]}});let fe=`${u}${f}ECSSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");for(let[me,At]of Object.entries(R)){let Lt=At.port||3000;this.builder.addResource(fe,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ECS tasks security group for ${u}-${f}`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:Lt,ToPort:Lt,SourceSecurityGroupId:{Ref:z},Description:"Allow traffic from ALB"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${u}-${f}-ecs-sg`},{Key:"Environment",Value:f}]}});let mt=`${u}${f}TaskExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(mt,{Type:"AWS::IAM::Role",Properties:{RoleName:`${u}-${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 Me=`${u}${f}TaskRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Me,{Type:"AWS::IAM::Role",Properties:{RoleName:`${u}-${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 ze=`${u}${f}${me}LogGroup`.replace(/[^a-zA-Z0-9]/g,""),j=`/ecs/${u}-${f}-${me}`;this.builder.addResource(ze,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:j,RetentionInDays:30}});let yt=`${u}${f}${me}TaskDef`.replace(/[^a-zA-Z0-9]/g,""),G=String(At.cpu||512),ht=String(At.memory||1024);this.builder.addResource(yt,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${u}-${f}-${me}`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:G,Memory:ht,ExecutionRoleArn:{"Fn::GetAtt":[mt,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[Me,"Arn"]},ContainerDefinitions:[{Name:me,Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${u}:latest`},Essential:!0,PortMappings:[{ContainerPort:Lt,Protocol:"tcp"}],LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":j,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":me}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${Lt}${At.healthCheck||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${u}-${f}-${me}`},{Key:"Environment",Value:f}]},DependsOn:[mt,Me,ze]});let St=`${u}${f}ALB`.replace(/[^a-zA-Z0-9]/g,"");if(A?.enabled!==!1){this.builder.addResource(St,{Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:`${u}-${f}-alb`,Scheme:"internet-facing",Type:"application",Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],SecurityGroups:[{Ref:z}],Tags:[{Key:"Name",Value:`${u}-${f}-alb`},{Key:"Environment",Value:f}]}});let Wt=`${u}${f}TargetGroup`.replace(/[^a-zA-Z0-9]/g,""),zt=A?.healthCheck?.path||At.healthCheck||"/health";this.builder.addResource(Wt,{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:`${u}-${f}-tg`,Port:Lt,Protocol:"HTTP",VpcId:{Ref:"VPC"},TargetType:"ip",HealthCheckPath:zt,HealthCheckIntervalSeconds:A?.healthCheck?.interval||30,HealthyThresholdCount:A?.healthCheck?.healthyThreshold||2,UnhealthyThresholdCount:A?.healthCheck?.unhealthyThreshold||5,HealthCheckTimeoutSeconds:10,Tags:[{Key:"Name",Value:`${u}-${f}-tg`},{Key:"Environment",Value:f}]}});let jt=`${u}${f}HTTPListener`.replace(/[^a-zA-Z0-9]/g,"");if(T?.enabled&&T?.redirectHttp)this.builder.addResource(jt,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:St},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"redirect",RedirectConfig:{Protocol:"HTTPS",Port:"443",StatusCode:"HTTP_301"}}]}});else this.builder.addResource(jt,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:St},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:Wt}}]}});if(T?.enabled){let Xt=T.certificateArn||(P?{Ref:P}:void 0);if(Xt){let Pr=`${u}${f}HTTPSListener`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Pr,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:St},Port:443,Protocol:"HTTPS",Certificates:[{CertificateArn:Xt}],DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:Wt}}],SslPolicy:"ELBSecurityPolicy-TLS13-1-2-2021-06"}})}}let Kt=`${u}${f}${me}Service`.replace(/[^a-zA-Z0-9]/g,""),Sr=At.desiredCount||1;this.builder.addResource(Kt,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${u}-${f}-${me}`,Cluster:{Ref:L},TaskDefinition:{Ref:yt},DesiredCount:Sr,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:fe}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},LoadBalancers:[{ContainerName:me,ContainerPort:Lt,TargetGroupArn:{Ref:Wt}}],HealthCheckGracePeriodSeconds:120,Tags:[{Key:"Name",Value:`${u}-${f}-${me}`},{Key:"Environment",Value:f}]},DependsOn:[yt,jt,Wt]});let Or=At.autoScaling;if(Or){let Xt=`${u}${f}${me}ScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(Xt,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:Or.max||10,MinCapacity:Or.min||1,ResourceId:{"Fn::Sub":`service/\${${L}}/${u}-${f}-${me}`},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:Kt}),Or.targetCpuUtilization)this.builder.addResource(`${u}${f}${me}CPUScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${u}-${f}-${me}-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Xt},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:Or.targetCpuUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}});if(Or.targetMemoryUtilization)this.builder.addResource(`${u}${f}${me}MemoryScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${u}-${f}-${me}-memory-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Xt},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageMemoryUtilization"},TargetValue:Or.targetMemoryUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(E?.domain&&E?.hostedZoneId)this.builder.addResource(`${u}${f}ApiDnsRecord`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:E.hostedZoneId,Name:`api.${E.domain}`,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[St,"DNSName"]},HostedZoneId:{"Fn::GetAtt":[St,"CanonicalHostedZoneID"]}}}});this.builder.addOutput("ECSClusterArn",{Description:"ECS Cluster ARN",Value:{"Fn::GetAtt":[L,"Arn"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-cluster-arn"}}}),this.builder.addOutput("ECSServiceName",{Description:"ECS Service Name",Value:`${u}-${f}-${me}`,Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-service-name"}}}),this.builder.addOutput("LoadBalancerDNS",{Description:"Application Load Balancer DNS Name",Value:{"Fn::GetAtt":[St,"DNSName"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-alb-dns"}}})}else{let Wt=`${u}${f}${me}Service`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Wt,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${u}-${f}-${me}`,Cluster:{Ref:L},TaskDefinition:{Ref:yt},DesiredCount:At.desiredCount||1,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:fe}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},Tags:[{Key:"Name",Value:`${u}-${f}-${me}`},{Key:"Environment",Value:f}]},DependsOn:[yt]})}break}}generateServerless(u,f){if(this.mergedConfig.infrastructure?.functions)for(let[R,A]of Object.entries(this.mergedConfig.infrastructure.functions)){if(!this.shouldDeploy(A))continue;let{role:T,logicalId:E}=de.createRole({slug:u,environment:f,roleName:`${u}-${f}-${R}-role`,servicePrincipal:"lambda.amazonaws.com",managedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]});this.builder.addResource(E,T);let{lambdaFunction:P,logicalId:L}=a.createLambdaFunction({slug:u,environment:f,functionName:`${u}-${f}-${R}`,handler:A.handler||"index.handler",runtime:A.runtime||"nodejs20.x",code:{zipFile:A.code||"export const handler = async () => ({ statusCode: 200 });"},role:E,timeout:A.timeout,memorySize:A.memorySize});this.builder.addResource(L,P)}if(this.mergedConfig.infrastructure?.api){let{restApi:R,logicalId:A}=nl.createRestApi({slug:u,environment:f,apiName:`${u}-${f}-api`});this.builder.addResource(A,R)}}generateServer(u,f){if(!this.mergedConfig.infrastructure?.servers)return;let R=this.mergedConfig.infrastructure.servers,A=this.mergedConfig.infrastructure?.compute,T=this.mergedConfig.infrastructure?.ssl;if(Object.values(R).some((P)=>!P.privateNetwork||P.privateNetwork==="create"))this.generateNetworkInfrastructure(u,f);for(let[P,L]of Object.entries(R)){let z=L.instanceType||L.size||A?.size,me=(z?a.InstanceSize.specs[z]:void 0)?.instanceType||z||"t3.micro",At=L.type||"app",Lt=L.userData||L.startupScript;if(!Lt)Lt=a.UserData.generateAppServerScript({runtime:"bun",runtimeVersion:L.bunVersion||"latest",webServer:"none",domain:L.domain,enableSsl:!!T?.enabled,sslEmail:T?.letsEncrypt?.email,installRedis:At==="cache",installDatabaseClients:!!L.database});let mt=L.privateNetwork&&L.privateNetwork!=="create"?L.privateNetwork:{Ref:"VPC"},Me=L.subnet||{Ref:"PublicSubnet1"},j=!!this.mergedConfig.infrastructure?.email?.server?.enabled,yt=[22,80,443,this.resolveApiOriginPort()];if(j)yt.push(25,465,587,143,993);let G=a.createServerModeStack({slug:`${u}-${P}`,environment:f,vpcId:mt,subnetId:Me,instanceType:me,keyName:L.keyName||`${u}-${f}`,domain:L.domain,userData:Lt,volumeSize:L.diskSize||20,imageId:L.image,allowedPorts:yt});for(let[ht,St]of Object.entries(G.resources))this.builder.addResource(ht,St);this.serverEipLogicalIds.set(P,G.outputs.eipLogicalId),this.serverEipLogicalIds.set(`${P}Instance`,G.outputs.instanceLogicalId),this.builder.addOutput(`${P}InstanceId`,{Value:{Ref:G.outputs.instanceLogicalId},Description:`Instance ID for ${P} server`}),this.builder.addOutput(`${P}PublicIp`,{Value:{Ref:G.outputs.eipLogicalId},Description:`Public IP for ${P} server`})}}generateComputeApp(u,f){let R=this.mergedConfig.infrastructure?.compute;if(!R)return;let A=this.mergedConfig.sites||{},T=Object.entries(A),P=this.mergedConfig.infrastructure?.dns?.domain,L=this.mergedConfig.infrastructure?.database,z=R.size,me=(z?a.InstanceSize.specs[z]:void 0)?.instanceType||z||"t3.micro";if(!this.builder.hasResource("VPC"))this.generateNetworkInfrastructure(u,f);let At=this.buildCaddyfile(T),Lt=a.UserData.generateBunAppScript({runtime:R.runtime||"bun",runtimeVersion:R.runtimeVersion||"latest",systemPackages:R.systemPackages,database:L,caddyfile:At}),mt=js(R.appUpdates),Me=mt.length>0?`${Lt}
|
|
11
|
+
${mt.join(`
|
|
12
12
|
`)}
|
|
13
|
-
`:
|
|
14
|
-
else if (!uri.includes('.')) { request.uri += '.html'; } return request; }`}});let Rs=[{Id:ri,DomainName:{"Fn::Sub":`\${${br}}.s3.${$c}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:Ee}}],qs=[],Dc=[];if(this.shouldRouteStorageBucketToCompute(ve,Pt)){this.appendComputeAppOrigin(Rs,qs,Dc,l,f,this.resolveComputeCachePathPatterns(Pt.computeRoutes));for(let Or of Ft){let xa=`S3-${l}-${f}-${Or.name}`,vc=`${l}${f}${Or.name}PathMountRewrite`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(vc,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${f}-${Or.name}-path-mount-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`Path mount rewrite for ${l} ${f} ${Or.name} at ${Or.mountPath}`,Runtime:"cloudfront-js-2.0"},FunctionCode:this.pathMountRewriteFunctionCode(Or.mountPath,Or.rewriteStyle)}}),Rs.push({Id:xa,DomainName:{"Fn::Sub":`\${${Or.logicalId}}.s3.${$c}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:Ee}}),Dc.push(Or.logicalId,vc);for(let Dg of[Or.mountPath,`${Or.mountPath}/*`])qs.push({PathPattern:Dg,TargetOriginId:xa,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":[vc,"FunctionARN"]}}]})}}let Qs,ku=ri;if(kr){let Or=`${ri}-failover`;Object.assign(Rs[0],kr.primaryConnection),Rs.push({Id:Or,DomainName:em(kr.replicaBucket,kr.replicaRegion),OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:Ee}}),Qs=Xr({primaryOriginId:ri,secondaryOriginId:Or,statusCodes:kr.statusCodes}),ku=Qs.Items[0].Id}let kc={Type:"AWS::CloudFront::Distribution",DependsOn:[br,Ee,...li?[li]:[],...Dc],Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${f} ${ve} site`,DefaultRootObject:"index.html",Origins:Rs,...Qs?{OriginGroups:Qs}:{},DefaultCacheBehavior:{TargetOriginId:ku,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...li?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[li,"FunctionARN"]}}]}:{}},...qs.length>0?{CacheBehaviors:qs}:{},...Er.length>0?{Aliases:Er}:{},ViewerCertificate:Wn,PriceClass:"PriceClass_100",HttpVersion:"http2and3",IPV6Enabled:!0,CustomErrorResponses:_r}}};if(ce)kc.DependsOn.push(ce);if(kr)St(kc.Properties.DistributionConfig,`infrastructure.storage.${ve}`),this.storageFailoverReplicas.push({name:ve,primaryBucket:lr,primaryRegion:$c,replicaBucket:kr.replicaBucket,replicaRegion:kr.replicaRegion,replicate:kr.replicate,distributionArnOutput:`${ve}CloudFrontDistributionArn`}),this.builder.addOutput(`${ve}CloudFrontDistributionArn`,{Value:{"Fn::Sub":`arn:\${AWS::Partition}:cloudfront::\${AWS::AccountId}:distribution/\${${Ir}}`},Description:`CloudFront distribution ARN for ${ve} (scopes the bucket policy of the failover replica)`}),this.builder.addOutput(`${ve}FailoverBucketName`,{Value:kr.replicaBucket,Description:`Failover replica bucket for ${ve} (${kr.replicaRegion}), outside this stack`});this.builder.addResource(Ir,kc);let Ig=`${br}CloudFrontPolicy`;if(this.builder.addResource(Ig,{Type:"AWS::S3::BucketPolicy",DependsOn:[br,Ir],Properties:{Bucket:{Ref:br},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":`arn:aws:s3:::\${${br}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${Ir}}`}}}}]}}}),this.shouldRouteStorageBucketToCompute(ve,Pt))for(let Or of Ft){let xa=`${Or.logicalId}CloudFrontPolicy`;this.builder.addResource(xa,{Type:"AWS::S3::BucketPolicy",DependsOn:[Or.logicalId,Ir],Properties:{Bucket:{Ref:Or.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:::\${${Or.logicalId}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${Ir}}`}}}}]}}})}if(Er.length>0)v.push({name:ve,bucketLogicalId:br,distLogicalId:Ir,oacLogicalId:Ee,aliases:Er});this.builder.addOutput(`${ve}CloudFrontDomain`,{Value:{"Fn::GetAtt":[Ir,"DomainName"]},Description:`CloudFront domain for ${ve}`}),this.builder.addOutput(`${ve}CloudFrontDistributionId`,{Value:{Ref:Ir},Description:`CloudFront distribution ID for ${ve}`})}if(this.builder.addOutput(`${ve}BucketName`,{Value:{Ref:br},Description:`S3 bucket name for ${ve}`}),ve==="public")this.builder.addOutput("FrontendBucketName",{Value:{Ref:br},Description:"Frontend S3 bucket name"});if(ve==="docs")this.builder.addOutput("DocsBucketName",{Value:{Ref:br},Description:"Documentation S3 bucket name"});if(ve==="blog")this.builder.addOutput("BlogBucketName",{Value:{Ref:br},Description:"Blog S3 bucket name"})}}if(this.mergedConfig.infrastructure?.sftp){let ut=this.mergedConfig.infrastructure.sftp,Ee=zd.create({...ut,storage:this.resolveSftpStorage(ut,l,f)??ut.storage,slug:l,environment:f});for(let[Ft,ve]of Object.entries(Ee.resources))this.builder.addResource(Ft,ve);this.builder.addOutput("SftpServerId",{Value:{Ref:Ee.serverLogicalId},Description:"AWS Transfer Family SFTP server ID"}),this.builder.addOutput("SftpEndpoint",{Value:{"Fn::Sub":`\${${Ee.serverLogicalId}}.server.transfer.\${AWS::Region}.amazonaws.com`},Description:"AWS Transfer Family SFTP endpoint"}),this.builder.addOutput("SftpStorageDomain",{Value:Ee.domain,Description:"Storage backing the SFTP server (EFS or S3)"})}if(B&&v.length>0)for(let{name:ut,distLogicalId:Ee,aliases:Ft}of v)for(let ve of Ft){let Pt=ve.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Pt}ARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[Ee],Properties:{HostedZoneId:B,Name:ve,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[Ee,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}}),this.builder.addResource(`${Pt}AAAARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[Ee],Properties:{HostedZoneId:B,Name:ve,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":[Ee,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}})}if(this.mergedConfig.infrastructure?.databases){for(let[ut,Ee]of Object.entries(this.mergedConfig.infrastructure.databases))if(Ee.engine==="dynamodb"){let{table:Ft,logicalId:ve}=Yt.createTable({slug:l,environment:f,tableName:`${l}-${f}-${ut}`,partitionKey:Ee.partitionKey||{name:"id",type:"S"},sortKey:Ee.sortKey});this.builder.addResource(ve,Ft)}else if(Ee.engine==="postgres"){let{dbInstance:Ft,logicalId:ve}=Yt.createPostgres({slug:l,environment:f,dbInstanceIdentifier:`${l}-${f}-${ut}`,masterUsername:Ee.username||"admin",masterUserPassword:Ee.password||"changeme123",allocatedStorage:Ee.storage||20,dbInstanceClass:Ee.instanceClass||"db.t3.micro"});this.builder.addResource(ve,Ft)}else if(Ee.engine==="mysql"){let{dbInstance:Ft,logicalId:ve}=Yt.createMysql({slug:l,environment:f,dbInstanceIdentifier:`${l}-${f}-${ut}`,masterUsername:Ee.username||"admin",masterUserPassword:Ee.password||"changeme123",allocatedStorage:Ee.storage||20,dbInstanceClass:Ee.instanceClass||"db.t3.micro"});this.builder.addResource(ve,Ft)}}if(this.mergedConfig.infrastructure?.cdn)for(let[ut,Ee]of Object.entries(this.mergedConfig.infrastructure.cdn)){if(!Ee.origin)continue;let Ft=typeof Ee.customDomain==="string"?Ee.customDomain:Ee.customDomain?.domain||Ee.domain,ve=typeof Ee.customDomain==="object"?Ee.customDomain?.certificateArn:Ee.certificateArn,Pt=ve||de,Ht=`${l}${f}${ut}CDN`.replace(/[^a-zA-Z0-9]/g,""),lr=`S3-${l}-${f}-${ut}-cdn`,Cr=[{Id:lr,DomainName:Ee.origin,OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginShield:Ee.originShield?{Enabled:!0,OriginShieldRegion:Ee.originShieldRegion||this.mergedConfig.environments[f]?.region||this.mergedConfig.project.region||"us-east-1"}:{Enabled:!1},...re(Ee,`infrastructure.cdn.${ut}`)}],br=[],wr=[],kr=["GET","HEAD","OPTIONS"],xr=lr,Ir;if(Ee.failoverOrigin){yt(kr,`the default cache behavior of infrastructure.cdn.${ut}`);let bn=`${lr}-failover`,_r=typeof Ee.failoverOrigin==="string"?{domain:Ee.failoverOrigin}:Ee.failoverOrigin;if(!_r.domain)throw Error(`infrastructure.cdn.${ut}.failoverOrigin.domain is required`);if(_r.domain===Ee.origin)throw Error(`infrastructure.cdn.${ut}: failoverOrigin must differ from origin (both are ${Ee.origin})`);Cr.push({Id:bn,DomainName:_r.domain,OriginPath:_r.originPath||"",...To(_r.domain)?{S3OriginConfig:{OriginAccessIdentity:""}}:{CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"}},OriginShield:{Enabled:!1},...re(_r,`infrastructure.cdn.${ut}.failoverOrigin`)}),Ir=Xr({primaryOriginId:lr,secondaryOriginId:bn,statusCodes:Ee.failoverStatusCodes}),xr=Ir.Items[0].Id}else if(Ee.failoverStatusCodes)throw Error(`infrastructure.cdn.${ut}: failoverStatusCodes needs failoverOrigin to fail over to`);if(Ee.routeCompute)this.appendComputeAppOrigin(Cr,br,wr,l,f,this.resolveComputeCachePathPatterns(Ee.computeRoutes));let Er=Pt&&Ft?{AcmCertificateArn:ce&&!ve?{Ref:ce}:Pt,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},sn=[...wr];if(ce&&!ve&&Ft)sn.push(ce);let Fn={Type:"AWS::CloudFront::Distribution",...sn.length>0?{DependsOn:sn}:{},Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${f} ${ut} CDN`,DefaultRootObject:"index.html",Origins:Cr,...Ir?{OriginGroups:Ir}:{},DefaultCacheBehavior:{TargetOriginId:xr,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:kr,CachedMethods:["GET","HEAD","OPTIONS"],Compress:Ee.compress!==!1,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},...br.length>0?{CacheBehaviors:br}:{},...Ft&&Pt?{Aliases:[Ft]}:{},ViewerCertificate:Er,PriceClass:"PriceClass_100",HttpVersion:Ee.http3?"http2and3":"http2"}}};if(St(Fn.Properties.DistributionConfig,`infrastructure.cdn.${ut}`),this.builder.addResource(Ht,Fn),B&&Ft&&Pt){let bn=Ft.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${bn}CdnARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[Ht,...ce&&!ve?[ce]:[]],Properties:{HostedZoneId:B,Name:Ft,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:{"Fn::GetAtt":[Ht,"DomainName"]}}}})}}if(this.mergedConfig.infrastructure?.queues)for(let[ut,Ee]of Object.entries(this.mergedConfig.infrastructure.queues)){if(!this.shouldDeploy(Ee))continue;let{queue:Ft,logicalId:ve}=G.createQueue({slug:l,environment:f,name:`${l}-${f}-${ut}`,fifo:Ee.fifo,visibilityTimeout:Ee.visibilityTimeout,messageRetentionPeriod:Ee.messageRetentionPeriod,delaySeconds:Ee.delaySeconds,maxMessageSize:Ee.maxMessageSize,receiveMessageWaitTime:Ee.receiveMessageWaitTime,contentBasedDeduplication:Ee.contentBasedDeduplication,encrypted:Ee.encrypted,kmsKeyId:Ee.kmsKeyId});this.builder.addResource(ve,Ft);let Pt;if(Ee.deadLetterQueue){let{deadLetterQueue:Ht,updatedSourceQueue:lr,deadLetterLogicalId:Cr}=G.createDeadLetterQueue(ve,{slug:l,environment:f,maxReceiveCount:Ee.maxReceiveCount});Pt=Cr,this.builder.addResource(Cr,Ht);let wr=this.builder.getResources()[ve];if(wr?.Properties)wr.Properties.RedrivePolicy=lr.Properties?.RedrivePolicy}if(Ee.trigger){let Ht=Ee.trigger,lr=`${l}${f}${Ht.functionName}`.replace(/[^a-zA-Z0-9]/g,""),Cr={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:{"Fn::GetAtt":[ve,"Arn"]},FunctionName:{Ref:lr},BatchSize:Ht.batchSize||10,MaximumBatchingWindowInSeconds:Ht.batchWindow||0,Enabled:!0,...Ht.reportBatchItemFailures!==!1&&{FunctionResponseTypes:["ReportBatchItemFailures"]},...Ht.maxConcurrency&&{ScalingConfig:{MaximumConcurrency:Ht.maxConcurrency}},...Ht.filterPattern&&{FilterCriteria:{Filters:[{Pattern:JSON.stringify(Ht.filterPattern)}]}}},DependsOn:[ve,lr]};this.builder.addResource(`${ve}Trigger`,Cr)}if(Ee.alarms?.enabled){let Ht=Ee.alarms,lr=Ht.notificationTopicArn;if(!lr&&Ht.notificationEmails?.length){let wr=`${ve}AlarmTopic`;this.builder.addResource(wr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${f}-${ut}-alarms`,DisplayName:`${ut} Queue Alarms`}}),Ht.notificationEmails.forEach((kr,xr)=>{this.builder.addResource(`${wr}Sub${xr}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:wr},Protocol:"email",Endpoint:kr}})}),lr={Ref:wr}}let Cr=Ht.queueDepthThreshold||1000;this.builder.addResource(`${ve}DepthAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${f}-${ut}-queue-depth`,AlarmDescription:`Queue ${ut} depth exceeds ${Cr} messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:Cr,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[ve,"QueueName"]}}],...lr&&{AlarmActions:[lr],OKActions:[lr]}}});let br=Ht.messageAgeThreshold||3600;if(this.builder.addResource(`${ve}AgeAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${f}-${ut}-message-age`,AlarmDescription:`Queue ${ut} oldest message exceeds ${br} seconds`,MetricName:"ApproximateAgeOfOldestMessage",Namespace:"AWS/SQS",Statistic:"Maximum",Period:300,EvaluationPeriods:2,Threshold:br,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[ve,"QueueName"]}}],...lr&&{AlarmActions:[lr],OKActions:[lr]}}}),Pt&&Ht.dlqAlarm!==!1)this.builder.addResource(`${Pt}Alarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${f}-${ut}-dlq-messages`,AlarmDescription:`Dead letter queue for ${ut} has messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Sum",Period:300,EvaluationPeriods:1,Threshold:0,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[Pt,"QueueName"]}}],...lr&&{AlarmActions:[lr]}}})}if(Ee.subscribe){let Ht=Ee.subscribe,lr=Ht.topicArn;if(!lr&&Ht.topicName)lr={Ref:Ht.topicName};if(lr){this.builder.addResource(`${ve}SnsPolicy`,{Type:"AWS::SQS::QueuePolicy",Properties:{Queues:[{Ref:ve}],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"sns.amazonaws.com"},Action:"sqs:SendMessage",Resource:{"Fn::GetAtt":[ve,"Arn"]},Condition:{ArnEquals:{"aws:SourceArn":lr}}}]}}});let Cr={TopicArn:lr,Protocol:"sqs",Endpoint:{"Fn::GetAtt":[ve,"Arn"]},RawMessageDelivery:Ht.rawMessageDelivery||!1};if(Ht.filterPolicy)Cr.FilterPolicy=Ht.filterPolicy,Cr.FilterPolicyScope=Ht.filterPolicyScope||"MessageAttributes";this.builder.addResource(`${ve}SnsSub`,{Type:"AWS::SNS::Subscription",Properties:Cr,DependsOn:`${ve}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 ct=this.mergedConfig.infrastructure?.redirects;if(ct){let ut=ct.target||this.mergedConfig.infrastructure?.dns?.domain||"",Ee=ct.protocol||"https";if(ct.domains?.length&&ut)for(let Ft of ct.domains){let{bucket:ve,bucketPolicy:Pt,logicalId:Ht,policyLogicalId:lr}=bt.createDomainRedirectBucket({slug:l,environment:f,sourceDomain:Ft,targetDomain:ut,protocol:Ee});this.builder.addResource(Ht,ve),this.builder.addResource(lr,Pt)}if(ct.paths&&Object.keys(ct.paths).length>0){let Ft=bt.fromMapping(ct.paths,{statusCode:ct.statusCode||301}),{function:ve,logicalId:Pt}=bt.createPathRedirectFunction({slug:l,environment:f,rules:Ft});this.builder.addResource(Pt,ve)}}if(this.mergedConfig.infrastructure?.monitoring?.alarms)for(let[ut,Ee]of Object.entries(this.mergedConfig.infrastructure.monitoring.alarms)){let{alarm:Ft,logicalId:ve}=Do.createAlarm({slug:l,environment:f,alarmName:`${l}-${f}-${ut}`,metricName:Ee.metricName||"Errors",namespace:Ee.namespace||"AWS/Lambda",threshold:Ee.threshold||1,comparisonOperator:Ee.comparisonOperator||"GreaterThanThreshold"});this.builder.addResource(ve,Ft)}let xe=this.mergedConfig.infrastructure?.cache;if(xe){let ut=xe.type||"redis";if(ut==="redis"){this.generateNetworkInfrastructure(l,f);let Ee=xe.redis||{},{replicationGroup:Ft,subnetGroup:ve,logicalId:Pt,subnetGroupId:Ht}=Ro.createRedis({slug:l,environment:f,nodeType:Ee.nodeType||xe.nodeType||"cache.t3.micro",engineVersion:Ee.engineVersion||"7.1",port:Ee.port||6379,numCacheClusters:Ee.numCacheNodes||2,automaticFailover:Ee.automaticFailoverEnabled!==!1,atRestEncryption:!0,transitEncryption:!0,snapshotRetentionDays:Ee.snapshotRetentionLimit||7,snapshotWindow:Ee.snapshotWindow,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(Pt,Ft),ve&&Ht)this.builder.addResource(Ht,ve);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[Pt,"PrimaryEndPoint.Address"]},Description:"Redis primary endpoint address"}),this.builder.addOutput("CachePort",{Value:{"Fn::GetAtt":[Pt,"PrimaryEndPoint.Port"]},Description:"Redis primary endpoint port"})}else if(ut==="memcached"){this.generateNetworkInfrastructure(l,f);let Ee=xe.elasticache||{},{cluster:Ft,subnetGroup:ve,logicalId:Pt,subnetGroupId:Ht}=Ro.createMemcached({slug:l,environment:f,nodeType:Ee.nodeType||xe.nodeType||"cache.t3.micro",engineVersion:Ee.engineVersion||"1.6.22",numCacheNodes:Ee.numCacheNodes||2,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(Pt,Ft),ve&&Ht)this.builder.addResource(Ht,ve);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[Pt,"ConfigurationEndpoint.Address"]},Description:"Memcached configuration endpoint address"})}}let Ut=this.mergedConfig.infrastructure?.email;if(Ut){let ut=Ut.domain||this.mergedConfig.infrastructure?.dns?.domain;if(ut){let{emailIdentity:Ee,logicalId:Ft}=m.verifyDomain({domain:ut,slug:l,environment:f,enableDkim:Ut.enableDkim!==!1,dkimKeyLength:Ut.dkimKeyLength||"RSA_2048_BIT"});if(this.builder.addResource(Ft,Ee),Ut.configurationSet!==!1){let{configurationSet:Ht,logicalId:lr}=m.createConfigurationSet({slug:l,environment:f});this.builder.addResource(lr,Ht)}let ve=Ut.hostedZoneId||this.mergedConfig.infrastructure?.dns?.hostedZoneId;if(ve){if(Ut.enableDkim!==!1)for(let wr=1;wr<=3;wr++){let kr=`DkimRecord${wr}${ut.replace(/\./g,"")}`;this.builder.addResource(kr,{Type:"AWS::Route53::RecordSet",DependsOn:[Ft],Properties:{HostedZoneId:ve,Name:{"Fn::GetAtt":[Ft,`DkimDNSTokenName${wr}`]},Type:"CNAME",TTL:1800,ResourceRecords:[{"Fn::GetAtt":[Ft,`DkimDNSTokenValue${wr}`]}]}})}let{record:Ht,logicalId:lr}=m.createSpfRecord(ut,ve);this.builder.addResource(lr,Ht);let{record:Cr,logicalId:br}=m.createDmarcRecord(ut,ve,{policy:"none",reportingEmail:Ut.dmarcReportingEmail||`dmarc-reports@${ut}`});this.builder.addResource(br,Cr)}this.builder.addOutput("EmailDomain",{Value:ut,Description:"SES verified email domain"});let Pt=Ut.server;if(Pt?.enabled&&ve){let Ht=this.mergedConfig.environments[f]?.region||this.mergedConfig.project.region||"us-east-1",lr=`${l}-${f}-email`,{role:Cr,policy:br,roleLogicalId:wr,policyLogicalId:kr}=m.createEmailLambdaRole({slug:l,environment:f,s3BucketArn:`arn:aws:s3:::${lr}`,sesIdentityArn:`arn:aws:ses:${Ht}:*:identity/${ut}`});this.builder.addResource(wr,Cr),this.builder.addResource(kr,br);let{function:xr,permission:Ir,logicalId:Er,permissionLogicalId:sn}=m.createInboundEmailLambda({slug:l,environment:f,roleArn:{"Fn::GetAtt":[wr,"Arn"]},s3BucketName:lr,organizedPrefix:"mailboxes/"});this.builder.addResource(Er,xr),this.builder.addResource(sn,Ir);let Fn=m.createInboundEmailSetup({slug:l,environment:f,domain:ut,s3BucketName:lr,s3KeyPrefix:"inbox/",region:Ht,hostedZoneId:ve,lambdaFunctionArn:{"Fn::GetAtt":[Er,"Arn"]}});for(let[_r,Wn]of Object.entries(Fn.resources)){if(Wn.Type==="AWS::SES::ReceiptRule")Wn.DependsOn=[sn,Er];this.builder.addResource(_r,Wn)}this.builder.addOutput("InboundEmailLambda",{Value:{Ref:Er},Description:"Inbound email processing Lambda function"}),this.builder.addOutput("EmailBucket",{Value:lr,Description:"S3 bucket for email storage"});let bn=this.serverEipLogicalIds.get("app");if(bn&&ve){let Wn=`${Pt?.subdomain||"mail"}.${ut}`,ri=Wn.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${ri}ARecord`,{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:ve,Name:Wn,Type:"A",TTL:"300",ResourceRecords:[{Ref:bn}]}})}this.builder.addOutput("MailHost",{Value:`mail.${ut}`,Description:"Mail server hostname for SMTP/IMAP clients"})}}}let Qt=this.mergedConfig.infrastructure?.search;if(Qt){let ut=Qt.vpc?{subnetIds:[{Ref:"PublicSubnet1"}],securityGroupIds:[]}:void 0;if(ut)this.generateNetworkInfrastructure(l,f);let{domain:Ee,logicalId:Ft}=Zt.createDomain({slug:l,environment:f,engineVersion:Qt.engineVersion||"OpenSearch_2.11",instanceType:Qt.instanceType||"t3.small.search",instanceCount:Qt.instanceCount||1,volumeSize:Qt.volumeSize||10,volumeType:Qt.volumeType||"gp3",dedicatedMaster:Qt.dedicatedMaster||!1,dedicatedMasterType:Qt.dedicatedMasterType,dedicatedMasterCount:Qt.dedicatedMasterCount||3,multiAz:Qt.multiAz||!1,encryption:Qt.encryption||{atRest:!0,nodeToNode:!0},advancedSecurity:Qt.advancedSecurity,autoTune:Qt.autoTune!==!1,vpc:ut});this.builder.addResource(Ft,Ee),this.builder.addOutput("SearchDomainEndpoint",{Value:{"Fn::GetAtt":[Ft,"DomainEndpoint"]},Description:"OpenSearch domain endpoint"}),this.builder.addOutput("SearchDomainArn",{Value:{"Fn::GetAtt":[Ft,"Arn"]},Description:"OpenSearch domain ARN"})}let gt=this.mergedConfig.infrastructure?.fileSystem;if(gt&&Object.keys(gt).length>0){this.generateNetworkInfrastructure(l,f);for(let[ut,Ee]of Object.entries(gt)){let{fileSystem:Ft,logicalId:ve}=ze.createFileSystem({slug:`${l}-${ut}`,environment:f,encrypted:Ee.encrypted!==!1,performanceMode:Ee.performanceMode||"generalPurpose",throughputMode:Ee.throughputMode||"bursting",enableBackup:!0});this.builder.addResource(ve,Ft);let{securityGroup:Pt,logicalId:Ht}=ze.createEfsSecurityGroup({slug:`${l}-${ut}`,environment:f,vpcId:{Ref:"VPC"},sourceCidrBlocks:["10.0.0.0/16"]});this.builder.addResource(Ht,Pt);let{mountTargets:lr,logicalIds:Cr}=ze.createMultiAzMountTargets(ve,{slug:`${l}-${ut}`,environment:f,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],securityGroupId:{Ref:Ht}});for(let br=0;br<lr.length;br++)this.builder.addResource(Cr[br],lr[br]);this.builder.addOutput(`${ut}FileSystemId`,{Value:{Ref:ve},Description:`EFS file system ID for ${ut}`})}}let lt=this.mergedConfig.infrastructure?.ai;if(lt){let ut=lt.service||"ecs",Ee=lt.models||["*"],Ft=lt.allowStreaming!==!1,ve;if(ut==="ecs")ve=Pe.enableBedrockForEcs({slug:l,environment:f,models:Ee,allowStreaming:Ft});else if(ut==="ec2")ve=Pe.enableBedrockForEc2({slug:l,environment:f,models:Ee,allowStreaming:Ft});else if(ut==="lambda")ve=Pe.enableBedrockForLambda({slug:l,environment:f,models:Ee,allowStreaming:Ft});else ve=Pe.createBedrockRole(ut,{slug:l,environment:f,models:Ee,allowStreaming:Ft});if(this.builder.addResource(ve.logicalId,ve.role),lt.allowAsync){let{policy:Pt,logicalId:Ht}=Pe.createBedrockPolicy({slug:l,environment:f,models:Ee,allowStreaming:Ft,allowAsync:!0});this.builder.addResource(Ht,Pt)}this.builder.addOutput("BedrockRoleArn",{Value:{"Fn::GetAtt":[ve.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||{},B=C.storage||{type:"dynamodb"},v=w.handlerMemory||256,ce=w.handlerTimeout||30,de=`${l}${f}RealtimeConnections`.replace(/[^a-zA-Z0-9]/g,""),ct=`${l}${f}RealtimeChannels`.replace(/[^a-zA-Z0-9]/g,"");if(B.type==="dynamodb"){let Cr=B.dynamodb||{},br=Cr.billingMode||"PAY_PER_REQUEST";this.builder.addResource(de,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${l}-${f}-realtime-connections`,BillingMode:br,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"},...br==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Cr.readCapacity||5,WriteCapacityUnits:Cr.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...br==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Cr.readCapacity||5,WriteCapacityUnits:Cr.writeCapacity||5}},...Cr.pointInTimeRecovery&&{PointInTimeRecoverySpecification:{PointInTimeRecoveryEnabled:!0}},Tags:[{Key:"Name",Value:`${l}-${f}-realtime-connections`},{Key:"Environment",Value:f}]}}),this.builder.addResource(ct,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${l}-${f}-realtime-channels`,BillingMode:br,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"},...br==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Cr.readCapacity||5,WriteCapacityUnits:Cr.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...br==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Cr.readCapacity||5,WriteCapacityUnits:Cr.writeCapacity||5}},Tags:[{Key:"Name",Value:`${l}-${f}-realtime-channels`},{Key:"Environment",Value:f}]}})}let xe=`${l}${f}RealtimeRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(xe,{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":[de,"Arn"]},{"Fn::Sub":`\${${de}.Arn}/index/*`},{"Fn::GetAtt":[ct,"Arn"]},{"Fn::Sub":`\${${ct}.Arn}/index/*`}]},{Effect:"Allow",Action:"execute-api:ManageConnections",Resource:{"Fn::Sub":"arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:*/*"}}]}}]}});let Ut=`${l}${f}RealtimeConnect`.replace(/[^a-zA-Z0-9]/g,""),Qt=`${l}${f}RealtimeDisconnect`.replace(/[^a-zA-Z0-9]/g,""),gt=`${l}${f}RealtimeMessage`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ut,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${f}-realtime-connect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[xe,"Arn"]},MemorySize:v,Timeout:ce,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:de},CHANNELS_TABLE:{Ref:ct},ENVIRONMENT:f}},Code:{ZipFile:this.generateConnectHandlerCode()}},DependsOn:[xe,de]}),this.builder.addResource(Qt,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${f}-realtime-disconnect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[xe,"Arn"]},MemorySize:v,Timeout:ce,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:de},CHANNELS_TABLE:{Ref:ct},ENVIRONMENT:f}},Code:{ZipFile:this.generateDisconnectHandlerCode()}},DependsOn:[xe,de,ct]}),this.builder.addResource(gt,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${f}-realtime-message`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[xe,"Arn"]},MemorySize:v,Timeout:ce,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:de},CHANNELS_TABLE:{Ref:ct},ENVIRONMENT:f}},Code:{ZipFile:this.generateMessageHandlerCode()}},DependsOn:[xe,de,ct]});let lt=`${l}${f}RealtimeApi`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(lt,{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:A,ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action",Tags:{Name:A,Environment:f}}});let ut=`${Ut}Permission`,Ee=`${Qt}Permission`,Ft=`${gt}Permission`;this.builder.addResource(ut,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:Ut},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${lt}}/*/$connect`}}}),this.builder.addResource(Ee,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:Qt},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${lt}}/*/$disconnect`}}}),this.builder.addResource(Ft,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:gt},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${lt}}/*/$default`}}});let ve=`${lt}ConnectInteg`,Pt=`${lt}DisconnectInteg`,Ht=`${lt}MessageInteg`;this.builder.addResource(ve,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:lt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${Ut}.Arn}/invocations`}}}),this.builder.addResource(Pt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:lt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${Qt}.Arn}/invocations`}}}),this.builder.addResource(Ht,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:lt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${gt}.Arn}/invocations`}}}),this.builder.addResource(`${lt}ConnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:lt},RouteKey:"$connect",AuthorizationType:"NONE",Target:{"Fn::Sub":`integrations/\${${ve}}`}}}),this.builder.addResource(`${lt}DisconnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:lt},RouteKey:"$disconnect",Target:{"Fn::Sub":`integrations/\${${Pt}}`}}}),this.builder.addResource(`${lt}DefaultRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:lt},RouteKey:"$default",Target:{"Fn::Sub":`integrations/\${${Ht}}`}}});let lr=`${lt}Stage`;if(this.builder.addResource(lr,{Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:{Ref:lt},StageName:f,AutoDeploy:!0,DefaultRouteSettings:{ThrottlingBurstLimit:w.messagesPerSecond||1000,ThrottlingRateLimit:w.messagesPerSecond||1000}}}),C.monitoring?.enabled){let Cr=C.monitoring,br=Cr.notificationTopicArn;if(!br&&Cr.notificationEmails?.length){let wr=`${lt}AlarmTopic`;this.builder.addResource(wr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${f}-realtime-alarms`,DisplayName:"Realtime WebSocket Alarms"}}),Cr.notificationEmails.forEach((kr,xr)=>{this.builder.addResource(`${wr}Sub${xr}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:wr},Protocol:"email",Endpoint:kr}})}),br={Ref:wr}}if(Cr.connectionThreshold)this.builder.addResource(`${lt}ConnectionAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${f}-realtime-connections`,AlarmDescription:`WebSocket connections exceed ${Cr.connectionThreshold}`,MetricName:"ConnectCount",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:300,EvaluationPeriods:2,Threshold:Cr.connectionThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:lt}}],...br&&{AlarmActions:[br]}}});if(Cr.errorThreshold)this.builder.addResource(`${lt}ErrorAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${f}-realtime-errors`,AlarmDescription:`WebSocket errors exceed ${Cr.errorThreshold}/min`,MetricName:"ExecutionError",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:60,EvaluationPeriods:3,Threshold:Cr.errorThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:lt}}],...br&&{AlarmActions:[br]}}})}this.builder.addOutput(`${lt}Endpoint`,{Description:"WebSocket API endpoint URL",Value:{"Fn::Sub":`wss://\${${lt}}.execute-api.\${AWS::Region}.amazonaws.com/${f}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}}),this.builder.addOutput(`${lt}Id`,{Description:"WebSocket API ID",Value:{Ref:lt},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-api-id"}}})}generateConnectHandlerCode(){return`
|
|
13
|
+
`:Lt,ze=T.map(([,zt])=>zt.port).filter((zt)=>typeof zt==="number"&&![80,443].includes(zt)),j=this.resolveApiOriginPort(),yt=`${u}${f}DeployBucket`.replace(/[^a-zA-Z0-9]/g,""),G=`${u}-${f}-deploy`;this.builder.addResource(yt,{Type:"AWS::S3::Bucket",Properties:{BucketName:G,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:u},{Key:"Environment",Value:f},{Key:"ManagedBy",Value:"ts-cloud"}]}});let ht=a.createServerModeStack({slug:`${u}-app`,environment:f,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},instanceType:me,keyName:R.allowSsh?`${u}-${f}`:void 0,domain:P,userData:Me,volumeSize:R.disk?.size||20,imageId:R.image,allowedPorts:[...R.allowSsh?[22]:[],80,443,j,...ze]}),St=ht.resources[ht.outputs.instanceLogicalId];if(St?.Properties){let zt=St.Properties.Tags||[];St.Properties.Tags=[...zt,{Key:"Project",Value:u},{Key:"Environment",Value:f},{Key:"Role",Value:"app"},{Key:"ManagedBy",Value:"ts-cloud"}]}let Wt=ht.resources[ht.outputs.roleLogicalId];if(Wt?.Properties)Wt.Properties.Policies=Wt.Properties.Policies||[],Wt.Properties.Policies.push({PolicyName:"DeployBucketRead",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:ListBucket"],Resource:[`arn:aws:s3:::${G}`,`arn:aws:s3:::${G}/*`]}]}});for(let[zt,jt]of Object.entries(ht.resources))this.builder.addResource(zt,jt);this.builder.addOutput("deployBucketName",{Value:{Ref:yt},Description:"S3 bucket where release tarballs are uploaded"}),this.builder.addOutput("appInstanceId",{Value:{Ref:ht.outputs.instanceLogicalId},Description:"EC2 instance ID for the app server"}),this.builder.addOutput("appPublicIp",{Value:{Ref:ht.outputs.eipLogicalId},Description:"Public IP for the app server"}),this.serverEipLogicalIds.set("app",ht.outputs.eipLogicalId),this.serverEipLogicalIds.set("appInstance",ht.outputs.instanceLogicalId)}jumpBoxFileSystemId(u,f,R){let A=Object.keys(this.mergedConfig.infrastructure?.fileSystem??{});if(typeof R==="string")return A.includes(R)?{Ref:this.fileSystemLogicalId(u,f,R)}:R;if(A.length===1)return{Ref:this.fileSystemLogicalId(u,f,A[0])};throw Error(A.length===0?"infrastructure.jumpBox.mountEfs is true, but infrastructure.fileSystem declares no file system. Declare one, or set mountEfs to an EFS id.":`infrastructure.jumpBox.mountEfs is true, but infrastructure.fileSystem declares ${A.length} (${A.join(", ")}). Set mountEfs to the name of the one to mount.`)}generateJumpBox(u,f){let R=this.mergedConfig.infrastructure?.jumpBox;if(!R)return;let A=R===!0?{}:R;if(A.enabled===!1)return;this.generateNetworkInfrastructure(u,f);let T=A.size||"micro",P=a.InstanceSize.specs[T]?.instanceType||T||"t3.micro",L=a.createJumpBox({slug:u,environment:f,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:A.keyName,instanceType:P,allowedCidrs:A.allowedCidrs,mountEfs:A.mountEfs?{fileSystemId:this.jumpBoxFileSystemId(u,f,A.mountEfs),mountPath:A.mountPath||"/mnt/efs"}:void 0,databaseTools:A.databaseTools});for(let[z,fe]of Object.entries(L.resources))this.builder.addResource(z,fe);this.builder.addOutput("JumpBoxInstanceId",{Value:{Ref:L.instanceLogicalId},Description:"The ID of the JumpBox EC2 instance (use with SSM Session Manager or SSH)"})}generateSharedInfrastructure(u,f){let R=this.mergedConfig.infrastructure?.ssl,A=this.mergedConfig.infrastructure?.dns,T=A?.domain,E=A?.hostedZoneId,P=[],L,z;if(R?.certificateArn)z=R.certificateArn;else if(R?.enabled&&T&&E){let ze=R.domains||[T],j=ze[0],yt=ze.slice(1).map((St)=>{if(St.includes(".")&&St.endsWith(j))return St.replace(`.${j}`,"");return St}),{certificate:G,logicalId:ht}=C.createCertificate({domain:j,subdomains:yt,slug:u,environment:f,validationMethod:"DNS",hostedZoneId:E});L=ht,this.builder.addResource(ht,G)}if(this.mergedConfig.infrastructure?.storage){let ze=Object.entries(this.mergedConfig.infrastructure.storage).some(([,G])=>G.website),j;if(ze&&(L||z))j=`${u}${f}CloudFrontOAC`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(j,{Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${u}-${f}-s3-oac`,Description:`OAC for ${u} ${f} S3 website buckets`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}});let yt=Object.entries(this.mergedConfig.infrastructure.storage).map(([G,ht])=>({name:G,config:ht,mountPath:this.normalizeMountPath(ht),rewriteStyle:ht.pathRewriteStyle||"directory",logicalId:this.storageBucketLogicalId(u,f,G)})).filter((G)=>G.name!=="public"&&G.config.website&&G.mountPath);for(let[G,ht]of Object.entries(this.mergedConfig.infrastructure.storage)){let St=!!(ht.website&&j),Wt=this.storageBucketName(u,f,G),{bucket:zt,logicalId:jt}=xe.createBucket({slug:u,name:G,environment:f,bucketName:Wt,versioning:ht.versioning,encryption:ht.encryption,public:St?!1:ht.public}),Kt=this.normalizeMountPath(ht),Sr;if(ht.failover){let Xt=`infrastructure.storage.${G}`;if(!St||!T||Kt&&G!=="public")throw Error(`${Xt}.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(Sr=lm({failover:ht.failover,primaryBucket:Wt,primaryRegion:this.mergedConfig.project.region||"us-east-1",where:Xt}),Sr.replicate&&zt.Properties){let Pr=`${jt}FailoverReplicationRole`;this.builder.addResource(Pr,gm({primaryBucket:Wt,replicaBucket:Sr.replicaBucket}));let Fr=zt.Properties;Fr.VersioningConfiguration={Status:"Enabled"},Fr.ReplicationConfiguration=pm({replicaBucket:Sr.replicaBucket,roleArn:{"Fn::GetAtt":[Pr,"Arn"]}})}}if(St&&zt.Properties)zt.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1};if(this.builder.addResource(jt,zt),ht.website){let Xt=typeof ht.website==="object"?ht.website:{},Pr=xe.enableWebsiteHosting(zt,Xt.indexDocument||"index.html",Xt.errorDocument);this.builder.addResource(jt,Pr)}let Or=this.normalizeMountPath(ht);if(St&&j&&T&&!(Or&&G!=="public")){let Xt=`${u}${f}${G}CDN`.replace(/[^a-zA-Z0-9]/g,""),Pr=[];if(ht.aliases&&ht.aliases.length>0)Pr.push(...ht.aliases);else if(G==="public"){if(Pr.push(T),R?.domains?.includes(`www.${T}`))Pr.push(`www.${T}`)}else if(G==="docs")Pr.push(`docs.${T}`);else if(G==="blog")Pr.push(`blog.${T}`);let Fr=typeof ht.website==="object"?ht.website:{},Qr=ht.spa===!0,Hr=Fr.errorDocument||(Qr?"index.html":"404.html"),Nr=[];if(Qr)Nr.push({ErrorCode:403,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300});else Nr.push({ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${Hr}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${Hr}`,ErrorCachingMinTTL:300});let pn=z&&Pr.length>0?{AcmCertificateArn:z,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:L&&Pr.length>0?{AcmCertificateArn:{Ref:L},SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},Wn=`S3-${u}-${f}-${G}`,$c=this.mergedConfig.project.region||"us-east-1",Zn;if(!Qr)Zn=`${u}${f}${G}UrlRewrite`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(Zn,{Type:"AWS::CloudFront::Function",Properties:{Name:`${u}-${f}-${G}-url-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`URL rewrite for ${u} ${f} ${G} - 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 Ei=[{Id:Wn,DomainName:{"Fn::Sub":`\${${jt}}.s3.${$c}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:j}}],ks=[],kc=[];if(this.shouldRouteStorageBucketToCompute(G,ht)){this.appendComputeAppOrigin(Ei,ks,kc,u,f,this.resolveComputeCachePathPatterns(ht.computeRoutes));for(let kr of yt){let Ns=`S3-${u}-${f}-${kr.name}`,Nc=`${u}${f}${kr.name}PathMountRewrite`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Nc,{Type:"AWS::CloudFront::Function",Properties:{Name:`${u}-${f}-${kr.name}-path-mount-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`Path mount rewrite for ${u} ${f} ${kr.name} at ${kr.mountPath}`,Runtime:"cloudfront-js-2.0"},FunctionCode:this.pathMountRewriteFunctionCode(kr.mountPath,kr.rewriteStyle)}}),Ei.push({Id:Ns,DomainName:{"Fn::Sub":`\${${kr.logicalId}}.s3.${$c}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:j}}),kc.push(kr.logicalId,Nc);for(let pg of[kr.mountPath,`${kr.mountPath}/*`])ks.push({PathPattern:pg,TargetOriginId:Ns,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[Nc,"FunctionARN"]}}]})}}let vs,Yc=Wn;if(Sr){let kr=`${Wn}-failover`;Object.assign(Ei[0],Sr.primaryConnection),Ei.push({Id:kr,DomainName:um(Sr.replicaBucket,Sr.replicaRegion),OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:j}}),vs=an({primaryOriginId:Wn,secondaryOriginId:kr,statusCodes:Sr.statusCodes}),Yc=vs.Items[0].Id}let Oc={Type:"AWS::CloudFront::Distribution",DependsOn:[jt,j,...Zn?[Zn]:[],...kc],Properties:{DistributionConfig:{Enabled:!0,Comment:`${u} ${f} ${G} site`,DefaultRootObject:"index.html",Origins:Ei,...vs?{OriginGroups:vs}:{},DefaultCacheBehavior:{TargetOriginId:Yc,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...Zn?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[Zn,"FunctionARN"]}}]}:{}},...ks.length>0?{CacheBehaviors:ks}:{},...Pr.length>0?{Aliases:Pr}:{},ViewerCertificate:pn,PriceClass:"PriceClass_100",HttpVersion:"http2and3",IPV6Enabled:!0,CustomErrorResponses:Nr}}};if(L)Oc.DependsOn.push(L);if(Sr)wt(Oc.Properties.DistributionConfig,`infrastructure.storage.${G}`),this.storageFailoverReplicas.push({name:G,primaryBucket:Wt,primaryRegion:$c,replicaBucket:Sr.replicaBucket,replicaRegion:Sr.replicaRegion,replicate:Sr.replicate,distributionArnOutput:`${G}CloudFrontDistributionArn`}),this.builder.addOutput(`${G}CloudFrontDistributionArn`,{Value:{"Fn::Sub":`arn:\${AWS::Partition}:cloudfront::\${AWS::AccountId}:distribution/\${${Xt}}`},Description:`CloudFront distribution ARN for ${G} (scopes the bucket policy of the failover replica)`}),this.builder.addOutput(`${G}FailoverBucketName`,{Value:Sr.replicaBucket,Description:`Failover replica bucket for ${G} (${Sr.replicaRegion}), outside this stack`});this.builder.addResource(Xt,Oc);let dg=`${jt}CloudFrontPolicy`;if(this.builder.addResource(dg,{Type:"AWS::S3::BucketPolicy",DependsOn:[jt,Xt],Properties:{Bucket:{Ref:jt},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":`arn:aws:s3:::\${${jt}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${Xt}}`}}}}]}}}),this.shouldRouteStorageBucketToCompute(G,ht))for(let kr of yt){let Ns=`${kr.logicalId}CloudFrontPolicy`;this.builder.addResource(Ns,{Type:"AWS::S3::BucketPolicy",DependsOn:[kr.logicalId,Xt],Properties:{Bucket:{Ref:kr.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:::\${${kr.logicalId}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${Xt}}`}}}}]}}})}if(Pr.length>0)P.push({name:G,bucketLogicalId:jt,distLogicalId:Xt,oacLogicalId:j,aliases:Pr});this.builder.addOutput(`${G}CloudFrontDomain`,{Value:{"Fn::GetAtt":[Xt,"DomainName"]},Description:`CloudFront domain for ${G}`}),this.builder.addOutput(`${G}CloudFrontDistributionId`,{Value:{Ref:Xt},Description:`CloudFront distribution ID for ${G}`})}if(this.builder.addOutput(`${G}BucketName`,{Value:{Ref:jt},Description:`S3 bucket name for ${G}`}),G==="public")this.builder.addOutput("FrontendBucketName",{Value:{Ref:jt},Description:"Frontend S3 bucket name"});if(G==="docs")this.builder.addOutput("DocsBucketName",{Value:{Ref:jt},Description:"Documentation S3 bucket name"});if(G==="blog")this.builder.addOutput("BlogBucketName",{Value:{Ref:jt},Description:"Blog S3 bucket name"})}}if(this.mergedConfig.infrastructure?.sftp){let ze=this.mergedConfig.infrastructure.sftp,j=rl.create({...ze,storage:this.resolveSftpStorage(ze,u,f)??ze.storage,slug:u,environment:f});for(let[yt,G]of Object.entries(j.resources))this.builder.addResource(yt,G);this.builder.addOutput("SftpServerId",{Value:{Ref:j.serverLogicalId},Description:"AWS Transfer Family SFTP server ID"}),this.builder.addOutput("SftpEndpoint",{Value:{"Fn::Sub":`\${${j.serverLogicalId}}.server.transfer.\${AWS::Region}.amazonaws.com`},Description:"AWS Transfer Family SFTP endpoint"}),this.builder.addOutput("SftpStorageDomain",{Value:j.domain,Description:"Storage backing the SFTP server (EFS or S3)"})}if(E&&P.length>0)for(let{name:ze,distLogicalId:j,aliases:yt}of P)for(let G of yt){let ht=G.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${ht}ARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[j],Properties:{HostedZoneId:E,Name:G,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[j,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}}),this.builder.addResource(`${ht}AAAARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[j],Properties:{HostedZoneId:E,Name:G,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":[j,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}})}if(this.mergedConfig.infrastructure?.databases){for(let[ze,j]of Object.entries(this.mergedConfig.infrastructure.databases))if(j.engine==="dynamodb"){let{table:yt,logicalId:G}=or.createTable({slug:u,environment:f,tableName:`${u}-${f}-${ze}`,partitionKey:j.partitionKey||{name:"id",type:"S"},sortKey:j.sortKey});this.builder.addResource(G,yt)}else if(j.engine==="postgres"){let{dbInstance:yt,logicalId:G}=or.createPostgres({slug:u,environment:f,dbInstanceIdentifier:`${u}-${f}-${ze}`,masterUsername:j.username||"admin",masterUserPassword:j.password||"changeme123",allocatedStorage:j.storage||20,dbInstanceClass:j.instanceClass||"db.t3.micro"});this.builder.addResource(G,yt)}else if(j.engine==="mysql"){let{dbInstance:yt,logicalId:G}=or.createMysql({slug:u,environment:f,dbInstanceIdentifier:`${u}-${f}-${ze}`,masterUsername:j.username||"admin",masterUserPassword:j.password||"changeme123",allocatedStorage:j.storage||20,dbInstanceClass:j.instanceClass||"db.t3.micro"});this.builder.addResource(G,yt)}}if(this.mergedConfig.infrastructure?.cdn)for(let[ze,j]of Object.entries(this.mergedConfig.infrastructure.cdn)){if(!j.origin)continue;let yt=typeof j.customDomain==="string"?j.customDomain:j.customDomain?.domain||j.domain,G=typeof j.customDomain==="object"?j.customDomain?.certificateArn:j.certificateArn,ht=G||z,St=`${u}${f}${ze}CDN`.replace(/[^a-zA-Z0-9]/g,""),Wt=`S3-${u}-${f}-${ze}-cdn`,zt=[{Id:Wt,DomainName:j.origin,OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginShield:j.originShield?{Enabled:!0,OriginShieldRegion:j.originShieldRegion||this.mergedConfig.environments[f]?.region||this.mergedConfig.project.region||"us-east-1"}:{Enabled:!1},...ce(j,`infrastructure.cdn.${ze}`)}],jt=[],Kt=[],Sr=["GET","HEAD","OPTIONS"],Or=Wt,Xt;if(j.failoverOrigin){Tt(Sr,`the default cache behavior of infrastructure.cdn.${ze}`);let Hr=`${Wt}-failover`,Nr=typeof j.failoverOrigin==="string"?{domain:j.failoverOrigin}:j.failoverOrigin;if(!Nr.domain)throw Error(`infrastructure.cdn.${ze}.failoverOrigin.domain is required`);if(Nr.domain===j.origin)throw Error(`infrastructure.cdn.${ze}: failoverOrigin must differ from origin (both are ${j.origin})`);zt.push({Id:Hr,DomainName:Nr.domain,OriginPath:Nr.originPath||"",...xo(Nr.domain)?{S3OriginConfig:{OriginAccessIdentity:""}}:{CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"}},OriginShield:{Enabled:!1},...ce(Nr,`infrastructure.cdn.${ze}.failoverOrigin`)}),Xt=an({primaryOriginId:Wt,secondaryOriginId:Hr,statusCodes:j.failoverStatusCodes}),Or=Xt.Items[0].Id}else if(j.failoverStatusCodes)throw Error(`infrastructure.cdn.${ze}: failoverStatusCodes needs failoverOrigin to fail over to`);if(j.routeCompute)this.appendComputeAppOrigin(zt,jt,Kt,u,f,this.resolveComputeCachePathPatterns(j.computeRoutes));let Pr=ht&&yt?{AcmCertificateArn:L&&!G?{Ref:L}:ht,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},Fr=[...Kt];if(L&&!G&&yt)Fr.push(L);let Qr={Type:"AWS::CloudFront::Distribution",...Fr.length>0?{DependsOn:Fr}:{},Properties:{DistributionConfig:{Enabled:!0,Comment:`${u} ${f} ${ze} CDN`,DefaultRootObject:"index.html",Origins:zt,...Xt?{OriginGroups:Xt}:{},DefaultCacheBehavior:{TargetOriginId:Or,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:Sr,CachedMethods:["GET","HEAD","OPTIONS"],Compress:j.compress!==!1,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},...jt.length>0?{CacheBehaviors:jt}:{},...yt&&ht?{Aliases:[yt]}:{},ViewerCertificate:Pr,PriceClass:"PriceClass_100",HttpVersion:j.http3?"http2and3":"http2"}}};if(wt(Qr.Properties.DistributionConfig,`infrastructure.cdn.${ze}`),this.builder.addResource(St,Qr),E&&yt&&ht){let Hr=yt.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Hr}CdnARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[St,...L&&!G?[L]:[]],Properties:{HostedZoneId:E,Name:yt,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:{"Fn::GetAtt":[St,"DomainName"]}}}})}}if(this.mergedConfig.infrastructure?.queues)for(let[ze,j]of Object.entries(this.mergedConfig.infrastructure.queues)){if(!this.shouldDeploy(j))continue;let{queue:yt,logicalId:G}=J.createQueue({slug:u,environment:f,name:`${u}-${f}-${ze}`,fifo:j.fifo,visibilityTimeout:j.visibilityTimeout,messageRetentionPeriod:j.messageRetentionPeriod,delaySeconds:j.delaySeconds,maxMessageSize:j.maxMessageSize,receiveMessageWaitTime:j.receiveMessageWaitTime,contentBasedDeduplication:j.contentBasedDeduplication,encrypted:j.encrypted,kmsKeyId:j.kmsKeyId});this.builder.addResource(G,yt);let ht;if(j.deadLetterQueue){let{deadLetterQueue:St,updatedSourceQueue:Wt,deadLetterLogicalId:zt}=J.createDeadLetterQueue(G,{slug:u,environment:f,maxReceiveCount:j.maxReceiveCount});ht=zt,this.builder.addResource(zt,St);let Kt=this.builder.getResources()[G];if(Kt?.Properties)Kt.Properties.RedrivePolicy=Wt.Properties?.RedrivePolicy}if(j.trigger){let St=j.trigger,Wt=`${u}${f}${St.functionName}`.replace(/[^a-zA-Z0-9]/g,""),zt={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:{"Fn::GetAtt":[G,"Arn"]},FunctionName:{Ref:Wt},BatchSize:St.batchSize||10,MaximumBatchingWindowInSeconds:St.batchWindow||0,Enabled:!0,...St.reportBatchItemFailures!==!1&&{FunctionResponseTypes:["ReportBatchItemFailures"]},...St.maxConcurrency&&{ScalingConfig:{MaximumConcurrency:St.maxConcurrency}},...St.filterPattern&&{FilterCriteria:{Filters:[{Pattern:JSON.stringify(St.filterPattern)}]}}},DependsOn:[G,Wt]};this.builder.addResource(`${G}Trigger`,zt)}if(j.alarms?.enabled){let St=j.alarms,Wt=St.notificationTopicArn;if(!Wt&&St.notificationEmails?.length){let Kt=`${G}AlarmTopic`;this.builder.addResource(Kt,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-${f}-${ze}-alarms`,DisplayName:`${ze} Queue Alarms`}}),St.notificationEmails.forEach((Sr,Or)=>{this.builder.addResource(`${Kt}Sub${Or}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:Kt},Protocol:"email",Endpoint:Sr}})}),Wt={Ref:Kt}}let zt=St.queueDepthThreshold||1000;this.builder.addResource(`${G}DepthAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${f}-${ze}-queue-depth`,AlarmDescription:`Queue ${ze} depth exceeds ${zt} messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:zt,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[G,"QueueName"]}}],...Wt&&{AlarmActions:[Wt],OKActions:[Wt]}}});let jt=St.messageAgeThreshold||3600;if(this.builder.addResource(`${G}AgeAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${f}-${ze}-message-age`,AlarmDescription:`Queue ${ze} oldest message exceeds ${jt} seconds`,MetricName:"ApproximateAgeOfOldestMessage",Namespace:"AWS/SQS",Statistic:"Maximum",Period:300,EvaluationPeriods:2,Threshold:jt,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[G,"QueueName"]}}],...Wt&&{AlarmActions:[Wt],OKActions:[Wt]}}}),ht&&St.dlqAlarm!==!1)this.builder.addResource(`${ht}Alarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${f}-${ze}-dlq-messages`,AlarmDescription:`Dead letter queue for ${ze} has messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Sum",Period:300,EvaluationPeriods:1,Threshold:0,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[ht,"QueueName"]}}],...Wt&&{AlarmActions:[Wt]}}})}if(j.subscribe){let St=j.subscribe,Wt=St.topicArn;if(!Wt&&St.topicName)Wt={Ref:St.topicName};if(Wt){this.builder.addResource(`${G}SnsPolicy`,{Type:"AWS::SQS::QueuePolicy",Properties:{Queues:[{Ref:G}],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"sns.amazonaws.com"},Action:"sqs:SendMessage",Resource:{"Fn::GetAtt":[G,"Arn"]},Condition:{ArnEquals:{"aws:SourceArn":Wt}}}]}}});let zt={TopicArn:Wt,Protocol:"sqs",Endpoint:{"Fn::GetAtt":[G,"Arn"]},RawMessageDelivery:St.rawMessageDelivery||!1};if(St.filterPolicy)zt.FilterPolicy=St.filterPolicy,zt.FilterPolicyScope=St.filterPolicyScope||"MessageAttributes";this.builder.addResource(`${G}SnsSub`,{Type:"AWS::SNS::Subscription",Properties:zt,DependsOn:`${G}SnsPolicy`})}}}if(this.mergedConfig.infrastructure?.realtime?.enabled)if((this.mergedConfig.infrastructure.realtime.mode||"serverless")==="server")this.generateRealtimeServerResources(u,f);else this.generateRealtimeResources(u,f);let fe=this.mergedConfig.infrastructure?.redirects;if(fe){let ze=fe.target||this.mergedConfig.infrastructure?.dns?.domain||"",j=fe.protocol||"https";if(fe.domains?.length&&ze)for(let yt of fe.domains){let{bucket:G,bucketPolicy:ht,logicalId:St,policyLogicalId:Wt}=Dt.createDomainRedirectBucket({slug:u,environment:f,sourceDomain:yt,targetDomain:ze,protocol:j});this.builder.addResource(St,G),this.builder.addResource(Wt,ht)}if(fe.paths&&Object.keys(fe.paths).length>0){let yt=Dt.fromMapping(fe.paths,{statusCode:fe.statusCode||301}),{function:G,logicalId:ht}=Dt.createPathRedirectFunction({slug:u,environment:f,rules:yt});this.builder.addResource(ht,G)}}if(this.mergedConfig.infrastructure?.monitoring?.alarms)for(let[ze,j]of Object.entries(this.mergedConfig.infrastructure.monitoring.alarms)){let{alarm:yt,logicalId:G}=Lo.createAlarm({slug:u,environment:f,alarmName:`${u}-${f}-${ze}`,metricName:j.metricName||"Errors",namespace:j.namespace||"AWS/Lambda",threshold:j.threshold||1,comparisonOperator:j.comparisonOperator||"GreaterThanThreshold"});this.builder.addResource(G,yt)}let me=this.mergedConfig.infrastructure?.cache;if(me){let ze=me.type||"redis";if(ze==="redis"){this.generateNetworkInfrastructure(u,f);let j=me.redis||{},{replicationGroup:yt,subnetGroup:G,logicalId:ht,subnetGroupId:St}=_o.createRedis({slug:u,environment:f,nodeType:j.nodeType||me.nodeType||"cache.t3.micro",engineVersion:j.engineVersion||"7.1",port:j.port||6379,numCacheClusters:j.numCacheNodes||2,automaticFailover:j.automaticFailoverEnabled!==!1,atRestEncryption:!0,transitEncryption:!0,snapshotRetentionDays:j.snapshotRetentionLimit||7,snapshotWindow:j.snapshotWindow,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(ht,yt),G&&St)this.builder.addResource(St,G);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[ht,"PrimaryEndPoint.Address"]},Description:"Redis primary endpoint address"}),this.builder.addOutput("CachePort",{Value:{"Fn::GetAtt":[ht,"PrimaryEndPoint.Port"]},Description:"Redis primary endpoint port"})}else if(ze==="memcached"){this.generateNetworkInfrastructure(u,f);let j=me.elasticache||{},{cluster:yt,subnetGroup:G,logicalId:ht,subnetGroupId:St}=_o.createMemcached({slug:u,environment:f,nodeType:j.nodeType||me.nodeType||"cache.t3.micro",engineVersion:j.engineVersion||"1.6.22",numCacheNodes:j.numCacheNodes||2,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(ht,yt),G&&St)this.builder.addResource(St,G);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[ht,"ConfigurationEndpoint.Address"]},Description:"Memcached configuration endpoint address"})}}let At=this.mergedConfig.infrastructure?.email;if(At){let ze=At.domain||this.mergedConfig.infrastructure?.dns?.domain;if(ze){let{emailIdentity:j,logicalId:yt}=m.verifyDomain({domain:ze,slug:u,environment:f,enableDkim:At.enableDkim!==!1,dkimKeyLength:At.dkimKeyLength||"RSA_2048_BIT"});if(this.builder.addResource(yt,j),At.configurationSet!==!1){let{configurationSet:St,logicalId:Wt}=m.createConfigurationSet({slug:u,environment:f});this.builder.addResource(Wt,St)}let G=At.hostedZoneId||this.mergedConfig.infrastructure?.dns?.hostedZoneId;if(G){if(At.enableDkim!==!1)for(let Kt=1;Kt<=3;Kt++){let Sr=`DkimRecord${Kt}${ze.replace(/\./g,"")}`;this.builder.addResource(Sr,{Type:"AWS::Route53::RecordSet",DependsOn:[yt],Properties:{HostedZoneId:G,Name:{"Fn::GetAtt":[yt,`DkimDNSTokenName${Kt}`]},Type:"CNAME",TTL:1800,ResourceRecords:[{"Fn::GetAtt":[yt,`DkimDNSTokenValue${Kt}`]}]}})}let{record:St,logicalId:Wt}=m.createSpfRecord(ze,G);this.builder.addResource(Wt,St);let{record:zt,logicalId:jt}=m.createDmarcRecord(ze,G,{policy:"none",reportingEmail:At.dmarcReportingEmail||`dmarc-reports@${ze}`});this.builder.addResource(jt,zt)}this.builder.addOutput("EmailDomain",{Value:ze,Description:"SES verified email domain"});let ht=At.server;if(ht?.enabled&&G){let St=this.mergedConfig.environments[f]?.region||this.mergedConfig.project.region||"us-east-1",Wt=`${u}-${f}-email`,{role:zt,policy:jt,roleLogicalId:Kt,policyLogicalId:Sr}=m.createEmailLambdaRole({slug:u,environment:f,s3BucketArn:`arn:aws:s3:::${Wt}`,sesIdentityArn:`arn:aws:ses:${St}:*:identity/${ze}`});this.builder.addResource(Kt,zt),this.builder.addResource(Sr,jt);let{function:Or,permission:Xt,logicalId:Pr,permissionLogicalId:Fr}=m.createInboundEmailLambda({slug:u,environment:f,roleArn:{"Fn::GetAtt":[Kt,"Arn"]},s3BucketName:Wt,organizedPrefix:"mailboxes/"});this.builder.addResource(Pr,Or),this.builder.addResource(Fr,Xt);let Qr=m.createInboundEmailSetup({slug:u,environment:f,domain:ze,s3BucketName:Wt,s3KeyPrefix:"inbox/",region:St,hostedZoneId:G,lambdaFunctionArn:{"Fn::GetAtt":[Pr,"Arn"]}});for(let[Nr,pn]of Object.entries(Qr.resources)){if(pn.Type==="AWS::SES::ReceiptRule")pn.DependsOn=[Fr,Pr];this.builder.addResource(Nr,pn)}this.builder.addOutput("InboundEmailLambda",{Value:{Ref:Pr},Description:"Inbound email processing Lambda function"}),this.builder.addOutput("EmailBucket",{Value:Wt,Description:"S3 bucket for email storage"});let Hr=this.serverEipLogicalIds.get("app");if(Hr&&G){let pn=`${ht?.subdomain||"mail"}.${ze}`,Wn=pn.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Wn}ARecord`,{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:G,Name:pn,Type:"A",TTL:"300",ResourceRecords:[{Ref:Hr}]}})}this.builder.addOutput("MailHost",{Value:`mail.${ze}`,Description:"Mail server hostname for SMTP/IMAP clients"})}}}let Lt=this.mergedConfig.infrastructure?.search;if(Lt){let ze=Lt.vpc?{subnetIds:[{Ref:"PublicSubnet1"}],securityGroupIds:[]}:void 0;if(ze)this.generateNetworkInfrastructure(u,f);let{domain:j,logicalId:yt}=ar.createDomain({slug:u,environment:f,engineVersion:Lt.engineVersion||"OpenSearch_2.11",instanceType:Lt.instanceType||"t3.small.search",instanceCount:Lt.instanceCount||1,volumeSize:Lt.volumeSize||10,volumeType:Lt.volumeType||"gp3",dedicatedMaster:Lt.dedicatedMaster||!1,dedicatedMasterType:Lt.dedicatedMasterType,dedicatedMasterCount:Lt.dedicatedMasterCount||3,multiAz:Lt.multiAz||!1,encryption:Lt.encryption||{atRest:!0,nodeToNode:!0},advancedSecurity:Lt.advancedSecurity,autoTune:Lt.autoTune!==!1,vpc:ze});this.builder.addResource(yt,j),this.builder.addOutput("SearchDomainEndpoint",{Value:{"Fn::GetAtt":[yt,"DomainEndpoint"]},Description:"OpenSearch domain endpoint"}),this.builder.addOutput("SearchDomainArn",{Value:{"Fn::GetAtt":[yt,"Arn"]},Description:"OpenSearch domain ARN"})}let mt=this.mergedConfig.infrastructure?.fileSystem;if(mt&&Object.keys(mt).length>0){this.generateNetworkInfrastructure(u,f);for(let[ze,j]of Object.entries(mt)){let{fileSystem:yt,logicalId:G}=Ze.createFileSystem({slug:`${u}-${ze}`,environment:f,encrypted:j.encrypted!==!1,performanceMode:j.performanceMode||"generalPurpose",throughputMode:j.throughputMode||"bursting",enableBackup:!0});this.builder.addResource(G,yt);let{securityGroup:ht,logicalId:St}=Ze.createEfsSecurityGroup({slug:`${u}-${ze}`,environment:f,vpcId:{Ref:"VPC"},sourceCidrBlocks:["10.0.0.0/16"]});this.builder.addResource(St,ht);let{mountTargets:Wt,logicalIds:zt}=Ze.createMultiAzMountTargets(G,{slug:`${u}-${ze}`,environment:f,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],securityGroupId:{Ref:St}});for(let jt=0;jt<Wt.length;jt++)this.builder.addResource(zt[jt],Wt[jt]);this.builder.addOutput(`${ze}FileSystemId`,{Value:{Ref:G},Description:`EFS file system ID for ${ze}`})}}let Me=this.mergedConfig.infrastructure?.ai;if(Me){let ze=Me.service||"ecs",j=Me.models||["*"],yt=Me.allowStreaming!==!1,G;if(ze==="ecs")G=Oe.enableBedrockForEcs({slug:u,environment:f,models:j,allowStreaming:yt});else if(ze==="ec2")G=Oe.enableBedrockForEc2({slug:u,environment:f,models:j,allowStreaming:yt});else if(ze==="lambda")G=Oe.enableBedrockForLambda({slug:u,environment:f,models:j,allowStreaming:yt});else G=Oe.createBedrockRole(ze,{slug:u,environment:f,models:j,allowStreaming:yt});if(this.builder.addResource(G.logicalId,G.role),Me.allowAsync){let{policy:ht,logicalId:St}=Oe.createBedrockPolicy({slug:u,environment:f,models:j,allowStreaming:yt,allowAsync:!0});this.builder.addResource(St,ht)}this.builder.addOutput("BedrockRoleArn",{Value:{"Fn::GetAtt":[G.logicalId,"Arn"]},Description:"IAM role ARN with Bedrock permissions"})}}generateRealtimeResources(u,f){let R=this.mergedConfig.infrastructure?.realtime;if(!R)return;let A=R.name||`${u}-${f}-realtime`,T=R.scaling||{},E=R.storage||{type:"dynamodb"},P=T.handlerMemory||256,L=T.handlerTimeout||30,z=`${u}${f}RealtimeConnections`.replace(/[^a-zA-Z0-9]/g,""),fe=`${u}${f}RealtimeChannels`.replace(/[^a-zA-Z0-9]/g,"");if(E.type==="dynamodb"){let zt=E.dynamodb||{},jt=zt.billingMode||"PAY_PER_REQUEST";this.builder.addResource(z,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-${f}-realtime-connections`,BillingMode:jt,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"},...jt==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:zt.readCapacity||5,WriteCapacityUnits:zt.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...jt==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:zt.readCapacity||5,WriteCapacityUnits:zt.writeCapacity||5}},...zt.pointInTimeRecovery&&{PointInTimeRecoverySpecification:{PointInTimeRecoveryEnabled:!0}},Tags:[{Key:"Name",Value:`${u}-${f}-realtime-connections`},{Key:"Environment",Value:f}]}}),this.builder.addResource(fe,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-${f}-realtime-channels`,BillingMode:jt,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"},...jt==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:zt.readCapacity||5,WriteCapacityUnits:zt.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...jt==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:zt.readCapacity||5,WriteCapacityUnits:zt.writeCapacity||5}},Tags:[{Key:"Name",Value:`${u}-${f}-realtime-channels`},{Key:"Environment",Value:f}]}})}let me=`${u}${f}RealtimeRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(me,{Type:"AWS::IAM::Role",Properties:{RoleName:`${u}-${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":[z,"Arn"]},{"Fn::Sub":`\${${z}.Arn}/index/*`},{"Fn::GetAtt":[fe,"Arn"]},{"Fn::Sub":`\${${fe}.Arn}/index/*`}]},{Effect:"Allow",Action:"execute-api:ManageConnections",Resource:{"Fn::Sub":"arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:*/*"}}]}}]}});let At=`${u}${f}RealtimeConnect`.replace(/[^a-zA-Z0-9]/g,""),Lt=`${u}${f}RealtimeDisconnect`.replace(/[^a-zA-Z0-9]/g,""),mt=`${u}${f}RealtimeMessage`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(At,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-${f}-realtime-connect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[me,"Arn"]},MemorySize:P,Timeout:L,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:z},CHANNELS_TABLE:{Ref:fe},ENVIRONMENT:f}},Code:{ZipFile:this.generateConnectHandlerCode()}},DependsOn:[me,z]}),this.builder.addResource(Lt,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-${f}-realtime-disconnect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[me,"Arn"]},MemorySize:P,Timeout:L,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:z},CHANNELS_TABLE:{Ref:fe},ENVIRONMENT:f}},Code:{ZipFile:this.generateDisconnectHandlerCode()}},DependsOn:[me,z,fe]}),this.builder.addResource(mt,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-${f}-realtime-message`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[me,"Arn"]},MemorySize:P,Timeout:L,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:z},CHANNELS_TABLE:{Ref:fe},ENVIRONMENT:f}},Code:{ZipFile:this.generateMessageHandlerCode()}},DependsOn:[me,z,fe]});let Me=`${u}${f}RealtimeApi`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Me,{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:A,ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action",Tags:{Name:A,Environment:f}}});let ze=`${At}Permission`,j=`${Lt}Permission`,yt=`${mt}Permission`;this.builder.addResource(ze,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:At},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Me}}/*/$connect`}}}),this.builder.addResource(j,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:Lt},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Me}}/*/$disconnect`}}}),this.builder.addResource(yt,{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}:\${${Me}}/*/$default`}}});let G=`${Me}ConnectInteg`,ht=`${Me}DisconnectInteg`,St=`${Me}MessageInteg`;this.builder.addResource(G,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Me},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${At}.Arn}/invocations`}}}),this.builder.addResource(ht,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Me},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${Lt}.Arn}/invocations`}}}),this.builder.addResource(St,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Me},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${mt}.Arn}/invocations`}}}),this.builder.addResource(`${Me}ConnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Me},RouteKey:"$connect",AuthorizationType:"NONE",Target:{"Fn::Sub":`integrations/\${${G}}`}}}),this.builder.addResource(`${Me}DisconnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Me},RouteKey:"$disconnect",Target:{"Fn::Sub":`integrations/\${${ht}}`}}}),this.builder.addResource(`${Me}DefaultRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Me},RouteKey:"$default",Target:{"Fn::Sub":`integrations/\${${St}}`}}});let Wt=`${Me}Stage`;if(this.builder.addResource(Wt,{Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:{Ref:Me},StageName:f,AutoDeploy:!0,DefaultRouteSettings:{ThrottlingBurstLimit:T.messagesPerSecond||1000,ThrottlingRateLimit:T.messagesPerSecond||1000}}}),R.monitoring?.enabled){let zt=R.monitoring,jt=zt.notificationTopicArn;if(!jt&&zt.notificationEmails?.length){let Kt=`${Me}AlarmTopic`;this.builder.addResource(Kt,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-${f}-realtime-alarms`,DisplayName:"Realtime WebSocket Alarms"}}),zt.notificationEmails.forEach((Sr,Or)=>{this.builder.addResource(`${Kt}Sub${Or}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:Kt},Protocol:"email",Endpoint:Sr}})}),jt={Ref:Kt}}if(zt.connectionThreshold)this.builder.addResource(`${Me}ConnectionAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${f}-realtime-connections`,AlarmDescription:`WebSocket connections exceed ${zt.connectionThreshold}`,MetricName:"ConnectCount",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:300,EvaluationPeriods:2,Threshold:zt.connectionThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:Me}}],...jt&&{AlarmActions:[jt]}}});if(zt.errorThreshold)this.builder.addResource(`${Me}ErrorAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${f}-realtime-errors`,AlarmDescription:`WebSocket errors exceed ${zt.errorThreshold}/min`,MetricName:"ExecutionError",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:60,EvaluationPeriods:3,Threshold:zt.errorThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:Me}}],...jt&&{AlarmActions:[jt]}}})}this.builder.addOutput(`${Me}Endpoint`,{Description:"WebSocket API endpoint URL",Value:{"Fn::Sub":`wss://\${${Me}}.execute-api.\${AWS::Region}.amazonaws.com/${f}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}}),this.builder.addOutput(`${Me}Id`,{Description:"WebSocket API ID",Value:{Ref:Me},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,7 +170,7 @@ catch (error) {
|
|
|
170
170
|
return { statusCode: 500, body: JSON.stringify({ error: 'Internal error' }) };
|
|
171
171
|
}
|
|
172
172
|
};
|
|
173
|
-
`.trim()}generateRealtimeServerResources(
|
|
173
|
+
`.trim()}generateRealtimeServerResources(u,f){let R=this.mergedConfig.infrastructure?.realtime;if(!R)return;let A=R.server||{},T=A.port||6001,E=A.instances||1,P=`${u}${f}RealtimeSG`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(P,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`Security group for ${u} realtime WebSocket server`,GroupName:`${u}-${f}-realtime-sg`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:T,ToPort:T,CidrIp:"0.0.0.0/0",Description:"WebSocket connections"},{IpProtocol:"tcp",FromPort:443,ToPort:443,CidrIp:"0.0.0.0/0",Description:"HTTPS/WSS connections"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${u}-${f}-realtime-sg`},{Key:"Environment",Value:f}]}});let L=`${u}${f}RealtimeTaskDef`.replace(/[^a-zA-Z0-9]/g,""),z=`${u}${f}RealtimeTaskRole`.replace(/[^a-zA-Z0-9]/g,""),fe=`${u}${f}RealtimeExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(fe,{Type:"AWS::IAM::Role",Properties:{RoleName:`${u}-${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(z,{Type:"AWS::IAM::Role",Properties:{RoleName:`${u}-${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 me=[{Name:"BROADCAST_HOST",Value:A.host||"0.0.0.0"},{Name:"BROADCAST_PORT",Value:String(T)},{Name:"NODE_ENV",Value:f==="production"?"production":"development"}];if(A.redis?.enabled){if(A.redis.useElastiCache)me.push({Name:"REDIS_HOST",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Address"]}}),me.push({Name:"REDIS_PORT",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Port"]}});else me.push({Name:"REDIS_HOST",Value:A.redis.host||"localhost"}),me.push({Name:"REDIS_PORT",Value:String(A.redis.port||6379)});if(A.redis.keyPrefix)me.push({Name:"REDIS_KEY_PREFIX",Value:A.redis.keyPrefix})}this.builder.addResource(L,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${u}-${f}-realtime`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:"512",Memory:"1024",ExecutionRoleArn:{"Fn::GetAtt":[fe,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[z,"Arn"]},ContainerDefinitions:[{Name:"realtime",Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${u}-realtime:latest`},Essential:!0,PortMappings:[{ContainerPort:T,Protocol:"tcp"}],Environment:me,LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":`/ecs/${u}-${f}-realtime`,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":"realtime"}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${T}${A.healthCheckPath||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${u}-${f}-realtime`},{Key:"Environment",Value:f}]},DependsOn:[fe,z]});let At=`${u}${f}RealtimeLogs`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(At,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/ecs/${u}-${f}-realtime`,RetentionInDays:30}});let Lt=`${u}${f}RealtimeService`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(Lt,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${u}-${f}-realtime`,Cluster:{Ref:"ECSCluster"},TaskDefinition:{Ref:L},DesiredCount:E,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:P}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},HealthCheckGracePeriodSeconds:60,Tags:[{Key:"Name",Value:`${u}-${f}-realtime`},{Key:"Environment",Value:f}]},DependsOn:[L,P,At]}),A.autoScaling){let mt=A.autoScaling,Me=`${u}${f}RealtimeScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(Me,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:mt.max||10,MinCapacity:mt.min||1,ResourceId:{"Fn::Sub":`service/\${ECSCluster}/${u}-${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:Lt}),mt.targetCPU)this.builder.addResource(`${u}${f}RealtimeCPUPolicy`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${u}-${f}-realtime-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Me},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:mt.targetCPU,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(R.monitoring?.enabled){let mt=R.monitoring,Me=mt.notificationTopicArn;if(!Me&&mt.notificationEmails?.length){let ze=`${u}${f}RealtimeAlarmTopic`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ze,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-${f}-realtime-alarms`,DisplayName:"Realtime Server Alarms"}}),mt.notificationEmails.forEach((j,yt)=>{this.builder.addResource(`${ze}Sub${yt}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:ze},Protocol:"email",Endpoint:j}})}),Me={Ref:ze}}this.builder.addResource(`${u}${f}RealtimeCPUAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${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:`${u}-${f}-realtime`}],...Me&&{AlarmActions:[Me]}},DependsOn:Lt}),this.builder.addResource(`${u}${f}RealtimeMemoryAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${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:`${u}-${f}-realtime`}],...Me&&{AlarmActions:[Me]}},DependsOn:Lt})}this.builder.addOutput(`${u}${f}RealtimeEndpoint`.replace(/[^a-zA-Z0-9]/g,""),{Description:"Realtime WebSocket server endpoint",Value:{"Fn::Sub":`wss://${u}-${f}-realtime.\${AWS::Region}.elb.amazonaws.com:${T}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}})}generateBroadcastConfig(){let u=this.mergedConfig.infrastructure?.realtime;if(!u||u.mode!=="server")return"";let f=u.server||{};return`import type { BroadcastConfig } from 'ts-broadcasting'
|
|
174
174
|
|
|
175
175
|
export default {
|
|
176
176
|
verbose: ${this.environment!=="production"},
|
|
@@ -219,7 +219,7 @@ ${f.loadManagement?.enabled?`
|
|
|
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 kg(u){let f=[],R=[];if(!u.AWSTemplateFormatVersion)f.push({path:"AWSTemplateFormatVersion",message:"AWSTemplateFormatVersion is required",severity:"error"});else if(u.AWSTemplateFormatVersion!=="2010-09-09")R.push({path:"AWSTemplateFormatVersion",message:'AWSTemplateFormatVersion should be "2010-09-09"',severity:"warning"});if(!u.Resources||Object.keys(u.Resources).length===0)f.push({path:"Resources",message:"At least one resource is required",severity:"error"});else for(let[A,T]of Object.entries(u.Resources))vg(A,T,f,R);if(u.Resources){let A=xg(u.Resources);if(A.length>0)f.push({path:"Resources",message:`Circular dependencies detected: ${A.join(" -> ")}`,severity:"error"})}if(u.Parameters)for(let[A,T]of Object.entries(u.Parameters))Og(A,T,f,R);if(u.Outputs)for(let[A,T]of Object.entries(u.Outputs))Ng(A,T,f,R);return{valid:f.length===0,errors:f,warnings:R}}function vg(u,f,R,A){if(!f.Type)R.push({path:`Resources.${u}.Type`,message:"Resource Type is required",severity:"error"});if(!/^[a-zA-Z0-9]+$/.test(u))A.push({path:`Resources.${u}`,message:"Logical ID should only contain alphanumeric characters",severity:"warning"});if(f.Type&&!f.Type.startsWith("AWS::")&&!f.Type.startsWith("Custom::"))R.push({path:`Resources.${u}.Type`,message:'Resource Type must start with "AWS::" or "Custom::"',severity:"error"});if(f.Properties){for(let[T,E]of Object.entries(f.Properties))if(E===void 0||E===null)A.push({path:`Resources.${u}.Properties.${T}`,message:"Property has undefined or null value",severity:"warning"})}if(f.DependsOn){if(typeof f.DependsOn==="string"){if(f.DependsOn===u)R.push({path:`Resources.${u}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}else if(Array.isArray(f.DependsOn)){if(f.DependsOn.includes(u))R.push({path:`Resources.${u}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}}}function Og(u,f,R,A){if(!f.Type)R.push({path:`Parameters.${u}.Type`,message:"Parameter Type is required",severity:"error"});let T=["String","Number","List<Number>","CommaDelimitedList","AWS::SSM::Parameter::Value<String>"];if(f.Type&&!T.includes(f.Type)&&!f.Type.startsWith("AWS::"))A.push({path:`Parameters.${u}.Type`,message:`Uncommon parameter type: ${f.Type}`,severity:"warning"});if(f.NoEcho&&f.Default)A.push({path:`Parameters.${u}`,message:"NoEcho parameters should not have default values",severity:"warning"})}function Ng(u,f,R,A){if(!f.Value)R.push({path:`Outputs.${u}.Value`,message:"Output Value is required",severity:"error"})}function xg(u){let f={};for(let[P,L]of Object.entries(u)){if(f[P]=[],L.DependsOn){if(typeof L.DependsOn==="string")f[P].push(L.DependsOn);else if(Array.isArray(L.DependsOn))f[P].push(...L.DependsOn)}let z=Fc(L);f[P].push(...z)}let R=new Set,A=new Set,T=[];function E(P,L){R.add(P),A.add(P),L.push(P);let z=f[P]||[];for(let fe of z)if(!R.has(fe)){if(E(fe,L))return!0}else if(A.has(fe)){let me=L.indexOf(fe);return T.push(...L.slice(me),fe),!0}return L.pop(),A.delete(P),!1}for(let P of Object.keys(f))if(!R.has(P)){if(E(P,[]))return T}return[]}function Fc(u,f=[]){if(typeof u!=="object"||u===null)return f;if(Array.isArray(u)){for(let R of u)Fc(R,f);return f}if(u.Ref&&typeof u.Ref==="string"&&!u.Ref.startsWith("AWS::"))f.push(u.Ref);if(u["Fn::GetAtt"]){let R=u["Fn::GetAtt"];if(Array.isArray(R)&&R.length>0)f.push(R[0])}for(let R of Object.values(u))Fc(R,f);return f}function Lg(u){let f=[],R=[],A=new TextEncoder().encode(u).length,T=51200,E=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 R.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:R}}function Fg(u){let f=[],R=[],A=u.Resources?Object.keys(u.Resources).length:0,T=u.Parameters?Object.keys(u.Parameters).length:0,E=u.Outputs?Object.keys(u.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)R.push({path:"Resources",message:`Template has ${A} resources. Consider using nested stacks for better organization.`,severity:"warning"});if(T>200)f.push({path:"Parameters",message:`Template has ${T} parameters, exceeding the limit of 200`,severity:"error"});if(E>200)f.push({path:"Outputs",message:`Template has ${E} outputs, exceeding the limit of 200`,severity:"error"});return{valid:f.length===0,errors:f,warnings:R}}function nR(u){let{domains:f,email:R,staging:A=!1,challengeType:T="http-01",certPath:E="/etc/letsencrypt/live",autoRenew:P=!0}=u,L=f[0],z=f.map((me)=>`-d ${me}`).join(" "),fe=A?"--staging":"";if(T==="http-01")return _g({domains:f,email:R,staging:A,certPath:E,autoRenew:P,domainFlags:z,stagingFlag:fe,primaryDomain:L});else{let me=u.dnsProvider?.provider||(u.hostedZoneId?"route53":void 0);return Mg({domains:f,email:R,staging:A,certPath:E,autoRenew:P,domainFlags:z,stagingFlag:fe,primaryDomain:L,hostedZoneId:u.hostedZoneId,dnsProvider:u.dnsProvider,dnsProviderType:me})}}function _g(u){let{email:f,certPath:R,autoRenew:A,domainFlags:T,stagingFlag:E,primaryDomain:P}=u;return`
|
|
223
223
|
# ==========================================
|
|
224
224
|
# Let's Encrypt Certificate Setup (HTTP-01)
|
|
225
225
|
# ==========================================
|
|
@@ -236,28 +236,28 @@ certbot certonly \\
|
|
|
236
236
|
--non-interactive \\
|
|
237
237
|
--agree-tos \\
|
|
238
238
|
--email ${f} \\
|
|
239
|
-
${
|
|
240
|
-
${
|
|
239
|
+
${E} \\
|
|
240
|
+
${T}
|
|
241
241
|
|
|
242
242
|
# Check if certificate was obtained
|
|
243
|
-
if [ -f "${
|
|
243
|
+
if [ -f "${R}/${P}/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 ${R}/${P}/fullchain.pem /etc/ssl/stacks/fullchain.pem
|
|
249
|
+
ln -sf ${R}/${P}/privkey.pem /etc/ssl/stacks/privkey.pem
|
|
250
|
+
ln -sf ${R}/${P}/cert.pem /etc/ssl/stacks/cert.pem
|
|
251
|
+
ln -sf ${R}/${P}/chain.pem /etc/ssl/stacks/chain.pem
|
|
252
252
|
else
|
|
253
253
|
echo "Failed to obtain certificate!"
|
|
254
254
|
fi
|
|
255
255
|
|
|
256
|
-
${A?
|
|
256
|
+
${A?_c(P):"# Auto-renewal disabled"}
|
|
257
257
|
|
|
258
258
|
# Restart the application
|
|
259
259
|
systemctl start stacks
|
|
260
|
-
`}function
|
|
260
|
+
`}function Mg(u){let{email:f,certPath:R,autoRenew:A,domainFlags:T,stagingFlag:E,primaryDomain:P,hostedZoneId:L,dnsProvider:z,dnsProviderType:fe}=u;if(fe==="route53"||L){if(!L)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
|
# ==========================================
|
|
@@ -271,48 +271,48 @@ certbot certonly \\
|
|
|
271
271
|
--non-interactive \\
|
|
272
272
|
--agree-tos \\
|
|
273
273
|
--email ${f} \\
|
|
274
|
-
${
|
|
275
|
-
${
|
|
274
|
+
${E} \\
|
|
275
|
+
${T}
|
|
276
276
|
|
|
277
277
|
# Check if certificate was obtained
|
|
278
|
-
if [ -f "${
|
|
278
|
+
if [ -f "${R}/${P}/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 ${R}/${P}/fullchain.pem /etc/ssl/stacks/fullchain.pem
|
|
284
|
+
ln -sf ${R}/${P}/privkey.pem /etc/ssl/stacks/privkey.pem
|
|
285
|
+
ln -sf ${R}/${P}/cert.pem /etc/ssl/stacks/cert.pem
|
|
286
|
+
ln -sf ${R}/${P}/chain.pem /etc/ssl/stacks/chain.pem
|
|
287
287
|
else
|
|
288
288
|
echo "Failed to obtain certificate!"
|
|
289
289
|
fi
|
|
290
290
|
|
|
291
|
-
${A?
|
|
292
|
-
`}if(!
|
|
291
|
+
${A?_c(P):"# Auto-renewal disabled"}
|
|
292
|
+
`}if(!z)throw Error("dnsProvider configuration is required for DNS-01 challenge with external DNS providers");let me=z.provider.toUpperCase(),At=Bg(z);return`
|
|
293
293
|
# ==========================================
|
|
294
|
-
# Let's Encrypt Certificate Setup (DNS-01 via ${
|
|
294
|
+
# Let's Encrypt Certificate Setup (DNS-01 via ${me})
|
|
295
295
|
# ==========================================
|
|
296
296
|
|
|
297
297
|
# Install certbot
|
|
298
298
|
dnf install -y certbot jq curl
|
|
299
299
|
|
|
300
|
-
${
|
|
300
|
+
${At}
|
|
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 ${me}
|
|
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 ${me}
|
|
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
|
+
${Wg(z)}
|
|
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 ${me}
|
|
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 ${me}
|
|
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
|
+
${Vg(z)}
|
|
335
335
|
CLEANUPHOOK
|
|
336
336
|
|
|
337
337
|
chmod +x /etc/letsencrypt/hooks/cleanup-hook.sh
|
|
@@ -345,36 +345,36 @@ certbot certonly \\
|
|
|
345
345
|
--non-interactive \\
|
|
346
346
|
--agree-tos \\
|
|
347
347
|
--email ${f} \\
|
|
348
|
-
${
|
|
349
|
-
${
|
|
348
|
+
${E} \\
|
|
349
|
+
${T}
|
|
350
350
|
|
|
351
351
|
# Check if certificate was obtained
|
|
352
|
-
if [ -f "${
|
|
352
|
+
if [ -f "${R}/${P}/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 ${R}/${P}/fullchain.pem /etc/ssl/stacks/fullchain.pem
|
|
358
|
+
ln -sf ${R}/${P}/privkey.pem /etc/ssl/stacks/privkey.pem
|
|
359
|
+
ln -sf ${R}/${P}/cert.pem /etc/ssl/stacks/cert.pem
|
|
360
|
+
ln -sf ${R}/${P}/chain.pem /etc/ssl/stacks/chain.pem
|
|
361
361
|
else
|
|
362
362
|
echo "Failed to obtain certificate!"
|
|
363
363
|
fi
|
|
364
364
|
|
|
365
|
-
${A?
|
|
366
|
-
`}function
|
|
365
|
+
${A?_c(P):"# Auto-renewal disabled"}
|
|
366
|
+
`}function Bg(u){switch(u.provider){case"porkbun":return`
|
|
367
367
|
# Porkbun API credentials
|
|
368
|
-
export PORKBUN_API_KEY="${
|
|
369
|
-
export PORKBUN_SECRET_KEY="${
|
|
368
|
+
export PORKBUN_API_KEY="${u.apiKey}"
|
|
369
|
+
export PORKBUN_SECRET_KEY="${u.secretKey}"
|
|
370
370
|
`;case"godaddy":return`
|
|
371
371
|
# GoDaddy API credentials
|
|
372
|
-
export GODADDY_API_KEY="${
|
|
373
|
-
export GODADDY_API_SECRET="${
|
|
374
|
-
export GODADDY_ENV="${
|
|
372
|
+
export GODADDY_API_KEY="${u.apiKey}"
|
|
373
|
+
export GODADDY_API_SECRET="${u.apiSecret}"
|
|
374
|
+
export GODADDY_ENV="${u.environment||"production"}"
|
|
375
375
|
`;case"route53":return`
|
|
376
376
|
# Route53 uses IAM role credentials
|
|
377
|
-
`;default:return""}}function
|
|
377
|
+
`;default:return""}}function Wg(u){switch(u.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 Vg(u){switch(u.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 _c(u){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 iR(u){let{httpPort:f=80,httpsPort:R=443,certPath:A="/etc/ssl/stacks",redirectHttp:T=!0}=u;return`
|
|
519
519
|
// HTTPS Server with Let's Encrypt certificates
|
|
520
520
|
import { existsSync } from 'node:fs'
|
|
521
521
|
|
|
522
522
|
const CERT_PATH = '${A}'
|
|
523
523
|
const HTTP_PORT = ${f}
|
|
524
|
-
const HTTPS_PORT = ${
|
|
524
|
+
const HTTPS_PORT = ${R}
|
|
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
|
+
${T?`
|
|
545
545
|
// Start HTTP server for redirect
|
|
546
546
|
const httpServer = Bun.serve({
|
|
547
547
|
port: HTTP_PORT,
|
|
@@ -601,5 +601,5 @@ async function handleRequest(request: Request): Promise<Response> {
|
|
|
601
601
|
// Implement your request handling here
|
|
602
602
|
return new Response('Hello from Stacks!')
|
|
603
603
|
}
|
|
604
|
-
`}async function
|
|
605
|
-
`).filter((B)=>!B.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=qu("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 B=this.base64UrlEncode(JSON.stringify(w)),v=f===""?"":this.base64UrlEncode(JSON.stringify(f)),ce=`${B}.${v}`,de=Vf("SHA256");de.update(ce);let ct=de.sign(this.accountKey),xe=ct.subarray(4,4+ct[3]),Ut=4+ct[3]+2,Qt=ct.subarray(Ut,Ut+ct[Ut-1]),gt=Buffer.alloc(32),lt=Buffer.alloc(32);xe.copy(gt,32-xe.length),Qt.copy(lt,32-Qt.length);let ut=Buffer.concat([gt,lt]);return JSON.stringify({protected:B,payload:v,signature:this.base64UrlEncode(ut)})}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 B,v=A.headers.get("content-type");if(v?.includes("application/json")||v?.includes("application/problem+json"))B=await A.json();else B=await A.text();if(!A.ok)throw Error(`ACME request failed: ${JSON.stringify(B)}`);return{body:B,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((B)=>({type:"dns",value:B}))}),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((B)=>B.type==="http-01"||B.type==="dns-01").map((B)=>{let v=`${B.token}.${A}`;if(B.type==="http-01")return{type:"http-01",token:B.token,keyAuthorization:v,identifier:`/.well-known/acme-challenge/${B.token}`};else{let ce=this.base64UrlEncode(qu("sha256").update(v).digest());return{type:"dns-01",token:B.token,keyAuthorization:v,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}=eg("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"))}),B=w.certificate;if(!B)throw Error("Certificate not immediately available - polling not implemented");let ce=await(await fetch(B)).text(),de=ce.split(/(?=-----BEGIN CERTIFICATE-----)/g),ct=de[0],xe=de.slice(1).join("");return{certificate:ct,privateKey:A,chain:xe,fullchain:ce,expiresAt:new Date(Date.now()+7776000000)}}getAccountKey(){return this.accountKey}}var wn=(l)=>l===void 0?void 0:l?"on":"off";function Lc(l){let f={ssl:l.ssl,always_use_https:wn(l.alwaysUseHttps),automatic_https_rewrites:wn(l.automaticHttpsRewrites),min_tls_version:l.minTlsVersion,tls_1_3:wn(l.tls13),brotli:wn(l.brotli),http3:wn(l.http3),"0rtt":wn(l.zeroRtt),early_hints:wn(l.earlyHints),browser_cache_ttl:l.browserCacheTtl,always_online:wn(l.alwaysOnline),websockets:wn(l.websockets),email_obfuscation:wn(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 Ts={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 jf}from"node:tls";async function Fc(l){let{address:f,serverName:C,port:A=443,timeoutMs:w=5000}=l;return new Promise((B)=>{let v=!1,ce=(ct)=>{if(v)return;v=!0;try{de.destroy()}catch{}B(ct)},de=jf({host:f,port:A,servername:C,rejectUnauthorized:!1,timeout:w});de.once("secureConnect",()=>{if(de.authorized){ce({reachable:!0,trusted:!0});return}ce({reachable:!0,trusted:!1,reason:de.authorizationError?String(de.authorizationError):"origin certificate is not trusted for this hostname"})}),de.once("timeout",()=>{ce({reachable:!1,trusted:!1,reason:`no TLS handshake within ${w}ms`})}),de.once("error",(ct)=>{ce({reachable:!1,trusted:!1,reason:ct.message})})})}function Kf(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 B=w.slice(2);if(!C.endsWith(`.${B}`))return!1;return!C.slice(0,C.length-B.length-1).includes(".")})}async function qf(l){let{provider:f,zone:C,hosts:A,ipv4:w,ipv6:B,proxied:v=!0,settings:ce=Ts,cache:de,originGuard:ct,purge:xe=!0,ttl:Ut=300,skipOriginProbe:Qt=!1,skipEdgeCertificateCheck:gt=!1}=l,lt={records:[],settingsChanged:[],cacheRules:0,originGuard:!1,purged:!1,deferredProxy:[],warnings:[]};if(A.length===0)return lt;let ut=[],Ee=v&&!gt?await f.listEdgeCertificateHosts(C):null;for(let ve of A){let Pt=v;if(Pt&&Ee&&!Kf(Ee,ve)){Pt=!1;let lr=Ee.length===0?"the zone has no active edge certificate yet":`no active edge certificate covers it (${Ee.join(", ")})`;lt.deferredProxy.push({host:ve,reason:lr}),lt.warnings.push(`${ve}: publishing DNS-only — ${lr}. 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(Pt&&!Qt){let lr=await Fc({address:w,serverName:ve});if(!lr.trusted){Pt=!1;let Cr=lr.reason||"origin is not serving a trusted certificate";lt.deferredProxy.push({host:ve,reason:Cr}),lt.warnings.push(`${ve}: publishing DNS-only for now — the origin does not yet serve a certificate this proxy can verify (${Cr}). 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(Pt)ut.push(ve);let Ht=[{type:"A",content:w}];if(B&&Un(ve))Ht.push({type:"AAAA",content:B});for(let{type:lr,content:Cr}of Ht){let br=await f.upsertRecord(C,{name:ve,type:lr,content:Cr,ttl:Ut,proxied:Pt});if(br.success)lt.records.push({host:ve,type:lr,content:Cr,proxied:Pt});else lt.warnings.push(`${ve} ${lr} → ${Cr} failed: ${br.message||"unknown provider error"}`)}}if(ut.length===0){if(v)lt.warnings.push("No host is proxied yet, so zone settings, cache rules and purge were skipped — they only take effect through the proxy.");return lt}try{let ve=Lc(ce),Pt=await f.applyZoneSettings(C,ve);lt.settingsChanged=Pt.changed;for(let Ht of Pt.failed)lt.warnings.push(`zone setting '${Ht.id}' could not be applied: ${Ht.error}`)}catch(ve){lt.warnings.push(`zone settings could not be read: ${ve instanceof Error?ve.message:String(ve)}`)}let Ft=gc(ut,de);if(Ft.length>0){let ve=await f.putManagedPhaseRules(C,"http_request_cache_settings",Ft);if(ve.success)lt.cacheRules=Ft.length;else lt.warnings.push(`cache rules could not be written: ${ve.message}`)}if(ct){let ve=pc(ut,ct.header,ct.value);if(ve.length>0){let Pt=await f.putManagedPhaseRules(C,"http_request_late_transform",ve);if(Pt.success)lt.originGuard=!0;else lt.warnings.push(`origin guard header could not be written: ${Pt.message}. `+"The gateway will reject requests that lack it — disable the guard or grant the token Transform Rules: Edit.")}}if(xe){if(lt.purged=await f.purgeCache(C,{hosts:ut}),!lt.purged)lt.warnings.push("edge cache purge failed — new content may take until TTL expiry to appear.")}return lt}var Jf=(l)=>process.env[l];function ng(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 eh(l,f={}){let C=f.env??Jf,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 B=C("CLOUDFLARE_API_TOKEN");if(!B)return w.push("CLOUDFLARE_API_TOKEN is not set — the Cloudflare CDN cannot be reconciled."),{plan:null,errors:w};let v=l.sites??{},ce=A.frontedHosts?.length?[...new Set(A.frontedHosts.map((Qt)=>Qt.toLowerCase()))]:qn(v,{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 de=l.infrastructure?.dns?.domain,ct=new Set(ce.map((Qt)=>ng(Qt,de)));if(ct.size>1)return w.push(`Fronted hosts span more than one zone (${[...ct].join(", ")}). A Cloudflare zone is configured as a unit, so run one CDN config per zone.`),{plan:null,errors:w};let xe=A.cloudflare??{},Ut=A.secret?{header:A.secretHeader??"X-Origin-Verify",value:A.secret}:void 0;return{plan:{zone:[...ct][0],hosts:ce,apiToken:B,zoneId:xe.zoneId??C("CLOUDFLARE_ZONE_ID"),accountId:xe.accountId??C("CLOUDFLARE_ACCOUNT_ID"),proxied:xe.proxied!==!1,settings:xe.settings??Ts,cache:xe.cache,originGuard:Ut,purge:xe.purgeOnDeploy!==!1,skipOriginProbe:xe.skipOriginProbe===!0},errors:w}}var th=26214400;var rh=new Set(["/_headers","/_redirects","/_routes.json","/_worker.js"]);class ig{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 oc(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 oc("POST","/pages/assets/check-missing",`Bearer ${l}`,{hashes:f});return new Set(C)}async upsertHashes(l,f){await oc("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:ih(A.extension)},base64:!0}));await oc("POST","/pages/assets/upload",`Bearer ${l}`,C)}async createDeployment(l,f,C){let A={};for(let B of f)A[B.path]=B.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 sg(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((de)=>de.hash)),w=f.filter((de)=>A.has(de.hash)),B=[];for(let de=0;de<w.length;de+=100)B.push(w.slice(de,de+100));let v=0;for(let de=0;de<B.length;de+=4){let ct=B.slice(de,de+4);await Promise.all(ct.map((xe)=>this.uploadBatch(C,xe))),v+=ct.reduce((xe,Ut)=>xe+Ut.length,0),l.onProgress?.(v,w.length)}return await this.upsertHashes(C,f.map((de)=>de.hash)),{deployment:await this.createDeployment(l.project,f,l.branch),total:f.length,uploaded:w.length,uploadedBytes:w.reduce((de,ct)=>de+ct.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 nh(l,f){return{type:"CNAME",name:l,value:f.endsWith(".pages.dev")?f:`${f}.pages.dev`,ttl:1,proxied:!0}}async function og(l,f){let{blake3:C}=await import("./chunk-rpng90t9.js").then((m)=>cS(m.default,1));return(await C(l+f)).slice(0,32)}async function sg(l){let{readdir:f}=await import("node:fs/promises"),{join:C,relative:A,sep:w}=await import("node:path"),B=[];async function v(ce){let de=await f(ce,{withFileTypes:!0});for(let ct of de){let xe=C(ce,ct.name);if(ct.isDirectory()){await v(xe);continue}if(!ct.isFile())continue;let Ut=`/${A(l,xe).split(w).join("/")}`;if(rh.has(Ut))continue;let Qt=await Bun.file(xe).bytes();if(Qt.byteLength>26214400)throw Error(`${Ut} is ${Qt.byteLength} bytes, over the Cloudflare Pages limit of 26214400`);let gt=Buffer.from(Qt).toString("base64"),lt=ct.name.lastIndexOf("."),ut=lt>0?ct.name.slice(lt+1):"";B.push({path:Ut,hash:await og(gt,ut),base64:gt,extension:ut,size:Qt.byteLength})}}return await v(l),B.sort((ce,de)=>ce.path.localeCompare(de.path)),B}function ih(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 oc(l,f,C,A){let w={Authorization:C},B;if(A instanceof FormData)B=A;else if(A!==void 0)w["Content-Type"]="application/json",B=JSON.stringify(A);let v=await fetch(`https://api.cloudflare.com/client/v4${f}`,{method:l,headers:w,body:B}),ce=await v.text(),de;try{de=JSON.parse(ce)}catch{throw Error(`Cloudflare Pages API returned ${v.status} with a non-JSON body: ${ce.slice(0,200)}`)}if(!de.success){let ct=(de.errors??[]).map((xe)=>`${xe.code}: ${xe.message}`).join(", ");throw Error(`Cloudflare Pages API error (${v.status}): ${ct||ce.slice(0,200)}`)}return de.result}import{createHash as oh}from"node:crypto";var hg="https://api.cloudflare.com/client/v4",yg=10042,sh=10006,ah=10059;class ti extends Error{status;errors;constructor(l,f,C=[]){super(l);this.name="R2ApiError",this.status=f,this.errors=C}hasCode(l){return this.errors.some((f)=>f.code===l)}}class jn extends ti{accountId;constructor(l,f,C=[]){super(`R2 is not enabled on Cloudflare account ${l}. Enable it once in the Cloudflare dashboard (R2 Object Storage, then follow the prompt to activate it), then re-run the deploy.`,f,C);this.name="R2NotEnabledError",this.accountId=l}}class Si{name="cloudflare-r2";apiToken;accountId;fetchImpl;constructor(l){if(!l.apiToken)throw Error("Cloudflare R2 needs an API token");if(!l.accountId)throw Error("Cloudflare R2 needs an account id");this.apiToken=l.apiToken,this.accountId=l.accountId,this.fetchImpl=l.fetch??((f,C)=>fetch(f,C))}async requestEnvelope(l,f,C,A={}){let w={Authorization:`Bearer ${this.apiToken}`};if(C!==void 0)w["Content-Type"]="application/json";if(A.jurisdiction&&A.jurisdiction!=="default")w["cf-r2-jurisdiction"]=A.jurisdiction;let B=await this.fetchImpl(`${hg}/accounts/${this.accountId}/r2${f}`,{method:l,headers:w,body:C===void 0?void 0:JSON.stringify(C)}),v=await B.text(),ce;try{ce=JSON.parse(v)}catch{throw new ti(`Cloudflare R2 API returned ${B.status} with a non-JSON body: ${v.slice(0,200)}`,B.status)}if(!ce.success){let de=ce.errors??[];if(de.some((xe)=>xe.code===yg))throw new jn(this.accountId,B.status,de);let ct=de.map((xe)=>`${xe.code}: ${xe.message}`).join(", ");throw new ti(`Cloudflare R2 API error (${B.status}) on ${l} ${f}: ${ct||v.slice(0,200)}`,B.status,de)}return ce}async request(l,f,C,A){return(await this.requestEnvelope(l,f,C,A)).result}bucketPath(l){return`/buckets/${encodeURIComponent(l)}`}async listBuckets(l={}){let f=[],C;do{let A=new URLSearchParams({per_page:"1000"});if(C)A.set("cursor",C);let w=await this.requestEnvelope("GET",`/buckets?${A}`,void 0,l),B=w.result?.buckets??[];f.push(...B),C=B.length>0?w.result_info?.cursor||void 0:void 0}while(C);return f}async getBucket(l,f={}){try{return await this.request("GET",this.bucketPath(l),void 0,f)}catch(C){if(C instanceof jn)throw C;if(C instanceof ti&&(C.hasCode(sh)||C.status===404))return null;throw C}}async ensureBucket(l,f={}){let C={jurisdiction:f.jurisdiction},A=await this.getBucket(l,C);if(A)return{bucket:A,created:!1};let w={name:l};if(f.locationHint)w.locationHint=f.locationHint;let B=await this.request("POST","/buckets",w,C);return{bucket:{...B,name:B?.name||l},created:!0}}async getCors(l,f={}){try{return(await this.request("GET",`${this.bucketPath(l)}/cors`,void 0,f))?.rules??[]}catch(C){if(C instanceof ti&&!(C instanceof jn)&&(C.hasCode(ah)||C.status===404))return[];throw C}}async putCors(l,f,C={}){if(f.length===0){await this.request("DELETE",`${this.bucketPath(l)}/cors`,void 0,C);return}await this.request("PUT",`${this.bucketPath(l)}/cors`,{rules:f},C)}async ensureCors(l,f,C={}){let A=await this.getCors(l,C);if(cc(A,f))return!1;return await this.putCors(l,f,C),!0}async getLifecycle(l,f={}){return(await this.request("GET",`${this.bucketPath(l)}/lifecycle`,void 0,f))?.rules??[]}async putLifecycle(l,f,C={}){await this.request("PUT",`${this.bucketPath(l)}/lifecycle`,{rules:f},C)}async ensureLifecycle(l,f,C={}){let A=await this.getLifecycle(l,C);if(Cc(A,f))return!1;return await this.putLifecycle(l,f,C),!0}async listCustomDomains(l,f={}){return(await this.request("GET",`${this.bucketPath(l)}/domains/custom`,void 0,f))?.domains??[]}async attachCustomDomain(l,f,C={}){return this.request("POST",`${this.bucketPath(l)}/domains/custom`,{domain:f.domain,zoneId:f.zoneId,enabled:f.enabled??!0,minTLS:f.minTLS??"1.2"},C)}async updateCustomDomain(l,f,C,A={}){return this.request("PUT",`${this.bucketPath(l)}/domains/custom/${encodeURIComponent(f)}`,C,A)}async ensureCustomDomain(l,f,C={},A){let w=f.minTLS??"1.2",v=(A??await this.listCustomDomains(l,C)).find((ct)=>ct.domain.toLowerCase()===f.domain.toLowerCase());if(!v){let ct=await this.attachCustomDomain(l,{...f,minTLS:w,enabled:!0},C);return{action:"attached",domain:{...ct,domain:ct?.domain||f.domain}}}let ce=v.minTLS??"1.0";if(v.enabled&&ce===w)return{action:"unchanged",domain:v};let de=await this.updateCustomDomain(l,v.domain,{enabled:!0,minTLS:w},C);return{action:"updated",domain:{...v,...de}}}async getManagedDomain(l,f={}){return this.request("GET",`${this.bucketPath(l)}/domains/managed`,void 0,f)}async setManagedDomain(l,f,C={}){let A=await this.getManagedDomain(l,C);if(A?.enabled===f)return{changed:!1,domain:A};return{changed:!0,domain:await this.request("PUT",`${this.bucketPath(l)}/domains/managed`,{enabled:f},C)}}}function Cg(l){return`https://${l}.r2.cloudflarestorage.com`}async function ch(l){let{apiToken:f,accountId:C}=l;if(!f)throw Error("r2S3Credentials needs an API token");if(!C)throw Error("r2S3Credentials needs an account id");let A=l.fetch??((v,ce)=>fetch(v,ce)),w=[],B;for(let v of[`/accounts/${C}/tokens/verify`,"/user/tokens/verify"]){let ce=await A(`${hg}${v}`,{method:"GET",headers:{Authorization:`Bearer ${f}`}}),de=await ce.json().catch(()=>null);if(ce.ok&&de?.success&&de.result?.id){B=de.result.id;break}let ct=de?.errors?.map((xe)=>`${xe.code}: ${xe.message}`).join(", ");w.push(`${v} -> ${ce.status}${ct?` (${ct})`:""}`)}if(!B)throw Error(`Could not verify the Cloudflare API token to derive R2 credentials: ${w.join("; ")}`);return{accessKeyId:B,secretAccessKey:oh("sha256").update(f).digest("hex"),endpoint:Cg(C),region:"auto"}}function ws(l){if(Array.isArray(l))return`[${l.map(ws).join(",")}]`;if(l&&typeof l==="object")return`{${Object.entries(l).filter(([,C])=>C!==void 0).sort(([C],[A])=>C.localeCompare(A)).map(([C,A])=>`${JSON.stringify(C)}:${ws(A)}`).join(",")}}`;return JSON.stringify(l)}function fg(l,f){let C=(A)=>A&&A.length>0?[...A].map(String).sort():void 0;return{id:f?l.id:void 0,allowed:{origins:C(l.allowed?.origins),methods:C(l.allowed?.methods?.map((A)=>A.toUpperCase())),headers:C(l.allowed?.headers?.map((A)=>A.toLowerCase()))},exposeHeaders:C(l.exposeHeaders?.map((A)=>A.toLowerCase())),maxAgeSeconds:l.maxAgeSeconds}}function cc(l,f){if(l.length!==f.length)return!1;return f.every((C,A)=>{let w=C.id!==void 0;return ws(fg(l[A],w))===ws(fg(C,w))})}function Cc(l,f){if(l.length!==f.length)return!1;let C=(A)=>ws([...A].map((w)=>({...w,storageClassTransitions:w.storageClassTransitions?.length?w.storageClassTransitions:void 0})).sort((w,B)=>w.id.localeCompare(B.id)));return C(l)===C(f)}var lh="r2 cache",uh=/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/;async function dh(l,f={}){let C=f.log??(()=>{}),A={buckets:[],warnings:[]},w=l.infrastructure?.r2??l.r2,B=Object.entries(w?.buckets??{});if(B.length===0)return C("R2: no buckets declared, skipping."),A;if(!f.apiToken||!f.accountId){let xe=[!f.apiToken&&"CLOUDFLARE_API_TOKEN",!f.accountId&&"CLOUDFLARE_ACCOUNT_ID"].filter(Boolean).join(" and "),Ut=`R2: ${B.length} bucket(s) declared but ${xe} is not set, skipping.`;return C(Ut),A.warnings.push(Ut),A}let v=f.dryRun===!0,ce=new Si({apiToken:f.apiToken,accountId:f.accountId,fetch:f.fetch}),de=new M(f.apiToken,{zoneId:f.zoneId,accountId:f.accountId}),ct=new Map;for(let[xe,Ut]of B){let Qt=Ut?.name;if(!Qt||!uh.test(Qt)){A.warnings.push(`R2: bucket '${xe}' has an invalid name '${Qt??""}' (3-63 chars: lowercase letters, digits, hyphens), skipping.`);continue}C(`R2: ${v?"checking":"reconciling"} bucket ${Qt}...`);let gt={name:Qt,changes:[],domains:[]};if(A.buckets.push(gt),await ph(Ut,{r2:ce,cloudflare:de,dryRun:v,summary:gt,warnings:A.warnings,claimed:ct,log:C}),gt.changes.length===0)C(`R2: ${Qt} is in sync.`);else for(let lt of gt.changes)C(`R2: ${Qt}: ${lt}`)}return A}async function ph(l,f){let{r2:C,dryRun:A,summary:w,warnings:B}=f,v=l.name,ce={jurisdiction:l.jurisdiction},de=(gt,lt)=>{let ut=A?lt&&`would ${lt}`:gt;if(ut)w.changes.push(ut)},ct;if(A)ct=await C.getBucket(v,ce)!==null;else{let{created:gt}=await C.ensureBucket(v,{locationHint:l.locationHint,jurisdiction:l.jurisdiction});if(ct=!0,gt)de("created","")}if(!ct)de("","create bucket");let xe=fh(l.customDomains);await Is(f,`cors on ${v}`,async()=>{if(!l.cors)return;if(!ct){de("cors updated","set cors");return}let gt=await C.getCors(v,ce);if(cc(gt,l.cors))return;if(!A)await C.putCors(v,l.cors,ce);de(l.cors.length===0?"cors removed":"cors updated",l.cors.length===0?"remove cors":"update cors")}),await Is(f,`lifecycle on ${v}`,async()=>{if(!l.lifecycle)return;let gt=l.lifecycle.map(bg);if(ct){let lt=await C.getLifecycle(v,ce);if(Cc(lt,gt))return}if(!A)await C.putLifecycle(v,gt,ce);de("lifecycle updated","update lifecycle")}),await Is(f,`r2.dev URL on ${v}`,async()=>{let gt=l.publicDevUrl===!0;if(!ct){if(gt)de("r2.dev URL enabled","enable r2.dev URL");return}if((await C.getManagedDomain(v,ce))?.enabled===gt)return;if(!A)await C.setManagedDomain(v,gt,ce);de(gt?"r2.dev URL enabled":"r2.dev URL disabled",gt?"enable r2.dev URL":"disable r2.dev URL")});let Ut=[];if(xe.length>0&&ct)try{Ut=await C.listCustomDomains(v,ce)}catch(gt){if(gt instanceof jn)throw gt;B.push(`R2: could not list custom domains on ${v}: ${Bc(gt)}`)}let Qt=new Map;for(let{domain:gt,minTLS:lt}of xe){let ut=f.claimed.get(gt);if(ut&&ut!==v){B.push(`R2: ${gt} is declared on both ${ut} and ${v}; leaving it on ${ut}.`);continue}f.claimed.set(gt,v);let Ee=Ut.find((ve)=>ve.domain.toLowerCase()===gt),Ft=lt??"1.2";if(Ee&&Ee.enabled&&(Ee.minTLS??"1.0")===Ft){if(w.domains.push({domain:gt,status:Mc(Ee)}),Ee.zoneId)Qt.set(gt,Ee.zoneId);continue}await Is(f,`custom domain ${gt} on ${v}`,async()=>{if(Ee){if(!A)await C.updateCustomDomain(v,Ee.domain,{enabled:!0,minTLS:Ft},ce);if(de(`custom domain ${gt} updated`,`update custom domain ${gt}`),w.domains.push({domain:gt,status:Mc({...Ee,enabled:!0})}),Ee.zoneId)Qt.set(gt,Ee.zoneId);return}let ve=await f.cloudflare.zoneIdFor(gt);if(Qt.set(gt,ve),!A)await C.ensureCustomDomain(v,{domain:gt,zoneId:ve,minTLS:Ft},ce,Ut);de(`custom domain ${gt} attached`,`attach custom domain ${gt}`),w.domains.push({domain:gt,status:A?"not attached":"pending"})},()=>w.domains.push({domain:gt,status:"error"}))}if(l.cache&&xe.length>0)await mh(l,xe.map((gt)=>gt.domain).filter((gt)=>f.claimed.get(gt)===v),Qt,f,de)}async function mh(l,f,C,A,w){let B=Sg(l.cache);if(!B||f.length===0)return;let v=new Map;for(let ce of f){let de=C.get(ce);if(!de)try{de=await A.cloudflare.zoneIdFor(ce)}catch(ct){A.warnings.push(`R2: could not resolve the zone for ${ce}, cache rule skipped: ${Bc(ct)}`);continue}v.set(de,[...v.get(de)??[],ce])}for(let ce of v.values()){let de={action:"set_cache_settings",description:`${Lt} ${lh}`,expression:`(${_t(ce)})`,enabled:!0,action_parameters:B};await Is(A,`cache rule for ${ce.join(", ")}`,async()=>{let ct=await A.cloudflare.getPhaseRules(ce[0],"http_request_cache_settings");if(Rg(ct,de))return;if(!A.dryRun){let xe=await A.cloudflare.putManagedPhaseRules(ce[0],"http_request_cache_settings",[de]);if(!xe.success)throw Error(xe.message||"cache rule write failed")}w(`cache rule updated for ${ce.join(", ")}`,`update cache rule for ${ce.join(", ")}`)})}}function Sg(l){if(l.edgeTtl===void 0&&l.browserTtl===void 0)return null;let f={cache:!0};if(l.edgeTtl!==void 0)f.edge_ttl={mode:"override_origin",default:l.edgeTtl};if(l.browserTtl!==void 0)f.browser_ttl={mode:"override_origin",default:l.browserTtl};return f}function Rg(l,f){let C=$t(f.expression),A=_n(f.expression),w=(ce)=>(ce.description||"").startsWith(Lt),B=(ce)=>ce.action===f.action&&ce.description===f.description&&(ce.enabled??!0)===(f.enabled??!0)&&_n(ce.expression)===A&&Sc(ce.action_parameters)===Sc(f.action_parameters),v=!1;for(let ce of l){if(!w(ce))continue;let de=$t(ce.expression);if(!C.some((xe)=>de.includes(xe)))continue;if(B(ce)&&C.every((xe)=>de.includes(xe))&&!v){v=!0;continue}return!1}return v}function bg(l){let f={id:l.id,enabled:l.enabled??!0,conditions:{prefix:l.prefix??""}};if(l.expireAfterDays!==void 0)f.deleteObjectsTransition={condition:{type:"Age",maxAge:_c(l.expireAfterDays)}};else if(l.expireOn!==void 0)f.deleteObjectsTransition={condition:{type:"Date",date:l.expireOn}};if(l.abortMultipartUploadsAfterDays!==void 0)f.abortMultipartUploadsTransition={condition:{type:"Age",maxAge:_c(l.abortMultipartUploadsAfterDays)}};if(l.infrequentAccessAfterDays!==void 0)f.storageClassTransitions=[{storageClass:"InfrequentAccess",condition:{type:"Age",maxAge:_c(l.infrequentAccessAfterDays)}}];return f}function _c(l){return Math.round(l*86400)}function fh(l){let f=new Set,C=[];for(let A of l??[]){let w=typeof A==="string"?{domain:A}:A,B=w.domain?.trim().replace(/\.$/,"").toLowerCase();if(!B||f.has(B))continue;f.add(B),C.push({domain:B,minTLS:w.minTLS})}return C}function Mc(l){if(!l.enabled)return"disabled";let f=l.status?.ownership,C=l.status?.ssl;if(f==="active"&&C==="active")return"active";for(let A of[f,C])if(A==="error"||A==="blocked"||A==="deactivated")return A;return"pending"}async function Is(l,f,C,A){try{await C()}catch(w){if(w instanceof jn)throw w;l.warnings.push(`R2: ${f} failed: ${Bc(w)}`),A?.()}}function Bc(l){return l instanceof Error?l.message:String(l)}function Sc(l){if(Array.isArray(l))return`[${l.map(Sc).join(",")}]`;if(l&&typeof l==="object")return`{${Object.entries(l).filter(([,C])=>C!==void 0).sort(([C],[A])=>C.localeCompare(A)).map(([C,A])=>`${JSON.stringify(C)}:${Sc(A)}`).join(",")}}`;return JSON.stringify(l)}import{basename as Ah,extname as Th}from"node:path";import{createHash as hh}from"node:crypto";var yh="https://api.cloudflare.com/client/v4",Qn="TS_CLOUD_CONTENT_HASH",Gs="2025-09-01",xl="application/javascript+module",Ch=10007,Sh=[1e4,9109];class ls extends Error{status;errors;constructor(l,f,C=[]){super(l);this.name="WorkersApiError",this.status=f,this.errors=C}hasCode(l){return this.errors.some((f)=>f.code===l)}}class Rc extends ls{permission;constructor(l,f,C,A=[]){super(`The Cloudflare API token is missing the "${l}" permission (${f}). Edit the token in the Cloudflare dashboard (My Profile, API Tokens), add it, then re-run the deploy.`,C,A);this.name="WorkersPermissionError",this.permission=l}}class Tc{name="cloudflare-workers";apiToken;accountId;fetchImpl;constructor(l){if(!l.apiToken)throw Error("Cloudflare Workers needs an API token");if(!l.accountId)throw Error("Cloudflare Workers needs an account id");this.apiToken=l.apiToken,this.accountId=l.accountId,this.fetchImpl=l.fetch??((f,C)=>fetch(f,C))}async request(l,f,C){let A={Authorization:`Bearer ${this.apiToken}`},w;if(C instanceof FormData)w=C;else if(C!==void 0)A["Content-Type"]="application/json",w=JSON.stringify(C);let B=await this.fetchImpl(`${yh}/accounts/${this.accountId}/workers${f}`,{method:l,headers:A,body:w}),v=await B.text(),ce;try{ce=JSON.parse(v)}catch{throw new ls(`Cloudflare Workers API returned ${B.status} with a non-JSON body: ${v.slice(0,200)}`,B.status)}if(!ce.success){let de=ce.errors??[],ct=de.map((xe)=>`${xe.code}: ${xe.message}`).join(", ");if(Rh(B.status,de))throw new Rc(bh(f),`${l} ${f} -> ${B.status}${ct?`, ${ct}`:""}`,B.status,de);throw new ls(`Cloudflare Workers API error (${B.status}) on ${l} ${f}: ${ct||v.slice(0,200)}`,B.status,de)}return ce.result}scriptPath(l){return`/scripts/${encodeURIComponent(l)}`}async getSettings(l){try{return await this.request("GET",`${this.scriptPath(l)}/settings`)}catch(f){if(f instanceof Rc)throw f;if(f instanceof ls&&(f.hasCode(Ch)||f.status===404))return null;throw f}}async getScript(l){return this.getSettings(l)}async uploadModuleScript(l,f){return this.request("PUT",this.scriptPath(l),Tg(f))}async ensureModuleScript(l,f){let C=js(f),A=await this.getSettings(l);if(A&&Pc(A,f,C))return{action:"unchanged",hash:C};return await this.uploadModuleScript(l,Pg(f,C)),{action:A?"updated":"created",hash:C}}async listCustomDomains(l={}){let f=new URLSearchParams;if(l.service)f.set("service",l.service);if(l.hostname)f.set("hostname",l.hostname);if(l.zoneId)f.set("zone_id",l.zoneId);let C=f.toString(),A=C?`?${C}`:"";return await this.request("GET",`/domains${A}`)??[]}async attachCustomDomain(l,f){let C={hostname:l,service:f.service,environment:f.environment??"production"};if(f.zoneId)C.zone_id=f.zoneId;return this.request("PUT","/domains",C)}async detachCustomDomain(l){await this.request("DELETE",`/domains/${encodeURIComponent(l)}`)}async ensureCustomDomain(l,f,C){let w=(C??await this.listCustomDomains({hostname:l})).find((v)=>v.hostname.toLowerCase()===l.toLowerCase());if(w&&w.service===f.service)return{action:"unchanged",domain:w};if(w)throw Error(`${l} is attached to the Worker '${w.service}'. Detach it there first (Workers & Pages, ${w.service}, Settings, Domains & Routes); ts-cloud does not move it.`);let B=await this.attachCustomDomain(l,f);return{action:"attached",domain:{...B,hostname:B?.hostname||l}}}}function Rh(l,f){if(f.some((C)=>Sh.includes(C.code)))return!0;return(l===401||l===403)&&f.length===0}function bh(l){if(l.startsWith("/domains"))return"Workers Routes: Edit (zone, for Workers custom domains) and Workers Scripts: Edit (account)";return"Workers Scripts: Edit (account)"}function Tg(l){if(!l.modules.some((A)=>A.name===l.mainModule))throw Error(`Worker main module '${l.mainModule}' is not one of the uploaded modules`);let f={main_module:l.mainModule,bindings:l.bindings??[],compatibility_date:l.compatibilityDate??Gs,compatibility_flags:l.compatibilityFlags??[],keep_bindings:["secret_text"]},C=new FormData;C.append("metadata",JSON.stringify(f));for(let A of l.modules)C.append(A.name,new Blob([A.content],{type:A.type}),A.name);return C}function js(l){let f={mainModule:l.mainModule,modules:[...l.modules].sort((C,A)=>C.name.localeCompare(A.name)).map((C)=>({name:C.name,type:C.type,sha256:Ag(C.content)})),bindings:[...l.bindings??[]].filter((C)=>C.name!==Qn).sort((C,A)=>C.name.localeCompare(A.name)),compatibilityDate:l.compatibilityDate??Gs,compatibilityFlags:[...l.compatibilityFlags??[]].sort()};return Ag(qc(f))}function Pg(l,f=js(l)){return{...l,bindings:[...(l.bindings??[]).filter((C)=>C.name!==Qn),{type:"plain_text",name:Qn,text:f}]}}function Pc(l,f,C){let A=l.bindings??[],w=A.find((B)=>B.name===Qn&&B.type==="plain_text");if(!w||w.text!==C)return!1;return(f.bindings??[]).every((B)=>{let v=A.find((de)=>de.name===B.name);if(!v||v.type!==B.type)return!1;let ce=B.type==="r2_bucket"?"bucket_name":B.type==="plain_text"?"text":void 0;return!ce||v[ce]===B[ce]})}function Ag(l){return hh("sha256").update(l).digest("hex")}function qc(l){if(Array.isArray(l))return`[${l.map(qc).join(",")}]`;if(l&&typeof l==="object")return`{${Object.entries(l).filter(([,C])=>C!==void 0).sort(([C],[A])=>C.localeCompare(A)).map(([C,A])=>`${JSON.stringify(C)}:${qc(A)}`).join(",")}}`;return JSON.stringify(l)}async function $u(l){if(!await Bun.file(l).exists())throw Error(`Worker entry not found: ${l}`);let f;try{f=await Bun.build({entrypoints:[l],target:"browser",format:"esm",minify:!0,external:["cloudflare:*"]})}catch(w){throw Error(`Bundling Worker ${l} failed: ${Ph(w)}`)}if(!f.success)throw Error(`Bundling Worker ${l} failed: ${f.logs.map((w)=>String(w.message??w)).join("; ")}`);if(f.outputs.length!==1)throw Error(`Bundling Worker ${l} produced ${f.outputs.length} files (${f.outputs.map((w)=>w.path).join(", ")}); a Worker is uploaded as a single module, so remove the dynamic imports or asset imports that split it.`);let C=f.outputs[0];if(C.kind!=="entry-point")throw Error(`Bundling Worker ${l} produced a ${C.kind} instead of an entry module`);let A=await C.text();return{name:`${Ah(l,Th(l))}.js`,content:A,type:xl,size:new TextEncoder().encode(A).byteLength}}function Ph(l){if(l instanceof AggregateError&&l.errors.length>0)return l.errors.map((f)=>f instanceof Error?f.message:String(f?.message??f)).join("; ");return l instanceof Error?l.message:String(l)}import{isAbsolute as wh,resolve as Ih}from"node:path";var Dh="https://api.cloudflare.com/client/v4",vh=/^[a-z0-9][a-z0-9_-]{0,62}$/;async function Eh(l,f={}){let C=f.log??(()=>{}),A={workers:[],warnings:[]},w=Object.entries(l.infrastructure?.workers??l.workers??{});if(w.length===0)return C("Workers: none declared, skipping."),A;if(!f.apiToken||!f.accountId){let ce=[!f.apiToken&&"CLOUDFLARE_API_TOKEN",!f.accountId&&"CLOUDFLARE_ACCOUNT_ID"].filter(Boolean).join(" and "),de=`Workers: ${w.length} Worker(s) declared but ${ce} is not set, skipping.`;return C(de),A.warnings.push(de),A}let B=l.infrastructure?.r2??l.r2,v={workers:new Tc({apiToken:f.apiToken,accountId:f.accountId,fetch:f.fetch}),r2:new Si({apiToken:f.apiToken,accountId:f.accountId,fetch:f.fetch}),cloudflare:new M(f.apiToken,{zoneId:f.zoneId,accountId:f.accountId}),apiToken:f.apiToken,fetch:f.fetch??((ce,de)=>fetch(ce,de)),projectRoot:f.projectRoot??process.cwd(),dryRun:f.dryRun===!0,warnings:A.warnings,log:C,r2ConfigDomains:bS(B),r2Buckets:B,claimed:new Map};for(let[ce,de]of w){let ct=de?.name;if(!ct||!vh.test(ct)){A.warnings.push(`Workers: '${ce}' has an invalid name '${ct??""}' (1-63 chars: lowercase letters, digits, '-' and '_'), skipping.`);continue}if(!de.entry){A.warnings.push(`Workers: ${ct} has no entry, skipping.`);continue}C(`Workers: ${v.dryRun?"checking":"reconciling"} ${ct}...`);let xe={name:ct,changes:[],domains:[]};A.workers.push(xe),await Nh(de,xe,v);for(let Ut of xe.changes)C(`Workers: ${ct}: ${Ut}`)}return A}async function Nh(l,f,C){let A=l.name,w=wh(l.entry)?l.entry:Ih(C.projectRoot,l.entry),B;try{B=await $u(w)}catch(ce){throw Error(`Worker ${A}: ${gs(ce)}`)}f.changes.push(`bundled ${PS(B.size)}`);let v={mainModule:B.name,modules:[{name:B.name,content:B.content,type:B.type}],bindings:$g(l,C),compatibilityDate:l.compatibilityDate??Gs,compatibilityFlags:l.compatibilityFlags??[]};if(C.dryRun){let ce=await C.workers.getSettings(A);f.changes.push(ce&&Pc(ce,v,js(v))?"unchanged":"would upload")}else{let{action:ce}=await C.workers.ensureModuleScript(A,v);f.changes.push(ce==="unchanged"?"unchanged":"uploaded")}for(let ce of TS(l.customDomains))await lS(A,ce,f,C)}async function lS(l,f,C,A){let w=(gt)=>{C.domains.push({domain:f,status:gt})},B=(gt)=>{A.warnings.push(`Workers: ${gt}`),w("conflict")},v=A.claimed.get(f);if(v&&v!==l){B(`${f} is declared on both ${v} and ${l}; leaving it on ${v}.`);return}A.claimed.set(f,l);let ce=A.r2ConfigDomains.get(f);if(ce){B(`${f} is also declared as a custom domain of the R2 bucket '${ce}' (r2.buckets). A hostname serves either a bucket or a Worker. Remove it from the bucket's customDomains and detach it in the dashboard (R2, ${ce}, Settings, Custom Domains) first; to serve the bucket through the Worker, bind it with bindings.r2Buckets instead.`);return}let de=await dS(A);if(de===null){w("error");return}let ct=de.find((gt)=>gt.hostname.toLowerCase()===f);if(ct?.service===l){w("active");return}if(ct){B(`${f} is attached to the Worker '${ct.service}'. Detach it there first (Workers & Pages, ${ct.service}, Settings, Domains & Routes); it is not moved automatically.`);return}let xe=(await CS(A))?.get(f);if(xe){B(`${f} is attached to the R2 bucket '${xe}' as a custom domain. Detach it first (R2, ${xe}, Settings, Custom Domains, then re-run the deploy); it is not detached automatically. To serve the bucket through the Worker, bind it with bindings.r2Buckets.`);return}let Ut;try{Ut=await A.cloudflare.zoneIdFor(f)}catch(gt){A.warnings.push(`Workers: could not resolve the zone for ${f}, not attached: ${gs(gt)}`),w("error");return}let Qt=await RS(A,Ut,f);if(Qt.length>0){let gt=Qt.map((lt)=>`${lt.type} ${lt.content}`).join(", ");B(`${f} already has a DNS record (${gt}). A Worker custom domain creates its own record, so Cloudflare will not attach over it. Delete the record first (DNS, Records), then re-run the deploy; it is not deleted automatically.`);return}if(A.dryRun){C.changes.push(`would attach custom domain ${f}`),w("not attached");return}try{await A.workers.ensureCustomDomain(f,{service:l,zoneId:Ut},de),C.changes.push(`custom domain ${f} attached`),de.push({id:"",hostname:f,service:l,zone_id:Ut}),w("pending")}catch(gt){A.warnings.push(`Workers: custom domain ${f} on ${l} failed: ${gs(gt)}`),w("error")}}async function dS(l){if(l.attached!==void 0)return l.attached;try{l.attached=await l.workers.listCustomDomains()}catch(f){l.warnings.push(`Workers: could not list Worker custom domains, none attached: ${gs(f)}`),l.attached=null}return l.attached}async function CS(l){if(l.r2AccountDomains!==void 0)return l.r2AccountDomains;let f=new Map;try{let C=(await l.r2.listBuckets()).map((A)=>({name:A.name}));for(let A of Object.values(l.r2Buckets?.buckets??{}))if(A.jurisdiction&&A.jurisdiction!=="default")C.push({name:A.name,jurisdiction:A.jurisdiction});for(let A of C){let w=await l.r2.listCustomDomains(A.name,{jurisdiction:A.jurisdiction}).catch(()=>[]);for(let B of w)f.set(B.domain.toLowerCase(),A.name)}l.r2AccountDomains=f}catch(C){l.log(`Workers: could not check R2 custom domains (${gs(C)}); relying on the DNS check.`),l.r2AccountDomains=null}return l.r2AccountDomains}async function RS(l,f,C){try{let A=await l.fetch(`${Dh}/zones/${f}/dns_records?name=${encodeURIComponent(C)}&per_page=100`,{method:"GET",headers:{Authorization:`Bearer ${l.apiToken}`}}),w=await A.json();if(!w?.success)throw Error(`HTTP ${A.status}`);return(w.result??[]).filter((B)=>B.name?.toLowerCase()===C).map((B)=>({type:B.type??"?",content:B.content??""}))}catch(A){return l.log(`Workers: could not read DNS records for ${C} (${gs(A)}); attaching anyway.`),[]}}function $g(l,f){let C=[],A=new Set,w=(v)=>{if(v===Qn)return f.warnings.push(`Workers: ${l.name}: binding name ${Qn} is reserved for ts-cloud, ignored.`),!1;if(A.has(v))return f.warnings.push(`Workers: ${l.name}: binding ${v} is declared twice; the first one wins.`),!1;return A.add(v),!0},B=new Map;for(let v of Object.values(f.r2Buckets?.buckets??{}))if(v.jurisdiction&&v.jurisdiction!=="default")B.set(v.name,v.jurisdiction);for(let[v,ce]of Object.entries(l.bindings?.r2Buckets??{})){if(!w(v))continue;let de=B.get(ce);C.push(de?{type:"r2_bucket",name:v,bucket_name:ce,jurisdiction:de}:{type:"r2_bucket",name:v,bucket_name:ce})}for(let[v,ce]of Object.entries(l.bindings?.vars??{}))if(w(v))C.push({type:"plain_text",name:v,text:String(ce)});return C}function bS(l){let f=new Map;for(let C of Object.values(l?.buckets??{}))for(let A of C?.customDomains??[]){let w=wg(typeof A==="string"?A:A.domain);if(w)f.set(w,C.name)}return f}function TS(l){return[...new Set((l??[]).map(wg).filter(Boolean))]}function wg(l){return(l??"").trim().replace(/\.$/,"").toLowerCase()}function PS(l){if(l<1024)return`${l} B`;if(l<1048576)return`${(l/1024).toFixed(1)} KB`;return`${(l/1024/1024).toFixed(1)} MB`}function gs(l){return l instanceof Error?l.message:String(l)}export{dl as ABTestManager,ge as ACMClient,Sr as ACMDnsValidator,tg as ACME_DIRECTORIES,Pe as AI,ql as API_IDEMPOTENCY_TTL_MS,Gl as API_TOKEN_DEFAULT_TTL_MS,Vl as API_TOKEN_MAX_TTL_MS,rs as API_VERSION,me as AUTHORIZATION_CAPABILITIES,Fl as AUTH_ACTION_TOKEN_TTL_MS,Ul as AUTH_MFA_CHALLENGE_TTL_MS,Ql as AUTH_OIDC_TRANSACTION_TTL_MS,Ye as AUTH_SESSION_ABSOLUTE_TTL_MS,Ml as AUTH_SESSION_IDLE_TTL_MS,ZA as AWSAPIError,n as AWSClient,h as AWSCloudFormationClient,S as AWSCloudFrontClient,sl as AWSConfigManager,TI as AWS_PSEUDO_PARAMETERS,Ne as AWS_REGIONS,zf as AcmeClient,jr as AlertEvaluator,ki as AlertStore,mo as AnomalyConfigStore,Kd as ApiGateway,i as ApiServiceError,ac as ApplicationAutoScalingClient,Yr as Arn,k as AssetHasher,q as Auth,Xi as AuthenticationStore,Li as AutomationApiService,Yi as AutomationIdentityStore,fa as AwsAuroraDataAdapter,Ia as AwsAuroraTransport,Ma as AwsDatabaseBackupSource,vr as AwsDriver,ha as AwsElastiCacheDataAdapter,ba as AwsElastiCacheTransport,Rf as AwsIamCapabilityScanner,Ga as AwsInfrastructureBackupSource,ma as AwsRdsDataAdapter,Sa as AwsRdsTransport,Uf as AwsRegionalDriver,qa as AwsSecretsManagerConfigurationBackend,Gp as AwsSpendTransport,ja as AwsSsmConfigurationBackend,ps as BackupCoordinator,nl as BackupManager,La as BackupStore,tf as BatchProcessingManager,Nn as BedrockClient,Pn as BedrockRuntimeClient,Yl as BitbucketSourceAdapter,cl as BlueGreenManager,qm as BounceComplaintHandler,Lm as BuildOptimizationManager,Iu as BunDockerRuntime,Ju as BunDockerVolumeRuntime,Wu as BunFilesystemArchiveRuntime,he as CDN,xo as CHAIN_HEADER,Lt as CLOUDFLARE_MANAGED_RULE_PREFIX,Gd as CLOUDFRONT_FAILOVER_STATUS_CODES,uC as COMMON_CROSS_ACCOUNT_ROLES,Qn as CONTENT_HASH_BINDING,Ge as CONTROL_PLANE_SCHEMA_VERSION,Ro as Cache,Vi as CanaryManager,xm as CertificateManager,lA as CloudBlockVolumeDriver,zs as CloudDriverFactory,We as CloudError,om as CloudFormationBuilder,h as CloudFormationClient,S as CloudFrontClient,ol as CloudTrailManager,Ie as CloudWatchLogsClient,ig as CloudflarePagesProvider,M as CloudflareProvider,Iy as CommandHistory,z as Communication,Qr as ComposeApplicationService,zt as ComposeApplicationStore,kt as ComprehendClient,a as Compute,Vp as ComputeSpendTransport,No as ConfigurationError,Ka as ConfigurationService,Va as ConfigurationStore,Rn as ConnectClient,ya as ContainerDataAdapter,ml as ContainerRegistryManager,Ha as ControlPlaneBackupSource,Ba as ControlPlaneCleanupDriver,vi as ControlPlaneStore,uo as CounterTracker,Ct as CredentialError,bm as CrossRegionReferenceManager,FA as DASHBOARD_ENTRY,UA as DASHBOARD_PORT_BASE,QA as DASHBOARD_PORT_SPAN,MA as DASHBOARD_STATE_DIR,Ho as DEFAULT_ATTACK_MODE_HOURS,Gs as DEFAULT_COMPATIBILITY_DATE,Nd as DEFAULT_DDOS_THRESHOLDS,Kp as DEFAULT_FAILOVER_STATUS_CODES,ud as DEFAULT_METER_MAPPINGS,dd as DEFAULT_PRICE_BOOK,rn as DEFAULT_RECURSION_LIMITS,Gn as DEFAULT_RPX_CERTS_DIR,K as DEFAULT_SERVICE_LIMITS,Od as DEFAULT_STATE_DIR,dg as DEFAULT_STATIC_ASSET_EXTENSIONS,OA as DEFAULT_STORAGE_FAILOVER_STATUS_CODES,EA as DEFAULT_TELEMETRY_POLICY,Rp as DEFAULT_THRESHOLDS,sA as DEPLOYMENT_QUEUE_KINDS,Bo as DEPTH_HEADER,Vr as DETECTABLE_SIGNALS,fu as DIAGNOSTIC_PRESETS,ef as DLQMonitoringManager,H as DNS,Gm as DNSSECManager,os as DataServiceLifecycle,pa as DataServiceStore,Yt as Database,km as DatabaseUserManager,U as DebugLogger,xA as DependencyGraph,j as Deployment,YA as DeploymentError,il as DisasterRecoveryManager,Mn as DnsProviderFactory,or as DockerDataTransport,aa as DockerDiscoveryAdapter,Ur as DockerNamedVolumeDriver,Qa as DockerVolumeBackupSource,c as DurableOperationQueue,no as DurableQueueWorker,_e as DynamoDBClient,Br as EC2Client,$e as ECRClient,nt as ECSClient,fr as EFSClient,nc as ELBv2Client,gA as ENFORCEMENT_ACTIONS,Pi as ENFORCEMENT_DESCRIPTIONS,N as ENFORCEMENT_SEVERITY,tp as ENVIRONMENT_LABEL,pu as EcsRuntimeAdapter,Qo as EdgeRateLimiter,st as ElastiCacheClient,m as Email,Wm as EmailAdvanced,jm as EmailAnalyticsManager,On as EmailClient,Jm as EmailHandlers,Km as EmailTemplateManager,Ca as EncryptedDataSecretStore,ey as ErrorCodes,pr as EventBridgeClient,$f as EventBridgeJobAdapter,za as ExternalConfigurationBackend,wo as FAILOVER_REPLICA_POLICY_SID,Zm as FIFOQueueManager,$S as FLY_MACHINES_API,_p as FOCUS_VERSION,Xd as FileCache,ze as FileSystem,Fa as FilesystemBackupSource,va as FleetService,Ea as FleetStore,_a as FlyApiError,kg as FlyClient,e as Fn,Zl as GiteaSourceAdapter,Jl as GithubSourceAdapter,Xl as GitlabSourceAdapter,Cm as GlobalResourceManager,Me as GoDaddyProvider,al as GuardDutyManager,pt as HOST_SITES_DIR,iy as HashCache,mf as HealthCheckManager,qe as HealthCheckRunner,Dr as HetznerClient,Te as HetznerDriver,be as IAMClient,Ac as IPV6_EXCLUDED_HOST_LABELS,_m as ImageScanningManager,_g as InfrastructureGenerator,Yc as InvalidOperationTransitionError,It as JobLoader,Mf as JobProviderReconciler,ga as JobService,la as JobStore,gr as KendraClient,gf as LARAVEL_SERVERLESS_BUILD_STEPS,E as LambdaClient,Fm as LambdaConcurrencyManager,Hm as LambdaDLQManager,Um as LambdaDestinationsManager,$m as LambdaLayersManager,mu as LambdaRuntimeAdapter,Qm as LambdaVPCManager,Mm as LambdaVersionsManager,Cn as LocalEncryptedConfigurationBackend,Ua as LogicalDatabaseBackupSource,ul as LogsManager,Qy as MANAGED_NODE_VERSIONS,Uc as MANAGEMENT_DASHBOARD_SITE,am as MANAGEMENT_DASHBOARD_SITE_PREFIX,Wi as MAX_CONTROL_HOURS,Zc as MAX_CONTROL_PLANE_ERROR_BYTES,Cp as MAX_CONTROL_PLANE_JSON_BYTES,ao as METERS,uA as METER_KEYS,pA as MICRO_CENTS,Dp as MIN_PROJECTION_CONFIDENCE,mg as MTA_STS_PORT,ka as MaintenanceService,Na as MaintenanceStore,ie as Messaging,Dm as MetricsManager,Pm as MigrationManager,hm as MockCloudFormation,ym as MockDynamoDB,Am as MockS3,Do as Monitoring,Tm as MultiAccountManager,Im as MultiRegionManager,my as MultiStepProgress,y as Network,ff as NetworkSecurityManager,Bi as NotificationRouter,Xp as ORIGIN_CONNECTION_ATTEMPTS,Yp as ORIGIN_CONNECTION_TIMEOUT,Wp as ORIGIN_GROUP_ALLOWED_METHODS,CI as ORIGIN_GROUP_ID_SUFFIX,Jp as ORIGIN_GROUP_SELECTION_CRITERIA,ic as OpenSearchClient,mt as OptimisticConcurrencyError,wm as OrganizationManager,th as PAGES_MAX_FILE_BYTES,Xy as PHP_DEFAULT_EXCLUDES,Hy as PHP_LAYER_EXTENSIONS,ep as PROJECT_LABEL,at as PROXIABLE_RECORD_TYPES,T as ParameterStore,Nm as PerformanceManager,ne as Permissions,sc as PersonalizeClient,Ke as Phone,Xm as PhoneAdvanced,im as PhoneHandlers,wa as PlacementService,Ta as PlacementStore,kn as PollyClient,le as PorkbunProvider,un as PreDeployScanner,tl as PreviewEnvironmentManager,Fr as PreviewEnvironmentService,Ve as PreviewEnvironmentStore,rl as PreviewNotificationService,py as ProgressBar,ll as ProgressiveDeploymentManager,Go as ProtectionControlStore,BA as Pseudo,G as Queue,Ti as QueueCancellationError,rf as QueueManagementManager,lI as QueuePresets,ro as QueueTimeoutError,ti as R2ApiError,jn as R2NotEnabledError,Si as R2Provider,yg as R2_NOT_ENABLED_ERROR_CODE,Nl as RATE_LIMIT_KEY_SEPARATOR,J as RDSClient,Cy as RECOMMENDED_ACCOUNT_STRUCTURES,lC as RECOMMENDED_SCPS,Ef as RELEASE_QUEUE_KINDS,Ay as REPL,Sy as REPLCommandBuilder,yy as REPLContext,rp as ROLE_LABEL,sy as RateLimiter,uI as RealtimePresets,Lp as RecordingSpendTransport,ji as RecursionGuard,bt as Redirects,Em as RegionPairManager,Da as RegionService,Ra as RegionStore,je as Registry,Bt as RekognitionClient,Et as ReleaseService,Yo as ReleaseStore,Ff as RemoteBuildService,gl as ReplicaManager,hf as ResourceManagementManager,te as RetryableOperationError,I as Route53Client,rc as Route53DomainsClient,X as Route53Provider,Vm as Route53ResolverManager,hl as Route53RoutingManager,ye as RuntimeOperationService,da as RuntimeStreamRegistry,$a as S3BackupDestinationAdapter,o as S3Client,F as S3Error,ru as SECRET_PATTERNS,xp as SENSITIVITY_THRESHOLDS,ot as SESClient,V as SMS,it as SNSClient,Hp as SPEND_CYCLE_SECONDS,vd as SPEND_GATE_SETTING,RA as SPEND_LEASE_SETTING,ae as SQSClient,we as SSH_BOOTSTRAP_VERSION,si as SSH_PREFLIGHT_SCRIPT,Re as SSMClient,jp as STATE_DIR_ENV_VAR,Ts as STATIC_SITE_ZONE_SETTINGS,qd as STORAGE_FAILOVER_METADATA_KEY,Se as STSClient,Bn as SchedulerClient,Zt as Search,gn as SecretFindingScanner,Ui as Secrets,pl as SecretsManager,W as SecretsManagerClient,Bm as SecretsRotationManager,b as Security,tr as SecurityHubManager,ln as SecurityPostureStore,vt as SecurityScannerRunner,Om as SecurityScanningManager,zm as SenderReputationManager,Lf as ServerCronJobAdapter,Aa as ServerDataAdapter,oo as ServerPathVolumeDriver,fl as ServiceMeshManager,zd as Sftp,ho as SignalSource,Ym as SmsAdvanced,Ot as SmsClient,sm as SmsHandlers,lc as SmsVoiceClient,Zo as SourceConnectionStore,ir as SourceProviderError,Td as SpendCapError,qr as SpendGate,Up as SpendLoopLease,bo as SpendNotificationRouter,Qp as SpendRunner,Wt as SpendService,Ri as SpendStore,fy as Spinner,Nr as SshDriver,fn as SshFleetDriver,vm as StackDependencyManager,vI as StacksIntegration,pf as StaticSiteManager,De as Storage,Rl as StorageAdvancedManager,xn as SupportClient,rr as SyntheticsManager,bu as SystemFleetSshTransport,Pr as SystemSshTransport,ca as SystemdDiscoveryAdapter,Oo as TRACE_HEADER,hy as TaskList,At as TelemetryStore,Qd as TemplateBuilder,Yd as TemplateCache,xt as TextractClient,Dn as TranscribeClient,ur as TranslateClient,Gf as TransportDisasterRecoveryDriver,Hf as TransportPlatformMaintenanceDriver,as as TransportRemoteBuildDriver,sa as TrivyImageScanner,Xo as TsCloudApiError,jl as TsCloudClient,wA as URGENT_SPEND_EVENTS,Pp as USER_VISIBLE_ACTIONS,Pa as UnavailableRegionalDriver,ue as UnifiedDnsValidator,Zs as UnsupportedSchemaVersionError,um as ValidationError,mr as VoiceClient,so as VolumeService,jt as VolumeStore,xl as WORKER_MODULE_TYPE,ls as WorkersApiError,Rc as WorkersPermissionError,Tc as WorkersProvider,$A as Workflow,Rm as XRayManager,ky as abTestManager,zl as activateImmutableRelease,Yg as addDns01ChallengeRecord,An as addSiteToCloudConfig,wt as ageSeconds,pd as aggregateDeltas,Sp as allocateSitePorts,nm as amazonLinuxImageId,LA as amazonLinuxImageParameter,II as analyzeStackDiff,Ni as anomalyOptionsForSignal,Vo as applyControlsToDdos,_l as applyControlsToRateLimits,Bs as applyDeclaredZoneSettings,Wr as applyMitigationFactor,Uh as applyPlan,Ls as applyZoneMigration,Al as artifactKey,yt as assertOriginGroupMethods,Zi as assertReleaseStrategy,CA as assertSpendAllows,qh as attachConflicts,jh as attachIsViable,Vh as attachPreconditions,au as attachProvenanceToRelease,oa as attachSbomToRelease,su as attachVulnerabilitySummary,bf as authEncryptionKeyFile,P as authorizeOrganization,Of as authorizeRuntimePath,Ub as autocomplete,Ty as awsConfigManager,zu as backupCredentialStatus,Ey as backupManager,ub as batch,tE as batchProcessingManager,Wo as beginOidcAuthorization,Py as blueGreenManager,WC as bounceComplaintHandler,ft as budgetWindow,Za as buildAndPushServerlessImage,iE as buildBunRuntimeLayerZip,Yh as buildCertificatePackScript,Wh as buildCertificateStateScript,Zh as buildCertificateUnpackScript,Wd as buildCloudFormationTemplate,xc as buildCloudInitFirstBoot,nd as buildComposeLogsCommand,cI as buildComposeRuntimeCommand,dI as buildComposeScaleCommand,id as buildComposeShellCommand,hp as buildDrainSourceScript,kh as buildDrainedSiteScanScript,jd as buildFailoverReplicaPolicyStatement,cr as buildFunctionEnv,fp as buildHealthGateScript,Xn as buildHostCleanupDeployScript,Vs as buildHostCleanupInstallScript,Jn as buildHostCleanupScript,Ci as buildHostSitePortsScript,Ud as buildMailEnv,Ws as buildManagementDashboardArtifact,VS as buildMediaCdnPlan,pg as buildMtaStsPolicy,gh as buildMtaStsServer,nE as buildNodeRuntimeLayerZip,UC as buildOptimizationManager,Vd as buildOriginGroup,Xr as buildOriginGroups,pc as buildOriginGuardRule,cp as buildPauseWorkersScript,cE as buildPhpRuntimeLayerZip,rm as buildReplicationConfiguration,tm as buildReplicationRole,gp as buildRestoreScript,Y as buildRpxConfig,Fe as buildRpxFragmentRefreshScript,Hh as buildSetHostnameScript,Zn as buildSiteDeployScript,up as buildSnapshotScript,Ap as buildSourceStateScript,zn as buildSshArgs,ni as buildSshBootstrapScript,gc as buildStaticSiteCacheRules,ei as buildStaticSiteDeployScript,pp as buildTargetStateScript,Tg as buildUploadForm,dp as buildWorkersStateScript,$u as bundleWorker,du as bytes,Sg as cacheRuleParameters,Ny as canaryManager,hn as canonicalJson,Tt as capabilities,ar as capacity,Ib as categorizeChanges,$C as certificateManager,Xh as certificatesMatch,tb as checkIAMPermissions,cf as checkInvocation,nb as checkServiceQuotas,oy as chunk,iR as cleanupDns01Challenge,iS as clearSigningKeyCache,ta as cloneSourceBinding,ay as cloudConfigSchema,Ug as cloudDrivers,wy as cloudTrailManager,sg as collectAssets,Mo as collectPhpAppEntries,lg as collectServerDnsDomains,Ep as completeComposeVolumeDeletion,Jo as completeOidcAuthorization,GI as composePresets,to as composeProjectName,Sl as composeServerlessAppTemplate,PA as compositeSpendTransport,Nt as compressBackup,uS as config,uc as configOrigins,yu as connectionGuidance,$y as containerRegistryManager,nA as controlPlaneDatabaseFile,Jc as controlPlaneMigrations,kI as createApiBackendPreset,ia as createApiV1Handler,IS as createAsgBuildDriver,Ku as createBackupQueueHandlers,Jy as createCliHandler,O as createCloudDriver,Bu as createCloudFrontPolicy,XI as createCredentialProvider,QI as createDashboardSite,LI as createDataPipelinePreset,Su as createDataServiceQueueHandlers,sd as createDeploymentQueueHandlers,D as createDnsProvider,SS as createEcsBuildDriver,wd as createEnforcementHandlers,gm as createError,Jd as createExistingStaticFullStackPreset,Cu as createFleetQueueHandlers,NI as createFullStackAppPreset,Fs as createGoDaddyValidator,aE as createHandlers,Ky as createHttpHandler,xI as createJamstackPreset,Au as createJobQueueHandlers,FI as createLaravelPreset,$I as createMLApiPreset,Pu as createMaintenanceQueueHandlers,MS as createMediaAccessToken,OI as createMicroservicesPreset,Db as createMockAWS,RI as createNodeJsServerPreset,DI as createNodeJsServerlessPreset,vs as createObjectStorageClient,Ms as createPorkbunValidator,VI as createPreset,Fo as createPresignedUrl,Zy as createPresignedUrlAsync,Wy as createQueueHandler,_I as createRealtimeAppPreset,vu as createRegionQueueHandlers,ou as createReleaseProvenance,Wl as createReleaseQueueHandlers,AS as createRemoteBuildQueueHandlers,Us as createRoute53Validator,xf as createRuntimeAdapters,XA as createS3Client,yS as createServerBuildDriver,UI as createServerlessLaravelPreset,PI as createServerlessNodePreset,cg as createSmsInfrastructure,et as createSourceAdapter,wI as createStaticSitePreset,MI as createTraditionalWebAppPreset,od as createVolumeQueueHandlers,BI as createWordPressPreset,Je as createZip,Kb as crossRegionReferenceManager,En as dashboardActions,Ks as dashboardCredentialsFile,mn as dataServiceCapabilities,_C as databaseUserManager,$l as decodeBase32,Oe as decompressBackup,Zf as decryptBackup,qo as defaultConfig,fm as defaultLocalConfig,Bl as defaultRateLimitRules,yr as delegateZone,Ns as delegateZoneFromConfig,Gu as deleteFailoverReplicaBuckets,Xa as deleteStaticSite,Hc as deployAllComputeSites,Oa as deployServerlessApp,Vu as deploySite,Js as deploySiteRelease,As as deployStaticSite,Ya as deployStaticSiteFull,vn as deployStaticSiteWithExternalDns,Tn as deployStaticSiteWithExternalDnsFull,vS as deployToFly,Md as deploymentCoexistenceError,HA as deriveManagementDashboardPort,ks as describeDelegation,Ol as describePosture,xs as describeZoneSettings,_f as desiredJobProviderState,Bp as detectAnomalies,zp as detectDeploymentTargets,mc as detectDnsProvider,bd as detectLatestAnomaly,ZI as detectMisconfigurations,Dl as detectServiceRegion,td as diffCompose,Ab as diffTemplates,ea as discoverGitRefs,Ko as discoverOidcProvider,lu as discoverRuntimeInventory,eE as dlqMonitoringManager,fc as dnsProviders,zC as dnssecManager,Nf as dockerWorkloads,cs as documentDigest,Mc as domainStatus,vy as drManager,Qe as driverStatePath,uu as ecsWorkloads,qt as effectiveCapabilities,JC as emailAnalyticsManager,YC as emailTemplateManager,Ji as encodeBase32,Yf as encryptBackup,cu as ensureDefaultSecurityPolicies,Uu as ensureFailoverReplicaBuckets,gi as ensureFirewall,fi as ensureManagementDashboard,pi as ensureServer,ui as ensureSshKey,ee as escapeSecLang,fd as evaluateBudget,ai as evaluatePreflight,Io as evaluateTelemetryAlertRules,hu as eventBridgeScheduleInput,zy as eventToRequest,SA as ewma,ed as exportCompose,Os as exportRoute53Zone,dm as extendPreset,ZC as fifoQueueManager,lb as findChangedFiles,Tp as findMapping,vp as findPriceEntry,kS as flyDeployOptions,Ou as flyIpType,Eg as flyMachineConfig,fC as formatAccountStructure,zh as formatAttachPlan,Bb as formatBytes,zr as formatCents,bI as formatDiff,xh as formatDrainedSiteRefusal,xb as formatDuration,Hb as formatFlagSuggestions,qb as formatHistory,jb as formatHistoryStats,$h as formatInventory,_b as formatKeyValue,Ob as formatList,Fh as formatPlan,di as formatPreflightFindings,kb as formatProgressBar,by as formatRegion,oC as formatRegionList,wf as formatScanResults,Lb as formatSuggestion,Pb as formatTable,Gr as formatTimeToExhaustion,Nb as formatTree,zA as fromEC2Metadata,KA as fromECSMetadata,qA as fromEnvironment,jA as fromSharedCredentials,WA as fromWebIdentity,Cl as functionFingerprint,qn as gatewayHostnames,bl as generateAppImageDockerfile,PC as generateApprovalConfig,nf as generateBootstrap,ly as generateCleanupWorkflow,uy as generateCostReportWorkflow,pC as generateCrossAccountRoleCF,nu as generateCycloneDxSbom,wC as generateDeploymentConfig,bC as generateDeploymentPipeline,hC as generateDeploymentWorkflow,Ja as generateExternalDnsStaticSiteTemplate,rR as generateHttpsServerCode,iu as generateImageSbom,tR as generateLetsEncryptUserData,t as generateLogicalId,TC as generateManualPipeline,IC as generateMatrixWorkflow,RC as generateMultiEnvConfig,CC as generateMultiEnvPipeline,AC as generateMultiEnvWorkflow,yC as generatePRPreviewWorkflow,NC as generateParallelConfig,uf as generatePhpFpmConfig,sf as generatePhpLayerDockerfile,EC as generatePreviewPipeline,dy as generatePreviewWorkflow,r as generateResourceName,DC as generateScheduledConfig,vC as generateScheduledPipeline,SC as generateScheduledWorkflow,hs as generateStaticSiteTemplate,x as generateUbuntuAppCloudInit,lm as getAccountId,Yb as getAllRegions,nC as getClosestRegion,Gb as getCommandUsage,iA as getComposeTemplate,yf as getConfig,Mb as getContextualHelp,Hi as getCredentials,bb as getDeploymentStrategy,Cb as getDiffStats,yb as getDiffSummary,ty as getErrorDetails,el as getLocalConfig,wb as getLocalCredentials,Tb as getLocalEndpoint,Rb as getLocalEnvVars,ib as getQuotaUsageSummary,gC as getRecommendedStructure,Gi as getRegion,aC as getRegionStats,eC as getRegionsByCompliance,Zb as getRegionsByLocation,tC as getRegionsByPricingTier,ry as getRequiredPermissions,sS as getSigningKeyCacheSize,ag as getSmsInfrastructureStatus,gI as getTimestamp,Uo as globMatches,Xs as globToRegex,Wb as globalResourceManager,Di as governingLimitCents,Qu as grantFailoverReplicaAccess,Ry as guardDutyManager,Co as handleSpendRequest,Vn as hasAutoWwwVariant,er as hasManagementDashboardSite,Wc as hasProxyUpstream,ob as hashBuffer,ab as hashDirectory,pm as hashFile,cb as hashManifest,mm as hashString,lE as healthCheckManager,Un as hostAcceptsIpv6,_t as hostCondition,jo as hotp,Hr as hourBucket,yA as hourBucketsBetween,FC as imageScanningManager,us as infraEnvFromOutputs,vl as inspectInvocation,qy as installRecursionFetch,Ss as invalidateCache,af as invocationContext,_A as isArmInstanceType,$b as isLikelyTypo,Hn as isLocalDatabase,vb as isLocalDevelopment,Zr as isManagementDashboardSiteName,hr as isNameserverRegistrar,oS as isNodeCryptoAvailable,Id as isOperationAllowed,So as isQuietHours,To as isS3RestEndpoint,Ai as isSafePattern,Ld as isStateDirConfigured,$d as isStatePath,Kr as isValidCidr,rC as isValidRegion,wi as isValidTimeZone,aS as isWebCryptoAvailable,Ar as isZoneHost,pn as jobProviderCapability,Es as keyMatchesFilters,GC as lambdaConcurrencyManager,jC as lambdaDLQManager,VC as lambdaDestinationsManager,QC as lambdaLayersManager,qC as lambdaVPCManager,HC as lambdaVersionsManager,gu as lambdaWorkloads,Tl as laravelServerlessEnvDefaults,Mr as listComposeTemplates,ts as listSourceReferences,Ll as loadCloudConfig,Jt as loadTelemetryPolicy,xy as logsManager,Cd as lookbackHoursForSignal,kA as mailEnabled,Fd as mailFirewallPorts,Qf as maintenanceWindowOpen,Af as makeAWSRequest,tS as makeAWSRequestAsync,eS as makeAWSRequestOnce,Rg as managedRuleInSync,cm as managementDashboardSiteName,Tu as manifestDigest,on as matchTotpCounter,WS as mediaObjectHeaders,po as median,Np as medianAbsoluteDeviation,hd as mergeDecisions,en as mergeInfrastructure,hA as mergePriceBooks,gd as meterTelemetry,BC as metricsManager,rg as migrateObjectStorage,xC as migrationManager,cC as multiAccountManager,zb as multiRegionManager,oR as needsRenewal,uE as networkSecurityManager,Rt as nextScheduleRuns,Ce as normalizePublicIpv6,ke as normalizeRuntimeStatus,tt as normalizeScheduleExpression,vf as normalizeSourceEvent,Ue as normalizeSshPublicKey,$p as normalizeTelemetryPolicy,bi as occupiedHostPorts,na as openApiDocument,Ao as optionsForSignal,dC as organizationManager,wl as packagePhpApp,tn as packageServerlessApp,og as pagesAssetHash,nh as pagesDnsRecord,Zd as parallel,gb as parallelMap,pb as parallelWithRetry,Jh as parseCertificateState,El as parseChain,$r as parseCompose,oI as parseComposeCatalog,Pf as parseDockerInspect,Xu as parseDotenv,Bh as parseDrainedSites,Ei as parseHostSiteFragments,nS as parseJSONResponse,oi as parsePreflightFacts,yp as parseSourceDrained,kf as parseSystemdRecords,mp as parseTargetReady,Kc as parseUpstreamPort,lp as parseWorkersPaused,rS as parseXMLResponse,Oi as pathTemplate,jc as pendingSteps,go as percentOfLimit,OC as performanceManager,Il as phpLayerBuildStage,Gy as phpLayerPackages,nn as phpRuntimeLayerAssets,aI as planComposeTemplateUpgrade,Ad as planEnforcement,op as planIsDestructive,qp as planMitigation,Qh as planServerRename,eA as planSiteMove,_s as planZoneMigration,Mt as policyTag,ci as preflightFailed,cy as previewManager,gy as previewNotifications,Dt as previewSchedule,AA as previousBudgetWindow,co as priceUsage,mA as priceUsageLines,_h as probeHostRoutes,Fc as probeOriginTls,hb as processInChunks,eu as processSourceWebhook,is as productionChangeReview,By as progressiveDeploymentManager,md as projectSpend,_o as propagationHeaders,ec as providerEndpoint,wu as publicKeyFingerprint,Ln as qualifyName,rE as queueManagementManager,db as quickHash,Cg as r2Endpoint,ch as r2S3Credentials,kl as rateLimitHeaders,Ki as rateLimitKey,He as readDriverState,Lh as reconcile,gg as reconcileAddressRecords,qf as reconcileCloudflareCdn,Eh as reconcileCloudflareWorkers,Ps as reconcileDeclaredRecords,hS as reconcileJobObservation,dh as reconcileR2Buckets,dn as reconcileSourceWebhook,ns as recordDashboardHostPosture,pS as recordPreDeploySecretScan,mS as recordSkippedSecretScan,Lo as recursionBlockedResponse,Be as redactRuntimeConfig,Pd as redactTelemetryText,xi as redactTelemetryValue,Sn as redeployServerlessApp,Jb as regionPairManager,cn as releaseStrategyCapabilities,Cf as releaseTrafficPlan,hi as reloadRpxGateway,Cs as remapKey,ug as removeAddressRecords,Qg as removeDns01ChallengeRecord,yn as removeSiteFromCloudConfig,tu as removeSourceWebhook,hc as removeStaleServerAddressRecords,rd as renderComposeTemplate,$i as renderDdosInstallScript,xd as renderNftablesRuleset,ss as renderServerCron,Bd as renderSysctlFile,Vc as renderWafConfig,yi as renderWafInstallScript,Gc as renewRpxCertificates,_y as replicaManager,NA as requestHash,Sb as requiresReplacement,sE as resetRecursionRuntime,oE as resolveApp,g as resolveAppDatabase,Gh as resolveAttachTarget,Ze as resolveAuthEncryptionKey,fe as resolveCloudProvider,eh as resolveCloudflareCdnPlan,Po as resolveCredentials,fs as resolveDashboardAction,Qc as resolveDashboardAuth,GA as resolveDashboardDomain,VA as resolveDashboardDomains,Ds as resolveDeclaredRecords,SI as resolveDeployBucketName,Q as resolveDeploymentMode,Yn as resolveExecStart,vo as resolveFailoverStatusCodes,wc as resolveHetznerApiToken,Rr as resolveHostCleanupConfig,Mi as resolveMailService,HI as resolveManagementDashboardSite,Qi as resolveManagementDashboardSites,tc as resolveObjectStorage,re as resolveOriginConnection,Mh as resolvePlan,p as resolveProjectStackName,Lr as resolveProxyUpstreams,yl as resolveQueueNames,oA as resolveQueuedDeploymentCommand,nr as resolveQueues,Vy as resolveRecursionConfig,JA as resolveRegion,oe as resolveRuntimeInventory,Xt as resolveServerlessAppStackName,Hd as resolveServerlessArtifactBucketName,Fi as resolveServerlessAssetBucketName,qi as resolveServerlessRuntime,hI as resolveSiteBucketName,Ys as resolveSiteDeployTarget,u as resolveSiteKind,fI as resolveSiteResourceName,mI as resolveSiteStackName,ii as resolveSshSettings,d as resolveStatePath,yI as resolveStorageBucketName,Zp as resolveStorageFailover,Gt as resolveUiSource,ng as resolveZoneApex,gE as resourceManagementManager,lf as responseToResult,kp as robustZScore,Vt as roleCapabilities,Kl as rollbackImmutableRelease,In as rollbackServerlessApp,fA as roundCents,KC as route53ResolverManager,Fy as route53RoutingManager,Op as routeMatches,np as routesFromFragments,zi as ruleMatches,Uy as runBuildHooks,yd as runEnforcement,$o as runPhpBuildHooks,rt as runRemoteCommand,Ae as runtimeId,Le as s3OriginBucket,em as s3RegionalDomain,cc as sameCorsRules,Cc as sameLifecycleRules,$n as sameNameservers,ms as sanitizeCloudConfig,s as sanitizeControlPlaneValue,pI as sanitizeName,Hl as sanitizeOidcReturnPath,Rd as saveTelemetryPolicy,Tf as scanForSecrets,Xc as scopeContains,ht as scopeKey,Ic as scpUpload,Fb as searchCommands,eo as searchControlPlane,Ly as secretsManager,LC as secretsRotationManager,fS as secureContainerRelease,Dy as securityHubManager,MC as securityScanningManager,se as securityScope,Hu as seedFailoverReplicas,an as sendAuthenticationEmail,XC as senderReputationManager,mb as sequence,Yu as serializeDotenv,mi as serverPublicIpv4,My as serviceMeshManager,Lu as setAttachToInCloudConfig,dr as setMaintenance,ds as setSitePropertyInCloudConfig,_d as setStateDir,nR as setupDns01Challenge,dc as setupSmsInfrastructure,ko as sha256,jy as sharedRecursionGuard,of as sharedRuntimeLoop,bp as shipsARelease,_S as signCloudFrontCookies,FS as signCloudFrontUrl,R as signRequest,Pl as signRequestAsync,fo as signalDefinition,_ as siteInstallBase,Ii as siteMoveArchivePath,Kh as siteMoveCertArchivePath,zc as siteUnitGlob,Fp as spendNotificationText,Eo as spendOpenApiPaths,Tr as sshExec,pe as sshExecOrThrow,Xb as stackDependencyManager,Wa as startLocalDashboardServer,DA as startSpendLoop,Jr as stateDir,L as statePath,dE as staticSiteManager,Yy as storageAdvancedManager,EI as storageFailoverReplicasFromTemplate,IA as streamFocusJsonl,Sd as strongestActiveAction,Sm as suggestCommand,Qb as suggestFlags,rb as suggestIAMPolicy,sb as suggestQuotaIncrease,sC as suggestRegionPairs,iC as suggestRegions,es as syncSourceRepositories,ad as synchronizeComposeVolumes,Zu as synchronizeConfiguredConfiguration,ua as synchronizeConfiguredJobs,Oy as syntheticsManager,kd as sysctlHardening,Bf as systemdWorkloads,TA as telemetryBucketLabel,_i as telemetryCursor,Dd as telemetryEstimatedMonthlyCost,vA as telemetryPercentile,Mp as telemetryPolicyKey,ny as templateCache,ip as tenantsOf,ra as testSourceConnection,cd as tieredMicroCents,bg as toApiLifecycleRule,Lc as toCloudflareZoneSettings,yo as toFocusJsonl,Ed as toFocusRecords,Oh as toInventoryServer,Sf as totp,zo as totpUri,sp as unaccountedSites,Df as unsupportedCapabilities,aA as unsupportedVolumeCapabilities,Du as updateCompatibility,Nu as updateSiteInCloudConfig,ys as uploadStaticFiles,wp as usageDeltaKey,Kt as utcInstantOfLocal,mC as validateAccountStructure,Eb as validateAgainstSchema,dA as validateAttachment,Xf as validateBackupDestination,Vb as validateCommand,YI as validateConfiguration,eb as validateCredentials,Ip as validateDeploymentConfig,cA as validateMountPath,St as validateOriginGroups,Gg as validateResourceLimits,ap as validateServerName,Mg as validateTemplate,Hg as validateTemplateSize,yc as verifyAddressRecord,gS as verifyArtifactSignature,BS as verifyMediaAccessToken,If as verifyTotp,Ru as verifyUpdateSignature,$s as verifyZoneParity,io as volumeCapabilities,Xg as wafEventTelemetry,bc as waitForCloudInit,Kn as waitForSsh,sr as webhookEndpoint,WI as withCDN,KI as withCache,Pg as withContentHash,zI as withDatabase,df as withInvocation,qI as withMonitoring,JI as withQueue,jI as withSecurity,fb as withTimeout,$g as workerBindings,js as workerContentHash,Pc as workerInSync,Z as wrapCloudInitUserData,dt as writeDriverState,kC as xrayManager,Eu as zeroCapacity,bA as zeroFill,ld as zoneOffsetMs,lo as zonedParts};
|
|
604
|
+
`}async function zg(u,f,R){let A=`_acme-challenge.${f}`;if(await Ug(u,f,A,R))return;let T=await u.createRecord(f,{name:A,type:"TXT",content:R,ttl:60});if(!T.success)throw Error(`Failed to create DNS challenge record: ${T.message}`)}async function Hg(u,f,R){let A=await u.deleteRecord(f,{name:`_acme-challenge.${f}`,type:"TXT",content:R});if(!A.success)console.warn(`Failed to delete DNS challenge record: ${A.message}`)}async function Ug(u,f,R,A){try{let T=await u.listRecords(f,"TXT"),E=R.replace(/\.$/,"").toLowerCase();return(T.records??[]).some((P)=>P.name.replace(/\.$/,"").toLowerCase()===E&&P.content.replace(/^"|"$/g,"")===A)}catch{return!1}}function Gu(u){let{hostedZoneId:f,dnsProvider:R,region:A="us-east-1"}=u;if(R)return k(R);if(f)return new ie(A,f);throw Error("Either dnsProvider or hostedZoneId must be provided")}async function oR(u){await zg(Gu(u),u.domain,u.challengeValue)}async function sR(u){await Hg(Gu(u),u.domain,u.challengeValue)}function aR(u){try{let{execSync:f}=nt("node:child_process"),R=f(`openssl x509 -checkend 2592000 -noout -in ${u}/cert.pem`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return!1}catch{return!0}}import{createHash as ju,createSign as Gg,generateKeyPairSync as Ku}from"node:crypto";var Qu={production:"https://acme-v02.api.letsencrypt.org/directory",staging:"https://acme-staging-v02.api.letsencrypt.org/directory"};class jg{directoryUrl;email;accountKey;accountUrl=null;directory=null;nonce=null;constructor(u){this.directoryUrl=u.staging?Qu.staging:Qu.production,this.email=u.email,this.accountKey=u.accountKey||this.generateAccountKey()}generateAccountKey(){let{privateKey:u}=Ku("ec",{namedCurve:"P-256"});return u.export({type:"pkcs8",format:"pem"})}async getDirectory(){if(this.directory)return this.directory;let u=await fetch(this.directoryUrl);if(!u.ok)throw Error(`Failed to fetch ACME directory: ${u.status}`);return this.directory=await u.json(),this.directory}async getNonce(){if(this.nonce){let A=this.nonce;return this.nonce=null,A}let u=await this.getDirectory(),R=(await fetch(u.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!R)throw Error("Failed to get nonce from ACME server");return R}getJwk(){let u=this.accountKey.split(`
|
|
605
|
+
`).filter((E)=>!E.startsWith("-----")).join(""),f=Buffer.from(u,"base64"),R=f.length-65,A=f.subarray(R+1,R+33),T=f.subarray(R+33,R+65);return{kty:"EC",crv:"P-256",x:this.base64UrlEncode(A),y:this.base64UrlEncode(T)}}getJwkThumbprint(){let u=this.getJwk(),f=JSON.stringify({crv:u.crv,kty:u.kty,x:u.x,y:u.y}),R=ju("sha256").update(f).digest();return this.base64UrlEncode(R)}base64UrlEncode(u){return(typeof u==="string"?Buffer.from(u):u).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async signPayload(u,f){let R=await this.getNonce(),A=this.getJwk(),T={alg:"ES256",nonce:R,url:u};if(this.accountUrl)T.kid=this.accountUrl;else T.jwk=A;let E=this.base64UrlEncode(JSON.stringify(T)),P=f===""?"":this.base64UrlEncode(JSON.stringify(f)),L=`${E}.${P}`,z=Gg("SHA256");z.update(L);let fe=z.sign(this.accountKey),me=fe.subarray(4,4+fe[3]),At=4+fe[3]+2,Lt=fe.subarray(At,At+fe[At-1]),mt=Buffer.alloc(32),Me=Buffer.alloc(32);me.copy(mt,32-me.length),Lt.copy(Me,32-Lt.length);let ze=Buffer.concat([mt,Me]);return JSON.stringify({protected:E,payload:P,signature:this.base64UrlEncode(ze)})}async acmeRequest(u,f){let R=await this.signPayload(u,f),A=await fetch(u,{method:"POST",headers:{"Content-Type":"application/jose+json"},body:R}),T=A.headers.get("replay-nonce");if(T)this.nonce=T;let E,P=A.headers.get("content-type");if(P?.includes("application/json")||P?.includes("application/problem+json"))E=await A.json();else E=await A.text();if(!A.ok)throw Error(`ACME request failed: ${JSON.stringify(E)}`);return{body:E,headers:A.headers}}async registerAccount(){let u=await this.getDirectory(),{body:f,headers:R}=await this.acmeRequest(u.newAccount,{termsOfServiceAgreed:!0,contact:[`mailto:${this.email}`]}),A=R.get("location");if(!A)throw Error("No account URL returned");return this.accountUrl=A,A}async createOrder(u){if(!this.accountUrl)await this.registerAccount();let f=await this.getDirectory(),{body:R,headers:A}=await this.acmeRequest(f.newOrder,{identifiers:u.map((E)=>({type:"dns",value:E}))}),T=A.get("location");if(!T)throw Error("No order URL returned");return{orderUrl:T,authorizations:R.authorizations,finalize:R.finalize}}async getAuthorization(u){let{body:f}=await this.acmeRequest(u,""),R=f.identifier.value,A=this.getJwkThumbprint(),T=f.challenges.filter((E)=>E.type==="http-01"||E.type==="dns-01").map((E)=>{let P=`${E.token}.${A}`;if(E.type==="http-01")return{type:"http-01",token:E.token,keyAuthorization:P,identifier:`/.well-known/acme-challenge/${E.token}`};else{let L=this.base64UrlEncode(ju("sha256").update(P).digest());return{type:"dns-01",token:E.token,keyAuthorization:P,identifier:`_acme-challenge.${R}`,dnsValue:L}}});return{domain:R,challenges:T}}async respondToChallenge(u){await this.acmeRequest(u,{})}async waitForAuthorization(u,f=30){for(let R=0;R<f;R++){let{body:A}=await this.acmeRequest(u,"");if(A.status==="valid")return;if(A.status==="invalid")throw Error(`Authorization failed: ${JSON.stringify(A)}`);await new Promise((T)=>setTimeout(T,2000))}throw Error("Authorization timed out")}generateCsr(u){let{privateKey:f}=Ku("rsa",{modulusLength:2048}),R=f.export({type:"pkcs8",format:"pem"});return{csr:this.createSimpleCsr(u,f),privateKey:R}}createSimpleCsr(u,f){throw Error("CSR generation requires additional implementation. Consider using the shell-based certbot approach instead.")}async finalizeOrder(u,f){let{csr:R,privateKey:A}=this.generateCsr(f),{body:T}=await this.acmeRequest(u,{csr:this.base64UrlEncode(Buffer.from(R,"base64"))}),E=T.certificate;if(!E)throw Error("Certificate not immediately available - polling not implemented");let L=await(await fetch(E)).text(),z=L.split(/(?=-----BEGIN CERTIFICATE-----)/g),fe=z[0],me=z.slice(1).join("");return{certificate:fe,privateKey:A,chain:me,fullchain:L,expiresAt:new Date(Date.now()+7776000000)}}getAccountKey(){return this.accountKey}}var Gr=(u)=>u===void 0?void 0:u?"on":"off";function Mc(u){let f={ssl:u.ssl,always_use_https:Gr(u.alwaysUseHttps),automatic_https_rewrites:Gr(u.automaticHttpsRewrites),min_tls_version:u.minTlsVersion,tls_1_3:Gr(u.tls13),brotli:Gr(u.brotli),http3:Gr(u.http3),"0rtt":Gr(u.zeroRtt),early_hints:Gr(u.earlyHints),browser_cache_ttl:u.browserCacheTtl,always_online:Gr(u.alwaysOnline),websockets:Gr(u.websockets),email_obfuscation:Gr(u.emailObfuscation)};if(u.hsts)f.security_header={strict_transport_security:{enabled:u.hsts.enabled,max_age:u.hsts.maxAge??31536000,include_subdomains:u.hsts.includeSubdomains??!1,preload:u.hsts.preload??!1,nosniff:u.hsts.noSniff??!0}};for(let R of Object.keys(f))if(f[R]===void 0)delete f[R];return{...f,...u.raw??{}}}var so={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 qg}from"node:tls";async function Bc(u){let{address:f,serverName:R,port:A=443,timeoutMs:T=5000}=u;return new Promise((E)=>{let P=!1,L=(fe)=>{if(P)return;P=!0;try{z.destroy()}catch{}E(fe)},z=qg({host:f,port:A,servername:R,rejectUnauthorized:!1,timeout:T});z.once("secureConnect",()=>{if(z.authorized){L({reachable:!0,trusted:!0});return}L({reachable:!0,trusted:!1,reason:z.authorizationError?String(z.authorizationError):"origin certificate is not trusted for this hostname"})}),z.once("timeout",()=>{L({reachable:!1,trusted:!1,reason:`no TLS handshake within ${T}ms`})}),z.once("error",(fe)=>{L({reachable:!1,trusted:!1,reason:fe.message})})})}function Zg(u,f){let R=f.replace(/\.$/,"").toLowerCase();return u.some((A)=>{let T=A.replace(/\.$/,"").toLowerCase();if(T===R)return!0;if(!T.startsWith("*."))return!1;let E=T.slice(2);if(!R.endsWith(`.${E}`))return!1;return!R.slice(0,R.length-E.length-1).includes(".")})}async function Jg(u){let{provider:f,zone:R,hosts:A,ipv4:T,ipv6:E,proxied:P=!0,settings:L=so,cache:z,originGuard:fe,purge:me=!0,ttl:At=300,skipOriginProbe:Lt=!1,skipEdgeCertificateCheck:mt=!1}=u,Me={records:[],settingsChanged:[],cacheRules:0,originGuard:!1,purged:!1,deferredProxy:[],warnings:[]};if(A.length===0)return Me;let ze=[],j=P&&!mt?await f.listEdgeCertificateHosts(R):null;for(let G of A){let ht=P;if(ht&&j&&!Zg(j,G)){ht=!1;let Wt=j.length===0?"the zone has no active edge certificate yet":`no active edge certificate covers it (${j.join(", ")})`;Me.deferredProxy.push({host:G,reason:Wt}),Me.warnings.push(`${G}: publishing DNS-only — ${Wt}. 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(ht&&!Lt){let Wt=await Bc({address:T,serverName:G});if(!Wt.trusted){ht=!1;let zt=Wt.reason||"origin is not serving a trusted certificate";Me.deferredProxy.push({host:G,reason:zt}),Me.warnings.push(`${G}: publishing DNS-only for now — the origin does not yet serve a certificate this proxy can verify (${zt}). 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(ht)ze.push(G);let St=[{type:"A",content:T}];if(E&&Kn(G))St.push({type:"AAAA",content:E});for(let{type:Wt,content:zt}of St){let jt=await f.upsertRecord(R,{name:G,type:Wt,content:zt,ttl:At,proxied:ht});if(jt.success)Me.records.push({host:G,type:Wt,content:zt,proxied:ht});else Me.warnings.push(`${G} ${Wt} → ${zt} failed: ${jt.message||"unknown provider error"}`)}}if(ze.length===0){if(P)Me.warnings.push("No host is proxied yet, so zone settings, cache rules and purge were skipped — they only take effect through the proxy.");return Me}try{let G=Mc(L),ht=await f.applyZoneSettings(R,G);Me.settingsChanged=ht.changed;for(let St of ht.failed)Me.warnings.push(`zone setting '${St.id}' could not be applied: ${St.error}`)}catch(G){Me.warnings.push(`zone settings could not be read: ${G instanceof Error?G.message:String(G)}`)}let yt=Ic(ze,z);if(yt.length>0){let G=await f.putManagedPhaseRules(R,"http_request_cache_settings",yt);if(G.success)Me.cacheRules=yt.length;else Me.warnings.push(`cache rules could not be written: ${G.message}`)}if(fe){let G=bc(ze,fe.header,fe.value);if(G.length>0){let ht=await f.putManagedPhaseRules(R,"http_request_late_transform",G);if(ht.success)Me.originGuard=!0;else Me.warnings.push(`origin guard header could not be written: ${ht.message}. `+"The gateway will reject requests that lack it — disable the guard or grant the token Transform Rules: Edit.")}}if(me){if(Me.purged=await f.purgeCache(R,{hosts:ze}),!Me.purged)Me.warnings.push("edge cache purge failed — new content may take until TTL expiry to appear.")}return Me}var Yg=(u)=>process.env[u];function ed(u,f){let R=u.replace(/\.$/,"").toLowerCase();if(f){let A=f.replace(/\.$/,"").toLowerCase();if(R===A||R.endsWith(`.${A}`))return A}return R.split(".").slice(-2).join(".")}function Xg(u,f={}){let R=f.env??Yg,A=u.infrastructure?.compute?.proxy?.cdn,T=[];if(!A||A.provider!=="cloudflare")return{plan:null,errors:T};if(A.originDomain)T.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 E=R("CLOUDFLARE_API_TOKEN");if(!E)return T.push("CLOUDFLARE_API_TOKEN is not set — the Cloudflare CDN cannot be reconciled."),{plan:null,errors:T};let P=u.sites??{},L=A.frontedHosts?.length?[...new Set(A.frontedHosts.map((Lt)=>Lt.toLowerCase()))]:io(P,{autoWww:u.infrastructure?.compute?.proxy?.autoWww!==!1});if(L.length===0)return T.push("No hostnames to front — set compute.proxy.cdn.frontedHosts, or give a site a domain."),{plan:null,errors:T};let z=u.infrastructure?.dns?.domain,fe=new Set(L.map((Lt)=>ed(Lt,z)));if(fe.size>1)return T.push(`Fronted hosts span more than one zone (${[...fe].join(", ")}). A Cloudflare zone is configured as a unit, so run one CDN config per zone.`),{plan:null,errors:T};let me=A.cloudflare??{},At=A.secret?{header:A.secretHeader??"X-Origin-Verify",value:A.secret}:void 0;return{plan:{zone:[...fe][0],hosts:L,apiToken:E,zoneId:me.zoneId??R("CLOUDFLARE_ZONE_ID"),accountId:me.accountId??R("CLOUDFLARE_ACCOUNT_ID"),proxied:me.proxied!==!1,settings:me.settings??so,cache:me.cache,originGuard:At,purge:me.purgeOnDeploy!==!1,skipOriginProbe:me.skipOriginProbe===!0},errors:T}}var Qg=26214400;var th=new Set(["/_headers","/_redirects","/_routes.json","/_worker.js"]);class td{name="cloudflare-pages";apiToken;accountId;constructor(u){if(!u.apiToken)throw Error("Cloudflare Pages needs an API token");if(!u.accountId)throw Error("Cloudflare Pages needs an account id");this.apiToken=u.apiToken,this.accountId=u.accountId}async request(u,f,R){return Ks(u,`/accounts/${this.accountId}${f}`,`Bearer ${this.apiToken}`,R)}async getProject(u){try{return await this.request("GET",`/pages/projects/${u}`)}catch(f){if(f instanceof Error&&/\b8000007\b|not found/i.test(f.message))return null;throw f}}async ensureProject(u,f="main"){let R=await this.getProject(u);if(R)return R;return this.request("POST","/pages/projects",{name:u,production_branch:f})}async uploadToken(u){return(await this.request("GET",`/pages/projects/${u}/upload-token`)).jwt}async missingHashes(u,f){let R=await Ks("POST","/pages/assets/check-missing",`Bearer ${u}`,{hashes:f});return new Set(R)}async upsertHashes(u,f){await Ks("POST","/pages/assets/upsert-hashes",`Bearer ${u}`,{hashes:f})}async uploadBatch(u,f){let R=f.map((A)=>({key:A.hash,value:A.base64,metadata:{contentType:nh(A.extension)},base64:!0}));await Ks("POST","/pages/assets/upload",`Bearer ${u}`,R)}async createDeployment(u,f,R){let A={};for(let E of f)A[E.path]=E.hash;let T=new FormData;if(T.append("manifest",JSON.stringify(A)),R)T.append("branch",R);return this.request("POST",`/pages/projects/${u}/deployments`,T)}async deployDirectory(u){let f=await ep(u.directory);if(f.length===0)throw Error(`No files to deploy in ${u.directory}`);let R=await this.uploadToken(u.project),A=await this.missingHashes(R,f.map((z)=>z.hash)),T=f.filter((z)=>A.has(z.hash)),E=[];for(let z=0;z<T.length;z+=100)E.push(T.slice(z,z+100));let P=0;for(let z=0;z<E.length;z+=4){let fe=E.slice(z,z+4);await Promise.all(fe.map((me)=>this.uploadBatch(R,me))),P+=fe.reduce((me,At)=>me+At.length,0),u.onProgress?.(P,T.length)}return await this.upsertHashes(R,f.map((z)=>z.hash)),{deployment:await this.createDeployment(u.project,f,u.branch),total:f.length,uploaded:T.length,uploadedBytes:T.reduce((z,fe)=>z+fe.size,0)}}async listCustomDomains(u){return(await this.request("GET",`/pages/projects/${u}/domains`)).map((R)=>R.name)}async attachCustomDomain(u,f){if((await this.listCustomDomains(u)).includes(f))return!1;return await this.request("POST",`/pages/projects/${u}/domains`,{name:f}),!0}}function rh(u,f){return{type:"CNAME",name:u,value:f.endsWith(".pages.dev")?f:`${f}.pages.dev`,ttl:1,proxied:!0}}async function rd(u,f){let{blake3:R}=await import("./chunk-4yqd62rd.js").then((m)=>SS(m.default,1));return(await R(u+f)).slice(0,32)}async function ep(u){let{readdir:f}=await import("node:fs/promises"),{join:R,relative:A,sep:T}=await import("node:path"),E=[];async function P(L){let z=await f(L,{withFileTypes:!0});for(let fe of z){let me=R(L,fe.name);if(fe.isDirectory()){await P(me);continue}if(!fe.isFile())continue;let At=`/${A(u,me).split(T).join("/")}`;if(th.has(At))continue;let Lt=await Bun.file(me).bytes();if(Lt.byteLength>26214400)throw Error(`${At} is ${Lt.byteLength} bytes, over the Cloudflare Pages limit of 26214400`);let mt=Buffer.from(Lt).toString("base64"),Me=fe.name.lastIndexOf("."),ze=Me>0?fe.name.slice(Me+1):"";E.push({path:At,hash:await rd(mt,ze),base64:mt,extension:ze,size:Lt.byteLength})}}return await P(u),E.sort((L,z)=>L.path.localeCompare(z.path)),E}function nh(u){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"}[u.toLowerCase()]||"application/octet-stream"}async function Ks(u,f,R,A){let T={Authorization:R},E;if(A instanceof FormData)E=A;else if(A!==void 0)T["Content-Type"]="application/json",E=JSON.stringify(A);let P=await fetch(`https://api.cloudflare.com/client/v4${f}`,{method:u,headers:T,body:E}),L=await P.text(),z;try{z=JSON.parse(L)}catch{throw Error(`Cloudflare Pages API returned ${P.status} with a non-JSON body: ${L.slice(0,200)}`)}if(!z.success){let fe=(z.errors??[]).map((me)=>`${me.code}: ${me.message}`).join(", ");throw Error(`Cloudflare Pages API error (${P.status}): ${fe||L.slice(0,200)}`)}return z.result}import{createHash as ih}from"node:crypto";var rp="https://api.cloudflare.com/client/v4",np=10042,oh=10006,sh=10059;class Fn extends Error{status;errors;constructor(u,f,R=[]){super(u);this.name="R2ApiError",this.status=f,this.errors=R}hasCode(u){return this.errors.some((f)=>f.code===u)}}class Pn extends Fn{accountId;constructor(u,f,R=[]){super(`R2 is not enabled on Cloudflare account ${u}. Enable it once in the Cloudflare dashboard (R2 Object Storage, then follow the prompt to activate it), then re-run the deploy.`,f,R);this.name="R2NotEnabledError",this.accountId=u}}class oi{name="cloudflare-r2";apiToken;accountId;fetchImpl;constructor(u){if(!u.apiToken)throw Error("Cloudflare R2 needs an API token");if(!u.accountId)throw Error("Cloudflare R2 needs an account id");this.apiToken=u.apiToken,this.accountId=u.accountId,this.fetchImpl=u.fetch??((f,R)=>fetch(f,R))}async requestEnvelope(u,f,R,A={}){let T={Authorization:`Bearer ${this.apiToken}`};if(R!==void 0)T["Content-Type"]="application/json";if(A.jurisdiction&&A.jurisdiction!=="default")T["cf-r2-jurisdiction"]=A.jurisdiction;let E=await this.fetchImpl(`${rp}/accounts/${this.accountId}/r2${f}`,{method:u,headers:T,body:R===void 0?void 0:JSON.stringify(R)}),P=await E.text(),L;try{L=JSON.parse(P)}catch{throw new Fn(`Cloudflare R2 API returned ${E.status} with a non-JSON body: ${P.slice(0,200)}`,E.status)}if(!L.success){let z=L.errors??[];if(z.some((me)=>me.code===np))throw new Pn(this.accountId,E.status,z);let fe=z.map((me)=>`${me.code}: ${me.message}`).join(", ");throw new Fn(`Cloudflare R2 API error (${E.status}) on ${u} ${f}: ${fe||P.slice(0,200)}`,E.status,z)}return L}async request(u,f,R,A){return(await this.requestEnvelope(u,f,R,A)).result}bucketPath(u){return`/buckets/${encodeURIComponent(u)}`}async listBuckets(u={}){let f=[],R;do{let A=new URLSearchParams({per_page:"1000"});if(R)A.set("cursor",R);let T=await this.requestEnvelope("GET",`/buckets?${A}`,void 0,u),E=T.result?.buckets??[];f.push(...E),R=E.length>0?T.result_info?.cursor||void 0:void 0}while(R);return f}async getBucket(u,f={}){try{return await this.request("GET",this.bucketPath(u),void 0,f)}catch(R){if(R instanceof Pn)throw R;if(R instanceof Fn&&(R.hasCode(oh)||R.status===404))return null;throw R}}async ensureBucket(u,f={}){let R={jurisdiction:f.jurisdiction},A=await this.getBucket(u,R);if(A)return{bucket:A,created:!1};let T={name:u};if(f.locationHint)T.locationHint=f.locationHint;let E=await this.request("POST","/buckets",T,R);return{bucket:{...E,name:E?.name||u},created:!0}}async getCors(u,f={}){try{return(await this.request("GET",`${this.bucketPath(u)}/cors`,void 0,f))?.rules??[]}catch(R){if(R instanceof Fn&&!(R instanceof Pn)&&(R.hasCode(sh)||R.status===404))return[];throw R}}async putCors(u,f,R={}){if(f.length===0){await this.request("DELETE",`${this.bucketPath(u)}/cors`,void 0,R);return}await this.request("PUT",`${this.bucketPath(u)}/cors`,{rules:f},R)}async ensureCors(u,f,R={}){let A=await this.getCors(u,R);if(qs(A,f))return!1;return await this.putCors(u,f,R),!0}async getLifecycle(u,f={}){return(await this.request("GET",`${this.bucketPath(u)}/lifecycle`,void 0,f))?.rules??[]}async putLifecycle(u,f,R={}){await this.request("PUT",`${this.bucketPath(u)}/lifecycle`,{rules:f},R)}async ensureLifecycle(u,f,R={}){let A=await this.getLifecycle(u,R);if(Ga(A,f))return!1;return await this.putLifecycle(u,f,R),!0}async listCustomDomains(u,f={}){return(await this.request("GET",`${this.bucketPath(u)}/domains/custom`,void 0,f))?.domains??[]}async attachCustomDomain(u,f,R={}){return this.request("POST",`${this.bucketPath(u)}/domains/custom`,{domain:f.domain,zoneId:f.zoneId,enabled:f.enabled??!0,minTLS:f.minTLS??"1.2"},R)}async updateCustomDomain(u,f,R,A={}){return this.request("PUT",`${this.bucketPath(u)}/domains/custom/${encodeURIComponent(f)}`,R,A)}async ensureCustomDomain(u,f,R={},A){let T=f.minTLS??"1.2",P=(A??await this.listCustomDomains(u,R)).find((fe)=>fe.domain.toLowerCase()===f.domain.toLowerCase());if(!P){let fe=await this.attachCustomDomain(u,{...f,minTLS:T,enabled:!0},R);return{action:"attached",domain:{...fe,domain:fe?.domain||f.domain}}}let L=P.minTLS??"1.0";if(P.enabled&&L===T)return{action:"unchanged",domain:P};let z=await this.updateCustomDomain(u,P.domain,{enabled:!0,minTLS:T},R);return{action:"updated",domain:{...P,...z}}}async getManagedDomain(u,f={}){return this.request("GET",`${this.bucketPath(u)}/domains/managed`,void 0,f)}async setManagedDomain(u,f,R={}){let A=await this.getManagedDomain(u,R);if(A?.enabled===f)return{changed:!1,domain:A};return{changed:!0,domain:await this.request("PUT",`${this.bucketPath(u)}/domains/managed`,{enabled:f},R)}}}function ip(u){return`https://${u}.r2.cloudflarestorage.com`}async function ah(u){let{apiToken:f,accountId:R}=u;if(!f)throw Error("r2S3Credentials needs an API token");if(!R)throw Error("r2S3Credentials needs an account id");let A=u.fetch??((P,L)=>fetch(P,L)),T=[],E;for(let P of[`/accounts/${R}/tokens/verify`,"/user/tokens/verify"]){let L=await A(`${rp}${P}`,{method:"GET",headers:{Authorization:`Bearer ${f}`}}),z=await L.json().catch(()=>null);if(L.ok&&z?.success&&z.result?.id){E=z.result.id;break}let fe=z?.errors?.map((me)=>`${me.code}: ${me.message}`).join(", ");T.push(`${P} -> ${L.status}${fe?` (${fe})`:""}`)}if(!E)throw Error(`Could not verify the Cloudflare API token to derive R2 credentials: ${T.join("; ")}`);return{accessKeyId:E,secretAccessKey:ih("sha256").update(f).digest("hex"),endpoint:ip(R),region:"auto"}}function ms(u){if(Array.isArray(u))return`[${u.map(ms).join(",")}]`;if(u&&typeof u==="object")return`{${Object.entries(u).filter(([,R])=>R!==void 0).sort(([R],[A])=>R.localeCompare(A)).map(([R,A])=>`${JSON.stringify(R)}:${ms(A)}`).join(",")}}`;return JSON.stringify(u)}function tp(u,f){let R=(A)=>A&&A.length>0?[...A].map(String).sort():void 0;return{id:f?u.id:void 0,allowed:{origins:R(u.allowed?.origins),methods:R(u.allowed?.methods?.map((A)=>A.toUpperCase())),headers:R(u.allowed?.headers?.map((A)=>A.toLowerCase()))},exposeHeaders:R(u.exposeHeaders?.map((A)=>A.toLowerCase())),maxAgeSeconds:u.maxAgeSeconds}}function qs(u,f){if(u.length!==f.length)return!1;return f.every((R,A)=>{let T=R.id!==void 0;return ms(tp(u[A],T))===ms(tp(R,T))})}function Ga(u,f){if(u.length!==f.length)return!1;let R=(A)=>ms([...A].map((T)=>({...T,storageClassTransitions:T.storageClassTransitions?.length?T.storageClassTransitions:void 0})).sort((T,E)=>T.id.localeCompare(E.id)));return R(u)===R(f)}var uh="r2 cache",ph=/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/;async function mh(u,f={}){let R=f.log??(()=>{}),A={buckets:[],warnings:[]},T=u.infrastructure?.r2??u.r2,E=Object.entries(T?.buckets??{});if(E.length===0)return R("R2: no buckets declared, skipping."),A;if(!f.apiToken||!f.accountId){let me=[!f.apiToken&&"CLOUDFLARE_API_TOKEN",!f.accountId&&"CLOUDFLARE_ACCOUNT_ID"].filter(Boolean).join(" and "),At=`R2: ${E.length} bucket(s) declared but ${me} is not set, skipping.`;return R(At),A.warnings.push(At),A}let P=f.dryRun===!0,L=new oi({apiToken:f.apiToken,accountId:f.accountId,fetch:f.fetch}),z=new H(f.apiToken,{zoneId:f.zoneId,accountId:f.accountId}),fe=new Map;for(let[me,At]of E){let Lt=At?.name;if(!Lt||!ph.test(Lt)){A.warnings.push(`R2: bucket '${me}' has an invalid name '${Lt??""}' (3-63 chars: lowercase letters, digits, hyphens), skipping.`);continue}R(`R2: ${P?"checking":"reconciling"} bucket ${Lt}...`);let mt={name:Lt,changes:[],domains:[]};if(A.buckets.push(mt),await gh(At,{r2:L,cloudflare:z,dryRun:P,summary:mt,warnings:A.warnings,claimed:fe,log:R}),mt.changes.length===0)R(`R2: ${Lt} is in sync.`);else for(let Me of mt.changes)R(`R2: ${Lt}: ${Me}`)}return A}async function gh(u,f){let{r2:R,dryRun:A,summary:T,warnings:E}=f,P=u.name,L={jurisdiction:u.jurisdiction},z=(mt,Me)=>{let ze=A?Me&&`would ${Me}`:mt;if(ze)T.changes.push(ze)},fe;if(A)fe=await R.getBucket(P,L)!==null;else{let{created:mt}=await R.ensureBucket(P,{locationHint:u.locationHint,jurisdiction:u.jurisdiction});if(fe=!0,mt)z("created","")}if(!fe)z("","create bucket");let me=hh(u.customDomains);await hs(f,`cors on ${P}`,async()=>{if(!u.cors)return;if(!fe){z("cors updated","set cors");return}let mt=await R.getCors(P,L);if(qs(mt,u.cors))return;if(!A)await R.putCors(P,u.cors,L);z(u.cors.length===0?"cors removed":"cors updated",u.cors.length===0?"remove cors":"update cors")}),await hs(f,`lifecycle on ${P}`,async()=>{if(!u.lifecycle)return;let mt=u.lifecycle.map(cp);if(fe){let Me=await R.getLifecycle(P,L);if(Ga(Me,mt))return}if(!A)await R.putLifecycle(P,mt,L);z("lifecycle updated","update lifecycle")}),await hs(f,`r2.dev URL on ${P}`,async()=>{let mt=u.publicDevUrl===!0;if(!fe){if(mt)z("r2.dev URL enabled","enable r2.dev URL");return}if((await R.getManagedDomain(P,L))?.enabled===mt)return;if(!A)await R.setManagedDomain(P,mt,L);z(mt?"r2.dev URL enabled":"r2.dev URL disabled",mt?"enable r2.dev URL":"disable r2.dev URL")});let At=[];if(me.length>0&&fe)try{At=await R.listCustomDomains(P,L)}catch(mt){if(mt instanceof Pn)throw mt;E.push(`R2: could not list custom domains on ${P}: ${Gc(mt)}`)}let Lt=new Map;for(let{domain:mt,minTLS:Me}of me){let ze=f.claimed.get(mt);if(ze&&ze!==P){E.push(`R2: ${mt} is declared on both ${ze} and ${P}; leaving it on ${ze}.`);continue}f.claimed.set(mt,P);let j=At.find((G)=>G.domain.toLowerCase()===mt),yt=Me??"1.2";if(j&&j.enabled&&(j.minTLS??"1.0")===yt){if(T.domains.push({domain:mt,status:Hc(j)}),j.zoneId)Lt.set(mt,j.zoneId);continue}await hs(f,`custom domain ${mt} on ${P}`,async()=>{if(j){if(!A)await R.updateCustomDomain(P,j.domain,{enabled:!0,minTLS:yt},L);if(z(`custom domain ${mt} updated`,`update custom domain ${mt}`),T.domains.push({domain:mt,status:Hc({...j,enabled:!0})}),j.zoneId)Lt.set(mt,j.zoneId);return}let G=await f.cloudflare.zoneIdFor(mt);if(Lt.set(mt,G),!A)await R.ensureCustomDomain(P,{domain:mt,zoneId:G,minTLS:yt},L,At);z(`custom domain ${mt} attached`,`attach custom domain ${mt}`),T.domains.push({domain:mt,status:A?"not attached":"pending"})},()=>T.domains.push({domain:mt,status:"error"}))}if(u.cache&&me.length>0)await fh(u,me.map((mt)=>mt.domain).filter((mt)=>f.claimed.get(mt)===P),Lt,f,z)}async function fh(u,f,R,A,T){let E=op(u.cache);if(!E||f.length===0)return;let P=new Map;for(let L of f){let z=R.get(L);if(!z)try{z=await A.cloudflare.zoneIdFor(L)}catch(fe){A.warnings.push(`R2: could not resolve the zone for ${L}, cache rule skipped: ${Gc(fe)}`);continue}P.set(z,[...P.get(z)??[],L])}for(let L of P.values()){let z={action:"set_cache_settings",description:`${Gt} ${uh}`,expression:`(${Ht(L)})`,enabled:!0,action_parameters:E};await hs(A,`cache rule for ${L.join(", ")}`,async()=>{let fe=await A.cloudflare.getPhaseRules(L[0],"http_request_cache_settings");if(ap(fe,z))return;if(!A.dryRun){let me=await A.cloudflare.putManagedPhaseRules(L[0],"http_request_cache_settings",[z]);if(!me.success)throw Error(me.message||"cache rule write failed")}T(`cache rule updated for ${L.join(", ")}`,`update cache rule for ${L.join(", ")}`)})}}function op(u){if(u.edgeTtl===void 0&&u.browserTtl===void 0)return null;let f={cache:!0};if(u.edgeTtl!==void 0)f.edge_ttl={mode:"override_origin",default:u.edgeTtl};if(u.browserTtl!==void 0)f.browser_ttl={mode:"override_origin",default:u.browserTtl};return f}function ap(u,f){let R=Vt(f.expression),A=Vn(f.expression),T=(L)=>(L.description||"").startsWith(Gt),E=(L)=>L.action===f.action&&L.description===f.description&&(L.enabled??!0)===(f.enabled??!0)&&Vn(L.expression)===A&&Qa(L.action_parameters)===Qa(f.action_parameters),P=!1;for(let L of u){if(!T(L))continue;let z=Vt(L.expression);if(!R.some((me)=>z.includes(me)))continue;if(E(L)&&R.every((me)=>z.includes(me))&&!P){P=!0;continue}return!1}return P}function cp(u){let f={id:u.id,enabled:u.enabled??!0,conditions:{prefix:u.prefix??""}};if(u.expireAfterDays!==void 0)f.deleteObjectsTransition={condition:{type:"Age",maxAge:Vc(u.expireAfterDays)}};else if(u.expireOn!==void 0)f.deleteObjectsTransition={condition:{type:"Date",date:u.expireOn}};if(u.abortMultipartUploadsAfterDays!==void 0)f.abortMultipartUploadsTransition={condition:{type:"Age",maxAge:Vc(u.abortMultipartUploadsAfterDays)}};if(u.infrequentAccessAfterDays!==void 0)f.storageClassTransitions=[{storageClass:"InfrequentAccess",condition:{type:"Age",maxAge:Vc(u.infrequentAccessAfterDays)}}];return f}function Vc(u){return Math.round(u*86400)}function hh(u){let f=new Set,R=[];for(let A of u??[]){let T=typeof A==="string"?{domain:A}:A,E=T.domain?.trim().replace(/\.$/,"").toLowerCase();if(!E||f.has(E))continue;f.add(E),R.push({domain:E,minTLS:T.minTLS})}return R}function Hc(u){if(!u.enabled)return"disabled";let f=u.status?.ownership,R=u.status?.ssl;if(f==="active"&&R==="active")return"active";for(let A of[f,R])if(A==="error"||A==="blocked"||A==="deactivated")return A;return"pending"}async function hs(u,f,R,A){try{await R()}catch(T){if(T instanceof Pn)throw T;u.warnings.push(`R2: ${f} failed: ${Gc(T)}`),A?.()}}function Gc(u){return u instanceof Error?u.message:String(u)}function Qa(u){if(Array.isArray(u))return`[${u.map(Qa).join(",")}]`;if(u&&typeof u==="object")return`{${Object.entries(u).filter(([,R])=>R!==void 0).sort(([R],[A])=>R.localeCompare(A)).map(([R,A])=>`${JSON.stringify(R)}:${Qa(A)}`).join(",")}}`;return JSON.stringify(u)}import{basename as Th,extname as Ph}from"node:path";import{createHash as yh}from"node:crypto";var Ch="https://api.cloudflare.com/client/v4",On="TS_CLOUD_CONTENT_HASH",Ts="2025-09-01",qc="application/javascript+module",Sh=10007,Rh=[1e4,9109];class si extends Error{status;errors;constructor(u,f,R=[]){super(u);this.name="WorkersApiError",this.status=f,this.errors=R}hasCode(u){return this.errors.some((f)=>f.code===u)}}class mc extends si{permission;constructor(u,f,R,A=[]){super(`The Cloudflare API token is missing the "${u}" permission (${f}). Edit the token in the Cloudflare dashboard (My Profile, API Tokens), add it, then re-run the deploy.`,R,A);this.name="WorkersPermissionError",this.permission=u}}class hc{name="cloudflare-workers";apiToken;accountId;fetchImpl;constructor(u){if(!u.apiToken)throw Error("Cloudflare Workers needs an API token");if(!u.accountId)throw Error("Cloudflare Workers needs an account id");this.apiToken=u.apiToken,this.accountId=u.accountId,this.fetchImpl=u.fetch??((f,R)=>fetch(f,R))}async request(u,f,R){let A={Authorization:`Bearer ${this.apiToken}`},T;if(R instanceof FormData)T=R;else if(R!==void 0)A["Content-Type"]="application/json",T=JSON.stringify(R);let E=await this.fetchImpl(`${Ch}/accounts/${this.accountId}/workers${f}`,{method:u,headers:A,body:T}),P=await E.text(),L;try{L=JSON.parse(P)}catch{throw new si(`Cloudflare Workers API returned ${E.status} with a non-JSON body: ${P.slice(0,200)}`,E.status)}if(!L.success){let z=L.errors??[],fe=z.map((me)=>`${me.code}: ${me.message}`).join(", ");if(bh(E.status,z))throw new mc(Ah(f),`${u} ${f} -> ${E.status}${fe?`, ${fe}`:""}`,E.status,z);throw new si(`Cloudflare Workers API error (${E.status}) on ${u} ${f}: ${fe||P.slice(0,200)}`,E.status,z)}return L.result}scriptPath(u){return`/scripts/${encodeURIComponent(u)}`}async getSettings(u){try{return await this.request("GET",`${this.scriptPath(u)}/settings`)}catch(f){if(f instanceof mc)throw f;if(f instanceof si&&(f.hasCode(Sh)||f.status===404))return null;throw f}}async getScript(u){return this.getSettings(u)}async uploadModuleScript(u,f){return this.request("PUT",this.scriptPath(u),dp(f))}async ensureModuleScript(u,f){let R=Ps(f),A=await this.getSettings(u);if(A&&Pc(A,f,R))return{action:"unchanged",hash:R};return await this.uploadModuleScript(u,eg(f,R)),{action:A?"updated":"created",hash:R}}async listCustomDomains(u={}){let f=new URLSearchParams;if(u.service)f.set("service",u.service);if(u.hostname)f.set("hostname",u.hostname);if(u.zoneId)f.set("zone_id",u.zoneId);let R=f.toString(),A=R?`?${R}`:"";return await this.request("GET",`/domains${A}`)??[]}async attachCustomDomain(u,f){let R={hostname:u,service:f.service,environment:f.environment??"production"};if(f.zoneId)R.zone_id=f.zoneId;return this.request("PUT","/domains",R)}async detachCustomDomain(u){await this.request("DELETE",`/domains/${encodeURIComponent(u)}`)}async ensureCustomDomain(u,f,R){let T=(R??await this.listCustomDomains({hostname:u})).find((P)=>P.hostname.toLowerCase()===u.toLowerCase());if(T&&T.service===f.service)return{action:"unchanged",domain:T};if(T)throw Error(`${u} is attached to the Worker '${T.service}'. Detach it there first (Workers & Pages, ${T.service}, Settings, Domains & Routes); ts-cloud does not move it.`);let E=await this.attachCustomDomain(u,f);return{action:"attached",domain:{...E,hostname:E?.hostname||u}}}}function bh(u,f){if(f.some((R)=>Rh.includes(R.code)))return!0;return(u===401||u===403)&&f.length===0}function Ah(u){if(u.startsWith("/domains"))return"Workers Routes: Edit (zone, for Workers custom domains) and Workers Scripts: Edit (account)";return"Workers Scripts: Edit (account)"}function dp(u){if(!u.modules.some((A)=>A.name===u.mainModule))throw Error(`Worker main module '${u.mainModule}' is not one of the uploaded modules`);let f={main_module:u.mainModule,bindings:u.bindings??[],compatibility_date:u.compatibilityDate??Ts,compatibility_flags:u.compatibilityFlags??[],keep_bindings:["secret_text"]},R=new FormData;R.append("metadata",JSON.stringify(f));for(let A of u.modules)R.append(A.name,new Blob([A.content],{type:A.type}),A.name);return R}function Ps(u){let f={mainModule:u.mainModule,modules:[...u.modules].sort((R,A)=>R.name.localeCompare(A.name)).map((R)=>({name:R.name,type:R.type,sha256:lp(R.content)})),bindings:[...u.bindings??[]].filter((R)=>R.name!==On).sort((R,A)=>R.name.localeCompare(A.name)),compatibilityDate:u.compatibilityDate??Ts,compatibilityFlags:[...u.compatibilityFlags??[]].sort()};return lp(jc(f))}function eg(u,f=Ps(u)){return{...u,bindings:[...(u.bindings??[]).filter((R)=>R.name!==On),{type:"plain_text",name:On,text:f}]}}function Pc(u,f,R){let A=u.bindings??[],T=A.find((E)=>E.name===On&&E.type==="plain_text");if(!T||T.text!==R)return!1;return(f.bindings??[]).every((E)=>{let P=A.find((z)=>z.name===E.name);if(!P||P.type!==E.type)return!1;let L=E.type==="r2_bucket"?"bucket_name":E.type==="plain_text"?"text":void 0;return!L||P[L]===E[L]})}function lp(u){return yh("sha256").update(u).digest("hex")}function jc(u){if(Array.isArray(u))return`[${u.map(jc).join(",")}]`;if(u&&typeof u==="object")return`{${Object.entries(u).filter(([,R])=>R!==void 0).sort(([R],[A])=>R.localeCompare(A)).map(([R,A])=>`${JSON.stringify(R)}:${jc(A)}`).join(",")}}`;return JSON.stringify(u)}async function Zc(u){if(!await Bun.file(u).exists())throw Error(`Worker entry not found: ${u}`);let f;try{f=await Bun.build({entrypoints:[u],target:"browser",format:"esm",minify:!0,external:["cloudflare:*"]})}catch(T){throw Error(`Bundling Worker ${u} failed: ${$h(T)}`)}if(!f.success)throw Error(`Bundling Worker ${u} failed: ${f.logs.map((T)=>String(T.message??T)).join("; ")}`);if(f.outputs.length!==1)throw Error(`Bundling Worker ${u} produced ${f.outputs.length} files (${f.outputs.map((T)=>T.path).join(", ")}); a Worker is uploaded as a single module, so remove the dynamic imports or asset imports that split it.`);let R=f.outputs[0];if(R.kind!=="entry-point")throw Error(`Bundling Worker ${u} produced a ${R.kind} instead of an entry module`);let A=await R.text();return{name:`${Th(u,Ph(u))}.js`,content:A,type:qc,size:new TextEncoder().encode(A).byteLength}}function $h(u){if(u instanceof AggregateError&&u.errors.length>0)return u.errors.map((f)=>f instanceof Error?f.message:String(f?.message??f)).join("; ");return u instanceof Error?u.message:String(u)}import{isAbsolute as wh,resolve as Ih}from"node:path";var Dh="https://api.cloudflare.com/client/v4",kh=/^[a-z0-9][a-z0-9_-]{0,62}$/;async function vh(u,f={}){let R=f.log??(()=>{}),A={workers:[],warnings:[]},T=Object.entries(u.infrastructure?.workers??u.workers??{});if(T.length===0)return R("Workers: none declared, skipping."),A;if(!f.apiToken||!f.accountId){let L=[!f.apiToken&&"CLOUDFLARE_API_TOKEN",!f.accountId&&"CLOUDFLARE_ACCOUNT_ID"].filter(Boolean).join(" and "),z=`Workers: ${T.length} Worker(s) declared but ${L} is not set, skipping.`;return R(z),A.warnings.push(z),A}let E=u.infrastructure?.r2??u.r2,P={workers:new hc({apiToken:f.apiToken,accountId:f.accountId,fetch:f.fetch}),r2:new oi({apiToken:f.apiToken,accountId:f.accountId,fetch:f.fetch}),cloudflare:new H(f.apiToken,{zoneId:f.zoneId,accountId:f.accountId}),apiToken:f.apiToken,fetch:f.fetch??((L,z)=>fetch(L,z)),projectRoot:f.projectRoot??process.cwd(),dryRun:f.dryRun===!0,warnings:A.warnings,log:R,r2ConfigDomains:_h(E),r2Buckets:E,claimed:new Map};for(let[L,z]of T){let fe=z?.name;if(!fe||!kh.test(fe)){A.warnings.push(`Workers: '${L}' has an invalid name '${fe??""}' (1-63 chars: lowercase letters, digits, '-' and '_'), skipping.`);continue}if(!z.entry){A.warnings.push(`Workers: ${fe} has no entry, skipping.`);continue}R(`Workers: ${P.dryRun?"checking":"reconciling"} ${fe}...`);let me={name:fe,changes:[],domains:[]};A.workers.push(me),await Oh(z,me,P);for(let At of me.changes)R(`Workers: ${fe}: ${At}`)}return A}async function Oh(u,f,R){let A=u.name,T=wh(u.entry)?u.entry:Ih(R.projectRoot,u.entry),E;try{E=await Zc(T)}catch(L){throw Error(`Worker ${A}: ${mi(L)}`)}f.changes.push(`bundled ${Bh(E.size)}`);let P={mainModule:E.name,modules:[{name:E.name,content:E.content,type:E.type}],bindings:tg(u,R),compatibilityDate:u.compatibilityDate??Ts,compatibilityFlags:u.compatibilityFlags??[]};if(R.dryRun){let L=await R.workers.getSettings(A);f.changes.push(L&&Pc(L,P,Ps(P))?"unchanged":"would upload")}else{let{action:L}=await R.workers.ensureModuleScript(A,P);f.changes.push(L==="unchanged"?"unchanged":"uploaded")}for(let L of Mh(u.customDomains))await Nh(A,L,f,R)}async function Nh(u,f,R,A){let T=(mt)=>{R.domains.push({domain:f,status:mt})},E=(mt)=>{A.warnings.push(`Workers: ${mt}`),T("conflict")},P=A.claimed.get(f);if(P&&P!==u){E(`${f} is declared on both ${P} and ${u}; leaving it on ${P}.`);return}A.claimed.set(f,u);let L=A.r2ConfigDomains.get(f);if(L){E(`${f} is also declared as a custom domain of the R2 bucket '${L}' (r2.buckets). A hostname serves either a bucket or a Worker. Remove it from the bucket's customDomains and detach it in the dashboard (R2, ${L}, Settings, Custom Domains) first; to serve the bucket through the Worker, bind it with bindings.r2Buckets instead.`);return}let z=await xh(A);if(z===null){T("error");return}let fe=z.find((mt)=>mt.hostname.toLowerCase()===f);if(fe?.service===u){T("active");return}if(fe){E(`${f} is attached to the Worker '${fe.service}'. Detach it there first (Workers & Pages, ${fe.service}, Settings, Domains & Routes); it is not moved automatically.`);return}let me=(await Lh(A))?.get(f);if(me){E(`${f} is attached to the R2 bucket '${me}' as a custom domain. Detach it first (R2, ${me}, Settings, Custom Domains, then re-run the deploy); it is not detached automatically. To serve the bucket through the Worker, bind it with bindings.r2Buckets.`);return}let At;try{At=await A.cloudflare.zoneIdFor(f)}catch(mt){A.warnings.push(`Workers: could not resolve the zone for ${f}, not attached: ${mi(mt)}`),T("error");return}let Lt=await Fh(A,At,f);if(Lt.length>0){let mt=Lt.map((Me)=>`${Me.type} ${Me.content}`).join(", ");E(`${f} already has a DNS record (${mt}). A Worker custom domain creates its own record, so Cloudflare will not attach over it. Delete the record first (DNS, Records), then re-run the deploy; it is not deleted automatically.`);return}if(A.dryRun){R.changes.push(`would attach custom domain ${f}`),T("not attached");return}try{await A.workers.ensureCustomDomain(f,{service:u,zoneId:At},z),R.changes.push(`custom domain ${f} attached`),z.push({id:"",hostname:f,service:u,zone_id:At}),T("pending")}catch(mt){A.warnings.push(`Workers: custom domain ${f} on ${u} failed: ${mi(mt)}`),T("error")}}async function xh(u){if(u.attached!==void 0)return u.attached;try{u.attached=await u.workers.listCustomDomains()}catch(f){u.warnings.push(`Workers: could not list Worker custom domains, none attached: ${mi(f)}`),u.attached=null}return u.attached}async function Lh(u){if(u.r2AccountDomains!==void 0)return u.r2AccountDomains;let f=new Map;try{let R=(await u.r2.listBuckets()).map((A)=>({name:A.name}));for(let A of Object.values(u.r2Buckets?.buckets??{}))if(A.jurisdiction&&A.jurisdiction!=="default")R.push({name:A.name,jurisdiction:A.jurisdiction});for(let A of R){let T=await u.r2.listCustomDomains(A.name,{jurisdiction:A.jurisdiction}).catch(()=>[]);for(let E of T)f.set(E.domain.toLowerCase(),A.name)}u.r2AccountDomains=f}catch(R){u.log(`Workers: could not check R2 custom domains (${mi(R)}); relying on the DNS check.`),u.r2AccountDomains=null}return u.r2AccountDomains}async function Fh(u,f,R){try{let A=await u.fetch(`${Dh}/zones/${f}/dns_records?name=${encodeURIComponent(R)}&per_page=100`,{method:"GET",headers:{Authorization:`Bearer ${u.apiToken}`}}),T=await A.json();if(!T?.success)throw Error(`HTTP ${A.status}`);return(T.result??[]).filter((E)=>E.name?.toLowerCase()===R).map((E)=>({type:E.type??"?",content:E.content??""}))}catch(A){return u.log(`Workers: could not read DNS records for ${R} (${mi(A)}); attaching anyway.`),[]}}function tg(u,f){let R=[],A=new Set,T=(P)=>{if(P===On)return f.warnings.push(`Workers: ${u.name}: binding name ${On} is reserved for ts-cloud, ignored.`),!1;if(A.has(P))return f.warnings.push(`Workers: ${u.name}: binding ${P} is declared twice; the first one wins.`),!1;return A.add(P),!0},E=new Map;for(let P of Object.values(f.r2Buckets?.buckets??{}))if(P.jurisdiction&&P.jurisdiction!=="default")E.set(P.name,P.jurisdiction);for(let[P,L]of Object.entries(u.bindings?.r2Buckets??{})){if(!T(P))continue;let z=E.get(L);R.push(z?{type:"r2_bucket",name:P,bucket_name:L,jurisdiction:z}:{type:"r2_bucket",name:P,bucket_name:L})}for(let[P,L]of Object.entries(u.bindings?.vars??{}))if(T(P))R.push({type:"plain_text",name:P,text:String(L)});return R}function _h(u){let f=new Map;for(let R of Object.values(u?.buckets??{}))for(let A of R?.customDomains??[]){let T=lg(typeof A==="string"?A:A.domain);if(T)f.set(T,R.name)}return f}function Mh(u){return[...new Set((u??[]).map(lg).filter(Boolean))]}function lg(u){return(u??"").trim().replace(/\.$/,"").toLowerCase()}function Bh(u){if(u<1024)return`${u} B`;if(u<1048576)return`${(u/1024).toFixed(1)} KB`;return`${(u/1024/1024).toFixed(1)} MB`}function mi(u){return u instanceof Error?u.message:String(u)}export{yl as ABTestManager,ye as ACMClient,Dr as ACMDnsValidator,Qu as ACME_DIRECTORIES,Oe as AI,eu as API_IDEMPOTENCY_TTL_MS,Yl as API_TOKEN_DEFAULT_TTL_MS,Zl as API_TOKEN_MAX_TTL_MS,os as API_VERSION,Ie as AUTHORIZATION_CAPABILITIES,Kl as AUTH_ACTION_TOKEN_TTL_MS,Wl as AUTH_MFA_CHALLENGE_TTL_MS,Jl as AUTH_OIDC_TRANSACTION_TTL_MS,it as AUTH_SESSION_ABSOLUTE_TTL_MS,zl as AUTH_SESSION_IDLE_TTL_MS,ly as AWSAPIError,n as AWSClient,h as AWSCloudFormationClient,S as AWSCloudFrontClient,ml as AWSConfigManager,$I as AWS_PSEUDO_PARAMETERS,_e as AWS_REGIONS,jg as AcmeClient,en as AlertEvaluator,_i as AlertStore,Co as AnomalyConfigStore,nl as ApiGateway,i as ApiServiceError,fc as ApplicationAutoScalingClient,cn as Arn,_ as AssetHasher,Y as Auth,ts as AuthenticationStore,Ui as AutomationApiService,rs as AutomationIdentityStore,Ea as AwsAuroraDataAdapter,Da as AwsAuroraTransport,ja as AwsDatabaseBackupSource,Br as AwsDriver,va as AwsElastiCacheDataAdapter,Pa as AwsElastiCacheTransport,Mf as AwsIamCapabilityScanner,Xa as AwsInfrastructureBackupSource,Ca as AwsRdsDataAdapter,Ra as AwsRdsTransport,Xf as AwsRegionalDriver,Za as AwsSecretsManagerConfigurationBackend,em as AwsSpendTransport,ec as AwsSsmConfigurationBackend,As as BackupCoordinator,gl as BackupManager,Va as BackupStore,pf as BatchProcessingManager,Mn as BedrockClient,$n as BedrockRuntimeClient,au as BitbucketSourceAdapter,Al as BlueGreenManager,rf as BounceComplaintHandler,zm as BuildOptimizationManager,Pu as BunDockerRuntime,sg as BunDockerVolumeRuntime,ig as BunFilesystemArchiveRuntime,Ce as CDN,Qo as CHAIN_HEADER,Gt as CLOUDFLARE_MANAGED_RULE_PREFIX,Yd as CLOUDFRONT_FAILOVER_STATUS_CODES,EC as COMMON_CROSS_ACCOUNT_ROLES,On as CONTENT_HASH_BINDING,Ke as CONTROL_PLANE_SCHEMA_VERSION,_o as Cache,Ki as CanaryManager,Vm as CertificateManager,bA as CloudBlockVolumeDriver,Js as CloudDriverFactory,tt as CloudError,Am as CloudFormationBuilder,h as CloudFormationClient,S as CloudFrontClient,fl as CloudTrailManager,we as CloudWatchLogsClient,td as CloudflarePagesProvider,H as CloudflareProvider,ky as CommandHistory,ee as Communication,Wr as ComposeApplicationService,tr as ComposeApplicationStore,Mt as ComprehendClient,a as Compute,tm as ComputeSpendTransport,Mo as ConfigurationError,rc as ConfigurationService,Ya as ConfigurationStore,_n as ConnectClient,wa as ContainerDataAdapter,El as ContainerRegistryManager,Ja as ControlPlaneBackupSource,Ua as ControlPlaneCleanupDriver,Di as ControlPlaneStore,So as CounterTracker,Pt as CredentialError,Bm as CrossRegionReferenceManager,JA as DASHBOARD_ENTRY,XA as DASHBOARD_PORT_BASE,YA as DASHBOARD_PORT_SPAN,WA as DASHBOARD_STATE_DIR,Jo as DEFAULT_ATTACK_MODE_HOURS,Ts as DEFAULT_COMPATIBILITY_DATE,Qd as DEFAULT_DDOS_THRESHOLDS,sm as DEFAULT_FAILOVER_STATUS_CODES,Cd as DEFAULT_METER_MAPPINGS,Id as DEFAULT_PRICE_BOOK,un as DEFAULT_RECURSION_LIMITS,to as DEFAULT_RPX_CERTS_DIR,te as DEFAULT_SERVICE_LIMITS,qd as DEFAULT_STATE_DIR,yg as DEFAULT_STATIC_ASSET_EXTENSIONS,qA as DEFAULT_STORAGE_FAILOVER_STATUS_CODES,OA as DEFAULT_TELEMETRY_POLICY,Mp as DEFAULT_THRESHOLDS,hA as DEPLOYMENT_QUEUE_KINDS,Uo as DEPTH_HEADER,Yr as DETECTABLE_SIGNALS,vu as DIAGNOSTIC_PRESETS,gf as DLQMonitoringManager,W as DNS,ef as DNSSECManager,ls as DataServiceLifecycle,ba as DataServiceStore,or as Database,Hm as DatabaseUserManager,q as DebugLogger,VA as DependencyGraph,Z as Deployment,dy as DeploymentError,pl as DisasterRecoveryManager,zn as DnsProviderFactory,fr as DockerDataTransport,fa as DockerDiscoveryAdapter,Kr as DockerNamedVolumeDriver,Wa as DockerVolumeBackupSource,c as DurableOperationQueue,go as DurableQueueWorker,Ue as DynamoDBClient,Ur as EC2Client,He as ECRClient,dt as ECSClient,vr as EFSClient,uc as ELBv2Client,EA as ENFORCEMENT_ACTIONS,xi as ENFORCEMENT_DESCRIPTIONS,O as ENFORCEMENT_SEVERITY,gp as ENVIRONMENT_LABEL,Cu as EcsRuntimeAdapter,Wo as EdgeRateLimiter,ut as ElastiCacheClient,m as Email,af as EmailAdvanced,nf as EmailAnalyticsManager,Gn as EmailClient,cf as EmailHandlers,of as EmailTemplateManager,Na as EncryptedDataSecretStore,uy as ErrorCodes,Cr as EventBridgeClient,Kf as EventBridgeJobAdapter,tc as ExternalConfigurationBackend,Oo as FAILOVER_REPLICA_POLICY_SID,uf as FIFOQueueManager,Uh as FLY_MACHINES_API,jp as FOCUS_VERSION,ol as FileCache,Ze as FileSystem,za as FilesystemBackupSource,Ba as FleetService,ka as FleetStore,Ws as FlyApiError,mg as FlyClient,e as Fn,cu as GiteaSourceAdapter,su as GithubSourceAdapter,ou as GitlabSourceAdapter,xm as GlobalResourceManager,Ge as GoDaddyProvider,hl as GuardDutyManager,It as HOST_SITES_DIR,fy as HashCache,Tf as HealthCheckManager,Je as HealthCheckRunner,Lr as HetznerClient,Pe as HetznerDriver,Re as IAMClient,Tc as IPV6_EXCLUDED_HOST_LABELS,jm as ImageScanningManager,Dg as InfrastructureGenerator,dd as InvalidOperationTransitionError,Rt as JobLoader,Wf as JobProviderReconciler,Sa as JobService,Ia as JobStore,br as KendraClient,Ef as LARAVEL_SERVERLESS_BUILD_STEPS,v as LambdaClient,Jm as LambdaConcurrencyManager,Zm as LambdaDLQManager,Xm as LambdaDestinationsManager,Km as LambdaLayersManager,Eu as LambdaRuntimeAdapter,Ym as LambdaVPCManager,Wm as LambdaVersionsManager,Nn as LocalEncryptedConfigurationBackend,Ka as LogicalDatabaseBackupSource,Il as LogsManager,Yy as MANAGED_NODE_VERSIONS,zc as MANAGEMENT_DASHBOARD_SITE,ym as MANAGEMENT_DASHBOARD_SITE_PREFIX,Zi as MAX_CONTROL_HOURS,ld as MAX_CONTROL_PLANE_ERROR_BYTES,xp as MAX_CONTROL_PLANE_JSON_BYTES,ho as METERS,CA as METER_KEYS,vA as MICRO_CENTS,Fp as MIN_PROJECTION_CONFIDENCE,Eg as MTA_STS_PORT,Fa as MaintenanceService,Ma as MaintenanceStore,le as Messaging,Fm as MetricsManager,Um as MigrationManager,Rm as MockCloudFormation,Pm as MockDynamoDB,Dm as MockS3,Lo as Monitoring,Lm as MultiAccountManager,km as MultiRegionManager,Ty as MultiStepProgress,y as Network,wf as NetworkSecurityManager,Li as NotificationRouter,cm as ORIGIN_CONNECTION_ATTEMPTS,dm as ORIGIN_CONNECTION_TIMEOUT,om as ORIGIN_GROUP_ALLOWED_METHODS,OI as ORIGIN_GROUP_ID_SUFFIX,am as ORIGIN_GROUP_SELECTION_CRITERIA,gc as OpenSearchClient,bt as OptimisticConcurrencyError,$m as OrganizationManager,Qg as PAGES_MAX_FILE_BYTES,cS as PHP_DEFAULT_EXCLUDES,Zy as PHP_LAYER_EXTENSIONS,up as PROJECT_LABEL,pt as PROXIABLE_RECORD_TYPES,D as ParameterStore,Qm as PerformanceManager,de as Permissions,pc as PersonalizeClient,et as Phone,df as PhoneAdvanced,fm as PhoneHandlers,Oa as PlacementService,xa as PlacementStore,Un as PollyClient,he as PorkbunProvider,Sn as PreDeployScanner,ll as PreviewEnvironmentManager,zr as PreviewEnvironmentService,We as PreviewEnvironmentStore,ul as PreviewNotificationService,vy as ProgressBar,Sl as ProgressiveDeploymentManager,Xo as ProtectionControlStore,GA as Pseudo,J as Queue,Pi as QueueCancellationError,mf as QueueManagementManager,EI as QueuePresets,uo as QueueTimeoutError,Fn as R2ApiError,Pn as R2NotEnabledError,oi as R2Provider,np as R2_NOT_ENABLED_ERROR_CODE,Fl as RATE_LIMIT_KEY_SEPARATOR,ne as RDSClient,xy as RECOMMENDED_ACCOUNT_STRUCTURES,CC as RECOMMENDED_SCPS,Of as RELEASE_QUEUE_KINDS,Dy as REPL,Ny as REPLCommandBuilder,Py as REPLContext,pp as ROLE_LABEL,hy as RateLimiter,vI as RealtimePresets,zp as RecordingSpendTransport,Ji as RecursionGuard,Dt as Redirects,Om as RegionPairManager,La as RegionService,_a as RegionStore,Ye as Registry,Ft as RekognitionClient,Nt as ReleaseService,oa as ReleaseStore,Jf as RemoteBuildService,bl as ReplicaManager,Rf as ResourceManagementManager,ae as RetryableOperationError,I as Route53Client,lc as Route53DomainsClient,ie as Route53Provider,tf as Route53ResolverManager,Tl as Route53RoutingManager,ve as RuntimeOperationService,Aa as RuntimeStreamRegistry,qa as S3BackupDestinationAdapter,o as S3Client,V as S3Error,uu as SECRET_PATTERNS,Vp as SENSITIVITY_THRESHOLDS,gt as SESClient,X as SMS,lt as SNSClient,Zp as SPEND_CYCLE_SECONDS,_d as SPEND_GATE_SETTING,MA as SPEND_LEASE_SETTING,pe as SQSClient,Ne as SSH_BOOTSTRAP_VERSION,di as SSH_PREFLIGHT_SCRIPT,Be as SSMClient,nm as STATE_DIR_ENV_VAR,so as STATIC_SITE_ZONE_SETTINGS,el as STORAGE_FAILOVER_METADATA_KEY,Te as STSClient,Qn as SchedulerClient,ar as Search,In as SecretFindingScanner,Vi as Secrets,Cl as SecretsManager,re as SecretsManagerClient,Gm as SecretsRotationManager,C as Security,lr as SecurityHubManager,yn as SecurityPostureStore,kt as SecurityScannerRunner,qm as SecurityScanningManager,sf as SenderReputationManager,zf as ServerCronJobAdapter,Ta as ServerDataAdapter,fo as ServerPathVolumeDriver,vl as ServiceMeshManager,rl as Sftp,vo as SignalSource,lf as SmsAdvanced,Qt as SmsClient,hm as SmsHandlers,yc as SmsVoiceClient,aa as SourceConnectionStore,pr as SourceProviderError,Ld as SpendCapError,Zr as SpendGate,Xp as SpendLoopLease,Po as SpendNotificationRouter,Yp as SpendRunner,nr as SpendService,ki as SpendStore,wy as Spinner,Mr as SshDriver,En as SshFleetDriver,_m as StackDependencyManager,LI as StacksIntegration,vf as StaticSiteManager,xe as Storage,Ll as StorageAdvancedManager,Hn as SupportClient,ur as SyntheticsManager,Nu as SystemFleetSshTransport,$r as SystemSshTransport,ha as SystemdDiscoveryAdapter,Ho as TRACE_HEADER,Ry as TaskList,vt as TelemetryStore,Jd as TemplateBuilder,al as TemplateCache,Ut as TextractClient,Ln as TranscribeClient,Ir as TranslateClient,eh as TransportDisasterRecoveryDriver,Zf as TransportPlatformMaintenanceDriver,us as TransportRemoteBuildDriver,pa as TrivyImageScanner,sa as TsCloudApiError,tu as TsCloudClient,$A as URGENT_SPEND_EVENTS,Up as USER_VISIBLE_ACTIONS,$a as UnavailableRegionalDriver,Ae as UnifiedDnsValidator,ao as UnsupportedSchemaVersionError,Cm as ValidationError,Er as VoiceClient,mo as VolumeService,er as VolumeStore,qc as WORKER_MODULE_TYPE,si as WorkersApiError,mc as WorkersPermissionError,hc as WorkersProvider,KA as Workflow,Mm as XRayManager,Hy as abTestManager,ru as activateImmutableRelease,zg as addDns01ChallengeRecord,Tn as addSiteToCloudConfig,xt as ageSeconds,vd as aggregateDeltas,Np as allocateSitePorts,mm as amazonLinuxImageId,zA as amazonLinuxImageParameter,BI as analyzeStackDiff,Oi as anomalyOptionsForSignal,Yo as applyControlsToDdos,Vl as applyControlsToRateLimits,Ls as applyDeclaredZoneSettings,nn as applyMitigationFactor,Xh as applyPlan,Us as applyZoneMigration,wl as artifactKey,Tt as assertOriginGroupMethods,ns as assertReleaseStrategy,xA as assertSpendAllows,rA as attachConflicts,nA as attachIsViable,tA as attachPreconditions,hu as attachProvenanceToRelease,ma as attachSbomToRelease,mu as attachVulnerabilitySummary,Bf as authEncryptionKeyFile,x as authorizeOrganization,qf as authorizeRuntimePath,Yb as autocomplete,Ly as awsConfigManager,rg as backupCredentialStatus,Oy as backupManager,Eb as batch,pE as batchProcessingManager,na as beginOidcAuthorization,Uy as blueGreenManager,aE as bounceComplaintHandler,Ct as budgetWindow,ac as buildAndPushServerlessImage,hE as buildBunRuntimeLayerZip,dA as buildCertificatePackScript,oA as buildCertificateStateScript,lA as buildCertificateUnpackScript,il as buildCloudFormationTemplate,Uc as buildCloudInitFirstBoot,md as buildComposeLogsCommand,bI as buildComposeRuntimeCommand,CI as buildComposeScaleCommand,fd as buildComposeShellCommand,Rp as buildDrainSourceScript,Hh as buildDrainedSiteScanScript,tl as buildFailoverReplicaPolicyStatement,Ar as buildFunctionEnv,wp as buildHealthGateScript,ti as buildHostCleanupDeployScript,zs as buildHostCleanupInstallScript,ei as buildHostCleanupScript,wi as buildHostSitePortsScript,Hi as buildMailEnv,Ys as buildManagementDashboardArtifact,HS as buildMediaCdnPlan,Cg as buildMtaStsPolicy,Eh as buildMtaStsServer,fE as buildNodeRuntimeLayerZip,YC as buildOptimizationManager,Zd as buildOriginGroup,an as buildOriginGroups,bc as buildOriginGuardRule,Sp as buildPauseWorkersScript,IE as buildPhpRuntimeLayerZip,pm as buildReplicationConfiguration,gm as buildReplicationRole,Ep as buildRestoreScript,B as buildRpxConfig,ke as buildRpxFragmentRefreshScript,Zh as buildSetHostnameScript,ni as buildSiteDeployScript,Cp as buildSnapshotScript,Dp as buildSourceStateScript,Xn as buildSshArgs,ai as buildSshBootstrapScript,Ic as buildStaticSiteCacheRules,ii as buildStaticSiteDeployScript,vp as buildTargetStateScript,dp as buildUploadForm,Ip as buildWorkersStateScript,Zc as bundleWorker,yu as bytes,op as cacheRuleParameters,Qy as canaryManager,vn as canonicalJson,Bt as capabilities,hr as capacity,Bb as categorizeChanges,WC as certificateManager,cA as certificatesMatch,pb as checkIAMPermissions,Sf as checkInvocation,fb as checkServiceQuotas,Ay as chunk,sR as cleanupDns01Challenge,fS as clearSigningKeyCache,da as cloneSourceBinding,yy as cloudConfigSchema,Kg as cloudDrivers,$y as cloudTrailManager,ep as collectAssets,jo as collectPhpAppEntries,Sg as collectServerDnsDomains,Op as completeComposeVolumeDeletion,ia as completeOidcAuthorization,tb as composePresets,lo as composeProjectName,Dl as composeServerlessAppTemplate,UA as compositeSpendTransport,$t as compressBackup,CS as config,Sc as configOrigins,Ru as connectionGuidance,Ky as containerRegistryManager,mA as controlPlaneDatabaseFile,ad as controlPlaneMigrations,GI as createApiBackendPreset,ga as createApiV1Handler,kS as createAsgBuildDriver,ng as createBackupQueueHandlers,aS as createCliHandler,F as createCloudDriver,Uu as createCloudFrontPolicy,db as createCredentialProvider,ZI as createDashboardSite,KI as createDataPipelinePreset,Du as createDataServiceQueueHandlers,hd as createDeploymentQueueHandlers,k as createDnsProvider,NS as createEcsBuildDriver,$d as createEnforcementHandlers,Em as createError,sl as createExistingStaticFullStackPreset,ku as createFleetQueueHandlers,HI as createFullStackAppPreset,Gs as createGoDaddyValidator,SE as createHandlers,sS as createHttpHandler,qI as createJamstackPreset,wu as createJobQueueHandlers,XI as createLaravelPreset,WI as createMLApiPreset,Mu as createMaintenanceQueueHandlers,WS as createMediaAccessToken,jI as createMicroservicesPreset,Ub as createMockAWS,FI as createNodeJsServerPreset,UI as createNodeJsServerlessPreset,Ds as createObjectStorageClient,Hs as createPorkbunValidator,rb as createPreset,zo as createPresignedUrl,lS as createPresignedUrlAsync,oS as createQueueHandler,zI as createRealtimeAppPreset,xu as createRegionQueueHandlers,fu as createReleaseProvenance,iu as createReleaseQueueHandlers,DS as createRemoteBuildQueueHandlers,Vs as createRoute53Validator,Vf as createRuntimeAdapters,cy as createS3Client,PS as createServerBuildDriver,YI as createServerlessLaravelPreset,QI as createServerlessNodePreset,Ag as createSmsInfrastructure,ot as createSourceAdapter,MI as createStaticSitePreset,JI as createTraditionalWebAppPreset,Ad as createVolumeQueueHandlers,VI as createWordPressPreset,rt as createZip,oC as crossRegionReferenceManager,kn as dashboardActions,Xs as dashboardCredentialsFile,Cn as dataServiceCapabilities,zC as databaseUserManager,jl as decodeBase32,Fe as decompressBackup,lh as decryptBackup,Zo as defaultConfig,wm as defaultLocalConfig,Ql as defaultRateLimitRules,Rr as delegateZone,Os as delegateZoneFromConfig,Yu as deleteFailoverReplicaBuckets,sc as deleteStaticSite,Wc as deployAllComputeSites,Ha as deployServerlessApp,Zu as deploySite,Zs as deploySiteRelease,bs as deployStaticSite,oc as deployStaticSiteFull,Bn as deployStaticSiteWithExternalDns,xn as deployStaticSiteWithExternalDnsFull,IS as deployToFly,Wd as deploymentCoexistenceError,ZA as deriveManagementDashboardPort,_s as describeDelegation,Gl as describePosture,$s as describeZoneSettings,jf as desiredJobProviderState,Gp as detectAnomalies,im as detectDeploymentTargets,Cc as detectDnsProvider,Bd as detectLatestAnomaly,ub as detectMisconfigurations,$l as detectServiceRegion,gd as diffCompose,Pb as diffTemplates,ca as discoverGitRefs,ra as discoverOidcProvider,Su as discoverRuntimeInventory,gE as dlqMonitoringManager,Ec as dnsProviders,sE as dnssecManager,Qf as dockerWorkloads,gs as documentDigest,Hc as domainStatus,_y as drManager,qe as driverStatePath,Iu as ecsWorkloads,Zt as effectiveCapabilities,cE as emailAnalyticsManager,lE as emailTemplateManager,es as encodeBase32,dh as encryptBackup,Au as ensureDefaultSecurityPolicies,Wu as ensureFailoverReplicaBuckets,hi as ensureFirewall,Si as ensureManagementDashboard,Ai as ensureServer,fi as ensureSshKey,oe as escapeSecLang,wd as evaluateBudget,ui as evaluatePreflight,Do as evaluateTelemetryAlertRules,Tu as eventBridgeScheduleInput,iS as eventToRequest,NA as ewma,ud as exportCompose,Ms as exportRoute53Zone,Im as extendPreset,uE as fifoQueueManager,Cb as findChangedFiles,Lp as findMapping,_p as findPriceEntry,$S as flyDeployOptions,Qc as flyIpType,fg as flyMachineConfig,RC as formatAccountStructure,iA as formatAttachPlan,Vb as formatBytes,tn as formatCents,xI as formatDiff,Vh as formatDrainedSiteRefusal,qb as formatDuration,eC as formatFlagSuggestions,nC as formatHistory,iC as formatHistoryStats,Kh as formatInventory,zb as formatKeyValue,jb as formatList,Jh as formatPlan,pi as formatPreflightFindings,Gb as formatProgressBar,By as formatRegion,yC as formatRegionList,$f as formatScanResults,Kb as formatSuggestion,Qb as formatTable,Xr as formatTimeToExhaustion,Hb as formatTree,iy as fromEC2Metadata,sy as fromECSMetadata,ry as fromEnvironment,ny as fromSharedCredentials,oy as fromWebIdentity,kl as functionFingerprint,io as gatewayHostnames,Nl as generateAppImageDockerfile,QC as generateApprovalConfig,ff as generateBootstrap,by as generateCleanupWorkflow,Cy as generateCostReportWorkflow,TC as generateCrossAccountRoleCF,gu as generateCycloneDxSbom,MC as generateDeploymentConfig,xC as generateDeploymentPipeline,DC as generateDeploymentWorkflow,ic as generateExternalDnsStaticSiteTemplate,iR as generateHttpsServerCode,pu as generateImageSbom,nR as generateLetsEncryptUserData,t as generateLogicalId,$C as generateManualPipeline,BC as generateMatrixWorkflow,FC as generateMultiEnvConfig,OC as generateMultiEnvPipeline,PC as generateMultiEnvWorkflow,NC as generatePRPreviewWorkflow,HC as generateParallelConfig,Cf as generatePhpFpmConfig,hf as generatePhpLayerDockerfile,_C as generatePreviewPipeline,Iy as generatePreviewWorkflow,r as generateResourceName,UC as generateScheduledConfig,LC as generateScheduledPipeline,kC as generateScheduledWorkflow,Is as generateStaticSiteTemplate,M as generateUbuntuAppCloudInit,bm as getAccountId,lC as getAllRegions,fC as getClosestRegion,tC as getCommandUsage,fA as getComposeTemplate,Pf as getConfig,Jb as getContextualHelp,ji as getCredentials,xb as getDeploymentStrategy,Ob as getDiffStats,Nb as getDiffSummary,gy as getErrorDetails,dl as getLocalConfig,Mb as getLocalCredentials,$b as getLocalEndpoint,Fb as getLocalEnvVars,hb as getQuotaUsageSummary,vC as getRecommendedStructure,zi as getRegion,SC as getRegionStats,gC as getRegionsByCompliance,uC as getRegionsByLocation,pC as getRegionsByPricingTier,py as getRequiredPermissions,hS as getSigningKeyCacheSize,hg as getSmsInfrastructureStatus,TI as getTimestamp,Ko as globMatches,eo as globToRegex,aC as globalResourceManager,Bi as governingLimitCents,Ju as grantFailoverReplicaAccess,My as guardDutyManager,No as handleSpendRequest,no as hasAutoWwwVariant,cr as hasManagementDashboardSite,od as hasProxyUpstream,yb as hashBuffer,Sb as hashDirectory,vm as hashFile,Ib as hashManifest,Tm as hashString,CE as healthCheckManager,Kn as hostAcceptsIpv6,Ht as hostCondition,ea as hotp,Jr as hourBucket,PA as hourBucketsBetween,XC as imageScanningManager,fs as infraEnvFromOutputs,xl as inspectInvocation,rS as installRecursionFetch,Es as invalidateCache,yf as invocationContext,jA as isArmInstanceType,Wb as isLikelyTypo,Jn as isLocalDatabase,Lb as isLocalDevelopment,dr as isManagementDashboardSiteName,Tr as isNameserverRegistrar,AS as isNodeCryptoAvailable,kd as isOperationAllowed,Ro as isQuietHours,xo as isS3RestEndpoint,bi as isSafePattern,zd as isStateDirConfigured,Kd as isStatePath,rn as isValidCidr,mC as isValidRegion,Ni as isValidTimeZone,yS as isWebCryptoAvailable,wr as isZoneHost,bn as jobProviderCapability,Rs as keyMatchesFilters,tE as lambdaConcurrencyManager,iE as lambdaDLQManager,rE as lambdaDestinationsManager,ZC as lambdaLayersManager,nE as lambdaVPCManager,eE as lambdaVersionsManager,bu as lambdaWorkloads,Ol as laravelServerlessEnvDefaults,jr as listComposeTemplates,ss as listSourceReferences,ql as loadCloudConfig,ir as loadTelemetryPolicy,Vy as logsManager,xd as lookbackHoursForSignal,HA as mailEnabled,Xe as mailFirewallPorts,on as mailWebmailSites,Yf as maintenanceWindowOpen,Df as makeAWSRequest,gS as makeAWSRequestAsync,uS as makeAWSRequestOnce,ap as managedRuleInSync,Sm as managementDashboardSiteName,Ou as manifestDigest,mn as matchTotpCounter,zS as mediaObjectHeaders,bo as median,Qp as medianAbsoluteDeviation,Rd as mergeDecisions,dn as mergeInfrastructure,RA as mergePriceBooks,Ed as meterTelemetry,VC as metricsManager,ug as migrateObjectStorage,qC as migrationManager,IC as multiAccountManager,sC as multiRegionManager,aR as needsRenewal,EE as networkSecurityManager,Ot as nextScheduleRuns,De as normalizePublicIpv6,Le as normalizeRuntimeStatus,at as normalizeScheduleExpression,_f as normalizeSourceEvent,Ve as normalizeSshPublicKey,Kp as normalizeTelemetryPolicy,Ti as occupiedHostPorts,ua as openApiDocument,To as optionsForSignal,bC as organizationManager,_l as packagePhpApp,ln as packageServerlessApp,rd as pagesAssetHash,rh as pagesDnsRecord,cl as parallel,vb as parallelMap,Tb as parallelWithRetry,aA as parseCertificateState,Bl as parseChain,qr as parseCompose,SI as parseComposeCatalog,Uf as parseDockerInspect,og as parseDotenv,Gh as parseDrainedSites,Ri as parseHostSiteFragments,mS as parseJSONResponse,li as parsePreflightFacts,Pp as parseSourceDrained,Hf as parseSystemdRecords,Tp as parseTargetReady,sd as parseUpstreamPort,bp as parseWorkersPaused,pS as parseXMLResponse,Mi as pathTemplate,nd as pendingSteps,Io as percentOfLimit,jC as performanceManager,Pl as phpLayerBuildStage,eS as phpLayerPackages,gn as phpRuntimeLayerAssets,II as planComposeTemplateUpgrade,Dd as planEnforcement,Ap as planIsDestructive,rm as planMitigation,Yh as planServerRename,uA as planSiteMove,Fs as planZoneMigration,qt as policyTag,gi as preflightFailed,Sy as previewManager,Ey as previewNotifications,_t as previewSchedule,DA as previousBudgetWindow,Ao as priceUsage,TA as priceUsageLines,jh as probeHostRoutes,Bc as probeOriginTls,Db as processInChunks,du as processSourceWebhook,cs as productionChangeReview,Gy as progressiveDeploymentManager,Td as projectSpend,Go as propagationHeaders,cc as providerEndpoint,_u as publicKeyFingerprint,qn as qualifyName,mE as queueManagementManager,bb as quickHash,ip as r2Endpoint,ah as r2S3Credentials,Ul as rateLimitHeaders,Yi as rateLimitKey,je as readDriverState,zh as reconcile,bg as reconcileAddressRecords,Jg as reconcileCloudflareCdn,vh as reconcileCloudflareWorkers,xs as reconcileDeclaredRecords,RS as reconcileJobObservation,mh as reconcileR2Buckets,An as reconcileSourceWebhook,as as recordDashboardHostPosture,vS as recordPreDeploySecretScan,TS as recordSkippedSecretScan,Vo as recursionBlockedResponse,$e as redactRuntimeConfig,Ud as redactTelemetryText,$i as redactTelemetryValue,Rn as redeployServerlessApp,cC as regionPairManager,hn as releaseStrategyCapabilities,xf as releaseTrafficPlan,Ii as reloadRpxGateway,ws as remapKey,Ig as removeAddressRecords,Hg as removeDns01ChallengeRecord,wn as removeSiteFromCloudConfig,lu as removeSourceWebhook,vc as removeStaleServerAddressRecords,pd as renderComposeTemplate,Qi as renderDdosInstallScript,Vd as renderNftablesRuleset,ds as renderServerCron,Gd as renderSysctlFile,Xc as renderWafConfig,Ci as renderWafInstallScript,Jc as renewRpxCertificates,jy as replicaManager,QA as requestHash,kb as requiresReplacement,AE as resetRecursionRuntime,yE as resolveApp,g as resolveAppDatabase,eA as resolveAttachTarget,st as resolveAuthEncryptionKey,be as resolveCloudProvider,Xg as resolveCloudflareCdnPlan,$o as resolveCredentials,Ss as resolveDashboardAction,Kc as resolveDashboardAuth,ey as resolveDashboardDomain,ty as resolveDashboardDomains,Bs as resolveDeclaredRecords,kI as resolveDeployBucketName,K as resolveDeploymentMode,ri as resolveExecStart,Bo as resolveFailoverStatusCodes,xc as resolveHetznerApiToken,_r as resolveHostCleanupConfig,w as resolveMailProxy,b as resolveMailService,eb as resolveManagementDashboardSite,qi as resolveManagementDashboardSites,dc as resolveObjectStorage,ce as resolveOriginConnection,Wh as resolvePlan,p as resolveProjectStackName,Vr as resolveProxyUpstreams,Rl as resolveQueueNames,AA as resolveQueuedDeploymentCommand,gr as resolveQueues,tS as resolveRecursionConfig,ay as resolveRegion,ge as resolveRuntimeInventory,sr as resolveServerlessAppStackName,Xd as resolveServerlessArtifactBucketName,Gi as resolveServerlessAssetBucketName,Wi as resolveServerlessRuntime,PI as resolveSiteBucketName,oo as resolveSiteDeployTarget,d as resolveSiteKind,DI as resolveSiteResourceName,RI as resolveSiteStackName,ci as resolveSshSettings,l as resolveStatePath,NI as resolveStorageBucketName,lm as resolveStorageFailover,Jt as resolveUiSource,ed as resolveZoneApex,vE as resourceManagementManager,bf as responseToResult,Hp as robustZScore,Yt as roleCapabilities,nu as rollbackImmutableRelease,Dn as rollbackServerlessApp,wA as roundCents,oE as route53ResolverManager,Jy as route53RoutingManager,qp as routeMatches,mp as routesFromFragments,Xi as ruleMatches,Xy as runBuildHooks,Pd as runEnforcement,qo as runPhpBuildHooks,ct as runRemoteCommand,Ee as runtimeId,Qe as s3OriginBucket,um as s3RegionalDomain,qs as sameCorsRules,Ga as sameLifecycleRules,jn as sameNameservers,ys as sanitizeCloudConfig,s as sanitizeControlPlaneValue,wI as sanitizeName,Xl as sanitizeOidcReturnPath,Md as saveTelemetryPolicy,Lf as scanForSecrets,cd as scopeContains,Et as scopeKey,Rc as scpUpload,Xb as searchCommands,co as searchControlPlane,zy as secretsManager,KC as secretsRotationManager,wS as secureContainerRelease,Fy as securityHubManager,JC as securityScanningManager,ue as securityScope,Xu as seedFailoverReplicas,fn as sendAuthenticationEmail,dE as senderReputationManager,wb as sequence,ag as serializeDotenv,yi as serverPublicIpv4,Wy as serviceMeshManager,qu as setAttachToInCloudConfig,yr as setMaintenance,ps as setSitePropertyInCloudConfig,jd as setStateDir,oR as setupDns01Challenge,Ac as setupSmsInfrastructure,Fo as sha256,nS as sharedRecursionGuard,Af as sharedRuntimeLoop,Bp as shipsARelease,BS as signCloudFrontCookies,MS as signCloudFrontUrl,N as signRequest,Ml as signRequestAsync,Eo as signalDefinition,U as siteInstallBase,vi as siteMoveArchivePath,sA as siteMoveCertArchivePath,id as siteUnitGlob,Jp as spendNotificationText,ko as spendOpenApiPaths,xr as sshExec,Se as sshExecOrThrow,dC as stackDependencyManager,nc as startLocalDashboardServer,FA as startSpendLoop,sn as stateDir,Q as statePath,bE as staticSiteManager,dS as storageAdvancedManager,_I as storageFailoverReplicasFromTemplate,kA as streamFocusJsonl,Nd as strongestActiveAction,Nm as suggestCommand,Zb as suggestFlags,mb as suggestIAMPolicy,Ab as suggestQuotaIncrease,AC as suggestRegionPairs,hC as suggestRegions,is as syncSourceRepositories,yd as synchronizeComposeVolumes,cg as synchronizeConfiguredConfiguration,ya as synchronizeConfiguredJobs,qy as syntheticsManager,Hd as sysctlHardening,Gf as systemdWorkloads,LA as telemetryBucketLabel,Fi as telemetryCursor,Fd as telemetryEstimatedMonthlyCost,_A as telemetryPercentile,Wp as telemetryPolicyKey,my as templateCache,fp as tenantsOf,la as testSourceConnection,Sd as tieredMicroCents,cp as toApiLifecycleRule,Mc as toCloudflareZoneSettings,wo as toFocusJsonl,Od as toFocusRecords,qh as toInventoryServer,Nf as totp,ta as totpUri,hp as unaccountedSites,Ff as unsupportedCapabilities,yA as unsupportedVolumeCapabilities,$u as updateCompatibility,Fu as updateSiteInCloudConfig,Cs as uploadStaticFiles,$p as usageDeltaKey,rr as utcInstantOfLocal,wC as validateAccountStructure,_b as validateAgainstSchema,IA as validateAttachment,ch as validateBackupDestination,rC as validateCommand,lb as validateConfiguration,gb as validateCredentials,kp as validateDeploymentConfig,SA as validateMountPath,wt as validateOriginGroups,Fg as validateResourceLimits,yp as validateServerName,kg as validateTemplate,Lg as validateTemplateSize,wc as verifyAddressRecord,ES as verifyArtifactSignature,VS as verifyMediaAccessToken,kf as verifyTotp,Lu as verifyUpdateSignature,Qs as verifyZoneParity,po as volumeCapabilities,sp as wafEventTelemetry,Dc as waitForCloudInit,Yn as waitForSsh,mr as webhookEndpoint,ab as withCDN,ob as withCache,eg as withContentHash,sb as withDatabase,If as withInvocation,nb as withMonitoring,cb as withQueue,ib as withSecurity,Rb as withTimeout,tg as workerBindings,Ps as workerContentHash,Pc as workerInSync,se as wrapCloudInitUserData,ft as writeDriverState,GC as xrayManager,Bu as zeroCapacity,BA as zeroFill,bd as zoneOffsetMs,yo as zonedParts};
|