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