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